PackageManagerService.java revision c6ca265902d41a0553d15f660647410db6a3e889
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 68import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 69import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 70import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 71import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 72import static android.content.pm.PackageManager.PERMISSION_DENIED; 73import static android.content.pm.PackageManager.PERMISSION_GRANTED; 74import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 75import static android.content.pm.PackageParser.isApkFile; 76import static android.os.Process.PACKAGE_INFO_GID; 77import static android.os.Process.SYSTEM_UID; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 96 97import android.Manifest; 98import android.annotation.NonNull; 99import android.annotation.Nullable; 100import android.app.ActivityManager; 101import android.app.ActivityManagerNative; 102import android.app.IActivityManager; 103import android.app.admin.IDevicePolicyManager; 104import android.app.backup.IBackupManager; 105import android.content.BroadcastReceiver; 106import android.content.ComponentName; 107import android.content.Context; 108import android.content.IIntentReceiver; 109import android.content.Intent; 110import android.content.IntentFilter; 111import android.content.IntentSender; 112import android.content.IntentSender.SendIntentException; 113import android.content.ServiceConnection; 114import android.content.pm.ActivityInfo; 115import android.content.pm.ApplicationInfo; 116import android.content.pm.AppsQueryHelper; 117import android.content.pm.ComponentInfo; 118import android.content.pm.EphemeralApplicationInfo; 119import android.content.pm.EphemeralResolveInfo; 120import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 121import android.content.pm.FeatureInfo; 122import android.content.pm.IOnPermissionsChangeListener; 123import android.content.pm.IPackageDataObserver; 124import android.content.pm.IPackageDeleteObserver; 125import android.content.pm.IPackageDeleteObserver2; 126import android.content.pm.IPackageInstallObserver2; 127import android.content.pm.IPackageInstaller; 128import android.content.pm.IPackageManager; 129import android.content.pm.IPackageMoveObserver; 130import android.content.pm.IPackageStatsObserver; 131import android.content.pm.InstrumentationInfo; 132import android.content.pm.IntentFilterVerificationInfo; 133import android.content.pm.KeySet; 134import android.content.pm.PackageCleanItem; 135import android.content.pm.PackageInfo; 136import android.content.pm.PackageInfoLite; 137import android.content.pm.PackageInstaller; 138import android.content.pm.PackageManager; 139import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 140import android.content.pm.PackageManagerInternal; 141import android.content.pm.PackageParser; 142import android.content.pm.PackageParser.ActivityIntentInfo; 143import android.content.pm.PackageParser.PackageLite; 144import android.content.pm.PackageParser.PackageParserException; 145import android.content.pm.PackageStats; 146import android.content.pm.PackageUserState; 147import android.content.pm.ParceledListSlice; 148import android.content.pm.PermissionGroupInfo; 149import android.content.pm.PermissionInfo; 150import android.content.pm.ProviderInfo; 151import android.content.pm.ResolveInfo; 152import android.content.pm.ServiceInfo; 153import android.content.pm.Signature; 154import android.content.pm.UserInfo; 155import android.content.pm.VerificationParams; 156import android.content.pm.VerifierDeviceIdentity; 157import android.content.pm.VerifierInfo; 158import android.content.res.Resources; 159import android.graphics.Bitmap; 160import android.hardware.display.DisplayManager; 161import android.net.Uri; 162import android.os.Binder; 163import android.os.Build; 164import android.os.Bundle; 165import android.os.Debug; 166import android.os.Environment; 167import android.os.Environment.UserEnvironment; 168import android.os.FileUtils; 169import android.os.Handler; 170import android.os.IBinder; 171import android.os.Looper; 172import android.os.Message; 173import android.os.Parcel; 174import android.os.ParcelFileDescriptor; 175import android.os.Process; 176import android.os.RemoteCallbackList; 177import android.os.RemoteException; 178import android.os.ResultReceiver; 179import android.os.SELinux; 180import android.os.ServiceManager; 181import android.os.SystemClock; 182import android.os.SystemProperties; 183import android.os.Trace; 184import android.os.UserHandle; 185import android.os.UserManager; 186import android.os.storage.IMountService; 187import android.os.storage.MountServiceInternal; 188import android.os.storage.StorageEventListener; 189import android.os.storage.StorageManager; 190import android.os.storage.VolumeInfo; 191import android.os.storage.VolumeRecord; 192import android.security.KeyStore; 193import android.security.SystemKeyStore; 194import android.system.ErrnoException; 195import android.system.Os; 196import android.text.TextUtils; 197import android.text.format.DateUtils; 198import android.util.ArrayMap; 199import android.util.ArraySet; 200import android.util.AtomicFile; 201import android.util.DisplayMetrics; 202import android.util.EventLog; 203import android.util.ExceptionUtils; 204import android.util.Log; 205import android.util.LogPrinter; 206import android.util.MathUtils; 207import android.util.PrintStreamPrinter; 208import android.util.Slog; 209import android.util.SparseArray; 210import android.util.SparseBooleanArray; 211import android.util.SparseIntArray; 212import android.util.Xml; 213import android.view.Display; 214 215import com.android.internal.R; 216import com.android.internal.annotations.GuardedBy; 217import com.android.internal.app.IMediaContainerService; 218import com.android.internal.app.ResolverActivity; 219import com.android.internal.content.NativeLibraryHelper; 220import com.android.internal.content.PackageHelper; 221import com.android.internal.os.IParcelFileDescriptorFactory; 222import com.android.internal.os.InstallerConnection.InstallerException; 223import com.android.internal.os.SomeArgs; 224import com.android.internal.os.Zygote; 225import com.android.internal.util.ArrayUtils; 226import com.android.internal.util.FastPrintWriter; 227import com.android.internal.util.FastXmlSerializer; 228import com.android.internal.util.IndentingPrintWriter; 229import com.android.internal.util.Preconditions; 230import com.android.internal.util.XmlUtils; 231import com.android.server.EventLogTags; 232import com.android.server.FgThread; 233import com.android.server.IntentResolver; 234import com.android.server.LocalServices; 235import com.android.server.ServiceThread; 236import com.android.server.SystemConfig; 237import com.android.server.Watchdog; 238import com.android.server.pm.PermissionsState.PermissionState; 239import com.android.server.pm.Settings.DatabaseVersion; 240import com.android.server.pm.Settings.VersionInfo; 241import com.android.server.storage.DeviceStorageMonitorInternal; 242 243import dalvik.system.DexFile; 244import dalvik.system.VMRuntime; 245 246import libcore.io.IoUtils; 247import libcore.util.EmptyArray; 248 249import org.xmlpull.v1.XmlPullParser; 250import org.xmlpull.v1.XmlPullParserException; 251import org.xmlpull.v1.XmlSerializer; 252 253import java.io.BufferedInputStream; 254import java.io.BufferedOutputStream; 255import java.io.BufferedReader; 256import java.io.ByteArrayInputStream; 257import java.io.ByteArrayOutputStream; 258import java.io.File; 259import java.io.FileDescriptor; 260import java.io.FileNotFoundException; 261import java.io.FileOutputStream; 262import java.io.FileReader; 263import java.io.FilenameFilter; 264import java.io.IOException; 265import java.io.InputStream; 266import java.io.PrintWriter; 267import java.nio.charset.StandardCharsets; 268import java.security.MessageDigest; 269import java.security.NoSuchAlgorithmException; 270import java.security.PublicKey; 271import java.security.cert.CertificateEncodingException; 272import java.security.cert.CertificateException; 273import java.text.SimpleDateFormat; 274import java.util.ArrayList; 275import java.util.Arrays; 276import java.util.Collection; 277import java.util.Collections; 278import java.util.Comparator; 279import java.util.Date; 280import java.util.HashSet; 281import java.util.Iterator; 282import java.util.List; 283import java.util.Map; 284import java.util.Objects; 285import java.util.Set; 286import java.util.concurrent.CountDownLatch; 287import java.util.concurrent.TimeUnit; 288import java.util.concurrent.atomic.AtomicBoolean; 289import java.util.concurrent.atomic.AtomicInteger; 290import java.util.concurrent.atomic.AtomicLong; 291 292/** 293 * Keep track of all those .apks everywhere. 294 * 295 * This is very central to the platform's security; please run the unit 296 * tests whenever making modifications here: 297 * 298runtest -c android.content.pm.PackageManagerTests frameworks-core 299 * 300 * {@hide} 301 */ 302public class PackageManagerService extends IPackageManager.Stub { 303 static final String TAG = "PackageManager"; 304 static final boolean DEBUG_SETTINGS = false; 305 static final boolean DEBUG_PREFERRED = false; 306 static final boolean DEBUG_UPGRADE = false; 307 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 308 private static final boolean DEBUG_BACKUP = false; 309 private static final boolean DEBUG_INSTALL = false; 310 private static final boolean DEBUG_REMOVE = false; 311 private static final boolean DEBUG_BROADCASTS = false; 312 private static final boolean DEBUG_SHOW_INFO = false; 313 private static final boolean DEBUG_PACKAGE_INFO = false; 314 private static final boolean DEBUG_INTENT_MATCHING = false; 315 private static final boolean DEBUG_PACKAGE_SCANNING = false; 316 private static final boolean DEBUG_VERIFY = false; 317 318 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 319 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 320 // user, but by default initialize to this. 321 static final boolean DEBUG_DEXOPT = false; 322 323 private static final boolean DEBUG_ABI_SELECTION = false; 324 private static final boolean DEBUG_EPHEMERAL = false; 325 private static final boolean DEBUG_TRIAGED_MISSING = false; 326 private static final boolean DEBUG_APP_DATA = false; 327 328 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 329 330 private static final boolean DISABLE_EPHEMERAL_APPS = true; 331 332 private static final int RADIO_UID = Process.PHONE_UID; 333 private static final int LOG_UID = Process.LOG_UID; 334 private static final int NFC_UID = Process.NFC_UID; 335 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 336 private static final int SHELL_UID = Process.SHELL_UID; 337 338 // Cap the size of permission trees that 3rd party apps can define 339 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 340 341 // Suffix used during package installation when copying/moving 342 // package apks to install directory. 343 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 344 345 static final int SCAN_NO_DEX = 1<<1; 346 static final int SCAN_FORCE_DEX = 1<<2; 347 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 348 static final int SCAN_NEW_INSTALL = 1<<4; 349 static final int SCAN_NO_PATHS = 1<<5; 350 static final int SCAN_UPDATE_TIME = 1<<6; 351 static final int SCAN_DEFER_DEX = 1<<7; 352 static final int SCAN_BOOTING = 1<<8; 353 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 354 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 355 static final int SCAN_REPLACING = 1<<11; 356 static final int SCAN_REQUIRE_KNOWN = 1<<12; 357 static final int SCAN_MOVE = 1<<13; 358 static final int SCAN_INITIAL = 1<<14; 359 static final int SCAN_CHECK_ONLY = 1<<15; 360 361 static final int REMOVE_CHATTY = 1<<16; 362 363 private static final int[] EMPTY_INT_ARRAY = new int[0]; 364 365 /** 366 * Timeout (in milliseconds) after which the watchdog should declare that 367 * our handler thread is wedged. The usual default for such things is one 368 * minute but we sometimes do very lengthy I/O operations on this thread, 369 * such as installing multi-gigabyte applications, so ours needs to be longer. 370 */ 371 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 372 373 /** 374 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 375 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 376 * settings entry if available, otherwise we use the hardcoded default. If it's been 377 * more than this long since the last fstrim, we force one during the boot sequence. 378 * 379 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 380 * one gets run at the next available charging+idle time. This final mandatory 381 * no-fstrim check kicks in only of the other scheduling criteria is never met. 382 */ 383 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 384 385 /** 386 * Whether verification is enabled by default. 387 */ 388 private static final boolean DEFAULT_VERIFY_ENABLE = true; 389 390 /** 391 * The default maximum time to wait for the verification agent to return in 392 * milliseconds. 393 */ 394 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 395 396 /** 397 * The default response for package verification timeout. 398 * 399 * This can be either PackageManager.VERIFICATION_ALLOW or 400 * PackageManager.VERIFICATION_REJECT. 401 */ 402 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 403 404 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 405 406 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 407 DEFAULT_CONTAINER_PACKAGE, 408 "com.android.defcontainer.DefaultContainerService"); 409 410 private static final String KILL_APP_REASON_GIDS_CHANGED = 411 "permission grant or revoke changed gids"; 412 413 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 414 "permissions revoked"; 415 416 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 417 418 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 419 420 /** Permission grant: not grant the permission. */ 421 private static final int GRANT_DENIED = 1; 422 423 /** Permission grant: grant the permission as an install permission. */ 424 private static final int GRANT_INSTALL = 2; 425 426 /** Permission grant: grant the permission as a runtime one. */ 427 private static final int GRANT_RUNTIME = 3; 428 429 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 430 private static final int GRANT_UPGRADE = 4; 431 432 /** Canonical intent used to identify what counts as a "web browser" app */ 433 private static final Intent sBrowserIntent; 434 static { 435 sBrowserIntent = new Intent(); 436 sBrowserIntent.setAction(Intent.ACTION_VIEW); 437 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 438 sBrowserIntent.setData(Uri.parse("http:")); 439 } 440 441 final ServiceThread mHandlerThread; 442 443 final PackageHandler mHandler; 444 445 /** 446 * Messages for {@link #mHandler} that need to wait for system ready before 447 * being dispatched. 448 */ 449 private ArrayList<Message> mPostSystemReadyMessages; 450 451 final int mSdkVersion = Build.VERSION.SDK_INT; 452 453 final Context mContext; 454 final boolean mFactoryTest; 455 final boolean mOnlyCore; 456 final DisplayMetrics mMetrics; 457 final int mDefParseFlags; 458 final String[] mSeparateProcesses; 459 final boolean mIsUpgrade; 460 461 /** The location for ASEC container files on internal storage. */ 462 final String mAsecInternalPath; 463 464 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 465 // LOCK HELD. Can be called with mInstallLock held. 466 @GuardedBy("mInstallLock") 467 final Installer mInstaller; 468 469 /** Directory where installed third-party apps stored */ 470 final File mAppInstallDir; 471 final File mEphemeralInstallDir; 472 473 /** 474 * Directory to which applications installed internally have their 475 * 32 bit native libraries copied. 476 */ 477 private File mAppLib32InstallDir; 478 479 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 480 // apps. 481 final File mDrmAppPrivateInstallDir; 482 483 // ---------------------------------------------------------------- 484 485 // Lock for state used when installing and doing other long running 486 // operations. Methods that must be called with this lock held have 487 // the suffix "LI". 488 final Object mInstallLock = new Object(); 489 490 // ---------------------------------------------------------------- 491 492 // Keys are String (package name), values are Package. This also serves 493 // as the lock for the global state. Methods that must be called with 494 // this lock held have the prefix "LP". 495 @GuardedBy("mPackages") 496 final ArrayMap<String, PackageParser.Package> mPackages = 497 new ArrayMap<String, PackageParser.Package>(); 498 499 // Tracks available target package names -> overlay package paths. 500 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 501 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 502 503 /** 504 * Tracks new system packages [received in an OTA] that we expect to 505 * find updated user-installed versions. Keys are package name, values 506 * are package location. 507 */ 508 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 509 510 /** 511 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 512 */ 513 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 514 /** 515 * Whether or not system app permissions should be promoted from install to runtime. 516 */ 517 boolean mPromoteSystemApps; 518 519 final Settings mSettings; 520 boolean mRestoredSettings; 521 522 // System configuration read by SystemConfig. 523 final int[] mGlobalGids; 524 final SparseArray<ArraySet<String>> mSystemPermissions; 525 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 526 527 // If mac_permissions.xml was found for seinfo labeling. 528 boolean mFoundPolicyFile; 529 530 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 531 532 public static final class SharedLibraryEntry { 533 public final String path; 534 public final String apk; 535 536 SharedLibraryEntry(String _path, String _apk) { 537 path = _path; 538 apk = _apk; 539 } 540 } 541 542 // Currently known shared libraries. 543 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 544 new ArrayMap<String, SharedLibraryEntry>(); 545 546 // All available activities, for your resolving pleasure. 547 final ActivityIntentResolver mActivities = 548 new ActivityIntentResolver(); 549 550 // All available receivers, for your resolving pleasure. 551 final ActivityIntentResolver mReceivers = 552 new ActivityIntentResolver(); 553 554 // All available services, for your resolving pleasure. 555 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 556 557 // All available providers, for your resolving pleasure. 558 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 559 560 // Mapping from provider base names (first directory in content URI codePath) 561 // to the provider information. 562 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 563 new ArrayMap<String, PackageParser.Provider>(); 564 565 // Mapping from instrumentation class names to info about them. 566 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 567 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 568 569 // Mapping from permission names to info about them. 570 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 571 new ArrayMap<String, PackageParser.PermissionGroup>(); 572 573 // Packages whose data we have transfered into another package, thus 574 // should no longer exist. 575 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 576 577 // Broadcast actions that are only available to the system. 578 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 579 580 /** List of packages waiting for verification. */ 581 final SparseArray<PackageVerificationState> mPendingVerification 582 = new SparseArray<PackageVerificationState>(); 583 584 /** Set of packages associated with each app op permission. */ 585 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 586 587 final PackageInstallerService mInstallerService; 588 589 private final PackageDexOptimizer mPackageDexOptimizer; 590 591 private AtomicInteger mNextMoveId = new AtomicInteger(); 592 private final MoveCallbacks mMoveCallbacks; 593 594 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 595 596 // Cache of users who need badging. 597 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 598 599 /** Token for keys in mPendingVerification. */ 600 private int mPendingVerificationToken = 0; 601 602 volatile boolean mSystemReady; 603 volatile boolean mSafeMode; 604 volatile boolean mHasSystemUidErrors; 605 606 ApplicationInfo mAndroidApplication; 607 final ActivityInfo mResolveActivity = new ActivityInfo(); 608 final ResolveInfo mResolveInfo = new ResolveInfo(); 609 ComponentName mResolveComponentName; 610 PackageParser.Package mPlatformPackage; 611 ComponentName mCustomResolverComponentName; 612 613 boolean mResolverReplaced = false; 614 615 private final @Nullable ComponentName mIntentFilterVerifierComponent; 616 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 617 618 private int mIntentFilterVerificationToken = 0; 619 620 /** Component that knows whether or not an ephemeral application exists */ 621 final ComponentName mEphemeralResolverComponent; 622 /** The service connection to the ephemeral resolver */ 623 final EphemeralResolverConnection mEphemeralResolverConnection; 624 625 /** Component used to install ephemeral applications */ 626 final ComponentName mEphemeralInstallerComponent; 627 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 628 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 629 630 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 631 = new SparseArray<IntentFilterVerificationState>(); 632 633 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 634 new DefaultPermissionGrantPolicy(this); 635 636 // List of packages names to keep cached, even if they are uninstalled for all users 637 private List<String> mKeepUninstalledPackages; 638 639 private boolean mUseJitProfiles = 640 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 641 642 private static class IFVerificationParams { 643 PackageParser.Package pkg; 644 boolean replacing; 645 int userId; 646 int verifierUid; 647 648 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 649 int _userId, int _verifierUid) { 650 pkg = _pkg; 651 replacing = _replacing; 652 userId = _userId; 653 replacing = _replacing; 654 verifierUid = _verifierUid; 655 } 656 } 657 658 private interface IntentFilterVerifier<T extends IntentFilter> { 659 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 660 T filter, String packageName); 661 void startVerifications(int userId); 662 void receiveVerificationResponse(int verificationId); 663 } 664 665 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 666 private Context mContext; 667 private ComponentName mIntentFilterVerifierComponent; 668 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 669 670 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 671 mContext = context; 672 mIntentFilterVerifierComponent = verifierComponent; 673 } 674 675 private String getDefaultScheme() { 676 return IntentFilter.SCHEME_HTTPS; 677 } 678 679 @Override 680 public void startVerifications(int userId) { 681 // Launch verifications requests 682 int count = mCurrentIntentFilterVerifications.size(); 683 for (int n=0; n<count; n++) { 684 int verificationId = mCurrentIntentFilterVerifications.get(n); 685 final IntentFilterVerificationState ivs = 686 mIntentFilterVerificationStates.get(verificationId); 687 688 String packageName = ivs.getPackageName(); 689 690 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 691 final int filterCount = filters.size(); 692 ArraySet<String> domainsSet = new ArraySet<>(); 693 for (int m=0; m<filterCount; m++) { 694 PackageParser.ActivityIntentInfo filter = filters.get(m); 695 domainsSet.addAll(filter.getHostsList()); 696 } 697 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 698 synchronized (mPackages) { 699 if (mSettings.createIntentFilterVerificationIfNeededLPw( 700 packageName, domainsList) != null) { 701 scheduleWriteSettingsLocked(); 702 } 703 } 704 sendVerificationRequest(userId, verificationId, ivs); 705 } 706 mCurrentIntentFilterVerifications.clear(); 707 } 708 709 private void sendVerificationRequest(int userId, int verificationId, 710 IntentFilterVerificationState ivs) { 711 712 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 713 verificationIntent.putExtra( 714 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 715 verificationId); 716 verificationIntent.putExtra( 717 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 718 getDefaultScheme()); 719 verificationIntent.putExtra( 720 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 721 ivs.getHostsString()); 722 verificationIntent.putExtra( 723 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 724 ivs.getPackageName()); 725 verificationIntent.setComponent(mIntentFilterVerifierComponent); 726 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 727 728 UserHandle user = new UserHandle(userId); 729 mContext.sendBroadcastAsUser(verificationIntent, user); 730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 731 "Sending IntentFilter verification broadcast"); 732 } 733 734 public void receiveVerificationResponse(int verificationId) { 735 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 736 737 final boolean verified = ivs.isVerified(); 738 739 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 740 final int count = filters.size(); 741 if (DEBUG_DOMAIN_VERIFICATION) { 742 Slog.i(TAG, "Received verification response " + verificationId 743 + " for " + count + " filters, verified=" + verified); 744 } 745 for (int n=0; n<count; n++) { 746 PackageParser.ActivityIntentInfo filter = filters.get(n); 747 filter.setVerified(verified); 748 749 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 750 + " verified with result:" + verified + " and hosts:" 751 + ivs.getHostsString()); 752 } 753 754 mIntentFilterVerificationStates.remove(verificationId); 755 756 final String packageName = ivs.getPackageName(); 757 IntentFilterVerificationInfo ivi = null; 758 759 synchronized (mPackages) { 760 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 761 } 762 if (ivi == null) { 763 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 764 + verificationId + " packageName:" + packageName); 765 return; 766 } 767 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 768 "Updating IntentFilterVerificationInfo for package " + packageName 769 +" verificationId:" + verificationId); 770 771 synchronized (mPackages) { 772 if (verified) { 773 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 774 } else { 775 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 776 } 777 scheduleWriteSettingsLocked(); 778 779 final int userId = ivs.getUserId(); 780 if (userId != UserHandle.USER_ALL) { 781 final int userStatus = 782 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 783 784 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 785 boolean needUpdate = false; 786 787 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 788 // already been set by the User thru the Disambiguation dialog 789 switch (userStatus) { 790 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 791 if (verified) { 792 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 793 } else { 794 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 795 } 796 needUpdate = true; 797 break; 798 799 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 800 if (verified) { 801 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 802 needUpdate = true; 803 } 804 break; 805 806 default: 807 // Nothing to do 808 } 809 810 if (needUpdate) { 811 mSettings.updateIntentFilterVerificationStatusLPw( 812 packageName, updatedStatus, userId); 813 scheduleWritePackageRestrictionsLocked(userId); 814 } 815 } 816 } 817 } 818 819 @Override 820 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 821 ActivityIntentInfo filter, String packageName) { 822 if (!hasValidDomains(filter)) { 823 return false; 824 } 825 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 826 if (ivs == null) { 827 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 828 packageName); 829 } 830 if (DEBUG_DOMAIN_VERIFICATION) { 831 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 832 } 833 ivs.addFilter(filter); 834 return true; 835 } 836 837 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 838 int userId, int verificationId, String packageName) { 839 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 840 verifierUid, userId, packageName); 841 ivs.setPendingState(); 842 synchronized (mPackages) { 843 mIntentFilterVerificationStates.append(verificationId, ivs); 844 mCurrentIntentFilterVerifications.add(verificationId); 845 } 846 return ivs; 847 } 848 } 849 850 private static boolean hasValidDomains(ActivityIntentInfo filter) { 851 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 852 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 853 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 854 } 855 856 // Set of pending broadcasts for aggregating enable/disable of components. 857 static class PendingPackageBroadcasts { 858 // for each user id, a map of <package name -> components within that package> 859 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 860 861 public PendingPackageBroadcasts() { 862 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 863 } 864 865 public ArrayList<String> get(int userId, String packageName) { 866 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 867 return packages.get(packageName); 868 } 869 870 public void put(int userId, String packageName, ArrayList<String> components) { 871 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 872 packages.put(packageName, components); 873 } 874 875 public void remove(int userId, String packageName) { 876 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 877 if (packages != null) { 878 packages.remove(packageName); 879 } 880 } 881 882 public void remove(int userId) { 883 mUidMap.remove(userId); 884 } 885 886 public int userIdCount() { 887 return mUidMap.size(); 888 } 889 890 public int userIdAt(int n) { 891 return mUidMap.keyAt(n); 892 } 893 894 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 895 return mUidMap.get(userId); 896 } 897 898 public int size() { 899 // total number of pending broadcast entries across all userIds 900 int num = 0; 901 for (int i = 0; i< mUidMap.size(); i++) { 902 num += mUidMap.valueAt(i).size(); 903 } 904 return num; 905 } 906 907 public void clear() { 908 mUidMap.clear(); 909 } 910 911 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 912 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 913 if (map == null) { 914 map = new ArrayMap<String, ArrayList<String>>(); 915 mUidMap.put(userId, map); 916 } 917 return map; 918 } 919 } 920 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 921 922 // Service Connection to remote media container service to copy 923 // package uri's from external media onto secure containers 924 // or internal storage. 925 private IMediaContainerService mContainerService = null; 926 927 static final int SEND_PENDING_BROADCAST = 1; 928 static final int MCS_BOUND = 3; 929 static final int END_COPY = 4; 930 static final int INIT_COPY = 5; 931 static final int MCS_UNBIND = 6; 932 static final int START_CLEANING_PACKAGE = 7; 933 static final int FIND_INSTALL_LOC = 8; 934 static final int POST_INSTALL = 9; 935 static final int MCS_RECONNECT = 10; 936 static final int MCS_GIVE_UP = 11; 937 static final int UPDATED_MEDIA_STATUS = 12; 938 static final int WRITE_SETTINGS = 13; 939 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 940 static final int PACKAGE_VERIFIED = 15; 941 static final int CHECK_PENDING_VERIFICATION = 16; 942 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 943 static final int INTENT_FILTER_VERIFIED = 18; 944 945 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 946 947 // Delay time in millisecs 948 static final int BROADCAST_DELAY = 10 * 1000; 949 950 static UserManagerService sUserManager; 951 952 // Stores a list of users whose package restrictions file needs to be updated 953 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 954 955 final private DefaultContainerConnection mDefContainerConn = 956 new DefaultContainerConnection(); 957 class DefaultContainerConnection implements ServiceConnection { 958 public void onServiceConnected(ComponentName name, IBinder service) { 959 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 960 IMediaContainerService imcs = 961 IMediaContainerService.Stub.asInterface(service); 962 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 963 } 964 965 public void onServiceDisconnected(ComponentName name) { 966 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 967 } 968 } 969 970 // Recordkeeping of restore-after-install operations that are currently in flight 971 // between the Package Manager and the Backup Manager 972 static class PostInstallData { 973 public InstallArgs args; 974 public PackageInstalledInfo res; 975 976 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 977 args = _a; 978 res = _r; 979 } 980 } 981 982 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 983 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 984 985 // XML tags for backup/restore of various bits of state 986 private static final String TAG_PREFERRED_BACKUP = "pa"; 987 private static final String TAG_DEFAULT_APPS = "da"; 988 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 989 990 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 991 private static final String TAG_ALL_GRANTS = "rt-grants"; 992 private static final String TAG_GRANT = "grant"; 993 private static final String ATTR_PACKAGE_NAME = "pkg"; 994 995 private static final String TAG_PERMISSION = "perm"; 996 private static final String ATTR_PERMISSION_NAME = "name"; 997 private static final String ATTR_IS_GRANTED = "g"; 998 private static final String ATTR_USER_SET = "set"; 999 private static final String ATTR_USER_FIXED = "fixed"; 1000 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1001 1002 // System/policy permission grants are not backed up 1003 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1004 FLAG_PERMISSION_POLICY_FIXED 1005 | FLAG_PERMISSION_SYSTEM_FIXED 1006 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1007 1008 // And we back up these user-adjusted states 1009 private static final int USER_RUNTIME_GRANT_MASK = 1010 FLAG_PERMISSION_USER_SET 1011 | FLAG_PERMISSION_USER_FIXED 1012 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1013 1014 final @Nullable String mRequiredVerifierPackage; 1015 final @Nullable String mRequiredInstallerPackage; 1016 1017 private final PackageUsage mPackageUsage = new PackageUsage(); 1018 1019 private class PackageUsage { 1020 private static final int WRITE_INTERVAL 1021 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1022 1023 private final Object mFileLock = new Object(); 1024 private final AtomicLong mLastWritten = new AtomicLong(0); 1025 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1026 1027 private boolean mIsHistoricalPackageUsageAvailable = true; 1028 1029 boolean isHistoricalPackageUsageAvailable() { 1030 return mIsHistoricalPackageUsageAvailable; 1031 } 1032 1033 void write(boolean force) { 1034 if (force) { 1035 writeInternal(); 1036 return; 1037 } 1038 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1039 && !DEBUG_DEXOPT) { 1040 return; 1041 } 1042 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1043 new Thread("PackageUsage_DiskWriter") { 1044 @Override 1045 public void run() { 1046 try { 1047 writeInternal(); 1048 } finally { 1049 mBackgroundWriteRunning.set(false); 1050 } 1051 } 1052 }.start(); 1053 } 1054 } 1055 1056 private void writeInternal() { 1057 synchronized (mPackages) { 1058 synchronized (mFileLock) { 1059 AtomicFile file = getFile(); 1060 FileOutputStream f = null; 1061 try { 1062 f = file.startWrite(); 1063 BufferedOutputStream out = new BufferedOutputStream(f); 1064 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1065 StringBuilder sb = new StringBuilder(); 1066 for (PackageParser.Package pkg : mPackages.values()) { 1067 if (pkg.mLastPackageUsageTimeInMills == 0) { 1068 continue; 1069 } 1070 sb.setLength(0); 1071 sb.append(pkg.packageName); 1072 sb.append(' '); 1073 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1074 sb.append('\n'); 1075 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1076 } 1077 out.flush(); 1078 file.finishWrite(f); 1079 } catch (IOException e) { 1080 if (f != null) { 1081 file.failWrite(f); 1082 } 1083 Log.e(TAG, "Failed to write package usage times", e); 1084 } 1085 } 1086 } 1087 mLastWritten.set(SystemClock.elapsedRealtime()); 1088 } 1089 1090 void readLP() { 1091 synchronized (mFileLock) { 1092 AtomicFile file = getFile(); 1093 BufferedInputStream in = null; 1094 try { 1095 in = new BufferedInputStream(file.openRead()); 1096 StringBuffer sb = new StringBuffer(); 1097 while (true) { 1098 String packageName = readToken(in, sb, ' '); 1099 if (packageName == null) { 1100 break; 1101 } 1102 String timeInMillisString = readToken(in, sb, '\n'); 1103 if (timeInMillisString == null) { 1104 throw new IOException("Failed to find last usage time for package " 1105 + packageName); 1106 } 1107 PackageParser.Package pkg = mPackages.get(packageName); 1108 if (pkg == null) { 1109 continue; 1110 } 1111 long timeInMillis; 1112 try { 1113 timeInMillis = Long.parseLong(timeInMillisString); 1114 } catch (NumberFormatException e) { 1115 throw new IOException("Failed to parse " + timeInMillisString 1116 + " as a long.", e); 1117 } 1118 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1119 } 1120 } catch (FileNotFoundException expected) { 1121 mIsHistoricalPackageUsageAvailable = false; 1122 } catch (IOException e) { 1123 Log.w(TAG, "Failed to read package usage times", e); 1124 } finally { 1125 IoUtils.closeQuietly(in); 1126 } 1127 } 1128 mLastWritten.set(SystemClock.elapsedRealtime()); 1129 } 1130 1131 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1132 throws IOException { 1133 sb.setLength(0); 1134 while (true) { 1135 int ch = in.read(); 1136 if (ch == -1) { 1137 if (sb.length() == 0) { 1138 return null; 1139 } 1140 throw new IOException("Unexpected EOF"); 1141 } 1142 if (ch == endOfToken) { 1143 return sb.toString(); 1144 } 1145 sb.append((char)ch); 1146 } 1147 } 1148 1149 private AtomicFile getFile() { 1150 File dataDir = Environment.getDataDirectory(); 1151 File systemDir = new File(dataDir, "system"); 1152 File fname = new File(systemDir, "package-usage.list"); 1153 return new AtomicFile(fname); 1154 } 1155 } 1156 1157 class PackageHandler extends Handler { 1158 private boolean mBound = false; 1159 final ArrayList<HandlerParams> mPendingInstalls = 1160 new ArrayList<HandlerParams>(); 1161 1162 private boolean connectToService() { 1163 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1164 " DefaultContainerService"); 1165 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1166 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1167 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1168 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1169 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1170 mBound = true; 1171 return true; 1172 } 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1174 return false; 1175 } 1176 1177 private void disconnectService() { 1178 mContainerService = null; 1179 mBound = false; 1180 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1181 mContext.unbindService(mDefContainerConn); 1182 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1183 } 1184 1185 PackageHandler(Looper looper) { 1186 super(looper); 1187 } 1188 1189 public void handleMessage(Message msg) { 1190 try { 1191 doHandleMessage(msg); 1192 } finally { 1193 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1194 } 1195 } 1196 1197 void doHandleMessage(Message msg) { 1198 switch (msg.what) { 1199 case INIT_COPY: { 1200 HandlerParams params = (HandlerParams) msg.obj; 1201 int idx = mPendingInstalls.size(); 1202 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1203 // If a bind was already initiated we dont really 1204 // need to do anything. The pending install 1205 // will be processed later on. 1206 if (!mBound) { 1207 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1208 System.identityHashCode(mHandler)); 1209 // If this is the only one pending we might 1210 // have to bind to the service again. 1211 if (!connectToService()) { 1212 Slog.e(TAG, "Failed to bind to media container service"); 1213 params.serviceError(); 1214 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1215 System.identityHashCode(mHandler)); 1216 if (params.traceMethod != null) { 1217 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1218 params.traceCookie); 1219 } 1220 return; 1221 } else { 1222 // Once we bind to the service, the first 1223 // pending request will be processed. 1224 mPendingInstalls.add(idx, params); 1225 } 1226 } else { 1227 mPendingInstalls.add(idx, params); 1228 // Already bound to the service. Just make 1229 // sure we trigger off processing the first request. 1230 if (idx == 0) { 1231 mHandler.sendEmptyMessage(MCS_BOUND); 1232 } 1233 } 1234 break; 1235 } 1236 case MCS_BOUND: { 1237 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1238 if (msg.obj != null) { 1239 mContainerService = (IMediaContainerService) msg.obj; 1240 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1241 System.identityHashCode(mHandler)); 1242 } 1243 if (mContainerService == null) { 1244 if (!mBound) { 1245 // Something seriously wrong since we are not bound and we are not 1246 // waiting for connection. Bail out. 1247 Slog.e(TAG, "Cannot bind to media container service"); 1248 for (HandlerParams params : mPendingInstalls) { 1249 // Indicate service bind error 1250 params.serviceError(); 1251 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1252 System.identityHashCode(params)); 1253 if (params.traceMethod != null) { 1254 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1255 params.traceMethod, params.traceCookie); 1256 } 1257 return; 1258 } 1259 mPendingInstalls.clear(); 1260 } else { 1261 Slog.w(TAG, "Waiting to connect to media container service"); 1262 } 1263 } else if (mPendingInstalls.size() > 0) { 1264 HandlerParams params = mPendingInstalls.get(0); 1265 if (params != null) { 1266 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1267 System.identityHashCode(params)); 1268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1269 if (params.startCopy()) { 1270 // We are done... look for more work or to 1271 // go idle. 1272 if (DEBUG_SD_INSTALL) Log.i(TAG, 1273 "Checking for more work or unbind..."); 1274 // Delete pending install 1275 if (mPendingInstalls.size() > 0) { 1276 mPendingInstalls.remove(0); 1277 } 1278 if (mPendingInstalls.size() == 0) { 1279 if (mBound) { 1280 if (DEBUG_SD_INSTALL) Log.i(TAG, 1281 "Posting delayed MCS_UNBIND"); 1282 removeMessages(MCS_UNBIND); 1283 Message ubmsg = obtainMessage(MCS_UNBIND); 1284 // Unbind after a little delay, to avoid 1285 // continual thrashing. 1286 sendMessageDelayed(ubmsg, 10000); 1287 } 1288 } else { 1289 // There are more pending requests in queue. 1290 // Just post MCS_BOUND message to trigger processing 1291 // of next pending install. 1292 if (DEBUG_SD_INSTALL) Log.i(TAG, 1293 "Posting MCS_BOUND for next work"); 1294 mHandler.sendEmptyMessage(MCS_BOUND); 1295 } 1296 } 1297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1298 } 1299 } else { 1300 // Should never happen ideally. 1301 Slog.w(TAG, "Empty queue"); 1302 } 1303 break; 1304 } 1305 case MCS_RECONNECT: { 1306 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1307 if (mPendingInstalls.size() > 0) { 1308 if (mBound) { 1309 disconnectService(); 1310 } 1311 if (!connectToService()) { 1312 Slog.e(TAG, "Failed to bind to media container service"); 1313 for (HandlerParams params : mPendingInstalls) { 1314 // Indicate service bind error 1315 params.serviceError(); 1316 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1317 System.identityHashCode(params)); 1318 } 1319 mPendingInstalls.clear(); 1320 } 1321 } 1322 break; 1323 } 1324 case MCS_UNBIND: { 1325 // If there is no actual work left, then time to unbind. 1326 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1327 1328 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1329 if (mBound) { 1330 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1331 1332 disconnectService(); 1333 } 1334 } else if (mPendingInstalls.size() > 0) { 1335 // There are more pending requests in queue. 1336 // Just post MCS_BOUND message to trigger processing 1337 // of next pending install. 1338 mHandler.sendEmptyMessage(MCS_BOUND); 1339 } 1340 1341 break; 1342 } 1343 case MCS_GIVE_UP: { 1344 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1345 HandlerParams params = mPendingInstalls.remove(0); 1346 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1347 System.identityHashCode(params)); 1348 break; 1349 } 1350 case SEND_PENDING_BROADCAST: { 1351 String packages[]; 1352 ArrayList<String> components[]; 1353 int size = 0; 1354 int uids[]; 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1356 synchronized (mPackages) { 1357 if (mPendingBroadcasts == null) { 1358 return; 1359 } 1360 size = mPendingBroadcasts.size(); 1361 if (size <= 0) { 1362 // Nothing to be done. Just return 1363 return; 1364 } 1365 packages = new String[size]; 1366 components = new ArrayList[size]; 1367 uids = new int[size]; 1368 int i = 0; // filling out the above arrays 1369 1370 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1371 int packageUserId = mPendingBroadcasts.userIdAt(n); 1372 Iterator<Map.Entry<String, ArrayList<String>>> it 1373 = mPendingBroadcasts.packagesForUserId(packageUserId) 1374 .entrySet().iterator(); 1375 while (it.hasNext() && i < size) { 1376 Map.Entry<String, ArrayList<String>> ent = it.next(); 1377 packages[i] = ent.getKey(); 1378 components[i] = ent.getValue(); 1379 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1380 uids[i] = (ps != null) 1381 ? UserHandle.getUid(packageUserId, ps.appId) 1382 : -1; 1383 i++; 1384 } 1385 } 1386 size = i; 1387 mPendingBroadcasts.clear(); 1388 } 1389 // Send broadcasts 1390 for (int i = 0; i < size; i++) { 1391 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1392 } 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1394 break; 1395 } 1396 case START_CLEANING_PACKAGE: { 1397 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1398 final String packageName = (String)msg.obj; 1399 final int userId = msg.arg1; 1400 final boolean andCode = msg.arg2 != 0; 1401 synchronized (mPackages) { 1402 if (userId == UserHandle.USER_ALL) { 1403 int[] users = sUserManager.getUserIds(); 1404 for (int user : users) { 1405 mSettings.addPackageToCleanLPw( 1406 new PackageCleanItem(user, packageName, andCode)); 1407 } 1408 } else { 1409 mSettings.addPackageToCleanLPw( 1410 new PackageCleanItem(userId, packageName, andCode)); 1411 } 1412 } 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1414 startCleaningPackages(); 1415 } break; 1416 case POST_INSTALL: { 1417 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1418 1419 PostInstallData data = mRunningInstalls.get(msg.arg1); 1420 mRunningInstalls.delete(msg.arg1); 1421 1422 if (data != null) { 1423 InstallArgs args = data.args; 1424 PackageInstalledInfo parentRes = data.res; 1425 1426 final boolean grantPermissions = (args.installFlags 1427 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1428 final String[] grantedPermissions = args.installGrantPermissions; 1429 1430 // Handle the parent package 1431 handlePackagePostInstall(parentRes, grantPermissions, grantedPermissions, 1432 args.observer); 1433 1434 // Handle the child packages 1435 final int childCount = (parentRes.addedChildPackages != null) 1436 ? parentRes.addedChildPackages.size() : 0; 1437 for (int i = 0; i < childCount; i++) { 1438 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1439 handlePackagePostInstall(childRes, grantPermissions, grantedPermissions, 1440 args.observer); 1441 } 1442 1443 // Log tracing if needed 1444 if (args.traceMethod != null) { 1445 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1446 args.traceCookie); 1447 } 1448 } else { 1449 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1450 } 1451 1452 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1453 } break; 1454 case UPDATED_MEDIA_STATUS: { 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1456 boolean reportStatus = msg.arg1 == 1; 1457 boolean doGc = msg.arg2 == 1; 1458 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1459 if (doGc) { 1460 // Force a gc to clear up stale containers. 1461 Runtime.getRuntime().gc(); 1462 } 1463 if (msg.obj != null) { 1464 @SuppressWarnings("unchecked") 1465 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1466 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1467 // Unload containers 1468 unloadAllContainers(args); 1469 } 1470 if (reportStatus) { 1471 try { 1472 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1473 PackageHelper.getMountService().finishMediaUpdate(); 1474 } catch (RemoteException e) { 1475 Log.e(TAG, "MountService not running?"); 1476 } 1477 } 1478 } break; 1479 case WRITE_SETTINGS: { 1480 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1481 synchronized (mPackages) { 1482 removeMessages(WRITE_SETTINGS); 1483 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1484 mSettings.writeLPr(); 1485 mDirtyUsers.clear(); 1486 } 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1488 } break; 1489 case WRITE_PACKAGE_RESTRICTIONS: { 1490 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1491 synchronized (mPackages) { 1492 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1493 for (int userId : mDirtyUsers) { 1494 mSettings.writePackageRestrictionsLPr(userId); 1495 } 1496 mDirtyUsers.clear(); 1497 } 1498 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1499 } break; 1500 case CHECK_PENDING_VERIFICATION: { 1501 final int verificationId = msg.arg1; 1502 final PackageVerificationState state = mPendingVerification.get(verificationId); 1503 1504 if ((state != null) && !state.timeoutExtended()) { 1505 final InstallArgs args = state.getInstallArgs(); 1506 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1507 1508 Slog.i(TAG, "Verification timed out for " + originUri); 1509 mPendingVerification.remove(verificationId); 1510 1511 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1512 1513 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1514 Slog.i(TAG, "Continuing with installation of " + originUri); 1515 state.setVerifierResponse(Binder.getCallingUid(), 1516 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1517 broadcastPackageVerified(verificationId, originUri, 1518 PackageManager.VERIFICATION_ALLOW, 1519 state.getInstallArgs().getUser()); 1520 try { 1521 ret = args.copyApk(mContainerService, true); 1522 } catch (RemoteException e) { 1523 Slog.e(TAG, "Could not contact the ContainerService"); 1524 } 1525 } else { 1526 broadcastPackageVerified(verificationId, originUri, 1527 PackageManager.VERIFICATION_REJECT, 1528 state.getInstallArgs().getUser()); 1529 } 1530 1531 Trace.asyncTraceEnd( 1532 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1533 1534 processPendingInstall(args, ret); 1535 mHandler.sendEmptyMessage(MCS_UNBIND); 1536 } 1537 break; 1538 } 1539 case PACKAGE_VERIFIED: { 1540 final int verificationId = msg.arg1; 1541 1542 final PackageVerificationState state = mPendingVerification.get(verificationId); 1543 if (state == null) { 1544 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1545 break; 1546 } 1547 1548 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1549 1550 state.setVerifierResponse(response.callerUid, response.code); 1551 1552 if (state.isVerificationComplete()) { 1553 mPendingVerification.remove(verificationId); 1554 1555 final InstallArgs args = state.getInstallArgs(); 1556 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1557 1558 int ret; 1559 if (state.isInstallAllowed()) { 1560 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1561 broadcastPackageVerified(verificationId, originUri, 1562 response.code, state.getInstallArgs().getUser()); 1563 try { 1564 ret = args.copyApk(mContainerService, true); 1565 } catch (RemoteException e) { 1566 Slog.e(TAG, "Could not contact the ContainerService"); 1567 } 1568 } else { 1569 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1570 } 1571 1572 Trace.asyncTraceEnd( 1573 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1574 1575 processPendingInstall(args, ret); 1576 mHandler.sendEmptyMessage(MCS_UNBIND); 1577 } 1578 1579 break; 1580 } 1581 case START_INTENT_FILTER_VERIFICATIONS: { 1582 IFVerificationParams params = (IFVerificationParams) msg.obj; 1583 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1584 params.replacing, params.pkg); 1585 break; 1586 } 1587 case INTENT_FILTER_VERIFIED: { 1588 final int verificationId = msg.arg1; 1589 1590 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1591 verificationId); 1592 if (state == null) { 1593 Slog.w(TAG, "Invalid IntentFilter verification token " 1594 + verificationId + " received"); 1595 break; 1596 } 1597 1598 final int userId = state.getUserId(); 1599 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1601 "Processing IntentFilter verification with token:" 1602 + verificationId + " and userId:" + userId); 1603 1604 final IntentFilterVerificationResponse response = 1605 (IntentFilterVerificationResponse) msg.obj; 1606 1607 state.setVerifierResponse(response.callerUid, response.code); 1608 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1610 "IntentFilter verification with token:" + verificationId 1611 + " and userId:" + userId 1612 + " is settings verifier response with response code:" 1613 + response.code); 1614 1615 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1616 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1617 + response.getFailedDomainsString()); 1618 } 1619 1620 if (state.isVerificationComplete()) { 1621 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1622 } else { 1623 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1624 "IntentFilter verification with token:" + verificationId 1625 + " was not said to be complete"); 1626 } 1627 1628 break; 1629 } 1630 } 1631 } 1632 } 1633 1634 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1635 String[] grantedPermissions, IPackageInstallObserver2 installObserver) { 1636 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1637 // Send the removed broadcasts 1638 if (res.removedInfo != null) { 1639 res.removedInfo.sendPackageRemovedBroadcasts(); 1640 } 1641 1642 // Now that we successfully installed the package, grant runtime 1643 // permissions if requested before broadcasting the install. 1644 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1645 >= Build.VERSION_CODES.M) { 1646 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1647 } 1648 1649 final boolean update = res.removedInfo != null 1650 && res.removedInfo.removedPackage != null; 1651 1652 // If this is the first time we have child packages for a disabled privileged 1653 // app that had no children, we grant requested runtime permissions to the new 1654 // children if the parent on the system image had them already granted. 1655 if (res.pkg.parentPackage != null) { 1656 synchronized (mPackages) { 1657 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1658 } 1659 } 1660 1661 synchronized (mPackages) { 1662 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1663 } 1664 1665 final String packageName = res.pkg.applicationInfo.packageName; 1666 Bundle extras = new Bundle(1); 1667 extras.putInt(Intent.EXTRA_UID, res.uid); 1668 1669 // Determine the set of users who are adding this package for 1670 // the first time vs. those who are seeing an update. 1671 int[] firstUsers = EMPTY_INT_ARRAY; 1672 int[] updateUsers = EMPTY_INT_ARRAY; 1673 if (res.origUsers == null || res.origUsers.length == 0) { 1674 firstUsers = res.newUsers; 1675 } else { 1676 for (int newUser : res.newUsers) { 1677 boolean isNew = true; 1678 for (int origUser : res.origUsers) { 1679 if (origUser == newUser) { 1680 isNew = false; 1681 break; 1682 } 1683 } 1684 if (isNew) { 1685 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1686 } else { 1687 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1688 } 1689 } 1690 } 1691 1692 // Send installed broadcasts if the install/update is not ephemeral 1693 if (!isEphemeral(res.pkg)) { 1694 // Send added for users that see the package for the first time 1695 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1696 extras, 0 /*flags*/, null /*targetPackage*/, 1697 null /*finishedReceiver*/, firstUsers); 1698 1699 // Send added for users that don't see the package for the first time 1700 if (update) { 1701 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1702 } 1703 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1704 extras, 0 /*flags*/, null /*targetPackage*/, 1705 null /*finishedReceiver*/, updateUsers); 1706 1707 // Send replaced for users that don't see the package for the first time 1708 if (update) { 1709 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1710 packageName, extras, 0 /*flags*/, 1711 null /*targetPackage*/, null /*finishedReceiver*/, 1712 updateUsers); 1713 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1714 null /*package*/, null /*extras*/, 0 /*flags*/, 1715 packageName /*targetPackage*/, 1716 null /*finishedReceiver*/, updateUsers); 1717 } 1718 1719 // Send broadcast package appeared if forward locked/external for all users 1720 // treat asec-hosted packages like removable media on upgrade 1721 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1722 if (DEBUG_INSTALL) { 1723 Slog.i(TAG, "upgrading pkg " + res.pkg 1724 + " is ASEC-hosted -> AVAILABLE"); 1725 } 1726 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1727 ArrayList<String> pkgList = new ArrayList<>(1); 1728 pkgList.add(packageName); 1729 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1730 } 1731 } 1732 1733 // Work that needs to happen on first install within each user 1734 if (firstUsers != null && firstUsers.length > 0) { 1735 synchronized (mPackages) { 1736 for (int userId : firstUsers) { 1737 // If this app is a browser and it's newly-installed for some 1738 // users, clear any default-browser state in those users. The 1739 // app's nature doesn't depend on the user, so we can just check 1740 // its browser nature in any user and generalize. 1741 if (packageIsBrowser(packageName, userId)) { 1742 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1743 } 1744 1745 // We may also need to apply pending (restored) runtime 1746 // permission grants within these users. 1747 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1748 } 1749 } 1750 } 1751 1752 // Log current value of "unknown sources" setting 1753 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1754 getUnknownSourcesSettings()); 1755 1756 // Force a gc to clear up things 1757 Runtime.getRuntime().gc(); 1758 1759 // Remove the replaced package's older resources safely now 1760 // We delete after a gc for applications on sdcard. 1761 if (res.removedInfo != null && res.removedInfo.args != null) { 1762 synchronized (mInstallLock) { 1763 res.removedInfo.args.doPostDeleteLI(true); 1764 } 1765 } 1766 } 1767 1768 // If someone is watching installs - notify them 1769 if (installObserver != null) { 1770 try { 1771 Bundle extras = extrasForInstallResult(res); 1772 installObserver.onPackageInstalled(res.name, res.returnCode, 1773 res.returnMsg, extras); 1774 } catch (RemoteException e) { 1775 Slog.i(TAG, "Observer no longer exists."); 1776 } 1777 } 1778 } 1779 1780 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1781 PackageParser.Package pkg) { 1782 if (pkg.parentPackage == null) { 1783 return; 1784 } 1785 if (pkg.requestedPermissions == null) { 1786 return; 1787 } 1788 final PackageSetting disabledSysParentPs = mSettings 1789 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1790 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1791 || !disabledSysParentPs.isPrivileged() 1792 || (disabledSysParentPs.childPackageNames != null 1793 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1794 return; 1795 } 1796 final int[] allUserIds = sUserManager.getUserIds(); 1797 final int permCount = pkg.requestedPermissions.size(); 1798 for (int i = 0; i < permCount; i++) { 1799 String permission = pkg.requestedPermissions.get(i); 1800 BasePermission bp = mSettings.mPermissions.get(permission); 1801 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1802 continue; 1803 } 1804 for (int userId : allUserIds) { 1805 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1806 permission, userId)) { 1807 grantRuntimePermission(pkg.packageName, permission, userId); 1808 } 1809 } 1810 } 1811 } 1812 1813 private StorageEventListener mStorageListener = new StorageEventListener() { 1814 @Override 1815 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1816 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1817 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1818 final String volumeUuid = vol.getFsUuid(); 1819 1820 // Clean up any users or apps that were removed or recreated 1821 // while this volume was missing 1822 reconcileUsers(volumeUuid); 1823 reconcileApps(volumeUuid); 1824 1825 // Clean up any install sessions that expired or were 1826 // cancelled while this volume was missing 1827 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1828 1829 loadPrivatePackages(vol); 1830 1831 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1832 unloadPrivatePackages(vol); 1833 } 1834 } 1835 1836 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1837 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1838 updateExternalMediaStatus(true, false); 1839 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1840 updateExternalMediaStatus(false, false); 1841 } 1842 } 1843 } 1844 1845 @Override 1846 public void onVolumeForgotten(String fsUuid) { 1847 if (TextUtils.isEmpty(fsUuid)) { 1848 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1849 return; 1850 } 1851 1852 // Remove any apps installed on the forgotten volume 1853 synchronized (mPackages) { 1854 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1855 for (PackageSetting ps : packages) { 1856 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1857 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1858 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1859 } 1860 1861 mSettings.onVolumeForgotten(fsUuid); 1862 mSettings.writeLPr(); 1863 } 1864 } 1865 }; 1866 1867 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1868 String[] grantedPermissions) { 1869 for (int userId : userIds) { 1870 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1871 } 1872 1873 // We could have touched GID membership, so flush out packages.list 1874 synchronized (mPackages) { 1875 mSettings.writePackageListLPr(); 1876 } 1877 } 1878 1879 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1880 String[] grantedPermissions) { 1881 SettingBase sb = (SettingBase) pkg.mExtras; 1882 if (sb == null) { 1883 return; 1884 } 1885 1886 PermissionsState permissionsState = sb.getPermissionsState(); 1887 1888 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1889 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1890 1891 synchronized (mPackages) { 1892 for (String permission : pkg.requestedPermissions) { 1893 BasePermission bp = mSettings.mPermissions.get(permission); 1894 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1895 && (grantedPermissions == null 1896 || ArrayUtils.contains(grantedPermissions, permission))) { 1897 final int flags = permissionsState.getPermissionFlags(permission, userId); 1898 // Installer cannot change immutable permissions. 1899 if ((flags & immutableFlags) == 0) { 1900 grantRuntimePermission(pkg.packageName, permission, userId); 1901 } 1902 } 1903 } 1904 } 1905 } 1906 1907 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1908 Bundle extras = null; 1909 switch (res.returnCode) { 1910 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1911 extras = new Bundle(); 1912 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1913 res.origPermission); 1914 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1915 res.origPackage); 1916 break; 1917 } 1918 case PackageManager.INSTALL_SUCCEEDED: { 1919 extras = new Bundle(); 1920 extras.putBoolean(Intent.EXTRA_REPLACING, 1921 res.removedInfo != null && res.removedInfo.removedPackage != null); 1922 break; 1923 } 1924 } 1925 return extras; 1926 } 1927 1928 void scheduleWriteSettingsLocked() { 1929 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1930 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1931 } 1932 } 1933 1934 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1935 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1936 scheduleWritePackageRestrictionsLocked(userId); 1937 } 1938 1939 void scheduleWritePackageRestrictionsLocked(int userId) { 1940 final int[] userIds = (userId == UserHandle.USER_ALL) 1941 ? sUserManager.getUserIds() : new int[]{userId}; 1942 for (int nextUserId : userIds) { 1943 if (!sUserManager.exists(nextUserId)) return; 1944 mDirtyUsers.add(nextUserId); 1945 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1946 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1947 } 1948 } 1949 } 1950 1951 public static PackageManagerService main(Context context, Installer installer, 1952 boolean factoryTest, boolean onlyCore) { 1953 PackageManagerService m = new PackageManagerService(context, installer, 1954 factoryTest, onlyCore); 1955 m.enableSystemUserPackages(); 1956 ServiceManager.addService("package", m); 1957 return m; 1958 } 1959 1960 private void enableSystemUserPackages() { 1961 if (!UserManager.isSplitSystemUser()) { 1962 return; 1963 } 1964 // For system user, enable apps based on the following conditions: 1965 // - app is whitelisted or belong to one of these groups: 1966 // -- system app which has no launcher icons 1967 // -- system app which has INTERACT_ACROSS_USERS permission 1968 // -- system IME app 1969 // - app is not in the blacklist 1970 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1971 Set<String> enableApps = new ArraySet<>(); 1972 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1973 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1974 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1975 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1976 enableApps.addAll(wlApps); 1977 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1978 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1979 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1980 enableApps.removeAll(blApps); 1981 Log.i(TAG, "Applications installed for system user: " + enableApps); 1982 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1983 UserHandle.SYSTEM); 1984 final int allAppsSize = allAps.size(); 1985 synchronized (mPackages) { 1986 for (int i = 0; i < allAppsSize; i++) { 1987 String pName = allAps.get(i); 1988 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1989 // Should not happen, but we shouldn't be failing if it does 1990 if (pkgSetting == null) { 1991 continue; 1992 } 1993 boolean install = enableApps.contains(pName); 1994 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1995 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1996 + " for system user"); 1997 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1998 } 1999 } 2000 } 2001 } 2002 2003 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2004 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2005 Context.DISPLAY_SERVICE); 2006 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2007 } 2008 2009 public PackageManagerService(Context context, Installer installer, 2010 boolean factoryTest, boolean onlyCore) { 2011 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2012 SystemClock.uptimeMillis()); 2013 2014 if (mSdkVersion <= 0) { 2015 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2016 } 2017 2018 mContext = context; 2019 mFactoryTest = factoryTest; 2020 mOnlyCore = onlyCore; 2021 mMetrics = new DisplayMetrics(); 2022 mSettings = new Settings(mPackages); 2023 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2024 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2025 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2026 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2027 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2028 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2029 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2030 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2031 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2032 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2033 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2034 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2035 2036 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2037 if (separateProcesses != null && separateProcesses.length() > 0) { 2038 if ("*".equals(separateProcesses)) { 2039 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2040 mSeparateProcesses = null; 2041 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2042 } else { 2043 mDefParseFlags = 0; 2044 mSeparateProcesses = separateProcesses.split(","); 2045 Slog.w(TAG, "Running with debug.separate_processes: " 2046 + separateProcesses); 2047 } 2048 } else { 2049 mDefParseFlags = 0; 2050 mSeparateProcesses = null; 2051 } 2052 2053 mInstaller = installer; 2054 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2055 "*dexopt*"); 2056 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2057 2058 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2059 FgThread.get().getLooper()); 2060 2061 getDefaultDisplayMetrics(context, mMetrics); 2062 2063 SystemConfig systemConfig = SystemConfig.getInstance(); 2064 mGlobalGids = systemConfig.getGlobalGids(); 2065 mSystemPermissions = systemConfig.getSystemPermissions(); 2066 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2067 2068 synchronized (mInstallLock) { 2069 // writer 2070 synchronized (mPackages) { 2071 mHandlerThread = new ServiceThread(TAG, 2072 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2073 mHandlerThread.start(); 2074 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2075 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2076 2077 File dataDir = Environment.getDataDirectory(); 2078 mAppInstallDir = new File(dataDir, "app"); 2079 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2080 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2081 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2082 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2083 2084 sUserManager = new UserManagerService(context, this, mPackages); 2085 2086 // Propagate permission configuration in to package manager. 2087 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2088 = systemConfig.getPermissions(); 2089 for (int i=0; i<permConfig.size(); i++) { 2090 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2091 BasePermission bp = mSettings.mPermissions.get(perm.name); 2092 if (bp == null) { 2093 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2094 mSettings.mPermissions.put(perm.name, bp); 2095 } 2096 if (perm.gids != null) { 2097 bp.setGids(perm.gids, perm.perUser); 2098 } 2099 } 2100 2101 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2102 for (int i=0; i<libConfig.size(); i++) { 2103 mSharedLibraries.put(libConfig.keyAt(i), 2104 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2105 } 2106 2107 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2108 2109 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2110 2111 String customResolverActivity = Resources.getSystem().getString( 2112 R.string.config_customResolverActivity); 2113 if (TextUtils.isEmpty(customResolverActivity)) { 2114 customResolverActivity = null; 2115 } else { 2116 mCustomResolverComponentName = ComponentName.unflattenFromString( 2117 customResolverActivity); 2118 } 2119 2120 long startTime = SystemClock.uptimeMillis(); 2121 2122 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2123 startTime); 2124 2125 // Set flag to monitor and not change apk file paths when 2126 // scanning install directories. 2127 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2128 2129 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2130 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2131 2132 if (bootClassPath == null) { 2133 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2134 } 2135 2136 if (systemServerClassPath == null) { 2137 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2138 } 2139 2140 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2141 final String[] dexCodeInstructionSets = 2142 getDexCodeInstructionSets( 2143 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2144 2145 /** 2146 * Ensure all external libraries have had dexopt run on them. 2147 */ 2148 if (mSharedLibraries.size() > 0) { 2149 // NOTE: For now, we're compiling these system "shared libraries" 2150 // (and framework jars) into all available architectures. It's possible 2151 // to compile them only when we come across an app that uses them (there's 2152 // already logic for that in scanPackageLI) but that adds some complexity. 2153 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2154 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2155 final String lib = libEntry.path; 2156 if (lib == null) { 2157 continue; 2158 } 2159 2160 try { 2161 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2162 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2163 // Shared libraries do not have profiles so we perform a full 2164 // AOT compilation. 2165 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2166 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2167 StorageManager.UUID_PRIVATE_INTERNAL, 2168 false /*useProfiles*/); 2169 } 2170 } catch (FileNotFoundException e) { 2171 Slog.w(TAG, "Library not found: " + lib); 2172 } catch (IOException | InstallerException e) { 2173 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2174 + e.getMessage()); 2175 } 2176 } 2177 } 2178 } 2179 2180 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2181 2182 final VersionInfo ver = mSettings.getInternalVersion(); 2183 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2184 // when upgrading from pre-M, promote system app permissions from install to runtime 2185 mPromoteSystemApps = 2186 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2187 2188 // save off the names of pre-existing system packages prior to scanning; we don't 2189 // want to automatically grant runtime permissions for new system apps 2190 if (mPromoteSystemApps) { 2191 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2192 while (pkgSettingIter.hasNext()) { 2193 PackageSetting ps = pkgSettingIter.next(); 2194 if (isSystemApp(ps)) { 2195 mExistingSystemPackages.add(ps.name); 2196 } 2197 } 2198 } 2199 2200 // Collect vendor overlay packages. 2201 // (Do this before scanning any apps.) 2202 // For security and version matching reason, only consider 2203 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2204 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2205 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2206 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2207 2208 // Find base frameworks (resource packages without code). 2209 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2210 | PackageParser.PARSE_IS_SYSTEM_DIR 2211 | PackageParser.PARSE_IS_PRIVILEGED, 2212 scanFlags | SCAN_NO_DEX, 0); 2213 2214 // Collected privileged system packages. 2215 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2216 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2217 | PackageParser.PARSE_IS_SYSTEM_DIR 2218 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2219 2220 // Collect ordinary system packages. 2221 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2222 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2223 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2224 2225 // Collect all vendor packages. 2226 File vendorAppDir = new File("/vendor/app"); 2227 try { 2228 vendorAppDir = vendorAppDir.getCanonicalFile(); 2229 } catch (IOException e) { 2230 // failed to look up canonical path, continue with original one 2231 } 2232 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2233 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2234 2235 // Collect all OEM packages. 2236 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2237 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2238 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2239 2240 // Prune any system packages that no longer exist. 2241 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2242 if (!mOnlyCore) { 2243 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2244 while (psit.hasNext()) { 2245 PackageSetting ps = psit.next(); 2246 2247 /* 2248 * If this is not a system app, it can't be a 2249 * disable system app. 2250 */ 2251 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2252 continue; 2253 } 2254 2255 /* 2256 * If the package is scanned, it's not erased. 2257 */ 2258 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2259 if (scannedPkg != null) { 2260 /* 2261 * If the system app is both scanned and in the 2262 * disabled packages list, then it must have been 2263 * added via OTA. Remove it from the currently 2264 * scanned package so the previously user-installed 2265 * application can be scanned. 2266 */ 2267 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2268 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2269 + ps.name + "; removing system app. Last known codePath=" 2270 + ps.codePathString + ", installStatus=" + ps.installStatus 2271 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2272 + scannedPkg.mVersionCode); 2273 removePackageLI(scannedPkg, true); 2274 mExpectingBetter.put(ps.name, ps.codePath); 2275 } 2276 2277 continue; 2278 } 2279 2280 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2281 psit.remove(); 2282 logCriticalInfo(Log.WARN, "System package " + ps.name 2283 + " no longer exists; wiping its data"); 2284 removeDataDirsLI(null, ps.name); 2285 } else { 2286 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2287 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2288 possiblyDeletedUpdatedSystemApps.add(ps.name); 2289 } 2290 } 2291 } 2292 } 2293 2294 //look for any incomplete package installations 2295 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2296 //clean up list 2297 for(int i = 0; i < deletePkgsList.size(); i++) { 2298 //clean up here 2299 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2300 } 2301 //delete tmp files 2302 deleteTempPackageFiles(); 2303 2304 // Remove any shared userIDs that have no associated packages 2305 mSettings.pruneSharedUsersLPw(); 2306 2307 if (!mOnlyCore) { 2308 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2309 SystemClock.uptimeMillis()); 2310 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2311 2312 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2313 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2314 2315 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2316 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2317 2318 /** 2319 * Remove disable package settings for any updated system 2320 * apps that were removed via an OTA. If they're not a 2321 * previously-updated app, remove them completely. 2322 * Otherwise, just revoke their system-level permissions. 2323 */ 2324 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2325 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2326 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2327 2328 String msg; 2329 if (deletedPkg == null) { 2330 msg = "Updated system package " + deletedAppName 2331 + " no longer exists; wiping its data"; 2332 removeDataDirsLI(null, deletedAppName); 2333 } else { 2334 msg = "Updated system app + " + deletedAppName 2335 + " no longer present; removing system privileges for " 2336 + deletedAppName; 2337 2338 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2339 2340 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2341 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2342 } 2343 logCriticalInfo(Log.WARN, msg); 2344 } 2345 2346 /** 2347 * Make sure all system apps that we expected to appear on 2348 * the userdata partition actually showed up. If they never 2349 * appeared, crawl back and revive the system version. 2350 */ 2351 for (int i = 0; i < mExpectingBetter.size(); i++) { 2352 final String packageName = mExpectingBetter.keyAt(i); 2353 if (!mPackages.containsKey(packageName)) { 2354 final File scanFile = mExpectingBetter.valueAt(i); 2355 2356 logCriticalInfo(Log.WARN, "Expected better " + packageName 2357 + " but never showed up; reverting to system"); 2358 2359 final int reparseFlags; 2360 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2361 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2362 | PackageParser.PARSE_IS_SYSTEM_DIR 2363 | PackageParser.PARSE_IS_PRIVILEGED; 2364 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2365 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2366 | PackageParser.PARSE_IS_SYSTEM_DIR; 2367 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2368 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2369 | PackageParser.PARSE_IS_SYSTEM_DIR; 2370 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2371 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2372 | PackageParser.PARSE_IS_SYSTEM_DIR; 2373 } else { 2374 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2375 continue; 2376 } 2377 2378 mSettings.enableSystemPackageLPw(packageName); 2379 2380 try { 2381 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2382 } catch (PackageManagerException e) { 2383 Slog.e(TAG, "Failed to parse original system package: " 2384 + e.getMessage()); 2385 } 2386 } 2387 } 2388 } 2389 mExpectingBetter.clear(); 2390 2391 // Now that we know all of the shared libraries, update all clients to have 2392 // the correct library paths. 2393 updateAllSharedLibrariesLPw(); 2394 2395 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2396 // NOTE: We ignore potential failures here during a system scan (like 2397 // the rest of the commands above) because there's precious little we 2398 // can do about it. A settings error is reported, though. 2399 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2400 false /* boot complete */); 2401 } 2402 2403 // Now that we know all the packages we are keeping, 2404 // read and update their last usage times. 2405 mPackageUsage.readLP(); 2406 2407 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2408 SystemClock.uptimeMillis()); 2409 Slog.i(TAG, "Time to scan packages: " 2410 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2411 + " seconds"); 2412 2413 // If the platform SDK has changed since the last time we booted, 2414 // we need to re-grant app permission to catch any new ones that 2415 // appear. This is really a hack, and means that apps can in some 2416 // cases get permissions that the user didn't initially explicitly 2417 // allow... it would be nice to have some better way to handle 2418 // this situation. 2419 int updateFlags = UPDATE_PERMISSIONS_ALL; 2420 if (ver.sdkVersion != mSdkVersion) { 2421 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2422 + mSdkVersion + "; regranting permissions for internal storage"); 2423 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2424 } 2425 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2426 ver.sdkVersion = mSdkVersion; 2427 2428 // If this is the first boot or an update from pre-M, and it is a normal 2429 // boot, then we need to initialize the default preferred apps across 2430 // all defined users. 2431 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2432 for (UserInfo user : sUserManager.getUsers(true)) { 2433 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2434 applyFactoryDefaultBrowserLPw(user.id); 2435 primeDomainVerificationsLPw(user.id); 2436 } 2437 } 2438 2439 // Prepare storage for system user really early during boot, 2440 // since core system apps like SettingsProvider and SystemUI 2441 // can't wait for user to start 2442 final int storageFlags; 2443 if (StorageManager.isFileBasedEncryptionEnabled()) { 2444 storageFlags = StorageManager.FLAG_STORAGE_DE; 2445 } else { 2446 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2447 } 2448 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2449 storageFlags); 2450 2451 if (!StorageManager.isFileBasedEncryptionEnabled() 2452 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 2453 // When upgrading a non-FBE device, we might need to shuffle 2454 // around the default storage location of system apps 2455 final List<UserInfo> users = sUserManager.getUsers(true); 2456 for (PackageSetting ps : mSettings.mPackages.values()) { 2457 if (ps.pkg == null || !ps.isSystem()) continue; 2458 final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted() 2459 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 2460 for (UserInfo user : users) { 2461 if (ps.getInstalled(user.id)) { 2462 try { 2463 mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2464 ps.name, user.id, storageTarget); 2465 } catch (InstallerException e) { 2466 logCriticalInfo(Log.WARN, 2467 "Failed to migrate " + ps.name + ": " + e.getMessage()); 2468 } 2469 // We may have just shuffled around app data 2470 // directories, so prepare it one more time 2471 prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id, 2472 storageFlags, ps.pkg, false); 2473 } 2474 } 2475 } 2476 } 2477 2478 // If this is first boot after an OTA, and a normal boot, then 2479 // we need to clear code cache directories. 2480 if (mIsUpgrade && !onlyCore) { 2481 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2482 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2483 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2484 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2485 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2486 } 2487 } 2488 ver.fingerprint = Build.FINGERPRINT; 2489 } 2490 2491 checkDefaultBrowser(); 2492 2493 // clear only after permissions and other defaults have been updated 2494 mExistingSystemPackages.clear(); 2495 mPromoteSystemApps = false; 2496 2497 // All the changes are done during package scanning. 2498 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2499 2500 // can downgrade to reader 2501 mSettings.writeLPr(); 2502 2503 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2504 SystemClock.uptimeMillis()); 2505 2506 if (!mOnlyCore) { 2507 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2508 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2509 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2510 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2511 mIntentFilterVerifierComponent); 2512 } else { 2513 mRequiredVerifierPackage = null; 2514 mRequiredInstallerPackage = null; 2515 mIntentFilterVerifierComponent = null; 2516 mIntentFilterVerifier = null; 2517 } 2518 2519 mInstallerService = new PackageInstallerService(context, this); 2520 2521 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2522 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2523 // both the installer and resolver must be present to enable ephemeral 2524 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2525 if (DEBUG_EPHEMERAL) { 2526 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2527 + " installer:" + ephemeralInstallerComponent); 2528 } 2529 mEphemeralResolverComponent = ephemeralResolverComponent; 2530 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2531 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2532 mEphemeralResolverConnection = 2533 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2534 } else { 2535 if (DEBUG_EPHEMERAL) { 2536 final String missingComponent = 2537 (ephemeralResolverComponent == null) 2538 ? (ephemeralInstallerComponent == null) 2539 ? "resolver and installer" 2540 : "resolver" 2541 : "installer"; 2542 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2543 } 2544 mEphemeralResolverComponent = null; 2545 mEphemeralInstallerComponent = null; 2546 mEphemeralResolverConnection = null; 2547 } 2548 2549 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2550 } // synchronized (mPackages) 2551 } // synchronized (mInstallLock) 2552 2553 // Now after opening every single application zip, make sure they 2554 // are all flushed. Not really needed, but keeps things nice and 2555 // tidy. 2556 Runtime.getRuntime().gc(); 2557 2558 // The initial scanning above does many calls into installd while 2559 // holding the mPackages lock, but we're mostly interested in yelling 2560 // once we have a booted system. 2561 mInstaller.setWarnIfHeld(mPackages); 2562 2563 // Expose private service for system components to use. 2564 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2565 } 2566 2567 @Override 2568 public boolean isFirstBoot() { 2569 return !mRestoredSettings; 2570 } 2571 2572 @Override 2573 public boolean isOnlyCoreApps() { 2574 return mOnlyCore; 2575 } 2576 2577 @Override 2578 public boolean isUpgrade() { 2579 return mIsUpgrade; 2580 } 2581 2582 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2583 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2584 2585 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2586 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2587 if (matches.size() == 1) { 2588 return matches.get(0).getComponentInfo().packageName; 2589 } else { 2590 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2591 return null; 2592 } 2593 } 2594 2595 private @NonNull String getRequiredInstallerLPr() { 2596 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2597 intent.addCategory(Intent.CATEGORY_DEFAULT); 2598 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2599 2600 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2601 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2602 if (matches.size() == 1) { 2603 return matches.get(0).getComponentInfo().packageName; 2604 } else { 2605 throw new RuntimeException("There must be exactly one installer; found " + matches); 2606 } 2607 } 2608 2609 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2610 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2611 2612 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2613 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2614 ResolveInfo best = null; 2615 final int N = matches.size(); 2616 for (int i = 0; i < N; i++) { 2617 final ResolveInfo cur = matches.get(i); 2618 final String packageName = cur.getComponentInfo().packageName; 2619 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2620 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2621 continue; 2622 } 2623 2624 if (best == null || cur.priority > best.priority) { 2625 best = cur; 2626 } 2627 } 2628 2629 if (best != null) { 2630 return best.getComponentInfo().getComponentName(); 2631 } else { 2632 throw new RuntimeException("There must be at least one intent filter verifier"); 2633 } 2634 } 2635 2636 private @Nullable ComponentName getEphemeralResolverLPr() { 2637 final String[] packageArray = 2638 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2639 if (packageArray.length == 0) { 2640 if (DEBUG_EPHEMERAL) { 2641 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2642 } 2643 return null; 2644 } 2645 2646 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2647 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2648 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2649 2650 final int N = resolvers.size(); 2651 if (N == 0) { 2652 if (DEBUG_EPHEMERAL) { 2653 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2654 } 2655 return null; 2656 } 2657 2658 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2659 for (int i = 0; i < N; i++) { 2660 final ResolveInfo info = resolvers.get(i); 2661 2662 if (info.serviceInfo == null) { 2663 continue; 2664 } 2665 2666 final String packageName = info.serviceInfo.packageName; 2667 if (!possiblePackages.contains(packageName)) { 2668 if (DEBUG_EPHEMERAL) { 2669 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2670 + " pkg: " + packageName + ", info:" + info); 2671 } 2672 continue; 2673 } 2674 2675 if (DEBUG_EPHEMERAL) { 2676 Slog.v(TAG, "Ephemeral resolver found;" 2677 + " pkg: " + packageName + ", info:" + info); 2678 } 2679 return new ComponentName(packageName, info.serviceInfo.name); 2680 } 2681 if (DEBUG_EPHEMERAL) { 2682 Slog.v(TAG, "Ephemeral resolver NOT found"); 2683 } 2684 return null; 2685 } 2686 2687 private @Nullable ComponentName getEphemeralInstallerLPr() { 2688 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2689 intent.addCategory(Intent.CATEGORY_DEFAULT); 2690 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2691 2692 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2693 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2694 if (matches.size() == 0) { 2695 return null; 2696 } else if (matches.size() == 1) { 2697 return matches.get(0).getComponentInfo().getComponentName(); 2698 } else { 2699 throw new RuntimeException( 2700 "There must be at most one ephemeral installer; found " + matches); 2701 } 2702 } 2703 2704 private void primeDomainVerificationsLPw(int userId) { 2705 if (DEBUG_DOMAIN_VERIFICATION) { 2706 Slog.d(TAG, "Priming domain verifications in user " + userId); 2707 } 2708 2709 SystemConfig systemConfig = SystemConfig.getInstance(); 2710 ArraySet<String> packages = systemConfig.getLinkedApps(); 2711 ArraySet<String> domains = new ArraySet<String>(); 2712 2713 for (String packageName : packages) { 2714 PackageParser.Package pkg = mPackages.get(packageName); 2715 if (pkg != null) { 2716 if (!pkg.isSystemApp()) { 2717 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2718 continue; 2719 } 2720 2721 domains.clear(); 2722 for (PackageParser.Activity a : pkg.activities) { 2723 for (ActivityIntentInfo filter : a.intents) { 2724 if (hasValidDomains(filter)) { 2725 domains.addAll(filter.getHostsList()); 2726 } 2727 } 2728 } 2729 2730 if (domains.size() > 0) { 2731 if (DEBUG_DOMAIN_VERIFICATION) { 2732 Slog.v(TAG, " + " + packageName); 2733 } 2734 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2735 // state w.r.t. the formal app-linkage "no verification attempted" state; 2736 // and then 'always' in the per-user state actually used for intent resolution. 2737 final IntentFilterVerificationInfo ivi; 2738 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2739 new ArrayList<String>(domains)); 2740 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2741 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2742 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2743 } else { 2744 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2745 + "' does not handle web links"); 2746 } 2747 } else { 2748 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2749 } 2750 } 2751 2752 scheduleWritePackageRestrictionsLocked(userId); 2753 scheduleWriteSettingsLocked(); 2754 } 2755 2756 private void applyFactoryDefaultBrowserLPw(int userId) { 2757 // The default browser app's package name is stored in a string resource, 2758 // with a product-specific overlay used for vendor customization. 2759 String browserPkg = mContext.getResources().getString( 2760 com.android.internal.R.string.default_browser); 2761 if (!TextUtils.isEmpty(browserPkg)) { 2762 // non-empty string => required to be a known package 2763 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2764 if (ps == null) { 2765 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2766 browserPkg = null; 2767 } else { 2768 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2769 } 2770 } 2771 2772 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2773 // default. If there's more than one, just leave everything alone. 2774 if (browserPkg == null) { 2775 calculateDefaultBrowserLPw(userId); 2776 } 2777 } 2778 2779 private void calculateDefaultBrowserLPw(int userId) { 2780 List<String> allBrowsers = resolveAllBrowserApps(userId); 2781 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2782 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2783 } 2784 2785 private List<String> resolveAllBrowserApps(int userId) { 2786 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2787 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2788 PackageManager.MATCH_ALL, userId); 2789 2790 final int count = list.size(); 2791 List<String> result = new ArrayList<String>(count); 2792 for (int i=0; i<count; i++) { 2793 ResolveInfo info = list.get(i); 2794 if (info.activityInfo == null 2795 || !info.handleAllWebDataURI 2796 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2797 || result.contains(info.activityInfo.packageName)) { 2798 continue; 2799 } 2800 result.add(info.activityInfo.packageName); 2801 } 2802 2803 return result; 2804 } 2805 2806 private boolean packageIsBrowser(String packageName, int userId) { 2807 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2808 PackageManager.MATCH_ALL, userId); 2809 final int N = list.size(); 2810 for (int i = 0; i < N; i++) { 2811 ResolveInfo info = list.get(i); 2812 if (packageName.equals(info.activityInfo.packageName)) { 2813 return true; 2814 } 2815 } 2816 return false; 2817 } 2818 2819 private void checkDefaultBrowser() { 2820 final int myUserId = UserHandle.myUserId(); 2821 final String packageName = getDefaultBrowserPackageName(myUserId); 2822 if (packageName != null) { 2823 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2824 if (info == null) { 2825 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2826 synchronized (mPackages) { 2827 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2828 } 2829 } 2830 } 2831 } 2832 2833 @Override 2834 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2835 throws RemoteException { 2836 try { 2837 return super.onTransact(code, data, reply, flags); 2838 } catch (RuntimeException e) { 2839 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2840 Slog.wtf(TAG, "Package Manager Crash", e); 2841 } 2842 throw e; 2843 } 2844 } 2845 2846 void cleanupInstallFailedPackage(PackageSetting ps) { 2847 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2848 2849 removeDataDirsLI(ps.volumeUuid, ps.name); 2850 if (ps.codePath != null) { 2851 removeCodePathLI(ps.codePath); 2852 } 2853 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2854 if (ps.resourcePath.isDirectory()) { 2855 FileUtils.deleteContents(ps.resourcePath); 2856 } 2857 ps.resourcePath.delete(); 2858 } 2859 mSettings.removePackageLPw(ps.name); 2860 } 2861 2862 static int[] appendInts(int[] cur, int[] add) { 2863 if (add == null) return cur; 2864 if (cur == null) return add; 2865 final int N = add.length; 2866 for (int i=0; i<N; i++) { 2867 cur = appendInt(cur, add[i]); 2868 } 2869 return cur; 2870 } 2871 2872 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2873 if (!sUserManager.exists(userId)) return null; 2874 final PackageSetting ps = (PackageSetting) p.mExtras; 2875 if (ps == null) { 2876 return null; 2877 } 2878 2879 final PermissionsState permissionsState = ps.getPermissionsState(); 2880 2881 final int[] gids = permissionsState.computeGids(userId); 2882 final Set<String> permissions = permissionsState.getPermissions(userId); 2883 final PackageUserState state = ps.readUserState(userId); 2884 2885 return PackageParser.generatePackageInfo(p, gids, flags, 2886 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2887 } 2888 2889 @Override 2890 public void checkPackageStartable(String packageName, int userId) { 2891 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2892 2893 synchronized (mPackages) { 2894 final PackageSetting ps = mSettings.mPackages.get(packageName); 2895 if (ps == null) { 2896 throw new SecurityException("Package " + packageName + " was not found!"); 2897 } 2898 2899 if (mSafeMode && !ps.isSystem()) { 2900 throw new SecurityException("Package " + packageName + " not a system app!"); 2901 } 2902 2903 if (ps.frozen) { 2904 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2905 } 2906 2907 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2908 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2909 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2910 } 2911 } 2912 } 2913 2914 @Override 2915 public boolean isPackageAvailable(String packageName, int userId) { 2916 if (!sUserManager.exists(userId)) return false; 2917 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2918 synchronized (mPackages) { 2919 PackageParser.Package p = mPackages.get(packageName); 2920 if (p != null) { 2921 final PackageSetting ps = (PackageSetting) p.mExtras; 2922 if (ps != null) { 2923 final PackageUserState state = ps.readUserState(userId); 2924 if (state != null) { 2925 return PackageParser.isAvailable(state); 2926 } 2927 } 2928 } 2929 } 2930 return false; 2931 } 2932 2933 @Override 2934 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2935 if (!sUserManager.exists(userId)) return null; 2936 flags = updateFlagsForPackage(flags, userId, packageName); 2937 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2938 // reader 2939 synchronized (mPackages) { 2940 PackageParser.Package p = mPackages.get(packageName); 2941 if (DEBUG_PACKAGE_INFO) 2942 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2943 if (p != null) { 2944 return generatePackageInfo(p, flags, userId); 2945 } 2946 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2947 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2948 } 2949 } 2950 return null; 2951 } 2952 2953 @Override 2954 public String[] currentToCanonicalPackageNames(String[] names) { 2955 String[] out = new String[names.length]; 2956 // reader 2957 synchronized (mPackages) { 2958 for (int i=names.length-1; i>=0; i--) { 2959 PackageSetting ps = mSettings.mPackages.get(names[i]); 2960 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2961 } 2962 } 2963 return out; 2964 } 2965 2966 @Override 2967 public String[] canonicalToCurrentPackageNames(String[] names) { 2968 String[] out = new String[names.length]; 2969 // reader 2970 synchronized (mPackages) { 2971 for (int i=names.length-1; i>=0; i--) { 2972 String cur = mSettings.mRenamedPackages.get(names[i]); 2973 out[i] = cur != null ? cur : names[i]; 2974 } 2975 } 2976 return out; 2977 } 2978 2979 @Override 2980 public int getPackageUid(String packageName, int flags, int userId) { 2981 if (!sUserManager.exists(userId)) return -1; 2982 flags = updateFlagsForPackage(flags, userId, packageName); 2983 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2984 2985 // reader 2986 synchronized (mPackages) { 2987 final PackageParser.Package p = mPackages.get(packageName); 2988 if (p != null && p.isMatch(flags)) { 2989 return UserHandle.getUid(userId, p.applicationInfo.uid); 2990 } 2991 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2992 final PackageSetting ps = mSettings.mPackages.get(packageName); 2993 if (ps != null && ps.isMatch(flags)) { 2994 return UserHandle.getUid(userId, ps.appId); 2995 } 2996 } 2997 } 2998 2999 return -1; 3000 } 3001 3002 @Override 3003 public int[] getPackageGids(String packageName, int flags, int userId) { 3004 if (!sUserManager.exists(userId)) return null; 3005 flags = updateFlagsForPackage(flags, userId, packageName); 3006 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3007 "getPackageGids"); 3008 3009 // reader 3010 synchronized (mPackages) { 3011 final PackageParser.Package p = mPackages.get(packageName); 3012 if (p != null && p.isMatch(flags)) { 3013 PackageSetting ps = (PackageSetting) p.mExtras; 3014 return ps.getPermissionsState().computeGids(userId); 3015 } 3016 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3017 final PackageSetting ps = mSettings.mPackages.get(packageName); 3018 if (ps != null && ps.isMatch(flags)) { 3019 return ps.getPermissionsState().computeGids(userId); 3020 } 3021 } 3022 } 3023 3024 return null; 3025 } 3026 3027 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3028 if (bp.perm != null) { 3029 return PackageParser.generatePermissionInfo(bp.perm, flags); 3030 } 3031 PermissionInfo pi = new PermissionInfo(); 3032 pi.name = bp.name; 3033 pi.packageName = bp.sourcePackage; 3034 pi.nonLocalizedLabel = bp.name; 3035 pi.protectionLevel = bp.protectionLevel; 3036 return pi; 3037 } 3038 3039 @Override 3040 public PermissionInfo getPermissionInfo(String name, int flags) { 3041 // reader 3042 synchronized (mPackages) { 3043 final BasePermission p = mSettings.mPermissions.get(name); 3044 if (p != null) { 3045 return generatePermissionInfo(p, flags); 3046 } 3047 return null; 3048 } 3049 } 3050 3051 @Override 3052 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 3053 // reader 3054 synchronized (mPackages) { 3055 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3056 for (BasePermission p : mSettings.mPermissions.values()) { 3057 if (group == null) { 3058 if (p.perm == null || p.perm.info.group == null) { 3059 out.add(generatePermissionInfo(p, flags)); 3060 } 3061 } else { 3062 if (p.perm != null && group.equals(p.perm.info.group)) { 3063 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3064 } 3065 } 3066 } 3067 3068 if (out.size() > 0) { 3069 return out; 3070 } 3071 return mPermissionGroups.containsKey(group) ? out : null; 3072 } 3073 } 3074 3075 @Override 3076 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3077 // reader 3078 synchronized (mPackages) { 3079 return PackageParser.generatePermissionGroupInfo( 3080 mPermissionGroups.get(name), flags); 3081 } 3082 } 3083 3084 @Override 3085 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3086 // reader 3087 synchronized (mPackages) { 3088 final int N = mPermissionGroups.size(); 3089 ArrayList<PermissionGroupInfo> out 3090 = new ArrayList<PermissionGroupInfo>(N); 3091 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3092 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3093 } 3094 return out; 3095 } 3096 } 3097 3098 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3099 int userId) { 3100 if (!sUserManager.exists(userId)) return null; 3101 PackageSetting ps = mSettings.mPackages.get(packageName); 3102 if (ps != null) { 3103 if (ps.pkg == null) { 3104 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3105 flags, userId); 3106 if (pInfo != null) { 3107 return pInfo.applicationInfo; 3108 } 3109 return null; 3110 } 3111 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3112 ps.readUserState(userId), userId); 3113 } 3114 return null; 3115 } 3116 3117 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3118 int userId) { 3119 if (!sUserManager.exists(userId)) return null; 3120 PackageSetting ps = mSettings.mPackages.get(packageName); 3121 if (ps != null) { 3122 PackageParser.Package pkg = ps.pkg; 3123 if (pkg == null) { 3124 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3125 return null; 3126 } 3127 // Only data remains, so we aren't worried about code paths 3128 pkg = new PackageParser.Package(packageName); 3129 pkg.applicationInfo.packageName = packageName; 3130 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3131 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3132 pkg.applicationInfo.uid = ps.appId; 3133 pkg.applicationInfo.initForUser(userId); 3134 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3135 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3136 } 3137 return generatePackageInfo(pkg, flags, userId); 3138 } 3139 return null; 3140 } 3141 3142 @Override 3143 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3144 if (!sUserManager.exists(userId)) return null; 3145 flags = updateFlagsForApplication(flags, userId, packageName); 3146 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3147 // writer 3148 synchronized (mPackages) { 3149 PackageParser.Package p = mPackages.get(packageName); 3150 if (DEBUG_PACKAGE_INFO) Log.v( 3151 TAG, "getApplicationInfo " + packageName 3152 + ": " + p); 3153 if (p != null) { 3154 PackageSetting ps = mSettings.mPackages.get(packageName); 3155 if (ps == null) return null; 3156 // Note: isEnabledLP() does not apply here - always return info 3157 return PackageParser.generateApplicationInfo( 3158 p, flags, ps.readUserState(userId), userId); 3159 } 3160 if ("android".equals(packageName)||"system".equals(packageName)) { 3161 return mAndroidApplication; 3162 } 3163 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3164 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3165 } 3166 } 3167 return null; 3168 } 3169 3170 @Override 3171 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3172 final IPackageDataObserver observer) { 3173 mContext.enforceCallingOrSelfPermission( 3174 android.Manifest.permission.CLEAR_APP_CACHE, null); 3175 // Queue up an async operation since clearing cache may take a little while. 3176 mHandler.post(new Runnable() { 3177 public void run() { 3178 mHandler.removeCallbacks(this); 3179 boolean success = true; 3180 synchronized (mInstallLock) { 3181 try { 3182 mInstaller.freeCache(volumeUuid, freeStorageSize); 3183 } catch (InstallerException e) { 3184 Slog.w(TAG, "Couldn't clear application caches: " + e); 3185 success = false; 3186 } 3187 } 3188 if (observer != null) { 3189 try { 3190 observer.onRemoveCompleted(null, success); 3191 } catch (RemoteException e) { 3192 Slog.w(TAG, "RemoveException when invoking call back"); 3193 } 3194 } 3195 } 3196 }); 3197 } 3198 3199 @Override 3200 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3201 final IntentSender pi) { 3202 mContext.enforceCallingOrSelfPermission( 3203 android.Manifest.permission.CLEAR_APP_CACHE, null); 3204 // Queue up an async operation since clearing cache may take a little while. 3205 mHandler.post(new Runnable() { 3206 public void run() { 3207 mHandler.removeCallbacks(this); 3208 boolean success = true; 3209 synchronized (mInstallLock) { 3210 try { 3211 mInstaller.freeCache(volumeUuid, freeStorageSize); 3212 } catch (InstallerException e) { 3213 Slog.w(TAG, "Couldn't clear application caches: " + e); 3214 success = false; 3215 } 3216 } 3217 if(pi != null) { 3218 try { 3219 // Callback via pending intent 3220 int code = success ? 1 : 0; 3221 pi.sendIntent(null, code, null, 3222 null, null); 3223 } catch (SendIntentException e1) { 3224 Slog.i(TAG, "Failed to send pending intent"); 3225 } 3226 } 3227 } 3228 }); 3229 } 3230 3231 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3232 synchronized (mInstallLock) { 3233 try { 3234 mInstaller.freeCache(volumeUuid, freeStorageSize); 3235 } catch (InstallerException e) { 3236 throw new IOException("Failed to free enough space", e); 3237 } 3238 } 3239 } 3240 3241 /** 3242 * Return if the user key is currently unlocked. 3243 */ 3244 private boolean isUserKeyUnlocked(int userId) { 3245 if (StorageManager.isFileBasedEncryptionEnabled()) { 3246 final IMountService mount = IMountService.Stub 3247 .asInterface(ServiceManager.getService("mount")); 3248 if (mount == null) { 3249 Slog.w(TAG, "Early during boot, assuming locked"); 3250 return false; 3251 } 3252 final long token = Binder.clearCallingIdentity(); 3253 try { 3254 return mount.isUserKeyUnlocked(userId); 3255 } catch (RemoteException e) { 3256 throw e.rethrowAsRuntimeException(); 3257 } finally { 3258 Binder.restoreCallingIdentity(token); 3259 } 3260 } else { 3261 return true; 3262 } 3263 } 3264 3265 /** 3266 * Update given flags based on encryption status of current user. 3267 */ 3268 private int updateFlags(int flags, int userId) { 3269 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3270 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3271 // Caller expressed an explicit opinion about what encryption 3272 // aware/unaware components they want to see, so fall through and 3273 // give them what they want 3274 } else { 3275 // Caller expressed no opinion, so match based on user state 3276 if (isUserKeyUnlocked(userId)) { 3277 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3278 } else { 3279 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3280 } 3281 } 3282 return flags; 3283 } 3284 3285 /** 3286 * Update given flags when being used to request {@link PackageInfo}. 3287 */ 3288 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3289 boolean triaged = true; 3290 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3291 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3292 // Caller is asking for component details, so they'd better be 3293 // asking for specific encryption matching behavior, or be triaged 3294 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3295 | PackageManager.MATCH_ENCRYPTION_AWARE 3296 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3297 triaged = false; 3298 } 3299 } 3300 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3301 | PackageManager.MATCH_SYSTEM_ONLY 3302 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3303 triaged = false; 3304 } 3305 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3306 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3307 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3308 } 3309 return updateFlags(flags, userId); 3310 } 3311 3312 /** 3313 * Update given flags when being used to request {@link ApplicationInfo}. 3314 */ 3315 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3316 return updateFlagsForPackage(flags, userId, cookie); 3317 } 3318 3319 /** 3320 * Update given flags when being used to request {@link ComponentInfo}. 3321 */ 3322 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3323 if (cookie instanceof Intent) { 3324 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3325 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3326 } 3327 } 3328 3329 boolean triaged = true; 3330 // Caller is asking for component details, so they'd better be 3331 // asking for specific encryption matching behavior, or be triaged 3332 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3333 | PackageManager.MATCH_ENCRYPTION_AWARE 3334 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3335 triaged = false; 3336 } 3337 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3338 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3339 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3340 } 3341 3342 // Safe mode means we shouldn't match any third-party components 3343 if (mSafeMode) { 3344 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3345 } 3346 3347 return updateFlags(flags, userId); 3348 } 3349 3350 /** 3351 * Update given flags when being used to request {@link ResolveInfo}. 3352 */ 3353 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3354 return updateFlagsForComponent(flags, userId, cookie); 3355 } 3356 3357 @Override 3358 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3359 if (!sUserManager.exists(userId)) return null; 3360 flags = updateFlagsForComponent(flags, userId, component); 3361 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3362 synchronized (mPackages) { 3363 PackageParser.Activity a = mActivities.mActivities.get(component); 3364 3365 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3366 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3367 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3368 if (ps == null) return null; 3369 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3370 userId); 3371 } 3372 if (mResolveComponentName.equals(component)) { 3373 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3374 new PackageUserState(), userId); 3375 } 3376 } 3377 return null; 3378 } 3379 3380 @Override 3381 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3382 String resolvedType) { 3383 synchronized (mPackages) { 3384 if (component.equals(mResolveComponentName)) { 3385 // The resolver supports EVERYTHING! 3386 return true; 3387 } 3388 PackageParser.Activity a = mActivities.mActivities.get(component); 3389 if (a == null) { 3390 return false; 3391 } 3392 for (int i=0; i<a.intents.size(); i++) { 3393 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3394 intent.getData(), intent.getCategories(), TAG) >= 0) { 3395 return true; 3396 } 3397 } 3398 return false; 3399 } 3400 } 3401 3402 @Override 3403 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3404 if (!sUserManager.exists(userId)) return null; 3405 flags = updateFlagsForComponent(flags, userId, component); 3406 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3407 synchronized (mPackages) { 3408 PackageParser.Activity a = mReceivers.mActivities.get(component); 3409 if (DEBUG_PACKAGE_INFO) Log.v( 3410 TAG, "getReceiverInfo " + component + ": " + a); 3411 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3412 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3413 if (ps == null) return null; 3414 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3415 userId); 3416 } 3417 } 3418 return null; 3419 } 3420 3421 @Override 3422 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3423 if (!sUserManager.exists(userId)) return null; 3424 flags = updateFlagsForComponent(flags, userId, component); 3425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3426 synchronized (mPackages) { 3427 PackageParser.Service s = mServices.mServices.get(component); 3428 if (DEBUG_PACKAGE_INFO) Log.v( 3429 TAG, "getServiceInfo " + component + ": " + s); 3430 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3431 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3432 if (ps == null) return null; 3433 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3434 userId); 3435 } 3436 } 3437 return null; 3438 } 3439 3440 @Override 3441 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3442 if (!sUserManager.exists(userId)) return null; 3443 flags = updateFlagsForComponent(flags, userId, component); 3444 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3445 synchronized (mPackages) { 3446 PackageParser.Provider p = mProviders.mProviders.get(component); 3447 if (DEBUG_PACKAGE_INFO) Log.v( 3448 TAG, "getProviderInfo " + component + ": " + p); 3449 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3450 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3451 if (ps == null) return null; 3452 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3453 userId); 3454 } 3455 } 3456 return null; 3457 } 3458 3459 @Override 3460 public String[] getSystemSharedLibraryNames() { 3461 Set<String> libSet; 3462 synchronized (mPackages) { 3463 libSet = mSharedLibraries.keySet(); 3464 int size = libSet.size(); 3465 if (size > 0) { 3466 String[] libs = new String[size]; 3467 libSet.toArray(libs); 3468 return libs; 3469 } 3470 } 3471 return null; 3472 } 3473 3474 @Override 3475 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3476 synchronized (mPackages) { 3477 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3478 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3479 if (libraryEntry != null) { 3480 return libraryEntry.apk; 3481 } 3482 } 3483 return null; 3484 } 3485 3486 @Override 3487 public FeatureInfo[] getSystemAvailableFeatures() { 3488 Collection<FeatureInfo> featSet; 3489 synchronized (mPackages) { 3490 featSet = mAvailableFeatures.values(); 3491 int size = featSet.size(); 3492 if (size > 0) { 3493 FeatureInfo[] features = new FeatureInfo[size+1]; 3494 featSet.toArray(features); 3495 FeatureInfo fi = new FeatureInfo(); 3496 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3497 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3498 features[size] = fi; 3499 return features; 3500 } 3501 } 3502 return null; 3503 } 3504 3505 @Override 3506 public boolean hasSystemFeature(String name) { 3507 synchronized (mPackages) { 3508 return mAvailableFeatures.containsKey(name); 3509 } 3510 } 3511 3512 @Override 3513 public int checkPermission(String permName, String pkgName, int userId) { 3514 if (!sUserManager.exists(userId)) { 3515 return PackageManager.PERMISSION_DENIED; 3516 } 3517 3518 synchronized (mPackages) { 3519 final PackageParser.Package p = mPackages.get(pkgName); 3520 if (p != null && p.mExtras != null) { 3521 final PackageSetting ps = (PackageSetting) p.mExtras; 3522 final PermissionsState permissionsState = ps.getPermissionsState(); 3523 if (permissionsState.hasPermission(permName, userId)) { 3524 return PackageManager.PERMISSION_GRANTED; 3525 } 3526 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3527 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3528 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3529 return PackageManager.PERMISSION_GRANTED; 3530 } 3531 } 3532 } 3533 3534 return PackageManager.PERMISSION_DENIED; 3535 } 3536 3537 @Override 3538 public int checkUidPermission(String permName, int uid) { 3539 final int userId = UserHandle.getUserId(uid); 3540 3541 if (!sUserManager.exists(userId)) { 3542 return PackageManager.PERMISSION_DENIED; 3543 } 3544 3545 synchronized (mPackages) { 3546 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3547 if (obj != null) { 3548 final SettingBase ps = (SettingBase) obj; 3549 final PermissionsState permissionsState = ps.getPermissionsState(); 3550 if (permissionsState.hasPermission(permName, userId)) { 3551 return PackageManager.PERMISSION_GRANTED; 3552 } 3553 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3554 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3555 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3556 return PackageManager.PERMISSION_GRANTED; 3557 } 3558 } else { 3559 ArraySet<String> perms = mSystemPermissions.get(uid); 3560 if (perms != null) { 3561 if (perms.contains(permName)) { 3562 return PackageManager.PERMISSION_GRANTED; 3563 } 3564 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3565 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3566 return PackageManager.PERMISSION_GRANTED; 3567 } 3568 } 3569 } 3570 } 3571 3572 return PackageManager.PERMISSION_DENIED; 3573 } 3574 3575 @Override 3576 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3577 if (UserHandle.getCallingUserId() != userId) { 3578 mContext.enforceCallingPermission( 3579 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3580 "isPermissionRevokedByPolicy for user " + userId); 3581 } 3582 3583 if (checkPermission(permission, packageName, userId) 3584 == PackageManager.PERMISSION_GRANTED) { 3585 return false; 3586 } 3587 3588 final long identity = Binder.clearCallingIdentity(); 3589 try { 3590 final int flags = getPermissionFlags(permission, packageName, userId); 3591 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3592 } finally { 3593 Binder.restoreCallingIdentity(identity); 3594 } 3595 } 3596 3597 @Override 3598 public String getPermissionControllerPackageName() { 3599 synchronized (mPackages) { 3600 return mRequiredInstallerPackage; 3601 } 3602 } 3603 3604 /** 3605 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3606 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3607 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3608 * @param message the message to log on security exception 3609 */ 3610 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3611 boolean checkShell, String message) { 3612 if (userId < 0) { 3613 throw new IllegalArgumentException("Invalid userId " + userId); 3614 } 3615 if (checkShell) { 3616 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3617 } 3618 if (userId == UserHandle.getUserId(callingUid)) return; 3619 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3620 if (requireFullPermission) { 3621 mContext.enforceCallingOrSelfPermission( 3622 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3623 } else { 3624 try { 3625 mContext.enforceCallingOrSelfPermission( 3626 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3627 } catch (SecurityException se) { 3628 mContext.enforceCallingOrSelfPermission( 3629 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3630 } 3631 } 3632 } 3633 } 3634 3635 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3636 if (callingUid == Process.SHELL_UID) { 3637 if (userHandle >= 0 3638 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3639 throw new SecurityException("Shell does not have permission to access user " 3640 + userHandle); 3641 } else if (userHandle < 0) { 3642 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3643 + Debug.getCallers(3)); 3644 } 3645 } 3646 } 3647 3648 private BasePermission findPermissionTreeLP(String permName) { 3649 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3650 if (permName.startsWith(bp.name) && 3651 permName.length() > bp.name.length() && 3652 permName.charAt(bp.name.length()) == '.') { 3653 return bp; 3654 } 3655 } 3656 return null; 3657 } 3658 3659 private BasePermission checkPermissionTreeLP(String permName) { 3660 if (permName != null) { 3661 BasePermission bp = findPermissionTreeLP(permName); 3662 if (bp != null) { 3663 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3664 return bp; 3665 } 3666 throw new SecurityException("Calling uid " 3667 + Binder.getCallingUid() 3668 + " is not allowed to add to permission tree " 3669 + bp.name + " owned by uid " + bp.uid); 3670 } 3671 } 3672 throw new SecurityException("No permission tree found for " + permName); 3673 } 3674 3675 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3676 if (s1 == null) { 3677 return s2 == null; 3678 } 3679 if (s2 == null) { 3680 return false; 3681 } 3682 if (s1.getClass() != s2.getClass()) { 3683 return false; 3684 } 3685 return s1.equals(s2); 3686 } 3687 3688 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3689 if (pi1.icon != pi2.icon) return false; 3690 if (pi1.logo != pi2.logo) return false; 3691 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3692 if (!compareStrings(pi1.name, pi2.name)) return false; 3693 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3694 // We'll take care of setting this one. 3695 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3696 // These are not currently stored in settings. 3697 //if (!compareStrings(pi1.group, pi2.group)) return false; 3698 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3699 //if (pi1.labelRes != pi2.labelRes) return false; 3700 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3701 return true; 3702 } 3703 3704 int permissionInfoFootprint(PermissionInfo info) { 3705 int size = info.name.length(); 3706 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3707 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3708 return size; 3709 } 3710 3711 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3712 int size = 0; 3713 for (BasePermission perm : mSettings.mPermissions.values()) { 3714 if (perm.uid == tree.uid) { 3715 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3716 } 3717 } 3718 return size; 3719 } 3720 3721 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3722 // We calculate the max size of permissions defined by this uid and throw 3723 // if that plus the size of 'info' would exceed our stated maximum. 3724 if (tree.uid != Process.SYSTEM_UID) { 3725 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3726 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3727 throw new SecurityException("Permission tree size cap exceeded"); 3728 } 3729 } 3730 } 3731 3732 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3733 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3734 throw new SecurityException("Label must be specified in permission"); 3735 } 3736 BasePermission tree = checkPermissionTreeLP(info.name); 3737 BasePermission bp = mSettings.mPermissions.get(info.name); 3738 boolean added = bp == null; 3739 boolean changed = true; 3740 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3741 if (added) { 3742 enforcePermissionCapLocked(info, tree); 3743 bp = new BasePermission(info.name, tree.sourcePackage, 3744 BasePermission.TYPE_DYNAMIC); 3745 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3746 throw new SecurityException( 3747 "Not allowed to modify non-dynamic permission " 3748 + info.name); 3749 } else { 3750 if (bp.protectionLevel == fixedLevel 3751 && bp.perm.owner.equals(tree.perm.owner) 3752 && bp.uid == tree.uid 3753 && comparePermissionInfos(bp.perm.info, info)) { 3754 changed = false; 3755 } 3756 } 3757 bp.protectionLevel = fixedLevel; 3758 info = new PermissionInfo(info); 3759 info.protectionLevel = fixedLevel; 3760 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3761 bp.perm.info.packageName = tree.perm.info.packageName; 3762 bp.uid = tree.uid; 3763 if (added) { 3764 mSettings.mPermissions.put(info.name, bp); 3765 } 3766 if (changed) { 3767 if (!async) { 3768 mSettings.writeLPr(); 3769 } else { 3770 scheduleWriteSettingsLocked(); 3771 } 3772 } 3773 return added; 3774 } 3775 3776 @Override 3777 public boolean addPermission(PermissionInfo info) { 3778 synchronized (mPackages) { 3779 return addPermissionLocked(info, false); 3780 } 3781 } 3782 3783 @Override 3784 public boolean addPermissionAsync(PermissionInfo info) { 3785 synchronized (mPackages) { 3786 return addPermissionLocked(info, true); 3787 } 3788 } 3789 3790 @Override 3791 public void removePermission(String name) { 3792 synchronized (mPackages) { 3793 checkPermissionTreeLP(name); 3794 BasePermission bp = mSettings.mPermissions.get(name); 3795 if (bp != null) { 3796 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3797 throw new SecurityException( 3798 "Not allowed to modify non-dynamic permission " 3799 + name); 3800 } 3801 mSettings.mPermissions.remove(name); 3802 mSettings.writeLPr(); 3803 } 3804 } 3805 } 3806 3807 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3808 BasePermission bp) { 3809 int index = pkg.requestedPermissions.indexOf(bp.name); 3810 if (index == -1) { 3811 throw new SecurityException("Package " + pkg.packageName 3812 + " has not requested permission " + bp.name); 3813 } 3814 if (!bp.isRuntime() && !bp.isDevelopment()) { 3815 throw new SecurityException("Permission " + bp.name 3816 + " is not a changeable permission type"); 3817 } 3818 } 3819 3820 @Override 3821 public void grantRuntimePermission(String packageName, String name, final int userId) { 3822 if (!sUserManager.exists(userId)) { 3823 Log.e(TAG, "No such user:" + userId); 3824 return; 3825 } 3826 3827 mContext.enforceCallingOrSelfPermission( 3828 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3829 "grantRuntimePermission"); 3830 3831 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3832 "grantRuntimePermission"); 3833 3834 final int uid; 3835 final SettingBase sb; 3836 3837 synchronized (mPackages) { 3838 final PackageParser.Package pkg = mPackages.get(packageName); 3839 if (pkg == null) { 3840 throw new IllegalArgumentException("Unknown package: " + packageName); 3841 } 3842 3843 final BasePermission bp = mSettings.mPermissions.get(name); 3844 if (bp == null) { 3845 throw new IllegalArgumentException("Unknown permission: " + name); 3846 } 3847 3848 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3849 3850 // If a permission review is required for legacy apps we represent 3851 // their permissions as always granted runtime ones since we need 3852 // to keep the review required permission flag per user while an 3853 // install permission's state is shared across all users. 3854 if (Build.PERMISSIONS_REVIEW_REQUIRED 3855 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3856 && bp.isRuntime()) { 3857 return; 3858 } 3859 3860 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3861 sb = (SettingBase) pkg.mExtras; 3862 if (sb == null) { 3863 throw new IllegalArgumentException("Unknown package: " + packageName); 3864 } 3865 3866 final PermissionsState permissionsState = sb.getPermissionsState(); 3867 3868 final int flags = permissionsState.getPermissionFlags(name, userId); 3869 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3870 throw new SecurityException("Cannot grant system fixed permission " 3871 + name + " for package " + packageName); 3872 } 3873 3874 if (bp.isDevelopment()) { 3875 // Development permissions must be handled specially, since they are not 3876 // normal runtime permissions. For now they apply to all users. 3877 if (permissionsState.grantInstallPermission(bp) != 3878 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3879 scheduleWriteSettingsLocked(); 3880 } 3881 return; 3882 } 3883 3884 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3885 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3886 return; 3887 } 3888 3889 final int result = permissionsState.grantRuntimePermission(bp, userId); 3890 switch (result) { 3891 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3892 return; 3893 } 3894 3895 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3896 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3897 mHandler.post(new Runnable() { 3898 @Override 3899 public void run() { 3900 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3901 } 3902 }); 3903 } 3904 break; 3905 } 3906 3907 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3908 3909 // Not critical if that is lost - app has to request again. 3910 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3911 } 3912 3913 // Only need to do this if user is initialized. Otherwise it's a new user 3914 // and there are no processes running as the user yet and there's no need 3915 // to make an expensive call to remount processes for the changed permissions. 3916 if (READ_EXTERNAL_STORAGE.equals(name) 3917 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3918 final long token = Binder.clearCallingIdentity(); 3919 try { 3920 if (sUserManager.isInitialized(userId)) { 3921 MountServiceInternal mountServiceInternal = LocalServices.getService( 3922 MountServiceInternal.class); 3923 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3924 } 3925 } finally { 3926 Binder.restoreCallingIdentity(token); 3927 } 3928 } 3929 } 3930 3931 @Override 3932 public void revokeRuntimePermission(String packageName, String name, int userId) { 3933 if (!sUserManager.exists(userId)) { 3934 Log.e(TAG, "No such user:" + userId); 3935 return; 3936 } 3937 3938 mContext.enforceCallingOrSelfPermission( 3939 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3940 "revokeRuntimePermission"); 3941 3942 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3943 "revokeRuntimePermission"); 3944 3945 final int appId; 3946 3947 synchronized (mPackages) { 3948 final PackageParser.Package pkg = mPackages.get(packageName); 3949 if (pkg == null) { 3950 throw new IllegalArgumentException("Unknown package: " + packageName); 3951 } 3952 3953 final BasePermission bp = mSettings.mPermissions.get(name); 3954 if (bp == null) { 3955 throw new IllegalArgumentException("Unknown permission: " + name); 3956 } 3957 3958 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3959 3960 // If a permission review is required for legacy apps we represent 3961 // their permissions as always granted runtime ones since we need 3962 // to keep the review required permission flag per user while an 3963 // install permission's state is shared across all users. 3964 if (Build.PERMISSIONS_REVIEW_REQUIRED 3965 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3966 && bp.isRuntime()) { 3967 return; 3968 } 3969 3970 SettingBase sb = (SettingBase) pkg.mExtras; 3971 if (sb == null) { 3972 throw new IllegalArgumentException("Unknown package: " + packageName); 3973 } 3974 3975 final PermissionsState permissionsState = sb.getPermissionsState(); 3976 3977 final int flags = permissionsState.getPermissionFlags(name, userId); 3978 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3979 throw new SecurityException("Cannot revoke system fixed permission " 3980 + name + " for package " + packageName); 3981 } 3982 3983 if (bp.isDevelopment()) { 3984 // Development permissions must be handled specially, since they are not 3985 // normal runtime permissions. For now they apply to all users. 3986 if (permissionsState.revokeInstallPermission(bp) != 3987 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3988 scheduleWriteSettingsLocked(); 3989 } 3990 return; 3991 } 3992 3993 if (permissionsState.revokeRuntimePermission(bp, userId) == 3994 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3995 return; 3996 } 3997 3998 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3999 4000 // Critical, after this call app should never have the permission. 4001 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4002 4003 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4004 } 4005 4006 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4007 } 4008 4009 @Override 4010 public void resetRuntimePermissions() { 4011 mContext.enforceCallingOrSelfPermission( 4012 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4013 "revokeRuntimePermission"); 4014 4015 int callingUid = Binder.getCallingUid(); 4016 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4017 mContext.enforceCallingOrSelfPermission( 4018 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4019 "resetRuntimePermissions"); 4020 } 4021 4022 synchronized (mPackages) { 4023 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4024 for (int userId : UserManagerService.getInstance().getUserIds()) { 4025 final int packageCount = mPackages.size(); 4026 for (int i = 0; i < packageCount; i++) { 4027 PackageParser.Package pkg = mPackages.valueAt(i); 4028 if (!(pkg.mExtras instanceof PackageSetting)) { 4029 continue; 4030 } 4031 PackageSetting ps = (PackageSetting) pkg.mExtras; 4032 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4033 } 4034 } 4035 } 4036 } 4037 4038 @Override 4039 public int getPermissionFlags(String name, String packageName, int userId) { 4040 if (!sUserManager.exists(userId)) { 4041 return 0; 4042 } 4043 4044 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4045 4046 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4047 "getPermissionFlags"); 4048 4049 synchronized (mPackages) { 4050 final PackageParser.Package pkg = mPackages.get(packageName); 4051 if (pkg == null) { 4052 throw new IllegalArgumentException("Unknown package: " + packageName); 4053 } 4054 4055 final BasePermission bp = mSettings.mPermissions.get(name); 4056 if (bp == null) { 4057 throw new IllegalArgumentException("Unknown permission: " + name); 4058 } 4059 4060 SettingBase sb = (SettingBase) pkg.mExtras; 4061 if (sb == null) { 4062 throw new IllegalArgumentException("Unknown package: " + packageName); 4063 } 4064 4065 PermissionsState permissionsState = sb.getPermissionsState(); 4066 return permissionsState.getPermissionFlags(name, userId); 4067 } 4068 } 4069 4070 @Override 4071 public void updatePermissionFlags(String name, String packageName, int flagMask, 4072 int flagValues, int userId) { 4073 if (!sUserManager.exists(userId)) { 4074 return; 4075 } 4076 4077 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4078 4079 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4080 "updatePermissionFlags"); 4081 4082 // Only the system can change these flags and nothing else. 4083 if (getCallingUid() != Process.SYSTEM_UID) { 4084 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4085 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4086 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4087 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4088 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4089 } 4090 4091 synchronized (mPackages) { 4092 final PackageParser.Package pkg = mPackages.get(packageName); 4093 if (pkg == null) { 4094 throw new IllegalArgumentException("Unknown package: " + packageName); 4095 } 4096 4097 final BasePermission bp = mSettings.mPermissions.get(name); 4098 if (bp == null) { 4099 throw new IllegalArgumentException("Unknown permission: " + name); 4100 } 4101 4102 SettingBase sb = (SettingBase) pkg.mExtras; 4103 if (sb == null) { 4104 throw new IllegalArgumentException("Unknown package: " + packageName); 4105 } 4106 4107 PermissionsState permissionsState = sb.getPermissionsState(); 4108 4109 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4110 4111 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4112 // Install and runtime permissions are stored in different places, 4113 // so figure out what permission changed and persist the change. 4114 if (permissionsState.getInstallPermissionState(name) != null) { 4115 scheduleWriteSettingsLocked(); 4116 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4117 || hadState) { 4118 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4119 } 4120 } 4121 } 4122 } 4123 4124 /** 4125 * Update the permission flags for all packages and runtime permissions of a user in order 4126 * to allow device or profile owner to remove POLICY_FIXED. 4127 */ 4128 @Override 4129 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4130 if (!sUserManager.exists(userId)) { 4131 return; 4132 } 4133 4134 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4135 4136 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4137 "updatePermissionFlagsForAllApps"); 4138 4139 // Only the system can change system fixed flags. 4140 if (getCallingUid() != Process.SYSTEM_UID) { 4141 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4142 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4143 } 4144 4145 synchronized (mPackages) { 4146 boolean changed = false; 4147 final int packageCount = mPackages.size(); 4148 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4149 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4150 SettingBase sb = (SettingBase) pkg.mExtras; 4151 if (sb == null) { 4152 continue; 4153 } 4154 PermissionsState permissionsState = sb.getPermissionsState(); 4155 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4156 userId, flagMask, flagValues); 4157 } 4158 if (changed) { 4159 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4160 } 4161 } 4162 } 4163 4164 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4165 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4166 != PackageManager.PERMISSION_GRANTED 4167 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4168 != PackageManager.PERMISSION_GRANTED) { 4169 throw new SecurityException(message + " requires " 4170 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4171 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4172 } 4173 } 4174 4175 @Override 4176 public boolean shouldShowRequestPermissionRationale(String permissionName, 4177 String packageName, int userId) { 4178 if (UserHandle.getCallingUserId() != userId) { 4179 mContext.enforceCallingPermission( 4180 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4181 "canShowRequestPermissionRationale for user " + userId); 4182 } 4183 4184 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4185 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4186 return false; 4187 } 4188 4189 if (checkPermission(permissionName, packageName, userId) 4190 == PackageManager.PERMISSION_GRANTED) { 4191 return false; 4192 } 4193 4194 final int flags; 4195 4196 final long identity = Binder.clearCallingIdentity(); 4197 try { 4198 flags = getPermissionFlags(permissionName, 4199 packageName, userId); 4200 } finally { 4201 Binder.restoreCallingIdentity(identity); 4202 } 4203 4204 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4205 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4206 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4207 4208 if ((flags & fixedFlags) != 0) { 4209 return false; 4210 } 4211 4212 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4213 } 4214 4215 @Override 4216 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4217 mContext.enforceCallingOrSelfPermission( 4218 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4219 "addOnPermissionsChangeListener"); 4220 4221 synchronized (mPackages) { 4222 mOnPermissionChangeListeners.addListenerLocked(listener); 4223 } 4224 } 4225 4226 @Override 4227 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4228 synchronized (mPackages) { 4229 mOnPermissionChangeListeners.removeListenerLocked(listener); 4230 } 4231 } 4232 4233 @Override 4234 public boolean isProtectedBroadcast(String actionName) { 4235 synchronized (mPackages) { 4236 if (mProtectedBroadcasts.contains(actionName)) { 4237 return true; 4238 } else if (actionName != null) { 4239 // TODO: remove these terrible hacks 4240 if (actionName.startsWith("android.net.netmon.lingerExpired") 4241 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4242 return true; 4243 } 4244 } 4245 } 4246 return false; 4247 } 4248 4249 @Override 4250 public int checkSignatures(String pkg1, String pkg2) { 4251 synchronized (mPackages) { 4252 final PackageParser.Package p1 = mPackages.get(pkg1); 4253 final PackageParser.Package p2 = mPackages.get(pkg2); 4254 if (p1 == null || p1.mExtras == null 4255 || p2 == null || p2.mExtras == null) { 4256 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4257 } 4258 return compareSignatures(p1.mSignatures, p2.mSignatures); 4259 } 4260 } 4261 4262 @Override 4263 public int checkUidSignatures(int uid1, int uid2) { 4264 // Map to base uids. 4265 uid1 = UserHandle.getAppId(uid1); 4266 uid2 = UserHandle.getAppId(uid2); 4267 // reader 4268 synchronized (mPackages) { 4269 Signature[] s1; 4270 Signature[] s2; 4271 Object obj = mSettings.getUserIdLPr(uid1); 4272 if (obj != null) { 4273 if (obj instanceof SharedUserSetting) { 4274 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4275 } else if (obj instanceof PackageSetting) { 4276 s1 = ((PackageSetting)obj).signatures.mSignatures; 4277 } else { 4278 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4279 } 4280 } else { 4281 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4282 } 4283 obj = mSettings.getUserIdLPr(uid2); 4284 if (obj != null) { 4285 if (obj instanceof SharedUserSetting) { 4286 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4287 } else if (obj instanceof PackageSetting) { 4288 s2 = ((PackageSetting)obj).signatures.mSignatures; 4289 } else { 4290 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4291 } 4292 } else { 4293 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4294 } 4295 return compareSignatures(s1, s2); 4296 } 4297 } 4298 4299 private void killUid(int appId, int userId, String reason) { 4300 final long identity = Binder.clearCallingIdentity(); 4301 try { 4302 IActivityManager am = ActivityManagerNative.getDefault(); 4303 if (am != null) { 4304 try { 4305 am.killUid(appId, userId, reason); 4306 } catch (RemoteException e) { 4307 /* ignore - same process */ 4308 } 4309 } 4310 } finally { 4311 Binder.restoreCallingIdentity(identity); 4312 } 4313 } 4314 4315 /** 4316 * Compares two sets of signatures. Returns: 4317 * <br /> 4318 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4319 * <br /> 4320 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4321 * <br /> 4322 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4323 * <br /> 4324 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4325 * <br /> 4326 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4327 */ 4328 static int compareSignatures(Signature[] s1, Signature[] s2) { 4329 if (s1 == null) { 4330 return s2 == null 4331 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4332 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4333 } 4334 4335 if (s2 == null) { 4336 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4337 } 4338 4339 if (s1.length != s2.length) { 4340 return PackageManager.SIGNATURE_NO_MATCH; 4341 } 4342 4343 // Since both signature sets are of size 1, we can compare without HashSets. 4344 if (s1.length == 1) { 4345 return s1[0].equals(s2[0]) ? 4346 PackageManager.SIGNATURE_MATCH : 4347 PackageManager.SIGNATURE_NO_MATCH; 4348 } 4349 4350 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4351 for (Signature sig : s1) { 4352 set1.add(sig); 4353 } 4354 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4355 for (Signature sig : s2) { 4356 set2.add(sig); 4357 } 4358 // Make sure s2 contains all signatures in s1. 4359 if (set1.equals(set2)) { 4360 return PackageManager.SIGNATURE_MATCH; 4361 } 4362 return PackageManager.SIGNATURE_NO_MATCH; 4363 } 4364 4365 /** 4366 * If the database version for this type of package (internal storage or 4367 * external storage) is less than the version where package signatures 4368 * were updated, return true. 4369 */ 4370 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4371 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4372 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4373 } 4374 4375 /** 4376 * Used for backward compatibility to make sure any packages with 4377 * certificate chains get upgraded to the new style. {@code existingSigs} 4378 * will be in the old format (since they were stored on disk from before the 4379 * system upgrade) and {@code scannedSigs} will be in the newer format. 4380 */ 4381 private int compareSignaturesCompat(PackageSignatures existingSigs, 4382 PackageParser.Package scannedPkg) { 4383 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4384 return PackageManager.SIGNATURE_NO_MATCH; 4385 } 4386 4387 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4388 for (Signature sig : existingSigs.mSignatures) { 4389 existingSet.add(sig); 4390 } 4391 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4392 for (Signature sig : scannedPkg.mSignatures) { 4393 try { 4394 Signature[] chainSignatures = sig.getChainSignatures(); 4395 for (Signature chainSig : chainSignatures) { 4396 scannedCompatSet.add(chainSig); 4397 } 4398 } catch (CertificateEncodingException e) { 4399 scannedCompatSet.add(sig); 4400 } 4401 } 4402 /* 4403 * Make sure the expanded scanned set contains all signatures in the 4404 * existing one. 4405 */ 4406 if (scannedCompatSet.equals(existingSet)) { 4407 // Migrate the old signatures to the new scheme. 4408 existingSigs.assignSignatures(scannedPkg.mSignatures); 4409 // The new KeySets will be re-added later in the scanning process. 4410 synchronized (mPackages) { 4411 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4412 } 4413 return PackageManager.SIGNATURE_MATCH; 4414 } 4415 return PackageManager.SIGNATURE_NO_MATCH; 4416 } 4417 4418 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4419 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4420 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4421 } 4422 4423 private int compareSignaturesRecover(PackageSignatures existingSigs, 4424 PackageParser.Package scannedPkg) { 4425 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4426 return PackageManager.SIGNATURE_NO_MATCH; 4427 } 4428 4429 String msg = null; 4430 try { 4431 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4432 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4433 + scannedPkg.packageName); 4434 return PackageManager.SIGNATURE_MATCH; 4435 } 4436 } catch (CertificateException e) { 4437 msg = e.getMessage(); 4438 } 4439 4440 logCriticalInfo(Log.INFO, 4441 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4442 return PackageManager.SIGNATURE_NO_MATCH; 4443 } 4444 4445 @Override 4446 public String[] getPackagesForUid(int uid) { 4447 uid = UserHandle.getAppId(uid); 4448 // reader 4449 synchronized (mPackages) { 4450 Object obj = mSettings.getUserIdLPr(uid); 4451 if (obj instanceof SharedUserSetting) { 4452 final SharedUserSetting sus = (SharedUserSetting) obj; 4453 final int N = sus.packages.size(); 4454 final String[] res = new String[N]; 4455 final Iterator<PackageSetting> it = sus.packages.iterator(); 4456 int i = 0; 4457 while (it.hasNext()) { 4458 res[i++] = it.next().name; 4459 } 4460 return res; 4461 } else if (obj instanceof PackageSetting) { 4462 final PackageSetting ps = (PackageSetting) obj; 4463 return new String[] { ps.name }; 4464 } 4465 } 4466 return null; 4467 } 4468 4469 @Override 4470 public String getNameForUid(int uid) { 4471 // reader 4472 synchronized (mPackages) { 4473 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4474 if (obj instanceof SharedUserSetting) { 4475 final SharedUserSetting sus = (SharedUserSetting) obj; 4476 return sus.name + ":" + sus.userId; 4477 } else if (obj instanceof PackageSetting) { 4478 final PackageSetting ps = (PackageSetting) obj; 4479 return ps.name; 4480 } 4481 } 4482 return null; 4483 } 4484 4485 @Override 4486 public int getUidForSharedUser(String sharedUserName) { 4487 if(sharedUserName == null) { 4488 return -1; 4489 } 4490 // reader 4491 synchronized (mPackages) { 4492 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4493 if (suid == null) { 4494 return -1; 4495 } 4496 return suid.userId; 4497 } 4498 } 4499 4500 @Override 4501 public int getFlagsForUid(int uid) { 4502 synchronized (mPackages) { 4503 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4504 if (obj instanceof SharedUserSetting) { 4505 final SharedUserSetting sus = (SharedUserSetting) obj; 4506 return sus.pkgFlags; 4507 } else if (obj instanceof PackageSetting) { 4508 final PackageSetting ps = (PackageSetting) obj; 4509 return ps.pkgFlags; 4510 } 4511 } 4512 return 0; 4513 } 4514 4515 @Override 4516 public int getPrivateFlagsForUid(int uid) { 4517 synchronized (mPackages) { 4518 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4519 if (obj instanceof SharedUserSetting) { 4520 final SharedUserSetting sus = (SharedUserSetting) obj; 4521 return sus.pkgPrivateFlags; 4522 } else if (obj instanceof PackageSetting) { 4523 final PackageSetting ps = (PackageSetting) obj; 4524 return ps.pkgPrivateFlags; 4525 } 4526 } 4527 return 0; 4528 } 4529 4530 @Override 4531 public boolean isUidPrivileged(int uid) { 4532 uid = UserHandle.getAppId(uid); 4533 // reader 4534 synchronized (mPackages) { 4535 Object obj = mSettings.getUserIdLPr(uid); 4536 if (obj instanceof SharedUserSetting) { 4537 final SharedUserSetting sus = (SharedUserSetting) obj; 4538 final Iterator<PackageSetting> it = sus.packages.iterator(); 4539 while (it.hasNext()) { 4540 if (it.next().isPrivileged()) { 4541 return true; 4542 } 4543 } 4544 } else if (obj instanceof PackageSetting) { 4545 final PackageSetting ps = (PackageSetting) obj; 4546 return ps.isPrivileged(); 4547 } 4548 } 4549 return false; 4550 } 4551 4552 @Override 4553 public String[] getAppOpPermissionPackages(String permissionName) { 4554 synchronized (mPackages) { 4555 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4556 if (pkgs == null) { 4557 return null; 4558 } 4559 return pkgs.toArray(new String[pkgs.size()]); 4560 } 4561 } 4562 4563 @Override 4564 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4565 int flags, int userId) { 4566 if (!sUserManager.exists(userId)) return null; 4567 flags = updateFlagsForResolve(flags, userId, intent); 4568 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4569 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4570 final ResolveInfo bestChoice = 4571 chooseBestActivity(intent, resolvedType, flags, query, userId); 4572 4573 if (isEphemeralAllowed(intent, query, userId)) { 4574 final EphemeralResolveInfo ai = 4575 getEphemeralResolveInfo(intent, resolvedType, userId); 4576 if (ai != null) { 4577 if (DEBUG_EPHEMERAL) { 4578 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4579 } 4580 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4581 bestChoice.ephemeralResolveInfo = ai; 4582 } 4583 } 4584 return bestChoice; 4585 } 4586 4587 @Override 4588 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4589 IntentFilter filter, int match, ComponentName activity) { 4590 final int userId = UserHandle.getCallingUserId(); 4591 if (DEBUG_PREFERRED) { 4592 Log.v(TAG, "setLastChosenActivity intent=" + intent 4593 + " resolvedType=" + resolvedType 4594 + " flags=" + flags 4595 + " filter=" + filter 4596 + " match=" + match 4597 + " activity=" + activity); 4598 filter.dump(new PrintStreamPrinter(System.out), " "); 4599 } 4600 intent.setComponent(null); 4601 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4602 // Find any earlier preferred or last chosen entries and nuke them 4603 findPreferredActivity(intent, resolvedType, 4604 flags, query, 0, false, true, false, userId); 4605 // Add the new activity as the last chosen for this filter 4606 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4607 "Setting last chosen"); 4608 } 4609 4610 @Override 4611 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4612 final int userId = UserHandle.getCallingUserId(); 4613 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4614 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4615 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4616 false, false, false, userId); 4617 } 4618 4619 4620 private boolean isEphemeralAllowed( 4621 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4622 // Short circuit and return early if possible. 4623 if (DISABLE_EPHEMERAL_APPS) { 4624 return false; 4625 } 4626 final int callingUser = UserHandle.getCallingUserId(); 4627 if (callingUser != UserHandle.USER_SYSTEM) { 4628 return false; 4629 } 4630 if (mEphemeralResolverConnection == null) { 4631 return false; 4632 } 4633 if (intent.getComponent() != null) { 4634 return false; 4635 } 4636 if (intent.getPackage() != null) { 4637 return false; 4638 } 4639 final boolean isWebUri = hasWebURI(intent); 4640 if (!isWebUri) { 4641 return false; 4642 } 4643 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4644 synchronized (mPackages) { 4645 final int count = resolvedActivites.size(); 4646 for (int n = 0; n < count; n++) { 4647 ResolveInfo info = resolvedActivites.get(n); 4648 String packageName = info.activityInfo.packageName; 4649 PackageSetting ps = mSettings.mPackages.get(packageName); 4650 if (ps != null) { 4651 // Try to get the status from User settings first 4652 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4653 int status = (int) (packedStatus >> 32); 4654 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4655 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4656 if (DEBUG_EPHEMERAL) { 4657 Slog.v(TAG, "DENY ephemeral apps;" 4658 + " pkg: " + packageName + ", status: " + status); 4659 } 4660 return false; 4661 } 4662 } 4663 } 4664 } 4665 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4666 return true; 4667 } 4668 4669 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4670 int userId) { 4671 MessageDigest digest = null; 4672 try { 4673 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4674 } catch (NoSuchAlgorithmException e) { 4675 // If we can't create a digest, ignore ephemeral apps. 4676 return null; 4677 } 4678 4679 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4680 final byte[] digestBytes = digest.digest(hostBytes); 4681 int shaPrefix = 4682 digestBytes[0] << 24 4683 | digestBytes[1] << 16 4684 | digestBytes[2] << 8 4685 | digestBytes[3] << 0; 4686 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4687 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4688 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4689 // No hash prefix match; there are no ephemeral apps for this domain. 4690 return null; 4691 } 4692 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4693 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4694 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4695 continue; 4696 } 4697 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4698 // No filters; this should never happen. 4699 if (filters.isEmpty()) { 4700 continue; 4701 } 4702 // We have a domain match; resolve the filters to see if anything matches. 4703 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4704 for (int j = filters.size() - 1; j >= 0; --j) { 4705 final EphemeralResolveIntentInfo intentInfo = 4706 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4707 ephemeralResolver.addFilter(intentInfo); 4708 } 4709 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4710 intent, resolvedType, false /*defaultOnly*/, userId); 4711 if (!matchedResolveInfoList.isEmpty()) { 4712 return matchedResolveInfoList.get(0); 4713 } 4714 } 4715 // Hash or filter mis-match; no ephemeral apps for this domain. 4716 return null; 4717 } 4718 4719 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4720 int flags, List<ResolveInfo> query, int userId) { 4721 if (query != null) { 4722 final int N = query.size(); 4723 if (N == 1) { 4724 return query.get(0); 4725 } else if (N > 1) { 4726 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4727 // If there is more than one activity with the same priority, 4728 // then let the user decide between them. 4729 ResolveInfo r0 = query.get(0); 4730 ResolveInfo r1 = query.get(1); 4731 if (DEBUG_INTENT_MATCHING || debug) { 4732 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4733 + r1.activityInfo.name + "=" + r1.priority); 4734 } 4735 // If the first activity has a higher priority, or a different 4736 // default, then it is always desirable to pick it. 4737 if (r0.priority != r1.priority 4738 || r0.preferredOrder != r1.preferredOrder 4739 || r0.isDefault != r1.isDefault) { 4740 return query.get(0); 4741 } 4742 // If we have saved a preference for a preferred activity for 4743 // this Intent, use that. 4744 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4745 flags, query, r0.priority, true, false, debug, userId); 4746 if (ri != null) { 4747 return ri; 4748 } 4749 ri = new ResolveInfo(mResolveInfo); 4750 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4751 ri.activityInfo.applicationInfo = new ApplicationInfo( 4752 ri.activityInfo.applicationInfo); 4753 if (userId != 0) { 4754 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4755 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4756 } 4757 // Make sure that the resolver is displayable in car mode 4758 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4759 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4760 return ri; 4761 } 4762 } 4763 return null; 4764 } 4765 4766 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4767 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4768 final int N = query.size(); 4769 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4770 .get(userId); 4771 // Get the list of persistent preferred activities that handle the intent 4772 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4773 List<PersistentPreferredActivity> pprefs = ppir != null 4774 ? ppir.queryIntent(intent, resolvedType, 4775 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4776 : null; 4777 if (pprefs != null && pprefs.size() > 0) { 4778 final int M = pprefs.size(); 4779 for (int i=0; i<M; i++) { 4780 final PersistentPreferredActivity ppa = pprefs.get(i); 4781 if (DEBUG_PREFERRED || debug) { 4782 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4783 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4784 + "\n component=" + ppa.mComponent); 4785 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4786 } 4787 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4788 flags | MATCH_DISABLED_COMPONENTS, userId); 4789 if (DEBUG_PREFERRED || debug) { 4790 Slog.v(TAG, "Found persistent preferred activity:"); 4791 if (ai != null) { 4792 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4793 } else { 4794 Slog.v(TAG, " null"); 4795 } 4796 } 4797 if (ai == null) { 4798 // This previously registered persistent preferred activity 4799 // component is no longer known. Ignore it and do NOT remove it. 4800 continue; 4801 } 4802 for (int j=0; j<N; j++) { 4803 final ResolveInfo ri = query.get(j); 4804 if (!ri.activityInfo.applicationInfo.packageName 4805 .equals(ai.applicationInfo.packageName)) { 4806 continue; 4807 } 4808 if (!ri.activityInfo.name.equals(ai.name)) { 4809 continue; 4810 } 4811 // Found a persistent preference that can handle the intent. 4812 if (DEBUG_PREFERRED || debug) { 4813 Slog.v(TAG, "Returning persistent preferred activity: " + 4814 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4815 } 4816 return ri; 4817 } 4818 } 4819 } 4820 return null; 4821 } 4822 4823 // TODO: handle preferred activities missing while user has amnesia 4824 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4825 List<ResolveInfo> query, int priority, boolean always, 4826 boolean removeMatches, boolean debug, int userId) { 4827 if (!sUserManager.exists(userId)) return null; 4828 flags = updateFlagsForResolve(flags, userId, intent); 4829 // writer 4830 synchronized (mPackages) { 4831 if (intent.getSelector() != null) { 4832 intent = intent.getSelector(); 4833 } 4834 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4835 4836 // Try to find a matching persistent preferred activity. 4837 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4838 debug, userId); 4839 4840 // If a persistent preferred activity matched, use it. 4841 if (pri != null) { 4842 return pri; 4843 } 4844 4845 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4846 // Get the list of preferred activities that handle the intent 4847 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4848 List<PreferredActivity> prefs = pir != null 4849 ? pir.queryIntent(intent, resolvedType, 4850 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4851 : null; 4852 if (prefs != null && prefs.size() > 0) { 4853 boolean changed = false; 4854 try { 4855 // First figure out how good the original match set is. 4856 // We will only allow preferred activities that came 4857 // from the same match quality. 4858 int match = 0; 4859 4860 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4861 4862 final int N = query.size(); 4863 for (int j=0; j<N; j++) { 4864 final ResolveInfo ri = query.get(j); 4865 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4866 + ": 0x" + Integer.toHexString(match)); 4867 if (ri.match > match) { 4868 match = ri.match; 4869 } 4870 } 4871 4872 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4873 + Integer.toHexString(match)); 4874 4875 match &= IntentFilter.MATCH_CATEGORY_MASK; 4876 final int M = prefs.size(); 4877 for (int i=0; i<M; i++) { 4878 final PreferredActivity pa = prefs.get(i); 4879 if (DEBUG_PREFERRED || debug) { 4880 Slog.v(TAG, "Checking PreferredActivity ds=" 4881 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4882 + "\n component=" + pa.mPref.mComponent); 4883 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4884 } 4885 if (pa.mPref.mMatch != match) { 4886 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4887 + Integer.toHexString(pa.mPref.mMatch)); 4888 continue; 4889 } 4890 // If it's not an "always" type preferred activity and that's what we're 4891 // looking for, skip it. 4892 if (always && !pa.mPref.mAlways) { 4893 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4894 continue; 4895 } 4896 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4897 flags | MATCH_DISABLED_COMPONENTS, userId); 4898 if (DEBUG_PREFERRED || debug) { 4899 Slog.v(TAG, "Found preferred activity:"); 4900 if (ai != null) { 4901 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4902 } else { 4903 Slog.v(TAG, " null"); 4904 } 4905 } 4906 if (ai == null) { 4907 // This previously registered preferred activity 4908 // component is no longer known. Most likely an update 4909 // to the app was installed and in the new version this 4910 // component no longer exists. Clean it up by removing 4911 // it from the preferred activities list, and skip it. 4912 Slog.w(TAG, "Removing dangling preferred activity: " 4913 + pa.mPref.mComponent); 4914 pir.removeFilter(pa); 4915 changed = true; 4916 continue; 4917 } 4918 for (int j=0; j<N; j++) { 4919 final ResolveInfo ri = query.get(j); 4920 if (!ri.activityInfo.applicationInfo.packageName 4921 .equals(ai.applicationInfo.packageName)) { 4922 continue; 4923 } 4924 if (!ri.activityInfo.name.equals(ai.name)) { 4925 continue; 4926 } 4927 4928 if (removeMatches) { 4929 pir.removeFilter(pa); 4930 changed = true; 4931 if (DEBUG_PREFERRED) { 4932 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4933 } 4934 break; 4935 } 4936 4937 // Okay we found a previously set preferred or last chosen app. 4938 // If the result set is different from when this 4939 // was created, we need to clear it and re-ask the 4940 // user their preference, if we're looking for an "always" type entry. 4941 if (always && !pa.mPref.sameSet(query)) { 4942 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4943 + intent + " type " + resolvedType); 4944 if (DEBUG_PREFERRED) { 4945 Slog.v(TAG, "Removing preferred activity since set changed " 4946 + pa.mPref.mComponent); 4947 } 4948 pir.removeFilter(pa); 4949 // Re-add the filter as a "last chosen" entry (!always) 4950 PreferredActivity lastChosen = new PreferredActivity( 4951 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4952 pir.addFilter(lastChosen); 4953 changed = true; 4954 return null; 4955 } 4956 4957 // Yay! Either the set matched or we're looking for the last chosen 4958 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4959 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4960 return ri; 4961 } 4962 } 4963 } finally { 4964 if (changed) { 4965 if (DEBUG_PREFERRED) { 4966 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4967 } 4968 scheduleWritePackageRestrictionsLocked(userId); 4969 } 4970 } 4971 } 4972 } 4973 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4974 return null; 4975 } 4976 4977 /* 4978 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4979 */ 4980 @Override 4981 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4982 int targetUserId) { 4983 mContext.enforceCallingOrSelfPermission( 4984 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4985 List<CrossProfileIntentFilter> matches = 4986 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4987 if (matches != null) { 4988 int size = matches.size(); 4989 for (int i = 0; i < size; i++) { 4990 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4991 } 4992 } 4993 if (hasWebURI(intent)) { 4994 // cross-profile app linking works only towards the parent. 4995 final UserInfo parent = getProfileParent(sourceUserId); 4996 synchronized(mPackages) { 4997 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4998 intent, resolvedType, 0, sourceUserId, parent.id); 4999 return xpDomainInfo != null; 5000 } 5001 } 5002 return false; 5003 } 5004 5005 private UserInfo getProfileParent(int userId) { 5006 final long identity = Binder.clearCallingIdentity(); 5007 try { 5008 return sUserManager.getProfileParent(userId); 5009 } finally { 5010 Binder.restoreCallingIdentity(identity); 5011 } 5012 } 5013 5014 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5015 String resolvedType, int userId) { 5016 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5017 if (resolver != null) { 5018 return resolver.queryIntent(intent, resolvedType, false, userId); 5019 } 5020 return null; 5021 } 5022 5023 @Override 5024 public List<ResolveInfo> queryIntentActivities(Intent intent, 5025 String resolvedType, int flags, int userId) { 5026 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5027 flags = updateFlagsForResolve(flags, userId, intent); 5028 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 5029 ComponentName comp = intent.getComponent(); 5030 if (comp == null) { 5031 if (intent.getSelector() != null) { 5032 intent = intent.getSelector(); 5033 comp = intent.getComponent(); 5034 } 5035 } 5036 5037 if (comp != null) { 5038 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5039 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5040 if (ai != null) { 5041 final ResolveInfo ri = new ResolveInfo(); 5042 ri.activityInfo = ai; 5043 list.add(ri); 5044 } 5045 return list; 5046 } 5047 5048 // reader 5049 synchronized (mPackages) { 5050 final String pkgName = intent.getPackage(); 5051 if (pkgName == null) { 5052 List<CrossProfileIntentFilter> matchingFilters = 5053 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5054 // Check for results that need to skip the current profile. 5055 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5056 resolvedType, flags, userId); 5057 if (xpResolveInfo != null) { 5058 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5059 result.add(xpResolveInfo); 5060 return filterIfNotSystemUser(result, userId); 5061 } 5062 5063 // Check for results in the current profile. 5064 List<ResolveInfo> result = mActivities.queryIntent( 5065 intent, resolvedType, flags, userId); 5066 result = filterIfNotSystemUser(result, userId); 5067 5068 // Check for cross profile results. 5069 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5070 xpResolveInfo = queryCrossProfileIntents( 5071 matchingFilters, intent, resolvedType, flags, userId, 5072 hasNonNegativePriorityResult); 5073 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5074 boolean isVisibleToUser = filterIfNotSystemUser( 5075 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5076 if (isVisibleToUser) { 5077 result.add(xpResolveInfo); 5078 Collections.sort(result, mResolvePrioritySorter); 5079 } 5080 } 5081 if (hasWebURI(intent)) { 5082 CrossProfileDomainInfo xpDomainInfo = null; 5083 final UserInfo parent = getProfileParent(userId); 5084 if (parent != null) { 5085 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5086 flags, userId, parent.id); 5087 } 5088 if (xpDomainInfo != null) { 5089 if (xpResolveInfo != null) { 5090 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5091 // in the result. 5092 result.remove(xpResolveInfo); 5093 } 5094 if (result.size() == 0) { 5095 result.add(xpDomainInfo.resolveInfo); 5096 return result; 5097 } 5098 } else if (result.size() <= 1) { 5099 return result; 5100 } 5101 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5102 xpDomainInfo, userId); 5103 Collections.sort(result, mResolvePrioritySorter); 5104 } 5105 return result; 5106 } 5107 final PackageParser.Package pkg = mPackages.get(pkgName); 5108 if (pkg != null) { 5109 return filterIfNotSystemUser( 5110 mActivities.queryIntentForPackage( 5111 intent, resolvedType, flags, pkg.activities, userId), 5112 userId); 5113 } 5114 return new ArrayList<ResolveInfo>(); 5115 } 5116 } 5117 5118 private static class CrossProfileDomainInfo { 5119 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5120 ResolveInfo resolveInfo; 5121 /* Best domain verification status of the activities found in the other profile */ 5122 int bestDomainVerificationStatus; 5123 } 5124 5125 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5126 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5127 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5128 sourceUserId)) { 5129 return null; 5130 } 5131 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5132 resolvedType, flags, parentUserId); 5133 5134 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5135 return null; 5136 } 5137 CrossProfileDomainInfo result = null; 5138 int size = resultTargetUser.size(); 5139 for (int i = 0; i < size; i++) { 5140 ResolveInfo riTargetUser = resultTargetUser.get(i); 5141 // Intent filter verification is only for filters that specify a host. So don't return 5142 // those that handle all web uris. 5143 if (riTargetUser.handleAllWebDataURI) { 5144 continue; 5145 } 5146 String packageName = riTargetUser.activityInfo.packageName; 5147 PackageSetting ps = mSettings.mPackages.get(packageName); 5148 if (ps == null) { 5149 continue; 5150 } 5151 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5152 int status = (int)(verificationState >> 32); 5153 if (result == null) { 5154 result = new CrossProfileDomainInfo(); 5155 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5156 sourceUserId, parentUserId); 5157 result.bestDomainVerificationStatus = status; 5158 } else { 5159 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5160 result.bestDomainVerificationStatus); 5161 } 5162 } 5163 // Don't consider matches with status NEVER across profiles. 5164 if (result != null && result.bestDomainVerificationStatus 5165 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5166 return null; 5167 } 5168 return result; 5169 } 5170 5171 /** 5172 * Verification statuses are ordered from the worse to the best, except for 5173 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5174 */ 5175 private int bestDomainVerificationStatus(int status1, int status2) { 5176 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5177 return status2; 5178 } 5179 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5180 return status1; 5181 } 5182 return (int) MathUtils.max(status1, status2); 5183 } 5184 5185 private boolean isUserEnabled(int userId) { 5186 long callingId = Binder.clearCallingIdentity(); 5187 try { 5188 UserInfo userInfo = sUserManager.getUserInfo(userId); 5189 return userInfo != null && userInfo.isEnabled(); 5190 } finally { 5191 Binder.restoreCallingIdentity(callingId); 5192 } 5193 } 5194 5195 /** 5196 * Filter out activities with systemUserOnly flag set, when current user is not System. 5197 * 5198 * @return filtered list 5199 */ 5200 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5201 if (userId == UserHandle.USER_SYSTEM) { 5202 return resolveInfos; 5203 } 5204 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5205 ResolveInfo info = resolveInfos.get(i); 5206 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5207 resolveInfos.remove(i); 5208 } 5209 } 5210 return resolveInfos; 5211 } 5212 5213 /** 5214 * @param resolveInfos list of resolve infos in descending priority order 5215 * @return if the list contains a resolve info with non-negative priority 5216 */ 5217 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5218 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5219 } 5220 5221 private static boolean hasWebURI(Intent intent) { 5222 if (intent.getData() == null) { 5223 return false; 5224 } 5225 final String scheme = intent.getScheme(); 5226 if (TextUtils.isEmpty(scheme)) { 5227 return false; 5228 } 5229 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5230 } 5231 5232 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5233 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5234 int userId) { 5235 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5236 5237 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5238 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5239 candidates.size()); 5240 } 5241 5242 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5243 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5244 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5245 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5246 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5247 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5248 5249 synchronized (mPackages) { 5250 final int count = candidates.size(); 5251 // First, try to use linked apps. Partition the candidates into four lists: 5252 // one for the final results, one for the "do not use ever", one for "undefined status" 5253 // and finally one for "browser app type". 5254 for (int n=0; n<count; n++) { 5255 ResolveInfo info = candidates.get(n); 5256 String packageName = info.activityInfo.packageName; 5257 PackageSetting ps = mSettings.mPackages.get(packageName); 5258 if (ps != null) { 5259 // Add to the special match all list (Browser use case) 5260 if (info.handleAllWebDataURI) { 5261 matchAllList.add(info); 5262 continue; 5263 } 5264 // Try to get the status from User settings first 5265 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5266 int status = (int)(packedStatus >> 32); 5267 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5268 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5269 if (DEBUG_DOMAIN_VERIFICATION) { 5270 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5271 + " : linkgen=" + linkGeneration); 5272 } 5273 // Use link-enabled generation as preferredOrder, i.e. 5274 // prefer newly-enabled over earlier-enabled. 5275 info.preferredOrder = linkGeneration; 5276 alwaysList.add(info); 5277 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5278 if (DEBUG_DOMAIN_VERIFICATION) { 5279 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5280 } 5281 neverList.add(info); 5282 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5283 if (DEBUG_DOMAIN_VERIFICATION) { 5284 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5285 } 5286 alwaysAskList.add(info); 5287 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5288 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5289 if (DEBUG_DOMAIN_VERIFICATION) { 5290 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5291 } 5292 undefinedList.add(info); 5293 } 5294 } 5295 } 5296 5297 // We'll want to include browser possibilities in a few cases 5298 boolean includeBrowser = false; 5299 5300 // First try to add the "always" resolution(s) for the current user, if any 5301 if (alwaysList.size() > 0) { 5302 result.addAll(alwaysList); 5303 } else { 5304 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5305 result.addAll(undefinedList); 5306 // Maybe add one for the other profile. 5307 if (xpDomainInfo != null && ( 5308 xpDomainInfo.bestDomainVerificationStatus 5309 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5310 result.add(xpDomainInfo.resolveInfo); 5311 } 5312 includeBrowser = true; 5313 } 5314 5315 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5316 // If there were 'always' entries their preferred order has been set, so we also 5317 // back that off to make the alternatives equivalent 5318 if (alwaysAskList.size() > 0) { 5319 for (ResolveInfo i : result) { 5320 i.preferredOrder = 0; 5321 } 5322 result.addAll(alwaysAskList); 5323 includeBrowser = true; 5324 } 5325 5326 if (includeBrowser) { 5327 // Also add browsers (all of them or only the default one) 5328 if (DEBUG_DOMAIN_VERIFICATION) { 5329 Slog.v(TAG, " ...including browsers in candidate set"); 5330 } 5331 if ((matchFlags & MATCH_ALL) != 0) { 5332 result.addAll(matchAllList); 5333 } else { 5334 // Browser/generic handling case. If there's a default browser, go straight 5335 // to that (but only if there is no other higher-priority match). 5336 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5337 int maxMatchPrio = 0; 5338 ResolveInfo defaultBrowserMatch = null; 5339 final int numCandidates = matchAllList.size(); 5340 for (int n = 0; n < numCandidates; n++) { 5341 ResolveInfo info = matchAllList.get(n); 5342 // track the highest overall match priority... 5343 if (info.priority > maxMatchPrio) { 5344 maxMatchPrio = info.priority; 5345 } 5346 // ...and the highest-priority default browser match 5347 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5348 if (defaultBrowserMatch == null 5349 || (defaultBrowserMatch.priority < info.priority)) { 5350 if (debug) { 5351 Slog.v(TAG, "Considering default browser match " + info); 5352 } 5353 defaultBrowserMatch = info; 5354 } 5355 } 5356 } 5357 if (defaultBrowserMatch != null 5358 && defaultBrowserMatch.priority >= maxMatchPrio 5359 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5360 { 5361 if (debug) { 5362 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5363 } 5364 result.add(defaultBrowserMatch); 5365 } else { 5366 result.addAll(matchAllList); 5367 } 5368 } 5369 5370 // If there is nothing selected, add all candidates and remove the ones that the user 5371 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5372 if (result.size() == 0) { 5373 result.addAll(candidates); 5374 result.removeAll(neverList); 5375 } 5376 } 5377 } 5378 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5379 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5380 result.size()); 5381 for (ResolveInfo info : result) { 5382 Slog.v(TAG, " + " + info.activityInfo); 5383 } 5384 } 5385 return result; 5386 } 5387 5388 // Returns a packed value as a long: 5389 // 5390 // high 'int'-sized word: link status: undefined/ask/never/always. 5391 // low 'int'-sized word: relative priority among 'always' results. 5392 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5393 long result = ps.getDomainVerificationStatusForUser(userId); 5394 // if none available, get the master status 5395 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5396 if (ps.getIntentFilterVerificationInfo() != null) { 5397 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5398 } 5399 } 5400 return result; 5401 } 5402 5403 private ResolveInfo querySkipCurrentProfileIntents( 5404 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5405 int flags, int sourceUserId) { 5406 if (matchingFilters != null) { 5407 int size = matchingFilters.size(); 5408 for (int i = 0; i < size; i ++) { 5409 CrossProfileIntentFilter filter = matchingFilters.get(i); 5410 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5411 // Checking if there are activities in the target user that can handle the 5412 // intent. 5413 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5414 resolvedType, flags, sourceUserId); 5415 if (resolveInfo != null) { 5416 return resolveInfo; 5417 } 5418 } 5419 } 5420 } 5421 return null; 5422 } 5423 5424 // Return matching ResolveInfo in target user if any. 5425 private ResolveInfo queryCrossProfileIntents( 5426 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5427 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5428 if (matchingFilters != null) { 5429 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5430 // match the same intent. For performance reasons, it is better not to 5431 // run queryIntent twice for the same userId 5432 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5433 int size = matchingFilters.size(); 5434 for (int i = 0; i < size; i++) { 5435 CrossProfileIntentFilter filter = matchingFilters.get(i); 5436 int targetUserId = filter.getTargetUserId(); 5437 boolean skipCurrentProfile = 5438 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5439 boolean skipCurrentProfileIfNoMatchFound = 5440 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5441 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5442 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5443 // Checking if there are activities in the target user that can handle the 5444 // intent. 5445 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5446 resolvedType, flags, sourceUserId); 5447 if (resolveInfo != null) return resolveInfo; 5448 alreadyTriedUserIds.put(targetUserId, true); 5449 } 5450 } 5451 } 5452 return null; 5453 } 5454 5455 /** 5456 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5457 * will forward the intent to the filter's target user. 5458 * Otherwise, returns null. 5459 */ 5460 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5461 String resolvedType, int flags, int sourceUserId) { 5462 int targetUserId = filter.getTargetUserId(); 5463 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5464 resolvedType, flags, targetUserId); 5465 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5466 // If all the matches in the target profile are suspended, return null. 5467 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5468 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5469 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5470 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5471 targetUserId); 5472 } 5473 } 5474 } 5475 return null; 5476 } 5477 5478 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5479 int sourceUserId, int targetUserId) { 5480 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5481 long ident = Binder.clearCallingIdentity(); 5482 boolean targetIsProfile; 5483 try { 5484 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5485 } finally { 5486 Binder.restoreCallingIdentity(ident); 5487 } 5488 String className; 5489 if (targetIsProfile) { 5490 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5491 } else { 5492 className = FORWARD_INTENT_TO_PARENT; 5493 } 5494 ComponentName forwardingActivityComponentName = new ComponentName( 5495 mAndroidApplication.packageName, className); 5496 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5497 sourceUserId); 5498 if (!targetIsProfile) { 5499 forwardingActivityInfo.showUserIcon = targetUserId; 5500 forwardingResolveInfo.noResourceId = true; 5501 } 5502 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5503 forwardingResolveInfo.priority = 0; 5504 forwardingResolveInfo.preferredOrder = 0; 5505 forwardingResolveInfo.match = 0; 5506 forwardingResolveInfo.isDefault = true; 5507 forwardingResolveInfo.filter = filter; 5508 forwardingResolveInfo.targetUserId = targetUserId; 5509 return forwardingResolveInfo; 5510 } 5511 5512 @Override 5513 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5514 Intent[] specifics, String[] specificTypes, Intent intent, 5515 String resolvedType, int flags, int userId) { 5516 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5517 flags = updateFlagsForResolve(flags, userId, intent); 5518 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5519 false, "query intent activity options"); 5520 final String resultsAction = intent.getAction(); 5521 5522 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5523 | PackageManager.GET_RESOLVED_FILTER, userId); 5524 5525 if (DEBUG_INTENT_MATCHING) { 5526 Log.v(TAG, "Query " + intent + ": " + results); 5527 } 5528 5529 int specificsPos = 0; 5530 int N; 5531 5532 // todo: note that the algorithm used here is O(N^2). This 5533 // isn't a problem in our current environment, but if we start running 5534 // into situations where we have more than 5 or 10 matches then this 5535 // should probably be changed to something smarter... 5536 5537 // First we go through and resolve each of the specific items 5538 // that were supplied, taking care of removing any corresponding 5539 // duplicate items in the generic resolve list. 5540 if (specifics != null) { 5541 for (int i=0; i<specifics.length; i++) { 5542 final Intent sintent = specifics[i]; 5543 if (sintent == null) { 5544 continue; 5545 } 5546 5547 if (DEBUG_INTENT_MATCHING) { 5548 Log.v(TAG, "Specific #" + i + ": " + sintent); 5549 } 5550 5551 String action = sintent.getAction(); 5552 if (resultsAction != null && resultsAction.equals(action)) { 5553 // If this action was explicitly requested, then don't 5554 // remove things that have it. 5555 action = null; 5556 } 5557 5558 ResolveInfo ri = null; 5559 ActivityInfo ai = null; 5560 5561 ComponentName comp = sintent.getComponent(); 5562 if (comp == null) { 5563 ri = resolveIntent( 5564 sintent, 5565 specificTypes != null ? specificTypes[i] : null, 5566 flags, userId); 5567 if (ri == null) { 5568 continue; 5569 } 5570 if (ri == mResolveInfo) { 5571 // ACK! Must do something better with this. 5572 } 5573 ai = ri.activityInfo; 5574 comp = new ComponentName(ai.applicationInfo.packageName, 5575 ai.name); 5576 } else { 5577 ai = getActivityInfo(comp, flags, userId); 5578 if (ai == null) { 5579 continue; 5580 } 5581 } 5582 5583 // Look for any generic query activities that are duplicates 5584 // of this specific one, and remove them from the results. 5585 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5586 N = results.size(); 5587 int j; 5588 for (j=specificsPos; j<N; j++) { 5589 ResolveInfo sri = results.get(j); 5590 if ((sri.activityInfo.name.equals(comp.getClassName()) 5591 && sri.activityInfo.applicationInfo.packageName.equals( 5592 comp.getPackageName())) 5593 || (action != null && sri.filter.matchAction(action))) { 5594 results.remove(j); 5595 if (DEBUG_INTENT_MATCHING) Log.v( 5596 TAG, "Removing duplicate item from " + j 5597 + " due to specific " + specificsPos); 5598 if (ri == null) { 5599 ri = sri; 5600 } 5601 j--; 5602 N--; 5603 } 5604 } 5605 5606 // Add this specific item to its proper place. 5607 if (ri == null) { 5608 ri = new ResolveInfo(); 5609 ri.activityInfo = ai; 5610 } 5611 results.add(specificsPos, ri); 5612 ri.specificIndex = i; 5613 specificsPos++; 5614 } 5615 } 5616 5617 // Now we go through the remaining generic results and remove any 5618 // duplicate actions that are found here. 5619 N = results.size(); 5620 for (int i=specificsPos; i<N-1; i++) { 5621 final ResolveInfo rii = results.get(i); 5622 if (rii.filter == null) { 5623 continue; 5624 } 5625 5626 // Iterate over all of the actions of this result's intent 5627 // filter... typically this should be just one. 5628 final Iterator<String> it = rii.filter.actionsIterator(); 5629 if (it == null) { 5630 continue; 5631 } 5632 while (it.hasNext()) { 5633 final String action = it.next(); 5634 if (resultsAction != null && resultsAction.equals(action)) { 5635 // If this action was explicitly requested, then don't 5636 // remove things that have it. 5637 continue; 5638 } 5639 for (int j=i+1; j<N; j++) { 5640 final ResolveInfo rij = results.get(j); 5641 if (rij.filter != null && rij.filter.hasAction(action)) { 5642 results.remove(j); 5643 if (DEBUG_INTENT_MATCHING) Log.v( 5644 TAG, "Removing duplicate item from " + j 5645 + " due to action " + action + " at " + i); 5646 j--; 5647 N--; 5648 } 5649 } 5650 } 5651 5652 // If the caller didn't request filter information, drop it now 5653 // so we don't have to marshall/unmarshall it. 5654 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5655 rii.filter = null; 5656 } 5657 } 5658 5659 // Filter out the caller activity if so requested. 5660 if (caller != null) { 5661 N = results.size(); 5662 for (int i=0; i<N; i++) { 5663 ActivityInfo ainfo = results.get(i).activityInfo; 5664 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5665 && caller.getClassName().equals(ainfo.name)) { 5666 results.remove(i); 5667 break; 5668 } 5669 } 5670 } 5671 5672 // If the caller didn't request filter information, 5673 // drop them now so we don't have to 5674 // marshall/unmarshall it. 5675 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5676 N = results.size(); 5677 for (int i=0; i<N; i++) { 5678 results.get(i).filter = null; 5679 } 5680 } 5681 5682 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5683 return results; 5684 } 5685 5686 @Override 5687 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5688 int userId) { 5689 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5690 flags = updateFlagsForResolve(flags, userId, intent); 5691 ComponentName comp = intent.getComponent(); 5692 if (comp == null) { 5693 if (intent.getSelector() != null) { 5694 intent = intent.getSelector(); 5695 comp = intent.getComponent(); 5696 } 5697 } 5698 if (comp != null) { 5699 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5700 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5701 if (ai != null) { 5702 ResolveInfo ri = new ResolveInfo(); 5703 ri.activityInfo = ai; 5704 list.add(ri); 5705 } 5706 return list; 5707 } 5708 5709 // reader 5710 synchronized (mPackages) { 5711 String pkgName = intent.getPackage(); 5712 if (pkgName == null) { 5713 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5714 } 5715 final PackageParser.Package pkg = mPackages.get(pkgName); 5716 if (pkg != null) { 5717 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5718 userId); 5719 } 5720 return null; 5721 } 5722 } 5723 5724 @Override 5725 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5726 if (!sUserManager.exists(userId)) return null; 5727 flags = updateFlagsForResolve(flags, userId, intent); 5728 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5729 if (query != null) { 5730 if (query.size() >= 1) { 5731 // If there is more than one service with the same priority, 5732 // just arbitrarily pick the first one. 5733 return query.get(0); 5734 } 5735 } 5736 return null; 5737 } 5738 5739 @Override 5740 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5741 int userId) { 5742 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5743 flags = updateFlagsForResolve(flags, userId, intent); 5744 ComponentName comp = intent.getComponent(); 5745 if (comp == null) { 5746 if (intent.getSelector() != null) { 5747 intent = intent.getSelector(); 5748 comp = intent.getComponent(); 5749 } 5750 } 5751 if (comp != null) { 5752 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5753 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5754 if (si != null) { 5755 final ResolveInfo ri = new ResolveInfo(); 5756 ri.serviceInfo = si; 5757 list.add(ri); 5758 } 5759 return list; 5760 } 5761 5762 // reader 5763 synchronized (mPackages) { 5764 String pkgName = intent.getPackage(); 5765 if (pkgName == null) { 5766 return mServices.queryIntent(intent, resolvedType, flags, userId); 5767 } 5768 final PackageParser.Package pkg = mPackages.get(pkgName); 5769 if (pkg != null) { 5770 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5771 userId); 5772 } 5773 return null; 5774 } 5775 } 5776 5777 @Override 5778 public List<ResolveInfo> queryIntentContentProviders( 5779 Intent intent, String resolvedType, int flags, int userId) { 5780 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5781 flags = updateFlagsForResolve(flags, userId, intent); 5782 ComponentName comp = intent.getComponent(); 5783 if (comp == null) { 5784 if (intent.getSelector() != null) { 5785 intent = intent.getSelector(); 5786 comp = intent.getComponent(); 5787 } 5788 } 5789 if (comp != null) { 5790 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5791 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5792 if (pi != null) { 5793 final ResolveInfo ri = new ResolveInfo(); 5794 ri.providerInfo = pi; 5795 list.add(ri); 5796 } 5797 return list; 5798 } 5799 5800 // reader 5801 synchronized (mPackages) { 5802 String pkgName = intent.getPackage(); 5803 if (pkgName == null) { 5804 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5805 } 5806 final PackageParser.Package pkg = mPackages.get(pkgName); 5807 if (pkg != null) { 5808 return mProviders.queryIntentForPackage( 5809 intent, resolvedType, flags, pkg.providers, userId); 5810 } 5811 return null; 5812 } 5813 } 5814 5815 @Override 5816 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5817 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5818 flags = updateFlagsForPackage(flags, userId, null); 5819 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5820 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5821 5822 // writer 5823 synchronized (mPackages) { 5824 ArrayList<PackageInfo> list; 5825 if (listUninstalled) { 5826 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5827 for (PackageSetting ps : mSettings.mPackages.values()) { 5828 PackageInfo pi; 5829 if (ps.pkg != null) { 5830 pi = generatePackageInfo(ps.pkg, flags, userId); 5831 } else { 5832 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5833 } 5834 if (pi != null) { 5835 list.add(pi); 5836 } 5837 } 5838 } else { 5839 list = new ArrayList<PackageInfo>(mPackages.size()); 5840 for (PackageParser.Package p : mPackages.values()) { 5841 PackageInfo pi = generatePackageInfo(p, flags, userId); 5842 if (pi != null) { 5843 list.add(pi); 5844 } 5845 } 5846 } 5847 5848 return new ParceledListSlice<PackageInfo>(list); 5849 } 5850 } 5851 5852 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5853 String[] permissions, boolean[] tmp, int flags, int userId) { 5854 int numMatch = 0; 5855 final PermissionsState permissionsState = ps.getPermissionsState(); 5856 for (int i=0; i<permissions.length; i++) { 5857 final String permission = permissions[i]; 5858 if (permissionsState.hasPermission(permission, userId)) { 5859 tmp[i] = true; 5860 numMatch++; 5861 } else { 5862 tmp[i] = false; 5863 } 5864 } 5865 if (numMatch == 0) { 5866 return; 5867 } 5868 PackageInfo pi; 5869 if (ps.pkg != null) { 5870 pi = generatePackageInfo(ps.pkg, flags, userId); 5871 } else { 5872 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5873 } 5874 // The above might return null in cases of uninstalled apps or install-state 5875 // skew across users/profiles. 5876 if (pi != null) { 5877 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5878 if (numMatch == permissions.length) { 5879 pi.requestedPermissions = permissions; 5880 } else { 5881 pi.requestedPermissions = new String[numMatch]; 5882 numMatch = 0; 5883 for (int i=0; i<permissions.length; i++) { 5884 if (tmp[i]) { 5885 pi.requestedPermissions[numMatch] = permissions[i]; 5886 numMatch++; 5887 } 5888 } 5889 } 5890 } 5891 list.add(pi); 5892 } 5893 } 5894 5895 @Override 5896 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5897 String[] permissions, int flags, int userId) { 5898 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5899 flags = updateFlagsForPackage(flags, userId, permissions); 5900 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5901 5902 // writer 5903 synchronized (mPackages) { 5904 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5905 boolean[] tmpBools = new boolean[permissions.length]; 5906 if (listUninstalled) { 5907 for (PackageSetting ps : mSettings.mPackages.values()) { 5908 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5909 } 5910 } else { 5911 for (PackageParser.Package pkg : mPackages.values()) { 5912 PackageSetting ps = (PackageSetting)pkg.mExtras; 5913 if (ps != null) { 5914 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5915 userId); 5916 } 5917 } 5918 } 5919 5920 return new ParceledListSlice<PackageInfo>(list); 5921 } 5922 } 5923 5924 @Override 5925 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5926 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5927 flags = updateFlagsForApplication(flags, userId, null); 5928 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5929 5930 // writer 5931 synchronized (mPackages) { 5932 ArrayList<ApplicationInfo> list; 5933 if (listUninstalled) { 5934 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5935 for (PackageSetting ps : mSettings.mPackages.values()) { 5936 ApplicationInfo ai; 5937 if (ps.pkg != null) { 5938 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5939 ps.readUserState(userId), userId); 5940 } else { 5941 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5942 } 5943 if (ai != null) { 5944 list.add(ai); 5945 } 5946 } 5947 } else { 5948 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5949 for (PackageParser.Package p : mPackages.values()) { 5950 if (p.mExtras != null) { 5951 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5952 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5953 if (ai != null) { 5954 list.add(ai); 5955 } 5956 } 5957 } 5958 } 5959 5960 return new ParceledListSlice<ApplicationInfo>(list); 5961 } 5962 } 5963 5964 @Override 5965 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5966 if (DISABLE_EPHEMERAL_APPS) { 5967 return null; 5968 } 5969 5970 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5971 "getEphemeralApplications"); 5972 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5973 "getEphemeralApplications"); 5974 synchronized (mPackages) { 5975 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5976 .getEphemeralApplicationsLPw(userId); 5977 if (ephemeralApps != null) { 5978 return new ParceledListSlice<>(ephemeralApps); 5979 } 5980 } 5981 return null; 5982 } 5983 5984 @Override 5985 public boolean isEphemeralApplication(String packageName, int userId) { 5986 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5987 "isEphemeral"); 5988 if (DISABLE_EPHEMERAL_APPS) { 5989 return false; 5990 } 5991 5992 if (!isCallerSameApp(packageName)) { 5993 return false; 5994 } 5995 synchronized (mPackages) { 5996 PackageParser.Package pkg = mPackages.get(packageName); 5997 if (pkg != null) { 5998 return pkg.applicationInfo.isEphemeralApp(); 5999 } 6000 } 6001 return false; 6002 } 6003 6004 @Override 6005 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6006 if (DISABLE_EPHEMERAL_APPS) { 6007 return null; 6008 } 6009 6010 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6011 "getCookie"); 6012 if (!isCallerSameApp(packageName)) { 6013 return null; 6014 } 6015 synchronized (mPackages) { 6016 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6017 packageName, userId); 6018 } 6019 } 6020 6021 @Override 6022 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6023 if (DISABLE_EPHEMERAL_APPS) { 6024 return true; 6025 } 6026 6027 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6028 "setCookie"); 6029 if (!isCallerSameApp(packageName)) { 6030 return false; 6031 } 6032 synchronized (mPackages) { 6033 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6034 packageName, cookie, userId); 6035 } 6036 } 6037 6038 @Override 6039 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6040 if (DISABLE_EPHEMERAL_APPS) { 6041 return null; 6042 } 6043 6044 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6045 "getEphemeralApplicationIcon"); 6046 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 6047 "getEphemeralApplicationIcon"); 6048 synchronized (mPackages) { 6049 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6050 packageName, userId); 6051 } 6052 } 6053 6054 private boolean isCallerSameApp(String packageName) { 6055 PackageParser.Package pkg = mPackages.get(packageName); 6056 return pkg != null 6057 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6058 } 6059 6060 public List<ApplicationInfo> getPersistentApplications(int flags) { 6061 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6062 6063 // reader 6064 synchronized (mPackages) { 6065 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6066 final int userId = UserHandle.getCallingUserId(); 6067 while (i.hasNext()) { 6068 final PackageParser.Package p = i.next(); 6069 if (p.applicationInfo != null 6070 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 6071 && (!mSafeMode || isSystemApp(p))) { 6072 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6073 if (ps != null) { 6074 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6075 ps.readUserState(userId), userId); 6076 if (ai != null) { 6077 finalList.add(ai); 6078 } 6079 } 6080 } 6081 } 6082 } 6083 6084 return finalList; 6085 } 6086 6087 @Override 6088 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6089 if (!sUserManager.exists(userId)) return null; 6090 flags = updateFlagsForComponent(flags, userId, name); 6091 // reader 6092 synchronized (mPackages) { 6093 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6094 PackageSetting ps = provider != null 6095 ? mSettings.mPackages.get(provider.owner.packageName) 6096 : null; 6097 return ps != null 6098 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6099 ? PackageParser.generateProviderInfo(provider, flags, 6100 ps.readUserState(userId), userId) 6101 : null; 6102 } 6103 } 6104 6105 /** 6106 * @deprecated 6107 */ 6108 @Deprecated 6109 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6110 // reader 6111 synchronized (mPackages) { 6112 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6113 .entrySet().iterator(); 6114 final int userId = UserHandle.getCallingUserId(); 6115 while (i.hasNext()) { 6116 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6117 PackageParser.Provider p = entry.getValue(); 6118 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6119 6120 if (ps != null && p.syncable 6121 && (!mSafeMode || (p.info.applicationInfo.flags 6122 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6123 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6124 ps.readUserState(userId), userId); 6125 if (info != null) { 6126 outNames.add(entry.getKey()); 6127 outInfo.add(info); 6128 } 6129 } 6130 } 6131 } 6132 } 6133 6134 @Override 6135 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6136 int uid, int flags) { 6137 final int userId = processName != null ? UserHandle.getUserId(uid) 6138 : UserHandle.getCallingUserId(); 6139 if (!sUserManager.exists(userId)) return null; 6140 flags = updateFlagsForComponent(flags, userId, processName); 6141 6142 ArrayList<ProviderInfo> finalList = null; 6143 // reader 6144 synchronized (mPackages) { 6145 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6146 while (i.hasNext()) { 6147 final PackageParser.Provider p = i.next(); 6148 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6149 if (ps != null && p.info.authority != null 6150 && (processName == null 6151 || (p.info.processName.equals(processName) 6152 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6153 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6154 if (finalList == null) { 6155 finalList = new ArrayList<ProviderInfo>(3); 6156 } 6157 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6158 ps.readUserState(userId), userId); 6159 if (info != null) { 6160 finalList.add(info); 6161 } 6162 } 6163 } 6164 } 6165 6166 if (finalList != null) { 6167 Collections.sort(finalList, mProviderInitOrderSorter); 6168 return new ParceledListSlice<ProviderInfo>(finalList); 6169 } 6170 6171 return null; 6172 } 6173 6174 @Override 6175 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6176 // reader 6177 synchronized (mPackages) { 6178 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6179 return PackageParser.generateInstrumentationInfo(i, flags); 6180 } 6181 } 6182 6183 @Override 6184 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6185 int flags) { 6186 ArrayList<InstrumentationInfo> finalList = 6187 new ArrayList<InstrumentationInfo>(); 6188 6189 // reader 6190 synchronized (mPackages) { 6191 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6192 while (i.hasNext()) { 6193 final PackageParser.Instrumentation p = i.next(); 6194 if (targetPackage == null 6195 || targetPackage.equals(p.info.targetPackage)) { 6196 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6197 flags); 6198 if (ii != null) { 6199 finalList.add(ii); 6200 } 6201 } 6202 } 6203 } 6204 6205 return finalList; 6206 } 6207 6208 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6209 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6210 if (overlays == null) { 6211 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6212 return; 6213 } 6214 for (PackageParser.Package opkg : overlays.values()) { 6215 // Not much to do if idmap fails: we already logged the error 6216 // and we certainly don't want to abort installation of pkg simply 6217 // because an overlay didn't fit properly. For these reasons, 6218 // ignore the return value of createIdmapForPackagePairLI. 6219 createIdmapForPackagePairLI(pkg, opkg); 6220 } 6221 } 6222 6223 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6224 PackageParser.Package opkg) { 6225 if (!opkg.mTrustedOverlay) { 6226 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6227 opkg.baseCodePath + ": overlay not trusted"); 6228 return false; 6229 } 6230 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6231 if (overlaySet == null) { 6232 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6233 opkg.baseCodePath + " but target package has no known overlays"); 6234 return false; 6235 } 6236 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6237 // TODO: generate idmap for split APKs 6238 try { 6239 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6240 } catch (InstallerException e) { 6241 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6242 + opkg.baseCodePath); 6243 return false; 6244 } 6245 PackageParser.Package[] overlayArray = 6246 overlaySet.values().toArray(new PackageParser.Package[0]); 6247 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6248 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6249 return p1.mOverlayPriority - p2.mOverlayPriority; 6250 } 6251 }; 6252 Arrays.sort(overlayArray, cmp); 6253 6254 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6255 int i = 0; 6256 for (PackageParser.Package p : overlayArray) { 6257 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6258 } 6259 return true; 6260 } 6261 6262 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6263 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6264 try { 6265 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6266 } finally { 6267 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6268 } 6269 } 6270 6271 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6272 final File[] files = dir.listFiles(); 6273 if (ArrayUtils.isEmpty(files)) { 6274 Log.d(TAG, "No files in app dir " + dir); 6275 return; 6276 } 6277 6278 if (DEBUG_PACKAGE_SCANNING) { 6279 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6280 + " flags=0x" + Integer.toHexString(parseFlags)); 6281 } 6282 6283 for (File file : files) { 6284 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6285 && !PackageInstallerService.isStageName(file.getName()); 6286 if (!isPackage) { 6287 // Ignore entries which are not packages 6288 continue; 6289 } 6290 try { 6291 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6292 scanFlags, currentTime, null); 6293 } catch (PackageManagerException e) { 6294 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6295 6296 // Delete invalid userdata apps 6297 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6298 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6299 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6300 removeCodePathLI(file); 6301 } 6302 } 6303 } 6304 } 6305 6306 private static File getSettingsProblemFile() { 6307 File dataDir = Environment.getDataDirectory(); 6308 File systemDir = new File(dataDir, "system"); 6309 File fname = new File(systemDir, "uiderrors.txt"); 6310 return fname; 6311 } 6312 6313 static void reportSettingsProblem(int priority, String msg) { 6314 logCriticalInfo(priority, msg); 6315 } 6316 6317 static void logCriticalInfo(int priority, String msg) { 6318 Slog.println(priority, TAG, msg); 6319 EventLogTags.writePmCriticalInfo(msg); 6320 try { 6321 File fname = getSettingsProblemFile(); 6322 FileOutputStream out = new FileOutputStream(fname, true); 6323 PrintWriter pw = new FastPrintWriter(out); 6324 SimpleDateFormat formatter = new SimpleDateFormat(); 6325 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6326 pw.println(dateString + ": " + msg); 6327 pw.close(); 6328 FileUtils.setPermissions( 6329 fname.toString(), 6330 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6331 -1, -1); 6332 } catch (java.io.IOException e) { 6333 } 6334 } 6335 6336 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6337 int parseFlags) throws PackageManagerException { 6338 if (ps != null 6339 && ps.codePath.equals(srcFile) 6340 && ps.timeStamp == srcFile.lastModified() 6341 && !isCompatSignatureUpdateNeeded(pkg) 6342 && !isRecoverSignatureUpdateNeeded(pkg)) { 6343 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6344 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6345 ArraySet<PublicKey> signingKs; 6346 synchronized (mPackages) { 6347 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6348 } 6349 if (ps.signatures.mSignatures != null 6350 && ps.signatures.mSignatures.length != 0 6351 && signingKs != null) { 6352 // Optimization: reuse the existing cached certificates 6353 // if the package appears to be unchanged. 6354 pkg.mSignatures = ps.signatures.mSignatures; 6355 pkg.mSigningKeys = signingKs; 6356 return; 6357 } 6358 6359 Slog.w(TAG, "PackageSetting for " + ps.name 6360 + " is missing signatures. Collecting certs again to recover them."); 6361 } else { 6362 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6363 } 6364 6365 try { 6366 PackageParser.collectCertificates(pkg, parseFlags); 6367 } catch (PackageParserException e) { 6368 throw PackageManagerException.from(e); 6369 } 6370 } 6371 6372 /** 6373 * Traces a package scan. 6374 * @see #scanPackageLI(File, int, int, long, UserHandle) 6375 */ 6376 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6377 long currentTime, UserHandle user) throws PackageManagerException { 6378 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6379 try { 6380 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6381 } finally { 6382 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6383 } 6384 } 6385 6386 /** 6387 * Scans a package and returns the newly parsed package. 6388 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6389 */ 6390 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6391 long currentTime, UserHandle user) throws PackageManagerException { 6392 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6393 parseFlags |= mDefParseFlags; 6394 PackageParser pp = new PackageParser(); 6395 pp.setSeparateProcesses(mSeparateProcesses); 6396 pp.setOnlyCoreApps(mOnlyCore); 6397 pp.setDisplayMetrics(mMetrics); 6398 6399 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6400 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6401 } 6402 6403 final PackageParser.Package pkg; 6404 try { 6405 pkg = pp.parsePackage(scanFile, parseFlags); 6406 } catch (PackageParserException e) { 6407 throw PackageManagerException.from(e); 6408 } 6409 6410 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6411 } 6412 6413 /** 6414 * Scans a package and returns the newly parsed package. 6415 * @throws PackageManagerException on a parse error. 6416 */ 6417 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6418 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6419 throws PackageManagerException { 6420 // If the package has children and this is the first dive in the function 6421 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6422 // packages (parent and children) would be successfully scanned before the 6423 // actual scan since scanning mutates internal state and we want to atomically 6424 // install the package and its children. 6425 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6426 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6427 scanFlags |= SCAN_CHECK_ONLY; 6428 } 6429 } else { 6430 scanFlags &= ~SCAN_CHECK_ONLY; 6431 } 6432 6433 // Scan the parent 6434 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6435 scanFlags, currentTime, user); 6436 6437 // Scan the children 6438 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6439 for (int i = 0; i < childCount; i++) { 6440 PackageParser.Package childPackage = pkg.childPackages.get(i); 6441 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6442 currentTime, user); 6443 } 6444 6445 6446 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6447 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6448 } 6449 6450 return scannedPkg; 6451 } 6452 6453 /** 6454 * Scans a package and returns the newly parsed package. 6455 * @throws PackageManagerException on a parse error. 6456 */ 6457 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6458 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6459 throws PackageManagerException { 6460 PackageSetting ps = null; 6461 PackageSetting updatedPkg; 6462 // reader 6463 synchronized (mPackages) { 6464 // Look to see if we already know about this package. 6465 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6466 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6467 // This package has been renamed to its original name. Let's 6468 // use that. 6469 ps = mSettings.peekPackageLPr(oldName); 6470 } 6471 // If there was no original package, see one for the real package name. 6472 if (ps == null) { 6473 ps = mSettings.peekPackageLPr(pkg.packageName); 6474 } 6475 // Check to see if this package could be hiding/updating a system 6476 // package. Must look for it either under the original or real 6477 // package name depending on our state. 6478 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6479 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6480 6481 // If this is a package we don't know about on the system partition, we 6482 // may need to remove disabled child packages on the system partition 6483 // or may need to not add child packages if the parent apk is updated 6484 // on the data partition and no longer defines this child package. 6485 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6486 // If this is a parent package for an updated system app and this system 6487 // app got an OTA update which no longer defines some of the child packages 6488 // we have to prune them from the disabled system packages. 6489 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6490 if (disabledPs != null) { 6491 final int scannedChildCount = (pkg.childPackages != null) 6492 ? pkg.childPackages.size() : 0; 6493 final int disabledChildCount = disabledPs.childPackageNames != null 6494 ? disabledPs.childPackageNames.size() : 0; 6495 for (int i = 0; i < disabledChildCount; i++) { 6496 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6497 boolean disabledPackageAvailable = false; 6498 for (int j = 0; j < scannedChildCount; j++) { 6499 PackageParser.Package childPkg = pkg.childPackages.get(j); 6500 if (childPkg.packageName.equals(disabledChildPackageName)) { 6501 disabledPackageAvailable = true; 6502 break; 6503 } 6504 } 6505 if (!disabledPackageAvailable) { 6506 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6507 } 6508 } 6509 } 6510 } 6511 } 6512 6513 boolean updatedPkgBetter = false; 6514 // First check if this is a system package that may involve an update 6515 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6516 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6517 // it needs to drop FLAG_PRIVILEGED. 6518 if (locationIsPrivileged(scanFile)) { 6519 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6520 } else { 6521 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6522 } 6523 6524 if (ps != null && !ps.codePath.equals(scanFile)) { 6525 // The path has changed from what was last scanned... check the 6526 // version of the new path against what we have stored to determine 6527 // what to do. 6528 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6529 if (pkg.mVersionCode <= ps.versionCode) { 6530 // The system package has been updated and the code path does not match 6531 // Ignore entry. Skip it. 6532 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6533 + " ignored: updated version " + ps.versionCode 6534 + " better than this " + pkg.mVersionCode); 6535 if (!updatedPkg.codePath.equals(scanFile)) { 6536 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6537 + ps.name + " changing from " + updatedPkg.codePathString 6538 + " to " + scanFile); 6539 updatedPkg.codePath = scanFile; 6540 updatedPkg.codePathString = scanFile.toString(); 6541 updatedPkg.resourcePath = scanFile; 6542 updatedPkg.resourcePathString = scanFile.toString(); 6543 } 6544 updatedPkg.pkg = pkg; 6545 updatedPkg.versionCode = pkg.mVersionCode; 6546 6547 // Update the disabled system child packages to point to the package too. 6548 final int childCount = updatedPkg.childPackageNames != null 6549 ? updatedPkg.childPackageNames.size() : 0; 6550 for (int i = 0; i < childCount; i++) { 6551 String childPackageName = updatedPkg.childPackageNames.get(i); 6552 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6553 childPackageName); 6554 if (updatedChildPkg != null) { 6555 updatedChildPkg.pkg = pkg; 6556 updatedChildPkg.versionCode = pkg.mVersionCode; 6557 } 6558 } 6559 6560 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6561 + scanFile + " ignored: updated version " + ps.versionCode 6562 + " better than this " + pkg.mVersionCode); 6563 } else { 6564 // The current app on the system partition is better than 6565 // what we have updated to on the data partition; switch 6566 // back to the system partition version. 6567 // At this point, its safely assumed that package installation for 6568 // apps in system partition will go through. If not there won't be a working 6569 // version of the app 6570 // writer 6571 synchronized (mPackages) { 6572 // Just remove the loaded entries from package lists. 6573 mPackages.remove(ps.name); 6574 } 6575 6576 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6577 + " reverting from " + ps.codePathString 6578 + ": new version " + pkg.mVersionCode 6579 + " better than installed " + ps.versionCode); 6580 6581 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6582 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6583 synchronized (mInstallLock) { 6584 args.cleanUpResourcesLI(); 6585 } 6586 synchronized (mPackages) { 6587 mSettings.enableSystemPackageLPw(ps.name); 6588 } 6589 updatedPkgBetter = true; 6590 } 6591 } 6592 } 6593 6594 if (updatedPkg != null) { 6595 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6596 // initially 6597 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6598 6599 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6600 // flag set initially 6601 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6602 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6603 } 6604 } 6605 6606 // Verify certificates against what was last scanned 6607 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6608 6609 /* 6610 * A new system app appeared, but we already had a non-system one of the 6611 * same name installed earlier. 6612 */ 6613 boolean shouldHideSystemApp = false; 6614 if (updatedPkg == null && ps != null 6615 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6616 /* 6617 * Check to make sure the signatures match first. If they don't, 6618 * wipe the installed application and its data. 6619 */ 6620 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6621 != PackageManager.SIGNATURE_MATCH) { 6622 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6623 + " signatures don't match existing userdata copy; removing"); 6624 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6625 ps = null; 6626 } else { 6627 /* 6628 * If the newly-added system app is an older version than the 6629 * already installed version, hide it. It will be scanned later 6630 * and re-added like an update. 6631 */ 6632 if (pkg.mVersionCode <= ps.versionCode) { 6633 shouldHideSystemApp = true; 6634 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6635 + " but new version " + pkg.mVersionCode + " better than installed " 6636 + ps.versionCode + "; hiding system"); 6637 } else { 6638 /* 6639 * The newly found system app is a newer version that the 6640 * one previously installed. Simply remove the 6641 * already-installed application and replace it with our own 6642 * while keeping the application data. 6643 */ 6644 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6645 + " reverting from " + ps.codePathString + ": new version " 6646 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6647 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6648 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6649 synchronized (mInstallLock) { 6650 args.cleanUpResourcesLI(); 6651 } 6652 } 6653 } 6654 } 6655 6656 // The apk is forward locked (not public) if its code and resources 6657 // are kept in different files. (except for app in either system or 6658 // vendor path). 6659 // TODO grab this value from PackageSettings 6660 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6661 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6662 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6663 } 6664 } 6665 6666 // TODO: extend to support forward-locked splits 6667 String resourcePath = null; 6668 String baseResourcePath = null; 6669 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6670 if (ps != null && ps.resourcePathString != null) { 6671 resourcePath = ps.resourcePathString; 6672 baseResourcePath = ps.resourcePathString; 6673 } else { 6674 // Should not happen at all. Just log an error. 6675 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6676 } 6677 } else { 6678 resourcePath = pkg.codePath; 6679 baseResourcePath = pkg.baseCodePath; 6680 } 6681 6682 // Set application objects path explicitly. 6683 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6684 pkg.setApplicationInfoCodePath(pkg.codePath); 6685 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6686 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6687 pkg.setApplicationInfoResourcePath(resourcePath); 6688 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6689 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6690 6691 // Note that we invoke the following method only if we are about to unpack an application 6692 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6693 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6694 6695 /* 6696 * If the system app should be overridden by a previously installed 6697 * data, hide the system app now and let the /data/app scan pick it up 6698 * again. 6699 */ 6700 if (shouldHideSystemApp) { 6701 synchronized (mPackages) { 6702 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6703 } 6704 } 6705 6706 return scannedPkg; 6707 } 6708 6709 private static String fixProcessName(String defProcessName, 6710 String processName, int uid) { 6711 if (processName == null) { 6712 return defProcessName; 6713 } 6714 return processName; 6715 } 6716 6717 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6718 throws PackageManagerException { 6719 if (pkgSetting.signatures.mSignatures != null) { 6720 // Already existing package. Make sure signatures match 6721 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6722 == PackageManager.SIGNATURE_MATCH; 6723 if (!match) { 6724 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6725 == PackageManager.SIGNATURE_MATCH; 6726 } 6727 if (!match) { 6728 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6729 == PackageManager.SIGNATURE_MATCH; 6730 } 6731 if (!match) { 6732 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6733 + pkg.packageName + " signatures do not match the " 6734 + "previously installed version; ignoring!"); 6735 } 6736 } 6737 6738 // Check for shared user signatures 6739 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6740 // Already existing package. Make sure signatures match 6741 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6742 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6743 if (!match) { 6744 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6745 == PackageManager.SIGNATURE_MATCH; 6746 } 6747 if (!match) { 6748 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6749 == PackageManager.SIGNATURE_MATCH; 6750 } 6751 if (!match) { 6752 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6753 "Package " + pkg.packageName 6754 + " has no signatures that match those in shared user " 6755 + pkgSetting.sharedUser.name + "; ignoring!"); 6756 } 6757 } 6758 } 6759 6760 /** 6761 * Enforces that only the system UID or root's UID can call a method exposed 6762 * via Binder. 6763 * 6764 * @param message used as message if SecurityException is thrown 6765 * @throws SecurityException if the caller is not system or root 6766 */ 6767 private static final void enforceSystemOrRoot(String message) { 6768 final int uid = Binder.getCallingUid(); 6769 if (uid != Process.SYSTEM_UID && uid != 0) { 6770 throw new SecurityException(message); 6771 } 6772 } 6773 6774 @Override 6775 public void performFstrimIfNeeded() { 6776 enforceSystemOrRoot("Only the system can request fstrim"); 6777 6778 // Before everything else, see whether we need to fstrim. 6779 try { 6780 IMountService ms = PackageHelper.getMountService(); 6781 if (ms != null) { 6782 final boolean isUpgrade = isUpgrade(); 6783 boolean doTrim = isUpgrade; 6784 if (doTrim) { 6785 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6786 } else { 6787 final long interval = android.provider.Settings.Global.getLong( 6788 mContext.getContentResolver(), 6789 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6790 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6791 if (interval > 0) { 6792 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6793 if (timeSinceLast > interval) { 6794 doTrim = true; 6795 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6796 + "; running immediately"); 6797 } 6798 } 6799 } 6800 if (doTrim) { 6801 if (!isFirstBoot()) { 6802 try { 6803 ActivityManagerNative.getDefault().showBootMessage( 6804 mContext.getResources().getString( 6805 R.string.android_upgrading_fstrim), true); 6806 } catch (RemoteException e) { 6807 } 6808 } 6809 ms.runMaintenance(); 6810 } 6811 } else { 6812 Slog.e(TAG, "Mount service unavailable!"); 6813 } 6814 } catch (RemoteException e) { 6815 // Can't happen; MountService is local 6816 } 6817 } 6818 6819 @Override 6820 public void extractPackagesIfNeeded() { 6821 enforceSystemOrRoot("Only the system can request package extraction"); 6822 6823 // Extract pacakges only if profile-guided compilation is enabled because 6824 // otherwise BackgroundDexOptService will not dexopt them later. 6825 if (mUseJitProfiles) { 6826 List<PackageParser.Package> pkgs; 6827 synchronized (mPackages) { 6828 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6829 } 6830 for (PackageParser.Package pkg : pkgs) { 6831 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6832 performDexOpt(pkg.packageName, null /* instructionSet */, 6833 false /* useProfiles */, true /* extractOnly */, false /* force */); 6834 } 6835 } 6836 } 6837 } 6838 6839 @Override 6840 public void notifyPackageUse(String packageName) { 6841 synchronized (mPackages) { 6842 PackageParser.Package p = mPackages.get(packageName); 6843 if (p == null) { 6844 return; 6845 } 6846 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6847 } 6848 } 6849 6850 // TODO: this is not used nor needed. Delete it. 6851 @Override 6852 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6853 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6854 false /* extractOnly */, false /* force */); 6855 } 6856 6857 @Override 6858 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6859 boolean extractOnly, boolean force) { 6860 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6861 } 6862 6863 private boolean performDexOptTraced(String packageName, String instructionSet, 6864 boolean useProfiles, boolean extractOnly, boolean force) { 6865 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6866 try { 6867 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6868 force); 6869 } finally { 6870 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6871 } 6872 } 6873 6874 private boolean performDexOptInternal(String packageName, String instructionSet, 6875 boolean useProfiles, boolean extractOnly, boolean force) { 6876 PackageParser.Package p; 6877 final String targetInstructionSet; 6878 synchronized (mPackages) { 6879 p = mPackages.get(packageName); 6880 if (p == null) { 6881 return false; 6882 } 6883 mPackageUsage.write(false); 6884 6885 targetInstructionSet = instructionSet != null ? instructionSet : 6886 getPrimaryInstructionSet(p.applicationInfo); 6887 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6888 // Skip only if we do not use profiles since they might trigger a recompilation. 6889 return false; 6890 } 6891 } 6892 long callingId = Binder.clearCallingIdentity(); 6893 try { 6894 synchronized (mInstallLock) { 6895 final String[] instructionSets = new String[] { targetInstructionSet }; 6896 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6897 useProfiles, extractOnly, force); 6898 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6899 } 6900 } finally { 6901 Binder.restoreCallingIdentity(callingId); 6902 } 6903 } 6904 6905 public ArraySet<String> getOptimizablePackages() { 6906 ArraySet<String> pkgs = new ArraySet<String>(); 6907 synchronized (mPackages) { 6908 for (PackageParser.Package p : mPackages.values()) { 6909 if (PackageDexOptimizer.canOptimizePackage(p)) { 6910 pkgs.add(p.packageName); 6911 } 6912 } 6913 } 6914 return pkgs; 6915 } 6916 6917 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6918 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6919 // Select the dex optimizer based on the force parameter. 6920 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6921 // allocate an object here. 6922 PackageDexOptimizer pdo = force 6923 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6924 : mPackageDexOptimizer; 6925 6926 // Optimize all dependencies first. Note: we ignore the return value and march on 6927 // on errors. 6928 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6929 if (!deps.isEmpty()) { 6930 for (PackageParser.Package depPackage : deps) { 6931 // TODO: Analyze and investigate if we (should) profile libraries. 6932 // Currently this will do a full compilation of the library. 6933 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6934 false /* extractOnly */); 6935 } 6936 } 6937 6938 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6939 } 6940 6941 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6942 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6943 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6944 Set<String> collectedNames = new HashSet<>(); 6945 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6946 6947 retValue.remove(p); 6948 6949 return retValue; 6950 } else { 6951 return Collections.emptyList(); 6952 } 6953 } 6954 6955 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6956 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6957 if (!collectedNames.contains(p.packageName)) { 6958 collectedNames.add(p.packageName); 6959 collected.add(p); 6960 6961 if (p.usesLibraries != null) { 6962 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6963 } 6964 if (p.usesOptionalLibraries != null) { 6965 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 6966 collectedNames); 6967 } 6968 } 6969 } 6970 6971 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 6972 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6973 for (String libName : libs) { 6974 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 6975 if (libPkg != null) { 6976 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 6977 } 6978 } 6979 } 6980 6981 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 6982 synchronized (mPackages) { 6983 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 6984 if (lib != null && lib.apk != null) { 6985 return mPackages.get(lib.apk); 6986 } 6987 } 6988 return null; 6989 } 6990 6991 public void shutdown() { 6992 mPackageUsage.write(true); 6993 } 6994 6995 @Override 6996 public void forceDexOpt(String packageName) { 6997 enforceSystemOrRoot("forceDexOpt"); 6998 6999 PackageParser.Package pkg; 7000 synchronized (mPackages) { 7001 pkg = mPackages.get(packageName); 7002 if (pkg == null) { 7003 throw new IllegalArgumentException("Unknown package: " + packageName); 7004 } 7005 } 7006 7007 synchronized (mInstallLock) { 7008 final String[] instructionSets = new String[] { 7009 getPrimaryInstructionSet(pkg.applicationInfo) }; 7010 7011 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7012 7013 // Whoever is calling forceDexOpt wants a fully compiled package. 7014 // Don't use profiles since that may cause compilation to be skipped. 7015 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7016 false /* useProfiles */, false /* extractOnly */, true /* force */); 7017 7018 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7019 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7020 throw new IllegalStateException("Failed to dexopt: " + res); 7021 } 7022 } 7023 } 7024 7025 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7026 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7027 Slog.w(TAG, "Unable to update from " + oldPkg.name 7028 + " to " + newPkg.packageName 7029 + ": old package not in system partition"); 7030 return false; 7031 } else if (mPackages.get(oldPkg.name) != null) { 7032 Slog.w(TAG, "Unable to update from " + oldPkg.name 7033 + " to " + newPkg.packageName 7034 + ": old package still exists"); 7035 return false; 7036 } 7037 return true; 7038 } 7039 7040 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7041 // TODO: triage flags as part of 26466827 7042 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7043 7044 boolean res = true; 7045 final int[] users = sUserManager.getUserIds(); 7046 for (int user : users) { 7047 try { 7048 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7049 } catch (InstallerException e) { 7050 Slog.w(TAG, "Failed to delete data directory", e); 7051 res = false; 7052 } 7053 } 7054 return res; 7055 } 7056 7057 void removeCodePathLI(File codePath) { 7058 if (codePath.isDirectory()) { 7059 try { 7060 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7061 } catch (InstallerException e) { 7062 Slog.w(TAG, "Failed to remove code path", e); 7063 } 7064 } else { 7065 codePath.delete(); 7066 } 7067 } 7068 7069 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7070 try { 7071 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7072 } catch (InstallerException e) { 7073 Slog.w(TAG, "Failed to destroy app data", e); 7074 } 7075 } 7076 7077 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7078 int appId, String seinfo) { 7079 try { 7080 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7081 } catch (InstallerException e) { 7082 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7083 } 7084 } 7085 7086 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7087 final PackageParser.Package pkg; 7088 synchronized (mPackages) { 7089 pkg = mPackages.get(packageName); 7090 } 7091 if (pkg == null) { 7092 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7093 return; 7094 } 7095 deleteCodeCacheDirsLI(pkg); 7096 } 7097 7098 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7099 // TODO: triage flags as part of 26466827 7100 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7101 7102 int[] users = sUserManager.getUserIds(); 7103 int res = 0; 7104 for (int user : users) { 7105 // Remove the parent code cache 7106 try { 7107 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7108 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7109 } catch (InstallerException e) { 7110 Slog.w(TAG, "Failed to delete code cache directory", e); 7111 } 7112 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7113 for (int i = 0; i < childCount; i++) { 7114 PackageParser.Package childPkg = pkg.childPackages.get(i); 7115 // Remove the child code cache 7116 try { 7117 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7118 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7119 } catch (InstallerException e) { 7120 Slog.w(TAG, "Failed to delete code cache directory", e); 7121 } 7122 } 7123 } 7124 } 7125 7126 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7127 long lastUpdateTime) { 7128 // Set parent install/update time 7129 PackageSetting ps = (PackageSetting) pkg.mExtras; 7130 if (ps != null) { 7131 ps.firstInstallTime = firstInstallTime; 7132 ps.lastUpdateTime = lastUpdateTime; 7133 } 7134 // Set children install/update time 7135 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7136 for (int i = 0; i < childCount; i++) { 7137 PackageParser.Package childPkg = pkg.childPackages.get(i); 7138 ps = (PackageSetting) childPkg.mExtras; 7139 if (ps != null) { 7140 ps.firstInstallTime = firstInstallTime; 7141 ps.lastUpdateTime = lastUpdateTime; 7142 } 7143 } 7144 } 7145 7146 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7147 PackageParser.Package changingLib) { 7148 if (file.path != null) { 7149 usesLibraryFiles.add(file.path); 7150 return; 7151 } 7152 PackageParser.Package p = mPackages.get(file.apk); 7153 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7154 // If we are doing this while in the middle of updating a library apk, 7155 // then we need to make sure to use that new apk for determining the 7156 // dependencies here. (We haven't yet finished committing the new apk 7157 // to the package manager state.) 7158 if (p == null || p.packageName.equals(changingLib.packageName)) { 7159 p = changingLib; 7160 } 7161 } 7162 if (p != null) { 7163 usesLibraryFiles.addAll(p.getAllCodePaths()); 7164 } 7165 } 7166 7167 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7168 PackageParser.Package changingLib) throws PackageManagerException { 7169 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7170 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7171 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7172 for (int i=0; i<N; i++) { 7173 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7174 if (file == null) { 7175 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7176 "Package " + pkg.packageName + " requires unavailable shared library " 7177 + pkg.usesLibraries.get(i) + "; failing!"); 7178 } 7179 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7180 } 7181 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7182 for (int i=0; i<N; i++) { 7183 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7184 if (file == null) { 7185 Slog.w(TAG, "Package " + pkg.packageName 7186 + " desires unavailable shared library " 7187 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7188 } else { 7189 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7190 } 7191 } 7192 N = usesLibraryFiles.size(); 7193 if (N > 0) { 7194 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7195 } else { 7196 pkg.usesLibraryFiles = null; 7197 } 7198 } 7199 } 7200 7201 private static boolean hasString(List<String> list, List<String> which) { 7202 if (list == null) { 7203 return false; 7204 } 7205 for (int i=list.size()-1; i>=0; i--) { 7206 for (int j=which.size()-1; j>=0; j--) { 7207 if (which.get(j).equals(list.get(i))) { 7208 return true; 7209 } 7210 } 7211 } 7212 return false; 7213 } 7214 7215 private void updateAllSharedLibrariesLPw() { 7216 for (PackageParser.Package pkg : mPackages.values()) { 7217 try { 7218 updateSharedLibrariesLPw(pkg, null); 7219 } catch (PackageManagerException e) { 7220 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7221 } 7222 } 7223 } 7224 7225 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7226 PackageParser.Package changingPkg) { 7227 ArrayList<PackageParser.Package> res = null; 7228 for (PackageParser.Package pkg : mPackages.values()) { 7229 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7230 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7231 if (res == null) { 7232 res = new ArrayList<PackageParser.Package>(); 7233 } 7234 res.add(pkg); 7235 try { 7236 updateSharedLibrariesLPw(pkg, changingPkg); 7237 } catch (PackageManagerException e) { 7238 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7239 } 7240 } 7241 } 7242 return res; 7243 } 7244 7245 /** 7246 * Derive the value of the {@code cpuAbiOverride} based on the provided 7247 * value and an optional stored value from the package settings. 7248 */ 7249 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7250 String cpuAbiOverride = null; 7251 7252 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7253 cpuAbiOverride = null; 7254 } else if (abiOverride != null) { 7255 cpuAbiOverride = abiOverride; 7256 } else if (settings != null) { 7257 cpuAbiOverride = settings.cpuAbiOverrideString; 7258 } 7259 7260 return cpuAbiOverride; 7261 } 7262 7263 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7264 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7265 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7266 // If the package has children and this is the first dive in the function 7267 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7268 // whether all packages (parent and children) would be successfully scanned 7269 // before the actual scan since scanning mutates internal state and we want 7270 // to atomically install the package and its children. 7271 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7272 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7273 scanFlags |= SCAN_CHECK_ONLY; 7274 } 7275 } else { 7276 scanFlags &= ~SCAN_CHECK_ONLY; 7277 } 7278 7279 final PackageParser.Package scannedPkg; 7280 try { 7281 // Scan the parent 7282 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7283 // Scan the children 7284 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7285 for (int i = 0; i < childCount; i++) { 7286 PackageParser.Package childPkg = pkg.childPackages.get(i); 7287 scanPackageLI(childPkg, parseFlags, 7288 scanFlags, currentTime, user); 7289 } 7290 } finally { 7291 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7292 } 7293 7294 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7295 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7296 } 7297 7298 return scannedPkg; 7299 } 7300 7301 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7302 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7303 boolean success = false; 7304 try { 7305 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7306 currentTime, user); 7307 success = true; 7308 return res; 7309 } finally { 7310 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7311 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7312 } 7313 } 7314 } 7315 7316 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7317 int scanFlags, long currentTime, UserHandle user) 7318 throws PackageManagerException { 7319 final File scanFile = new File(pkg.codePath); 7320 if (pkg.applicationInfo.getCodePath() == null || 7321 pkg.applicationInfo.getResourcePath() == null) { 7322 // Bail out. The resource and code paths haven't been set. 7323 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7324 "Code and resource paths haven't been set correctly"); 7325 } 7326 7327 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7328 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7329 } else { 7330 // Only allow system apps to be flagged as core apps. 7331 pkg.coreApp = false; 7332 } 7333 7334 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7335 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7336 } 7337 7338 if (mCustomResolverComponentName != null && 7339 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7340 setUpCustomResolverActivity(pkg); 7341 } 7342 7343 if (pkg.packageName.equals("android")) { 7344 synchronized (mPackages) { 7345 if (mAndroidApplication != null) { 7346 Slog.w(TAG, "*************************************************"); 7347 Slog.w(TAG, "Core android package being redefined. Skipping."); 7348 Slog.w(TAG, " file=" + scanFile); 7349 Slog.w(TAG, "*************************************************"); 7350 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7351 "Core android package being redefined. Skipping."); 7352 } 7353 7354 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7355 // Set up information for our fall-back user intent resolution activity. 7356 mPlatformPackage = pkg; 7357 pkg.mVersionCode = mSdkVersion; 7358 mAndroidApplication = pkg.applicationInfo; 7359 7360 if (!mResolverReplaced) { 7361 mResolveActivity.applicationInfo = mAndroidApplication; 7362 mResolveActivity.name = ResolverActivity.class.getName(); 7363 mResolveActivity.packageName = mAndroidApplication.packageName; 7364 mResolveActivity.processName = "system:ui"; 7365 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7366 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7367 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7368 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7369 mResolveActivity.exported = true; 7370 mResolveActivity.enabled = true; 7371 mResolveInfo.activityInfo = mResolveActivity; 7372 mResolveInfo.priority = 0; 7373 mResolveInfo.preferredOrder = 0; 7374 mResolveInfo.match = 0; 7375 mResolveComponentName = new ComponentName( 7376 mAndroidApplication.packageName, mResolveActivity.name); 7377 } 7378 } 7379 } 7380 } 7381 7382 if (DEBUG_PACKAGE_SCANNING) { 7383 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7384 Log.d(TAG, "Scanning package " + pkg.packageName); 7385 } 7386 7387 synchronized (mPackages) { 7388 if (mPackages.containsKey(pkg.packageName) 7389 || mSharedLibraries.containsKey(pkg.packageName)) { 7390 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7391 "Application package " + pkg.packageName 7392 + " already installed. Skipping duplicate."); 7393 } 7394 7395 // If we're only installing presumed-existing packages, require that the 7396 // scanned APK is both already known and at the path previously established 7397 // for it. Previously unknown packages we pick up normally, but if we have an 7398 // a priori expectation about this package's install presence, enforce it. 7399 // With a singular exception for new system packages. When an OTA contains 7400 // a new system package, we allow the codepath to change from a system location 7401 // to the user-installed location. If we don't allow this change, any newer, 7402 // user-installed version of the application will be ignored. 7403 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7404 if (mExpectingBetter.containsKey(pkg.packageName)) { 7405 logCriticalInfo(Log.WARN, 7406 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7407 } else { 7408 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7409 if (known != null) { 7410 if (DEBUG_PACKAGE_SCANNING) { 7411 Log.d(TAG, "Examining " + pkg.codePath 7412 + " and requiring known paths " + known.codePathString 7413 + " & " + known.resourcePathString); 7414 } 7415 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7416 || !pkg.applicationInfo.getResourcePath().equals( 7417 known.resourcePathString)) { 7418 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7419 "Application package " + pkg.packageName 7420 + " found at " + pkg.applicationInfo.getCodePath() 7421 + " but expected at " + known.codePathString 7422 + "; ignoring."); 7423 } 7424 } 7425 } 7426 } 7427 } 7428 7429 // Initialize package source and resource directories 7430 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7431 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7432 7433 SharedUserSetting suid = null; 7434 PackageSetting pkgSetting = null; 7435 7436 if (!isSystemApp(pkg)) { 7437 // Only system apps can use these features. 7438 pkg.mOriginalPackages = null; 7439 pkg.mRealPackage = null; 7440 pkg.mAdoptPermissions = null; 7441 } 7442 7443 // Getting the package setting may have a side-effect, so if we 7444 // are only checking if scan would succeed, stash a copy of the 7445 // old setting to restore at the end. 7446 PackageSetting nonMutatedPs = null; 7447 7448 // writer 7449 synchronized (mPackages) { 7450 if (pkg.mSharedUserId != null) { 7451 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7452 if (suid == null) { 7453 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7454 "Creating application package " + pkg.packageName 7455 + " for shared user failed"); 7456 } 7457 if (DEBUG_PACKAGE_SCANNING) { 7458 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7459 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7460 + "): packages=" + suid.packages); 7461 } 7462 } 7463 7464 // Check if we are renaming from an original package name. 7465 PackageSetting origPackage = null; 7466 String realName = null; 7467 if (pkg.mOriginalPackages != null) { 7468 // This package may need to be renamed to a previously 7469 // installed name. Let's check on that... 7470 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7471 if (pkg.mOriginalPackages.contains(renamed)) { 7472 // This package had originally been installed as the 7473 // original name, and we have already taken care of 7474 // transitioning to the new one. Just update the new 7475 // one to continue using the old name. 7476 realName = pkg.mRealPackage; 7477 if (!pkg.packageName.equals(renamed)) { 7478 // Callers into this function may have already taken 7479 // care of renaming the package; only do it here if 7480 // it is not already done. 7481 pkg.setPackageName(renamed); 7482 } 7483 7484 } else { 7485 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7486 if ((origPackage = mSettings.peekPackageLPr( 7487 pkg.mOriginalPackages.get(i))) != null) { 7488 // We do have the package already installed under its 7489 // original name... should we use it? 7490 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7491 // New package is not compatible with original. 7492 origPackage = null; 7493 continue; 7494 } else if (origPackage.sharedUser != null) { 7495 // Make sure uid is compatible between packages. 7496 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7497 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7498 + " to " + pkg.packageName + ": old uid " 7499 + origPackage.sharedUser.name 7500 + " differs from " + pkg.mSharedUserId); 7501 origPackage = null; 7502 continue; 7503 } 7504 } else { 7505 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7506 + pkg.packageName + " to old name " + origPackage.name); 7507 } 7508 break; 7509 } 7510 } 7511 } 7512 } 7513 7514 if (mTransferedPackages.contains(pkg.packageName)) { 7515 Slog.w(TAG, "Package " + pkg.packageName 7516 + " was transferred to another, but its .apk remains"); 7517 } 7518 7519 // See comments in nonMutatedPs declaration 7520 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7521 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7522 if (foundPs != null) { 7523 nonMutatedPs = new PackageSetting(foundPs); 7524 } 7525 } 7526 7527 // Just create the setting, don't add it yet. For already existing packages 7528 // the PkgSetting exists already and doesn't have to be created. 7529 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7530 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7531 pkg.applicationInfo.primaryCpuAbi, 7532 pkg.applicationInfo.secondaryCpuAbi, 7533 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7534 user, false); 7535 if (pkgSetting == null) { 7536 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7537 "Creating application package " + pkg.packageName + " failed"); 7538 } 7539 7540 if (pkgSetting.origPackage != null) { 7541 // If we are first transitioning from an original package, 7542 // fix up the new package's name now. We need to do this after 7543 // looking up the package under its new name, so getPackageLP 7544 // can take care of fiddling things correctly. 7545 pkg.setPackageName(origPackage.name); 7546 7547 // File a report about this. 7548 String msg = "New package " + pkgSetting.realName 7549 + " renamed to replace old package " + pkgSetting.name; 7550 reportSettingsProblem(Log.WARN, msg); 7551 7552 // Make a note of it. 7553 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7554 mTransferedPackages.add(origPackage.name); 7555 } 7556 7557 // No longer need to retain this. 7558 pkgSetting.origPackage = null; 7559 } 7560 7561 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7562 // Make a note of it. 7563 mTransferedPackages.add(pkg.packageName); 7564 } 7565 7566 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7567 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7568 } 7569 7570 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7571 // Check all shared libraries and map to their actual file path. 7572 // We only do this here for apps not on a system dir, because those 7573 // are the only ones that can fail an install due to this. We 7574 // will take care of the system apps by updating all of their 7575 // library paths after the scan is done. 7576 updateSharedLibrariesLPw(pkg, null); 7577 } 7578 7579 if (mFoundPolicyFile) { 7580 SELinuxMMAC.assignSeinfoValue(pkg); 7581 } 7582 7583 pkg.applicationInfo.uid = pkgSetting.appId; 7584 pkg.mExtras = pkgSetting; 7585 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7586 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7587 // We just determined the app is signed correctly, so bring 7588 // over the latest parsed certs. 7589 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7590 } else { 7591 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7592 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7593 "Package " + pkg.packageName + " upgrade keys do not match the " 7594 + "previously installed version"); 7595 } else { 7596 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7597 String msg = "System package " + pkg.packageName 7598 + " signature changed; retaining data."; 7599 reportSettingsProblem(Log.WARN, msg); 7600 } 7601 } 7602 } else { 7603 try { 7604 verifySignaturesLP(pkgSetting, pkg); 7605 // We just determined the app is signed correctly, so bring 7606 // over the latest parsed certs. 7607 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7608 } catch (PackageManagerException e) { 7609 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7610 throw e; 7611 } 7612 // The signature has changed, but this package is in the system 7613 // image... let's recover! 7614 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7615 // However... if this package is part of a shared user, but it 7616 // doesn't match the signature of the shared user, let's fail. 7617 // What this means is that you can't change the signatures 7618 // associated with an overall shared user, which doesn't seem all 7619 // that unreasonable. 7620 if (pkgSetting.sharedUser != null) { 7621 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7622 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7623 throw new PackageManagerException( 7624 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7625 "Signature mismatch for shared user: " 7626 + pkgSetting.sharedUser); 7627 } 7628 } 7629 // File a report about this. 7630 String msg = "System package " + pkg.packageName 7631 + " signature changed; retaining data."; 7632 reportSettingsProblem(Log.WARN, msg); 7633 } 7634 } 7635 // Verify that this new package doesn't have any content providers 7636 // that conflict with existing packages. Only do this if the 7637 // package isn't already installed, since we don't want to break 7638 // things that are installed. 7639 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7640 final int N = pkg.providers.size(); 7641 int i; 7642 for (i=0; i<N; i++) { 7643 PackageParser.Provider p = pkg.providers.get(i); 7644 if (p.info.authority != null) { 7645 String names[] = p.info.authority.split(";"); 7646 for (int j = 0; j < names.length; j++) { 7647 if (mProvidersByAuthority.containsKey(names[j])) { 7648 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7649 final String otherPackageName = 7650 ((other != null && other.getComponentName() != null) ? 7651 other.getComponentName().getPackageName() : "?"); 7652 throw new PackageManagerException( 7653 INSTALL_FAILED_CONFLICTING_PROVIDER, 7654 "Can't install because provider name " + names[j] 7655 + " (in package " + pkg.applicationInfo.packageName 7656 + ") is already used by " + otherPackageName); 7657 } 7658 } 7659 } 7660 } 7661 } 7662 7663 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7664 // This package wants to adopt ownership of permissions from 7665 // another package. 7666 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7667 final String origName = pkg.mAdoptPermissions.get(i); 7668 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7669 if (orig != null) { 7670 if (verifyPackageUpdateLPr(orig, pkg)) { 7671 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7672 + pkg.packageName); 7673 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7674 } 7675 } 7676 } 7677 } 7678 } 7679 7680 final String pkgName = pkg.packageName; 7681 7682 final long scanFileTime = scanFile.lastModified(); 7683 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7684 pkg.applicationInfo.processName = fixProcessName( 7685 pkg.applicationInfo.packageName, 7686 pkg.applicationInfo.processName, 7687 pkg.applicationInfo.uid); 7688 7689 if (pkg != mPlatformPackage) { 7690 // Get all of our default paths setup 7691 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7692 } 7693 7694 final String path = scanFile.getPath(); 7695 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7696 7697 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7698 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7699 7700 // Some system apps still use directory structure for native libraries 7701 // in which case we might end up not detecting abi solely based on apk 7702 // structure. Try to detect abi based on directory structure. 7703 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7704 pkg.applicationInfo.primaryCpuAbi == null) { 7705 setBundledAppAbisAndRoots(pkg, pkgSetting); 7706 setNativeLibraryPaths(pkg); 7707 } 7708 7709 } else { 7710 if ((scanFlags & SCAN_MOVE) != 0) { 7711 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7712 // but we already have this packages package info in the PackageSetting. We just 7713 // use that and derive the native library path based on the new codepath. 7714 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7715 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7716 } 7717 7718 // Set native library paths again. For moves, the path will be updated based on the 7719 // ABIs we've determined above. For non-moves, the path will be updated based on the 7720 // ABIs we determined during compilation, but the path will depend on the final 7721 // package path (after the rename away from the stage path). 7722 setNativeLibraryPaths(pkg); 7723 } 7724 7725 // This is a special case for the "system" package, where the ABI is 7726 // dictated by the zygote configuration (and init.rc). We should keep track 7727 // of this ABI so that we can deal with "normal" applications that run under 7728 // the same UID correctly. 7729 if (mPlatformPackage == pkg) { 7730 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7731 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7732 } 7733 7734 // If there's a mismatch between the abi-override in the package setting 7735 // and the abiOverride specified for the install. Warn about this because we 7736 // would've already compiled the app without taking the package setting into 7737 // account. 7738 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7739 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7740 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7741 " for package " + pkg.packageName); 7742 } 7743 } 7744 7745 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7746 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7747 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7748 7749 // Copy the derived override back to the parsed package, so that we can 7750 // update the package settings accordingly. 7751 pkg.cpuAbiOverride = cpuAbiOverride; 7752 7753 if (DEBUG_ABI_SELECTION) { 7754 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7755 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7756 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7757 } 7758 7759 // Push the derived path down into PackageSettings so we know what to 7760 // clean up at uninstall time. 7761 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7762 7763 if (DEBUG_ABI_SELECTION) { 7764 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7765 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7766 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7767 } 7768 7769 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7770 // We don't do this here during boot because we can do it all 7771 // at once after scanning all existing packages. 7772 // 7773 // We also do this *before* we perform dexopt on this package, so that 7774 // we can avoid redundant dexopts, and also to make sure we've got the 7775 // code and package path correct. 7776 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7777 pkg, true /* boot complete */); 7778 } 7779 7780 if (mFactoryTest && pkg.requestedPermissions.contains( 7781 android.Manifest.permission.FACTORY_TEST)) { 7782 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7783 } 7784 7785 ArrayList<PackageParser.Package> clientLibPkgs = null; 7786 7787 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7788 if (nonMutatedPs != null) { 7789 synchronized (mPackages) { 7790 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7791 } 7792 } 7793 return pkg; 7794 } 7795 7796 // Only privileged apps and updated privileged apps can add child packages. 7797 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7798 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7799 throw new PackageManagerException("Only privileged apps and updated " 7800 + "privileged apps can add child packages. Ignoring package " 7801 + pkg.packageName); 7802 } 7803 final int childCount = pkg.childPackages.size(); 7804 for (int i = 0; i < childCount; i++) { 7805 PackageParser.Package childPkg = pkg.childPackages.get(i); 7806 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7807 childPkg.packageName)) { 7808 throw new PackageManagerException("Cannot override a child package of " 7809 + "another disabled system app. Ignoring package " + pkg.packageName); 7810 } 7811 } 7812 } 7813 7814 // writer 7815 synchronized (mPackages) { 7816 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7817 // Only system apps can add new shared libraries. 7818 if (pkg.libraryNames != null) { 7819 for (int i=0; i<pkg.libraryNames.size(); i++) { 7820 String name = pkg.libraryNames.get(i); 7821 boolean allowed = false; 7822 if (pkg.isUpdatedSystemApp()) { 7823 // New library entries can only be added through the 7824 // system image. This is important to get rid of a lot 7825 // of nasty edge cases: for example if we allowed a non- 7826 // system update of the app to add a library, then uninstalling 7827 // the update would make the library go away, and assumptions 7828 // we made such as through app install filtering would now 7829 // have allowed apps on the device which aren't compatible 7830 // with it. Better to just have the restriction here, be 7831 // conservative, and create many fewer cases that can negatively 7832 // impact the user experience. 7833 final PackageSetting sysPs = mSettings 7834 .getDisabledSystemPkgLPr(pkg.packageName); 7835 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7836 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7837 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7838 allowed = true; 7839 break; 7840 } 7841 } 7842 } 7843 } else { 7844 allowed = true; 7845 } 7846 if (allowed) { 7847 if (!mSharedLibraries.containsKey(name)) { 7848 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7849 } else if (!name.equals(pkg.packageName)) { 7850 Slog.w(TAG, "Package " + pkg.packageName + " library " 7851 + name + " already exists; skipping"); 7852 } 7853 } else { 7854 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7855 + name + " that is not declared on system image; skipping"); 7856 } 7857 } 7858 if ((scanFlags & SCAN_BOOTING) == 0) { 7859 // If we are not booting, we need to update any applications 7860 // that are clients of our shared library. If we are booting, 7861 // this will all be done once the scan is complete. 7862 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7863 } 7864 } 7865 } 7866 } 7867 7868 // Request the ActivityManager to kill the process(only for existing packages) 7869 // so that we do not end up in a confused state while the user is still using the older 7870 // version of the application while the new one gets installed. 7871 if ((scanFlags & SCAN_REPLACING) != 0) { 7872 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7873 7874 killApplication(pkg.applicationInfo.packageName, 7875 pkg.applicationInfo.uid, "replace pkg"); 7876 7877 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7878 } 7879 7880 // Also need to kill any apps that are dependent on the library. 7881 if (clientLibPkgs != null) { 7882 for (int i=0; i<clientLibPkgs.size(); i++) { 7883 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7884 killApplication(clientPkg.applicationInfo.packageName, 7885 clientPkg.applicationInfo.uid, "update lib"); 7886 } 7887 } 7888 7889 // Make sure we're not adding any bogus keyset info 7890 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7891 ksms.assertScannedPackageValid(pkg); 7892 7893 // writer 7894 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7895 7896 boolean createIdmapFailed = false; 7897 synchronized (mPackages) { 7898 // We don't expect installation to fail beyond this point 7899 7900 // Add the new setting to mSettings 7901 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7902 // Add the new setting to mPackages 7903 mPackages.put(pkg.applicationInfo.packageName, pkg); 7904 // Make sure we don't accidentally delete its data. 7905 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7906 while (iter.hasNext()) { 7907 PackageCleanItem item = iter.next(); 7908 if (pkgName.equals(item.packageName)) { 7909 iter.remove(); 7910 } 7911 } 7912 7913 // Take care of first install / last update times. 7914 if (currentTime != 0) { 7915 if (pkgSetting.firstInstallTime == 0) { 7916 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7917 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7918 pkgSetting.lastUpdateTime = currentTime; 7919 } 7920 } else if (pkgSetting.firstInstallTime == 0) { 7921 // We need *something*. Take time time stamp of the file. 7922 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7923 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7924 if (scanFileTime != pkgSetting.timeStamp) { 7925 // A package on the system image has changed; consider this 7926 // to be an update. 7927 pkgSetting.lastUpdateTime = scanFileTime; 7928 } 7929 } 7930 7931 // Add the package's KeySets to the global KeySetManagerService 7932 ksms.addScannedPackageLPw(pkg); 7933 7934 int N = pkg.providers.size(); 7935 StringBuilder r = null; 7936 int i; 7937 for (i=0; i<N; i++) { 7938 PackageParser.Provider p = pkg.providers.get(i); 7939 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7940 p.info.processName, pkg.applicationInfo.uid); 7941 mProviders.addProvider(p); 7942 p.syncable = p.info.isSyncable; 7943 if (p.info.authority != null) { 7944 String names[] = p.info.authority.split(";"); 7945 p.info.authority = null; 7946 for (int j = 0; j < names.length; j++) { 7947 if (j == 1 && p.syncable) { 7948 // We only want the first authority for a provider to possibly be 7949 // syncable, so if we already added this provider using a different 7950 // authority clear the syncable flag. We copy the provider before 7951 // changing it because the mProviders object contains a reference 7952 // to a provider that we don't want to change. 7953 // Only do this for the second authority since the resulting provider 7954 // object can be the same for all future authorities for this provider. 7955 p = new PackageParser.Provider(p); 7956 p.syncable = false; 7957 } 7958 if (!mProvidersByAuthority.containsKey(names[j])) { 7959 mProvidersByAuthority.put(names[j], p); 7960 if (p.info.authority == null) { 7961 p.info.authority = names[j]; 7962 } else { 7963 p.info.authority = p.info.authority + ";" + names[j]; 7964 } 7965 if (DEBUG_PACKAGE_SCANNING) { 7966 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7967 Log.d(TAG, "Registered content provider: " + names[j] 7968 + ", className = " + p.info.name + ", isSyncable = " 7969 + p.info.isSyncable); 7970 } 7971 } else { 7972 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7973 Slog.w(TAG, "Skipping provider name " + names[j] + 7974 " (in package " + pkg.applicationInfo.packageName + 7975 "): name already used by " 7976 + ((other != null && other.getComponentName() != null) 7977 ? other.getComponentName().getPackageName() : "?")); 7978 } 7979 } 7980 } 7981 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7982 if (r == null) { 7983 r = new StringBuilder(256); 7984 } else { 7985 r.append(' '); 7986 } 7987 r.append(p.info.name); 7988 } 7989 } 7990 if (r != null) { 7991 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7992 } 7993 7994 N = pkg.services.size(); 7995 r = null; 7996 for (i=0; i<N; i++) { 7997 PackageParser.Service s = pkg.services.get(i); 7998 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7999 s.info.processName, pkg.applicationInfo.uid); 8000 mServices.addService(s); 8001 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8002 if (r == null) { 8003 r = new StringBuilder(256); 8004 } else { 8005 r.append(' '); 8006 } 8007 r.append(s.info.name); 8008 } 8009 } 8010 if (r != null) { 8011 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8012 } 8013 8014 N = pkg.receivers.size(); 8015 r = null; 8016 for (i=0; i<N; i++) { 8017 PackageParser.Activity a = pkg.receivers.get(i); 8018 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8019 a.info.processName, pkg.applicationInfo.uid); 8020 mReceivers.addActivity(a, "receiver"); 8021 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8022 if (r == null) { 8023 r = new StringBuilder(256); 8024 } else { 8025 r.append(' '); 8026 } 8027 r.append(a.info.name); 8028 } 8029 } 8030 if (r != null) { 8031 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8032 } 8033 8034 N = pkg.activities.size(); 8035 r = null; 8036 for (i=0; i<N; i++) { 8037 PackageParser.Activity a = pkg.activities.get(i); 8038 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8039 a.info.processName, pkg.applicationInfo.uid); 8040 mActivities.addActivity(a, "activity"); 8041 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8042 if (r == null) { 8043 r = new StringBuilder(256); 8044 } else { 8045 r.append(' '); 8046 } 8047 r.append(a.info.name); 8048 } 8049 } 8050 if (r != null) { 8051 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8052 } 8053 8054 N = pkg.permissionGroups.size(); 8055 r = null; 8056 for (i=0; i<N; i++) { 8057 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8058 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8059 if (cur == null) { 8060 mPermissionGroups.put(pg.info.name, pg); 8061 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8062 if (r == null) { 8063 r = new StringBuilder(256); 8064 } else { 8065 r.append(' '); 8066 } 8067 r.append(pg.info.name); 8068 } 8069 } else { 8070 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8071 + pg.info.packageName + " ignored: original from " 8072 + cur.info.packageName); 8073 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8074 if (r == null) { 8075 r = new StringBuilder(256); 8076 } else { 8077 r.append(' '); 8078 } 8079 r.append("DUP:"); 8080 r.append(pg.info.name); 8081 } 8082 } 8083 } 8084 if (r != null) { 8085 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8086 } 8087 8088 N = pkg.permissions.size(); 8089 r = null; 8090 for (i=0; i<N; i++) { 8091 PackageParser.Permission p = pkg.permissions.get(i); 8092 8093 // Assume by default that we did not install this permission into the system. 8094 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8095 8096 // Now that permission groups have a special meaning, we ignore permission 8097 // groups for legacy apps to prevent unexpected behavior. In particular, 8098 // permissions for one app being granted to someone just becase they happen 8099 // to be in a group defined by another app (before this had no implications). 8100 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8101 p.group = mPermissionGroups.get(p.info.group); 8102 // Warn for a permission in an unknown group. 8103 if (p.info.group != null && p.group == null) { 8104 Slog.w(TAG, "Permission " + p.info.name + " from package " 8105 + p.info.packageName + " in an unknown group " + p.info.group); 8106 } 8107 } 8108 8109 ArrayMap<String, BasePermission> permissionMap = 8110 p.tree ? mSettings.mPermissionTrees 8111 : mSettings.mPermissions; 8112 BasePermission bp = permissionMap.get(p.info.name); 8113 8114 // Allow system apps to redefine non-system permissions 8115 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8116 final boolean currentOwnerIsSystem = (bp.perm != null 8117 && isSystemApp(bp.perm.owner)); 8118 if (isSystemApp(p.owner)) { 8119 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8120 // It's a built-in permission and no owner, take ownership now 8121 bp.packageSetting = pkgSetting; 8122 bp.perm = p; 8123 bp.uid = pkg.applicationInfo.uid; 8124 bp.sourcePackage = p.info.packageName; 8125 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8126 } else if (!currentOwnerIsSystem) { 8127 String msg = "New decl " + p.owner + " of permission " 8128 + p.info.name + " is system; overriding " + bp.sourcePackage; 8129 reportSettingsProblem(Log.WARN, msg); 8130 bp = null; 8131 } 8132 } 8133 } 8134 8135 if (bp == null) { 8136 bp = new BasePermission(p.info.name, p.info.packageName, 8137 BasePermission.TYPE_NORMAL); 8138 permissionMap.put(p.info.name, bp); 8139 } 8140 8141 if (bp.perm == null) { 8142 if (bp.sourcePackage == null 8143 || bp.sourcePackage.equals(p.info.packageName)) { 8144 BasePermission tree = findPermissionTreeLP(p.info.name); 8145 if (tree == null 8146 || tree.sourcePackage.equals(p.info.packageName)) { 8147 bp.packageSetting = pkgSetting; 8148 bp.perm = p; 8149 bp.uid = pkg.applicationInfo.uid; 8150 bp.sourcePackage = p.info.packageName; 8151 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8152 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8153 if (r == null) { 8154 r = new StringBuilder(256); 8155 } else { 8156 r.append(' '); 8157 } 8158 r.append(p.info.name); 8159 } 8160 } else { 8161 Slog.w(TAG, "Permission " + p.info.name + " from package " 8162 + p.info.packageName + " ignored: base tree " 8163 + tree.name + " is from package " 8164 + tree.sourcePackage); 8165 } 8166 } else { 8167 Slog.w(TAG, "Permission " + p.info.name + " from package " 8168 + p.info.packageName + " ignored: original from " 8169 + bp.sourcePackage); 8170 } 8171 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8172 if (r == null) { 8173 r = new StringBuilder(256); 8174 } else { 8175 r.append(' '); 8176 } 8177 r.append("DUP:"); 8178 r.append(p.info.name); 8179 } 8180 if (bp.perm == p) { 8181 bp.protectionLevel = p.info.protectionLevel; 8182 } 8183 } 8184 8185 if (r != null) { 8186 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8187 } 8188 8189 N = pkg.instrumentation.size(); 8190 r = null; 8191 for (i=0; i<N; i++) { 8192 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8193 a.info.packageName = pkg.applicationInfo.packageName; 8194 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8195 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8196 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8197 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8198 a.info.dataDir = pkg.applicationInfo.dataDir; 8199 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8200 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8201 8202 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8203 // need other information about the application, like the ABI and what not ? 8204 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8205 mInstrumentation.put(a.getComponentName(), a); 8206 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8207 if (r == null) { 8208 r = new StringBuilder(256); 8209 } else { 8210 r.append(' '); 8211 } 8212 r.append(a.info.name); 8213 } 8214 } 8215 if (r != null) { 8216 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8217 } 8218 8219 if (pkg.protectedBroadcasts != null) { 8220 N = pkg.protectedBroadcasts.size(); 8221 for (i=0; i<N; i++) { 8222 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8223 } 8224 } 8225 8226 pkgSetting.setTimeStamp(scanFileTime); 8227 8228 // Create idmap files for pairs of (packages, overlay packages). 8229 // Note: "android", ie framework-res.apk, is handled by native layers. 8230 if (pkg.mOverlayTarget != null) { 8231 // This is an overlay package. 8232 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8233 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8234 mOverlays.put(pkg.mOverlayTarget, 8235 new ArrayMap<String, PackageParser.Package>()); 8236 } 8237 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8238 map.put(pkg.packageName, pkg); 8239 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8240 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8241 createIdmapFailed = true; 8242 } 8243 } 8244 } else if (mOverlays.containsKey(pkg.packageName) && 8245 !pkg.packageName.equals("android")) { 8246 // This is a regular package, with one or more known overlay packages. 8247 createIdmapsForPackageLI(pkg); 8248 } 8249 } 8250 8251 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8252 8253 if (createIdmapFailed) { 8254 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8255 "scanPackageLI failed to createIdmap"); 8256 } 8257 return pkg; 8258 } 8259 8260 /** 8261 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8262 * is derived purely on the basis of the contents of {@code scanFile} and 8263 * {@code cpuAbiOverride}. 8264 * 8265 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8266 */ 8267 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8268 String cpuAbiOverride, boolean extractLibs) 8269 throws PackageManagerException { 8270 // TODO: We can probably be smarter about this stuff. For installed apps, 8271 // we can calculate this information at install time once and for all. For 8272 // system apps, we can probably assume that this information doesn't change 8273 // after the first boot scan. As things stand, we do lots of unnecessary work. 8274 8275 // Give ourselves some initial paths; we'll come back for another 8276 // pass once we've determined ABI below. 8277 setNativeLibraryPaths(pkg); 8278 8279 // We would never need to extract libs for forward-locked and external packages, 8280 // since the container service will do it for us. We shouldn't attempt to 8281 // extract libs from system app when it was not updated. 8282 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8283 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8284 extractLibs = false; 8285 } 8286 8287 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8288 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8289 8290 NativeLibraryHelper.Handle handle = null; 8291 try { 8292 handle = NativeLibraryHelper.Handle.create(pkg); 8293 // TODO(multiArch): This can be null for apps that didn't go through the 8294 // usual installation process. We can calculate it again, like we 8295 // do during install time. 8296 // 8297 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8298 // unnecessary. 8299 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8300 8301 // Null out the abis so that they can be recalculated. 8302 pkg.applicationInfo.primaryCpuAbi = null; 8303 pkg.applicationInfo.secondaryCpuAbi = null; 8304 if (isMultiArch(pkg.applicationInfo)) { 8305 // Warn if we've set an abiOverride for multi-lib packages.. 8306 // By definition, we need to copy both 32 and 64 bit libraries for 8307 // such packages. 8308 if (pkg.cpuAbiOverride != null 8309 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8310 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8311 } 8312 8313 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8314 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8315 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8316 if (extractLibs) { 8317 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8318 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8319 useIsaSpecificSubdirs); 8320 } else { 8321 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8322 } 8323 } 8324 8325 maybeThrowExceptionForMultiArchCopy( 8326 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8327 8328 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8329 if (extractLibs) { 8330 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8331 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8332 useIsaSpecificSubdirs); 8333 } else { 8334 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8335 } 8336 } 8337 8338 maybeThrowExceptionForMultiArchCopy( 8339 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8340 8341 if (abi64 >= 0) { 8342 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8343 } 8344 8345 if (abi32 >= 0) { 8346 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8347 if (abi64 >= 0) { 8348 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8349 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8350 pkg.applicationInfo.primaryCpuAbi = abi; 8351 } else { 8352 pkg.applicationInfo.secondaryCpuAbi = abi; 8353 } 8354 } else { 8355 pkg.applicationInfo.primaryCpuAbi = abi; 8356 } 8357 } 8358 8359 } else { 8360 String[] abiList = (cpuAbiOverride != null) ? 8361 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8362 8363 // Enable gross and lame hacks for apps that are built with old 8364 // SDK tools. We must scan their APKs for renderscript bitcode and 8365 // not launch them if it's present. Don't bother checking on devices 8366 // that don't have 64 bit support. 8367 boolean needsRenderScriptOverride = false; 8368 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8369 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8370 abiList = Build.SUPPORTED_32_BIT_ABIS; 8371 needsRenderScriptOverride = true; 8372 } 8373 8374 final int copyRet; 8375 if (extractLibs) { 8376 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8377 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8378 } else { 8379 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8380 } 8381 8382 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8383 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8384 "Error unpackaging native libs for app, errorCode=" + copyRet); 8385 } 8386 8387 if (copyRet >= 0) { 8388 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8389 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8390 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8391 } else if (needsRenderScriptOverride) { 8392 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8393 } 8394 } 8395 } catch (IOException ioe) { 8396 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8397 } finally { 8398 IoUtils.closeQuietly(handle); 8399 } 8400 8401 // Now that we've calculated the ABIs and determined if it's an internal app, 8402 // we will go ahead and populate the nativeLibraryPath. 8403 setNativeLibraryPaths(pkg); 8404 } 8405 8406 /** 8407 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8408 * i.e, so that all packages can be run inside a single process if required. 8409 * 8410 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8411 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8412 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8413 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8414 * updating a package that belongs to a shared user. 8415 * 8416 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8417 * adds unnecessary complexity. 8418 */ 8419 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8420 PackageParser.Package scannedPackage, boolean bootComplete) { 8421 String requiredInstructionSet = null; 8422 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8423 requiredInstructionSet = VMRuntime.getInstructionSet( 8424 scannedPackage.applicationInfo.primaryCpuAbi); 8425 } 8426 8427 PackageSetting requirer = null; 8428 for (PackageSetting ps : packagesForUser) { 8429 // If packagesForUser contains scannedPackage, we skip it. This will happen 8430 // when scannedPackage is an update of an existing package. Without this check, 8431 // we will never be able to change the ABI of any package belonging to a shared 8432 // user, even if it's compatible with other packages. 8433 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8434 if (ps.primaryCpuAbiString == null) { 8435 continue; 8436 } 8437 8438 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8439 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8440 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8441 // this but there's not much we can do. 8442 String errorMessage = "Instruction set mismatch, " 8443 + ((requirer == null) ? "[caller]" : requirer) 8444 + " requires " + requiredInstructionSet + " whereas " + ps 8445 + " requires " + instructionSet; 8446 Slog.w(TAG, errorMessage); 8447 } 8448 8449 if (requiredInstructionSet == null) { 8450 requiredInstructionSet = instructionSet; 8451 requirer = ps; 8452 } 8453 } 8454 } 8455 8456 if (requiredInstructionSet != null) { 8457 String adjustedAbi; 8458 if (requirer != null) { 8459 // requirer != null implies that either scannedPackage was null or that scannedPackage 8460 // did not require an ABI, in which case we have to adjust scannedPackage to match 8461 // the ABI of the set (which is the same as requirer's ABI) 8462 adjustedAbi = requirer.primaryCpuAbiString; 8463 if (scannedPackage != null) { 8464 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8465 } 8466 } else { 8467 // requirer == null implies that we're updating all ABIs in the set to 8468 // match scannedPackage. 8469 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8470 } 8471 8472 for (PackageSetting ps : packagesForUser) { 8473 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8474 if (ps.primaryCpuAbiString != null) { 8475 continue; 8476 } 8477 8478 ps.primaryCpuAbiString = adjustedAbi; 8479 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8480 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8481 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8482 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8483 + " (requirer=" 8484 + (requirer == null ? "null" : requirer.pkg.packageName) 8485 + ", scannedPackage=" 8486 + (scannedPackage != null ? scannedPackage.packageName : "null") 8487 + ")"); 8488 try { 8489 mInstaller.rmdex(ps.codePathString, 8490 getDexCodeInstructionSet(getPreferredInstructionSet())); 8491 } catch (InstallerException ignored) { 8492 } 8493 } 8494 } 8495 } 8496 } 8497 } 8498 8499 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8500 synchronized (mPackages) { 8501 mResolverReplaced = true; 8502 // Set up information for custom user intent resolution activity. 8503 mResolveActivity.applicationInfo = pkg.applicationInfo; 8504 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8505 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8506 mResolveActivity.processName = pkg.applicationInfo.packageName; 8507 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8508 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8509 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8510 mResolveActivity.theme = 0; 8511 mResolveActivity.exported = true; 8512 mResolveActivity.enabled = true; 8513 mResolveInfo.activityInfo = mResolveActivity; 8514 mResolveInfo.priority = 0; 8515 mResolveInfo.preferredOrder = 0; 8516 mResolveInfo.match = 0; 8517 mResolveComponentName = mCustomResolverComponentName; 8518 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8519 mResolveComponentName); 8520 } 8521 } 8522 8523 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8524 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8525 8526 // Set up information for ephemeral installer activity 8527 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8528 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8529 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8530 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8531 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8532 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8533 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8534 mEphemeralInstallerActivity.theme = 0; 8535 mEphemeralInstallerActivity.exported = true; 8536 mEphemeralInstallerActivity.enabled = true; 8537 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8538 mEphemeralInstallerInfo.priority = 0; 8539 mEphemeralInstallerInfo.preferredOrder = 0; 8540 mEphemeralInstallerInfo.match = 0; 8541 8542 if (DEBUG_EPHEMERAL) { 8543 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8544 } 8545 } 8546 8547 private static String calculateBundledApkRoot(final String codePathString) { 8548 final File codePath = new File(codePathString); 8549 final File codeRoot; 8550 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8551 codeRoot = Environment.getRootDirectory(); 8552 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8553 codeRoot = Environment.getOemDirectory(); 8554 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8555 codeRoot = Environment.getVendorDirectory(); 8556 } else { 8557 // Unrecognized code path; take its top real segment as the apk root: 8558 // e.g. /something/app/blah.apk => /something 8559 try { 8560 File f = codePath.getCanonicalFile(); 8561 File parent = f.getParentFile(); // non-null because codePath is a file 8562 File tmp; 8563 while ((tmp = parent.getParentFile()) != null) { 8564 f = parent; 8565 parent = tmp; 8566 } 8567 codeRoot = f; 8568 Slog.w(TAG, "Unrecognized code path " 8569 + codePath + " - using " + codeRoot); 8570 } catch (IOException e) { 8571 // Can't canonicalize the code path -- shenanigans? 8572 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8573 return Environment.getRootDirectory().getPath(); 8574 } 8575 } 8576 return codeRoot.getPath(); 8577 } 8578 8579 /** 8580 * Derive and set the location of native libraries for the given package, 8581 * which varies depending on where and how the package was installed. 8582 */ 8583 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8584 final ApplicationInfo info = pkg.applicationInfo; 8585 final String codePath = pkg.codePath; 8586 final File codeFile = new File(codePath); 8587 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8588 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8589 8590 info.nativeLibraryRootDir = null; 8591 info.nativeLibraryRootRequiresIsa = false; 8592 info.nativeLibraryDir = null; 8593 info.secondaryNativeLibraryDir = null; 8594 8595 if (isApkFile(codeFile)) { 8596 // Monolithic install 8597 if (bundledApp) { 8598 // If "/system/lib64/apkname" exists, assume that is the per-package 8599 // native library directory to use; otherwise use "/system/lib/apkname". 8600 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8601 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8602 getPrimaryInstructionSet(info)); 8603 8604 // This is a bundled system app so choose the path based on the ABI. 8605 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8606 // is just the default path. 8607 final String apkName = deriveCodePathName(codePath); 8608 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8609 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8610 apkName).getAbsolutePath(); 8611 8612 if (info.secondaryCpuAbi != null) { 8613 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8614 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8615 secondaryLibDir, apkName).getAbsolutePath(); 8616 } 8617 } else if (asecApp) { 8618 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8619 .getAbsolutePath(); 8620 } else { 8621 final String apkName = deriveCodePathName(codePath); 8622 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8623 .getAbsolutePath(); 8624 } 8625 8626 info.nativeLibraryRootRequiresIsa = false; 8627 info.nativeLibraryDir = info.nativeLibraryRootDir; 8628 } else { 8629 // Cluster install 8630 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8631 info.nativeLibraryRootRequiresIsa = true; 8632 8633 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8634 getPrimaryInstructionSet(info)).getAbsolutePath(); 8635 8636 if (info.secondaryCpuAbi != null) { 8637 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8638 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8639 } 8640 } 8641 } 8642 8643 /** 8644 * Calculate the abis and roots for a bundled app. These can uniquely 8645 * be determined from the contents of the system partition, i.e whether 8646 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8647 * of this information, and instead assume that the system was built 8648 * sensibly. 8649 */ 8650 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8651 PackageSetting pkgSetting) { 8652 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8653 8654 // If "/system/lib64/apkname" exists, assume that is the per-package 8655 // native library directory to use; otherwise use "/system/lib/apkname". 8656 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8657 setBundledAppAbi(pkg, apkRoot, apkName); 8658 // pkgSetting might be null during rescan following uninstall of updates 8659 // to a bundled app, so accommodate that possibility. The settings in 8660 // that case will be established later from the parsed package. 8661 // 8662 // If the settings aren't null, sync them up with what we've just derived. 8663 // note that apkRoot isn't stored in the package settings. 8664 if (pkgSetting != null) { 8665 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8666 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8667 } 8668 } 8669 8670 /** 8671 * Deduces the ABI of a bundled app and sets the relevant fields on the 8672 * parsed pkg object. 8673 * 8674 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8675 * under which system libraries are installed. 8676 * @param apkName the name of the installed package. 8677 */ 8678 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8679 final File codeFile = new File(pkg.codePath); 8680 8681 final boolean has64BitLibs; 8682 final boolean has32BitLibs; 8683 if (isApkFile(codeFile)) { 8684 // Monolithic install 8685 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8686 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8687 } else { 8688 // Cluster install 8689 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8690 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8691 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8692 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8693 has64BitLibs = (new File(rootDir, isa)).exists(); 8694 } else { 8695 has64BitLibs = false; 8696 } 8697 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8698 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8699 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8700 has32BitLibs = (new File(rootDir, isa)).exists(); 8701 } else { 8702 has32BitLibs = false; 8703 } 8704 } 8705 8706 if (has64BitLibs && !has32BitLibs) { 8707 // The package has 64 bit libs, but not 32 bit libs. Its primary 8708 // ABI should be 64 bit. We can safely assume here that the bundled 8709 // native libraries correspond to the most preferred ABI in the list. 8710 8711 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8712 pkg.applicationInfo.secondaryCpuAbi = null; 8713 } else if (has32BitLibs && !has64BitLibs) { 8714 // The package has 32 bit libs but not 64 bit libs. Its primary 8715 // ABI should be 32 bit. 8716 8717 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8718 pkg.applicationInfo.secondaryCpuAbi = null; 8719 } else if (has32BitLibs && has64BitLibs) { 8720 // The application has both 64 and 32 bit bundled libraries. We check 8721 // here that the app declares multiArch support, and warn if it doesn't. 8722 // 8723 // We will be lenient here and record both ABIs. The primary will be the 8724 // ABI that's higher on the list, i.e, a device that's configured to prefer 8725 // 64 bit apps will see a 64 bit primary ABI, 8726 8727 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8728 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8729 } 8730 8731 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8732 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8733 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8734 } else { 8735 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8736 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8737 } 8738 } else { 8739 pkg.applicationInfo.primaryCpuAbi = null; 8740 pkg.applicationInfo.secondaryCpuAbi = null; 8741 } 8742 } 8743 8744 private void killPackage(PackageParser.Package pkg, String reason) { 8745 // Kill the parent package 8746 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8747 // Kill the child packages 8748 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8749 for (int i = 0; i < childCount; i++) { 8750 PackageParser.Package childPkg = pkg.childPackages.get(i); 8751 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8752 } 8753 } 8754 8755 private void killApplication(String pkgName, int appId, String reason) { 8756 // Request the ActivityManager to kill the process(only for existing packages) 8757 // so that we do not end up in a confused state while the user is still using the older 8758 // version of the application while the new one gets installed. 8759 IActivityManager am = ActivityManagerNative.getDefault(); 8760 if (am != null) { 8761 try { 8762 am.killApplicationWithAppId(pkgName, appId, reason); 8763 } catch (RemoteException e) { 8764 } 8765 } 8766 } 8767 8768 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8769 // Remove the parent package setting 8770 PackageSetting ps = (PackageSetting) pkg.mExtras; 8771 if (ps != null) { 8772 removePackageLI(ps, chatty); 8773 } 8774 // Remove the child package setting 8775 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8776 for (int i = 0; i < childCount; i++) { 8777 PackageParser.Package childPkg = pkg.childPackages.get(i); 8778 ps = (PackageSetting) childPkg.mExtras; 8779 if (ps != null) { 8780 removePackageLI(ps, chatty); 8781 } 8782 } 8783 } 8784 8785 void removePackageLI(PackageSetting ps, boolean chatty) { 8786 if (DEBUG_INSTALL) { 8787 if (chatty) 8788 Log.d(TAG, "Removing package " + ps.name); 8789 } 8790 8791 // writer 8792 synchronized (mPackages) { 8793 mPackages.remove(ps.name); 8794 final PackageParser.Package pkg = ps.pkg; 8795 if (pkg != null) { 8796 cleanPackageDataStructuresLILPw(pkg, chatty); 8797 } 8798 } 8799 } 8800 8801 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8802 if (DEBUG_INSTALL) { 8803 if (chatty) 8804 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8805 } 8806 8807 // writer 8808 synchronized (mPackages) { 8809 // Remove the parent package 8810 mPackages.remove(pkg.applicationInfo.packageName); 8811 cleanPackageDataStructuresLILPw(pkg, chatty); 8812 8813 // Remove the child packages 8814 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8815 for (int i = 0; i < childCount; i++) { 8816 PackageParser.Package childPkg = pkg.childPackages.get(i); 8817 mPackages.remove(childPkg.applicationInfo.packageName); 8818 cleanPackageDataStructuresLILPw(childPkg, chatty); 8819 } 8820 } 8821 } 8822 8823 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8824 int N = pkg.providers.size(); 8825 StringBuilder r = null; 8826 int i; 8827 for (i=0; i<N; i++) { 8828 PackageParser.Provider p = pkg.providers.get(i); 8829 mProviders.removeProvider(p); 8830 if (p.info.authority == null) { 8831 8832 /* There was another ContentProvider with this authority when 8833 * this app was installed so this authority is null, 8834 * Ignore it as we don't have to unregister the provider. 8835 */ 8836 continue; 8837 } 8838 String names[] = p.info.authority.split(";"); 8839 for (int j = 0; j < names.length; j++) { 8840 if (mProvidersByAuthority.get(names[j]) == p) { 8841 mProvidersByAuthority.remove(names[j]); 8842 if (DEBUG_REMOVE) { 8843 if (chatty) 8844 Log.d(TAG, "Unregistered content provider: " + names[j] 8845 + ", className = " + p.info.name + ", isSyncable = " 8846 + p.info.isSyncable); 8847 } 8848 } 8849 } 8850 if (DEBUG_REMOVE && chatty) { 8851 if (r == null) { 8852 r = new StringBuilder(256); 8853 } else { 8854 r.append(' '); 8855 } 8856 r.append(p.info.name); 8857 } 8858 } 8859 if (r != null) { 8860 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8861 } 8862 8863 N = pkg.services.size(); 8864 r = null; 8865 for (i=0; i<N; i++) { 8866 PackageParser.Service s = pkg.services.get(i); 8867 mServices.removeService(s); 8868 if (chatty) { 8869 if (r == null) { 8870 r = new StringBuilder(256); 8871 } else { 8872 r.append(' '); 8873 } 8874 r.append(s.info.name); 8875 } 8876 } 8877 if (r != null) { 8878 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8879 } 8880 8881 N = pkg.receivers.size(); 8882 r = null; 8883 for (i=0; i<N; i++) { 8884 PackageParser.Activity a = pkg.receivers.get(i); 8885 mReceivers.removeActivity(a, "receiver"); 8886 if (DEBUG_REMOVE && chatty) { 8887 if (r == null) { 8888 r = new StringBuilder(256); 8889 } else { 8890 r.append(' '); 8891 } 8892 r.append(a.info.name); 8893 } 8894 } 8895 if (r != null) { 8896 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8897 } 8898 8899 N = pkg.activities.size(); 8900 r = null; 8901 for (i=0; i<N; i++) { 8902 PackageParser.Activity a = pkg.activities.get(i); 8903 mActivities.removeActivity(a, "activity"); 8904 if (DEBUG_REMOVE && chatty) { 8905 if (r == null) { 8906 r = new StringBuilder(256); 8907 } else { 8908 r.append(' '); 8909 } 8910 r.append(a.info.name); 8911 } 8912 } 8913 if (r != null) { 8914 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8915 } 8916 8917 N = pkg.permissions.size(); 8918 r = null; 8919 for (i=0; i<N; i++) { 8920 PackageParser.Permission p = pkg.permissions.get(i); 8921 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8922 if (bp == null) { 8923 bp = mSettings.mPermissionTrees.get(p.info.name); 8924 } 8925 if (bp != null && bp.perm == p) { 8926 bp.perm = null; 8927 if (DEBUG_REMOVE && chatty) { 8928 if (r == null) { 8929 r = new StringBuilder(256); 8930 } else { 8931 r.append(' '); 8932 } 8933 r.append(p.info.name); 8934 } 8935 } 8936 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8937 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8938 if (appOpPkgs != null) { 8939 appOpPkgs.remove(pkg.packageName); 8940 } 8941 } 8942 } 8943 if (r != null) { 8944 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8945 } 8946 8947 N = pkg.requestedPermissions.size(); 8948 r = null; 8949 for (i=0; i<N; i++) { 8950 String perm = pkg.requestedPermissions.get(i); 8951 BasePermission bp = mSettings.mPermissions.get(perm); 8952 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8953 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8954 if (appOpPkgs != null) { 8955 appOpPkgs.remove(pkg.packageName); 8956 if (appOpPkgs.isEmpty()) { 8957 mAppOpPermissionPackages.remove(perm); 8958 } 8959 } 8960 } 8961 } 8962 if (r != null) { 8963 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8964 } 8965 8966 N = pkg.instrumentation.size(); 8967 r = null; 8968 for (i=0; i<N; i++) { 8969 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8970 mInstrumentation.remove(a.getComponentName()); 8971 if (DEBUG_REMOVE && chatty) { 8972 if (r == null) { 8973 r = new StringBuilder(256); 8974 } else { 8975 r.append(' '); 8976 } 8977 r.append(a.info.name); 8978 } 8979 } 8980 if (r != null) { 8981 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8982 } 8983 8984 r = null; 8985 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8986 // Only system apps can hold shared libraries. 8987 if (pkg.libraryNames != null) { 8988 for (i=0; i<pkg.libraryNames.size(); i++) { 8989 String name = pkg.libraryNames.get(i); 8990 SharedLibraryEntry cur = mSharedLibraries.get(name); 8991 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8992 mSharedLibraries.remove(name); 8993 if (DEBUG_REMOVE && chatty) { 8994 if (r == null) { 8995 r = new StringBuilder(256); 8996 } else { 8997 r.append(' '); 8998 } 8999 r.append(name); 9000 } 9001 } 9002 } 9003 } 9004 } 9005 if (r != null) { 9006 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9007 } 9008 } 9009 9010 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9011 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9012 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9013 return true; 9014 } 9015 } 9016 return false; 9017 } 9018 9019 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9020 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9021 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9022 9023 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9024 // Update the parent permissions 9025 updatePermissionsLPw(pkg.packageName, pkg, flags); 9026 // Update the child permissions 9027 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9028 for (int i = 0; i < childCount; i++) { 9029 PackageParser.Package childPkg = pkg.childPackages.get(i); 9030 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9031 } 9032 } 9033 9034 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9035 int flags) { 9036 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9037 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9038 } 9039 9040 private void updatePermissionsLPw(String changingPkg, 9041 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9042 // Make sure there are no dangling permission trees. 9043 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9044 while (it.hasNext()) { 9045 final BasePermission bp = it.next(); 9046 if (bp.packageSetting == null) { 9047 // We may not yet have parsed the package, so just see if 9048 // we still know about its settings. 9049 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9050 } 9051 if (bp.packageSetting == null) { 9052 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9053 + " from package " + bp.sourcePackage); 9054 it.remove(); 9055 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9056 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9057 Slog.i(TAG, "Removing old permission tree: " + bp.name 9058 + " from package " + bp.sourcePackage); 9059 flags |= UPDATE_PERMISSIONS_ALL; 9060 it.remove(); 9061 } 9062 } 9063 } 9064 9065 // Make sure all dynamic permissions have been assigned to a package, 9066 // and make sure there are no dangling permissions. 9067 it = mSettings.mPermissions.values().iterator(); 9068 while (it.hasNext()) { 9069 final BasePermission bp = it.next(); 9070 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9071 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9072 + bp.name + " pkg=" + bp.sourcePackage 9073 + " info=" + bp.pendingInfo); 9074 if (bp.packageSetting == null && bp.pendingInfo != null) { 9075 final BasePermission tree = findPermissionTreeLP(bp.name); 9076 if (tree != null && tree.perm != null) { 9077 bp.packageSetting = tree.packageSetting; 9078 bp.perm = new PackageParser.Permission(tree.perm.owner, 9079 new PermissionInfo(bp.pendingInfo)); 9080 bp.perm.info.packageName = tree.perm.info.packageName; 9081 bp.perm.info.name = bp.name; 9082 bp.uid = tree.uid; 9083 } 9084 } 9085 } 9086 if (bp.packageSetting == null) { 9087 // We may not yet have parsed the package, so just see if 9088 // we still know about its settings. 9089 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9090 } 9091 if (bp.packageSetting == null) { 9092 Slog.w(TAG, "Removing dangling permission: " + bp.name 9093 + " from package " + bp.sourcePackage); 9094 it.remove(); 9095 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9096 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9097 Slog.i(TAG, "Removing old permission: " + bp.name 9098 + " from package " + bp.sourcePackage); 9099 flags |= UPDATE_PERMISSIONS_ALL; 9100 it.remove(); 9101 } 9102 } 9103 } 9104 9105 // Now update the permissions for all packages, in particular 9106 // replace the granted permissions of the system packages. 9107 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9108 for (PackageParser.Package pkg : mPackages.values()) { 9109 if (pkg != pkgInfo) { 9110 // Only replace for packages on requested volume 9111 final String volumeUuid = getVolumeUuidForPackage(pkg); 9112 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9113 && Objects.equals(replaceVolumeUuid, volumeUuid); 9114 grantPermissionsLPw(pkg, replace, changingPkg); 9115 } 9116 } 9117 } 9118 9119 if (pkgInfo != null) { 9120 // Only replace for packages on requested volume 9121 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9122 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9123 && Objects.equals(replaceVolumeUuid, volumeUuid); 9124 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9125 } 9126 } 9127 9128 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9129 String packageOfInterest) { 9130 // IMPORTANT: There are two types of permissions: install and runtime. 9131 // Install time permissions are granted when the app is installed to 9132 // all device users and users added in the future. Runtime permissions 9133 // are granted at runtime explicitly to specific users. Normal and signature 9134 // protected permissions are install time permissions. Dangerous permissions 9135 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9136 // otherwise they are runtime permissions. This function does not manage 9137 // runtime permissions except for the case an app targeting Lollipop MR1 9138 // being upgraded to target a newer SDK, in which case dangerous permissions 9139 // are transformed from install time to runtime ones. 9140 9141 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9142 if (ps == null) { 9143 return; 9144 } 9145 9146 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9147 9148 PermissionsState permissionsState = ps.getPermissionsState(); 9149 PermissionsState origPermissions = permissionsState; 9150 9151 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9152 9153 boolean runtimePermissionsRevoked = false; 9154 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9155 9156 boolean changedInstallPermission = false; 9157 9158 if (replace) { 9159 ps.installPermissionsFixed = false; 9160 if (!ps.isSharedUser()) { 9161 origPermissions = new PermissionsState(permissionsState); 9162 permissionsState.reset(); 9163 } else { 9164 // We need to know only about runtime permission changes since the 9165 // calling code always writes the install permissions state but 9166 // the runtime ones are written only if changed. The only cases of 9167 // changed runtime permissions here are promotion of an install to 9168 // runtime and revocation of a runtime from a shared user. 9169 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9170 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9171 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9172 runtimePermissionsRevoked = true; 9173 } 9174 } 9175 } 9176 9177 permissionsState.setGlobalGids(mGlobalGids); 9178 9179 final int N = pkg.requestedPermissions.size(); 9180 for (int i=0; i<N; i++) { 9181 final String name = pkg.requestedPermissions.get(i); 9182 final BasePermission bp = mSettings.mPermissions.get(name); 9183 9184 if (DEBUG_INSTALL) { 9185 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9186 } 9187 9188 if (bp == null || bp.packageSetting == null) { 9189 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9190 Slog.w(TAG, "Unknown permission " + name 9191 + " in package " + pkg.packageName); 9192 } 9193 continue; 9194 } 9195 9196 final String perm = bp.name; 9197 boolean allowedSig = false; 9198 int grant = GRANT_DENIED; 9199 9200 // Keep track of app op permissions. 9201 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9202 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9203 if (pkgs == null) { 9204 pkgs = new ArraySet<>(); 9205 mAppOpPermissionPackages.put(bp.name, pkgs); 9206 } 9207 pkgs.add(pkg.packageName); 9208 } 9209 9210 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9211 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9212 >= Build.VERSION_CODES.M; 9213 switch (level) { 9214 case PermissionInfo.PROTECTION_NORMAL: { 9215 // For all apps normal permissions are install time ones. 9216 grant = GRANT_INSTALL; 9217 } break; 9218 9219 case PermissionInfo.PROTECTION_DANGEROUS: { 9220 // If a permission review is required for legacy apps we represent 9221 // their permissions as always granted runtime ones since we need 9222 // to keep the review required permission flag per user while an 9223 // install permission's state is shared across all users. 9224 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9225 // For legacy apps dangerous permissions are install time ones. 9226 grant = GRANT_INSTALL; 9227 } else if (origPermissions.hasInstallPermission(bp.name)) { 9228 // For legacy apps that became modern, install becomes runtime. 9229 grant = GRANT_UPGRADE; 9230 } else if (mPromoteSystemApps 9231 && isSystemApp(ps) 9232 && mExistingSystemPackages.contains(ps.name)) { 9233 // For legacy system apps, install becomes runtime. 9234 // We cannot check hasInstallPermission() for system apps since those 9235 // permissions were granted implicitly and not persisted pre-M. 9236 grant = GRANT_UPGRADE; 9237 } else { 9238 // For modern apps keep runtime permissions unchanged. 9239 grant = GRANT_RUNTIME; 9240 } 9241 } break; 9242 9243 case PermissionInfo.PROTECTION_SIGNATURE: { 9244 // For all apps signature permissions are install time ones. 9245 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9246 if (allowedSig) { 9247 grant = GRANT_INSTALL; 9248 } 9249 } break; 9250 } 9251 9252 if (DEBUG_INSTALL) { 9253 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9254 } 9255 9256 if (grant != GRANT_DENIED) { 9257 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9258 // If this is an existing, non-system package, then 9259 // we can't add any new permissions to it. 9260 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9261 // Except... if this is a permission that was added 9262 // to the platform (note: need to only do this when 9263 // updating the platform). 9264 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9265 grant = GRANT_DENIED; 9266 } 9267 } 9268 } 9269 9270 switch (grant) { 9271 case GRANT_INSTALL: { 9272 // Revoke this as runtime permission to handle the case of 9273 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9274 for (int userId : UserManagerService.getInstance().getUserIds()) { 9275 if (origPermissions.getRuntimePermissionState( 9276 bp.name, userId) != null) { 9277 // Revoke the runtime permission and clear the flags. 9278 origPermissions.revokeRuntimePermission(bp, userId); 9279 origPermissions.updatePermissionFlags(bp, userId, 9280 PackageManager.MASK_PERMISSION_FLAGS, 0); 9281 // If we revoked a permission permission, we have to write. 9282 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9283 changedRuntimePermissionUserIds, userId); 9284 } 9285 } 9286 // Grant an install permission. 9287 if (permissionsState.grantInstallPermission(bp) != 9288 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9289 changedInstallPermission = true; 9290 } 9291 } break; 9292 9293 case GRANT_RUNTIME: { 9294 // Grant previously granted runtime permissions. 9295 for (int userId : UserManagerService.getInstance().getUserIds()) { 9296 PermissionState permissionState = origPermissions 9297 .getRuntimePermissionState(bp.name, userId); 9298 int flags = permissionState != null 9299 ? permissionState.getFlags() : 0; 9300 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9301 if (permissionsState.grantRuntimePermission(bp, userId) == 9302 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9303 // If we cannot put the permission as it was, we have to write. 9304 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9305 changedRuntimePermissionUserIds, userId); 9306 } 9307 // If the app supports runtime permissions no need for a review. 9308 if (Build.PERMISSIONS_REVIEW_REQUIRED 9309 && appSupportsRuntimePermissions 9310 && (flags & PackageManager 9311 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9312 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9313 // Since we changed the flags, we have to write. 9314 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9315 changedRuntimePermissionUserIds, userId); 9316 } 9317 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9318 && !appSupportsRuntimePermissions) { 9319 // For legacy apps that need a permission review, every new 9320 // runtime permission is granted but it is pending a review. 9321 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9322 permissionsState.grantRuntimePermission(bp, userId); 9323 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9324 // We changed the permission and flags, hence have to write. 9325 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9326 changedRuntimePermissionUserIds, userId); 9327 } 9328 } 9329 // Propagate the permission flags. 9330 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9331 } 9332 } break; 9333 9334 case GRANT_UPGRADE: { 9335 // Grant runtime permissions for a previously held install permission. 9336 PermissionState permissionState = origPermissions 9337 .getInstallPermissionState(bp.name); 9338 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9339 9340 if (origPermissions.revokeInstallPermission(bp) 9341 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9342 // We will be transferring the permission flags, so clear them. 9343 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9344 PackageManager.MASK_PERMISSION_FLAGS, 0); 9345 changedInstallPermission = true; 9346 } 9347 9348 // If the permission is not to be promoted to runtime we ignore it and 9349 // also its other flags as they are not applicable to install permissions. 9350 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9351 for (int userId : currentUserIds) { 9352 if (permissionsState.grantRuntimePermission(bp, userId) != 9353 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9354 // Transfer the permission flags. 9355 permissionsState.updatePermissionFlags(bp, userId, 9356 flags, flags); 9357 // If we granted the permission, we have to write. 9358 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9359 changedRuntimePermissionUserIds, userId); 9360 } 9361 } 9362 } 9363 } break; 9364 9365 default: { 9366 if (packageOfInterest == null 9367 || packageOfInterest.equals(pkg.packageName)) { 9368 Slog.w(TAG, "Not granting permission " + perm 9369 + " to package " + pkg.packageName 9370 + " because it was previously installed without"); 9371 } 9372 } break; 9373 } 9374 } else { 9375 if (permissionsState.revokeInstallPermission(bp) != 9376 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9377 // Also drop the permission flags. 9378 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9379 PackageManager.MASK_PERMISSION_FLAGS, 0); 9380 changedInstallPermission = true; 9381 Slog.i(TAG, "Un-granting permission " + perm 9382 + " from package " + pkg.packageName 9383 + " (protectionLevel=" + bp.protectionLevel 9384 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9385 + ")"); 9386 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9387 // Don't print warning for app op permissions, since it is fine for them 9388 // not to be granted, there is a UI for the user to decide. 9389 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9390 Slog.w(TAG, "Not granting permission " + perm 9391 + " to package " + pkg.packageName 9392 + " (protectionLevel=" + bp.protectionLevel 9393 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9394 + ")"); 9395 } 9396 } 9397 } 9398 } 9399 9400 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9401 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9402 // This is the first that we have heard about this package, so the 9403 // permissions we have now selected are fixed until explicitly 9404 // changed. 9405 ps.installPermissionsFixed = true; 9406 } 9407 9408 // Persist the runtime permissions state for users with changes. If permissions 9409 // were revoked because no app in the shared user declares them we have to 9410 // write synchronously to avoid losing runtime permissions state. 9411 for (int userId : changedRuntimePermissionUserIds) { 9412 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9413 } 9414 9415 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9416 } 9417 9418 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9419 boolean allowed = false; 9420 final int NP = PackageParser.NEW_PERMISSIONS.length; 9421 for (int ip=0; ip<NP; ip++) { 9422 final PackageParser.NewPermissionInfo npi 9423 = PackageParser.NEW_PERMISSIONS[ip]; 9424 if (npi.name.equals(perm) 9425 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9426 allowed = true; 9427 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9428 + pkg.packageName); 9429 break; 9430 } 9431 } 9432 return allowed; 9433 } 9434 9435 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9436 BasePermission bp, PermissionsState origPermissions) { 9437 boolean allowed; 9438 allowed = (compareSignatures( 9439 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9440 == PackageManager.SIGNATURE_MATCH) 9441 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9442 == PackageManager.SIGNATURE_MATCH); 9443 if (!allowed && (bp.protectionLevel 9444 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9445 if (isSystemApp(pkg)) { 9446 // For updated system applications, a system permission 9447 // is granted only if it had been defined by the original application. 9448 if (pkg.isUpdatedSystemApp()) { 9449 final PackageSetting sysPs = mSettings 9450 .getDisabledSystemPkgLPr(pkg.packageName); 9451 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9452 // If the original was granted this permission, we take 9453 // that grant decision as read and propagate it to the 9454 // update. 9455 if (sysPs.isPrivileged()) { 9456 allowed = true; 9457 } 9458 } else { 9459 // The system apk may have been updated with an older 9460 // version of the one on the data partition, but which 9461 // granted a new system permission that it didn't have 9462 // before. In this case we do want to allow the app to 9463 // now get the new permission if the ancestral apk is 9464 // privileged to get it. 9465 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9466 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9467 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9468 allowed = true; 9469 break; 9470 } 9471 } 9472 } 9473 // Also if a privileged parent package on the system image or any of 9474 // its children requested a privileged permission, the updated child 9475 // packages can also get the permission. 9476 if (pkg.parentPackage != null) { 9477 final PackageSetting disabledSysParentPs = mSettings 9478 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9479 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9480 && disabledSysParentPs.isPrivileged()) { 9481 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9482 allowed = true; 9483 } else if (disabledSysParentPs.pkg.childPackages != null) { 9484 final int count = disabledSysParentPs.pkg.childPackages.size(); 9485 for (int i = 0; i < count; i++) { 9486 PackageParser.Package disabledSysChildPkg = 9487 disabledSysParentPs.pkg.childPackages.get(i); 9488 if (isPackageRequestingPermission(disabledSysChildPkg, 9489 perm)) { 9490 allowed = true; 9491 break; 9492 } 9493 } 9494 } 9495 } 9496 } 9497 } 9498 } else { 9499 allowed = isPrivilegedApp(pkg); 9500 } 9501 } 9502 } 9503 if (!allowed) { 9504 if (!allowed && (bp.protectionLevel 9505 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9506 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9507 // If this was a previously normal/dangerous permission that got moved 9508 // to a system permission as part of the runtime permission redesign, then 9509 // we still want to blindly grant it to old apps. 9510 allowed = true; 9511 } 9512 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9513 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9514 // If this permission is to be granted to the system installer and 9515 // this app is an installer, then it gets the permission. 9516 allowed = true; 9517 } 9518 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9519 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9520 // If this permission is to be granted to the system verifier and 9521 // this app is a verifier, then it gets the permission. 9522 allowed = true; 9523 } 9524 if (!allowed && (bp.protectionLevel 9525 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9526 && isSystemApp(pkg)) { 9527 // Any pre-installed system app is allowed to get this permission. 9528 allowed = true; 9529 } 9530 if (!allowed && (bp.protectionLevel 9531 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9532 // For development permissions, a development permission 9533 // is granted only if it was already granted. 9534 allowed = origPermissions.hasInstallPermission(perm); 9535 } 9536 } 9537 return allowed; 9538 } 9539 9540 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9541 final int permCount = pkg.requestedPermissions.size(); 9542 for (int j = 0; j < permCount; j++) { 9543 String requestedPermission = pkg.requestedPermissions.get(j); 9544 if (permission.equals(requestedPermission)) { 9545 return true; 9546 } 9547 } 9548 return false; 9549 } 9550 9551 final class ActivityIntentResolver 9552 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9553 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9554 boolean defaultOnly, int userId) { 9555 if (!sUserManager.exists(userId)) return null; 9556 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9557 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9558 } 9559 9560 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9561 int userId) { 9562 if (!sUserManager.exists(userId)) return null; 9563 mFlags = flags; 9564 return super.queryIntent(intent, resolvedType, 9565 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9566 } 9567 9568 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9569 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9570 if (!sUserManager.exists(userId)) return null; 9571 if (packageActivities == null) { 9572 return null; 9573 } 9574 mFlags = flags; 9575 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9576 final int N = packageActivities.size(); 9577 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9578 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9579 9580 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9581 for (int i = 0; i < N; ++i) { 9582 intentFilters = packageActivities.get(i).intents; 9583 if (intentFilters != null && intentFilters.size() > 0) { 9584 PackageParser.ActivityIntentInfo[] array = 9585 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9586 intentFilters.toArray(array); 9587 listCut.add(array); 9588 } 9589 } 9590 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9591 } 9592 9593 public final void addActivity(PackageParser.Activity a, String type) { 9594 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9595 mActivities.put(a.getComponentName(), a); 9596 if (DEBUG_SHOW_INFO) 9597 Log.v( 9598 TAG, " " + type + " " + 9599 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9600 if (DEBUG_SHOW_INFO) 9601 Log.v(TAG, " Class=" + a.info.name); 9602 final int NI = a.intents.size(); 9603 for (int j=0; j<NI; j++) { 9604 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9605 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9606 intent.setPriority(0); 9607 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9608 + a.className + " with priority > 0, forcing to 0"); 9609 } 9610 if (DEBUG_SHOW_INFO) { 9611 Log.v(TAG, " IntentFilter:"); 9612 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9613 } 9614 if (!intent.debugCheck()) { 9615 Log.w(TAG, "==> For Activity " + a.info.name); 9616 } 9617 addFilter(intent); 9618 } 9619 } 9620 9621 public final void removeActivity(PackageParser.Activity a, String type) { 9622 mActivities.remove(a.getComponentName()); 9623 if (DEBUG_SHOW_INFO) { 9624 Log.v(TAG, " " + type + " " 9625 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9626 : a.info.name) + ":"); 9627 Log.v(TAG, " Class=" + a.info.name); 9628 } 9629 final int NI = a.intents.size(); 9630 for (int j=0; j<NI; j++) { 9631 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9632 if (DEBUG_SHOW_INFO) { 9633 Log.v(TAG, " IntentFilter:"); 9634 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9635 } 9636 removeFilter(intent); 9637 } 9638 } 9639 9640 @Override 9641 protected boolean allowFilterResult( 9642 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9643 ActivityInfo filterAi = filter.activity.info; 9644 for (int i=dest.size()-1; i>=0; i--) { 9645 ActivityInfo destAi = dest.get(i).activityInfo; 9646 if (destAi.name == filterAi.name 9647 && destAi.packageName == filterAi.packageName) { 9648 return false; 9649 } 9650 } 9651 return true; 9652 } 9653 9654 @Override 9655 protected ActivityIntentInfo[] newArray(int size) { 9656 return new ActivityIntentInfo[size]; 9657 } 9658 9659 @Override 9660 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9661 if (!sUserManager.exists(userId)) return true; 9662 PackageParser.Package p = filter.activity.owner; 9663 if (p != null) { 9664 PackageSetting ps = (PackageSetting)p.mExtras; 9665 if (ps != null) { 9666 // System apps are never considered stopped for purposes of 9667 // filtering, because there may be no way for the user to 9668 // actually re-launch them. 9669 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9670 && ps.getStopped(userId); 9671 } 9672 } 9673 return false; 9674 } 9675 9676 @Override 9677 protected boolean isPackageForFilter(String packageName, 9678 PackageParser.ActivityIntentInfo info) { 9679 return packageName.equals(info.activity.owner.packageName); 9680 } 9681 9682 @Override 9683 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9684 int match, int userId) { 9685 if (!sUserManager.exists(userId)) return null; 9686 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9687 return null; 9688 } 9689 final PackageParser.Activity activity = info.activity; 9690 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9691 if (ps == null) { 9692 return null; 9693 } 9694 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9695 ps.readUserState(userId), userId); 9696 if (ai == null) { 9697 return null; 9698 } 9699 final ResolveInfo res = new ResolveInfo(); 9700 res.activityInfo = ai; 9701 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9702 res.filter = info; 9703 } 9704 if (info != null) { 9705 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9706 } 9707 res.priority = info.getPriority(); 9708 res.preferredOrder = activity.owner.mPreferredOrder; 9709 //System.out.println("Result: " + res.activityInfo.className + 9710 // " = " + res.priority); 9711 res.match = match; 9712 res.isDefault = info.hasDefault; 9713 res.labelRes = info.labelRes; 9714 res.nonLocalizedLabel = info.nonLocalizedLabel; 9715 if (userNeedsBadging(userId)) { 9716 res.noResourceId = true; 9717 } else { 9718 res.icon = info.icon; 9719 } 9720 res.iconResourceId = info.icon; 9721 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9722 return res; 9723 } 9724 9725 @Override 9726 protected void sortResults(List<ResolveInfo> results) { 9727 Collections.sort(results, mResolvePrioritySorter); 9728 } 9729 9730 @Override 9731 protected void dumpFilter(PrintWriter out, String prefix, 9732 PackageParser.ActivityIntentInfo filter) { 9733 out.print(prefix); out.print( 9734 Integer.toHexString(System.identityHashCode(filter.activity))); 9735 out.print(' '); 9736 filter.activity.printComponentShortName(out); 9737 out.print(" filter "); 9738 out.println(Integer.toHexString(System.identityHashCode(filter))); 9739 } 9740 9741 @Override 9742 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9743 return filter.activity; 9744 } 9745 9746 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9747 PackageParser.Activity activity = (PackageParser.Activity)label; 9748 out.print(prefix); out.print( 9749 Integer.toHexString(System.identityHashCode(activity))); 9750 out.print(' '); 9751 activity.printComponentShortName(out); 9752 if (count > 1) { 9753 out.print(" ("); out.print(count); out.print(" filters)"); 9754 } 9755 out.println(); 9756 } 9757 9758// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9759// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9760// final List<ResolveInfo> retList = Lists.newArrayList(); 9761// while (i.hasNext()) { 9762// final ResolveInfo resolveInfo = i.next(); 9763// if (isEnabledLP(resolveInfo.activityInfo)) { 9764// retList.add(resolveInfo); 9765// } 9766// } 9767// return retList; 9768// } 9769 9770 // Keys are String (activity class name), values are Activity. 9771 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9772 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9773 private int mFlags; 9774 } 9775 9776 private final class ServiceIntentResolver 9777 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9778 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9779 boolean defaultOnly, int userId) { 9780 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9781 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9782 } 9783 9784 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9785 int userId) { 9786 if (!sUserManager.exists(userId)) return null; 9787 mFlags = flags; 9788 return super.queryIntent(intent, resolvedType, 9789 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9790 } 9791 9792 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9793 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9794 if (!sUserManager.exists(userId)) return null; 9795 if (packageServices == null) { 9796 return null; 9797 } 9798 mFlags = flags; 9799 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9800 final int N = packageServices.size(); 9801 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9802 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9803 9804 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9805 for (int i = 0; i < N; ++i) { 9806 intentFilters = packageServices.get(i).intents; 9807 if (intentFilters != null && intentFilters.size() > 0) { 9808 PackageParser.ServiceIntentInfo[] array = 9809 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9810 intentFilters.toArray(array); 9811 listCut.add(array); 9812 } 9813 } 9814 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9815 } 9816 9817 public final void addService(PackageParser.Service s) { 9818 mServices.put(s.getComponentName(), s); 9819 if (DEBUG_SHOW_INFO) { 9820 Log.v(TAG, " " 9821 + (s.info.nonLocalizedLabel != null 9822 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9823 Log.v(TAG, " Class=" + s.info.name); 9824 } 9825 final int NI = s.intents.size(); 9826 int j; 9827 for (j=0; j<NI; j++) { 9828 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9829 if (DEBUG_SHOW_INFO) { 9830 Log.v(TAG, " IntentFilter:"); 9831 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9832 } 9833 if (!intent.debugCheck()) { 9834 Log.w(TAG, "==> For Service " + s.info.name); 9835 } 9836 addFilter(intent); 9837 } 9838 } 9839 9840 public final void removeService(PackageParser.Service s) { 9841 mServices.remove(s.getComponentName()); 9842 if (DEBUG_SHOW_INFO) { 9843 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9844 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9845 Log.v(TAG, " Class=" + s.info.name); 9846 } 9847 final int NI = s.intents.size(); 9848 int j; 9849 for (j=0; j<NI; j++) { 9850 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9851 if (DEBUG_SHOW_INFO) { 9852 Log.v(TAG, " IntentFilter:"); 9853 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9854 } 9855 removeFilter(intent); 9856 } 9857 } 9858 9859 @Override 9860 protected boolean allowFilterResult( 9861 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9862 ServiceInfo filterSi = filter.service.info; 9863 for (int i=dest.size()-1; i>=0; i--) { 9864 ServiceInfo destAi = dest.get(i).serviceInfo; 9865 if (destAi.name == filterSi.name 9866 && destAi.packageName == filterSi.packageName) { 9867 return false; 9868 } 9869 } 9870 return true; 9871 } 9872 9873 @Override 9874 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9875 return new PackageParser.ServiceIntentInfo[size]; 9876 } 9877 9878 @Override 9879 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9880 if (!sUserManager.exists(userId)) return true; 9881 PackageParser.Package p = filter.service.owner; 9882 if (p != null) { 9883 PackageSetting ps = (PackageSetting)p.mExtras; 9884 if (ps != null) { 9885 // System apps are never considered stopped for purposes of 9886 // filtering, because there may be no way for the user to 9887 // actually re-launch them. 9888 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9889 && ps.getStopped(userId); 9890 } 9891 } 9892 return false; 9893 } 9894 9895 @Override 9896 protected boolean isPackageForFilter(String packageName, 9897 PackageParser.ServiceIntentInfo info) { 9898 return packageName.equals(info.service.owner.packageName); 9899 } 9900 9901 @Override 9902 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9903 int match, int userId) { 9904 if (!sUserManager.exists(userId)) return null; 9905 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9906 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9907 return null; 9908 } 9909 final PackageParser.Service service = info.service; 9910 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9911 if (ps == null) { 9912 return null; 9913 } 9914 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9915 ps.readUserState(userId), userId); 9916 if (si == null) { 9917 return null; 9918 } 9919 final ResolveInfo res = new ResolveInfo(); 9920 res.serviceInfo = si; 9921 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9922 res.filter = filter; 9923 } 9924 res.priority = info.getPriority(); 9925 res.preferredOrder = service.owner.mPreferredOrder; 9926 res.match = match; 9927 res.isDefault = info.hasDefault; 9928 res.labelRes = info.labelRes; 9929 res.nonLocalizedLabel = info.nonLocalizedLabel; 9930 res.icon = info.icon; 9931 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9932 return res; 9933 } 9934 9935 @Override 9936 protected void sortResults(List<ResolveInfo> results) { 9937 Collections.sort(results, mResolvePrioritySorter); 9938 } 9939 9940 @Override 9941 protected void dumpFilter(PrintWriter out, String prefix, 9942 PackageParser.ServiceIntentInfo filter) { 9943 out.print(prefix); out.print( 9944 Integer.toHexString(System.identityHashCode(filter.service))); 9945 out.print(' '); 9946 filter.service.printComponentShortName(out); 9947 out.print(" filter "); 9948 out.println(Integer.toHexString(System.identityHashCode(filter))); 9949 } 9950 9951 @Override 9952 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9953 return filter.service; 9954 } 9955 9956 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9957 PackageParser.Service service = (PackageParser.Service)label; 9958 out.print(prefix); out.print( 9959 Integer.toHexString(System.identityHashCode(service))); 9960 out.print(' '); 9961 service.printComponentShortName(out); 9962 if (count > 1) { 9963 out.print(" ("); out.print(count); out.print(" filters)"); 9964 } 9965 out.println(); 9966 } 9967 9968// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9969// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9970// final List<ResolveInfo> retList = Lists.newArrayList(); 9971// while (i.hasNext()) { 9972// final ResolveInfo resolveInfo = (ResolveInfo) i; 9973// if (isEnabledLP(resolveInfo.serviceInfo)) { 9974// retList.add(resolveInfo); 9975// } 9976// } 9977// return retList; 9978// } 9979 9980 // Keys are String (activity class name), values are Activity. 9981 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9982 = new ArrayMap<ComponentName, PackageParser.Service>(); 9983 private int mFlags; 9984 }; 9985 9986 private final class ProviderIntentResolver 9987 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9988 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9989 boolean defaultOnly, int userId) { 9990 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9991 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9992 } 9993 9994 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9995 int userId) { 9996 if (!sUserManager.exists(userId)) 9997 return null; 9998 mFlags = flags; 9999 return super.queryIntent(intent, resolvedType, 10000 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10001 } 10002 10003 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10004 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10005 if (!sUserManager.exists(userId)) 10006 return null; 10007 if (packageProviders == null) { 10008 return null; 10009 } 10010 mFlags = flags; 10011 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10012 final int N = packageProviders.size(); 10013 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10014 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10015 10016 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10017 for (int i = 0; i < N; ++i) { 10018 intentFilters = packageProviders.get(i).intents; 10019 if (intentFilters != null && intentFilters.size() > 0) { 10020 PackageParser.ProviderIntentInfo[] array = 10021 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10022 intentFilters.toArray(array); 10023 listCut.add(array); 10024 } 10025 } 10026 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10027 } 10028 10029 public final void addProvider(PackageParser.Provider p) { 10030 if (mProviders.containsKey(p.getComponentName())) { 10031 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10032 return; 10033 } 10034 10035 mProviders.put(p.getComponentName(), p); 10036 if (DEBUG_SHOW_INFO) { 10037 Log.v(TAG, " " 10038 + (p.info.nonLocalizedLabel != null 10039 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10040 Log.v(TAG, " Class=" + p.info.name); 10041 } 10042 final int NI = p.intents.size(); 10043 int j; 10044 for (j = 0; j < NI; j++) { 10045 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10046 if (DEBUG_SHOW_INFO) { 10047 Log.v(TAG, " IntentFilter:"); 10048 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10049 } 10050 if (!intent.debugCheck()) { 10051 Log.w(TAG, "==> For Provider " + p.info.name); 10052 } 10053 addFilter(intent); 10054 } 10055 } 10056 10057 public final void removeProvider(PackageParser.Provider p) { 10058 mProviders.remove(p.getComponentName()); 10059 if (DEBUG_SHOW_INFO) { 10060 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10061 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10062 Log.v(TAG, " Class=" + p.info.name); 10063 } 10064 final int NI = p.intents.size(); 10065 int j; 10066 for (j = 0; j < NI; j++) { 10067 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10068 if (DEBUG_SHOW_INFO) { 10069 Log.v(TAG, " IntentFilter:"); 10070 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10071 } 10072 removeFilter(intent); 10073 } 10074 } 10075 10076 @Override 10077 protected boolean allowFilterResult( 10078 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10079 ProviderInfo filterPi = filter.provider.info; 10080 for (int i = dest.size() - 1; i >= 0; i--) { 10081 ProviderInfo destPi = dest.get(i).providerInfo; 10082 if (destPi.name == filterPi.name 10083 && destPi.packageName == filterPi.packageName) { 10084 return false; 10085 } 10086 } 10087 return true; 10088 } 10089 10090 @Override 10091 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10092 return new PackageParser.ProviderIntentInfo[size]; 10093 } 10094 10095 @Override 10096 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10097 if (!sUserManager.exists(userId)) 10098 return true; 10099 PackageParser.Package p = filter.provider.owner; 10100 if (p != null) { 10101 PackageSetting ps = (PackageSetting) p.mExtras; 10102 if (ps != null) { 10103 // System apps are never considered stopped for purposes of 10104 // filtering, because there may be no way for the user to 10105 // actually re-launch them. 10106 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10107 && ps.getStopped(userId); 10108 } 10109 } 10110 return false; 10111 } 10112 10113 @Override 10114 protected boolean isPackageForFilter(String packageName, 10115 PackageParser.ProviderIntentInfo info) { 10116 return packageName.equals(info.provider.owner.packageName); 10117 } 10118 10119 @Override 10120 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10121 int match, int userId) { 10122 if (!sUserManager.exists(userId)) 10123 return null; 10124 final PackageParser.ProviderIntentInfo info = filter; 10125 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10126 return null; 10127 } 10128 final PackageParser.Provider provider = info.provider; 10129 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10130 if (ps == null) { 10131 return null; 10132 } 10133 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10134 ps.readUserState(userId), userId); 10135 if (pi == null) { 10136 return null; 10137 } 10138 final ResolveInfo res = new ResolveInfo(); 10139 res.providerInfo = pi; 10140 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10141 res.filter = filter; 10142 } 10143 res.priority = info.getPriority(); 10144 res.preferredOrder = provider.owner.mPreferredOrder; 10145 res.match = match; 10146 res.isDefault = info.hasDefault; 10147 res.labelRes = info.labelRes; 10148 res.nonLocalizedLabel = info.nonLocalizedLabel; 10149 res.icon = info.icon; 10150 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10151 return res; 10152 } 10153 10154 @Override 10155 protected void sortResults(List<ResolveInfo> results) { 10156 Collections.sort(results, mResolvePrioritySorter); 10157 } 10158 10159 @Override 10160 protected void dumpFilter(PrintWriter out, String prefix, 10161 PackageParser.ProviderIntentInfo filter) { 10162 out.print(prefix); 10163 out.print( 10164 Integer.toHexString(System.identityHashCode(filter.provider))); 10165 out.print(' '); 10166 filter.provider.printComponentShortName(out); 10167 out.print(" filter "); 10168 out.println(Integer.toHexString(System.identityHashCode(filter))); 10169 } 10170 10171 @Override 10172 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10173 return filter.provider; 10174 } 10175 10176 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10177 PackageParser.Provider provider = (PackageParser.Provider)label; 10178 out.print(prefix); out.print( 10179 Integer.toHexString(System.identityHashCode(provider))); 10180 out.print(' '); 10181 provider.printComponentShortName(out); 10182 if (count > 1) { 10183 out.print(" ("); out.print(count); out.print(" filters)"); 10184 } 10185 out.println(); 10186 } 10187 10188 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10189 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10190 private int mFlags; 10191 } 10192 10193 private static final class EphemeralIntentResolver 10194 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10195 @Override 10196 protected EphemeralResolveIntentInfo[] newArray(int size) { 10197 return new EphemeralResolveIntentInfo[size]; 10198 } 10199 10200 @Override 10201 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10202 return true; 10203 } 10204 10205 @Override 10206 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10207 int userId) { 10208 if (!sUserManager.exists(userId)) { 10209 return null; 10210 } 10211 return info.getEphemeralResolveInfo(); 10212 } 10213 } 10214 10215 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10216 new Comparator<ResolveInfo>() { 10217 public int compare(ResolveInfo r1, ResolveInfo r2) { 10218 int v1 = r1.priority; 10219 int v2 = r2.priority; 10220 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10221 if (v1 != v2) { 10222 return (v1 > v2) ? -1 : 1; 10223 } 10224 v1 = r1.preferredOrder; 10225 v2 = r2.preferredOrder; 10226 if (v1 != v2) { 10227 return (v1 > v2) ? -1 : 1; 10228 } 10229 if (r1.isDefault != r2.isDefault) { 10230 return r1.isDefault ? -1 : 1; 10231 } 10232 v1 = r1.match; 10233 v2 = r2.match; 10234 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10235 if (v1 != v2) { 10236 return (v1 > v2) ? -1 : 1; 10237 } 10238 if (r1.system != r2.system) { 10239 return r1.system ? -1 : 1; 10240 } 10241 if (r1.activityInfo != null) { 10242 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10243 } 10244 if (r1.serviceInfo != null) { 10245 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10246 } 10247 if (r1.providerInfo != null) { 10248 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10249 } 10250 return 0; 10251 } 10252 }; 10253 10254 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10255 new Comparator<ProviderInfo>() { 10256 public int compare(ProviderInfo p1, ProviderInfo p2) { 10257 final int v1 = p1.initOrder; 10258 final int v2 = p2.initOrder; 10259 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10260 } 10261 }; 10262 10263 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10264 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10265 final int[] userIds) { 10266 mHandler.post(new Runnable() { 10267 @Override 10268 public void run() { 10269 try { 10270 final IActivityManager am = ActivityManagerNative.getDefault(); 10271 if (am == null) return; 10272 final int[] resolvedUserIds; 10273 if (userIds == null) { 10274 resolvedUserIds = am.getRunningUserIds(); 10275 } else { 10276 resolvedUserIds = userIds; 10277 } 10278 for (int id : resolvedUserIds) { 10279 final Intent intent = new Intent(action, 10280 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10281 if (extras != null) { 10282 intent.putExtras(extras); 10283 } 10284 if (targetPkg != null) { 10285 intent.setPackage(targetPkg); 10286 } 10287 // Modify the UID when posting to other users 10288 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10289 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10290 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10291 intent.putExtra(Intent.EXTRA_UID, uid); 10292 } 10293 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10294 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10295 if (DEBUG_BROADCASTS) { 10296 RuntimeException here = new RuntimeException("here"); 10297 here.fillInStackTrace(); 10298 Slog.d(TAG, "Sending to user " + id + ": " 10299 + intent.toShortString(false, true, false, false) 10300 + " " + intent.getExtras(), here); 10301 } 10302 am.broadcastIntent(null, intent, null, finishedReceiver, 10303 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10304 null, finishedReceiver != null, false, id); 10305 } 10306 } catch (RemoteException ex) { 10307 } 10308 } 10309 }); 10310 } 10311 10312 /** 10313 * Check if the external storage media is available. This is true if there 10314 * is a mounted external storage medium or if the external storage is 10315 * emulated. 10316 */ 10317 private boolean isExternalMediaAvailable() { 10318 return mMediaMounted || Environment.isExternalStorageEmulated(); 10319 } 10320 10321 @Override 10322 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10323 // writer 10324 synchronized (mPackages) { 10325 if (!isExternalMediaAvailable()) { 10326 // If the external storage is no longer mounted at this point, 10327 // the caller may not have been able to delete all of this 10328 // packages files and can not delete any more. Bail. 10329 return null; 10330 } 10331 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10332 if (lastPackage != null) { 10333 pkgs.remove(lastPackage); 10334 } 10335 if (pkgs.size() > 0) { 10336 return pkgs.get(0); 10337 } 10338 } 10339 return null; 10340 } 10341 10342 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10343 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10344 userId, andCode ? 1 : 0, packageName); 10345 if (mSystemReady) { 10346 msg.sendToTarget(); 10347 } else { 10348 if (mPostSystemReadyMessages == null) { 10349 mPostSystemReadyMessages = new ArrayList<>(); 10350 } 10351 mPostSystemReadyMessages.add(msg); 10352 } 10353 } 10354 10355 void startCleaningPackages() { 10356 // reader 10357 synchronized (mPackages) { 10358 if (!isExternalMediaAvailable()) { 10359 return; 10360 } 10361 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10362 return; 10363 } 10364 } 10365 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10366 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10367 IActivityManager am = ActivityManagerNative.getDefault(); 10368 if (am != null) { 10369 try { 10370 am.startService(null, intent, null, mContext.getOpPackageName(), 10371 UserHandle.USER_SYSTEM); 10372 } catch (RemoteException e) { 10373 } 10374 } 10375 } 10376 10377 @Override 10378 public void installPackage(String originPath, IPackageInstallObserver2 observer, 10379 int installFlags, String installerPackageName, VerificationParams verificationParams, 10380 String packageAbiOverride) { 10381 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 10382 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 10383 } 10384 10385 @Override 10386 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10387 int installFlags, String installerPackageName, VerificationParams verificationParams, 10388 String packageAbiOverride, int userId) { 10389 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10390 10391 final int callingUid = Binder.getCallingUid(); 10392 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 10393 10394 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10395 try { 10396 if (observer != null) { 10397 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10398 } 10399 } catch (RemoteException re) { 10400 } 10401 return; 10402 } 10403 10404 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10405 installFlags |= PackageManager.INSTALL_FROM_ADB; 10406 10407 } else { 10408 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10409 // about installerPackageName. 10410 10411 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10412 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10413 } 10414 10415 UserHandle user; 10416 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10417 user = UserHandle.ALL; 10418 } else { 10419 user = new UserHandle(userId); 10420 } 10421 10422 // Only system components can circumvent runtime permissions when installing. 10423 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10424 && mContext.checkCallingOrSelfPermission(Manifest.permission 10425 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10426 throw new SecurityException("You need the " 10427 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10428 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10429 } 10430 10431 verificationParams.setInstallerUid(callingUid); 10432 10433 final File originFile = new File(originPath); 10434 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10435 10436 final Message msg = mHandler.obtainMessage(INIT_COPY); 10437 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10438 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10439 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10440 msg.obj = params; 10441 10442 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10443 System.identityHashCode(msg.obj)); 10444 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10445 System.identityHashCode(msg.obj)); 10446 10447 mHandler.sendMessage(msg); 10448 } 10449 10450 void installStage(String packageName, File stagedDir, String stagedCid, 10451 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10452 String installerPackageName, int installerUid, UserHandle user) { 10453 if (DEBUG_EPHEMERAL) { 10454 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10455 Slog.d(TAG, "Ephemeral install of " + packageName); 10456 } 10457 } 10458 final VerificationParams verifParams = new VerificationParams( 10459 null, sessionParams.originatingUri, sessionParams.referrerUri, 10460 sessionParams.originatingUid); 10461 verifParams.setInstallerUid(installerUid); 10462 10463 final OriginInfo origin; 10464 if (stagedDir != null) { 10465 origin = OriginInfo.fromStagedFile(stagedDir); 10466 } else { 10467 origin = OriginInfo.fromStagedContainer(stagedCid); 10468 } 10469 10470 final Message msg = mHandler.obtainMessage(INIT_COPY); 10471 final InstallParams params = new InstallParams(origin, null, observer, 10472 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10473 verifParams, user, sessionParams.abiOverride, 10474 sessionParams.grantedRuntimePermissions); 10475 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10476 msg.obj = params; 10477 10478 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10479 System.identityHashCode(msg.obj)); 10480 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10481 System.identityHashCode(msg.obj)); 10482 10483 mHandler.sendMessage(msg); 10484 } 10485 10486 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10487 int userId) { 10488 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10489 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10490 } 10491 10492 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10493 int appId, int userId) { 10494 Bundle extras = new Bundle(1); 10495 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10496 10497 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10498 packageName, extras, 0, null, null, new int[] {userId}); 10499 try { 10500 IActivityManager am = ActivityManagerNative.getDefault(); 10501 if (isSystem && am.isUserRunning(userId, 0)) { 10502 // The just-installed/enabled app is bundled on the system, so presumed 10503 // to be able to run automatically without needing an explicit launch. 10504 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10505 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10506 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10507 .setPackage(packageName); 10508 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10509 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10510 } 10511 } catch (RemoteException e) { 10512 // shouldn't happen 10513 Slog.w(TAG, "Unable to bootstrap installed package", e); 10514 } 10515 } 10516 10517 @Override 10518 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10519 int userId) { 10520 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10521 PackageSetting pkgSetting; 10522 final int uid = Binder.getCallingUid(); 10523 enforceCrossUserPermission(uid, userId, true, true, 10524 "setApplicationHiddenSetting for user " + userId); 10525 10526 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10527 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10528 return false; 10529 } 10530 10531 long callingId = Binder.clearCallingIdentity(); 10532 try { 10533 boolean sendAdded = false; 10534 boolean sendRemoved = false; 10535 // writer 10536 synchronized (mPackages) { 10537 pkgSetting = mSettings.mPackages.get(packageName); 10538 if (pkgSetting == null) { 10539 return false; 10540 } 10541 if (pkgSetting.getHidden(userId) != hidden) { 10542 pkgSetting.setHidden(hidden, userId); 10543 mSettings.writePackageRestrictionsLPr(userId); 10544 if (hidden) { 10545 sendRemoved = true; 10546 } else { 10547 sendAdded = true; 10548 } 10549 } 10550 } 10551 if (sendAdded) { 10552 sendPackageAddedForUser(packageName, pkgSetting, userId); 10553 return true; 10554 } 10555 if (sendRemoved) { 10556 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10557 "hiding pkg"); 10558 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10559 return true; 10560 } 10561 } finally { 10562 Binder.restoreCallingIdentity(callingId); 10563 } 10564 return false; 10565 } 10566 10567 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10568 int userId) { 10569 final PackageRemovedInfo info = new PackageRemovedInfo(); 10570 info.removedPackage = packageName; 10571 info.removedUsers = new int[] {userId}; 10572 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10573 info.sendPackageRemovedBroadcasts(); 10574 } 10575 10576 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10577 if (pkgList.length > 0) { 10578 Bundle extras = new Bundle(1); 10579 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10580 10581 sendPackageBroadcast( 10582 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10583 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10584 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10585 new int[] {userId}); 10586 } 10587 } 10588 10589 /** 10590 * Returns true if application is not found or there was an error. Otherwise it returns 10591 * the hidden state of the package for the given user. 10592 */ 10593 @Override 10594 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10595 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10596 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10597 false, "getApplicationHidden for user " + userId); 10598 PackageSetting pkgSetting; 10599 long callingId = Binder.clearCallingIdentity(); 10600 try { 10601 // writer 10602 synchronized (mPackages) { 10603 pkgSetting = mSettings.mPackages.get(packageName); 10604 if (pkgSetting == null) { 10605 return true; 10606 } 10607 return pkgSetting.getHidden(userId); 10608 } 10609 } finally { 10610 Binder.restoreCallingIdentity(callingId); 10611 } 10612 } 10613 10614 /** 10615 * @hide 10616 */ 10617 @Override 10618 public int installExistingPackageAsUser(String packageName, int userId) { 10619 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10620 null); 10621 PackageSetting pkgSetting; 10622 final int uid = Binder.getCallingUid(); 10623 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10624 + userId); 10625 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10626 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10627 } 10628 10629 long callingId = Binder.clearCallingIdentity(); 10630 try { 10631 boolean installed = false; 10632 10633 // writer 10634 synchronized (mPackages) { 10635 pkgSetting = mSettings.mPackages.get(packageName); 10636 if (pkgSetting == null) { 10637 return PackageManager.INSTALL_FAILED_INVALID_URI; 10638 } 10639 if (!pkgSetting.getInstalled(userId)) { 10640 pkgSetting.setInstalled(true, userId); 10641 pkgSetting.setHidden(false, userId); 10642 mSettings.writePackageRestrictionsLPr(userId); 10643 if (pkgSetting.pkg != null) { 10644 prepareAppDataAfterInstall(pkgSetting.pkg); 10645 } 10646 installed = true; 10647 } 10648 } 10649 10650 if (installed) { 10651 sendPackageAddedForUser(packageName, pkgSetting, userId); 10652 } 10653 } finally { 10654 Binder.restoreCallingIdentity(callingId); 10655 } 10656 10657 return PackageManager.INSTALL_SUCCEEDED; 10658 } 10659 10660 boolean isUserRestricted(int userId, String restrictionKey) { 10661 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10662 if (restrictions.getBoolean(restrictionKey, false)) { 10663 Log.w(TAG, "User is restricted: " + restrictionKey); 10664 return true; 10665 } 10666 return false; 10667 } 10668 10669 @Override 10670 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10671 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10672 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10673 "setPackageSuspended for user " + userId); 10674 10675 // TODO: investigate and add more restrictions for suspending crucial packages. 10676 if (isPackageDeviceAdmin(packageName, userId)) { 10677 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10678 + "\": has active device admin"); 10679 return false; 10680 } 10681 10682 long callingId = Binder.clearCallingIdentity(); 10683 try { 10684 boolean changed = false; 10685 boolean success = false; 10686 int appId = -1; 10687 synchronized (mPackages) { 10688 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10689 if (pkgSetting != null) { 10690 if (pkgSetting.getSuspended(userId) != suspended) { 10691 pkgSetting.setSuspended(suspended, userId); 10692 mSettings.writePackageRestrictionsLPr(userId); 10693 appId = pkgSetting.appId; 10694 changed = true; 10695 } 10696 success = true; 10697 } 10698 } 10699 10700 if (changed) { 10701 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10702 if (suspended) { 10703 killApplication(packageName, UserHandle.getUid(userId, appId), 10704 "suspending package"); 10705 } 10706 } 10707 return success; 10708 } finally { 10709 Binder.restoreCallingIdentity(callingId); 10710 } 10711 } 10712 10713 @Override 10714 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10715 mContext.enforceCallingOrSelfPermission( 10716 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10717 "Only package verification agents can verify applications"); 10718 10719 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10720 final PackageVerificationResponse response = new PackageVerificationResponse( 10721 verificationCode, Binder.getCallingUid()); 10722 msg.arg1 = id; 10723 msg.obj = response; 10724 mHandler.sendMessage(msg); 10725 } 10726 10727 @Override 10728 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10729 long millisecondsToDelay) { 10730 mContext.enforceCallingOrSelfPermission( 10731 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10732 "Only package verification agents can extend verification timeouts"); 10733 10734 final PackageVerificationState state = mPendingVerification.get(id); 10735 final PackageVerificationResponse response = new PackageVerificationResponse( 10736 verificationCodeAtTimeout, Binder.getCallingUid()); 10737 10738 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10739 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10740 } 10741 if (millisecondsToDelay < 0) { 10742 millisecondsToDelay = 0; 10743 } 10744 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10745 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10746 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10747 } 10748 10749 if ((state != null) && !state.timeoutExtended()) { 10750 state.extendTimeout(); 10751 10752 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10753 msg.arg1 = id; 10754 msg.obj = response; 10755 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10756 } 10757 } 10758 10759 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10760 int verificationCode, UserHandle user) { 10761 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10762 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10763 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10764 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10765 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10766 10767 mContext.sendBroadcastAsUser(intent, user, 10768 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10769 } 10770 10771 private ComponentName matchComponentForVerifier(String packageName, 10772 List<ResolveInfo> receivers) { 10773 ActivityInfo targetReceiver = null; 10774 10775 final int NR = receivers.size(); 10776 for (int i = 0; i < NR; i++) { 10777 final ResolveInfo info = receivers.get(i); 10778 if (info.activityInfo == null) { 10779 continue; 10780 } 10781 10782 if (packageName.equals(info.activityInfo.packageName)) { 10783 targetReceiver = info.activityInfo; 10784 break; 10785 } 10786 } 10787 10788 if (targetReceiver == null) { 10789 return null; 10790 } 10791 10792 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10793 } 10794 10795 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10796 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10797 if (pkgInfo.verifiers.length == 0) { 10798 return null; 10799 } 10800 10801 final int N = pkgInfo.verifiers.length; 10802 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10803 for (int i = 0; i < N; i++) { 10804 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10805 10806 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10807 receivers); 10808 if (comp == null) { 10809 continue; 10810 } 10811 10812 final int verifierUid = getUidForVerifier(verifierInfo); 10813 if (verifierUid == -1) { 10814 continue; 10815 } 10816 10817 if (DEBUG_VERIFY) { 10818 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10819 + " with the correct signature"); 10820 } 10821 sufficientVerifiers.add(comp); 10822 verificationState.addSufficientVerifier(verifierUid); 10823 } 10824 10825 return sufficientVerifiers; 10826 } 10827 10828 private int getUidForVerifier(VerifierInfo verifierInfo) { 10829 synchronized (mPackages) { 10830 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10831 if (pkg == null) { 10832 return -1; 10833 } else if (pkg.mSignatures.length != 1) { 10834 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10835 + " has more than one signature; ignoring"); 10836 return -1; 10837 } 10838 10839 /* 10840 * If the public key of the package's signature does not match 10841 * our expected public key, then this is a different package and 10842 * we should skip. 10843 */ 10844 10845 final byte[] expectedPublicKey; 10846 try { 10847 final Signature verifierSig = pkg.mSignatures[0]; 10848 final PublicKey publicKey = verifierSig.getPublicKey(); 10849 expectedPublicKey = publicKey.getEncoded(); 10850 } catch (CertificateException e) { 10851 return -1; 10852 } 10853 10854 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10855 10856 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10857 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10858 + " does not have the expected public key; ignoring"); 10859 return -1; 10860 } 10861 10862 return pkg.applicationInfo.uid; 10863 } 10864 } 10865 10866 @Override 10867 public void finishPackageInstall(int token) { 10868 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10869 10870 if (DEBUG_INSTALL) { 10871 Slog.v(TAG, "BM finishing package install for " + token); 10872 } 10873 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10874 10875 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10876 mHandler.sendMessage(msg); 10877 } 10878 10879 /** 10880 * Get the verification agent timeout. 10881 * 10882 * @return verification timeout in milliseconds 10883 */ 10884 private long getVerificationTimeout() { 10885 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10886 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10887 DEFAULT_VERIFICATION_TIMEOUT); 10888 } 10889 10890 /** 10891 * Get the default verification agent response code. 10892 * 10893 * @return default verification response code 10894 */ 10895 private int getDefaultVerificationResponse() { 10896 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10897 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10898 DEFAULT_VERIFICATION_RESPONSE); 10899 } 10900 10901 /** 10902 * Check whether or not package verification has been enabled. 10903 * 10904 * @return true if verification should be performed 10905 */ 10906 private boolean isVerificationEnabled(int userId, int installFlags) { 10907 if (!DEFAULT_VERIFY_ENABLE) { 10908 return false; 10909 } 10910 // Ephemeral apps don't get the full verification treatment 10911 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10912 if (DEBUG_EPHEMERAL) { 10913 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10914 } 10915 return false; 10916 } 10917 10918 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10919 10920 // Check if installing from ADB 10921 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10922 // Do not run verification in a test harness environment 10923 if (ActivityManager.isRunningInTestHarness()) { 10924 return false; 10925 } 10926 if (ensureVerifyAppsEnabled) { 10927 return true; 10928 } 10929 // Check if the developer does not want package verification for ADB installs 10930 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10931 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10932 return false; 10933 } 10934 } 10935 10936 if (ensureVerifyAppsEnabled) { 10937 return true; 10938 } 10939 10940 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10941 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10942 } 10943 10944 @Override 10945 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10946 throws RemoteException { 10947 mContext.enforceCallingOrSelfPermission( 10948 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10949 "Only intentfilter verification agents can verify applications"); 10950 10951 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10952 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10953 Binder.getCallingUid(), verificationCode, failedDomains); 10954 msg.arg1 = id; 10955 msg.obj = response; 10956 mHandler.sendMessage(msg); 10957 } 10958 10959 @Override 10960 public int getIntentVerificationStatus(String packageName, int userId) { 10961 synchronized (mPackages) { 10962 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10963 } 10964 } 10965 10966 @Override 10967 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10968 mContext.enforceCallingOrSelfPermission( 10969 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10970 10971 boolean result = false; 10972 synchronized (mPackages) { 10973 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10974 } 10975 if (result) { 10976 scheduleWritePackageRestrictionsLocked(userId); 10977 } 10978 return result; 10979 } 10980 10981 @Override 10982 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10983 synchronized (mPackages) { 10984 return mSettings.getIntentFilterVerificationsLPr(packageName); 10985 } 10986 } 10987 10988 @Override 10989 public List<IntentFilter> getAllIntentFilters(String packageName) { 10990 if (TextUtils.isEmpty(packageName)) { 10991 return Collections.<IntentFilter>emptyList(); 10992 } 10993 synchronized (mPackages) { 10994 PackageParser.Package pkg = mPackages.get(packageName); 10995 if (pkg == null || pkg.activities == null) { 10996 return Collections.<IntentFilter>emptyList(); 10997 } 10998 final int count = pkg.activities.size(); 10999 ArrayList<IntentFilter> result = new ArrayList<>(); 11000 for (int n=0; n<count; n++) { 11001 PackageParser.Activity activity = pkg.activities.get(n); 11002 if (activity.intents != null && activity.intents.size() > 0) { 11003 result.addAll(activity.intents); 11004 } 11005 } 11006 return result; 11007 } 11008 } 11009 11010 @Override 11011 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11012 mContext.enforceCallingOrSelfPermission( 11013 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11014 11015 synchronized (mPackages) { 11016 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11017 if (packageName != null) { 11018 result |= updateIntentVerificationStatus(packageName, 11019 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11020 userId); 11021 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11022 packageName, userId); 11023 } 11024 return result; 11025 } 11026 } 11027 11028 @Override 11029 public String getDefaultBrowserPackageName(int userId) { 11030 synchronized (mPackages) { 11031 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11032 } 11033 } 11034 11035 /** 11036 * Get the "allow unknown sources" setting. 11037 * 11038 * @return the current "allow unknown sources" setting 11039 */ 11040 private int getUnknownSourcesSettings() { 11041 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11042 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11043 -1); 11044 } 11045 11046 @Override 11047 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11048 final int uid = Binder.getCallingUid(); 11049 // writer 11050 synchronized (mPackages) { 11051 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11052 if (targetPackageSetting == null) { 11053 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11054 } 11055 11056 PackageSetting installerPackageSetting; 11057 if (installerPackageName != null) { 11058 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11059 if (installerPackageSetting == null) { 11060 throw new IllegalArgumentException("Unknown installer package: " 11061 + installerPackageName); 11062 } 11063 } else { 11064 installerPackageSetting = null; 11065 } 11066 11067 Signature[] callerSignature; 11068 Object obj = mSettings.getUserIdLPr(uid); 11069 if (obj != null) { 11070 if (obj instanceof SharedUserSetting) { 11071 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11072 } else if (obj instanceof PackageSetting) { 11073 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11074 } else { 11075 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11076 } 11077 } else { 11078 throw new SecurityException("Unknown calling UID: " + uid); 11079 } 11080 11081 // Verify: can't set installerPackageName to a package that is 11082 // not signed with the same cert as the caller. 11083 if (installerPackageSetting != null) { 11084 if (compareSignatures(callerSignature, 11085 installerPackageSetting.signatures.mSignatures) 11086 != PackageManager.SIGNATURE_MATCH) { 11087 throw new SecurityException( 11088 "Caller does not have same cert as new installer package " 11089 + installerPackageName); 11090 } 11091 } 11092 11093 // Verify: if target already has an installer package, it must 11094 // be signed with the same cert as the caller. 11095 if (targetPackageSetting.installerPackageName != null) { 11096 PackageSetting setting = mSettings.mPackages.get( 11097 targetPackageSetting.installerPackageName); 11098 // If the currently set package isn't valid, then it's always 11099 // okay to change it. 11100 if (setting != null) { 11101 if (compareSignatures(callerSignature, 11102 setting.signatures.mSignatures) 11103 != PackageManager.SIGNATURE_MATCH) { 11104 throw new SecurityException( 11105 "Caller does not have same cert as old installer package " 11106 + targetPackageSetting.installerPackageName); 11107 } 11108 } 11109 } 11110 11111 // Okay! 11112 targetPackageSetting.installerPackageName = installerPackageName; 11113 scheduleWriteSettingsLocked(); 11114 } 11115 } 11116 11117 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11118 // Queue up an async operation since the package installation may take a little while. 11119 mHandler.post(new Runnable() { 11120 public void run() { 11121 mHandler.removeCallbacks(this); 11122 // Result object to be returned 11123 PackageInstalledInfo res = new PackageInstalledInfo(); 11124 res.setReturnCode(currentStatus); 11125 res.uid = -1; 11126 res.pkg = null; 11127 res.removedInfo = null; 11128 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11129 args.doPreInstall(res.returnCode); 11130 synchronized (mInstallLock) { 11131 installPackageTracedLI(args, res); 11132 } 11133 args.doPostInstall(res.returnCode, res.uid); 11134 } 11135 11136 // A restore should be performed at this point if (a) the install 11137 // succeeded, (b) the operation is not an update, and (c) the new 11138 // package has not opted out of backup participation. 11139 final boolean update = res.removedInfo != null 11140 && res.removedInfo.removedPackage != null; 11141 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11142 boolean doRestore = !update 11143 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11144 11145 // Set up the post-install work request bookkeeping. This will be used 11146 // and cleaned up by the post-install event handling regardless of whether 11147 // there's a restore pass performed. Token values are >= 1. 11148 int token; 11149 if (mNextInstallToken < 0) mNextInstallToken = 1; 11150 token = mNextInstallToken++; 11151 11152 PostInstallData data = new PostInstallData(args, res); 11153 mRunningInstalls.put(token, data); 11154 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11155 11156 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11157 // Pass responsibility to the Backup Manager. It will perform a 11158 // restore if appropriate, then pass responsibility back to the 11159 // Package Manager to run the post-install observer callbacks 11160 // and broadcasts. 11161 IBackupManager bm = IBackupManager.Stub.asInterface( 11162 ServiceManager.getService(Context.BACKUP_SERVICE)); 11163 if (bm != null) { 11164 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11165 + " to BM for possible restore"); 11166 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11167 try { 11168 // TODO: http://b/22388012 11169 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11170 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11171 } else { 11172 doRestore = false; 11173 } 11174 } catch (RemoteException e) { 11175 // can't happen; the backup manager is local 11176 } catch (Exception e) { 11177 Slog.e(TAG, "Exception trying to enqueue restore", e); 11178 doRestore = false; 11179 } 11180 } else { 11181 Slog.e(TAG, "Backup Manager not found!"); 11182 doRestore = false; 11183 } 11184 } 11185 11186 if (!doRestore) { 11187 // No restore possible, or the Backup Manager was mysteriously not 11188 // available -- just fire the post-install work request directly. 11189 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11190 11191 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11192 11193 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11194 mHandler.sendMessage(msg); 11195 } 11196 } 11197 }); 11198 } 11199 11200 private abstract class HandlerParams { 11201 private static final int MAX_RETRIES = 4; 11202 11203 /** 11204 * Number of times startCopy() has been attempted and had a non-fatal 11205 * error. 11206 */ 11207 private int mRetries = 0; 11208 11209 /** User handle for the user requesting the information or installation. */ 11210 private final UserHandle mUser; 11211 String traceMethod; 11212 int traceCookie; 11213 11214 HandlerParams(UserHandle user) { 11215 mUser = user; 11216 } 11217 11218 UserHandle getUser() { 11219 return mUser; 11220 } 11221 11222 HandlerParams setTraceMethod(String traceMethod) { 11223 this.traceMethod = traceMethod; 11224 return this; 11225 } 11226 11227 HandlerParams setTraceCookie(int traceCookie) { 11228 this.traceCookie = traceCookie; 11229 return this; 11230 } 11231 11232 final boolean startCopy() { 11233 boolean res; 11234 try { 11235 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11236 11237 if (++mRetries > MAX_RETRIES) { 11238 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11239 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11240 handleServiceError(); 11241 return false; 11242 } else { 11243 handleStartCopy(); 11244 res = true; 11245 } 11246 } catch (RemoteException e) { 11247 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11248 mHandler.sendEmptyMessage(MCS_RECONNECT); 11249 res = false; 11250 } 11251 handleReturnCode(); 11252 return res; 11253 } 11254 11255 final void serviceError() { 11256 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11257 handleServiceError(); 11258 handleReturnCode(); 11259 } 11260 11261 abstract void handleStartCopy() throws RemoteException; 11262 abstract void handleServiceError(); 11263 abstract void handleReturnCode(); 11264 } 11265 11266 class MeasureParams extends HandlerParams { 11267 private final PackageStats mStats; 11268 private boolean mSuccess; 11269 11270 private final IPackageStatsObserver mObserver; 11271 11272 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11273 super(new UserHandle(stats.userHandle)); 11274 mObserver = observer; 11275 mStats = stats; 11276 } 11277 11278 @Override 11279 public String toString() { 11280 return "MeasureParams{" 11281 + Integer.toHexString(System.identityHashCode(this)) 11282 + " " + mStats.packageName + "}"; 11283 } 11284 11285 @Override 11286 void handleStartCopy() throws RemoteException { 11287 synchronized (mInstallLock) { 11288 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11289 } 11290 11291 if (mSuccess) { 11292 final boolean mounted; 11293 if (Environment.isExternalStorageEmulated()) { 11294 mounted = true; 11295 } else { 11296 final String status = Environment.getExternalStorageState(); 11297 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11298 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11299 } 11300 11301 if (mounted) { 11302 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11303 11304 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11305 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11306 11307 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11308 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11309 11310 // Always subtract cache size, since it's a subdirectory 11311 mStats.externalDataSize -= mStats.externalCacheSize; 11312 11313 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11314 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11315 11316 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11317 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11318 } 11319 } 11320 } 11321 11322 @Override 11323 void handleReturnCode() { 11324 if (mObserver != null) { 11325 try { 11326 mObserver.onGetStatsCompleted(mStats, mSuccess); 11327 } catch (RemoteException e) { 11328 Slog.i(TAG, "Observer no longer exists."); 11329 } 11330 } 11331 } 11332 11333 @Override 11334 void handleServiceError() { 11335 Slog.e(TAG, "Could not measure application " + mStats.packageName 11336 + " external storage"); 11337 } 11338 } 11339 11340 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11341 throws RemoteException { 11342 long result = 0; 11343 for (File path : paths) { 11344 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11345 } 11346 return result; 11347 } 11348 11349 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11350 for (File path : paths) { 11351 try { 11352 mcs.clearDirectory(path.getAbsolutePath()); 11353 } catch (RemoteException e) { 11354 } 11355 } 11356 } 11357 11358 static class OriginInfo { 11359 /** 11360 * Location where install is coming from, before it has been 11361 * copied/renamed into place. This could be a single monolithic APK 11362 * file, or a cluster directory. This location may be untrusted. 11363 */ 11364 final File file; 11365 final String cid; 11366 11367 /** 11368 * Flag indicating that {@link #file} or {@link #cid} has already been 11369 * staged, meaning downstream users don't need to defensively copy the 11370 * contents. 11371 */ 11372 final boolean staged; 11373 11374 /** 11375 * Flag indicating that {@link #file} or {@link #cid} is an already 11376 * installed app that is being moved. 11377 */ 11378 final boolean existing; 11379 11380 final String resolvedPath; 11381 final File resolvedFile; 11382 11383 static OriginInfo fromNothing() { 11384 return new OriginInfo(null, null, false, false); 11385 } 11386 11387 static OriginInfo fromUntrustedFile(File file) { 11388 return new OriginInfo(file, null, false, false); 11389 } 11390 11391 static OriginInfo fromExistingFile(File file) { 11392 return new OriginInfo(file, null, false, true); 11393 } 11394 11395 static OriginInfo fromStagedFile(File file) { 11396 return new OriginInfo(file, null, true, false); 11397 } 11398 11399 static OriginInfo fromStagedContainer(String cid) { 11400 return new OriginInfo(null, cid, true, false); 11401 } 11402 11403 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11404 this.file = file; 11405 this.cid = cid; 11406 this.staged = staged; 11407 this.existing = existing; 11408 11409 if (cid != null) { 11410 resolvedPath = PackageHelper.getSdDir(cid); 11411 resolvedFile = new File(resolvedPath); 11412 } else if (file != null) { 11413 resolvedPath = file.getAbsolutePath(); 11414 resolvedFile = file; 11415 } else { 11416 resolvedPath = null; 11417 resolvedFile = null; 11418 } 11419 } 11420 } 11421 11422 static class MoveInfo { 11423 final int moveId; 11424 final String fromUuid; 11425 final String toUuid; 11426 final String packageName; 11427 final String dataAppName; 11428 final int appId; 11429 final String seinfo; 11430 final int targetSdkVersion; 11431 11432 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11433 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11434 this.moveId = moveId; 11435 this.fromUuid = fromUuid; 11436 this.toUuid = toUuid; 11437 this.packageName = packageName; 11438 this.dataAppName = dataAppName; 11439 this.appId = appId; 11440 this.seinfo = seinfo; 11441 this.targetSdkVersion = targetSdkVersion; 11442 } 11443 } 11444 11445 class InstallParams extends HandlerParams { 11446 final OriginInfo origin; 11447 final MoveInfo move; 11448 final IPackageInstallObserver2 observer; 11449 int installFlags; 11450 final String installerPackageName; 11451 final String volumeUuid; 11452 final VerificationParams verificationParams; 11453 private InstallArgs mArgs; 11454 private int mRet; 11455 final String packageAbiOverride; 11456 final String[] grantedRuntimePermissions; 11457 11458 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11459 int installFlags, String installerPackageName, String volumeUuid, 11460 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 11461 String[] grantedPermissions) { 11462 super(user); 11463 this.origin = origin; 11464 this.move = move; 11465 this.observer = observer; 11466 this.installFlags = installFlags; 11467 this.installerPackageName = installerPackageName; 11468 this.volumeUuid = volumeUuid; 11469 this.verificationParams = verificationParams; 11470 this.packageAbiOverride = packageAbiOverride; 11471 this.grantedRuntimePermissions = grantedPermissions; 11472 } 11473 11474 @Override 11475 public String toString() { 11476 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11477 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11478 } 11479 11480 private int installLocationPolicy(PackageInfoLite pkgLite) { 11481 String packageName = pkgLite.packageName; 11482 int installLocation = pkgLite.installLocation; 11483 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11484 // reader 11485 synchronized (mPackages) { 11486 PackageParser.Package pkg = mPackages.get(packageName); 11487 if (pkg != null) { 11488 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11489 // Check for downgrading. 11490 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11491 try { 11492 checkDowngrade(pkg, pkgLite); 11493 } catch (PackageManagerException e) { 11494 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11495 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11496 } 11497 } 11498 // Check for updated system application. 11499 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11500 if (onSd) { 11501 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11502 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11503 } 11504 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11505 } else { 11506 if (onSd) { 11507 // Install flag overrides everything. 11508 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11509 } 11510 // If current upgrade specifies particular preference 11511 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11512 // Application explicitly specified internal. 11513 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11514 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11515 // App explictly prefers external. Let policy decide 11516 } else { 11517 // Prefer previous location 11518 if (isExternal(pkg)) { 11519 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11520 } 11521 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11522 } 11523 } 11524 } else { 11525 // Invalid install. Return error code 11526 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11527 } 11528 } 11529 } 11530 // All the special cases have been taken care of. 11531 // Return result based on recommended install location. 11532 if (onSd) { 11533 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11534 } 11535 return pkgLite.recommendedInstallLocation; 11536 } 11537 11538 /* 11539 * Invoke remote method to get package information and install 11540 * location values. Override install location based on default 11541 * policy if needed and then create install arguments based 11542 * on the install location. 11543 */ 11544 public void handleStartCopy() throws RemoteException { 11545 int ret = PackageManager.INSTALL_SUCCEEDED; 11546 11547 // If we're already staged, we've firmly committed to an install location 11548 if (origin.staged) { 11549 if (origin.file != null) { 11550 installFlags |= PackageManager.INSTALL_INTERNAL; 11551 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11552 } else if (origin.cid != null) { 11553 installFlags |= PackageManager.INSTALL_EXTERNAL; 11554 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11555 } else { 11556 throw new IllegalStateException("Invalid stage location"); 11557 } 11558 } 11559 11560 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11561 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11562 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11563 PackageInfoLite pkgLite = null; 11564 11565 if (onInt && onSd) { 11566 // Check if both bits are set. 11567 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11568 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11569 } else if (onSd && ephemeral) { 11570 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11571 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11572 } else { 11573 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11574 packageAbiOverride); 11575 11576 if (DEBUG_EPHEMERAL && ephemeral) { 11577 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11578 } 11579 11580 /* 11581 * If we have too little free space, try to free cache 11582 * before giving up. 11583 */ 11584 if (!origin.staged && pkgLite.recommendedInstallLocation 11585 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11586 // TODO: focus freeing disk space on the target device 11587 final StorageManager storage = StorageManager.from(mContext); 11588 final long lowThreshold = storage.getStorageLowBytes( 11589 Environment.getDataDirectory()); 11590 11591 final long sizeBytes = mContainerService.calculateInstalledSize( 11592 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11593 11594 try { 11595 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11596 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11597 installFlags, packageAbiOverride); 11598 } catch (InstallerException e) { 11599 Slog.w(TAG, "Failed to free cache", e); 11600 } 11601 11602 /* 11603 * The cache free must have deleted the file we 11604 * downloaded to install. 11605 * 11606 * TODO: fix the "freeCache" call to not delete 11607 * the file we care about. 11608 */ 11609 if (pkgLite.recommendedInstallLocation 11610 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11611 pkgLite.recommendedInstallLocation 11612 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11613 } 11614 } 11615 } 11616 11617 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11618 int loc = pkgLite.recommendedInstallLocation; 11619 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11620 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11621 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11622 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11623 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11624 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11625 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11626 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11627 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11628 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11629 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11630 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11631 } else { 11632 // Override with defaults if needed. 11633 loc = installLocationPolicy(pkgLite); 11634 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11635 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11636 } else if (!onSd && !onInt) { 11637 // Override install location with flags 11638 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11639 // Set the flag to install on external media. 11640 installFlags |= PackageManager.INSTALL_EXTERNAL; 11641 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11642 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11643 if (DEBUG_EPHEMERAL) { 11644 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11645 } 11646 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11647 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11648 |PackageManager.INSTALL_INTERNAL); 11649 } else { 11650 // Make sure the flag for installing on external 11651 // media is unset 11652 installFlags |= PackageManager.INSTALL_INTERNAL; 11653 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11654 } 11655 } 11656 } 11657 } 11658 11659 final InstallArgs args = createInstallArgs(this); 11660 mArgs = args; 11661 11662 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11663 // TODO: http://b/22976637 11664 // Apps installed for "all" users use the device owner to verify the app 11665 UserHandle verifierUser = getUser(); 11666 if (verifierUser == UserHandle.ALL) { 11667 verifierUser = UserHandle.SYSTEM; 11668 } 11669 11670 /* 11671 * Determine if we have any installed package verifiers. If we 11672 * do, then we'll defer to them to verify the packages. 11673 */ 11674 final int requiredUid = mRequiredVerifierPackage == null ? -1 11675 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11676 verifierUser.getIdentifier()); 11677 if (!origin.existing && requiredUid != -1 11678 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11679 final Intent verification = new Intent( 11680 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11681 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11682 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11683 PACKAGE_MIME_TYPE); 11684 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11685 11686 // Query all live verifiers based on current user state 11687 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11688 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11689 11690 if (DEBUG_VERIFY) { 11691 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11692 + verification.toString() + " with " + pkgLite.verifiers.length 11693 + " optional verifiers"); 11694 } 11695 11696 final int verificationId = mPendingVerificationToken++; 11697 11698 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11699 11700 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11701 installerPackageName); 11702 11703 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11704 installFlags); 11705 11706 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11707 pkgLite.packageName); 11708 11709 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11710 pkgLite.versionCode); 11711 11712 if (verificationParams != null) { 11713 if (verificationParams.getVerificationURI() != null) { 11714 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11715 verificationParams.getVerificationURI()); 11716 } 11717 if (verificationParams.getOriginatingURI() != null) { 11718 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11719 verificationParams.getOriginatingURI()); 11720 } 11721 if (verificationParams.getReferrer() != null) { 11722 verification.putExtra(Intent.EXTRA_REFERRER, 11723 verificationParams.getReferrer()); 11724 } 11725 if (verificationParams.getOriginatingUid() >= 0) { 11726 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11727 verificationParams.getOriginatingUid()); 11728 } 11729 if (verificationParams.getInstallerUid() >= 0) { 11730 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11731 verificationParams.getInstallerUid()); 11732 } 11733 } 11734 11735 final PackageVerificationState verificationState = new PackageVerificationState( 11736 requiredUid, args); 11737 11738 mPendingVerification.append(verificationId, verificationState); 11739 11740 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11741 receivers, verificationState); 11742 11743 /* 11744 * If any sufficient verifiers were listed in the package 11745 * manifest, attempt to ask them. 11746 */ 11747 if (sufficientVerifiers != null) { 11748 final int N = sufficientVerifiers.size(); 11749 if (N == 0) { 11750 Slog.i(TAG, "Additional verifiers required, but none installed."); 11751 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11752 } else { 11753 for (int i = 0; i < N; i++) { 11754 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11755 11756 final Intent sufficientIntent = new Intent(verification); 11757 sufficientIntent.setComponent(verifierComponent); 11758 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11759 } 11760 } 11761 } 11762 11763 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11764 mRequiredVerifierPackage, receivers); 11765 if (ret == PackageManager.INSTALL_SUCCEEDED 11766 && mRequiredVerifierPackage != null) { 11767 Trace.asyncTraceBegin( 11768 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11769 /* 11770 * Send the intent to the required verification agent, 11771 * but only start the verification timeout after the 11772 * target BroadcastReceivers have run. 11773 */ 11774 verification.setComponent(requiredVerifierComponent); 11775 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11776 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11777 new BroadcastReceiver() { 11778 @Override 11779 public void onReceive(Context context, Intent intent) { 11780 final Message msg = mHandler 11781 .obtainMessage(CHECK_PENDING_VERIFICATION); 11782 msg.arg1 = verificationId; 11783 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11784 } 11785 }, null, 0, null, null); 11786 11787 /* 11788 * We don't want the copy to proceed until verification 11789 * succeeds, so null out this field. 11790 */ 11791 mArgs = null; 11792 } 11793 } else { 11794 /* 11795 * No package verification is enabled, so immediately start 11796 * the remote call to initiate copy using temporary file. 11797 */ 11798 ret = args.copyApk(mContainerService, true); 11799 } 11800 } 11801 11802 mRet = ret; 11803 } 11804 11805 @Override 11806 void handleReturnCode() { 11807 // If mArgs is null, then MCS couldn't be reached. When it 11808 // reconnects, it will try again to install. At that point, this 11809 // will succeed. 11810 if (mArgs != null) { 11811 processPendingInstall(mArgs, mRet); 11812 } 11813 } 11814 11815 @Override 11816 void handleServiceError() { 11817 mArgs = createInstallArgs(this); 11818 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11819 } 11820 11821 public boolean isForwardLocked() { 11822 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11823 } 11824 } 11825 11826 /** 11827 * Used during creation of InstallArgs 11828 * 11829 * @param installFlags package installation flags 11830 * @return true if should be installed on external storage 11831 */ 11832 private static boolean installOnExternalAsec(int installFlags) { 11833 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11834 return false; 11835 } 11836 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11837 return true; 11838 } 11839 return false; 11840 } 11841 11842 /** 11843 * Used during creation of InstallArgs 11844 * 11845 * @param installFlags package installation flags 11846 * @return true if should be installed as forward locked 11847 */ 11848 private static boolean installForwardLocked(int installFlags) { 11849 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11850 } 11851 11852 private InstallArgs createInstallArgs(InstallParams params) { 11853 if (params.move != null) { 11854 return new MoveInstallArgs(params); 11855 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11856 return new AsecInstallArgs(params); 11857 } else { 11858 return new FileInstallArgs(params); 11859 } 11860 } 11861 11862 /** 11863 * Create args that describe an existing installed package. Typically used 11864 * when cleaning up old installs, or used as a move source. 11865 */ 11866 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11867 String resourcePath, String[] instructionSets) { 11868 final boolean isInAsec; 11869 if (installOnExternalAsec(installFlags)) { 11870 /* Apps on SD card are always in ASEC containers. */ 11871 isInAsec = true; 11872 } else if (installForwardLocked(installFlags) 11873 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11874 /* 11875 * Forward-locked apps are only in ASEC containers if they're the 11876 * new style 11877 */ 11878 isInAsec = true; 11879 } else { 11880 isInAsec = false; 11881 } 11882 11883 if (isInAsec) { 11884 return new AsecInstallArgs(codePath, instructionSets, 11885 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11886 } else { 11887 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11888 } 11889 } 11890 11891 static abstract class InstallArgs { 11892 /** @see InstallParams#origin */ 11893 final OriginInfo origin; 11894 /** @see InstallParams#move */ 11895 final MoveInfo move; 11896 11897 final IPackageInstallObserver2 observer; 11898 // Always refers to PackageManager flags only 11899 final int installFlags; 11900 final String installerPackageName; 11901 final String volumeUuid; 11902 final UserHandle user; 11903 final String abiOverride; 11904 final String[] installGrantPermissions; 11905 /** If non-null, drop an async trace when the install completes */ 11906 final String traceMethod; 11907 final int traceCookie; 11908 11909 // The list of instruction sets supported by this app. This is currently 11910 // only used during the rmdex() phase to clean up resources. We can get rid of this 11911 // if we move dex files under the common app path. 11912 /* nullable */ String[] instructionSets; 11913 11914 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11915 int installFlags, String installerPackageName, String volumeUuid, 11916 UserHandle user, String[] instructionSets, 11917 String abiOverride, String[] installGrantPermissions, 11918 String traceMethod, int traceCookie) { 11919 this.origin = origin; 11920 this.move = move; 11921 this.installFlags = installFlags; 11922 this.observer = observer; 11923 this.installerPackageName = installerPackageName; 11924 this.volumeUuid = volumeUuid; 11925 this.user = user; 11926 this.instructionSets = instructionSets; 11927 this.abiOverride = abiOverride; 11928 this.installGrantPermissions = installGrantPermissions; 11929 this.traceMethod = traceMethod; 11930 this.traceCookie = traceCookie; 11931 } 11932 11933 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11934 abstract int doPreInstall(int status); 11935 11936 /** 11937 * Rename package into final resting place. All paths on the given 11938 * scanned package should be updated to reflect the rename. 11939 */ 11940 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11941 abstract int doPostInstall(int status, int uid); 11942 11943 /** @see PackageSettingBase#codePathString */ 11944 abstract String getCodePath(); 11945 /** @see PackageSettingBase#resourcePathString */ 11946 abstract String getResourcePath(); 11947 11948 // Need installer lock especially for dex file removal. 11949 abstract void cleanUpResourcesLI(); 11950 abstract boolean doPostDeleteLI(boolean delete); 11951 11952 /** 11953 * Called before the source arguments are copied. This is used mostly 11954 * for MoveParams when it needs to read the source file to put it in the 11955 * destination. 11956 */ 11957 int doPreCopy() { 11958 return PackageManager.INSTALL_SUCCEEDED; 11959 } 11960 11961 /** 11962 * Called after the source arguments are copied. This is used mostly for 11963 * MoveParams when it needs to read the source file to put it in the 11964 * destination. 11965 * 11966 * @return 11967 */ 11968 int doPostCopy(int uid) { 11969 return PackageManager.INSTALL_SUCCEEDED; 11970 } 11971 11972 protected boolean isFwdLocked() { 11973 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11974 } 11975 11976 protected boolean isExternalAsec() { 11977 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11978 } 11979 11980 protected boolean isEphemeral() { 11981 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11982 } 11983 11984 UserHandle getUser() { 11985 return user; 11986 } 11987 } 11988 11989 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11990 if (!allCodePaths.isEmpty()) { 11991 if (instructionSets == null) { 11992 throw new IllegalStateException("instructionSet == null"); 11993 } 11994 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11995 for (String codePath : allCodePaths) { 11996 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11997 try { 11998 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11999 } catch (InstallerException ignored) { 12000 } 12001 } 12002 } 12003 } 12004 } 12005 12006 /** 12007 * Logic to handle installation of non-ASEC applications, including copying 12008 * and renaming logic. 12009 */ 12010 class FileInstallArgs extends InstallArgs { 12011 private File codeFile; 12012 private File resourceFile; 12013 12014 // Example topology: 12015 // /data/app/com.example/base.apk 12016 // /data/app/com.example/split_foo.apk 12017 // /data/app/com.example/lib/arm/libfoo.so 12018 // /data/app/com.example/lib/arm64/libfoo.so 12019 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12020 12021 /** New install */ 12022 FileInstallArgs(InstallParams params) { 12023 super(params.origin, params.move, params.observer, params.installFlags, 12024 params.installerPackageName, params.volumeUuid, 12025 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12026 params.grantedRuntimePermissions, 12027 params.traceMethod, params.traceCookie); 12028 if (isFwdLocked()) { 12029 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12030 } 12031 } 12032 12033 /** Existing install */ 12034 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12035 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12036 null, null, null, 0); 12037 this.codeFile = (codePath != null) ? new File(codePath) : null; 12038 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12039 } 12040 12041 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12042 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12043 try { 12044 return doCopyApk(imcs, temp); 12045 } finally { 12046 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12047 } 12048 } 12049 12050 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12051 if (origin.staged) { 12052 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12053 codeFile = origin.file; 12054 resourceFile = origin.file; 12055 return PackageManager.INSTALL_SUCCEEDED; 12056 } 12057 12058 try { 12059 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12060 final File tempDir = 12061 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12062 codeFile = tempDir; 12063 resourceFile = tempDir; 12064 } catch (IOException e) { 12065 Slog.w(TAG, "Failed to create copy file: " + e); 12066 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12067 } 12068 12069 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12070 @Override 12071 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12072 if (!FileUtils.isValidExtFilename(name)) { 12073 throw new IllegalArgumentException("Invalid filename: " + name); 12074 } 12075 try { 12076 final File file = new File(codeFile, name); 12077 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12078 O_RDWR | O_CREAT, 0644); 12079 Os.chmod(file.getAbsolutePath(), 0644); 12080 return new ParcelFileDescriptor(fd); 12081 } catch (ErrnoException e) { 12082 throw new RemoteException("Failed to open: " + e.getMessage()); 12083 } 12084 } 12085 }; 12086 12087 int ret = PackageManager.INSTALL_SUCCEEDED; 12088 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12089 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12090 Slog.e(TAG, "Failed to copy package"); 12091 return ret; 12092 } 12093 12094 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12095 NativeLibraryHelper.Handle handle = null; 12096 try { 12097 handle = NativeLibraryHelper.Handle.create(codeFile); 12098 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12099 abiOverride); 12100 } catch (IOException e) { 12101 Slog.e(TAG, "Copying native libraries failed", e); 12102 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12103 } finally { 12104 IoUtils.closeQuietly(handle); 12105 } 12106 12107 return ret; 12108 } 12109 12110 int doPreInstall(int status) { 12111 if (status != PackageManager.INSTALL_SUCCEEDED) { 12112 cleanUp(); 12113 } 12114 return status; 12115 } 12116 12117 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12118 if (status != PackageManager.INSTALL_SUCCEEDED) { 12119 cleanUp(); 12120 return false; 12121 } 12122 12123 final File targetDir = codeFile.getParentFile(); 12124 final File beforeCodeFile = codeFile; 12125 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12126 12127 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12128 try { 12129 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12130 } catch (ErrnoException e) { 12131 Slog.w(TAG, "Failed to rename", e); 12132 return false; 12133 } 12134 12135 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12136 Slog.w(TAG, "Failed to restorecon"); 12137 return false; 12138 } 12139 12140 // Reflect the rename internally 12141 codeFile = afterCodeFile; 12142 resourceFile = afterCodeFile; 12143 12144 // Reflect the rename in scanned details 12145 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12146 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12147 afterCodeFile, pkg.baseCodePath)); 12148 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12149 afterCodeFile, pkg.splitCodePaths)); 12150 12151 // Reflect the rename in app info 12152 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12153 pkg.setApplicationInfoCodePath(pkg.codePath); 12154 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12155 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12156 pkg.setApplicationInfoResourcePath(pkg.codePath); 12157 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12158 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12159 12160 return true; 12161 } 12162 12163 int doPostInstall(int status, int uid) { 12164 if (status != PackageManager.INSTALL_SUCCEEDED) { 12165 cleanUp(); 12166 } 12167 return status; 12168 } 12169 12170 @Override 12171 String getCodePath() { 12172 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12173 } 12174 12175 @Override 12176 String getResourcePath() { 12177 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12178 } 12179 12180 private boolean cleanUp() { 12181 if (codeFile == null || !codeFile.exists()) { 12182 return false; 12183 } 12184 12185 removeCodePathLI(codeFile); 12186 12187 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12188 resourceFile.delete(); 12189 } 12190 12191 return true; 12192 } 12193 12194 void cleanUpResourcesLI() { 12195 // Try enumerating all code paths before deleting 12196 List<String> allCodePaths = Collections.EMPTY_LIST; 12197 if (codeFile != null && codeFile.exists()) { 12198 try { 12199 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12200 allCodePaths = pkg.getAllCodePaths(); 12201 } catch (PackageParserException e) { 12202 // Ignored; we tried our best 12203 } 12204 } 12205 12206 cleanUp(); 12207 removeDexFiles(allCodePaths, instructionSets); 12208 } 12209 12210 boolean doPostDeleteLI(boolean delete) { 12211 // XXX err, shouldn't we respect the delete flag? 12212 cleanUpResourcesLI(); 12213 return true; 12214 } 12215 } 12216 12217 private boolean isAsecExternal(String cid) { 12218 final String asecPath = PackageHelper.getSdFilesystem(cid); 12219 return !asecPath.startsWith(mAsecInternalPath); 12220 } 12221 12222 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12223 PackageManagerException { 12224 if (copyRet < 0) { 12225 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12226 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12227 throw new PackageManagerException(copyRet, message); 12228 } 12229 } 12230 } 12231 12232 /** 12233 * Extract the MountService "container ID" from the full code path of an 12234 * .apk. 12235 */ 12236 static String cidFromCodePath(String fullCodePath) { 12237 int eidx = fullCodePath.lastIndexOf("/"); 12238 String subStr1 = fullCodePath.substring(0, eidx); 12239 int sidx = subStr1.lastIndexOf("/"); 12240 return subStr1.substring(sidx+1, eidx); 12241 } 12242 12243 /** 12244 * Logic to handle installation of ASEC applications, including copying and 12245 * renaming logic. 12246 */ 12247 class AsecInstallArgs extends InstallArgs { 12248 static final String RES_FILE_NAME = "pkg.apk"; 12249 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12250 12251 String cid; 12252 String packagePath; 12253 String resourcePath; 12254 12255 /** New install */ 12256 AsecInstallArgs(InstallParams params) { 12257 super(params.origin, params.move, params.observer, params.installFlags, 12258 params.installerPackageName, params.volumeUuid, 12259 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12260 params.grantedRuntimePermissions, 12261 params.traceMethod, params.traceCookie); 12262 } 12263 12264 /** Existing install */ 12265 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12266 boolean isExternal, boolean isForwardLocked) { 12267 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12268 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12269 instructionSets, null, null, null, 0); 12270 // Hackily pretend we're still looking at a full code path 12271 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12272 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12273 } 12274 12275 // Extract cid from fullCodePath 12276 int eidx = fullCodePath.lastIndexOf("/"); 12277 String subStr1 = fullCodePath.substring(0, eidx); 12278 int sidx = subStr1.lastIndexOf("/"); 12279 cid = subStr1.substring(sidx+1, eidx); 12280 setMountPath(subStr1); 12281 } 12282 12283 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12284 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12285 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12286 instructionSets, null, null, null, 0); 12287 this.cid = cid; 12288 setMountPath(PackageHelper.getSdDir(cid)); 12289 } 12290 12291 void createCopyFile() { 12292 cid = mInstallerService.allocateExternalStageCidLegacy(); 12293 } 12294 12295 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12296 if (origin.staged && origin.cid != null) { 12297 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12298 cid = origin.cid; 12299 setMountPath(PackageHelper.getSdDir(cid)); 12300 return PackageManager.INSTALL_SUCCEEDED; 12301 } 12302 12303 if (temp) { 12304 createCopyFile(); 12305 } else { 12306 /* 12307 * Pre-emptively destroy the container since it's destroyed if 12308 * copying fails due to it existing anyway. 12309 */ 12310 PackageHelper.destroySdDir(cid); 12311 } 12312 12313 final String newMountPath = imcs.copyPackageToContainer( 12314 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12315 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12316 12317 if (newMountPath != null) { 12318 setMountPath(newMountPath); 12319 return PackageManager.INSTALL_SUCCEEDED; 12320 } else { 12321 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12322 } 12323 } 12324 12325 @Override 12326 String getCodePath() { 12327 return packagePath; 12328 } 12329 12330 @Override 12331 String getResourcePath() { 12332 return resourcePath; 12333 } 12334 12335 int doPreInstall(int status) { 12336 if (status != PackageManager.INSTALL_SUCCEEDED) { 12337 // Destroy container 12338 PackageHelper.destroySdDir(cid); 12339 } else { 12340 boolean mounted = PackageHelper.isContainerMounted(cid); 12341 if (!mounted) { 12342 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12343 Process.SYSTEM_UID); 12344 if (newMountPath != null) { 12345 setMountPath(newMountPath); 12346 } else { 12347 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12348 } 12349 } 12350 } 12351 return status; 12352 } 12353 12354 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12355 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12356 String newMountPath = null; 12357 if (PackageHelper.isContainerMounted(cid)) { 12358 // Unmount the container 12359 if (!PackageHelper.unMountSdDir(cid)) { 12360 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12361 return false; 12362 } 12363 } 12364 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12365 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12366 " which might be stale. Will try to clean up."); 12367 // Clean up the stale container and proceed to recreate. 12368 if (!PackageHelper.destroySdDir(newCacheId)) { 12369 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12370 return false; 12371 } 12372 // Successfully cleaned up stale container. Try to rename again. 12373 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12374 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12375 + " inspite of cleaning it up."); 12376 return false; 12377 } 12378 } 12379 if (!PackageHelper.isContainerMounted(newCacheId)) { 12380 Slog.w(TAG, "Mounting container " + newCacheId); 12381 newMountPath = PackageHelper.mountSdDir(newCacheId, 12382 getEncryptKey(), Process.SYSTEM_UID); 12383 } else { 12384 newMountPath = PackageHelper.getSdDir(newCacheId); 12385 } 12386 if (newMountPath == null) { 12387 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12388 return false; 12389 } 12390 Log.i(TAG, "Succesfully renamed " + cid + 12391 " to " + newCacheId + 12392 " at new path: " + newMountPath); 12393 cid = newCacheId; 12394 12395 final File beforeCodeFile = new File(packagePath); 12396 setMountPath(newMountPath); 12397 final File afterCodeFile = new File(packagePath); 12398 12399 // Reflect the rename in scanned details 12400 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12401 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12402 afterCodeFile, pkg.baseCodePath)); 12403 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12404 afterCodeFile, pkg.splitCodePaths)); 12405 12406 // Reflect the rename in app info 12407 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12408 pkg.setApplicationInfoCodePath(pkg.codePath); 12409 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12410 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12411 pkg.setApplicationInfoResourcePath(pkg.codePath); 12412 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12413 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12414 12415 return true; 12416 } 12417 12418 private void setMountPath(String mountPath) { 12419 final File mountFile = new File(mountPath); 12420 12421 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12422 if (monolithicFile.exists()) { 12423 packagePath = monolithicFile.getAbsolutePath(); 12424 if (isFwdLocked()) { 12425 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12426 } else { 12427 resourcePath = packagePath; 12428 } 12429 } else { 12430 packagePath = mountFile.getAbsolutePath(); 12431 resourcePath = packagePath; 12432 } 12433 } 12434 12435 int doPostInstall(int status, int uid) { 12436 if (status != PackageManager.INSTALL_SUCCEEDED) { 12437 cleanUp(); 12438 } else { 12439 final int groupOwner; 12440 final String protectedFile; 12441 if (isFwdLocked()) { 12442 groupOwner = UserHandle.getSharedAppGid(uid); 12443 protectedFile = RES_FILE_NAME; 12444 } else { 12445 groupOwner = -1; 12446 protectedFile = null; 12447 } 12448 12449 if (uid < Process.FIRST_APPLICATION_UID 12450 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12451 Slog.e(TAG, "Failed to finalize " + cid); 12452 PackageHelper.destroySdDir(cid); 12453 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12454 } 12455 12456 boolean mounted = PackageHelper.isContainerMounted(cid); 12457 if (!mounted) { 12458 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12459 } 12460 } 12461 return status; 12462 } 12463 12464 private void cleanUp() { 12465 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12466 12467 // Destroy secure container 12468 PackageHelper.destroySdDir(cid); 12469 } 12470 12471 private List<String> getAllCodePaths() { 12472 final File codeFile = new File(getCodePath()); 12473 if (codeFile != null && codeFile.exists()) { 12474 try { 12475 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12476 return pkg.getAllCodePaths(); 12477 } catch (PackageParserException e) { 12478 // Ignored; we tried our best 12479 } 12480 } 12481 return Collections.EMPTY_LIST; 12482 } 12483 12484 void cleanUpResourcesLI() { 12485 // Enumerate all code paths before deleting 12486 cleanUpResourcesLI(getAllCodePaths()); 12487 } 12488 12489 private void cleanUpResourcesLI(List<String> allCodePaths) { 12490 cleanUp(); 12491 removeDexFiles(allCodePaths, instructionSets); 12492 } 12493 12494 String getPackageName() { 12495 return getAsecPackageName(cid); 12496 } 12497 12498 boolean doPostDeleteLI(boolean delete) { 12499 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12500 final List<String> allCodePaths = getAllCodePaths(); 12501 boolean mounted = PackageHelper.isContainerMounted(cid); 12502 if (mounted) { 12503 // Unmount first 12504 if (PackageHelper.unMountSdDir(cid)) { 12505 mounted = false; 12506 } 12507 } 12508 if (!mounted && delete) { 12509 cleanUpResourcesLI(allCodePaths); 12510 } 12511 return !mounted; 12512 } 12513 12514 @Override 12515 int doPreCopy() { 12516 if (isFwdLocked()) { 12517 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12518 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12519 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12520 } 12521 } 12522 12523 return PackageManager.INSTALL_SUCCEEDED; 12524 } 12525 12526 @Override 12527 int doPostCopy(int uid) { 12528 if (isFwdLocked()) { 12529 if (uid < Process.FIRST_APPLICATION_UID 12530 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12531 RES_FILE_NAME)) { 12532 Slog.e(TAG, "Failed to finalize " + cid); 12533 PackageHelper.destroySdDir(cid); 12534 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12535 } 12536 } 12537 12538 return PackageManager.INSTALL_SUCCEEDED; 12539 } 12540 } 12541 12542 /** 12543 * Logic to handle movement of existing installed applications. 12544 */ 12545 class MoveInstallArgs extends InstallArgs { 12546 private File codeFile; 12547 private File resourceFile; 12548 12549 /** New install */ 12550 MoveInstallArgs(InstallParams params) { 12551 super(params.origin, params.move, params.observer, params.installFlags, 12552 params.installerPackageName, params.volumeUuid, 12553 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12554 params.grantedRuntimePermissions, 12555 params.traceMethod, params.traceCookie); 12556 } 12557 12558 int copyApk(IMediaContainerService imcs, boolean temp) { 12559 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12560 + move.fromUuid + " to " + move.toUuid); 12561 synchronized (mInstaller) { 12562 try { 12563 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12564 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12565 } catch (InstallerException e) { 12566 Slog.w(TAG, "Failed to move app", e); 12567 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12568 } 12569 } 12570 12571 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12572 resourceFile = codeFile; 12573 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12574 12575 return PackageManager.INSTALL_SUCCEEDED; 12576 } 12577 12578 int doPreInstall(int status) { 12579 if (status != PackageManager.INSTALL_SUCCEEDED) { 12580 cleanUp(move.toUuid); 12581 } 12582 return status; 12583 } 12584 12585 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12586 if (status != PackageManager.INSTALL_SUCCEEDED) { 12587 cleanUp(move.toUuid); 12588 return false; 12589 } 12590 12591 // Reflect the move in app info 12592 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12593 pkg.setApplicationInfoCodePath(pkg.codePath); 12594 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12595 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12596 pkg.setApplicationInfoResourcePath(pkg.codePath); 12597 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12598 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12599 12600 return true; 12601 } 12602 12603 int doPostInstall(int status, int uid) { 12604 if (status == PackageManager.INSTALL_SUCCEEDED) { 12605 cleanUp(move.fromUuid); 12606 } else { 12607 cleanUp(move.toUuid); 12608 } 12609 return status; 12610 } 12611 12612 @Override 12613 String getCodePath() { 12614 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12615 } 12616 12617 @Override 12618 String getResourcePath() { 12619 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12620 } 12621 12622 private boolean cleanUp(String volumeUuid) { 12623 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12624 move.dataAppName); 12625 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12626 synchronized (mInstallLock) { 12627 // Clean up both app data and code 12628 removeDataDirsLI(volumeUuid, move.packageName); 12629 removeCodePathLI(codeFile); 12630 } 12631 return true; 12632 } 12633 12634 void cleanUpResourcesLI() { 12635 throw new UnsupportedOperationException(); 12636 } 12637 12638 boolean doPostDeleteLI(boolean delete) { 12639 throw new UnsupportedOperationException(); 12640 } 12641 } 12642 12643 static String getAsecPackageName(String packageCid) { 12644 int idx = packageCid.lastIndexOf("-"); 12645 if (idx == -1) { 12646 return packageCid; 12647 } 12648 return packageCid.substring(0, idx); 12649 } 12650 12651 // Utility method used to create code paths based on package name and available index. 12652 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12653 String idxStr = ""; 12654 int idx = 1; 12655 // Fall back to default value of idx=1 if prefix is not 12656 // part of oldCodePath 12657 if (oldCodePath != null) { 12658 String subStr = oldCodePath; 12659 // Drop the suffix right away 12660 if (suffix != null && subStr.endsWith(suffix)) { 12661 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12662 } 12663 // If oldCodePath already contains prefix find out the 12664 // ending index to either increment or decrement. 12665 int sidx = subStr.lastIndexOf(prefix); 12666 if (sidx != -1) { 12667 subStr = subStr.substring(sidx + prefix.length()); 12668 if (subStr != null) { 12669 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12670 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12671 } 12672 try { 12673 idx = Integer.parseInt(subStr); 12674 if (idx <= 1) { 12675 idx++; 12676 } else { 12677 idx--; 12678 } 12679 } catch(NumberFormatException e) { 12680 } 12681 } 12682 } 12683 } 12684 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12685 return prefix + idxStr; 12686 } 12687 12688 private File getNextCodePath(File targetDir, String packageName) { 12689 int suffix = 1; 12690 File result; 12691 do { 12692 result = new File(targetDir, packageName + "-" + suffix); 12693 suffix++; 12694 } while (result.exists()); 12695 return result; 12696 } 12697 12698 // Utility method that returns the relative package path with respect 12699 // to the installation directory. Like say for /data/data/com.test-1.apk 12700 // string com.test-1 is returned. 12701 static String deriveCodePathName(String codePath) { 12702 if (codePath == null) { 12703 return null; 12704 } 12705 final File codeFile = new File(codePath); 12706 final String name = codeFile.getName(); 12707 if (codeFile.isDirectory()) { 12708 return name; 12709 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12710 final int lastDot = name.lastIndexOf('.'); 12711 return name.substring(0, lastDot); 12712 } else { 12713 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12714 return null; 12715 } 12716 } 12717 12718 static class PackageInstalledInfo { 12719 String name; 12720 int uid; 12721 // The set of users that originally had this package installed. 12722 int[] origUsers; 12723 // The set of users that now have this package installed. 12724 int[] newUsers; 12725 PackageParser.Package pkg; 12726 int returnCode; 12727 String returnMsg; 12728 PackageRemovedInfo removedInfo; 12729 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 12730 12731 public void setError(int code, String msg) { 12732 setReturnCode(code); 12733 setReturnMessage(msg); 12734 Slog.w(TAG, msg); 12735 } 12736 12737 public void setError(String msg, PackageParserException e) { 12738 setReturnCode(e.error); 12739 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12740 Slog.w(TAG, msg, e); 12741 } 12742 12743 public void setError(String msg, PackageManagerException e) { 12744 returnCode = e.error; 12745 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12746 Slog.w(TAG, msg, e); 12747 } 12748 12749 public void setReturnCode(int returnCode) { 12750 this.returnCode = returnCode; 12751 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12752 for (int i = 0; i < childCount; i++) { 12753 addedChildPackages.valueAt(i).returnCode = returnCode; 12754 } 12755 } 12756 12757 private void setReturnMessage(String returnMsg) { 12758 this.returnMsg = returnMsg; 12759 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12760 for (int i = 0; i < childCount; i++) { 12761 addedChildPackages.valueAt(i).returnMsg = returnMsg; 12762 } 12763 } 12764 12765 // In some error cases we want to convey more info back to the observer 12766 String origPackage; 12767 String origPermission; 12768 } 12769 12770 /* 12771 * Install a non-existing package. 12772 */ 12773 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12774 UserHandle user, String installerPackageName, String volumeUuid, 12775 PackageInstalledInfo res) { 12776 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12777 12778 // Remember this for later, in case we need to rollback this install 12779 String pkgName = pkg.packageName; 12780 12781 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12782 12783 synchronized(mPackages) { 12784 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12785 // A package with the same name is already installed, though 12786 // it has been renamed to an older name. The package we 12787 // are trying to install should be installed as an update to 12788 // the existing one, but that has not been requested, so bail. 12789 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12790 + " without first uninstalling package running as " 12791 + mSettings.mRenamedPackages.get(pkgName)); 12792 return; 12793 } 12794 if (mPackages.containsKey(pkgName)) { 12795 // Don't allow installation over an existing package with the same name. 12796 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12797 + " without first uninstalling."); 12798 return; 12799 } 12800 } 12801 12802 try { 12803 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12804 System.currentTimeMillis(), user); 12805 12806 updateSettingsLI(newPackage, installerPackageName, null, res, user); 12807 12808 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12809 prepareAppDataAfterInstall(newPackage); 12810 12811 } else { 12812 // Remove package from internal structures, but keep around any 12813 // data that might have already existed 12814 deletePackageLI(pkgName, UserHandle.ALL, false, null, 12815 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12816 } 12817 } catch (PackageManagerException e) { 12818 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12819 } 12820 12821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12822 } 12823 12824 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12825 // Can't rotate keys during boot or if sharedUser. 12826 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12827 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12828 return false; 12829 } 12830 // app is using upgradeKeySets; make sure all are valid 12831 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12832 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12833 for (int i = 0; i < upgradeKeySets.length; i++) { 12834 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12835 Slog.wtf(TAG, "Package " 12836 + (oldPs.name != null ? oldPs.name : "<null>") 12837 + " contains upgrade-key-set reference to unknown key-set: " 12838 + upgradeKeySets[i] 12839 + " reverting to signatures check."); 12840 return false; 12841 } 12842 } 12843 return true; 12844 } 12845 12846 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12847 // Upgrade keysets are being used. Determine if new package has a superset of the 12848 // required keys. 12849 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12850 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12851 for (int i = 0; i < upgradeKeySets.length; i++) { 12852 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12853 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12854 return true; 12855 } 12856 } 12857 return false; 12858 } 12859 12860 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12861 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 12862 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12863 12864 final PackageParser.Package oldPackage; 12865 final String pkgName = pkg.packageName; 12866 final int[] allUsers; 12867 12868 // First find the old package info and check signatures 12869 synchronized(mPackages) { 12870 oldPackage = mPackages.get(pkgName); 12871 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12872 if (isEphemeral && !oldIsEphemeral) { 12873 // can't downgrade from full to ephemeral 12874 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12875 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 12876 return; 12877 } 12878 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12879 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12880 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12881 if (!checkUpgradeKeySetLP(ps, pkg)) { 12882 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12883 "New package not signed by keys specified by upgrade-keysets: " 12884 + pkgName); 12885 return; 12886 } 12887 } else { 12888 // default to original signature matching 12889 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12890 != PackageManager.SIGNATURE_MATCH) { 12891 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12892 "New package has a different signature: " + pkgName); 12893 return; 12894 } 12895 } 12896 12897 // In case of rollback, remember per-user/profile install state 12898 allUsers = sUserManager.getUserIds(); 12899 } 12900 12901 // Update what is removed 12902 res.removedInfo = new PackageRemovedInfo(); 12903 res.removedInfo.uid = oldPackage.applicationInfo.uid; 12904 res.removedInfo.removedPackage = oldPackage.packageName; 12905 res.removedInfo.isUpdate = true; 12906 final int childCount = (oldPackage.childPackages != null) 12907 ? oldPackage.childPackages.size() : 0; 12908 for (int i = 0; i < childCount; i++) { 12909 boolean childPackageUpdated = false; 12910 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 12911 if (res.addedChildPackages != null) { 12912 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 12913 if (childRes != null) { 12914 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 12915 childRes.removedInfo.removedPackage = childPkg.packageName; 12916 childRes.removedInfo.isUpdate = true; 12917 childPackageUpdated = true; 12918 } 12919 } 12920 if (!childPackageUpdated) { 12921 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 12922 childRemovedRes.removedPackage = childPkg.packageName; 12923 childRemovedRes.isUpdate = false; 12924 childRemovedRes.dataRemoved = true; 12925 synchronized (mPackages) { 12926 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 12927 if (childPs != null) { 12928 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 12929 } 12930 } 12931 if (res.removedInfo.removedChildPackages == null) { 12932 res.removedInfo.removedChildPackages = new ArrayMap<>(); 12933 } 12934 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 12935 } 12936 } 12937 12938 boolean sysPkg = (isSystemApp(oldPackage)); 12939 if (sysPkg) { 12940 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12941 user, allUsers, installerPackageName, res); 12942 } else { 12943 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12944 user, allUsers, installerPackageName, res); 12945 } 12946 } 12947 12948 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12949 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12950 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 12951 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12952 + deletedPackage); 12953 12954 String pkgName = deletedPackage.packageName; 12955 boolean deletedPkg = true; 12956 boolean addedPkg = false; 12957 12958 final long origUpdateTime = (pkg.mExtras != null) 12959 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 12960 12961 // First delete the existing package while retaining the data directory 12962 if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 12963 res.removedInfo, true, pkg)) { 12964 // If the existing package wasn't successfully deleted 12965 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12966 deletedPkg = false; 12967 } else { 12968 // Successfully deleted the old package; proceed with replace. 12969 12970 // If deleted package lived in a container, give users a chance to 12971 // relinquish resources before killing. 12972 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12973 if (DEBUG_INSTALL) { 12974 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12975 } 12976 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12977 final ArrayList<String> pkgList = new ArrayList<String>(1); 12978 pkgList.add(deletedPackage.applicationInfo.packageName); 12979 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12980 } 12981 12982 deleteCodeCacheDirsLI(pkg); 12983 12984 try { 12985 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12986 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12987 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 12988 prepareAppDataAfterInstall(newPackage); 12989 addedPkg = true; 12990 } catch (PackageManagerException e) { 12991 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12992 } 12993 } 12994 12995 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12996 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12997 12998 // Revert all internal state mutations and added folders for the failed install 12999 if (addedPkg) { 13000 deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13001 res.removedInfo, true, null); 13002 } 13003 13004 // Restore the old package 13005 if (deletedPkg) { 13006 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13007 File restoreFile = new File(deletedPackage.codePath); 13008 // Parse old package 13009 boolean oldExternal = isExternal(deletedPackage); 13010 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13011 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13012 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13013 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13014 try { 13015 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13016 null); 13017 } catch (PackageManagerException e) { 13018 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13019 + e.getMessage()); 13020 return; 13021 } 13022 13023 synchronized (mPackages) { 13024 // Ensure the installer package name up to date 13025 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13026 13027 // Update permissions for restored package 13028 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13029 13030 mSettings.writeLPr(); 13031 } 13032 13033 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13034 } 13035 } else { 13036 synchronized (mPackages) { 13037 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13038 if (ps != null) { 13039 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13040 if (res.removedInfo.removedChildPackages != null) { 13041 final int childCount = res.removedInfo.removedChildPackages.size(); 13042 // Iterate in reverse as we may modify the collection 13043 for (int i = childCount - 1; i >= 0; i--) { 13044 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13045 if (res.addedChildPackages.containsKey(childPackageName)) { 13046 res.removedInfo.removedChildPackages.removeAt(i); 13047 } else { 13048 PackageRemovedInfo childInfo = res.removedInfo 13049 .removedChildPackages.valueAt(i); 13050 childInfo.removedForAllUsers = mPackages.get( 13051 childInfo.removedPackage) == null; 13052 } 13053 } 13054 } 13055 } 13056 } 13057 } 13058 } 13059 13060 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13061 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13062 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13063 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13064 + ", old=" + deletedPackage); 13065 13066 final boolean disabledSystem; 13067 13068 // Set the system/privileged flags as needed 13069 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13070 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13071 != 0) { 13072 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13073 } 13074 13075 // Kill package processes including services, providers, etc. 13076 killPackage(deletedPackage, "replace sys pkg"); 13077 13078 // Remove existing system package 13079 removePackageLI(deletedPackage, true); 13080 13081 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13082 if (!disabledSystem) { 13083 // We didn't need to disable the .apk as a current system package, 13084 // which means we are replacing another update that is already 13085 // installed. We need to make sure to delete the older one's .apk. 13086 res.removedInfo.args = createInstallArgsForExisting(0, 13087 deletedPackage.applicationInfo.getCodePath(), 13088 deletedPackage.applicationInfo.getResourcePath(), 13089 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13090 } else { 13091 res.removedInfo.args = null; 13092 } 13093 13094 // Successfully disabled the old package. Now proceed with re-installation 13095 deleteCodeCacheDirsLI(pkg); 13096 13097 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13098 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13099 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13100 13101 PackageParser.Package newPackage = null; 13102 try { 13103 // Add the package to the internal data structures 13104 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13105 13106 // Set the update and install times 13107 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13108 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13109 System.currentTimeMillis()); 13110 13111 // Check for shared user id changes 13112 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13113 deletedPackage, newPackage); 13114 if (invalidPackageName != null) { 13115 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13116 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13117 + " to " + invalidPackageName); 13118 } 13119 13120 // Update the package dynamic state if succeeded 13121 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13122 // Now that the install succeeded make sure we remove data 13123 // directories for any child package the update removed. 13124 final int deletedChildCount = (deletedPackage.childPackages != null) 13125 ? deletedPackage.childPackages.size() : 0; 13126 final int newChildCount = (newPackage.childPackages != null) 13127 ? newPackage.childPackages.size() : 0; 13128 for (int i = 0; i < deletedChildCount; i++) { 13129 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13130 boolean childPackageDeleted = true; 13131 for (int j = 0; j < newChildCount; j++) { 13132 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13133 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13134 childPackageDeleted = false; 13135 break; 13136 } 13137 } 13138 if (childPackageDeleted) { 13139 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13140 deletedChildPkg.packageName); 13141 if (ps != null && res.removedInfo.removedChildPackages != null) { 13142 PackageRemovedInfo removedChildRes = res.removedInfo 13143 .removedChildPackages.get(deletedChildPkg.packageName); 13144 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13145 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13146 } 13147 } 13148 } 13149 13150 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13151 prepareAppDataAfterInstall(newPackage); 13152 } 13153 } catch (PackageManagerException e) { 13154 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13155 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13156 } 13157 13158 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13159 // Re installation failed. Restore old information 13160 // Remove new pkg information 13161 if (newPackage != null) { 13162 removeInstalledPackageLI(newPackage, true); 13163 } 13164 // Add back the old system package 13165 try { 13166 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13167 } catch (PackageManagerException e) { 13168 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13169 } 13170 13171 synchronized (mPackages) { 13172 if (disabledSystem) { 13173 enableSystemPackageLPw(deletedPackage); 13174 } 13175 13176 // Ensure the installer package name up to date 13177 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13178 13179 // Update permissions for restored package 13180 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13181 13182 mSettings.writeLPr(); 13183 } 13184 13185 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13186 + " after failed upgrade"); 13187 } 13188 } 13189 13190 /** 13191 * Checks whether the parent or any of the child packages have a change shared 13192 * user. For a package to be a valid update the shred users of the parent and 13193 * the children should match. We may later support changing child shared users. 13194 * @param oldPkg The updated package. 13195 * @param newPkg The update package. 13196 * @return The shared user that change between the versions. 13197 */ 13198 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13199 PackageParser.Package newPkg) { 13200 // Check parent shared user 13201 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13202 return newPkg.packageName; 13203 } 13204 // Check child shared users 13205 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13206 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13207 for (int i = 0; i < newChildCount; i++) { 13208 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13209 // If this child was present, did it have the same shared user? 13210 for (int j = 0; j < oldChildCount; j++) { 13211 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13212 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13213 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13214 return newChildPkg.packageName; 13215 } 13216 } 13217 } 13218 return null; 13219 } 13220 13221 private void removeNativeBinariesLI(PackageParser.Package pkg) { 13222 // Remove the lib path for the parent package 13223 PackageSetting ps = (PackageSetting) pkg.mExtras; 13224 if (ps != null) { 13225 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13226 } 13227 // Remove the lib path for the child packages 13228 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13229 for (int i = 0; i < childCount; i++) { 13230 ps = (PackageSetting) pkg.childPackages.get(i).mExtras; 13231 if (ps != null) { 13232 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13233 } 13234 } 13235 } 13236 13237 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13238 // Enable the parent package 13239 mSettings.enableSystemPackageLPw(pkg.packageName); 13240 // Enable the child packages 13241 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13242 for (int i = 0; i < childCount; i++) { 13243 PackageParser.Package childPkg = pkg.childPackages.get(i); 13244 mSettings.enableSystemPackageLPw(childPkg.packageName); 13245 } 13246 } 13247 13248 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13249 PackageParser.Package newPkg) { 13250 // Disable the parent package (parent always replaced) 13251 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13252 // Disable the child packages 13253 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13254 for (int i = 0; i < childCount; i++) { 13255 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13256 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13257 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13258 } 13259 return disabled; 13260 } 13261 13262 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13263 String installerPackageName) { 13264 // Enable the parent package 13265 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13266 // Enable the child packages 13267 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13268 for (int i = 0; i < childCount; i++) { 13269 PackageParser.Package childPkg = pkg.childPackages.get(i); 13270 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13271 } 13272 } 13273 13274 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13275 // Collect all used permissions in the UID 13276 ArraySet<String> usedPermissions = new ArraySet<>(); 13277 final int packageCount = su.packages.size(); 13278 for (int i = 0; i < packageCount; i++) { 13279 PackageSetting ps = su.packages.valueAt(i); 13280 if (ps.pkg == null) { 13281 continue; 13282 } 13283 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13284 for (int j = 0; j < requestedPermCount; j++) { 13285 String permission = ps.pkg.requestedPermissions.get(j); 13286 BasePermission bp = mSettings.mPermissions.get(permission); 13287 if (bp != null) { 13288 usedPermissions.add(permission); 13289 } 13290 } 13291 } 13292 13293 PermissionsState permissionsState = su.getPermissionsState(); 13294 // Prune install permissions 13295 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13296 final int installPermCount = installPermStates.size(); 13297 for (int i = installPermCount - 1; i >= 0; i--) { 13298 PermissionState permissionState = installPermStates.get(i); 13299 if (!usedPermissions.contains(permissionState.getName())) { 13300 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13301 if (bp != null) { 13302 permissionsState.revokeInstallPermission(bp); 13303 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13304 PackageManager.MASK_PERMISSION_FLAGS, 0); 13305 } 13306 } 13307 } 13308 13309 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13310 13311 // Prune runtime permissions 13312 for (int userId : allUserIds) { 13313 List<PermissionState> runtimePermStates = permissionsState 13314 .getRuntimePermissionStates(userId); 13315 final int runtimePermCount = runtimePermStates.size(); 13316 for (int i = runtimePermCount - 1; i >= 0; i--) { 13317 PermissionState permissionState = runtimePermStates.get(i); 13318 if (!usedPermissions.contains(permissionState.getName())) { 13319 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13320 if (bp != null) { 13321 permissionsState.revokeRuntimePermission(bp, userId); 13322 permissionsState.updatePermissionFlags(bp, userId, 13323 PackageManager.MASK_PERMISSION_FLAGS, 0); 13324 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13325 runtimePermissionChangedUserIds, userId); 13326 } 13327 } 13328 } 13329 } 13330 13331 return runtimePermissionChangedUserIds; 13332 } 13333 13334 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13335 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13336 // Update the parent package setting 13337 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13338 res, user); 13339 // Update the child packages setting 13340 final int childCount = (newPackage.childPackages != null) 13341 ? newPackage.childPackages.size() : 0; 13342 for (int i = 0; i < childCount; i++) { 13343 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13344 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13345 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13346 childRes.origUsers, childRes, user); 13347 } 13348 } 13349 13350 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13351 String installerPackageName, int[] allUsers, int[] installedForUsers, 13352 PackageInstalledInfo res, UserHandle user) { 13353 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13354 13355 String pkgName = newPackage.packageName; 13356 synchronized (mPackages) { 13357 //write settings. the installStatus will be incomplete at this stage. 13358 //note that the new package setting would have already been 13359 //added to mPackages. It hasn't been persisted yet. 13360 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13361 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13362 mSettings.writeLPr(); 13363 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13364 } 13365 13366 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13367 synchronized (mPackages) { 13368 updatePermissionsLPw(newPackage.packageName, newPackage, 13369 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13370 ? UPDATE_PERMISSIONS_ALL : 0)); 13371 // For system-bundled packages, we assume that installing an upgraded version 13372 // of the package implies that the user actually wants to run that new code, 13373 // so we enable the package. 13374 PackageSetting ps = mSettings.mPackages.get(pkgName); 13375 final int userId = user.getIdentifier(); 13376 if (ps != null) { 13377 if (isSystemApp(newPackage)) { 13378 if (DEBUG_INSTALL) { 13379 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13380 } 13381 // Enable system package for requested users 13382 if (res.origUsers != null) { 13383 for (int origUserId : res.origUsers) { 13384 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13385 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13386 origUserId, installerPackageName); 13387 } 13388 } 13389 } 13390 // Also convey the prior install/uninstall state 13391 if (allUsers != null && installedForUsers != null) { 13392 for (int currentUserId : allUsers) { 13393 final boolean installed = ArrayUtils.contains( 13394 installedForUsers, currentUserId); 13395 if (DEBUG_INSTALL) { 13396 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13397 } 13398 ps.setInstalled(installed, currentUserId); 13399 } 13400 // these install state changes will be persisted in the 13401 // upcoming call to mSettings.writeLPr(). 13402 } 13403 } 13404 // It's implied that when a user requests installation, they want the app to be 13405 // installed and enabled. 13406 if (userId != UserHandle.USER_ALL) { 13407 ps.setInstalled(true, userId); 13408 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13409 } 13410 } 13411 res.name = pkgName; 13412 res.uid = newPackage.applicationInfo.uid; 13413 res.pkg = newPackage; 13414 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13415 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13416 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13417 //to update install status 13418 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13419 mSettings.writeLPr(); 13420 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13421 } 13422 13423 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13424 } 13425 13426 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13427 try { 13428 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13429 installPackageLI(args, res); 13430 } finally { 13431 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13432 } 13433 } 13434 13435 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13436 final int installFlags = args.installFlags; 13437 final String installerPackageName = args.installerPackageName; 13438 final String volumeUuid = args.volumeUuid; 13439 final File tmpPackageFile = new File(args.getCodePath()); 13440 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13441 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13442 || (args.volumeUuid != null)); 13443 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13444 boolean replace = false; 13445 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13446 if (args.move != null) { 13447 // moving a complete application; perform an initial scan on the new install location 13448 scanFlags |= SCAN_INITIAL; 13449 } 13450 13451 // Result object to be returned 13452 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13453 13454 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13455 13456 // Sanity check 13457 if (ephemeral && (forwardLocked || onExternal)) { 13458 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13459 + " external=" + onExternal); 13460 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13461 return; 13462 } 13463 13464 // Retrieve PackageSettings and parse package 13465 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13466 | PackageParser.PARSE_ENFORCE_CODE 13467 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13468 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13469 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13470 PackageParser pp = new PackageParser(); 13471 pp.setSeparateProcesses(mSeparateProcesses); 13472 pp.setDisplayMetrics(mMetrics); 13473 13474 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13475 final PackageParser.Package pkg; 13476 try { 13477 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13478 } catch (PackageParserException e) { 13479 res.setError("Failed parse during installPackageLI", e); 13480 return; 13481 } finally { 13482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13483 } 13484 13485 // If we are installing a clustered package add results for the children 13486 if (pkg.childPackages != null) { 13487 synchronized (mPackages) { 13488 final int childCount = pkg.childPackages.size(); 13489 for (int i = 0; i < childCount; i++) { 13490 PackageParser.Package childPkg = pkg.childPackages.get(i); 13491 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13492 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13493 childRes.pkg = childPkg; 13494 childRes.name = childPkg.packageName; 13495 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13496 if (childPs != null) { 13497 childRes.origUsers = childPs.queryInstalledUsers( 13498 sUserManager.getUserIds(), true); 13499 } 13500 if ((mPackages.containsKey(childPkg.packageName))) { 13501 childRes.removedInfo = new PackageRemovedInfo(); 13502 childRes.removedInfo.removedPackage = childPkg.packageName; 13503 } 13504 if (res.addedChildPackages == null) { 13505 res.addedChildPackages = new ArrayMap<>(); 13506 } 13507 res.addedChildPackages.put(childPkg.packageName, childRes); 13508 } 13509 } 13510 } 13511 13512 // If package doesn't declare API override, mark that we have an install 13513 // time CPU ABI override. 13514 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13515 pkg.cpuAbiOverride = args.abiOverride; 13516 } 13517 13518 String pkgName = res.name = pkg.packageName; 13519 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13520 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13521 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13522 return; 13523 } 13524 } 13525 13526 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13527 try { 13528 PackageParser.collectCertificates(pkg, parseFlags); 13529 } catch (PackageParserException e) { 13530 res.setError("Failed collect during installPackageLI", e); 13531 return; 13532 } finally { 13533 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13534 } 13535 13536 // Get rid of all references to package scan path via parser. 13537 pp = null; 13538 String oldCodePath = null; 13539 boolean systemApp = false; 13540 synchronized (mPackages) { 13541 // Check if installing already existing package 13542 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13543 String oldName = mSettings.mRenamedPackages.get(pkgName); 13544 if (pkg.mOriginalPackages != null 13545 && pkg.mOriginalPackages.contains(oldName) 13546 && mPackages.containsKey(oldName)) { 13547 // This package is derived from an original package, 13548 // and this device has been updating from that original 13549 // name. We must continue using the original name, so 13550 // rename the new package here. 13551 pkg.setPackageName(oldName); 13552 pkgName = pkg.packageName; 13553 replace = true; 13554 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13555 + oldName + " pkgName=" + pkgName); 13556 } else if (mPackages.containsKey(pkgName)) { 13557 // This package, under its official name, already exists 13558 // on the device; we should replace it. 13559 replace = true; 13560 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13561 } 13562 13563 // Child packages are installed through the parent package 13564 if (pkg.parentPackage != null) { 13565 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13566 "Package " + pkg.packageName + " is child of package " 13567 + pkg.parentPackage.parentPackage + ". Child packages " 13568 + "can be updated only through the parent package."); 13569 return; 13570 } 13571 13572 if (replace) { 13573 // Prevent apps opting out from runtime permissions 13574 PackageParser.Package oldPackage = mPackages.get(pkgName); 13575 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13576 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13577 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13578 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13579 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13580 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13581 + " doesn't support runtime permissions but the old" 13582 + " target SDK " + oldTargetSdk + " does."); 13583 return; 13584 } 13585 13586 // Prevent installing of child packages 13587 if (oldPackage.parentPackage != null) { 13588 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13589 "Package " + pkg.packageName + " is child of package " 13590 + oldPackage.parentPackage + ". Child packages " 13591 + "can be updated only through the parent package."); 13592 return; 13593 } 13594 } 13595 } 13596 13597 PackageSetting ps = mSettings.mPackages.get(pkgName); 13598 if (ps != null) { 13599 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13600 13601 // Quick sanity check that we're signed correctly if updating; 13602 // we'll check this again later when scanning, but we want to 13603 // bail early here before tripping over redefined permissions. 13604 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13605 if (!checkUpgradeKeySetLP(ps, pkg)) { 13606 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13607 + pkg.packageName + " upgrade keys do not match the " 13608 + "previously installed version"); 13609 return; 13610 } 13611 } else { 13612 try { 13613 verifySignaturesLP(ps, pkg); 13614 } catch (PackageManagerException e) { 13615 res.setError(e.error, e.getMessage()); 13616 return; 13617 } 13618 } 13619 13620 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13621 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13622 systemApp = (ps.pkg.applicationInfo.flags & 13623 ApplicationInfo.FLAG_SYSTEM) != 0; 13624 } 13625 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13626 } 13627 13628 // Check whether the newly-scanned package wants to define an already-defined perm 13629 int N = pkg.permissions.size(); 13630 for (int i = N-1; i >= 0; i--) { 13631 PackageParser.Permission perm = pkg.permissions.get(i); 13632 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13633 if (bp != null) { 13634 // If the defining package is signed with our cert, it's okay. This 13635 // also includes the "updating the same package" case, of course. 13636 // "updating same package" could also involve key-rotation. 13637 final boolean sigsOk; 13638 if (bp.sourcePackage.equals(pkg.packageName) 13639 && (bp.packageSetting instanceof PackageSetting) 13640 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13641 scanFlags))) { 13642 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13643 } else { 13644 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13645 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13646 } 13647 if (!sigsOk) { 13648 // If the owning package is the system itself, we log but allow 13649 // install to proceed; we fail the install on all other permission 13650 // redefinitions. 13651 if (!bp.sourcePackage.equals("android")) { 13652 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13653 + pkg.packageName + " attempting to redeclare permission " 13654 + perm.info.name + " already owned by " + bp.sourcePackage); 13655 res.origPermission = perm.info.name; 13656 res.origPackage = bp.sourcePackage; 13657 return; 13658 } else { 13659 Slog.w(TAG, "Package " + pkg.packageName 13660 + " attempting to redeclare system permission " 13661 + perm.info.name + "; ignoring new declaration"); 13662 pkg.permissions.remove(i); 13663 } 13664 } 13665 } 13666 } 13667 } 13668 13669 if (systemApp) { 13670 if (onExternal) { 13671 // Abort update; system app can't be replaced with app on sdcard 13672 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13673 "Cannot install updates to system apps on sdcard"); 13674 return; 13675 } else if (ephemeral) { 13676 // Abort update; system app can't be replaced with an ephemeral app 13677 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13678 "Cannot update a system app with an ephemeral app"); 13679 return; 13680 } 13681 } 13682 13683 if (args.move != null) { 13684 // We did an in-place move, so dex is ready to roll 13685 scanFlags |= SCAN_NO_DEX; 13686 scanFlags |= SCAN_MOVE; 13687 13688 synchronized (mPackages) { 13689 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13690 if (ps == null) { 13691 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13692 "Missing settings for moved package " + pkgName); 13693 } 13694 13695 // We moved the entire application as-is, so bring over the 13696 // previously derived ABI information. 13697 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13698 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13699 } 13700 13701 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13702 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13703 scanFlags |= SCAN_NO_DEX; 13704 13705 try { 13706 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13707 args.abiOverride : pkg.cpuAbiOverride); 13708 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13709 true /* extract libs */); 13710 } catch (PackageManagerException pme) { 13711 Slog.e(TAG, "Error deriving application ABI", pme); 13712 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13713 return; 13714 } 13715 13716 // Extract package to save the VM unzipping the APK in memory during 13717 // launch. Only do this if profile-guided compilation is enabled because 13718 // otherwise BackgroundDexOptService will not dexopt the package later. 13719 if (mUseJitProfiles) { 13720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13721 // Do not run PackageDexOptimizer through the local performDexOpt 13722 // method because `pkg` is not in `mPackages` yet. 13723 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13724 false /* useProfiles */, true /* extractOnly */); 13725 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13726 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13727 String msg = "Extracking package failed for " + pkgName; 13728 res.setError(INSTALL_FAILED_DEXOPT, msg); 13729 return; 13730 } 13731 } 13732 } 13733 13734 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13735 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13736 return; 13737 } 13738 13739 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13740 13741 if (replace) { 13742 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13743 installerPackageName, res); 13744 } else { 13745 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13746 args.user, installerPackageName, volumeUuid, res); 13747 } 13748 synchronized (mPackages) { 13749 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13750 if (ps != null) { 13751 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13752 } 13753 13754 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13755 for (int i = 0; i < childCount; i++) { 13756 PackageParser.Package childPkg = pkg.childPackages.get(i); 13757 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13758 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13759 if (childPs != null) { 13760 childRes.newUsers = childPs.queryInstalledUsers( 13761 sUserManager.getUserIds(), true); 13762 } 13763 } 13764 } 13765 } 13766 13767 private void startIntentFilterVerifications(int userId, boolean replacing, 13768 PackageParser.Package pkg) { 13769 if (mIntentFilterVerifierComponent == null) { 13770 Slog.w(TAG, "No IntentFilter verification will not be done as " 13771 + "there is no IntentFilterVerifier available!"); 13772 return; 13773 } 13774 13775 final int verifierUid = getPackageUid( 13776 mIntentFilterVerifierComponent.getPackageName(), 13777 MATCH_DEBUG_TRIAGED_MISSING, 13778 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13779 13780 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13781 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13782 mHandler.sendMessage(msg); 13783 13784 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13785 for (int i = 0; i < childCount; i++) { 13786 PackageParser.Package childPkg = pkg.childPackages.get(i); 13787 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13788 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 13789 mHandler.sendMessage(msg); 13790 } 13791 } 13792 13793 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13794 PackageParser.Package pkg) { 13795 int size = pkg.activities.size(); 13796 if (size == 0) { 13797 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13798 "No activity, so no need to verify any IntentFilter!"); 13799 return; 13800 } 13801 13802 final boolean hasDomainURLs = hasDomainURLs(pkg); 13803 if (!hasDomainURLs) { 13804 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13805 "No domain URLs, so no need to verify any IntentFilter!"); 13806 return; 13807 } 13808 13809 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13810 + " if any IntentFilter from the " + size 13811 + " Activities needs verification ..."); 13812 13813 int count = 0; 13814 final String packageName = pkg.packageName; 13815 13816 synchronized (mPackages) { 13817 // If this is a new install and we see that we've already run verification for this 13818 // package, we have nothing to do: it means the state was restored from backup. 13819 if (!replacing) { 13820 IntentFilterVerificationInfo ivi = 13821 mSettings.getIntentFilterVerificationLPr(packageName); 13822 if (ivi != null) { 13823 if (DEBUG_DOMAIN_VERIFICATION) { 13824 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13825 + ivi.getStatusString()); 13826 } 13827 return; 13828 } 13829 } 13830 13831 // If any filters need to be verified, then all need to be. 13832 boolean needToVerify = false; 13833 for (PackageParser.Activity a : pkg.activities) { 13834 for (ActivityIntentInfo filter : a.intents) { 13835 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13836 if (DEBUG_DOMAIN_VERIFICATION) { 13837 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13838 } 13839 needToVerify = true; 13840 break; 13841 } 13842 } 13843 } 13844 13845 if (needToVerify) { 13846 final int verificationId = mIntentFilterVerificationToken++; 13847 for (PackageParser.Activity a : pkg.activities) { 13848 for (ActivityIntentInfo filter : a.intents) { 13849 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13850 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13851 "Verification needed for IntentFilter:" + filter.toString()); 13852 mIntentFilterVerifier.addOneIntentFilterVerification( 13853 verifierUid, userId, verificationId, filter, packageName); 13854 count++; 13855 } 13856 } 13857 } 13858 } 13859 } 13860 13861 if (count > 0) { 13862 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13863 + " IntentFilter verification" + (count > 1 ? "s" : "") 13864 + " for userId:" + userId); 13865 mIntentFilterVerifier.startVerifications(userId); 13866 } else { 13867 if (DEBUG_DOMAIN_VERIFICATION) { 13868 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13869 } 13870 } 13871 } 13872 13873 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13874 final ComponentName cn = filter.activity.getComponentName(); 13875 final String packageName = cn.getPackageName(); 13876 13877 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13878 packageName); 13879 if (ivi == null) { 13880 return true; 13881 } 13882 int status = ivi.getStatus(); 13883 switch (status) { 13884 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13885 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13886 return true; 13887 13888 default: 13889 // Nothing to do 13890 return false; 13891 } 13892 } 13893 13894 private static boolean isMultiArch(ApplicationInfo info) { 13895 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13896 } 13897 13898 private static boolean isExternal(PackageParser.Package pkg) { 13899 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13900 } 13901 13902 private static boolean isExternal(PackageSetting ps) { 13903 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13904 } 13905 13906 private static boolean isEphemeral(PackageParser.Package pkg) { 13907 return pkg.applicationInfo.isEphemeralApp(); 13908 } 13909 13910 private static boolean isEphemeral(PackageSetting ps) { 13911 return ps.pkg != null && isEphemeral(ps.pkg); 13912 } 13913 13914 private static boolean isSystemApp(PackageParser.Package pkg) { 13915 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13916 } 13917 13918 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13919 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13920 } 13921 13922 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13923 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13924 } 13925 13926 private static boolean isSystemApp(PackageSetting ps) { 13927 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13928 } 13929 13930 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13931 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13932 } 13933 13934 private int packageFlagsToInstallFlags(PackageSetting ps) { 13935 int installFlags = 0; 13936 if (isEphemeral(ps)) { 13937 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13938 } 13939 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13940 // This existing package was an external ASEC install when we have 13941 // the external flag without a UUID 13942 installFlags |= PackageManager.INSTALL_EXTERNAL; 13943 } 13944 if (ps.isForwardLocked()) { 13945 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13946 } 13947 return installFlags; 13948 } 13949 13950 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13951 if (isExternal(pkg)) { 13952 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13953 return StorageManager.UUID_PRIMARY_PHYSICAL; 13954 } else { 13955 return pkg.volumeUuid; 13956 } 13957 } else { 13958 return StorageManager.UUID_PRIVATE_INTERNAL; 13959 } 13960 } 13961 13962 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13963 if (isExternal(pkg)) { 13964 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13965 return mSettings.getExternalVersion(); 13966 } else { 13967 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13968 } 13969 } else { 13970 return mSettings.getInternalVersion(); 13971 } 13972 } 13973 13974 private void deleteTempPackageFiles() { 13975 final FilenameFilter filter = new FilenameFilter() { 13976 public boolean accept(File dir, String name) { 13977 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13978 } 13979 }; 13980 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13981 file.delete(); 13982 } 13983 } 13984 13985 @Override 13986 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13987 int flags) { 13988 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13989 flags); 13990 } 13991 13992 @Override 13993 public void deletePackage(final String packageName, 13994 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13995 mContext.enforceCallingOrSelfPermission( 13996 android.Manifest.permission.DELETE_PACKAGES, null); 13997 Preconditions.checkNotNull(packageName); 13998 Preconditions.checkNotNull(observer); 13999 final int uid = Binder.getCallingUid(); 14000 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14001 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14002 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14003 mContext.enforceCallingOrSelfPermission( 14004 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14005 "deletePackage for user " + userId); 14006 } 14007 14008 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14009 try { 14010 observer.onPackageDeleted(packageName, 14011 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14012 } catch (RemoteException re) { 14013 } 14014 return; 14015 } 14016 14017 for (int currentUserId : users) { 14018 if (getBlockUninstallForUser(packageName, currentUserId)) { 14019 try { 14020 observer.onPackageDeleted(packageName, 14021 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14022 } catch (RemoteException re) { 14023 } 14024 return; 14025 } 14026 } 14027 14028 if (DEBUG_REMOVE) { 14029 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 14030 } 14031 // Queue up an async operation since the package deletion may take a little while. 14032 mHandler.post(new Runnable() { 14033 public void run() { 14034 mHandler.removeCallbacks(this); 14035 final int returnCode = deletePackageX(packageName, userId, flags); 14036 try { 14037 observer.onPackageDeleted(packageName, returnCode, null); 14038 } catch (RemoteException e) { 14039 Log.i(TAG, "Observer no longer exists."); 14040 } //end catch 14041 } //end run 14042 }); 14043 } 14044 14045 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14046 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14047 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14048 try { 14049 if (dpm != null) { 14050 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14051 /* callingUserOnly =*/ false); 14052 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14053 : deviceOwnerComponentName.getPackageName(); 14054 // Does the package contains the device owner? 14055 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14056 // this check is probably not needed, since DO should be registered as a device 14057 // admin on some user too. (Original bug for this: b/17657954) 14058 if (packageName.equals(deviceOwnerPackageName)) { 14059 return true; 14060 } 14061 // Does it contain a device admin for any user? 14062 int[] users; 14063 if (userId == UserHandle.USER_ALL) { 14064 users = sUserManager.getUserIds(); 14065 } else { 14066 users = new int[]{userId}; 14067 } 14068 for (int i = 0; i < users.length; ++i) { 14069 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14070 return true; 14071 } 14072 } 14073 } 14074 } catch (RemoteException e) { 14075 } 14076 return false; 14077 } 14078 14079 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14080 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14081 } 14082 14083 /** 14084 * This method is an internal method that could be get invoked either 14085 * to delete an installed package or to clean up a failed installation. 14086 * After deleting an installed package, a broadcast is sent to notify any 14087 * listeners that the package has been installed. For cleaning up a failed 14088 * installation, the broadcast is not necessary since the package's 14089 * installation wouldn't have sent the initial broadcast either 14090 * The key steps in deleting a package are 14091 * deleting the package information in internal structures like mPackages, 14092 * deleting the packages base directories through installd 14093 * updating mSettings to reflect current status 14094 * persisting settings for later use 14095 * sending a broadcast if necessary 14096 */ 14097 private int deletePackageX(String packageName, int userId, int flags) { 14098 final PackageRemovedInfo info = new PackageRemovedInfo(); 14099 final boolean res; 14100 14101 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14102 ? UserHandle.ALL : new UserHandle(userId); 14103 14104 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14105 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14106 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14107 } 14108 14109 PackageParser.Package uninstalledPkg; 14110 14111 // for the uninstall-updates case and restricted profiles, remember the per- 14112 // user handle installed state 14113 int[] allUsers; 14114 synchronized (mPackages) { 14115 uninstalledPkg = mPackages.get(packageName); 14116 PackageSetting ps = mSettings.mPackages.get(packageName); 14117 if (ps == null || uninstalledPkg == null) { 14118 Slog.w(TAG, "Not removing non-existent package " + packageName); 14119 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14120 } 14121 allUsers = sUserManager.getUserIds(); 14122 info.origUsers = ps.queryInstalledUsers(allUsers, true); 14123 } 14124 14125 synchronized (mInstallLock) { 14126 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14127 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14128 flags | REMOVE_CHATTY, info, true, null); 14129 synchronized (mPackages) { 14130 if (res) { 14131 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 14132 } 14133 } 14134 } 14135 14136 if (res) { 14137 info.sendPackageRemovedBroadcasts(); 14138 info.sendSystemPackageUpdatedBroadcasts(); 14139 info.sendSystemPackageAppearedBroadcasts(); 14140 } 14141 // Force a gc here. 14142 Runtime.getRuntime().gc(); 14143 // Delete the resources here after sending the broadcast to let 14144 // other processes clean up before deleting resources. 14145 if (info.args != null) { 14146 synchronized (mInstallLock) { 14147 info.args.doPostDeleteLI(true); 14148 } 14149 } 14150 14151 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14152 } 14153 14154 class PackageRemovedInfo { 14155 String removedPackage; 14156 int uid = -1; 14157 int removedAppId = -1; 14158 int[] origUsers; 14159 int[] removedUsers = null; 14160 boolean isRemovedPackageSystemUpdate = false; 14161 boolean isUpdate; 14162 boolean dataRemoved; 14163 boolean removedForAllUsers; 14164 // Clean up resources deleted packages. 14165 InstallArgs args = null; 14166 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14167 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14168 14169 void sendPackageRemovedBroadcasts() { 14170 sendPackageRemovedBroadcastInternal(); 14171 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14172 for (int i = 0; i < childCount; i++) { 14173 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14174 childInfo.sendPackageRemovedBroadcastInternal(); 14175 } 14176 } 14177 14178 void sendSystemPackageUpdatedBroadcasts() { 14179 if (isRemovedPackageSystemUpdate) { 14180 sendSystemPackageUpdatedBroadcastsInternal(); 14181 final int childCount = (removedChildPackages != null) 14182 ? removedChildPackages.size() : 0; 14183 for (int i = 0; i < childCount; i++) { 14184 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14185 if (childInfo.isRemovedPackageSystemUpdate) { 14186 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14187 } 14188 } 14189 } 14190 } 14191 14192 void sendSystemPackageAppearedBroadcasts() { 14193 final int packageCount = (appearedChildPackages != null) 14194 ? appearedChildPackages.size() : 0; 14195 for (int i = 0; i < packageCount; i++) { 14196 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14197 for (int userId : installedInfo.newUsers) { 14198 sendPackageAddedForUser(installedInfo.name, true, 14199 UserHandle.getAppId(installedInfo.uid), userId); 14200 } 14201 } 14202 } 14203 14204 private void sendSystemPackageUpdatedBroadcastsInternal() { 14205 Bundle extras = new Bundle(2); 14206 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14207 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14208 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14209 extras, 0, null, null, null); 14210 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14211 extras, 0, null, null, null); 14212 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14213 null, 0, removedPackage, null, null); 14214 } 14215 14216 private void sendPackageRemovedBroadcastInternal() { 14217 Bundle extras = new Bundle(2); 14218 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14219 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14220 if (isUpdate || isRemovedPackageSystemUpdate) { 14221 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14222 } 14223 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14224 if (removedPackage != null) { 14225 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14226 extras, 0, null, null, removedUsers); 14227 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14228 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14229 removedPackage, extras, 0, null, null, removedUsers); 14230 } 14231 } 14232 if (removedAppId >= 0) { 14233 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14234 removedUsers); 14235 } 14236 } 14237 } 14238 14239 /* 14240 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14241 * flag is not set, the data directory is removed as well. 14242 * make sure this flag is set for partially installed apps. If not its meaningless to 14243 * delete a partially installed application. 14244 */ 14245 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14246 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14247 String packageName = ps.name; 14248 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14249 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14250 // Retrieve object to delete permissions for shared user later on 14251 final PackageSetting deletedPs; 14252 // reader 14253 synchronized (mPackages) { 14254 deletedPs = mSettings.mPackages.get(packageName); 14255 if (outInfo != null) { 14256 outInfo.removedPackage = packageName; 14257 outInfo.removedUsers = deletedPs != null 14258 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14259 : null; 14260 } 14261 } 14262 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14263 removeDataDirsLI(ps.volumeUuid, packageName); 14264 if (outInfo != null) { 14265 outInfo.dataRemoved = true; 14266 } 14267 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14268 } 14269 // writer 14270 synchronized (mPackages) { 14271 if (deletedPs != null) { 14272 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14273 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14274 clearDefaultBrowserIfNeeded(packageName); 14275 if (outInfo != null) { 14276 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14277 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14278 } 14279 updatePermissionsLPw(deletedPs.name, null, 0); 14280 if (deletedPs.sharedUser != null) { 14281 // Remove permissions associated with package. Since runtime 14282 // permissions are per user we have to kill the removed package 14283 // or packages running under the shared user of the removed 14284 // package if revoking the permissions requested only by the removed 14285 // package is successful and this causes a change in gids. 14286 for (int userId : UserManagerService.getInstance().getUserIds()) { 14287 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14288 userId); 14289 if (userIdToKill == UserHandle.USER_ALL 14290 || userIdToKill >= UserHandle.USER_SYSTEM) { 14291 // If gids changed for this user, kill all affected packages. 14292 mHandler.post(new Runnable() { 14293 @Override 14294 public void run() { 14295 // This has to happen with no lock held. 14296 killApplication(deletedPs.name, deletedPs.appId, 14297 KILL_APP_REASON_GIDS_CHANGED); 14298 } 14299 }); 14300 break; 14301 } 14302 } 14303 } 14304 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14305 } 14306 // make sure to preserve per-user disabled state if this removal was just 14307 // a downgrade of a system app to the factory package 14308 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14309 if (DEBUG_REMOVE) { 14310 Slog.d(TAG, "Propagating install state across downgrade"); 14311 } 14312 for (int userId : allUserHandles) { 14313 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14314 if (DEBUG_REMOVE) { 14315 Slog.d(TAG, " user " + userId + " => " + installed); 14316 } 14317 ps.setInstalled(installed, userId); 14318 } 14319 } 14320 } 14321 // can downgrade to reader 14322 if (writeSettings) { 14323 // Save settings now 14324 mSettings.writeLPr(); 14325 } 14326 } 14327 if (outInfo != null) { 14328 // A user ID was deleted here. Go through all users and remove it 14329 // from KeyStore. 14330 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14331 } 14332 } 14333 14334 static boolean locationIsPrivileged(File path) { 14335 try { 14336 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14337 .getCanonicalPath(); 14338 return path.getCanonicalPath().startsWith(privilegedAppDir); 14339 } catch (IOException e) { 14340 Slog.e(TAG, "Unable to access code path " + path); 14341 } 14342 return false; 14343 } 14344 14345 /* 14346 * Tries to delete system package. 14347 */ 14348 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14349 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14350 boolean writeSettings) { 14351 if (deletedPkg.parentPackage != null) { 14352 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14353 return false; 14354 } 14355 14356 final boolean applyUserRestrictions 14357 = (allUserHandles != null) && (outInfo.origUsers != null); 14358 final PackageSetting disabledPs; 14359 // Confirm if the system package has been updated 14360 // An updated system app can be deleted. This will also have to restore 14361 // the system pkg from system partition 14362 // reader 14363 synchronized (mPackages) { 14364 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName); 14365 } 14366 14367 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14368 + " disabledPs=" + disabledPs); 14369 14370 if (disabledPs == null) { 14371 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14372 return false; 14373 } else if (DEBUG_REMOVE) { 14374 Slog.d(TAG, "Deleting system pkg from data partition"); 14375 } 14376 14377 if (DEBUG_REMOVE) { 14378 if (applyUserRestrictions) { 14379 Slog.d(TAG, "Remembering install states:"); 14380 for (int userId : allUserHandles) { 14381 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14382 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14383 } 14384 } 14385 } 14386 14387 // Delete the updated package 14388 outInfo.isRemovedPackageSystemUpdate = true; 14389 if (outInfo.removedChildPackages != null) { 14390 final int childCount = (deletedPkg.childPackages != null) 14391 ? deletedPkg.childPackages.size() : 0; 14392 for (int i = 0; i < childCount; i++) { 14393 String childPackageName = deletedPkg.childPackages.get(i).packageName; 14394 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14395 .contains(childPackageName)) { 14396 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14397 childPackageName); 14398 if (childInfo != null) { 14399 childInfo.isRemovedPackageSystemUpdate = true; 14400 } 14401 } 14402 } 14403 } 14404 14405 if (disabledPs.versionCode < deletedPs.versionCode) { 14406 // Delete data for downgrades 14407 flags &= ~PackageManager.DELETE_KEEP_DATA; 14408 } else { 14409 // Preserve data by setting flag 14410 flags |= PackageManager.DELETE_KEEP_DATA; 14411 } 14412 14413 boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles, 14414 outInfo, writeSettings, disabledPs.pkg); 14415 if (!ret) { 14416 return false; 14417 } 14418 14419 // writer 14420 synchronized (mPackages) { 14421 // Reinstate the old system package 14422 enableSystemPackageLPw(disabledPs.pkg); 14423 // Remove any native libraries from the upgraded package. 14424 removeNativeBinariesLI(deletedPkg); 14425 } 14426 14427 // Install the system package 14428 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14429 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14430 if (locationIsPrivileged(disabledPs.codePath)) { 14431 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14432 } 14433 14434 final PackageParser.Package newPkg; 14435 try { 14436 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14437 } catch (PackageManagerException e) { 14438 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14439 + e.getMessage()); 14440 return false; 14441 } 14442 14443 prepareAppDataAfterInstall(newPkg); 14444 14445 // writer 14446 synchronized (mPackages) { 14447 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14448 14449 // Propagate the permissions state as we do not want to drop on the floor 14450 // runtime permissions. The update permissions method below will take 14451 // care of removing obsolete permissions and grant install permissions. 14452 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14453 updatePermissionsLPw(newPkg.packageName, newPkg, 14454 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14455 14456 if (applyUserRestrictions) { 14457 if (DEBUG_REMOVE) { 14458 Slog.d(TAG, "Propagating install state across reinstall"); 14459 } 14460 for (int userId : allUserHandles) { 14461 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14462 if (DEBUG_REMOVE) { 14463 Slog.d(TAG, " user " + userId + " => " + installed); 14464 } 14465 ps.setInstalled(installed, userId); 14466 14467 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14468 } 14469 // Regardless of writeSettings we need to ensure that this restriction 14470 // state propagation is persisted 14471 mSettings.writeAllUsersPackageRestrictionsLPr(); 14472 } 14473 // can downgrade to reader here 14474 if (writeSettings) { 14475 mSettings.writeLPr(); 14476 } 14477 } 14478 return true; 14479 } 14480 14481 private boolean deleteInstalledPackageLI(PackageParser.Package pkg, 14482 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14483 PackageRemovedInfo outInfo, boolean writeSettings, 14484 PackageParser.Package replacingPackage) { 14485 PackageSetting ps = null; 14486 14487 synchronized (mPackages) { 14488 pkg = mPackages.get(pkg.packageName); 14489 if (pkg == null) { 14490 return false; 14491 } 14492 14493 ps = mSettings.mPackages.get(pkg.packageName); 14494 if (ps == null) { 14495 return false; 14496 } 14497 14498 if (outInfo != null) { 14499 outInfo.uid = ps.appId; 14500 } 14501 14502 if (outInfo != null && outInfo.removedChildPackages != null) { 14503 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14504 for (int i = 0; i < childCount; i++) { 14505 String childPackageName = ps.childPackageNames.get(i); 14506 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14507 if (childPs == null) { 14508 return false; 14509 } 14510 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14511 childPackageName); 14512 if (childInfo != null) { 14513 childInfo.uid = childPs.appId; 14514 } 14515 } 14516 } 14517 } 14518 14519 // Delete package data from internal structures and also remove data if flag is set 14520 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14521 14522 // Delete the child packages data 14523 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14524 for (int i = 0; i < childCount; i++) { 14525 PackageSetting childPs; 14526 synchronized (mPackages) { 14527 childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName); 14528 } 14529 if (childPs != null) { 14530 PackageRemovedInfo childOutInfo = (outInfo != null 14531 && outInfo.removedChildPackages != null) 14532 ? outInfo.removedChildPackages.get(childPs.name) : null; 14533 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14534 && (replacingPackage != null 14535 && !replacingPackage.hasChildPackage(childPs.name)) 14536 ? flags & ~DELETE_KEEP_DATA : flags; 14537 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14538 deleteFlags, writeSettings); 14539 } 14540 } 14541 14542 // Delete application code and resources only for parent packages 14543 if (ps.pkg.parentPackage == null) { 14544 if (deleteCodeAndResources && (outInfo != null)) { 14545 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14546 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14547 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14548 } 14549 } 14550 14551 return true; 14552 } 14553 14554 @Override 14555 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14556 int userId) { 14557 mContext.enforceCallingOrSelfPermission( 14558 android.Manifest.permission.DELETE_PACKAGES, null); 14559 synchronized (mPackages) { 14560 PackageSetting ps = mSettings.mPackages.get(packageName); 14561 if (ps == null) { 14562 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14563 return false; 14564 } 14565 if (!ps.getInstalled(userId)) { 14566 // Can't block uninstall for an app that is not installed or enabled. 14567 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14568 return false; 14569 } 14570 ps.setBlockUninstall(blockUninstall, userId); 14571 mSettings.writePackageRestrictionsLPr(userId); 14572 } 14573 return true; 14574 } 14575 14576 @Override 14577 public boolean getBlockUninstallForUser(String packageName, int userId) { 14578 synchronized (mPackages) { 14579 PackageSetting ps = mSettings.mPackages.get(packageName); 14580 if (ps == null) { 14581 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14582 return false; 14583 } 14584 return ps.getBlockUninstall(userId); 14585 } 14586 } 14587 14588 @Override 14589 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14590 int callingUid = Binder.getCallingUid(); 14591 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14592 throw new SecurityException( 14593 "setRequiredForSystemUser can only be run by the system or root"); 14594 } 14595 synchronized (mPackages) { 14596 PackageSetting ps = mSettings.mPackages.get(packageName); 14597 if (ps == null) { 14598 Log.w(TAG, "Package doesn't exist: " + packageName); 14599 return false; 14600 } 14601 if (systemUserApp) { 14602 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14603 } else { 14604 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14605 } 14606 mSettings.writeLPr(); 14607 } 14608 return true; 14609 } 14610 14611 /* 14612 * This method handles package deletion in general 14613 */ 14614 private boolean deletePackageLI(String packageName, UserHandle user, 14615 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14616 PackageRemovedInfo outInfo, boolean writeSettings, 14617 PackageParser.Package replacingPackage) { 14618 if (packageName == null) { 14619 Slog.w(TAG, "Attempt to delete null packageName."); 14620 return false; 14621 } 14622 14623 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14624 14625 PackageSetting ps; 14626 14627 synchronized (mPackages) { 14628 ps = mSettings.mPackages.get(packageName); 14629 if (ps == null) { 14630 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14631 return false; 14632 } 14633 14634 if (ps.pkg.parentPackage != null && (!isSystemApp(ps) 14635 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14636 if (DEBUG_REMOVE) { 14637 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14638 + ((user == null) ? UserHandle.USER_ALL : user)); 14639 } 14640 final int removedUserId = (user != null) ? user.getIdentifier() 14641 : UserHandle.USER_ALL; 14642 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14643 return false; 14644 } 14645 markPackageUninstalledForUserLPw(ps, user); 14646 scheduleWritePackageRestrictionsLocked(user); 14647 return true; 14648 } 14649 } 14650 14651 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14652 && user.getIdentifier() != UserHandle.USER_ALL)) { 14653 // The caller is asking that the package only be deleted for a single 14654 // user. To do this, we just mark its uninstalled state and delete 14655 // its data. If this is a system app, we only allow this to happen if 14656 // they have set the special DELETE_SYSTEM_APP which requests different 14657 // semantics than normal for uninstalling system apps. 14658 markPackageUninstalledForUserLPw(ps, user); 14659 14660 if (!isSystemApp(ps)) { 14661 // Do not uninstall the APK if an app should be cached 14662 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14663 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14664 // Other user still have this package installed, so all 14665 // we need to do is clear this user's data and save that 14666 // it is uninstalled. 14667 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14668 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14669 return false; 14670 } 14671 scheduleWritePackageRestrictionsLocked(user); 14672 return true; 14673 } else { 14674 // We need to set it back to 'installed' so the uninstall 14675 // broadcasts will be sent correctly. 14676 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14677 ps.setInstalled(true, user.getIdentifier()); 14678 } 14679 } else { 14680 // This is a system app, so we assume that the 14681 // other users still have this package installed, so all 14682 // we need to do is clear this user's data and save that 14683 // it is uninstalled. 14684 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14685 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14686 return false; 14687 } 14688 scheduleWritePackageRestrictionsLocked(user); 14689 return true; 14690 } 14691 } 14692 14693 // If we are deleting a composite package for all users, keep track 14694 // of result for each child. 14695 if (ps.childPackageNames != null && outInfo != null) { 14696 synchronized (mPackages) { 14697 final int childCount = ps.childPackageNames.size(); 14698 outInfo.removedChildPackages = new ArrayMap<>(childCount); 14699 for (int i = 0; i < childCount; i++) { 14700 String childPackageName = ps.childPackageNames.get(i); 14701 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 14702 childInfo.removedPackage = childPackageName; 14703 outInfo.removedChildPackages.put(childPackageName, childInfo); 14704 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14705 if (childPs != null) { 14706 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 14707 } 14708 } 14709 } 14710 } 14711 14712 boolean ret = false; 14713 if (isSystemApp(ps)) { 14714 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14715 // When an updated system application is deleted we delete the existing resources 14716 // as well and fall back to existing code in system partition 14717 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 14718 } else { 14719 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14720 // Kill application pre-emptively especially for apps on sd. 14721 killApplication(packageName, ps.appId, "uninstall pkg"); 14722 ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles, 14723 outInfo, writeSettings, replacingPackage); 14724 } 14725 14726 // Take a note whether we deleted the package for all users 14727 if (outInfo != null) { 14728 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14729 if (outInfo.removedChildPackages != null) { 14730 synchronized (mPackages) { 14731 final int childCount = outInfo.removedChildPackages.size(); 14732 for (int i = 0; i < childCount; i++) { 14733 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 14734 if (childInfo != null) { 14735 childInfo.removedForAllUsers = mPackages.get( 14736 childInfo.removedPackage) == null; 14737 } 14738 } 14739 } 14740 } 14741 // If we uninstalled an update to a system app there may be some 14742 // child packages that appeared as they are declared in the system 14743 // app but were not declared in the update. 14744 if (isSystemApp(ps)) { 14745 synchronized (mPackages) { 14746 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 14747 final int childCount = (updatedPs.childPackageNames != null) 14748 ? updatedPs.childPackageNames.size() : 0; 14749 for (int i = 0; i < childCount; i++) { 14750 String childPackageName = updatedPs.childPackageNames.get(i); 14751 if (outInfo.removedChildPackages == null 14752 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 14753 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14754 if (childPs == null) { 14755 continue; 14756 } 14757 PackageInstalledInfo installRes = new PackageInstalledInfo(); 14758 installRes.name = childPackageName; 14759 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 14760 installRes.pkg = mPackages.get(childPackageName); 14761 installRes.uid = childPs.pkg.applicationInfo.uid; 14762 if (outInfo.appearedChildPackages == null) { 14763 outInfo.appearedChildPackages = new ArrayMap<>(); 14764 } 14765 outInfo.appearedChildPackages.put(childPackageName, installRes); 14766 } 14767 } 14768 } 14769 } 14770 } 14771 14772 return ret; 14773 } 14774 14775 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 14776 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 14777 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 14778 for (int nextUserId : userIds) { 14779 if (DEBUG_REMOVE) { 14780 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 14781 } 14782 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 14783 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 14784 false /*hidden*/, false /*suspended*/, null, null, null, 14785 false /*blockUninstall*/, 14786 ps.readUserState(nextUserId).domainVerificationStatus, 0); 14787 } 14788 } 14789 14790 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 14791 PackageRemovedInfo outInfo) { 14792 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14793 : new int[] {userId}; 14794 for (int nextUserId : userIds) { 14795 if (DEBUG_REMOVE) { 14796 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 14797 + nextUserId); 14798 } 14799 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 14800 try { 14801 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 14802 } catch (InstallerException e) { 14803 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 14804 return false; 14805 } 14806 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 14807 schedulePackageCleaning(ps.name, nextUserId, false); 14808 synchronized (mPackages) { 14809 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 14810 scheduleWritePackageRestrictionsLocked(nextUserId); 14811 } 14812 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 14813 } 14814 } 14815 14816 if (outInfo != null) { 14817 outInfo.removedPackage = ps.name; 14818 outInfo.removedAppId = ps.appId; 14819 outInfo.removedUsers = userIds; 14820 } 14821 14822 return true; 14823 } 14824 14825 private final class ClearStorageConnection implements ServiceConnection { 14826 IMediaContainerService mContainerService; 14827 14828 @Override 14829 public void onServiceConnected(ComponentName name, IBinder service) { 14830 synchronized (this) { 14831 mContainerService = IMediaContainerService.Stub.asInterface(service); 14832 notifyAll(); 14833 } 14834 } 14835 14836 @Override 14837 public void onServiceDisconnected(ComponentName name) { 14838 } 14839 } 14840 14841 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 14842 final boolean mounted; 14843 if (Environment.isExternalStorageEmulated()) { 14844 mounted = true; 14845 } else { 14846 final String status = Environment.getExternalStorageState(); 14847 14848 mounted = status.equals(Environment.MEDIA_MOUNTED) 14849 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 14850 } 14851 14852 if (!mounted) { 14853 return; 14854 } 14855 14856 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 14857 int[] users; 14858 if (userId == UserHandle.USER_ALL) { 14859 users = sUserManager.getUserIds(); 14860 } else { 14861 users = new int[] { userId }; 14862 } 14863 final ClearStorageConnection conn = new ClearStorageConnection(); 14864 if (mContext.bindServiceAsUser( 14865 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 14866 try { 14867 for (int curUser : users) { 14868 long timeout = SystemClock.uptimeMillis() + 5000; 14869 synchronized (conn) { 14870 long now = SystemClock.uptimeMillis(); 14871 while (conn.mContainerService == null && now < timeout) { 14872 try { 14873 conn.wait(timeout - now); 14874 } catch (InterruptedException e) { 14875 } 14876 } 14877 } 14878 if (conn.mContainerService == null) { 14879 return; 14880 } 14881 14882 final UserEnvironment userEnv = new UserEnvironment(curUser); 14883 clearDirectory(conn.mContainerService, 14884 userEnv.buildExternalStorageAppCacheDirs(packageName)); 14885 if (allData) { 14886 clearDirectory(conn.mContainerService, 14887 userEnv.buildExternalStorageAppDataDirs(packageName)); 14888 clearDirectory(conn.mContainerService, 14889 userEnv.buildExternalStorageAppMediaDirs(packageName)); 14890 } 14891 } 14892 } finally { 14893 mContext.unbindService(conn); 14894 } 14895 } 14896 } 14897 14898 @Override 14899 public void clearApplicationUserData(final String packageName, 14900 final IPackageDataObserver observer, final int userId) { 14901 mContext.enforceCallingOrSelfPermission( 14902 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 14903 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 14904 // Queue up an async operation since the package deletion may take a little while. 14905 mHandler.post(new Runnable() { 14906 public void run() { 14907 mHandler.removeCallbacks(this); 14908 final boolean succeeded; 14909 synchronized (mInstallLock) { 14910 succeeded = clearApplicationUserDataLI(packageName, userId); 14911 } 14912 clearExternalStorageDataSync(packageName, userId, true); 14913 if (succeeded) { 14914 // invoke DeviceStorageMonitor's update method to clear any notifications 14915 DeviceStorageMonitorInternal 14916 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14917 if (dsm != null) { 14918 dsm.checkMemory(); 14919 } 14920 } 14921 if(observer != null) { 14922 try { 14923 observer.onRemoveCompleted(packageName, succeeded); 14924 } catch (RemoteException e) { 14925 Log.i(TAG, "Observer no longer exists."); 14926 } 14927 } //end if observer 14928 } //end run 14929 }); 14930 } 14931 14932 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14933 if (packageName == null) { 14934 Slog.w(TAG, "Attempt to delete null packageName."); 14935 return false; 14936 } 14937 14938 // Try finding details about the requested package 14939 PackageParser.Package pkg; 14940 synchronized (mPackages) { 14941 pkg = mPackages.get(packageName); 14942 if (pkg == null) { 14943 final PackageSetting ps = mSettings.mPackages.get(packageName); 14944 if (ps != null) { 14945 pkg = ps.pkg; 14946 } 14947 } 14948 14949 if (pkg == null) { 14950 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14951 return false; 14952 } 14953 14954 PackageSetting ps = (PackageSetting) pkg.mExtras; 14955 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14956 } 14957 14958 // Always delete data directories for package, even if we found no other 14959 // record of app. This helps users recover from UID mismatches without 14960 // resorting to a full data wipe. 14961 // TODO: triage flags as part of 26466827 14962 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 14963 try { 14964 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14965 } catch (InstallerException e) { 14966 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14967 return false; 14968 } 14969 14970 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14971 removeKeystoreDataIfNeeded(userId, appId); 14972 14973 // Create a native library symlink only if we have native libraries 14974 // and if the native libraries are 32 bit libraries. We do not provide 14975 // this symlink for 64 bit libraries. 14976 if (pkg.applicationInfo.primaryCpuAbi != null && 14977 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14978 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14979 try { 14980 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14981 nativeLibPath, userId); 14982 } catch (InstallerException e) { 14983 Slog.w(TAG, "Failed linking native library dir", e); 14984 return false; 14985 } 14986 } 14987 14988 return true; 14989 } 14990 14991 /** 14992 * Reverts user permission state changes (permissions and flags) in 14993 * all packages for a given user. 14994 * 14995 * @param userId The device user for which to do a reset. 14996 */ 14997 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14998 final int packageCount = mPackages.size(); 14999 for (int i = 0; i < packageCount; i++) { 15000 PackageParser.Package pkg = mPackages.valueAt(i); 15001 PackageSetting ps = (PackageSetting) pkg.mExtras; 15002 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15003 } 15004 } 15005 15006 /** 15007 * Reverts user permission state changes (permissions and flags). 15008 * 15009 * @param ps The package for which to reset. 15010 * @param userId The device user for which to do a reset. 15011 */ 15012 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15013 final PackageSetting ps, final int userId) { 15014 if (ps.pkg == null) { 15015 return; 15016 } 15017 15018 // These are flags that can change base on user actions. 15019 final int userSettableMask = FLAG_PERMISSION_USER_SET 15020 | FLAG_PERMISSION_USER_FIXED 15021 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15022 | FLAG_PERMISSION_REVIEW_REQUIRED; 15023 15024 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15025 | FLAG_PERMISSION_POLICY_FIXED; 15026 15027 boolean writeInstallPermissions = false; 15028 boolean writeRuntimePermissions = false; 15029 15030 final int permissionCount = ps.pkg.requestedPermissions.size(); 15031 for (int i = 0; i < permissionCount; i++) { 15032 String permission = ps.pkg.requestedPermissions.get(i); 15033 15034 BasePermission bp = mSettings.mPermissions.get(permission); 15035 if (bp == null) { 15036 continue; 15037 } 15038 15039 // If shared user we just reset the state to which only this app contributed. 15040 if (ps.sharedUser != null) { 15041 boolean used = false; 15042 final int packageCount = ps.sharedUser.packages.size(); 15043 for (int j = 0; j < packageCount; j++) { 15044 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15045 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15046 && pkg.pkg.requestedPermissions.contains(permission)) { 15047 used = true; 15048 break; 15049 } 15050 } 15051 if (used) { 15052 continue; 15053 } 15054 } 15055 15056 PermissionsState permissionsState = ps.getPermissionsState(); 15057 15058 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15059 15060 // Always clear the user settable flags. 15061 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15062 bp.name) != null; 15063 // If permission review is enabled and this is a legacy app, mark the 15064 // permission as requiring a review as this is the initial state. 15065 int flags = 0; 15066 if (Build.PERMISSIONS_REVIEW_REQUIRED 15067 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15068 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15069 } 15070 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15071 if (hasInstallState) { 15072 writeInstallPermissions = true; 15073 } else { 15074 writeRuntimePermissions = true; 15075 } 15076 } 15077 15078 // Below is only runtime permission handling. 15079 if (!bp.isRuntime()) { 15080 continue; 15081 } 15082 15083 // Never clobber system or policy. 15084 if ((oldFlags & policyOrSystemFlags) != 0) { 15085 continue; 15086 } 15087 15088 // If this permission was granted by default, make sure it is. 15089 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15090 if (permissionsState.grantRuntimePermission(bp, userId) 15091 != PERMISSION_OPERATION_FAILURE) { 15092 writeRuntimePermissions = true; 15093 } 15094 // If permission review is enabled the permissions for a legacy apps 15095 // are represented as constantly granted runtime ones, so don't revoke. 15096 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15097 // Otherwise, reset the permission. 15098 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15099 switch (revokeResult) { 15100 case PERMISSION_OPERATION_SUCCESS: { 15101 writeRuntimePermissions = true; 15102 } break; 15103 15104 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15105 writeRuntimePermissions = true; 15106 final int appId = ps.appId; 15107 mHandler.post(new Runnable() { 15108 @Override 15109 public void run() { 15110 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15111 } 15112 }); 15113 } break; 15114 } 15115 } 15116 } 15117 15118 // Synchronously write as we are taking permissions away. 15119 if (writeRuntimePermissions) { 15120 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15121 } 15122 15123 // Synchronously write as we are taking permissions away. 15124 if (writeInstallPermissions) { 15125 mSettings.writeLPr(); 15126 } 15127 } 15128 15129 /** 15130 * Remove entries from the keystore daemon. Will only remove it if the 15131 * {@code appId} is valid. 15132 */ 15133 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15134 if (appId < 0) { 15135 return; 15136 } 15137 15138 final KeyStore keyStore = KeyStore.getInstance(); 15139 if (keyStore != null) { 15140 if (userId == UserHandle.USER_ALL) { 15141 for (final int individual : sUserManager.getUserIds()) { 15142 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15143 } 15144 } else { 15145 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15146 } 15147 } else { 15148 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15149 } 15150 } 15151 15152 @Override 15153 public void deleteApplicationCacheFiles(final String packageName, 15154 final IPackageDataObserver observer) { 15155 mContext.enforceCallingOrSelfPermission( 15156 android.Manifest.permission.DELETE_CACHE_FILES, null); 15157 // Queue up an async operation since the package deletion may take a little while. 15158 final int userId = UserHandle.getCallingUserId(); 15159 mHandler.post(new Runnable() { 15160 public void run() { 15161 mHandler.removeCallbacks(this); 15162 final boolean succeded; 15163 synchronized (mInstallLock) { 15164 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15165 } 15166 clearExternalStorageDataSync(packageName, userId, false); 15167 if (observer != null) { 15168 try { 15169 observer.onRemoveCompleted(packageName, succeded); 15170 } catch (RemoteException e) { 15171 Log.i(TAG, "Observer no longer exists."); 15172 } 15173 } //end if observer 15174 } //end run 15175 }); 15176 } 15177 15178 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15179 if (packageName == null) { 15180 Slog.w(TAG, "Attempt to delete null packageName."); 15181 return false; 15182 } 15183 PackageParser.Package p; 15184 synchronized (mPackages) { 15185 p = mPackages.get(packageName); 15186 } 15187 if (p == null) { 15188 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15189 return false; 15190 } 15191 final ApplicationInfo applicationInfo = p.applicationInfo; 15192 if (applicationInfo == null) { 15193 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15194 return false; 15195 } 15196 // TODO: triage flags as part of 26466827 15197 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15198 try { 15199 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15200 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15201 } catch (InstallerException e) { 15202 Slog.w(TAG, "Couldn't remove cache files for package " 15203 + packageName + " u" + userId, e); 15204 return false; 15205 } 15206 return true; 15207 } 15208 15209 @Override 15210 public void getPackageSizeInfo(final String packageName, int userHandle, 15211 final IPackageStatsObserver observer) { 15212 mContext.enforceCallingOrSelfPermission( 15213 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15214 if (packageName == null) { 15215 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15216 } 15217 15218 PackageStats stats = new PackageStats(packageName, userHandle); 15219 15220 /* 15221 * Queue up an async operation since the package measurement may take a 15222 * little while. 15223 */ 15224 Message msg = mHandler.obtainMessage(INIT_COPY); 15225 msg.obj = new MeasureParams(stats, observer); 15226 mHandler.sendMessage(msg); 15227 } 15228 15229 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15230 PackageStats pStats) { 15231 if (packageName == null) { 15232 Slog.w(TAG, "Attempt to get size of null packageName."); 15233 return false; 15234 } 15235 PackageParser.Package p; 15236 boolean dataOnly = false; 15237 String libDirRoot = null; 15238 String asecPath = null; 15239 PackageSetting ps = null; 15240 synchronized (mPackages) { 15241 p = mPackages.get(packageName); 15242 ps = mSettings.mPackages.get(packageName); 15243 if(p == null) { 15244 dataOnly = true; 15245 if((ps == null) || (ps.pkg == null)) { 15246 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15247 return false; 15248 } 15249 p = ps.pkg; 15250 } 15251 if (ps != null) { 15252 libDirRoot = ps.legacyNativeLibraryPathString; 15253 } 15254 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15255 final long token = Binder.clearCallingIdentity(); 15256 try { 15257 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15258 if (secureContainerId != null) { 15259 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15260 } 15261 } finally { 15262 Binder.restoreCallingIdentity(token); 15263 } 15264 } 15265 } 15266 String publicSrcDir = null; 15267 if(!dataOnly) { 15268 final ApplicationInfo applicationInfo = p.applicationInfo; 15269 if (applicationInfo == null) { 15270 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15271 return false; 15272 } 15273 if (p.isForwardLocked()) { 15274 publicSrcDir = applicationInfo.getBaseResourcePath(); 15275 } 15276 } 15277 // TODO: extend to measure size of split APKs 15278 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15279 // not just the first level. 15280 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15281 // just the primary. 15282 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15283 15284 String apkPath; 15285 File packageDir = new File(p.codePath); 15286 15287 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15288 apkPath = packageDir.getAbsolutePath(); 15289 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15290 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15291 libDirRoot = null; 15292 } 15293 } else { 15294 apkPath = p.baseCodePath; 15295 } 15296 15297 // TODO: triage flags as part of 26466827 15298 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15299 try { 15300 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15301 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15302 } catch (InstallerException e) { 15303 return false; 15304 } 15305 15306 // Fix-up for forward-locked applications in ASEC containers. 15307 if (!isExternal(p)) { 15308 pStats.codeSize += pStats.externalCodeSize; 15309 pStats.externalCodeSize = 0L; 15310 } 15311 15312 return true; 15313 } 15314 15315 15316 @Override 15317 public void addPackageToPreferred(String packageName) { 15318 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 15319 } 15320 15321 @Override 15322 public void removePackageFromPreferred(String packageName) { 15323 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 15324 } 15325 15326 @Override 15327 public List<PackageInfo> getPreferredPackages(int flags) { 15328 return new ArrayList<PackageInfo>(); 15329 } 15330 15331 private int getUidTargetSdkVersionLockedLPr(int uid) { 15332 Object obj = mSettings.getUserIdLPr(uid); 15333 if (obj instanceof SharedUserSetting) { 15334 final SharedUserSetting sus = (SharedUserSetting) obj; 15335 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15336 final Iterator<PackageSetting> it = sus.packages.iterator(); 15337 while (it.hasNext()) { 15338 final PackageSetting ps = it.next(); 15339 if (ps.pkg != null) { 15340 int v = ps.pkg.applicationInfo.targetSdkVersion; 15341 if (v < vers) vers = v; 15342 } 15343 } 15344 return vers; 15345 } else if (obj instanceof PackageSetting) { 15346 final PackageSetting ps = (PackageSetting) obj; 15347 if (ps.pkg != null) { 15348 return ps.pkg.applicationInfo.targetSdkVersion; 15349 } 15350 } 15351 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15352 } 15353 15354 @Override 15355 public void addPreferredActivity(IntentFilter filter, int match, 15356 ComponentName[] set, ComponentName activity, int userId) { 15357 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15358 "Adding preferred"); 15359 } 15360 15361 private void addPreferredActivityInternal(IntentFilter filter, int match, 15362 ComponentName[] set, ComponentName activity, boolean always, int userId, 15363 String opname) { 15364 // writer 15365 int callingUid = Binder.getCallingUid(); 15366 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 15367 if (filter.countActions() == 0) { 15368 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15369 return; 15370 } 15371 synchronized (mPackages) { 15372 if (mContext.checkCallingOrSelfPermission( 15373 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15374 != PackageManager.PERMISSION_GRANTED) { 15375 if (getUidTargetSdkVersionLockedLPr(callingUid) 15376 < Build.VERSION_CODES.FROYO) { 15377 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15378 + callingUid); 15379 return; 15380 } 15381 mContext.enforceCallingOrSelfPermission( 15382 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15383 } 15384 15385 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15386 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15387 + userId + ":"); 15388 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15389 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15390 scheduleWritePackageRestrictionsLocked(userId); 15391 } 15392 } 15393 15394 @Override 15395 public void replacePreferredActivity(IntentFilter filter, int match, 15396 ComponentName[] set, ComponentName activity, int userId) { 15397 if (filter.countActions() != 1) { 15398 throw new IllegalArgumentException( 15399 "replacePreferredActivity expects filter to have only 1 action."); 15400 } 15401 if (filter.countDataAuthorities() != 0 15402 || filter.countDataPaths() != 0 15403 || filter.countDataSchemes() > 1 15404 || filter.countDataTypes() != 0) { 15405 throw new IllegalArgumentException( 15406 "replacePreferredActivity expects filter to have no data authorities, " + 15407 "paths, or types; and at most one scheme."); 15408 } 15409 15410 final int callingUid = Binder.getCallingUid(); 15411 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 15412 synchronized (mPackages) { 15413 if (mContext.checkCallingOrSelfPermission( 15414 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15415 != PackageManager.PERMISSION_GRANTED) { 15416 if (getUidTargetSdkVersionLockedLPr(callingUid) 15417 < Build.VERSION_CODES.FROYO) { 15418 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15419 + Binder.getCallingUid()); 15420 return; 15421 } 15422 mContext.enforceCallingOrSelfPermission( 15423 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15424 } 15425 15426 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15427 if (pir != null) { 15428 // Get all of the existing entries that exactly match this filter. 15429 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15430 if (existing != null && existing.size() == 1) { 15431 PreferredActivity cur = existing.get(0); 15432 if (DEBUG_PREFERRED) { 15433 Slog.i(TAG, "Checking replace of preferred:"); 15434 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15435 if (!cur.mPref.mAlways) { 15436 Slog.i(TAG, " -- CUR; not mAlways!"); 15437 } else { 15438 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15439 Slog.i(TAG, " -- CUR: mSet=" 15440 + Arrays.toString(cur.mPref.mSetComponents)); 15441 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15442 Slog.i(TAG, " -- NEW: mMatch=" 15443 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15444 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15445 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15446 } 15447 } 15448 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15449 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15450 && cur.mPref.sameSet(set)) { 15451 // Setting the preferred activity to what it happens to be already 15452 if (DEBUG_PREFERRED) { 15453 Slog.i(TAG, "Replacing with same preferred activity " 15454 + cur.mPref.mShortComponent + " for user " 15455 + userId + ":"); 15456 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15457 } 15458 return; 15459 } 15460 } 15461 15462 if (existing != null) { 15463 if (DEBUG_PREFERRED) { 15464 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15465 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15466 } 15467 for (int i = 0; i < existing.size(); i++) { 15468 PreferredActivity pa = existing.get(i); 15469 if (DEBUG_PREFERRED) { 15470 Slog.i(TAG, "Removing existing preferred activity " 15471 + pa.mPref.mComponent + ":"); 15472 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15473 } 15474 pir.removeFilter(pa); 15475 } 15476 } 15477 } 15478 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15479 "Replacing preferred"); 15480 } 15481 } 15482 15483 @Override 15484 public void clearPackagePreferredActivities(String packageName) { 15485 final int uid = Binder.getCallingUid(); 15486 // writer 15487 synchronized (mPackages) { 15488 PackageParser.Package pkg = mPackages.get(packageName); 15489 if (pkg == null || pkg.applicationInfo.uid != uid) { 15490 if (mContext.checkCallingOrSelfPermission( 15491 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15492 != PackageManager.PERMISSION_GRANTED) { 15493 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15494 < Build.VERSION_CODES.FROYO) { 15495 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15496 + Binder.getCallingUid()); 15497 return; 15498 } 15499 mContext.enforceCallingOrSelfPermission( 15500 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15501 } 15502 } 15503 15504 int user = UserHandle.getCallingUserId(); 15505 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15506 scheduleWritePackageRestrictionsLocked(user); 15507 } 15508 } 15509 } 15510 15511 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15512 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15513 ArrayList<PreferredActivity> removed = null; 15514 boolean changed = false; 15515 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15516 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15517 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15518 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15519 continue; 15520 } 15521 Iterator<PreferredActivity> it = pir.filterIterator(); 15522 while (it.hasNext()) { 15523 PreferredActivity pa = it.next(); 15524 // Mark entry for removal only if it matches the package name 15525 // and the entry is of type "always". 15526 if (packageName == null || 15527 (pa.mPref.mComponent.getPackageName().equals(packageName) 15528 && pa.mPref.mAlways)) { 15529 if (removed == null) { 15530 removed = new ArrayList<PreferredActivity>(); 15531 } 15532 removed.add(pa); 15533 } 15534 } 15535 if (removed != null) { 15536 for (int j=0; j<removed.size(); j++) { 15537 PreferredActivity pa = removed.get(j); 15538 pir.removeFilter(pa); 15539 } 15540 changed = true; 15541 } 15542 } 15543 return changed; 15544 } 15545 15546 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15547 private void clearIntentFilterVerificationsLPw(int userId) { 15548 final int packageCount = mPackages.size(); 15549 for (int i = 0; i < packageCount; i++) { 15550 PackageParser.Package pkg = mPackages.valueAt(i); 15551 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15552 } 15553 } 15554 15555 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15556 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15557 if (userId == UserHandle.USER_ALL) { 15558 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15559 sUserManager.getUserIds())) { 15560 for (int oneUserId : sUserManager.getUserIds()) { 15561 scheduleWritePackageRestrictionsLocked(oneUserId); 15562 } 15563 } 15564 } else { 15565 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15566 scheduleWritePackageRestrictionsLocked(userId); 15567 } 15568 } 15569 } 15570 15571 void clearDefaultBrowserIfNeeded(String packageName) { 15572 for (int oneUserId : sUserManager.getUserIds()) { 15573 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15574 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15575 if (packageName.equals(defaultBrowserPackageName)) { 15576 setDefaultBrowserPackageName(null, oneUserId); 15577 } 15578 } 15579 } 15580 15581 @Override 15582 public void resetApplicationPreferences(int userId) { 15583 mContext.enforceCallingOrSelfPermission( 15584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15585 // writer 15586 synchronized (mPackages) { 15587 final long identity = Binder.clearCallingIdentity(); 15588 try { 15589 clearPackagePreferredActivitiesLPw(null, userId); 15590 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15591 // TODO: We have to reset the default SMS and Phone. This requires 15592 // significant refactoring to keep all default apps in the package 15593 // manager (cleaner but more work) or have the services provide 15594 // callbacks to the package manager to request a default app reset. 15595 applyFactoryDefaultBrowserLPw(userId); 15596 clearIntentFilterVerificationsLPw(userId); 15597 primeDomainVerificationsLPw(userId); 15598 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15599 scheduleWritePackageRestrictionsLocked(userId); 15600 } finally { 15601 Binder.restoreCallingIdentity(identity); 15602 } 15603 } 15604 } 15605 15606 @Override 15607 public int getPreferredActivities(List<IntentFilter> outFilters, 15608 List<ComponentName> outActivities, String packageName) { 15609 15610 int num = 0; 15611 final int userId = UserHandle.getCallingUserId(); 15612 // reader 15613 synchronized (mPackages) { 15614 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15615 if (pir != null) { 15616 final Iterator<PreferredActivity> it = pir.filterIterator(); 15617 while (it.hasNext()) { 15618 final PreferredActivity pa = it.next(); 15619 if (packageName == null 15620 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15621 && pa.mPref.mAlways)) { 15622 if (outFilters != null) { 15623 outFilters.add(new IntentFilter(pa)); 15624 } 15625 if (outActivities != null) { 15626 outActivities.add(pa.mPref.mComponent); 15627 } 15628 } 15629 } 15630 } 15631 } 15632 15633 return num; 15634 } 15635 15636 @Override 15637 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15638 int userId) { 15639 int callingUid = Binder.getCallingUid(); 15640 if (callingUid != Process.SYSTEM_UID) { 15641 throw new SecurityException( 15642 "addPersistentPreferredActivity can only be run by the system"); 15643 } 15644 if (filter.countActions() == 0) { 15645 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15646 return; 15647 } 15648 synchronized (mPackages) { 15649 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15650 ":"); 15651 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15652 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15653 new PersistentPreferredActivity(filter, activity)); 15654 scheduleWritePackageRestrictionsLocked(userId); 15655 } 15656 } 15657 15658 @Override 15659 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15660 int callingUid = Binder.getCallingUid(); 15661 if (callingUid != Process.SYSTEM_UID) { 15662 throw new SecurityException( 15663 "clearPackagePersistentPreferredActivities can only be run by the system"); 15664 } 15665 ArrayList<PersistentPreferredActivity> removed = null; 15666 boolean changed = false; 15667 synchronized (mPackages) { 15668 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15669 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15670 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15671 .valueAt(i); 15672 if (userId != thisUserId) { 15673 continue; 15674 } 15675 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15676 while (it.hasNext()) { 15677 PersistentPreferredActivity ppa = it.next(); 15678 // Mark entry for removal only if it matches the package name. 15679 if (ppa.mComponent.getPackageName().equals(packageName)) { 15680 if (removed == null) { 15681 removed = new ArrayList<PersistentPreferredActivity>(); 15682 } 15683 removed.add(ppa); 15684 } 15685 } 15686 if (removed != null) { 15687 for (int j=0; j<removed.size(); j++) { 15688 PersistentPreferredActivity ppa = removed.get(j); 15689 ppir.removeFilter(ppa); 15690 } 15691 changed = true; 15692 } 15693 } 15694 15695 if (changed) { 15696 scheduleWritePackageRestrictionsLocked(userId); 15697 } 15698 } 15699 } 15700 15701 /** 15702 * Common machinery for picking apart a restored XML blob and passing 15703 * it to a caller-supplied functor to be applied to the running system. 15704 */ 15705 private void restoreFromXml(XmlPullParser parser, int userId, 15706 String expectedStartTag, BlobXmlRestorer functor) 15707 throws IOException, XmlPullParserException { 15708 int type; 15709 while ((type = parser.next()) != XmlPullParser.START_TAG 15710 && type != XmlPullParser.END_DOCUMENT) { 15711 } 15712 if (type != XmlPullParser.START_TAG) { 15713 // oops didn't find a start tag?! 15714 if (DEBUG_BACKUP) { 15715 Slog.e(TAG, "Didn't find start tag during restore"); 15716 } 15717 return; 15718 } 15719Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15720 // this is supposed to be TAG_PREFERRED_BACKUP 15721 if (!expectedStartTag.equals(parser.getName())) { 15722 if (DEBUG_BACKUP) { 15723 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15724 } 15725 return; 15726 } 15727 15728 // skip interfering stuff, then we're aligned with the backing implementation 15729 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15730Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15731 functor.apply(parser, userId); 15732 } 15733 15734 private interface BlobXmlRestorer { 15735 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15736 } 15737 15738 /** 15739 * Non-Binder method, support for the backup/restore mechanism: write the 15740 * full set of preferred activities in its canonical XML format. Returns the 15741 * XML output as a byte array, or null if there is none. 15742 */ 15743 @Override 15744 public byte[] getPreferredActivityBackup(int userId) { 15745 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15746 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15747 } 15748 15749 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15750 try { 15751 final XmlSerializer serializer = new FastXmlSerializer(); 15752 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15753 serializer.startDocument(null, true); 15754 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15755 15756 synchronized (mPackages) { 15757 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15758 } 15759 15760 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15761 serializer.endDocument(); 15762 serializer.flush(); 15763 } catch (Exception e) { 15764 if (DEBUG_BACKUP) { 15765 Slog.e(TAG, "Unable to write preferred activities for backup", e); 15766 } 15767 return null; 15768 } 15769 15770 return dataStream.toByteArray(); 15771 } 15772 15773 @Override 15774 public void restorePreferredActivities(byte[] backup, int userId) { 15775 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15776 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15777 } 15778 15779 try { 15780 final XmlPullParser parser = Xml.newPullParser(); 15781 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15782 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 15783 new BlobXmlRestorer() { 15784 @Override 15785 public void apply(XmlPullParser parser, int userId) 15786 throws XmlPullParserException, IOException { 15787 synchronized (mPackages) { 15788 mSettings.readPreferredActivitiesLPw(parser, userId); 15789 } 15790 } 15791 } ); 15792 } catch (Exception e) { 15793 if (DEBUG_BACKUP) { 15794 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15795 } 15796 } 15797 } 15798 15799 /** 15800 * Non-Binder method, support for the backup/restore mechanism: write the 15801 * default browser (etc) settings in its canonical XML format. Returns the default 15802 * browser XML representation as a byte array, or null if there is none. 15803 */ 15804 @Override 15805 public byte[] getDefaultAppsBackup(int userId) { 15806 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15807 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15808 } 15809 15810 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15811 try { 15812 final XmlSerializer serializer = new FastXmlSerializer(); 15813 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15814 serializer.startDocument(null, true); 15815 serializer.startTag(null, TAG_DEFAULT_APPS); 15816 15817 synchronized (mPackages) { 15818 mSettings.writeDefaultAppsLPr(serializer, userId); 15819 } 15820 15821 serializer.endTag(null, TAG_DEFAULT_APPS); 15822 serializer.endDocument(); 15823 serializer.flush(); 15824 } catch (Exception e) { 15825 if (DEBUG_BACKUP) { 15826 Slog.e(TAG, "Unable to write default apps for backup", e); 15827 } 15828 return null; 15829 } 15830 15831 return dataStream.toByteArray(); 15832 } 15833 15834 @Override 15835 public void restoreDefaultApps(byte[] backup, int userId) { 15836 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15837 throw new SecurityException("Only the system may call restoreDefaultApps()"); 15838 } 15839 15840 try { 15841 final XmlPullParser parser = Xml.newPullParser(); 15842 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15843 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 15844 new BlobXmlRestorer() { 15845 @Override 15846 public void apply(XmlPullParser parser, int userId) 15847 throws XmlPullParserException, IOException { 15848 synchronized (mPackages) { 15849 mSettings.readDefaultAppsLPw(parser, userId); 15850 } 15851 } 15852 } ); 15853 } catch (Exception e) { 15854 if (DEBUG_BACKUP) { 15855 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 15856 } 15857 } 15858 } 15859 15860 @Override 15861 public byte[] getIntentFilterVerificationBackup(int userId) { 15862 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15863 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 15864 } 15865 15866 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15867 try { 15868 final XmlSerializer serializer = new FastXmlSerializer(); 15869 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15870 serializer.startDocument(null, true); 15871 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 15872 15873 synchronized (mPackages) { 15874 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 15875 } 15876 15877 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 15878 serializer.endDocument(); 15879 serializer.flush(); 15880 } catch (Exception e) { 15881 if (DEBUG_BACKUP) { 15882 Slog.e(TAG, "Unable to write default apps for backup", e); 15883 } 15884 return null; 15885 } 15886 15887 return dataStream.toByteArray(); 15888 } 15889 15890 @Override 15891 public void restoreIntentFilterVerification(byte[] backup, int userId) { 15892 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15893 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15894 } 15895 15896 try { 15897 final XmlPullParser parser = Xml.newPullParser(); 15898 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15899 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 15900 new BlobXmlRestorer() { 15901 @Override 15902 public void apply(XmlPullParser parser, int userId) 15903 throws XmlPullParserException, IOException { 15904 synchronized (mPackages) { 15905 mSettings.readAllDomainVerificationsLPr(parser, userId); 15906 mSettings.writeLPr(); 15907 } 15908 } 15909 } ); 15910 } catch (Exception e) { 15911 if (DEBUG_BACKUP) { 15912 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15913 } 15914 } 15915 } 15916 15917 @Override 15918 public byte[] getPermissionGrantBackup(int userId) { 15919 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15920 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15921 } 15922 15923 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15924 try { 15925 final XmlSerializer serializer = new FastXmlSerializer(); 15926 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15927 serializer.startDocument(null, true); 15928 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15929 15930 synchronized (mPackages) { 15931 serializeRuntimePermissionGrantsLPr(serializer, userId); 15932 } 15933 15934 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15935 serializer.endDocument(); 15936 serializer.flush(); 15937 } catch (Exception e) { 15938 if (DEBUG_BACKUP) { 15939 Slog.e(TAG, "Unable to write default apps for backup", e); 15940 } 15941 return null; 15942 } 15943 15944 return dataStream.toByteArray(); 15945 } 15946 15947 @Override 15948 public void restorePermissionGrants(byte[] backup, int userId) { 15949 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15950 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15951 } 15952 15953 try { 15954 final XmlPullParser parser = Xml.newPullParser(); 15955 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15956 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15957 new BlobXmlRestorer() { 15958 @Override 15959 public void apply(XmlPullParser parser, int userId) 15960 throws XmlPullParserException, IOException { 15961 synchronized (mPackages) { 15962 processRestoredPermissionGrantsLPr(parser, userId); 15963 } 15964 } 15965 } ); 15966 } catch (Exception e) { 15967 if (DEBUG_BACKUP) { 15968 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15969 } 15970 } 15971 } 15972 15973 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15974 throws IOException { 15975 serializer.startTag(null, TAG_ALL_GRANTS); 15976 15977 final int N = mSettings.mPackages.size(); 15978 for (int i = 0; i < N; i++) { 15979 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15980 boolean pkgGrantsKnown = false; 15981 15982 PermissionsState packagePerms = ps.getPermissionsState(); 15983 15984 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15985 final int grantFlags = state.getFlags(); 15986 // only look at grants that are not system/policy fixed 15987 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15988 final boolean isGranted = state.isGranted(); 15989 // And only back up the user-twiddled state bits 15990 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15991 final String packageName = mSettings.mPackages.keyAt(i); 15992 if (!pkgGrantsKnown) { 15993 serializer.startTag(null, TAG_GRANT); 15994 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15995 pkgGrantsKnown = true; 15996 } 15997 15998 final boolean userSet = 15999 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16000 final boolean userFixed = 16001 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16002 final boolean revoke = 16003 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16004 16005 serializer.startTag(null, TAG_PERMISSION); 16006 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16007 if (isGranted) { 16008 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16009 } 16010 if (userSet) { 16011 serializer.attribute(null, ATTR_USER_SET, "true"); 16012 } 16013 if (userFixed) { 16014 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16015 } 16016 if (revoke) { 16017 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16018 } 16019 serializer.endTag(null, TAG_PERMISSION); 16020 } 16021 } 16022 } 16023 16024 if (pkgGrantsKnown) { 16025 serializer.endTag(null, TAG_GRANT); 16026 } 16027 } 16028 16029 serializer.endTag(null, TAG_ALL_GRANTS); 16030 } 16031 16032 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16033 throws XmlPullParserException, IOException { 16034 String pkgName = null; 16035 int outerDepth = parser.getDepth(); 16036 int type; 16037 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16038 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16039 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16040 continue; 16041 } 16042 16043 final String tagName = parser.getName(); 16044 if (tagName.equals(TAG_GRANT)) { 16045 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16046 if (DEBUG_BACKUP) { 16047 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16048 } 16049 } else if (tagName.equals(TAG_PERMISSION)) { 16050 16051 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16052 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16053 16054 int newFlagSet = 0; 16055 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16056 newFlagSet |= FLAG_PERMISSION_USER_SET; 16057 } 16058 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16059 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16060 } 16061 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16062 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16063 } 16064 if (DEBUG_BACKUP) { 16065 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16066 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16067 } 16068 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16069 if (ps != null) { 16070 // Already installed so we apply the grant immediately 16071 if (DEBUG_BACKUP) { 16072 Slog.v(TAG, " + already installed; applying"); 16073 } 16074 PermissionsState perms = ps.getPermissionsState(); 16075 BasePermission bp = mSettings.mPermissions.get(permName); 16076 if (bp != null) { 16077 if (isGranted) { 16078 perms.grantRuntimePermission(bp, userId); 16079 } 16080 if (newFlagSet != 0) { 16081 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16082 } 16083 } 16084 } else { 16085 // Need to wait for post-restore install to apply the grant 16086 if (DEBUG_BACKUP) { 16087 Slog.v(TAG, " - not yet installed; saving for later"); 16088 } 16089 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16090 isGranted, newFlagSet, userId); 16091 } 16092 } else { 16093 PackageManagerService.reportSettingsProblem(Log.WARN, 16094 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16095 XmlUtils.skipCurrentTag(parser); 16096 } 16097 } 16098 16099 scheduleWriteSettingsLocked(); 16100 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16101 } 16102 16103 @Override 16104 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16105 int sourceUserId, int targetUserId, int flags) { 16106 mContext.enforceCallingOrSelfPermission( 16107 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16108 int callingUid = Binder.getCallingUid(); 16109 enforceOwnerRights(ownerPackage, callingUid); 16110 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16111 if (intentFilter.countActions() == 0) { 16112 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16113 return; 16114 } 16115 synchronized (mPackages) { 16116 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16117 ownerPackage, targetUserId, flags); 16118 CrossProfileIntentResolver resolver = 16119 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16120 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16121 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16122 if (existing != null) { 16123 int size = existing.size(); 16124 for (int i = 0; i < size; i++) { 16125 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16126 return; 16127 } 16128 } 16129 } 16130 resolver.addFilter(newFilter); 16131 scheduleWritePackageRestrictionsLocked(sourceUserId); 16132 } 16133 } 16134 16135 @Override 16136 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16137 mContext.enforceCallingOrSelfPermission( 16138 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16139 int callingUid = Binder.getCallingUid(); 16140 enforceOwnerRights(ownerPackage, callingUid); 16141 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16142 synchronized (mPackages) { 16143 CrossProfileIntentResolver resolver = 16144 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16145 ArraySet<CrossProfileIntentFilter> set = 16146 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16147 for (CrossProfileIntentFilter filter : set) { 16148 if (filter.getOwnerPackage().equals(ownerPackage)) { 16149 resolver.removeFilter(filter); 16150 } 16151 } 16152 scheduleWritePackageRestrictionsLocked(sourceUserId); 16153 } 16154 } 16155 16156 // Enforcing that callingUid is owning pkg on userId 16157 private void enforceOwnerRights(String pkg, int callingUid) { 16158 // The system owns everything. 16159 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16160 return; 16161 } 16162 int callingUserId = UserHandle.getUserId(callingUid); 16163 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16164 if (pi == null) { 16165 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16166 + callingUserId); 16167 } 16168 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16169 throw new SecurityException("Calling uid " + callingUid 16170 + " does not own package " + pkg); 16171 } 16172 } 16173 16174 @Override 16175 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16176 Intent intent = new Intent(Intent.ACTION_MAIN); 16177 intent.addCategory(Intent.CATEGORY_HOME); 16178 16179 final int callingUserId = UserHandle.getCallingUserId(); 16180 List<ResolveInfo> list = queryIntentActivities(intent, null, 16181 PackageManager.GET_META_DATA, callingUserId); 16182 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16183 true, false, false, callingUserId); 16184 16185 allHomeCandidates.clear(); 16186 if (list != null) { 16187 for (ResolveInfo ri : list) { 16188 allHomeCandidates.add(ri); 16189 } 16190 } 16191 return (preferred == null || preferred.activityInfo == null) 16192 ? null 16193 : new ComponentName(preferred.activityInfo.packageName, 16194 preferred.activityInfo.name); 16195 } 16196 16197 @Override 16198 public void setApplicationEnabledSetting(String appPackageName, 16199 int newState, int flags, int userId, String callingPackage) { 16200 if (!sUserManager.exists(userId)) return; 16201 if (callingPackage == null) { 16202 callingPackage = Integer.toString(Binder.getCallingUid()); 16203 } 16204 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16205 } 16206 16207 @Override 16208 public void setComponentEnabledSetting(ComponentName componentName, 16209 int newState, int flags, int userId) { 16210 if (!sUserManager.exists(userId)) return; 16211 setEnabledSetting(componentName.getPackageName(), 16212 componentName.getClassName(), newState, flags, userId, null); 16213 } 16214 16215 private void setEnabledSetting(final String packageName, String className, int newState, 16216 final int flags, int userId, String callingPackage) { 16217 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16218 || newState == COMPONENT_ENABLED_STATE_ENABLED 16219 || newState == COMPONENT_ENABLED_STATE_DISABLED 16220 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16221 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16222 throw new IllegalArgumentException("Invalid new component state: " 16223 + newState); 16224 } 16225 PackageSetting pkgSetting; 16226 final int uid = Binder.getCallingUid(); 16227 final int permission = mContext.checkCallingOrSelfPermission( 16228 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16229 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 16230 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16231 boolean sendNow = false; 16232 boolean isApp = (className == null); 16233 String componentName = isApp ? packageName : className; 16234 int packageUid = -1; 16235 ArrayList<String> components; 16236 16237 // writer 16238 synchronized (mPackages) { 16239 pkgSetting = mSettings.mPackages.get(packageName); 16240 if (pkgSetting == null) { 16241 if (className == null) { 16242 throw new IllegalArgumentException("Unknown package: " + packageName); 16243 } 16244 throw new IllegalArgumentException( 16245 "Unknown component: " + packageName + "/" + className); 16246 } 16247 // Allow root and verify that userId is not being specified by a different user 16248 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16249 throw new SecurityException( 16250 "Permission Denial: attempt to change component state from pid=" 16251 + Binder.getCallingPid() 16252 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16253 } 16254 if (className == null) { 16255 // We're dealing with an application/package level state change 16256 if (pkgSetting.getEnabled(userId) == newState) { 16257 // Nothing to do 16258 return; 16259 } 16260 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16261 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16262 // Don't care about who enables an app. 16263 callingPackage = null; 16264 } 16265 pkgSetting.setEnabled(newState, userId, callingPackage); 16266 // pkgSetting.pkg.mSetEnabled = newState; 16267 } else { 16268 // We're dealing with a component level state change 16269 // First, verify that this is a valid class name. 16270 PackageParser.Package pkg = pkgSetting.pkg; 16271 if (pkg == null || !pkg.hasComponentClassName(className)) { 16272 if (pkg != null && 16273 pkg.applicationInfo.targetSdkVersion >= 16274 Build.VERSION_CODES.JELLY_BEAN) { 16275 throw new IllegalArgumentException("Component class " + className 16276 + " does not exist in " + packageName); 16277 } else { 16278 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16279 + className + " does not exist in " + packageName); 16280 } 16281 } 16282 switch (newState) { 16283 case COMPONENT_ENABLED_STATE_ENABLED: 16284 if (!pkgSetting.enableComponentLPw(className, userId)) { 16285 return; 16286 } 16287 break; 16288 case COMPONENT_ENABLED_STATE_DISABLED: 16289 if (!pkgSetting.disableComponentLPw(className, userId)) { 16290 return; 16291 } 16292 break; 16293 case COMPONENT_ENABLED_STATE_DEFAULT: 16294 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16295 return; 16296 } 16297 break; 16298 default: 16299 Slog.e(TAG, "Invalid new component state: " + newState); 16300 return; 16301 } 16302 } 16303 scheduleWritePackageRestrictionsLocked(userId); 16304 components = mPendingBroadcasts.get(userId, packageName); 16305 final boolean newPackage = components == null; 16306 if (newPackage) { 16307 components = new ArrayList<String>(); 16308 } 16309 if (!components.contains(componentName)) { 16310 components.add(componentName); 16311 } 16312 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16313 sendNow = true; 16314 // Purge entry from pending broadcast list if another one exists already 16315 // since we are sending one right away. 16316 mPendingBroadcasts.remove(userId, packageName); 16317 } else { 16318 if (newPackage) { 16319 mPendingBroadcasts.put(userId, packageName, components); 16320 } 16321 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16322 // Schedule a message 16323 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16324 } 16325 } 16326 } 16327 16328 long callingId = Binder.clearCallingIdentity(); 16329 try { 16330 if (sendNow) { 16331 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16332 sendPackageChangedBroadcast(packageName, 16333 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16334 } 16335 } finally { 16336 Binder.restoreCallingIdentity(callingId); 16337 } 16338 } 16339 16340 private void sendPackageChangedBroadcast(String packageName, 16341 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16342 if (DEBUG_INSTALL) 16343 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16344 + componentNames); 16345 Bundle extras = new Bundle(4); 16346 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16347 String nameList[] = new String[componentNames.size()]; 16348 componentNames.toArray(nameList); 16349 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16350 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16351 extras.putInt(Intent.EXTRA_UID, packageUid); 16352 // If this is not reporting a change of the overall package, then only send it 16353 // to registered receivers. We don't want to launch a swath of apps for every 16354 // little component state change. 16355 final int flags = !componentNames.contains(packageName) 16356 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16357 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16358 new int[] {UserHandle.getUserId(packageUid)}); 16359 } 16360 16361 @Override 16362 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16363 if (!sUserManager.exists(userId)) return; 16364 final int uid = Binder.getCallingUid(); 16365 final int permission = mContext.checkCallingOrSelfPermission( 16366 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16367 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16368 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 16369 // writer 16370 synchronized (mPackages) { 16371 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16372 allowedByPermission, uid, userId)) { 16373 scheduleWritePackageRestrictionsLocked(userId); 16374 } 16375 } 16376 } 16377 16378 @Override 16379 public String getInstallerPackageName(String packageName) { 16380 // reader 16381 synchronized (mPackages) { 16382 return mSettings.getInstallerPackageNameLPr(packageName); 16383 } 16384 } 16385 16386 @Override 16387 public int getApplicationEnabledSetting(String packageName, int userId) { 16388 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16389 int uid = Binder.getCallingUid(); 16390 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 16391 // reader 16392 synchronized (mPackages) { 16393 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16394 } 16395 } 16396 16397 @Override 16398 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16399 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16400 int uid = Binder.getCallingUid(); 16401 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 16402 // reader 16403 synchronized (mPackages) { 16404 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16405 } 16406 } 16407 16408 @Override 16409 public void enterSafeMode() { 16410 enforceSystemOrRoot("Only the system can request entering safe mode"); 16411 16412 if (!mSystemReady) { 16413 mSafeMode = true; 16414 } 16415 } 16416 16417 @Override 16418 public void systemReady() { 16419 mSystemReady = true; 16420 16421 // Read the compatibilty setting when the system is ready. 16422 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16423 mContext.getContentResolver(), 16424 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16425 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16426 if (DEBUG_SETTINGS) { 16427 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16428 } 16429 16430 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16431 16432 synchronized (mPackages) { 16433 // Verify that all of the preferred activity components actually 16434 // exist. It is possible for applications to be updated and at 16435 // that point remove a previously declared activity component that 16436 // had been set as a preferred activity. We try to clean this up 16437 // the next time we encounter that preferred activity, but it is 16438 // possible for the user flow to never be able to return to that 16439 // situation so here we do a sanity check to make sure we haven't 16440 // left any junk around. 16441 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16442 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16443 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16444 removed.clear(); 16445 for (PreferredActivity pa : pir.filterSet()) { 16446 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16447 removed.add(pa); 16448 } 16449 } 16450 if (removed.size() > 0) { 16451 for (int r=0; r<removed.size(); r++) { 16452 PreferredActivity pa = removed.get(r); 16453 Slog.w(TAG, "Removing dangling preferred activity: " 16454 + pa.mPref.mComponent); 16455 pir.removeFilter(pa); 16456 } 16457 mSettings.writePackageRestrictionsLPr( 16458 mSettings.mPreferredActivities.keyAt(i)); 16459 } 16460 } 16461 16462 for (int userId : UserManagerService.getInstance().getUserIds()) { 16463 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16464 grantPermissionsUserIds = ArrayUtils.appendInt( 16465 grantPermissionsUserIds, userId); 16466 } 16467 } 16468 } 16469 sUserManager.systemReady(); 16470 16471 // If we upgraded grant all default permissions before kicking off. 16472 for (int userId : grantPermissionsUserIds) { 16473 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16474 } 16475 16476 // Kick off any messages waiting for system ready 16477 if (mPostSystemReadyMessages != null) { 16478 for (Message msg : mPostSystemReadyMessages) { 16479 msg.sendToTarget(); 16480 } 16481 mPostSystemReadyMessages = null; 16482 } 16483 16484 // Watch for external volumes that come and go over time 16485 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16486 storage.registerListener(mStorageListener); 16487 16488 mInstallerService.systemReady(); 16489 mPackageDexOptimizer.systemReady(); 16490 16491 MountServiceInternal mountServiceInternal = LocalServices.getService( 16492 MountServiceInternal.class); 16493 mountServiceInternal.addExternalStoragePolicy( 16494 new MountServiceInternal.ExternalStorageMountPolicy() { 16495 @Override 16496 public int getMountMode(int uid, String packageName) { 16497 if (Process.isIsolated(uid)) { 16498 return Zygote.MOUNT_EXTERNAL_NONE; 16499 } 16500 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16501 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16502 } 16503 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16504 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16505 } 16506 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16507 return Zygote.MOUNT_EXTERNAL_READ; 16508 } 16509 return Zygote.MOUNT_EXTERNAL_WRITE; 16510 } 16511 16512 @Override 16513 public boolean hasExternalStorage(int uid, String packageName) { 16514 return true; 16515 } 16516 }); 16517 } 16518 16519 @Override 16520 public boolean isSafeMode() { 16521 return mSafeMode; 16522 } 16523 16524 @Override 16525 public boolean hasSystemUidErrors() { 16526 return mHasSystemUidErrors; 16527 } 16528 16529 static String arrayToString(int[] array) { 16530 StringBuffer buf = new StringBuffer(128); 16531 buf.append('['); 16532 if (array != null) { 16533 for (int i=0; i<array.length; i++) { 16534 if (i > 0) buf.append(", "); 16535 buf.append(array[i]); 16536 } 16537 } 16538 buf.append(']'); 16539 return buf.toString(); 16540 } 16541 16542 static class DumpState { 16543 public static final int DUMP_LIBS = 1 << 0; 16544 public static final int DUMP_FEATURES = 1 << 1; 16545 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16546 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16547 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16548 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16549 public static final int DUMP_PERMISSIONS = 1 << 6; 16550 public static final int DUMP_PACKAGES = 1 << 7; 16551 public static final int DUMP_SHARED_USERS = 1 << 8; 16552 public static final int DUMP_MESSAGES = 1 << 9; 16553 public static final int DUMP_PROVIDERS = 1 << 10; 16554 public static final int DUMP_VERIFIERS = 1 << 11; 16555 public static final int DUMP_PREFERRED = 1 << 12; 16556 public static final int DUMP_PREFERRED_XML = 1 << 13; 16557 public static final int DUMP_KEYSETS = 1 << 14; 16558 public static final int DUMP_VERSION = 1 << 15; 16559 public static final int DUMP_INSTALLS = 1 << 16; 16560 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16561 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16562 16563 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16564 16565 private int mTypes; 16566 16567 private int mOptions; 16568 16569 private boolean mTitlePrinted; 16570 16571 private SharedUserSetting mSharedUser; 16572 16573 public boolean isDumping(int type) { 16574 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16575 return true; 16576 } 16577 16578 return (mTypes & type) != 0; 16579 } 16580 16581 public void setDump(int type) { 16582 mTypes |= type; 16583 } 16584 16585 public boolean isOptionEnabled(int option) { 16586 return (mOptions & option) != 0; 16587 } 16588 16589 public void setOptionEnabled(int option) { 16590 mOptions |= option; 16591 } 16592 16593 public boolean onTitlePrinted() { 16594 final boolean printed = mTitlePrinted; 16595 mTitlePrinted = true; 16596 return printed; 16597 } 16598 16599 public boolean getTitlePrinted() { 16600 return mTitlePrinted; 16601 } 16602 16603 public void setTitlePrinted(boolean enabled) { 16604 mTitlePrinted = enabled; 16605 } 16606 16607 public SharedUserSetting getSharedUser() { 16608 return mSharedUser; 16609 } 16610 16611 public void setSharedUser(SharedUserSetting user) { 16612 mSharedUser = user; 16613 } 16614 } 16615 16616 @Override 16617 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16618 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16619 (new PackageManagerShellCommand(this)).exec( 16620 this, in, out, err, args, resultReceiver); 16621 } 16622 16623 @Override 16624 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16625 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16626 != PackageManager.PERMISSION_GRANTED) { 16627 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16628 + Binder.getCallingPid() 16629 + ", uid=" + Binder.getCallingUid() 16630 + " without permission " 16631 + android.Manifest.permission.DUMP); 16632 return; 16633 } 16634 16635 DumpState dumpState = new DumpState(); 16636 boolean fullPreferred = false; 16637 boolean checkin = false; 16638 16639 String packageName = null; 16640 ArraySet<String> permissionNames = null; 16641 16642 int opti = 0; 16643 while (opti < args.length) { 16644 String opt = args[opti]; 16645 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16646 break; 16647 } 16648 opti++; 16649 16650 if ("-a".equals(opt)) { 16651 // Right now we only know how to print all. 16652 } else if ("-h".equals(opt)) { 16653 pw.println("Package manager dump options:"); 16654 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16655 pw.println(" --checkin: dump for a checkin"); 16656 pw.println(" -f: print details of intent filters"); 16657 pw.println(" -h: print this help"); 16658 pw.println(" cmd may be one of:"); 16659 pw.println(" l[ibraries]: list known shared libraries"); 16660 pw.println(" f[eatures]: list device features"); 16661 pw.println(" k[eysets]: print known keysets"); 16662 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16663 pw.println(" perm[issions]: dump permissions"); 16664 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16665 pw.println(" pref[erred]: print preferred package settings"); 16666 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16667 pw.println(" prov[iders]: dump content providers"); 16668 pw.println(" p[ackages]: dump installed packages"); 16669 pw.println(" s[hared-users]: dump shared user IDs"); 16670 pw.println(" m[essages]: print collected runtime messages"); 16671 pw.println(" v[erifiers]: print package verifier info"); 16672 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16673 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16674 pw.println(" version: print database version info"); 16675 pw.println(" write: write current settings now"); 16676 pw.println(" installs: details about install sessions"); 16677 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16678 pw.println(" <package.name>: info about given package"); 16679 return; 16680 } else if ("--checkin".equals(opt)) { 16681 checkin = true; 16682 } else if ("-f".equals(opt)) { 16683 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16684 } else { 16685 pw.println("Unknown argument: " + opt + "; use -h for help"); 16686 } 16687 } 16688 16689 // Is the caller requesting to dump a particular piece of data? 16690 if (opti < args.length) { 16691 String cmd = args[opti]; 16692 opti++; 16693 // Is this a package name? 16694 if ("android".equals(cmd) || cmd.contains(".")) { 16695 packageName = cmd; 16696 // When dumping a single package, we always dump all of its 16697 // filter information since the amount of data will be reasonable. 16698 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16699 } else if ("check-permission".equals(cmd)) { 16700 if (opti >= args.length) { 16701 pw.println("Error: check-permission missing permission argument"); 16702 return; 16703 } 16704 String perm = args[opti]; 16705 opti++; 16706 if (opti >= args.length) { 16707 pw.println("Error: check-permission missing package argument"); 16708 return; 16709 } 16710 String pkg = args[opti]; 16711 opti++; 16712 int user = UserHandle.getUserId(Binder.getCallingUid()); 16713 if (opti < args.length) { 16714 try { 16715 user = Integer.parseInt(args[opti]); 16716 } catch (NumberFormatException e) { 16717 pw.println("Error: check-permission user argument is not a number: " 16718 + args[opti]); 16719 return; 16720 } 16721 } 16722 pw.println(checkPermission(perm, pkg, user)); 16723 return; 16724 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16725 dumpState.setDump(DumpState.DUMP_LIBS); 16726 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16727 dumpState.setDump(DumpState.DUMP_FEATURES); 16728 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16729 if (opti >= args.length) { 16730 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16731 | DumpState.DUMP_SERVICE_RESOLVERS 16732 | DumpState.DUMP_RECEIVER_RESOLVERS 16733 | DumpState.DUMP_CONTENT_RESOLVERS); 16734 } else { 16735 while (opti < args.length) { 16736 String name = args[opti]; 16737 if ("a".equals(name) || "activity".equals(name)) { 16738 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16739 } else if ("s".equals(name) || "service".equals(name)) { 16740 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16741 } else if ("r".equals(name) || "receiver".equals(name)) { 16742 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16743 } else if ("c".equals(name) || "content".equals(name)) { 16744 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16745 } else { 16746 pw.println("Error: unknown resolver table type: " + name); 16747 return; 16748 } 16749 opti++; 16750 } 16751 } 16752 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16753 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16754 } else if ("permission".equals(cmd)) { 16755 if (opti >= args.length) { 16756 pw.println("Error: permission requires permission name"); 16757 return; 16758 } 16759 permissionNames = new ArraySet<>(); 16760 while (opti < args.length) { 16761 permissionNames.add(args[opti]); 16762 opti++; 16763 } 16764 dumpState.setDump(DumpState.DUMP_PERMISSIONS 16765 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 16766 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 16767 dumpState.setDump(DumpState.DUMP_PREFERRED); 16768 } else if ("preferred-xml".equals(cmd)) { 16769 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 16770 if (opti < args.length && "--full".equals(args[opti])) { 16771 fullPreferred = true; 16772 opti++; 16773 } 16774 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 16775 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 16776 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 16777 dumpState.setDump(DumpState.DUMP_PACKAGES); 16778 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 16779 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 16780 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 16781 dumpState.setDump(DumpState.DUMP_PROVIDERS); 16782 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 16783 dumpState.setDump(DumpState.DUMP_MESSAGES); 16784 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 16785 dumpState.setDump(DumpState.DUMP_VERIFIERS); 16786 } else if ("i".equals(cmd) || "ifv".equals(cmd) 16787 || "intent-filter-verifiers".equals(cmd)) { 16788 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 16789 } else if ("version".equals(cmd)) { 16790 dumpState.setDump(DumpState.DUMP_VERSION); 16791 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 16792 dumpState.setDump(DumpState.DUMP_KEYSETS); 16793 } else if ("installs".equals(cmd)) { 16794 dumpState.setDump(DumpState.DUMP_INSTALLS); 16795 } else if ("write".equals(cmd)) { 16796 synchronized (mPackages) { 16797 mSettings.writeLPr(); 16798 pw.println("Settings written."); 16799 return; 16800 } 16801 } 16802 } 16803 16804 if (checkin) { 16805 pw.println("vers,1"); 16806 } 16807 16808 // reader 16809 synchronized (mPackages) { 16810 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16811 if (!checkin) { 16812 if (dumpState.onTitlePrinted()) 16813 pw.println(); 16814 pw.println("Database versions:"); 16815 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16816 } 16817 } 16818 16819 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16820 if (!checkin) { 16821 if (dumpState.onTitlePrinted()) 16822 pw.println(); 16823 pw.println("Verifiers:"); 16824 pw.print(" Required: "); 16825 pw.print(mRequiredVerifierPackage); 16826 pw.print(" (uid="); 16827 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16828 UserHandle.USER_SYSTEM)); 16829 pw.println(")"); 16830 } else if (mRequiredVerifierPackage != null) { 16831 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 16832 pw.print(","); 16833 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16834 UserHandle.USER_SYSTEM)); 16835 } 16836 } 16837 16838 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 16839 packageName == null) { 16840 if (mIntentFilterVerifierComponent != null) { 16841 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 16842 if (!checkin) { 16843 if (dumpState.onTitlePrinted()) 16844 pw.println(); 16845 pw.println("Intent Filter Verifier:"); 16846 pw.print(" Using: "); 16847 pw.print(verifierPackageName); 16848 pw.print(" (uid="); 16849 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16850 UserHandle.USER_SYSTEM)); 16851 pw.println(")"); 16852 } else if (verifierPackageName != null) { 16853 pw.print("ifv,"); pw.print(verifierPackageName); 16854 pw.print(","); 16855 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16856 UserHandle.USER_SYSTEM)); 16857 } 16858 } else { 16859 pw.println(); 16860 pw.println("No Intent Filter Verifier available!"); 16861 } 16862 } 16863 16864 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 16865 boolean printedHeader = false; 16866 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 16867 while (it.hasNext()) { 16868 String name = it.next(); 16869 SharedLibraryEntry ent = mSharedLibraries.get(name); 16870 if (!checkin) { 16871 if (!printedHeader) { 16872 if (dumpState.onTitlePrinted()) 16873 pw.println(); 16874 pw.println("Libraries:"); 16875 printedHeader = true; 16876 } 16877 pw.print(" "); 16878 } else { 16879 pw.print("lib,"); 16880 } 16881 pw.print(name); 16882 if (!checkin) { 16883 pw.print(" -> "); 16884 } 16885 if (ent.path != null) { 16886 if (!checkin) { 16887 pw.print("(jar) "); 16888 pw.print(ent.path); 16889 } else { 16890 pw.print(",jar,"); 16891 pw.print(ent.path); 16892 } 16893 } else { 16894 if (!checkin) { 16895 pw.print("(apk) "); 16896 pw.print(ent.apk); 16897 } else { 16898 pw.print(",apk,"); 16899 pw.print(ent.apk); 16900 } 16901 } 16902 pw.println(); 16903 } 16904 } 16905 16906 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 16907 if (dumpState.onTitlePrinted()) 16908 pw.println(); 16909 if (!checkin) { 16910 pw.println("Features:"); 16911 } 16912 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 16913 while (it.hasNext()) { 16914 String name = it.next(); 16915 if (!checkin) { 16916 pw.print(" "); 16917 } else { 16918 pw.print("feat,"); 16919 } 16920 pw.println(name); 16921 } 16922 } 16923 16924 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16925 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16926 : "Activity Resolver Table:", " ", packageName, 16927 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16928 dumpState.setTitlePrinted(true); 16929 } 16930 } 16931 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16932 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16933 : "Receiver Resolver Table:", " ", packageName, 16934 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16935 dumpState.setTitlePrinted(true); 16936 } 16937 } 16938 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16939 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16940 : "Service Resolver Table:", " ", packageName, 16941 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16942 dumpState.setTitlePrinted(true); 16943 } 16944 } 16945 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16946 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16947 : "Provider Resolver Table:", " ", packageName, 16948 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16949 dumpState.setTitlePrinted(true); 16950 } 16951 } 16952 16953 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16954 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16955 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16956 int user = mSettings.mPreferredActivities.keyAt(i); 16957 if (pir.dump(pw, 16958 dumpState.getTitlePrinted() 16959 ? "\nPreferred Activities User " + user + ":" 16960 : "Preferred Activities User " + user + ":", " ", 16961 packageName, true, false)) { 16962 dumpState.setTitlePrinted(true); 16963 } 16964 } 16965 } 16966 16967 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16968 pw.flush(); 16969 FileOutputStream fout = new FileOutputStream(fd); 16970 BufferedOutputStream str = new BufferedOutputStream(fout); 16971 XmlSerializer serializer = new FastXmlSerializer(); 16972 try { 16973 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16974 serializer.startDocument(null, true); 16975 serializer.setFeature( 16976 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16977 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16978 serializer.endDocument(); 16979 serializer.flush(); 16980 } catch (IllegalArgumentException e) { 16981 pw.println("Failed writing: " + e); 16982 } catch (IllegalStateException e) { 16983 pw.println("Failed writing: " + e); 16984 } catch (IOException e) { 16985 pw.println("Failed writing: " + e); 16986 } 16987 } 16988 16989 if (!checkin 16990 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16991 && packageName == null) { 16992 pw.println(); 16993 int count = mSettings.mPackages.size(); 16994 if (count == 0) { 16995 pw.println("No applications!"); 16996 pw.println(); 16997 } else { 16998 final String prefix = " "; 16999 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17000 if (allPackageSettings.size() == 0) { 17001 pw.println("No domain preferred apps!"); 17002 pw.println(); 17003 } else { 17004 pw.println("App verification status:"); 17005 pw.println(); 17006 count = 0; 17007 for (PackageSetting ps : allPackageSettings) { 17008 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17009 if (ivi == null || ivi.getPackageName() == null) continue; 17010 pw.println(prefix + "Package: " + ivi.getPackageName()); 17011 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17012 pw.println(prefix + "Status: " + ivi.getStatusString()); 17013 pw.println(); 17014 count++; 17015 } 17016 if (count == 0) { 17017 pw.println(prefix + "No app verification established."); 17018 pw.println(); 17019 } 17020 for (int userId : sUserManager.getUserIds()) { 17021 pw.println("App linkages for user " + userId + ":"); 17022 pw.println(); 17023 count = 0; 17024 for (PackageSetting ps : allPackageSettings) { 17025 final long status = ps.getDomainVerificationStatusForUser(userId); 17026 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17027 continue; 17028 } 17029 pw.println(prefix + "Package: " + ps.name); 17030 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17031 String statusStr = IntentFilterVerificationInfo. 17032 getStatusStringFromValue(status); 17033 pw.println(prefix + "Status: " + statusStr); 17034 pw.println(); 17035 count++; 17036 } 17037 if (count == 0) { 17038 pw.println(prefix + "No configured app linkages."); 17039 pw.println(); 17040 } 17041 } 17042 } 17043 } 17044 } 17045 17046 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17047 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17048 if (packageName == null && permissionNames == null) { 17049 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17050 if (iperm == 0) { 17051 if (dumpState.onTitlePrinted()) 17052 pw.println(); 17053 pw.println("AppOp Permissions:"); 17054 } 17055 pw.print(" AppOp Permission "); 17056 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17057 pw.println(":"); 17058 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17059 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17060 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17061 } 17062 } 17063 } 17064 } 17065 17066 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17067 boolean printedSomething = false; 17068 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17069 if (packageName != null && !packageName.equals(p.info.packageName)) { 17070 continue; 17071 } 17072 if (!printedSomething) { 17073 if (dumpState.onTitlePrinted()) 17074 pw.println(); 17075 pw.println("Registered ContentProviders:"); 17076 printedSomething = true; 17077 } 17078 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17079 pw.print(" "); pw.println(p.toString()); 17080 } 17081 printedSomething = false; 17082 for (Map.Entry<String, PackageParser.Provider> entry : 17083 mProvidersByAuthority.entrySet()) { 17084 PackageParser.Provider p = entry.getValue(); 17085 if (packageName != null && !packageName.equals(p.info.packageName)) { 17086 continue; 17087 } 17088 if (!printedSomething) { 17089 if (dumpState.onTitlePrinted()) 17090 pw.println(); 17091 pw.println("ContentProvider Authorities:"); 17092 printedSomething = true; 17093 } 17094 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17095 pw.print(" "); pw.println(p.toString()); 17096 if (p.info != null && p.info.applicationInfo != null) { 17097 final String appInfo = p.info.applicationInfo.toString(); 17098 pw.print(" applicationInfo="); pw.println(appInfo); 17099 } 17100 } 17101 } 17102 17103 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17104 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17105 } 17106 17107 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17108 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17109 } 17110 17111 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17112 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17113 } 17114 17115 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17116 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17117 } 17118 17119 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17120 // XXX should handle packageName != null by dumping only install data that 17121 // the given package is involved with. 17122 if (dumpState.onTitlePrinted()) pw.println(); 17123 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17124 } 17125 17126 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17127 if (dumpState.onTitlePrinted()) pw.println(); 17128 mSettings.dumpReadMessagesLPr(pw, dumpState); 17129 17130 pw.println(); 17131 pw.println("Package warning messages:"); 17132 BufferedReader in = null; 17133 String line = null; 17134 try { 17135 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17136 while ((line = in.readLine()) != null) { 17137 if (line.contains("ignored: updated version")) continue; 17138 pw.println(line); 17139 } 17140 } catch (IOException ignored) { 17141 } finally { 17142 IoUtils.closeQuietly(in); 17143 } 17144 } 17145 17146 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17147 BufferedReader in = null; 17148 String line = null; 17149 try { 17150 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17151 while ((line = in.readLine()) != null) { 17152 if (line.contains("ignored: updated version")) continue; 17153 pw.print("msg,"); 17154 pw.println(line); 17155 } 17156 } catch (IOException ignored) { 17157 } finally { 17158 IoUtils.closeQuietly(in); 17159 } 17160 } 17161 } 17162 } 17163 17164 private String dumpDomainString(String packageName) { 17165 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 17166 List<IntentFilter> filters = getAllIntentFilters(packageName); 17167 17168 ArraySet<String> result = new ArraySet<>(); 17169 if (iviList.size() > 0) { 17170 for (IntentFilterVerificationInfo ivi : iviList) { 17171 for (String host : ivi.getDomains()) { 17172 result.add(host); 17173 } 17174 } 17175 } 17176 if (filters != null && filters.size() > 0) { 17177 for (IntentFilter filter : filters) { 17178 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17179 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17180 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17181 result.addAll(filter.getHostsList()); 17182 } 17183 } 17184 } 17185 17186 StringBuilder sb = new StringBuilder(result.size() * 16); 17187 for (String domain : result) { 17188 if (sb.length() > 0) sb.append(" "); 17189 sb.append(domain); 17190 } 17191 return sb.toString(); 17192 } 17193 17194 // ------- apps on sdcard specific code ------- 17195 static final boolean DEBUG_SD_INSTALL = false; 17196 17197 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17198 17199 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17200 17201 private boolean mMediaMounted = false; 17202 17203 static String getEncryptKey() { 17204 try { 17205 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17206 SD_ENCRYPTION_KEYSTORE_NAME); 17207 if (sdEncKey == null) { 17208 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17209 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17210 if (sdEncKey == null) { 17211 Slog.e(TAG, "Failed to create encryption keys"); 17212 return null; 17213 } 17214 } 17215 return sdEncKey; 17216 } catch (NoSuchAlgorithmException nsae) { 17217 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17218 return null; 17219 } catch (IOException ioe) { 17220 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17221 return null; 17222 } 17223 } 17224 17225 /* 17226 * Update media status on PackageManager. 17227 */ 17228 @Override 17229 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17230 int callingUid = Binder.getCallingUid(); 17231 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17232 throw new SecurityException("Media status can only be updated by the system"); 17233 } 17234 // reader; this apparently protects mMediaMounted, but should probably 17235 // be a different lock in that case. 17236 synchronized (mPackages) { 17237 Log.i(TAG, "Updating external media status from " 17238 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17239 + (mediaStatus ? "mounted" : "unmounted")); 17240 if (DEBUG_SD_INSTALL) 17241 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17242 + ", mMediaMounted=" + mMediaMounted); 17243 if (mediaStatus == mMediaMounted) { 17244 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17245 : 0, -1); 17246 mHandler.sendMessage(msg); 17247 return; 17248 } 17249 mMediaMounted = mediaStatus; 17250 } 17251 // Queue up an async operation since the package installation may take a 17252 // little while. 17253 mHandler.post(new Runnable() { 17254 public void run() { 17255 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17256 } 17257 }); 17258 } 17259 17260 /** 17261 * Called by MountService when the initial ASECs to scan are available. 17262 * Should block until all the ASEC containers are finished being scanned. 17263 */ 17264 public void scanAvailableAsecs() { 17265 updateExternalMediaStatusInner(true, false, false); 17266 } 17267 17268 /* 17269 * Collect information of applications on external media, map them against 17270 * existing containers and update information based on current mount status. 17271 * Please note that we always have to report status if reportStatus has been 17272 * set to true especially when unloading packages. 17273 */ 17274 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17275 boolean externalStorage) { 17276 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17277 int[] uidArr = EmptyArray.INT; 17278 17279 final String[] list = PackageHelper.getSecureContainerList(); 17280 if (ArrayUtils.isEmpty(list)) { 17281 Log.i(TAG, "No secure containers found"); 17282 } else { 17283 // Process list of secure containers and categorize them 17284 // as active or stale based on their package internal state. 17285 17286 // reader 17287 synchronized (mPackages) { 17288 for (String cid : list) { 17289 // Leave stages untouched for now; installer service owns them 17290 if (PackageInstallerService.isStageName(cid)) continue; 17291 17292 if (DEBUG_SD_INSTALL) 17293 Log.i(TAG, "Processing container " + cid); 17294 String pkgName = getAsecPackageName(cid); 17295 if (pkgName == null) { 17296 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17297 continue; 17298 } 17299 if (DEBUG_SD_INSTALL) 17300 Log.i(TAG, "Looking for pkg : " + pkgName); 17301 17302 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17303 if (ps == null) { 17304 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17305 continue; 17306 } 17307 17308 /* 17309 * Skip packages that are not external if we're unmounting 17310 * external storage. 17311 */ 17312 if (externalStorage && !isMounted && !isExternal(ps)) { 17313 continue; 17314 } 17315 17316 final AsecInstallArgs args = new AsecInstallArgs(cid, 17317 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17318 // The package status is changed only if the code path 17319 // matches between settings and the container id. 17320 if (ps.codePathString != null 17321 && ps.codePathString.startsWith(args.getCodePath())) { 17322 if (DEBUG_SD_INSTALL) { 17323 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17324 + " at code path: " + ps.codePathString); 17325 } 17326 17327 // We do have a valid package installed on sdcard 17328 processCids.put(args, ps.codePathString); 17329 final int uid = ps.appId; 17330 if (uid != -1) { 17331 uidArr = ArrayUtils.appendInt(uidArr, uid); 17332 } 17333 } else { 17334 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17335 + ps.codePathString); 17336 } 17337 } 17338 } 17339 17340 Arrays.sort(uidArr); 17341 } 17342 17343 // Process packages with valid entries. 17344 if (isMounted) { 17345 if (DEBUG_SD_INSTALL) 17346 Log.i(TAG, "Loading packages"); 17347 loadMediaPackages(processCids, uidArr, externalStorage); 17348 startCleaningPackages(); 17349 mInstallerService.onSecureContainersAvailable(); 17350 } else { 17351 if (DEBUG_SD_INSTALL) 17352 Log.i(TAG, "Unloading packages"); 17353 unloadMediaPackages(processCids, uidArr, reportStatus); 17354 } 17355 } 17356 17357 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17358 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17359 final int size = infos.size(); 17360 final String[] packageNames = new String[size]; 17361 final int[] packageUids = new int[size]; 17362 for (int i = 0; i < size; i++) { 17363 final ApplicationInfo info = infos.get(i); 17364 packageNames[i] = info.packageName; 17365 packageUids[i] = info.uid; 17366 } 17367 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17368 finishedReceiver); 17369 } 17370 17371 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17372 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17373 sendResourcesChangedBroadcast(mediaStatus, replacing, 17374 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17375 } 17376 17377 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17378 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17379 int size = pkgList.length; 17380 if (size > 0) { 17381 // Send broadcasts here 17382 Bundle extras = new Bundle(); 17383 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17384 if (uidArr != null) { 17385 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17386 } 17387 if (replacing) { 17388 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17389 } 17390 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17391 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17392 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17393 } 17394 } 17395 17396 /* 17397 * Look at potentially valid container ids from processCids If package 17398 * information doesn't match the one on record or package scanning fails, 17399 * the cid is added to list of removeCids. We currently don't delete stale 17400 * containers. 17401 */ 17402 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17403 boolean externalStorage) { 17404 ArrayList<String> pkgList = new ArrayList<String>(); 17405 Set<AsecInstallArgs> keys = processCids.keySet(); 17406 17407 for (AsecInstallArgs args : keys) { 17408 String codePath = processCids.get(args); 17409 if (DEBUG_SD_INSTALL) 17410 Log.i(TAG, "Loading container : " + args.cid); 17411 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17412 try { 17413 // Make sure there are no container errors first. 17414 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17415 Slog.e(TAG, "Failed to mount cid : " + args.cid 17416 + " when installing from sdcard"); 17417 continue; 17418 } 17419 // Check code path here. 17420 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17421 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17422 + " does not match one in settings " + codePath); 17423 continue; 17424 } 17425 // Parse package 17426 int parseFlags = mDefParseFlags; 17427 if (args.isExternalAsec()) { 17428 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17429 } 17430 if (args.isFwdLocked()) { 17431 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17432 } 17433 17434 synchronized (mInstallLock) { 17435 PackageParser.Package pkg = null; 17436 try { 17437 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17438 } catch (PackageManagerException e) { 17439 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17440 } 17441 // Scan the package 17442 if (pkg != null) { 17443 /* 17444 * TODO why is the lock being held? doPostInstall is 17445 * called in other places without the lock. This needs 17446 * to be straightened out. 17447 */ 17448 // writer 17449 synchronized (mPackages) { 17450 retCode = PackageManager.INSTALL_SUCCEEDED; 17451 pkgList.add(pkg.packageName); 17452 // Post process args 17453 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17454 pkg.applicationInfo.uid); 17455 } 17456 } else { 17457 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17458 } 17459 } 17460 17461 } finally { 17462 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17463 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17464 } 17465 } 17466 } 17467 // writer 17468 synchronized (mPackages) { 17469 // If the platform SDK has changed since the last time we booted, 17470 // we need to re-grant app permission to catch any new ones that 17471 // appear. This is really a hack, and means that apps can in some 17472 // cases get permissions that the user didn't initially explicitly 17473 // allow... it would be nice to have some better way to handle 17474 // this situation. 17475 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17476 : mSettings.getInternalVersion(); 17477 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17478 : StorageManager.UUID_PRIVATE_INTERNAL; 17479 17480 int updateFlags = UPDATE_PERMISSIONS_ALL; 17481 if (ver.sdkVersion != mSdkVersion) { 17482 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17483 + mSdkVersion + "; regranting permissions for external"); 17484 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17485 } 17486 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17487 17488 // Yay, everything is now upgraded 17489 ver.forceCurrent(); 17490 17491 // can downgrade to reader 17492 // Persist settings 17493 mSettings.writeLPr(); 17494 } 17495 // Send a broadcast to let everyone know we are done processing 17496 if (pkgList.size() > 0) { 17497 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17498 } 17499 } 17500 17501 /* 17502 * Utility method to unload a list of specified containers 17503 */ 17504 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17505 // Just unmount all valid containers. 17506 for (AsecInstallArgs arg : cidArgs) { 17507 synchronized (mInstallLock) { 17508 arg.doPostDeleteLI(false); 17509 } 17510 } 17511 } 17512 17513 /* 17514 * Unload packages mounted on external media. This involves deleting package 17515 * data from internal structures, sending broadcasts about disabled packages, 17516 * gc'ing to free up references, unmounting all secure containers 17517 * corresponding to packages on external media, and posting a 17518 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17519 * that we always have to post this message if status has been requested no 17520 * matter what. 17521 */ 17522 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17523 final boolean reportStatus) { 17524 if (DEBUG_SD_INSTALL) 17525 Log.i(TAG, "unloading media packages"); 17526 ArrayList<String> pkgList = new ArrayList<String>(); 17527 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17528 final Set<AsecInstallArgs> keys = processCids.keySet(); 17529 for (AsecInstallArgs args : keys) { 17530 String pkgName = args.getPackageName(); 17531 if (DEBUG_SD_INSTALL) 17532 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17533 // Delete package internally 17534 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17535 synchronized (mInstallLock) { 17536 boolean res = deletePackageLI(pkgName, null, false, null, 17537 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17538 if (res) { 17539 pkgList.add(pkgName); 17540 } else { 17541 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17542 failedList.add(args); 17543 } 17544 } 17545 } 17546 17547 // reader 17548 synchronized (mPackages) { 17549 // We didn't update the settings after removing each package; 17550 // write them now for all packages. 17551 mSettings.writeLPr(); 17552 } 17553 17554 // We have to absolutely send UPDATED_MEDIA_STATUS only 17555 // after confirming that all the receivers processed the ordered 17556 // broadcast when packages get disabled, force a gc to clean things up. 17557 // and unload all the containers. 17558 if (pkgList.size() > 0) { 17559 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17560 new IIntentReceiver.Stub() { 17561 public void performReceive(Intent intent, int resultCode, String data, 17562 Bundle extras, boolean ordered, boolean sticky, 17563 int sendingUser) throws RemoteException { 17564 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17565 reportStatus ? 1 : 0, 1, keys); 17566 mHandler.sendMessage(msg); 17567 } 17568 }); 17569 } else { 17570 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17571 keys); 17572 mHandler.sendMessage(msg); 17573 } 17574 } 17575 17576 private void loadPrivatePackages(final VolumeInfo vol) { 17577 mHandler.post(new Runnable() { 17578 @Override 17579 public void run() { 17580 loadPrivatePackagesInner(vol); 17581 } 17582 }); 17583 } 17584 17585 private void loadPrivatePackagesInner(VolumeInfo vol) { 17586 final String volumeUuid = vol.fsUuid; 17587 if (TextUtils.isEmpty(volumeUuid)) { 17588 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17589 return; 17590 } 17591 17592 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17593 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17594 17595 final VersionInfo ver; 17596 final List<PackageSetting> packages; 17597 synchronized (mPackages) { 17598 ver = mSettings.findOrCreateVersion(volumeUuid); 17599 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17600 } 17601 17602 // TODO: introduce a new concept similar to "frozen" to prevent these 17603 // apps from being launched until after data has been fully reconciled 17604 for (PackageSetting ps : packages) { 17605 synchronized (mInstallLock) { 17606 final PackageParser.Package pkg; 17607 try { 17608 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17609 loaded.add(pkg.applicationInfo); 17610 17611 } catch (PackageManagerException e) { 17612 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17613 } 17614 17615 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17616 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17617 } 17618 } 17619 } 17620 17621 // Reconcile app data for all started/unlocked users 17622 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17623 final UserManager um = mContext.getSystemService(UserManager.class); 17624 for (UserInfo user : um.getUsers()) { 17625 final int flags; 17626 if (um.isUserUnlocked(user.id)) { 17627 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17628 } else if (um.isUserRunning(user.id)) { 17629 flags = StorageManager.FLAG_STORAGE_DE; 17630 } else { 17631 continue; 17632 } 17633 17634 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17635 reconcileAppsData(volumeUuid, user.id, flags); 17636 } 17637 17638 synchronized (mPackages) { 17639 int updateFlags = UPDATE_PERMISSIONS_ALL; 17640 if (ver.sdkVersion != mSdkVersion) { 17641 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17642 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17643 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17644 } 17645 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17646 17647 // Yay, everything is now upgraded 17648 ver.forceCurrent(); 17649 17650 mSettings.writeLPr(); 17651 } 17652 17653 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17654 sendResourcesChangedBroadcast(true, false, loaded, null); 17655 } 17656 17657 private void unloadPrivatePackages(final VolumeInfo vol) { 17658 mHandler.post(new Runnable() { 17659 @Override 17660 public void run() { 17661 unloadPrivatePackagesInner(vol); 17662 } 17663 }); 17664 } 17665 17666 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17667 final String volumeUuid = vol.fsUuid; 17668 if (TextUtils.isEmpty(volumeUuid)) { 17669 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17670 return; 17671 } 17672 17673 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17674 synchronized (mInstallLock) { 17675 synchronized (mPackages) { 17676 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17677 for (PackageSetting ps : packages) { 17678 if (ps.pkg == null) continue; 17679 17680 final ApplicationInfo info = ps.pkg.applicationInfo; 17681 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17682 if (deletePackageLI(ps.name, null, false, null, 17683 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17684 unloaded.add(info); 17685 } else { 17686 Slog.w(TAG, "Failed to unload " + ps.codePath); 17687 } 17688 } 17689 17690 mSettings.writeLPr(); 17691 } 17692 } 17693 17694 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17695 sendResourcesChangedBroadcast(false, false, unloaded, null); 17696 } 17697 17698 /** 17699 * Examine all users present on given mounted volume, and destroy data 17700 * belonging to users that are no longer valid, or whose user ID has been 17701 * recycled. 17702 */ 17703 private void reconcileUsers(String volumeUuid) { 17704 // TODO: also reconcile DE directories 17705 final File[] files = FileUtils 17706 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17707 for (File file : files) { 17708 if (!file.isDirectory()) continue; 17709 17710 final int userId; 17711 final UserInfo info; 17712 try { 17713 userId = Integer.parseInt(file.getName()); 17714 info = sUserManager.getUserInfo(userId); 17715 } catch (NumberFormatException e) { 17716 Slog.w(TAG, "Invalid user directory " + file); 17717 continue; 17718 } 17719 17720 boolean destroyUser = false; 17721 if (info == null) { 17722 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17723 + " because no matching user was found"); 17724 destroyUser = true; 17725 } else { 17726 try { 17727 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17728 } catch (IOException e) { 17729 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17730 + " because we failed to enforce serial number: " + e); 17731 destroyUser = true; 17732 } 17733 } 17734 17735 if (destroyUser) { 17736 synchronized (mInstallLock) { 17737 try { 17738 mInstaller.removeUserDataDirs(volumeUuid, userId); 17739 } catch (InstallerException e) { 17740 Slog.w(TAG, "Failed to clean up user dirs", e); 17741 } 17742 } 17743 } 17744 } 17745 } 17746 17747 private void assertPackageKnown(String volumeUuid, String packageName) 17748 throws PackageManagerException { 17749 synchronized (mPackages) { 17750 final PackageSetting ps = mSettings.mPackages.get(packageName); 17751 if (ps == null) { 17752 throw new PackageManagerException("Package " + packageName + " is unknown"); 17753 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17754 throw new PackageManagerException( 17755 "Package " + packageName + " found on unknown volume " + volumeUuid 17756 + "; expected volume " + ps.volumeUuid); 17757 } 17758 } 17759 } 17760 17761 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 17762 throws PackageManagerException { 17763 synchronized (mPackages) { 17764 final PackageSetting ps = mSettings.mPackages.get(packageName); 17765 if (ps == null) { 17766 throw new PackageManagerException("Package " + packageName + " is unknown"); 17767 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17768 throw new PackageManagerException( 17769 "Package " + packageName + " found on unknown volume " + volumeUuid 17770 + "; expected volume " + ps.volumeUuid); 17771 } else if (!ps.getInstalled(userId)) { 17772 throw new PackageManagerException( 17773 "Package " + packageName + " not installed for user " + userId); 17774 } 17775 } 17776 } 17777 17778 /** 17779 * Examine all apps present on given mounted volume, and destroy apps that 17780 * aren't expected, either due to uninstallation or reinstallation on 17781 * another volume. 17782 */ 17783 private void reconcileApps(String volumeUuid) { 17784 final File[] files = FileUtils 17785 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 17786 for (File file : files) { 17787 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 17788 && !PackageInstallerService.isStageName(file.getName()); 17789 if (!isPackage) { 17790 // Ignore entries which are not packages 17791 continue; 17792 } 17793 17794 try { 17795 final PackageLite pkg = PackageParser.parsePackageLite(file, 17796 PackageParser.PARSE_MUST_BE_APK); 17797 assertPackageKnown(volumeUuid, pkg.packageName); 17798 17799 } catch (PackageParserException | PackageManagerException e) { 17800 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17801 synchronized (mInstallLock) { 17802 removeCodePathLI(file); 17803 } 17804 } 17805 } 17806 } 17807 17808 /** 17809 * Reconcile all app data for the given user. 17810 * <p> 17811 * Verifies that directories exist and that ownership and labeling is 17812 * correct for all installed apps on all mounted volumes. 17813 */ 17814 void reconcileAppsData(int userId, int flags) { 17815 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17816 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17817 final String volumeUuid = vol.getFsUuid(); 17818 reconcileAppsData(volumeUuid, userId, flags); 17819 } 17820 } 17821 17822 /** 17823 * Reconcile all app data on given mounted volume. 17824 * <p> 17825 * Destroys app data that isn't expected, either due to uninstallation or 17826 * reinstallation on another volume. 17827 * <p> 17828 * Verifies that directories exist and that ownership and labeling is 17829 * correct for all installed apps. 17830 */ 17831 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 17832 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 17833 + Integer.toHexString(flags)); 17834 17835 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 17836 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 17837 17838 boolean restoreconNeeded = false; 17839 17840 // First look for stale data that doesn't belong, and check if things 17841 // have changed since we did our last restorecon 17842 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17843 if (!isUserKeyUnlocked(userId)) { 17844 throw new RuntimeException( 17845 "Yikes, someone asked us to reconcile CE storage while " + userId 17846 + " was still locked; this would have caused massive data loss!"); 17847 } 17848 17849 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 17850 17851 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 17852 for (File file : files) { 17853 final String packageName = file.getName(); 17854 try { 17855 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17856 } catch (PackageManagerException e) { 17857 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17858 synchronized (mInstallLock) { 17859 destroyAppDataLI(volumeUuid, packageName, userId, 17860 StorageManager.FLAG_STORAGE_CE); 17861 } 17862 } 17863 } 17864 } 17865 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17866 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 17867 17868 final File[] files = FileUtils.listFilesOrEmpty(deDir); 17869 for (File file : files) { 17870 final String packageName = file.getName(); 17871 try { 17872 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17873 } catch (PackageManagerException e) { 17874 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17875 synchronized (mInstallLock) { 17876 destroyAppDataLI(volumeUuid, packageName, userId, 17877 StorageManager.FLAG_STORAGE_DE); 17878 } 17879 } 17880 } 17881 } 17882 17883 // Ensure that data directories are ready to roll for all packages 17884 // installed for this volume and user 17885 final List<PackageSetting> packages; 17886 synchronized (mPackages) { 17887 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17888 } 17889 int preparedCount = 0; 17890 for (PackageSetting ps : packages) { 17891 final String packageName = ps.name; 17892 if (ps.pkg == null) { 17893 Slog.w(TAG, "Odd, missing scanned package " + packageName); 17894 // TODO: might be due to legacy ASEC apps; we should circle back 17895 // and reconcile again once they're scanned 17896 continue; 17897 } 17898 17899 if (ps.getInstalled(userId)) { 17900 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 17901 preparedCount++; 17902 } 17903 } 17904 17905 if (restoreconNeeded) { 17906 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17907 SELinuxMMAC.setRestoreconDone(ceDir); 17908 } 17909 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17910 SELinuxMMAC.setRestoreconDone(deDir); 17911 } 17912 } 17913 17914 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17915 + " packages; restoreconNeeded was " + restoreconNeeded); 17916 } 17917 17918 /** 17919 * Prepare app data for the given app just after it was installed or 17920 * upgraded. This method carefully only touches users that it's installed 17921 * for, and it forces a restorecon to handle any seinfo changes. 17922 * <p> 17923 * Verifies that directories exist and that ownership and labeling is 17924 * correct for all installed apps. If there is an ownership mismatch, it 17925 * will try recovering system apps by wiping data; third-party app data is 17926 * left intact. 17927 */ 17928 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17929 prepareAppDataAfterInstallInternal(pkg); 17930 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17931 for (int i = 0; i < childCount; i++) { 17932 PackageParser.Package childPackage = pkg.childPackages.get(i); 17933 prepareAppDataAfterInstallInternal(childPackage); 17934 } 17935 } 17936 17937 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 17938 final PackageSetting ps; 17939 synchronized (mPackages) { 17940 ps = mSettings.mPackages.get(pkg.packageName); 17941 } 17942 17943 final UserManager um = mContext.getSystemService(UserManager.class); 17944 for (UserInfo user : um.getUsers()) { 17945 final int flags; 17946 if (um.isUserUnlocked(user.id)) { 17947 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17948 } else if (um.isUserRunning(user.id)) { 17949 flags = StorageManager.FLAG_STORAGE_DE; 17950 } else { 17951 continue; 17952 } 17953 17954 if (ps.getInstalled(user.id)) { 17955 // Whenever an app changes, force a restorecon of its data 17956 // TODO: when user data is locked, mark that we're still dirty 17957 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17958 } 17959 } 17960 } 17961 17962 /** 17963 * Prepare app data for the given app. 17964 * <p> 17965 * Verifies that directories exist and that ownership and labeling is 17966 * correct for all installed apps. If there is an ownership mismatch, this 17967 * will try recovering system apps by wiping data; third-party app data is 17968 * left intact. 17969 */ 17970 private void prepareAppData(String volumeUuid, int userId, int flags, 17971 PackageParser.Package pkg, boolean restoreconNeeded) { 17972 if (DEBUG_APP_DATA) { 17973 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17974 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17975 } 17976 17977 final String packageName = pkg.packageName; 17978 final ApplicationInfo app = pkg.applicationInfo; 17979 final int appId = UserHandle.getAppId(app.uid); 17980 17981 Preconditions.checkNotNull(app.seinfo); 17982 17983 synchronized (mInstallLock) { 17984 try { 17985 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17986 appId, app.seinfo, app.targetSdkVersion); 17987 } catch (InstallerException e) { 17988 if (app.isSystemApp()) { 17989 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17990 + ", but trying to recover: " + e); 17991 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17992 try { 17993 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17994 appId, app.seinfo, app.targetSdkVersion); 17995 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17996 } catch (InstallerException e2) { 17997 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17998 } 17999 } else { 18000 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18001 } 18002 } 18003 18004 if (restoreconNeeded) { 18005 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18006 } 18007 18008 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18009 // Create a native library symlink only if we have native libraries 18010 // and if the native libraries are 32 bit libraries. We do not provide 18011 // this symlink for 64 bit libraries. 18012 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18013 final String nativeLibPath = app.nativeLibraryDir; 18014 try { 18015 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18016 nativeLibPath, userId); 18017 } catch (InstallerException e) { 18018 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18019 } 18020 } 18021 } 18022 } 18023 } 18024 18025 private void unfreezePackage(String packageName) { 18026 synchronized (mPackages) { 18027 final PackageSetting ps = mSettings.mPackages.get(packageName); 18028 if (ps != null) { 18029 ps.frozen = false; 18030 } 18031 } 18032 } 18033 18034 @Override 18035 public int movePackage(final String packageName, final String volumeUuid) { 18036 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18037 18038 final int moveId = mNextMoveId.getAndIncrement(); 18039 mHandler.post(new Runnable() { 18040 @Override 18041 public void run() { 18042 try { 18043 movePackageInternal(packageName, volumeUuid, moveId); 18044 } catch (PackageManagerException e) { 18045 Slog.w(TAG, "Failed to move " + packageName, e); 18046 mMoveCallbacks.notifyStatusChanged(moveId, 18047 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18048 } 18049 } 18050 }); 18051 return moveId; 18052 } 18053 18054 private void movePackageInternal(final String packageName, final String volumeUuid, 18055 final int moveId) throws PackageManagerException { 18056 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18057 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18058 final PackageManager pm = mContext.getPackageManager(); 18059 18060 final boolean currentAsec; 18061 final String currentVolumeUuid; 18062 final File codeFile; 18063 final String installerPackageName; 18064 final String packageAbiOverride; 18065 final int appId; 18066 final String seinfo; 18067 final String label; 18068 final int targetSdkVersion; 18069 18070 // reader 18071 synchronized (mPackages) { 18072 final PackageParser.Package pkg = mPackages.get(packageName); 18073 final PackageSetting ps = mSettings.mPackages.get(packageName); 18074 if (pkg == null || ps == null) { 18075 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18076 } 18077 18078 if (pkg.applicationInfo.isSystemApp()) { 18079 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18080 "Cannot move system application"); 18081 } 18082 18083 if (pkg.applicationInfo.isExternalAsec()) { 18084 currentAsec = true; 18085 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18086 } else if (pkg.applicationInfo.isForwardLocked()) { 18087 currentAsec = true; 18088 currentVolumeUuid = "forward_locked"; 18089 } else { 18090 currentAsec = false; 18091 currentVolumeUuid = ps.volumeUuid; 18092 18093 final File probe = new File(pkg.codePath); 18094 final File probeOat = new File(probe, "oat"); 18095 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18096 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18097 "Move only supported for modern cluster style installs"); 18098 } 18099 } 18100 18101 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18102 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18103 "Package already moved to " + volumeUuid); 18104 } 18105 18106 if (ps.frozen) { 18107 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18108 "Failed to move already frozen package"); 18109 } 18110 ps.frozen = true; 18111 18112 codeFile = new File(pkg.codePath); 18113 installerPackageName = ps.installerPackageName; 18114 packageAbiOverride = ps.cpuAbiOverrideString; 18115 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18116 seinfo = pkg.applicationInfo.seinfo; 18117 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18118 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18119 } 18120 18121 // Now that we're guarded by frozen state, kill app during move 18122 final long token = Binder.clearCallingIdentity(); 18123 try { 18124 killApplication(packageName, appId, "move pkg"); 18125 } finally { 18126 Binder.restoreCallingIdentity(token); 18127 } 18128 18129 final Bundle extras = new Bundle(); 18130 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18131 extras.putString(Intent.EXTRA_TITLE, label); 18132 mMoveCallbacks.notifyCreated(moveId, extras); 18133 18134 int installFlags; 18135 final boolean moveCompleteApp; 18136 final File measurePath; 18137 18138 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18139 installFlags = INSTALL_INTERNAL; 18140 moveCompleteApp = !currentAsec; 18141 measurePath = Environment.getDataAppDirectory(volumeUuid); 18142 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18143 installFlags = INSTALL_EXTERNAL; 18144 moveCompleteApp = false; 18145 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18146 } else { 18147 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18148 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18149 || !volume.isMountedWritable()) { 18150 unfreezePackage(packageName); 18151 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18152 "Move location not mounted private volume"); 18153 } 18154 18155 Preconditions.checkState(!currentAsec); 18156 18157 installFlags = INSTALL_INTERNAL; 18158 moveCompleteApp = true; 18159 measurePath = Environment.getDataAppDirectory(volumeUuid); 18160 } 18161 18162 final PackageStats stats = new PackageStats(null, -1); 18163 synchronized (mInstaller) { 18164 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18165 unfreezePackage(packageName); 18166 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18167 "Failed to measure package size"); 18168 } 18169 } 18170 18171 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18172 + stats.dataSize); 18173 18174 final long startFreeBytes = measurePath.getFreeSpace(); 18175 final long sizeBytes; 18176 if (moveCompleteApp) { 18177 sizeBytes = stats.codeSize + stats.dataSize; 18178 } else { 18179 sizeBytes = stats.codeSize; 18180 } 18181 18182 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18183 unfreezePackage(packageName); 18184 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18185 "Not enough free space to move"); 18186 } 18187 18188 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18189 18190 final CountDownLatch installedLatch = new CountDownLatch(1); 18191 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18192 @Override 18193 public void onUserActionRequired(Intent intent) throws RemoteException { 18194 throw new IllegalStateException(); 18195 } 18196 18197 @Override 18198 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18199 Bundle extras) throws RemoteException { 18200 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18201 + PackageManager.installStatusToString(returnCode, msg)); 18202 18203 installedLatch.countDown(); 18204 18205 // Regardless of success or failure of the move operation, 18206 // always unfreeze the package 18207 unfreezePackage(packageName); 18208 18209 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18210 switch (status) { 18211 case PackageInstaller.STATUS_SUCCESS: 18212 mMoveCallbacks.notifyStatusChanged(moveId, 18213 PackageManager.MOVE_SUCCEEDED); 18214 break; 18215 case PackageInstaller.STATUS_FAILURE_STORAGE: 18216 mMoveCallbacks.notifyStatusChanged(moveId, 18217 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18218 break; 18219 default: 18220 mMoveCallbacks.notifyStatusChanged(moveId, 18221 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18222 break; 18223 } 18224 } 18225 }; 18226 18227 final MoveInfo move; 18228 if (moveCompleteApp) { 18229 // Kick off a thread to report progress estimates 18230 new Thread() { 18231 @Override 18232 public void run() { 18233 while (true) { 18234 try { 18235 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18236 break; 18237 } 18238 } catch (InterruptedException ignored) { 18239 } 18240 18241 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18242 final int progress = 10 + (int) MathUtils.constrain( 18243 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18244 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18245 } 18246 } 18247 }.start(); 18248 18249 final String dataAppName = codeFile.getName(); 18250 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18251 dataAppName, appId, seinfo, targetSdkVersion); 18252 } else { 18253 move = null; 18254 } 18255 18256 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18257 18258 final Message msg = mHandler.obtainMessage(INIT_COPY); 18259 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18260 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18261 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 18262 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18263 msg.obj = params; 18264 18265 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18266 System.identityHashCode(msg.obj)); 18267 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18268 System.identityHashCode(msg.obj)); 18269 18270 mHandler.sendMessage(msg); 18271 } 18272 18273 @Override 18274 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18275 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18276 18277 final int realMoveId = mNextMoveId.getAndIncrement(); 18278 final Bundle extras = new Bundle(); 18279 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18280 mMoveCallbacks.notifyCreated(realMoveId, extras); 18281 18282 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18283 @Override 18284 public void onCreated(int moveId, Bundle extras) { 18285 // Ignored 18286 } 18287 18288 @Override 18289 public void onStatusChanged(int moveId, int status, long estMillis) { 18290 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18291 } 18292 }; 18293 18294 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18295 storage.setPrimaryStorageUuid(volumeUuid, callback); 18296 return realMoveId; 18297 } 18298 18299 @Override 18300 public int getMoveStatus(int moveId) { 18301 mContext.enforceCallingOrSelfPermission( 18302 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18303 return mMoveCallbacks.mLastStatus.get(moveId); 18304 } 18305 18306 @Override 18307 public void registerMoveCallback(IPackageMoveObserver callback) { 18308 mContext.enforceCallingOrSelfPermission( 18309 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18310 mMoveCallbacks.register(callback); 18311 } 18312 18313 @Override 18314 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18315 mContext.enforceCallingOrSelfPermission( 18316 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18317 mMoveCallbacks.unregister(callback); 18318 } 18319 18320 @Override 18321 public boolean setInstallLocation(int loc) { 18322 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18323 null); 18324 if (getInstallLocation() == loc) { 18325 return true; 18326 } 18327 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18328 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18329 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18330 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18331 return true; 18332 } 18333 return false; 18334 } 18335 18336 @Override 18337 public int getInstallLocation() { 18338 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18339 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18340 PackageHelper.APP_INSTALL_AUTO); 18341 } 18342 18343 /** Called by UserManagerService */ 18344 void cleanUpUser(UserManagerService userManager, int userHandle) { 18345 synchronized (mPackages) { 18346 mDirtyUsers.remove(userHandle); 18347 mUserNeedsBadging.delete(userHandle); 18348 mSettings.removeUserLPw(userHandle); 18349 mPendingBroadcasts.remove(userHandle); 18350 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18351 } 18352 synchronized (mInstallLock) { 18353 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18354 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18355 final String volumeUuid = vol.getFsUuid(); 18356 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18357 try { 18358 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18359 } catch (InstallerException e) { 18360 Slog.w(TAG, "Failed to remove user data", e); 18361 } 18362 } 18363 synchronized (mPackages) { 18364 removeUnusedPackagesLILPw(userManager, userHandle); 18365 } 18366 } 18367 } 18368 18369 /** 18370 * We're removing userHandle and would like to remove any downloaded packages 18371 * that are no longer in use by any other user. 18372 * @param userHandle the user being removed 18373 */ 18374 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18375 final boolean DEBUG_CLEAN_APKS = false; 18376 int [] users = userManager.getUserIds(); 18377 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18378 while (psit.hasNext()) { 18379 PackageSetting ps = psit.next(); 18380 if (ps.pkg == null) { 18381 continue; 18382 } 18383 final String packageName = ps.pkg.packageName; 18384 // Skip over if system app 18385 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18386 continue; 18387 } 18388 if (DEBUG_CLEAN_APKS) { 18389 Slog.i(TAG, "Checking package " + packageName); 18390 } 18391 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18392 if (keep) { 18393 if (DEBUG_CLEAN_APKS) { 18394 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18395 } 18396 } else { 18397 for (int i = 0; i < users.length; i++) { 18398 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18399 keep = true; 18400 if (DEBUG_CLEAN_APKS) { 18401 Slog.i(TAG, " Keeping package " + packageName + " for user " 18402 + users[i]); 18403 } 18404 break; 18405 } 18406 } 18407 } 18408 if (!keep) { 18409 if (DEBUG_CLEAN_APKS) { 18410 Slog.i(TAG, " Removing package " + packageName); 18411 } 18412 mHandler.post(new Runnable() { 18413 public void run() { 18414 deletePackageX(packageName, userHandle, 0); 18415 } //end run 18416 }); 18417 } 18418 } 18419 } 18420 18421 /** Called by UserManagerService */ 18422 void createNewUser(int userHandle) { 18423 synchronized (mInstallLock) { 18424 try { 18425 mInstaller.createUserConfig(userHandle); 18426 } catch (InstallerException e) { 18427 Slog.w(TAG, "Failed to create user config", e); 18428 } 18429 mSettings.createNewUserLI(this, mInstaller, userHandle); 18430 } 18431 synchronized (mPackages) { 18432 applyFactoryDefaultBrowserLPw(userHandle); 18433 primeDomainVerificationsLPw(userHandle); 18434 } 18435 } 18436 18437 void newUserCreated(final int userHandle) { 18438 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18439 // If permission review for legacy apps is required, we represent 18440 // dagerous permissions for such apps as always granted runtime 18441 // permissions to keep per user flag state whether review is needed. 18442 // Hence, if a new user is added we have to propagate dangerous 18443 // permission grants for these legacy apps. 18444 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18445 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18446 | UPDATE_PERMISSIONS_REPLACE_ALL); 18447 } 18448 } 18449 18450 @Override 18451 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18452 mContext.enforceCallingOrSelfPermission( 18453 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18454 "Only package verification agents can read the verifier device identity"); 18455 18456 synchronized (mPackages) { 18457 return mSettings.getVerifierDeviceIdentityLPw(); 18458 } 18459 } 18460 18461 @Override 18462 public void setPermissionEnforced(String permission, boolean enforced) { 18463 // TODO: Now that we no longer change GID for storage, this should to away. 18464 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18465 "setPermissionEnforced"); 18466 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18467 synchronized (mPackages) { 18468 if (mSettings.mReadExternalStorageEnforced == null 18469 || mSettings.mReadExternalStorageEnforced != enforced) { 18470 mSettings.mReadExternalStorageEnforced = enforced; 18471 mSettings.writeLPr(); 18472 } 18473 } 18474 // kill any non-foreground processes so we restart them and 18475 // grant/revoke the GID. 18476 final IActivityManager am = ActivityManagerNative.getDefault(); 18477 if (am != null) { 18478 final long token = Binder.clearCallingIdentity(); 18479 try { 18480 am.killProcessesBelowForeground("setPermissionEnforcement"); 18481 } catch (RemoteException e) { 18482 } finally { 18483 Binder.restoreCallingIdentity(token); 18484 } 18485 } 18486 } else { 18487 throw new IllegalArgumentException("No selective enforcement for " + permission); 18488 } 18489 } 18490 18491 @Override 18492 @Deprecated 18493 public boolean isPermissionEnforced(String permission) { 18494 return true; 18495 } 18496 18497 @Override 18498 public boolean isStorageLow() { 18499 final long token = Binder.clearCallingIdentity(); 18500 try { 18501 final DeviceStorageMonitorInternal 18502 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18503 if (dsm != null) { 18504 return dsm.isMemoryLow(); 18505 } else { 18506 return false; 18507 } 18508 } finally { 18509 Binder.restoreCallingIdentity(token); 18510 } 18511 } 18512 18513 @Override 18514 public IPackageInstaller getPackageInstaller() { 18515 return mInstallerService; 18516 } 18517 18518 private boolean userNeedsBadging(int userId) { 18519 int index = mUserNeedsBadging.indexOfKey(userId); 18520 if (index < 0) { 18521 final UserInfo userInfo; 18522 final long token = Binder.clearCallingIdentity(); 18523 try { 18524 userInfo = sUserManager.getUserInfo(userId); 18525 } finally { 18526 Binder.restoreCallingIdentity(token); 18527 } 18528 final boolean b; 18529 if (userInfo != null && userInfo.isManagedProfile()) { 18530 b = true; 18531 } else { 18532 b = false; 18533 } 18534 mUserNeedsBadging.put(userId, b); 18535 return b; 18536 } 18537 return mUserNeedsBadging.valueAt(index); 18538 } 18539 18540 @Override 18541 public KeySet getKeySetByAlias(String packageName, String alias) { 18542 if (packageName == null || alias == null) { 18543 return null; 18544 } 18545 synchronized(mPackages) { 18546 final PackageParser.Package pkg = mPackages.get(packageName); 18547 if (pkg == null) { 18548 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18549 throw new IllegalArgumentException("Unknown package: " + packageName); 18550 } 18551 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18552 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18553 } 18554 } 18555 18556 @Override 18557 public KeySet getSigningKeySet(String packageName) { 18558 if (packageName == null) { 18559 return null; 18560 } 18561 synchronized(mPackages) { 18562 final PackageParser.Package pkg = mPackages.get(packageName); 18563 if (pkg == null) { 18564 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18565 throw new IllegalArgumentException("Unknown package: " + packageName); 18566 } 18567 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18568 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18569 throw new SecurityException("May not access signing KeySet of other apps."); 18570 } 18571 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18572 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18573 } 18574 } 18575 18576 @Override 18577 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18578 if (packageName == null || ks == null) { 18579 return false; 18580 } 18581 synchronized(mPackages) { 18582 final PackageParser.Package pkg = mPackages.get(packageName); 18583 if (pkg == null) { 18584 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18585 throw new IllegalArgumentException("Unknown package: " + packageName); 18586 } 18587 IBinder ksh = ks.getToken(); 18588 if (ksh instanceof KeySetHandle) { 18589 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18590 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18591 } 18592 return false; 18593 } 18594 } 18595 18596 @Override 18597 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18598 if (packageName == null || ks == null) { 18599 return false; 18600 } 18601 synchronized(mPackages) { 18602 final PackageParser.Package pkg = mPackages.get(packageName); 18603 if (pkg == null) { 18604 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18605 throw new IllegalArgumentException("Unknown package: " + packageName); 18606 } 18607 IBinder ksh = ks.getToken(); 18608 if (ksh instanceof KeySetHandle) { 18609 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18610 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18611 } 18612 return false; 18613 } 18614 } 18615 18616 private void deletePackageIfUnusedLPr(final String packageName) { 18617 PackageSetting ps = mSettings.mPackages.get(packageName); 18618 if (ps == null) { 18619 return; 18620 } 18621 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18622 // TODO Implement atomic delete if package is unused 18623 // It is currently possible that the package will be deleted even if it is installed 18624 // after this method returns. 18625 mHandler.post(new Runnable() { 18626 public void run() { 18627 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18628 } 18629 }); 18630 } 18631 } 18632 18633 /** 18634 * Check and throw if the given before/after packages would be considered a 18635 * downgrade. 18636 */ 18637 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18638 throws PackageManagerException { 18639 if (after.versionCode < before.mVersionCode) { 18640 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18641 "Update version code " + after.versionCode + " is older than current " 18642 + before.mVersionCode); 18643 } else if (after.versionCode == before.mVersionCode) { 18644 if (after.baseRevisionCode < before.baseRevisionCode) { 18645 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18646 "Update base revision code " + after.baseRevisionCode 18647 + " is older than current " + before.baseRevisionCode); 18648 } 18649 18650 if (!ArrayUtils.isEmpty(after.splitNames)) { 18651 for (int i = 0; i < after.splitNames.length; i++) { 18652 final String splitName = after.splitNames[i]; 18653 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18654 if (j != -1) { 18655 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18656 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18657 "Update split " + splitName + " revision code " 18658 + after.splitRevisionCodes[i] + " is older than current " 18659 + before.splitRevisionCodes[j]); 18660 } 18661 } 18662 } 18663 } 18664 } 18665 } 18666 18667 private static class MoveCallbacks extends Handler { 18668 private static final int MSG_CREATED = 1; 18669 private static final int MSG_STATUS_CHANGED = 2; 18670 18671 private final RemoteCallbackList<IPackageMoveObserver> 18672 mCallbacks = new RemoteCallbackList<>(); 18673 18674 private final SparseIntArray mLastStatus = new SparseIntArray(); 18675 18676 public MoveCallbacks(Looper looper) { 18677 super(looper); 18678 } 18679 18680 public void register(IPackageMoveObserver callback) { 18681 mCallbacks.register(callback); 18682 } 18683 18684 public void unregister(IPackageMoveObserver callback) { 18685 mCallbacks.unregister(callback); 18686 } 18687 18688 @Override 18689 public void handleMessage(Message msg) { 18690 final SomeArgs args = (SomeArgs) msg.obj; 18691 final int n = mCallbacks.beginBroadcast(); 18692 for (int i = 0; i < n; i++) { 18693 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18694 try { 18695 invokeCallback(callback, msg.what, args); 18696 } catch (RemoteException ignored) { 18697 } 18698 } 18699 mCallbacks.finishBroadcast(); 18700 args.recycle(); 18701 } 18702 18703 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18704 throws RemoteException { 18705 switch (what) { 18706 case MSG_CREATED: { 18707 callback.onCreated(args.argi1, (Bundle) args.arg2); 18708 break; 18709 } 18710 case MSG_STATUS_CHANGED: { 18711 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 18712 break; 18713 } 18714 } 18715 } 18716 18717 private void notifyCreated(int moveId, Bundle extras) { 18718 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 18719 18720 final SomeArgs args = SomeArgs.obtain(); 18721 args.argi1 = moveId; 18722 args.arg2 = extras; 18723 obtainMessage(MSG_CREATED, args).sendToTarget(); 18724 } 18725 18726 private void notifyStatusChanged(int moveId, int status) { 18727 notifyStatusChanged(moveId, status, -1); 18728 } 18729 18730 private void notifyStatusChanged(int moveId, int status, long estMillis) { 18731 Slog.v(TAG, "Move " + moveId + " status " + status); 18732 18733 final SomeArgs args = SomeArgs.obtain(); 18734 args.argi1 = moveId; 18735 args.argi2 = status; 18736 args.arg3 = estMillis; 18737 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 18738 18739 synchronized (mLastStatus) { 18740 mLastStatus.put(moveId, status); 18741 } 18742 } 18743 } 18744 18745 private final static class OnPermissionChangeListeners extends Handler { 18746 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 18747 18748 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 18749 new RemoteCallbackList<>(); 18750 18751 public OnPermissionChangeListeners(Looper looper) { 18752 super(looper); 18753 } 18754 18755 @Override 18756 public void handleMessage(Message msg) { 18757 switch (msg.what) { 18758 case MSG_ON_PERMISSIONS_CHANGED: { 18759 final int uid = msg.arg1; 18760 handleOnPermissionsChanged(uid); 18761 } break; 18762 } 18763 } 18764 18765 public void addListenerLocked(IOnPermissionsChangeListener listener) { 18766 mPermissionListeners.register(listener); 18767 18768 } 18769 18770 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 18771 mPermissionListeners.unregister(listener); 18772 } 18773 18774 public void onPermissionsChanged(int uid) { 18775 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 18776 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 18777 } 18778 } 18779 18780 private void handleOnPermissionsChanged(int uid) { 18781 final int count = mPermissionListeners.beginBroadcast(); 18782 try { 18783 for (int i = 0; i < count; i++) { 18784 IOnPermissionsChangeListener callback = mPermissionListeners 18785 .getBroadcastItem(i); 18786 try { 18787 callback.onPermissionsChanged(uid); 18788 } catch (RemoteException e) { 18789 Log.e(TAG, "Permission listener is dead", e); 18790 } 18791 } 18792 } finally { 18793 mPermissionListeners.finishBroadcast(); 18794 } 18795 } 18796 } 18797 18798 private class PackageManagerInternalImpl extends PackageManagerInternal { 18799 @Override 18800 public void setLocationPackagesProvider(PackagesProvider provider) { 18801 synchronized (mPackages) { 18802 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 18803 } 18804 } 18805 18806 @Override 18807 public void setImePackagesProvider(PackagesProvider provider) { 18808 synchronized (mPackages) { 18809 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 18810 } 18811 } 18812 18813 @Override 18814 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 18815 synchronized (mPackages) { 18816 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 18817 } 18818 } 18819 18820 @Override 18821 public void setSmsAppPackagesProvider(PackagesProvider provider) { 18822 synchronized (mPackages) { 18823 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 18824 } 18825 } 18826 18827 @Override 18828 public void setDialerAppPackagesProvider(PackagesProvider provider) { 18829 synchronized (mPackages) { 18830 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 18831 } 18832 } 18833 18834 @Override 18835 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 18836 synchronized (mPackages) { 18837 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 18838 } 18839 } 18840 18841 @Override 18842 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 18843 synchronized (mPackages) { 18844 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 18845 } 18846 } 18847 18848 @Override 18849 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 18850 synchronized (mPackages) { 18851 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 18852 packageName, userId); 18853 } 18854 } 18855 18856 @Override 18857 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 18858 synchronized (mPackages) { 18859 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 18860 packageName, userId); 18861 } 18862 } 18863 18864 @Override 18865 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 18866 synchronized (mPackages) { 18867 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 18868 packageName, userId); 18869 } 18870 } 18871 18872 @Override 18873 public void setKeepUninstalledPackages(final List<String> packageList) { 18874 Preconditions.checkNotNull(packageList); 18875 List<String> removedFromList = null; 18876 synchronized (mPackages) { 18877 if (mKeepUninstalledPackages != null) { 18878 final int packagesCount = mKeepUninstalledPackages.size(); 18879 for (int i = 0; i < packagesCount; i++) { 18880 String oldPackage = mKeepUninstalledPackages.get(i); 18881 if (packageList != null && packageList.contains(oldPackage)) { 18882 continue; 18883 } 18884 if (removedFromList == null) { 18885 removedFromList = new ArrayList<>(); 18886 } 18887 removedFromList.add(oldPackage); 18888 } 18889 } 18890 mKeepUninstalledPackages = new ArrayList<>(packageList); 18891 if (removedFromList != null) { 18892 final int removedCount = removedFromList.size(); 18893 for (int i = 0; i < removedCount; i++) { 18894 deletePackageIfUnusedLPr(removedFromList.get(i)); 18895 } 18896 } 18897 } 18898 } 18899 18900 @Override 18901 public boolean isPermissionsReviewRequired(String packageName, int userId) { 18902 synchronized (mPackages) { 18903 // If we do not support permission review, done. 18904 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 18905 return false; 18906 } 18907 18908 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 18909 if (packageSetting == null) { 18910 return false; 18911 } 18912 18913 // Permission review applies only to apps not supporting the new permission model. 18914 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 18915 return false; 18916 } 18917 18918 // Legacy apps have the permission and get user consent on launch. 18919 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18920 return permissionsState.isPermissionReviewRequired(userId); 18921 } 18922 } 18923 } 18924 18925 @Override 18926 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18927 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18928 synchronized (mPackages) { 18929 final long identity = Binder.clearCallingIdentity(); 18930 try { 18931 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18932 packageNames, userId); 18933 } finally { 18934 Binder.restoreCallingIdentity(identity); 18935 } 18936 } 18937 } 18938 18939 private static void enforceSystemOrPhoneCaller(String tag) { 18940 int callingUid = Binder.getCallingUid(); 18941 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18942 throw new SecurityException( 18943 "Cannot call " + tag + " from UID " + callingUid); 18944 } 18945 } 18946 18947 boolean isHistoricalPackageUsageAvailable() { 18948 return mPackageUsage.isHistoricalPackageUsageAvailable(); 18949 } 18950} 18951