PackageManagerService.java revision 2f3e35376ada0327b34a71d7c45ac6e6d955d7dc
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 63import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 64import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 65import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 66import static android.content.pm.PackageManager.PERMISSION_DENIED; 67import static android.content.pm.PackageManager.PERMISSION_GRANTED; 68import static android.content.pm.PackageParser.isApkFile; 69import static android.os.Process.PACKAGE_INFO_GID; 70import static android.os.Process.SYSTEM_UID; 71import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 72import static android.system.OsConstants.O_CREAT; 73import static android.system.OsConstants.O_RDWR; 74 75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 76import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 77import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 78import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 79import static com.android.internal.util.ArrayUtils.appendInt; 80import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 81import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 83import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 84import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 85import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 88import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 89 90import android.Manifest; 91import android.app.ActivityManager; 92import android.app.ActivityManagerNative; 93import android.app.AppGlobals; 94import android.app.IActivityManager; 95import android.app.admin.IDevicePolicyManager; 96import android.app.backup.IBackupManager; 97import android.content.BroadcastReceiver; 98import android.content.ComponentName; 99import android.content.Context; 100import android.content.IIntentReceiver; 101import android.content.Intent; 102import android.content.IntentFilter; 103import android.content.IntentSender; 104import android.content.IntentSender.SendIntentException; 105import android.content.ServiceConnection; 106import android.content.pm.ActivityInfo; 107import android.content.pm.ApplicationInfo; 108import android.content.pm.AppsQueryHelper; 109import android.content.pm.ComponentInfo; 110import android.content.pm.EphemeralApplicationInfo; 111import android.content.pm.EphemeralResolveInfo; 112import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 113import android.content.pm.FeatureInfo; 114import android.content.pm.IOnPermissionsChangeListener; 115import android.content.pm.IPackageDataObserver; 116import android.content.pm.IPackageDeleteObserver; 117import android.content.pm.IPackageDeleteObserver2; 118import android.content.pm.IPackageInstallObserver2; 119import android.content.pm.IPackageInstaller; 120import android.content.pm.IPackageManager; 121import android.content.pm.IPackageMoveObserver; 122import android.content.pm.IPackageStatsObserver; 123import android.content.pm.InstrumentationInfo; 124import android.content.pm.IntentFilterVerificationInfo; 125import android.content.pm.KeySet; 126import android.content.pm.ManifestDigest; 127import android.content.pm.PackageCleanItem; 128import android.content.pm.PackageInfo; 129import android.content.pm.PackageInfoLite; 130import android.content.pm.PackageInstaller; 131import android.content.pm.PackageManager; 132import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 133import android.content.pm.PackageManagerInternal; 134import android.content.pm.PackageParser; 135import android.content.pm.PackageParser.ActivityIntentInfo; 136import android.content.pm.PackageParser.PackageLite; 137import android.content.pm.PackageParser.PackageParserException; 138import android.content.pm.PackageStats; 139import android.content.pm.PackageUserState; 140import android.content.pm.ParceledListSlice; 141import android.content.pm.PermissionGroupInfo; 142import android.content.pm.PermissionInfo; 143import android.content.pm.ProviderInfo; 144import android.content.pm.ResolveInfo; 145import android.content.pm.ServiceInfo; 146import android.content.pm.Signature; 147import android.content.pm.UserInfo; 148import android.content.pm.VerificationParams; 149import android.content.pm.VerifierDeviceIdentity; 150import android.content.pm.VerifierInfo; 151import android.content.res.Resources; 152import android.graphics.Bitmap; 153import android.hardware.display.DisplayManager; 154import android.net.Uri; 155import android.os.Binder; 156import android.os.Build; 157import android.os.Bundle; 158import android.os.Debug; 159import android.os.Environment; 160import android.os.Environment.UserEnvironment; 161import android.os.FileUtils; 162import android.os.Handler; 163import android.os.IBinder; 164import android.os.Looper; 165import android.os.Message; 166import android.os.Parcel; 167import android.os.ParcelFileDescriptor; 168import android.os.Process; 169import android.os.RemoteCallbackList; 170import android.os.RemoteException; 171import android.os.ResultReceiver; 172import android.os.SELinux; 173import android.os.ServiceManager; 174import android.os.SystemClock; 175import android.os.SystemProperties; 176import android.os.Trace; 177import android.os.UserHandle; 178import android.os.UserManager; 179import android.os.storage.IMountService; 180import android.os.storage.MountServiceInternal; 181import android.os.storage.StorageEventListener; 182import android.os.storage.StorageManager; 183import android.os.storage.VolumeInfo; 184import android.os.storage.VolumeRecord; 185import android.security.KeyStore; 186import android.security.SystemKeyStore; 187import android.system.ErrnoException; 188import android.system.Os; 189import android.system.StructStat; 190import android.text.TextUtils; 191import android.text.format.DateUtils; 192import android.util.ArrayMap; 193import android.util.ArraySet; 194import android.util.AtomicFile; 195import android.util.DisplayMetrics; 196import android.util.EventLog; 197import android.util.ExceptionUtils; 198import android.util.Log; 199import android.util.LogPrinter; 200import android.util.MathUtils; 201import android.util.PrintStreamPrinter; 202import android.util.Slog; 203import android.util.SparseArray; 204import android.util.SparseBooleanArray; 205import android.util.SparseIntArray; 206import android.util.Xml; 207import android.view.Display; 208 209import com.android.internal.R; 210import com.android.internal.annotations.GuardedBy; 211import com.android.internal.app.IMediaContainerService; 212import com.android.internal.app.ResolverActivity; 213import com.android.internal.content.NativeLibraryHelper; 214import com.android.internal.content.PackageHelper; 215import com.android.internal.os.IParcelFileDescriptorFactory; 216import com.android.internal.os.SomeArgs; 217import com.android.internal.os.Zygote; 218import com.android.internal.util.ArrayUtils; 219import com.android.internal.util.FastPrintWriter; 220import com.android.internal.util.FastXmlSerializer; 221import com.android.internal.util.IndentingPrintWriter; 222import com.android.internal.util.Preconditions; 223import com.android.server.EventLogTags; 224import com.android.server.FgThread; 225import com.android.server.IntentResolver; 226import com.android.server.LocalServices; 227import com.android.server.ServiceThread; 228import com.android.server.SystemConfig; 229import com.android.server.Watchdog; 230import com.android.server.pm.PermissionsState.PermissionState; 231import com.android.server.pm.Settings.DatabaseVersion; 232import com.android.server.pm.Settings.VersionInfo; 233import com.android.server.storage.DeviceStorageMonitorInternal; 234 235import dalvik.system.DexFile; 236import dalvik.system.VMRuntime; 237 238import libcore.io.IoUtils; 239import libcore.util.EmptyArray; 240 241import org.xmlpull.v1.XmlPullParser; 242import org.xmlpull.v1.XmlPullParserException; 243import org.xmlpull.v1.XmlSerializer; 244 245import java.io.BufferedInputStream; 246import java.io.BufferedOutputStream; 247import java.io.BufferedReader; 248import java.io.ByteArrayInputStream; 249import java.io.ByteArrayOutputStream; 250import java.io.File; 251import java.io.FileDescriptor; 252import java.io.FileNotFoundException; 253import java.io.FileOutputStream; 254import java.io.FileReader; 255import java.io.FilenameFilter; 256import java.io.IOException; 257import java.io.InputStream; 258import java.io.PrintWriter; 259import java.nio.charset.StandardCharsets; 260import java.security.MessageDigest; 261import java.security.NoSuchAlgorithmException; 262import java.security.PublicKey; 263import java.security.cert.CertificateEncodingException; 264import java.security.cert.CertificateException; 265import java.text.SimpleDateFormat; 266import java.util.ArrayList; 267import java.util.Arrays; 268import java.util.Collection; 269import java.util.Collections; 270import java.util.Comparator; 271import java.util.Date; 272import java.util.Iterator; 273import java.util.List; 274import java.util.Map; 275import java.util.Objects; 276import java.util.Set; 277import java.util.concurrent.CountDownLatch; 278import java.util.concurrent.TimeUnit; 279import java.util.concurrent.atomic.AtomicBoolean; 280import java.util.concurrent.atomic.AtomicInteger; 281import java.util.concurrent.atomic.AtomicLong; 282 283/** 284 * Keep track of all those .apks everywhere. 285 * 286 * This is very central to the platform's security; please run the unit 287 * tests whenever making modifications here: 288 * 289runtest -c android.content.pm.PackageManagerTests frameworks-core 290 * 291 * {@hide} 292 */ 293public class PackageManagerService extends IPackageManager.Stub { 294 static final String TAG = "PackageManager"; 295 static final boolean DEBUG_SETTINGS = false; 296 static final boolean DEBUG_PREFERRED = false; 297 static final boolean DEBUG_UPGRADE = false; 298 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 299 private static final boolean DEBUG_BACKUP = false; 300 private static final boolean DEBUG_INSTALL = false; 301 private static final boolean DEBUG_REMOVE = false; 302 private static final boolean DEBUG_BROADCASTS = false; 303 private static final boolean DEBUG_SHOW_INFO = false; 304 private static final boolean DEBUG_PACKAGE_INFO = false; 305 private static final boolean DEBUG_INTENT_MATCHING = false; 306 private static final boolean DEBUG_PACKAGE_SCANNING = false; 307 private static final boolean DEBUG_VERIFY = false; 308 private static final boolean DEBUG_DEXOPT = false; 309 private static final boolean DEBUG_ABI_SELECTION = false; 310 private static final boolean DEBUG_EPHEMERAL = false; 311 private static final boolean DEBUG_TRIAGED_MISSING = false; 312 313 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 314 315 private static final int RADIO_UID = Process.PHONE_UID; 316 private static final int LOG_UID = Process.LOG_UID; 317 private static final int NFC_UID = Process.NFC_UID; 318 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 319 private static final int SHELL_UID = Process.SHELL_UID; 320 321 // Cap the size of permission trees that 3rd party apps can define 322 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 323 324 // Suffix used during package installation when copying/moving 325 // package apks to install directory. 326 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 327 328 static final int SCAN_NO_DEX = 1<<1; 329 static final int SCAN_FORCE_DEX = 1<<2; 330 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 331 static final int SCAN_NEW_INSTALL = 1<<4; 332 static final int SCAN_NO_PATHS = 1<<5; 333 static final int SCAN_UPDATE_TIME = 1<<6; 334 static final int SCAN_DEFER_DEX = 1<<7; 335 static final int SCAN_BOOTING = 1<<8; 336 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 337 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 338 static final int SCAN_REPLACING = 1<<11; 339 static final int SCAN_REQUIRE_KNOWN = 1<<12; 340 static final int SCAN_MOVE = 1<<13; 341 static final int SCAN_INITIAL = 1<<14; 342 343 static final int REMOVE_CHATTY = 1<<16; 344 345 private static final int[] EMPTY_INT_ARRAY = new int[0]; 346 347 /** 348 * Timeout (in milliseconds) after which the watchdog should declare that 349 * our handler thread is wedged. The usual default for such things is one 350 * minute but we sometimes do very lengthy I/O operations on this thread, 351 * such as installing multi-gigabyte applications, so ours needs to be longer. 352 */ 353 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 354 355 /** 356 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 357 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 358 * settings entry if available, otherwise we use the hardcoded default. If it's been 359 * more than this long since the last fstrim, we force one during the boot sequence. 360 * 361 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 362 * one gets run at the next available charging+idle time. This final mandatory 363 * no-fstrim check kicks in only of the other scheduling criteria is never met. 364 */ 365 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 366 367 /** 368 * Whether verification is enabled by default. 369 */ 370 private static final boolean DEFAULT_VERIFY_ENABLE = true; 371 372 /** 373 * The default maximum time to wait for the verification agent to return in 374 * milliseconds. 375 */ 376 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 377 378 /** 379 * The default response for package verification timeout. 380 * 381 * This can be either PackageManager.VERIFICATION_ALLOW or 382 * PackageManager.VERIFICATION_REJECT. 383 */ 384 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 385 386 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 387 388 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 389 DEFAULT_CONTAINER_PACKAGE, 390 "com.android.defcontainer.DefaultContainerService"); 391 392 private static final String KILL_APP_REASON_GIDS_CHANGED = 393 "permission grant or revoke changed gids"; 394 395 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 396 "permissions revoked"; 397 398 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 399 400 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 401 402 /** Permission grant: not grant the permission. */ 403 private static final int GRANT_DENIED = 1; 404 405 /** Permission grant: grant the permission as an install permission. */ 406 private static final int GRANT_INSTALL = 2; 407 408 /** Permission grant: grant the permission as a runtime one. */ 409 private static final int GRANT_RUNTIME = 3; 410 411 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 412 private static final int GRANT_UPGRADE = 4; 413 414 /** Canonical intent used to identify what counts as a "web browser" app */ 415 private static final Intent sBrowserIntent; 416 static { 417 sBrowserIntent = new Intent(); 418 sBrowserIntent.setAction(Intent.ACTION_VIEW); 419 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 420 sBrowserIntent.setData(Uri.parse("http:")); 421 } 422 423 final ServiceThread mHandlerThread; 424 425 final PackageHandler mHandler; 426 427 /** 428 * Messages for {@link #mHandler} that need to wait for system ready before 429 * being dispatched. 430 */ 431 private ArrayList<Message> mPostSystemReadyMessages; 432 433 final int mSdkVersion = Build.VERSION.SDK_INT; 434 435 final Context mContext; 436 final boolean mFactoryTest; 437 final boolean mOnlyCore; 438 final DisplayMetrics mMetrics; 439 final int mDefParseFlags; 440 final String[] mSeparateProcesses; 441 final boolean mIsUpgrade; 442 443 /** The location for ASEC container files on internal storage. */ 444 final String mAsecInternalPath; 445 446 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 447 // LOCK HELD. Can be called with mInstallLock held. 448 @GuardedBy("mInstallLock") 449 final Installer mInstaller; 450 451 /** Directory where installed third-party apps stored */ 452 final File mAppInstallDir; 453 final File mEphemeralInstallDir; 454 455 /** 456 * Directory to which applications installed internally have their 457 * 32 bit native libraries copied. 458 */ 459 private File mAppLib32InstallDir; 460 461 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 462 // apps. 463 final File mDrmAppPrivateInstallDir; 464 465 // ---------------------------------------------------------------- 466 467 // Lock for state used when installing and doing other long running 468 // operations. Methods that must be called with this lock held have 469 // the suffix "LI". 470 final Object mInstallLock = new Object(); 471 472 // ---------------------------------------------------------------- 473 474 // Keys are String (package name), values are Package. This also serves 475 // as the lock for the global state. Methods that must be called with 476 // this lock held have the prefix "LP". 477 @GuardedBy("mPackages") 478 final ArrayMap<String, PackageParser.Package> mPackages = 479 new ArrayMap<String, PackageParser.Package>(); 480 481 // Tracks available target package names -> overlay package paths. 482 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 483 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 484 485 /** 486 * Tracks new system packages [received in an OTA] that we expect to 487 * find updated user-installed versions. Keys are package name, values 488 * are package location. 489 */ 490 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 491 492 /** 493 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 494 */ 495 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 496 /** 497 * Whether or not system app permissions should be promoted from install to runtime. 498 */ 499 boolean mPromoteSystemApps; 500 501 final Settings mSettings; 502 boolean mRestoredSettings; 503 504 // System configuration read by SystemConfig. 505 final int[] mGlobalGids; 506 final SparseArray<ArraySet<String>> mSystemPermissions; 507 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 508 509 // If mac_permissions.xml was found for seinfo labeling. 510 boolean mFoundPolicyFile; 511 512 // If a recursive restorecon of /data/data/<pkg> is needed. 513 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 514 515 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 516 517 public static final class SharedLibraryEntry { 518 public final String path; 519 public final String apk; 520 521 SharedLibraryEntry(String _path, String _apk) { 522 path = _path; 523 apk = _apk; 524 } 525 } 526 527 // Currently known shared libraries. 528 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 529 new ArrayMap<String, SharedLibraryEntry>(); 530 531 // All available activities, for your resolving pleasure. 532 final ActivityIntentResolver mActivities = 533 new ActivityIntentResolver(); 534 535 // All available receivers, for your resolving pleasure. 536 final ActivityIntentResolver mReceivers = 537 new ActivityIntentResolver(); 538 539 // All available services, for your resolving pleasure. 540 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 541 542 // All available providers, for your resolving pleasure. 543 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 544 545 // Mapping from provider base names (first directory in content URI codePath) 546 // to the provider information. 547 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 548 new ArrayMap<String, PackageParser.Provider>(); 549 550 // Mapping from instrumentation class names to info about them. 551 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 552 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 553 554 // Mapping from permission names to info about them. 555 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 556 new ArrayMap<String, PackageParser.PermissionGroup>(); 557 558 // Packages whose data we have transfered into another package, thus 559 // should no longer exist. 560 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 561 562 // Broadcast actions that are only available to the system. 563 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 564 565 /** List of packages waiting for verification. */ 566 final SparseArray<PackageVerificationState> mPendingVerification 567 = new SparseArray<PackageVerificationState>(); 568 569 /** Set of packages associated with each app op permission. */ 570 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 571 572 final PackageInstallerService mInstallerService; 573 574 private final PackageDexOptimizer mPackageDexOptimizer; 575 576 private AtomicInteger mNextMoveId = new AtomicInteger(); 577 private final MoveCallbacks mMoveCallbacks; 578 579 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 580 581 // Cache of users who need badging. 582 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 583 584 /** Token for keys in mPendingVerification. */ 585 private int mPendingVerificationToken = 0; 586 587 volatile boolean mSystemReady; 588 volatile boolean mSafeMode; 589 volatile boolean mHasSystemUidErrors; 590 591 ApplicationInfo mAndroidApplication; 592 final ActivityInfo mResolveActivity = new ActivityInfo(); 593 final ResolveInfo mResolveInfo = new ResolveInfo(); 594 ComponentName mResolveComponentName; 595 PackageParser.Package mPlatformPackage; 596 ComponentName mCustomResolverComponentName; 597 598 boolean mResolverReplaced = false; 599 600 private final ComponentName mIntentFilterVerifierComponent; 601 private int mIntentFilterVerificationToken = 0; 602 603 /** Component that knows whether or not an ephemeral application exists */ 604 final ComponentName mEphemeralResolverComponent; 605 /** The service connection to the ephemeral resolver */ 606 final EphemeralResolverConnection mEphemeralResolverConnection; 607 608 /** Component used to install ephemeral applications */ 609 final ComponentName mEphemeralInstallerComponent; 610 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 611 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 612 613 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 614 = new SparseArray<IntentFilterVerificationState>(); 615 616 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 617 new DefaultPermissionGrantPolicy(this); 618 619 // List of packages names to keep cached, even if they are uninstalled for all users 620 private List<String> mKeepUninstalledPackages; 621 622 private static class IFVerificationParams { 623 PackageParser.Package pkg; 624 boolean replacing; 625 int userId; 626 int verifierUid; 627 628 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 629 int _userId, int _verifierUid) { 630 pkg = _pkg; 631 replacing = _replacing; 632 userId = _userId; 633 replacing = _replacing; 634 verifierUid = _verifierUid; 635 } 636 } 637 638 private interface IntentFilterVerifier<T extends IntentFilter> { 639 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 640 T filter, String packageName); 641 void startVerifications(int userId); 642 void receiveVerificationResponse(int verificationId); 643 } 644 645 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 646 private Context mContext; 647 private ComponentName mIntentFilterVerifierComponent; 648 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 649 650 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 651 mContext = context; 652 mIntentFilterVerifierComponent = verifierComponent; 653 } 654 655 private String getDefaultScheme() { 656 return IntentFilter.SCHEME_HTTPS; 657 } 658 659 @Override 660 public void startVerifications(int userId) { 661 // Launch verifications requests 662 int count = mCurrentIntentFilterVerifications.size(); 663 for (int n=0; n<count; n++) { 664 int verificationId = mCurrentIntentFilterVerifications.get(n); 665 final IntentFilterVerificationState ivs = 666 mIntentFilterVerificationStates.get(verificationId); 667 668 String packageName = ivs.getPackageName(); 669 670 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 671 final int filterCount = filters.size(); 672 ArraySet<String> domainsSet = new ArraySet<>(); 673 for (int m=0; m<filterCount; m++) { 674 PackageParser.ActivityIntentInfo filter = filters.get(m); 675 domainsSet.addAll(filter.getHostsList()); 676 } 677 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 678 synchronized (mPackages) { 679 if (mSettings.createIntentFilterVerificationIfNeededLPw( 680 packageName, domainsList) != null) { 681 scheduleWriteSettingsLocked(); 682 } 683 } 684 sendVerificationRequest(userId, verificationId, ivs); 685 } 686 mCurrentIntentFilterVerifications.clear(); 687 } 688 689 private void sendVerificationRequest(int userId, int verificationId, 690 IntentFilterVerificationState ivs) { 691 692 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 693 verificationIntent.putExtra( 694 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 695 verificationId); 696 verificationIntent.putExtra( 697 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 698 getDefaultScheme()); 699 verificationIntent.putExtra( 700 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 701 ivs.getHostsString()); 702 verificationIntent.putExtra( 703 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 704 ivs.getPackageName()); 705 verificationIntent.setComponent(mIntentFilterVerifierComponent); 706 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 707 708 UserHandle user = new UserHandle(userId); 709 mContext.sendBroadcastAsUser(verificationIntent, user); 710 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 711 "Sending IntentFilter verification broadcast"); 712 } 713 714 public void receiveVerificationResponse(int verificationId) { 715 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 716 717 final boolean verified = ivs.isVerified(); 718 719 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 720 final int count = filters.size(); 721 if (DEBUG_DOMAIN_VERIFICATION) { 722 Slog.i(TAG, "Received verification response " + verificationId 723 + " for " + count + " filters, verified=" + verified); 724 } 725 for (int n=0; n<count; n++) { 726 PackageParser.ActivityIntentInfo filter = filters.get(n); 727 filter.setVerified(verified); 728 729 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 730 + " verified with result:" + verified + " and hosts:" 731 + ivs.getHostsString()); 732 } 733 734 mIntentFilterVerificationStates.remove(verificationId); 735 736 final String packageName = ivs.getPackageName(); 737 IntentFilterVerificationInfo ivi = null; 738 739 synchronized (mPackages) { 740 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 741 } 742 if (ivi == null) { 743 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 744 + verificationId + " packageName:" + packageName); 745 return; 746 } 747 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 748 "Updating IntentFilterVerificationInfo for package " + packageName 749 +" verificationId:" + verificationId); 750 751 synchronized (mPackages) { 752 if (verified) { 753 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 754 } else { 755 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 756 } 757 scheduleWriteSettingsLocked(); 758 759 final int userId = ivs.getUserId(); 760 if (userId != UserHandle.USER_ALL) { 761 final int userStatus = 762 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 763 764 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 765 boolean needUpdate = false; 766 767 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 768 // already been set by the User thru the Disambiguation dialog 769 switch (userStatus) { 770 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 771 if (verified) { 772 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 773 } else { 774 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 775 } 776 needUpdate = true; 777 break; 778 779 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 780 if (verified) { 781 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 782 needUpdate = true; 783 } 784 break; 785 786 default: 787 // Nothing to do 788 } 789 790 if (needUpdate) { 791 mSettings.updateIntentFilterVerificationStatusLPw( 792 packageName, updatedStatus, userId); 793 scheduleWritePackageRestrictionsLocked(userId); 794 } 795 } 796 } 797 } 798 799 @Override 800 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 801 ActivityIntentInfo filter, String packageName) { 802 if (!hasValidDomains(filter)) { 803 return false; 804 } 805 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 806 if (ivs == null) { 807 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 808 packageName); 809 } 810 if (DEBUG_DOMAIN_VERIFICATION) { 811 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 812 } 813 ivs.addFilter(filter); 814 return true; 815 } 816 817 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 818 int userId, int verificationId, String packageName) { 819 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 820 verifierUid, userId, packageName); 821 ivs.setPendingState(); 822 synchronized (mPackages) { 823 mIntentFilterVerificationStates.append(verificationId, ivs); 824 mCurrentIntentFilterVerifications.add(verificationId); 825 } 826 return ivs; 827 } 828 } 829 830 private static boolean hasValidDomains(ActivityIntentInfo filter) { 831 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 832 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 833 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 834 } 835 836 private IntentFilterVerifier mIntentFilterVerifier; 837 838 // Set of pending broadcasts for aggregating enable/disable of components. 839 static class PendingPackageBroadcasts { 840 // for each user id, a map of <package name -> components within that package> 841 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 842 843 public PendingPackageBroadcasts() { 844 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 845 } 846 847 public ArrayList<String> get(int userId, String packageName) { 848 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 849 return packages.get(packageName); 850 } 851 852 public void put(int userId, String packageName, ArrayList<String> components) { 853 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 854 packages.put(packageName, components); 855 } 856 857 public void remove(int userId, String packageName) { 858 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 859 if (packages != null) { 860 packages.remove(packageName); 861 } 862 } 863 864 public void remove(int userId) { 865 mUidMap.remove(userId); 866 } 867 868 public int userIdCount() { 869 return mUidMap.size(); 870 } 871 872 public int userIdAt(int n) { 873 return mUidMap.keyAt(n); 874 } 875 876 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 877 return mUidMap.get(userId); 878 } 879 880 public int size() { 881 // total number of pending broadcast entries across all userIds 882 int num = 0; 883 for (int i = 0; i< mUidMap.size(); i++) { 884 num += mUidMap.valueAt(i).size(); 885 } 886 return num; 887 } 888 889 public void clear() { 890 mUidMap.clear(); 891 } 892 893 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 894 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 895 if (map == null) { 896 map = new ArrayMap<String, ArrayList<String>>(); 897 mUidMap.put(userId, map); 898 } 899 return map; 900 } 901 } 902 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 903 904 // Service Connection to remote media container service to copy 905 // package uri's from external media onto secure containers 906 // or internal storage. 907 private IMediaContainerService mContainerService = null; 908 909 static final int SEND_PENDING_BROADCAST = 1; 910 static final int MCS_BOUND = 3; 911 static final int END_COPY = 4; 912 static final int INIT_COPY = 5; 913 static final int MCS_UNBIND = 6; 914 static final int START_CLEANING_PACKAGE = 7; 915 static final int FIND_INSTALL_LOC = 8; 916 static final int POST_INSTALL = 9; 917 static final int MCS_RECONNECT = 10; 918 static final int MCS_GIVE_UP = 11; 919 static final int UPDATED_MEDIA_STATUS = 12; 920 static final int WRITE_SETTINGS = 13; 921 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 922 static final int PACKAGE_VERIFIED = 15; 923 static final int CHECK_PENDING_VERIFICATION = 16; 924 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 925 static final int INTENT_FILTER_VERIFIED = 18; 926 927 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 928 929 // Delay time in millisecs 930 static final int BROADCAST_DELAY = 10 * 1000; 931 932 static UserManagerService sUserManager; 933 934 // Stores a list of users whose package restrictions file needs to be updated 935 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 936 937 final private DefaultContainerConnection mDefContainerConn = 938 new DefaultContainerConnection(); 939 class DefaultContainerConnection implements ServiceConnection { 940 public void onServiceConnected(ComponentName name, IBinder service) { 941 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 942 IMediaContainerService imcs = 943 IMediaContainerService.Stub.asInterface(service); 944 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 945 } 946 947 public void onServiceDisconnected(ComponentName name) { 948 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 949 } 950 } 951 952 // Recordkeeping of restore-after-install operations that are currently in flight 953 // between the Package Manager and the Backup Manager 954 static class PostInstallData { 955 public InstallArgs args; 956 public PackageInstalledInfo res; 957 958 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 959 args = _a; 960 res = _r; 961 } 962 } 963 964 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 965 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 966 967 // XML tags for backup/restore of various bits of state 968 private static final String TAG_PREFERRED_BACKUP = "pa"; 969 private static final String TAG_DEFAULT_APPS = "da"; 970 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 971 972 final String mRequiredVerifierPackage; 973 final String mRequiredInstallerPackage; 974 975 private final PackageUsage mPackageUsage = new PackageUsage(); 976 977 private class PackageUsage { 978 private static final int WRITE_INTERVAL 979 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 980 981 private final Object mFileLock = new Object(); 982 private final AtomicLong mLastWritten = new AtomicLong(0); 983 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 984 985 private boolean mIsHistoricalPackageUsageAvailable = true; 986 987 boolean isHistoricalPackageUsageAvailable() { 988 return mIsHistoricalPackageUsageAvailable; 989 } 990 991 void write(boolean force) { 992 if (force) { 993 writeInternal(); 994 return; 995 } 996 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 997 && !DEBUG_DEXOPT) { 998 return; 999 } 1000 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1001 new Thread("PackageUsage_DiskWriter") { 1002 @Override 1003 public void run() { 1004 try { 1005 writeInternal(); 1006 } finally { 1007 mBackgroundWriteRunning.set(false); 1008 } 1009 } 1010 }.start(); 1011 } 1012 } 1013 1014 private void writeInternal() { 1015 synchronized (mPackages) { 1016 synchronized (mFileLock) { 1017 AtomicFile file = getFile(); 1018 FileOutputStream f = null; 1019 try { 1020 f = file.startWrite(); 1021 BufferedOutputStream out = new BufferedOutputStream(f); 1022 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1023 StringBuilder sb = new StringBuilder(); 1024 for (PackageParser.Package pkg : mPackages.values()) { 1025 if (pkg.mLastPackageUsageTimeInMills == 0) { 1026 continue; 1027 } 1028 sb.setLength(0); 1029 sb.append(pkg.packageName); 1030 sb.append(' '); 1031 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1032 sb.append('\n'); 1033 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1034 } 1035 out.flush(); 1036 file.finishWrite(f); 1037 } catch (IOException e) { 1038 if (f != null) { 1039 file.failWrite(f); 1040 } 1041 Log.e(TAG, "Failed to write package usage times", e); 1042 } 1043 } 1044 } 1045 mLastWritten.set(SystemClock.elapsedRealtime()); 1046 } 1047 1048 void readLP() { 1049 synchronized (mFileLock) { 1050 AtomicFile file = getFile(); 1051 BufferedInputStream in = null; 1052 try { 1053 in = new BufferedInputStream(file.openRead()); 1054 StringBuffer sb = new StringBuffer(); 1055 while (true) { 1056 String packageName = readToken(in, sb, ' '); 1057 if (packageName == null) { 1058 break; 1059 } 1060 String timeInMillisString = readToken(in, sb, '\n'); 1061 if (timeInMillisString == null) { 1062 throw new IOException("Failed to find last usage time for package " 1063 + packageName); 1064 } 1065 PackageParser.Package pkg = mPackages.get(packageName); 1066 if (pkg == null) { 1067 continue; 1068 } 1069 long timeInMillis; 1070 try { 1071 timeInMillis = Long.parseLong(timeInMillisString); 1072 } catch (NumberFormatException e) { 1073 throw new IOException("Failed to parse " + timeInMillisString 1074 + " as a long.", e); 1075 } 1076 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1077 } 1078 } catch (FileNotFoundException expected) { 1079 mIsHistoricalPackageUsageAvailable = false; 1080 } catch (IOException e) { 1081 Log.w(TAG, "Failed to read package usage times", e); 1082 } finally { 1083 IoUtils.closeQuietly(in); 1084 } 1085 } 1086 mLastWritten.set(SystemClock.elapsedRealtime()); 1087 } 1088 1089 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1090 throws IOException { 1091 sb.setLength(0); 1092 while (true) { 1093 int ch = in.read(); 1094 if (ch == -1) { 1095 if (sb.length() == 0) { 1096 return null; 1097 } 1098 throw new IOException("Unexpected EOF"); 1099 } 1100 if (ch == endOfToken) { 1101 return sb.toString(); 1102 } 1103 sb.append((char)ch); 1104 } 1105 } 1106 1107 private AtomicFile getFile() { 1108 File dataDir = Environment.getDataDirectory(); 1109 File systemDir = new File(dataDir, "system"); 1110 File fname = new File(systemDir, "package-usage.list"); 1111 return new AtomicFile(fname); 1112 } 1113 } 1114 1115 class PackageHandler extends Handler { 1116 private boolean mBound = false; 1117 final ArrayList<HandlerParams> mPendingInstalls = 1118 new ArrayList<HandlerParams>(); 1119 1120 private boolean connectToService() { 1121 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1122 " DefaultContainerService"); 1123 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1125 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1126 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1127 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1128 mBound = true; 1129 return true; 1130 } 1131 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1132 return false; 1133 } 1134 1135 private void disconnectService() { 1136 mContainerService = null; 1137 mBound = false; 1138 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1139 mContext.unbindService(mDefContainerConn); 1140 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1141 } 1142 1143 PackageHandler(Looper looper) { 1144 super(looper); 1145 } 1146 1147 public void handleMessage(Message msg) { 1148 try { 1149 doHandleMessage(msg); 1150 } finally { 1151 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1152 } 1153 } 1154 1155 void doHandleMessage(Message msg) { 1156 switch (msg.what) { 1157 case INIT_COPY: { 1158 HandlerParams params = (HandlerParams) msg.obj; 1159 int idx = mPendingInstalls.size(); 1160 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1161 // If a bind was already initiated we dont really 1162 // need to do anything. The pending install 1163 // will be processed later on. 1164 if (!mBound) { 1165 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1166 System.identityHashCode(mHandler)); 1167 // If this is the only one pending we might 1168 // have to bind to the service again. 1169 if (!connectToService()) { 1170 Slog.e(TAG, "Failed to bind to media container service"); 1171 params.serviceError(); 1172 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1173 System.identityHashCode(mHandler)); 1174 if (params.traceMethod != null) { 1175 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1176 params.traceCookie); 1177 } 1178 return; 1179 } else { 1180 // Once we bind to the service, the first 1181 // pending request will be processed. 1182 mPendingInstalls.add(idx, params); 1183 } 1184 } else { 1185 mPendingInstalls.add(idx, params); 1186 // Already bound to the service. Just make 1187 // sure we trigger off processing the first request. 1188 if (idx == 0) { 1189 mHandler.sendEmptyMessage(MCS_BOUND); 1190 } 1191 } 1192 break; 1193 } 1194 case MCS_BOUND: { 1195 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1196 if (msg.obj != null) { 1197 mContainerService = (IMediaContainerService) msg.obj; 1198 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1199 System.identityHashCode(mHandler)); 1200 } 1201 if (mContainerService == null) { 1202 if (!mBound) { 1203 // Something seriously wrong since we are not bound and we are not 1204 // waiting for connection. Bail out. 1205 Slog.e(TAG, "Cannot bind to media container service"); 1206 for (HandlerParams params : mPendingInstalls) { 1207 // Indicate service bind error 1208 params.serviceError(); 1209 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1210 System.identityHashCode(params)); 1211 if (params.traceMethod != null) { 1212 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1213 params.traceMethod, params.traceCookie); 1214 } 1215 return; 1216 } 1217 mPendingInstalls.clear(); 1218 } else { 1219 Slog.w(TAG, "Waiting to connect to media container service"); 1220 } 1221 } else if (mPendingInstalls.size() > 0) { 1222 HandlerParams params = mPendingInstalls.get(0); 1223 if (params != null) { 1224 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1225 System.identityHashCode(params)); 1226 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1227 if (params.startCopy()) { 1228 // We are done... look for more work or to 1229 // go idle. 1230 if (DEBUG_SD_INSTALL) Log.i(TAG, 1231 "Checking for more work or unbind..."); 1232 // Delete pending install 1233 if (mPendingInstalls.size() > 0) { 1234 mPendingInstalls.remove(0); 1235 } 1236 if (mPendingInstalls.size() == 0) { 1237 if (mBound) { 1238 if (DEBUG_SD_INSTALL) Log.i(TAG, 1239 "Posting delayed MCS_UNBIND"); 1240 removeMessages(MCS_UNBIND); 1241 Message ubmsg = obtainMessage(MCS_UNBIND); 1242 // Unbind after a little delay, to avoid 1243 // continual thrashing. 1244 sendMessageDelayed(ubmsg, 10000); 1245 } 1246 } else { 1247 // There are more pending requests in queue. 1248 // Just post MCS_BOUND message to trigger processing 1249 // of next pending install. 1250 if (DEBUG_SD_INSTALL) Log.i(TAG, 1251 "Posting MCS_BOUND for next work"); 1252 mHandler.sendEmptyMessage(MCS_BOUND); 1253 } 1254 } 1255 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1256 } 1257 } else { 1258 // Should never happen ideally. 1259 Slog.w(TAG, "Empty queue"); 1260 } 1261 break; 1262 } 1263 case MCS_RECONNECT: { 1264 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1265 if (mPendingInstalls.size() > 0) { 1266 if (mBound) { 1267 disconnectService(); 1268 } 1269 if (!connectToService()) { 1270 Slog.e(TAG, "Failed to bind to media container service"); 1271 for (HandlerParams params : mPendingInstalls) { 1272 // Indicate service bind error 1273 params.serviceError(); 1274 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1275 System.identityHashCode(params)); 1276 } 1277 mPendingInstalls.clear(); 1278 } 1279 } 1280 break; 1281 } 1282 case MCS_UNBIND: { 1283 // If there is no actual work left, then time to unbind. 1284 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1285 1286 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1287 if (mBound) { 1288 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1289 1290 disconnectService(); 1291 } 1292 } else if (mPendingInstalls.size() > 0) { 1293 // There are more pending requests in queue. 1294 // Just post MCS_BOUND message to trigger processing 1295 // of next pending install. 1296 mHandler.sendEmptyMessage(MCS_BOUND); 1297 } 1298 1299 break; 1300 } 1301 case MCS_GIVE_UP: { 1302 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1303 HandlerParams params = mPendingInstalls.remove(0); 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1305 System.identityHashCode(params)); 1306 break; 1307 } 1308 case SEND_PENDING_BROADCAST: { 1309 String packages[]; 1310 ArrayList<String> components[]; 1311 int size = 0; 1312 int uids[]; 1313 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1314 synchronized (mPackages) { 1315 if (mPendingBroadcasts == null) { 1316 return; 1317 } 1318 size = mPendingBroadcasts.size(); 1319 if (size <= 0) { 1320 // Nothing to be done. Just return 1321 return; 1322 } 1323 packages = new String[size]; 1324 components = new ArrayList[size]; 1325 uids = new int[size]; 1326 int i = 0; // filling out the above arrays 1327 1328 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1329 int packageUserId = mPendingBroadcasts.userIdAt(n); 1330 Iterator<Map.Entry<String, ArrayList<String>>> it 1331 = mPendingBroadcasts.packagesForUserId(packageUserId) 1332 .entrySet().iterator(); 1333 while (it.hasNext() && i < size) { 1334 Map.Entry<String, ArrayList<String>> ent = it.next(); 1335 packages[i] = ent.getKey(); 1336 components[i] = ent.getValue(); 1337 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1338 uids[i] = (ps != null) 1339 ? UserHandle.getUid(packageUserId, ps.appId) 1340 : -1; 1341 i++; 1342 } 1343 } 1344 size = i; 1345 mPendingBroadcasts.clear(); 1346 } 1347 // Send broadcasts 1348 for (int i = 0; i < size; i++) { 1349 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1350 } 1351 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1352 break; 1353 } 1354 case START_CLEANING_PACKAGE: { 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1356 final String packageName = (String)msg.obj; 1357 final int userId = msg.arg1; 1358 final boolean andCode = msg.arg2 != 0; 1359 synchronized (mPackages) { 1360 if (userId == UserHandle.USER_ALL) { 1361 int[] users = sUserManager.getUserIds(); 1362 for (int user : users) { 1363 mSettings.addPackageToCleanLPw( 1364 new PackageCleanItem(user, packageName, andCode)); 1365 } 1366 } else { 1367 mSettings.addPackageToCleanLPw( 1368 new PackageCleanItem(userId, packageName, andCode)); 1369 } 1370 } 1371 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1372 startCleaningPackages(); 1373 } break; 1374 case POST_INSTALL: { 1375 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1376 1377 PostInstallData data = mRunningInstalls.get(msg.arg1); 1378 mRunningInstalls.delete(msg.arg1); 1379 boolean deleteOld = false; 1380 1381 if (data != null) { 1382 InstallArgs args = data.args; 1383 PackageInstalledInfo res = data.res; 1384 1385 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1386 final String packageName = res.pkg.applicationInfo.packageName; 1387 res.removedInfo.sendBroadcast(false, true, false); 1388 Bundle extras = new Bundle(1); 1389 extras.putInt(Intent.EXTRA_UID, res.uid); 1390 1391 // Now that we successfully installed the package, grant runtime 1392 // permissions if requested before broadcasting the install. 1393 if ((args.installFlags 1394 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1395 && res.pkg.applicationInfo.targetSdkVersion 1396 >= Build.VERSION_CODES.M) { 1397 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1398 args.installGrantPermissions); 1399 } 1400 1401 synchronized (mPackages) { 1402 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1403 } 1404 1405 // Determine the set of users who are adding this 1406 // package for the first time vs. those who are seeing 1407 // an update. 1408 int[] firstUsers; 1409 int[] updateUsers = new int[0]; 1410 if (res.origUsers == null || res.origUsers.length == 0) { 1411 firstUsers = res.newUsers; 1412 } else { 1413 firstUsers = new int[0]; 1414 for (int i=0; i<res.newUsers.length; i++) { 1415 int user = res.newUsers[i]; 1416 boolean isNew = true; 1417 for (int j=0; j<res.origUsers.length; j++) { 1418 if (res.origUsers[j] == user) { 1419 isNew = false; 1420 break; 1421 } 1422 } 1423 if (isNew) { 1424 int[] newFirst = new int[firstUsers.length+1]; 1425 System.arraycopy(firstUsers, 0, newFirst, 0, 1426 firstUsers.length); 1427 newFirst[firstUsers.length] = user; 1428 firstUsers = newFirst; 1429 } else { 1430 int[] newUpdate = new int[updateUsers.length+1]; 1431 System.arraycopy(updateUsers, 0, newUpdate, 0, 1432 updateUsers.length); 1433 newUpdate[updateUsers.length] = user; 1434 updateUsers = newUpdate; 1435 } 1436 } 1437 } 1438 // don't broadcast for ephemeral installs/updates 1439 final boolean isEphemeral = isEphemeral(res.pkg); 1440 if (!isEphemeral) { 1441 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1442 extras, 0 /*flags*/, null /*targetPackage*/, 1443 null /*finishedReceiver*/, firstUsers); 1444 } 1445 final boolean update = res.removedInfo.removedPackage != null; 1446 if (update) { 1447 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1448 } 1449 if (!isEphemeral) { 1450 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1451 extras, 0 /*flags*/, null /*targetPackage*/, 1452 null /*finishedReceiver*/, updateUsers); 1453 } 1454 if (update) { 1455 if (!isEphemeral) { 1456 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1457 packageName, extras, 0 /*flags*/, 1458 null /*targetPackage*/, null /*finishedReceiver*/, 1459 updateUsers); 1460 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1461 null /*package*/, null /*extras*/, 0 /*flags*/, 1462 packageName /*targetPackage*/, 1463 null /*finishedReceiver*/, updateUsers); 1464 } 1465 1466 // treat asec-hosted packages like removable media on upgrade 1467 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1468 if (DEBUG_INSTALL) { 1469 Slog.i(TAG, "upgrading pkg " + res.pkg 1470 + " is ASEC-hosted -> AVAILABLE"); 1471 } 1472 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1473 ArrayList<String> pkgList = new ArrayList<String>(1); 1474 pkgList.add(packageName); 1475 sendResourcesChangedBroadcast(true, true, 1476 pkgList,uidArray, null); 1477 } 1478 } 1479 if (res.removedInfo.args != null) { 1480 // Remove the replaced package's older resources safely now 1481 deleteOld = true; 1482 } 1483 1484 // If this app is a browser and it's newly-installed for some 1485 // users, clear any default-browser state in those users 1486 if (firstUsers.length > 0) { 1487 // the app's nature doesn't depend on the user, so we can just 1488 // check its browser nature in any user and generalize. 1489 if (packageIsBrowser(packageName, firstUsers[0])) { 1490 synchronized (mPackages) { 1491 for (int userId : firstUsers) { 1492 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1493 } 1494 } 1495 } 1496 } 1497 // Log current value of "unknown sources" setting 1498 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1499 getUnknownSourcesSettings()); 1500 } 1501 // Force a gc to clear up things 1502 Runtime.getRuntime().gc(); 1503 // We delete after a gc for applications on sdcard. 1504 if (deleteOld) { 1505 synchronized (mInstallLock) { 1506 res.removedInfo.args.doPostDeleteLI(true); 1507 } 1508 } 1509 if (args.observer != null) { 1510 try { 1511 Bundle extras = extrasForInstallResult(res); 1512 args.observer.onPackageInstalled(res.name, res.returnCode, 1513 res.returnMsg, extras); 1514 } catch (RemoteException e) { 1515 Slog.i(TAG, "Observer no longer exists."); 1516 } 1517 } 1518 if (args.traceMethod != null) { 1519 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1520 args.traceCookie); 1521 } 1522 return; 1523 } else { 1524 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1525 } 1526 1527 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1528 } break; 1529 case UPDATED_MEDIA_STATUS: { 1530 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1531 boolean reportStatus = msg.arg1 == 1; 1532 boolean doGc = msg.arg2 == 1; 1533 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1534 if (doGc) { 1535 // Force a gc to clear up stale containers. 1536 Runtime.getRuntime().gc(); 1537 } 1538 if (msg.obj != null) { 1539 @SuppressWarnings("unchecked") 1540 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1541 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1542 // Unload containers 1543 unloadAllContainers(args); 1544 } 1545 if (reportStatus) { 1546 try { 1547 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1548 PackageHelper.getMountService().finishMediaUpdate(); 1549 } catch (RemoteException e) { 1550 Log.e(TAG, "MountService not running?"); 1551 } 1552 } 1553 } break; 1554 case WRITE_SETTINGS: { 1555 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1556 synchronized (mPackages) { 1557 removeMessages(WRITE_SETTINGS); 1558 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1559 mSettings.writeLPr(); 1560 mDirtyUsers.clear(); 1561 } 1562 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1563 } break; 1564 case WRITE_PACKAGE_RESTRICTIONS: { 1565 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1566 synchronized (mPackages) { 1567 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1568 for (int userId : mDirtyUsers) { 1569 mSettings.writePackageRestrictionsLPr(userId); 1570 } 1571 mDirtyUsers.clear(); 1572 } 1573 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1574 } break; 1575 case CHECK_PENDING_VERIFICATION: { 1576 final int verificationId = msg.arg1; 1577 final PackageVerificationState state = mPendingVerification.get(verificationId); 1578 1579 if ((state != null) && !state.timeoutExtended()) { 1580 final InstallArgs args = state.getInstallArgs(); 1581 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1582 1583 Slog.i(TAG, "Verification timed out for " + originUri); 1584 mPendingVerification.remove(verificationId); 1585 1586 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1587 1588 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1589 Slog.i(TAG, "Continuing with installation of " + originUri); 1590 state.setVerifierResponse(Binder.getCallingUid(), 1591 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1592 broadcastPackageVerified(verificationId, originUri, 1593 PackageManager.VERIFICATION_ALLOW, 1594 state.getInstallArgs().getUser()); 1595 try { 1596 ret = args.copyApk(mContainerService, true); 1597 } catch (RemoteException e) { 1598 Slog.e(TAG, "Could not contact the ContainerService"); 1599 } 1600 } else { 1601 broadcastPackageVerified(verificationId, originUri, 1602 PackageManager.VERIFICATION_REJECT, 1603 state.getInstallArgs().getUser()); 1604 } 1605 1606 Trace.asyncTraceEnd( 1607 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1608 1609 processPendingInstall(args, ret); 1610 mHandler.sendEmptyMessage(MCS_UNBIND); 1611 } 1612 break; 1613 } 1614 case PACKAGE_VERIFIED: { 1615 final int verificationId = msg.arg1; 1616 1617 final PackageVerificationState state = mPendingVerification.get(verificationId); 1618 if (state == null) { 1619 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1620 break; 1621 } 1622 1623 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1624 1625 state.setVerifierResponse(response.callerUid, response.code); 1626 1627 if (state.isVerificationComplete()) { 1628 mPendingVerification.remove(verificationId); 1629 1630 final InstallArgs args = state.getInstallArgs(); 1631 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1632 1633 int ret; 1634 if (state.isInstallAllowed()) { 1635 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1636 broadcastPackageVerified(verificationId, originUri, 1637 response.code, state.getInstallArgs().getUser()); 1638 try { 1639 ret = args.copyApk(mContainerService, true); 1640 } catch (RemoteException e) { 1641 Slog.e(TAG, "Could not contact the ContainerService"); 1642 } 1643 } else { 1644 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1645 } 1646 1647 Trace.asyncTraceEnd( 1648 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1649 1650 processPendingInstall(args, ret); 1651 mHandler.sendEmptyMessage(MCS_UNBIND); 1652 } 1653 1654 break; 1655 } 1656 case START_INTENT_FILTER_VERIFICATIONS: { 1657 IFVerificationParams params = (IFVerificationParams) msg.obj; 1658 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1659 params.replacing, params.pkg); 1660 break; 1661 } 1662 case INTENT_FILTER_VERIFIED: { 1663 final int verificationId = msg.arg1; 1664 1665 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1666 verificationId); 1667 if (state == null) { 1668 Slog.w(TAG, "Invalid IntentFilter verification token " 1669 + verificationId + " received"); 1670 break; 1671 } 1672 1673 final int userId = state.getUserId(); 1674 1675 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1676 "Processing IntentFilter verification with token:" 1677 + verificationId + " and userId:" + userId); 1678 1679 final IntentFilterVerificationResponse response = 1680 (IntentFilterVerificationResponse) msg.obj; 1681 1682 state.setVerifierResponse(response.callerUid, response.code); 1683 1684 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1685 "IntentFilter verification with token:" + verificationId 1686 + " and userId:" + userId 1687 + " is settings verifier response with response code:" 1688 + response.code); 1689 1690 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1691 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1692 + response.getFailedDomainsString()); 1693 } 1694 1695 if (state.isVerificationComplete()) { 1696 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1697 } else { 1698 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1699 "IntentFilter verification with token:" + verificationId 1700 + " was not said to be complete"); 1701 } 1702 1703 break; 1704 } 1705 } 1706 } 1707 } 1708 1709 private StorageEventListener mStorageListener = new StorageEventListener() { 1710 @Override 1711 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1712 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1713 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1714 final String volumeUuid = vol.getFsUuid(); 1715 1716 // Clean up any users or apps that were removed or recreated 1717 // while this volume was missing 1718 reconcileUsers(volumeUuid); 1719 reconcileApps(volumeUuid); 1720 1721 // Clean up any install sessions that expired or were 1722 // cancelled while this volume was missing 1723 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1724 1725 loadPrivatePackages(vol); 1726 1727 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1728 unloadPrivatePackages(vol); 1729 } 1730 } 1731 1732 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1733 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1734 updateExternalMediaStatus(true, false); 1735 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1736 updateExternalMediaStatus(false, false); 1737 } 1738 } 1739 } 1740 1741 @Override 1742 public void onVolumeForgotten(String fsUuid) { 1743 if (TextUtils.isEmpty(fsUuid)) { 1744 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1745 return; 1746 } 1747 1748 // Remove any apps installed on the forgotten volume 1749 synchronized (mPackages) { 1750 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1751 for (PackageSetting ps : packages) { 1752 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1753 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1754 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1755 } 1756 1757 mSettings.onVolumeForgotten(fsUuid); 1758 mSettings.writeLPr(); 1759 } 1760 } 1761 }; 1762 1763 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1764 String[] grantedPermissions) { 1765 if (userId >= UserHandle.USER_SYSTEM) { 1766 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1767 } else if (userId == UserHandle.USER_ALL) { 1768 final int[] userIds; 1769 synchronized (mPackages) { 1770 userIds = UserManagerService.getInstance().getUserIds(); 1771 } 1772 for (int someUserId : userIds) { 1773 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1774 } 1775 } 1776 1777 // We could have touched GID membership, so flush out packages.list 1778 synchronized (mPackages) { 1779 mSettings.writePackageListLPr(); 1780 } 1781 } 1782 1783 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1784 String[] grantedPermissions) { 1785 SettingBase sb = (SettingBase) pkg.mExtras; 1786 if (sb == null) { 1787 return; 1788 } 1789 1790 PermissionsState permissionsState = sb.getPermissionsState(); 1791 1792 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1793 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1794 1795 synchronized (mPackages) { 1796 for (String permission : pkg.requestedPermissions) { 1797 BasePermission bp = mSettings.mPermissions.get(permission); 1798 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1799 && (grantedPermissions == null 1800 || ArrayUtils.contains(grantedPermissions, permission))) { 1801 final int flags = permissionsState.getPermissionFlags(permission, userId); 1802 // Installer cannot change immutable permissions. 1803 if ((flags & immutableFlags) == 0) { 1804 grantRuntimePermission(pkg.packageName, permission, userId); 1805 } 1806 } 1807 } 1808 } 1809 } 1810 1811 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1812 Bundle extras = null; 1813 switch (res.returnCode) { 1814 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1815 extras = new Bundle(); 1816 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1817 res.origPermission); 1818 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1819 res.origPackage); 1820 break; 1821 } 1822 case PackageManager.INSTALL_SUCCEEDED: { 1823 extras = new Bundle(); 1824 extras.putBoolean(Intent.EXTRA_REPLACING, 1825 res.removedInfo != null && res.removedInfo.removedPackage != null); 1826 break; 1827 } 1828 } 1829 return extras; 1830 } 1831 1832 void scheduleWriteSettingsLocked() { 1833 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1834 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1835 } 1836 } 1837 1838 void scheduleWritePackageRestrictionsLocked(int userId) { 1839 if (!sUserManager.exists(userId)) return; 1840 mDirtyUsers.add(userId); 1841 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1842 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1843 } 1844 } 1845 1846 public static PackageManagerService main(Context context, Installer installer, 1847 boolean factoryTest, boolean onlyCore) { 1848 PackageManagerService m = new PackageManagerService(context, installer, 1849 factoryTest, onlyCore); 1850 m.enableSystemUserPackages(); 1851 ServiceManager.addService("package", m); 1852 return m; 1853 } 1854 1855 private void enableSystemUserPackages() { 1856 if (!UserManager.isSplitSystemUser()) { 1857 return; 1858 } 1859 // For system user, enable apps based on the following conditions: 1860 // - app is whitelisted or belong to one of these groups: 1861 // -- system app which has no launcher icons 1862 // -- system app which has INTERACT_ACROSS_USERS permission 1863 // -- system IME app 1864 // - app is not in the blacklist 1865 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1866 Set<String> enableApps = new ArraySet<>(); 1867 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1868 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1869 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1870 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1871 enableApps.addAll(wlApps); 1872 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1873 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1874 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1875 enableApps.removeAll(blApps); 1876 Log.i(TAG, "Applications installed for system user: " + enableApps); 1877 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1878 UserHandle.SYSTEM); 1879 final int allAppsSize = allAps.size(); 1880 synchronized (mPackages) { 1881 for (int i = 0; i < allAppsSize; i++) { 1882 String pName = allAps.get(i); 1883 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1884 // Should not happen, but we shouldn't be failing if it does 1885 if (pkgSetting == null) { 1886 continue; 1887 } 1888 boolean install = enableApps.contains(pName); 1889 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1890 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1891 + " for system user"); 1892 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1893 } 1894 } 1895 } 1896 } 1897 1898 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1899 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1900 Context.DISPLAY_SERVICE); 1901 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1902 } 1903 1904 public PackageManagerService(Context context, Installer installer, 1905 boolean factoryTest, boolean onlyCore) { 1906 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1907 SystemClock.uptimeMillis()); 1908 1909 if (mSdkVersion <= 0) { 1910 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1911 } 1912 1913 mContext = context; 1914 mFactoryTest = factoryTest; 1915 mOnlyCore = onlyCore; 1916 mMetrics = new DisplayMetrics(); 1917 mSettings = new Settings(mPackages); 1918 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1919 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1920 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1921 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1922 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1923 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1924 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1925 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1926 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1927 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1928 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1929 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1930 1931 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1932 if (separateProcesses != null && separateProcesses.length() > 0) { 1933 if ("*".equals(separateProcesses)) { 1934 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1935 mSeparateProcesses = null; 1936 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1937 } else { 1938 mDefParseFlags = 0; 1939 mSeparateProcesses = separateProcesses.split(","); 1940 Slog.w(TAG, "Running with debug.separate_processes: " 1941 + separateProcesses); 1942 } 1943 } else { 1944 mDefParseFlags = 0; 1945 mSeparateProcesses = null; 1946 } 1947 1948 mInstaller = installer; 1949 mPackageDexOptimizer = new PackageDexOptimizer(this); 1950 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1951 1952 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1953 FgThread.get().getLooper()); 1954 1955 getDefaultDisplayMetrics(context, mMetrics); 1956 1957 SystemConfig systemConfig = SystemConfig.getInstance(); 1958 mGlobalGids = systemConfig.getGlobalGids(); 1959 mSystemPermissions = systemConfig.getSystemPermissions(); 1960 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1961 1962 synchronized (mInstallLock) { 1963 // writer 1964 synchronized (mPackages) { 1965 mHandlerThread = new ServiceThread(TAG, 1966 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1967 mHandlerThread.start(); 1968 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1969 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1970 1971 File dataDir = Environment.getDataDirectory(); 1972 mAppInstallDir = new File(dataDir, "app"); 1973 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1974 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 1975 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1976 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1977 1978 sUserManager = new UserManagerService(context, this, mPackages); 1979 1980 // Propagate permission configuration in to package manager. 1981 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1982 = systemConfig.getPermissions(); 1983 for (int i=0; i<permConfig.size(); i++) { 1984 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1985 BasePermission bp = mSettings.mPermissions.get(perm.name); 1986 if (bp == null) { 1987 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1988 mSettings.mPermissions.put(perm.name, bp); 1989 } 1990 if (perm.gids != null) { 1991 bp.setGids(perm.gids, perm.perUser); 1992 } 1993 } 1994 1995 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1996 for (int i=0; i<libConfig.size(); i++) { 1997 mSharedLibraries.put(libConfig.keyAt(i), 1998 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1999 } 2000 2001 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2002 2003 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2004 2005 String customResolverActivity = Resources.getSystem().getString( 2006 R.string.config_customResolverActivity); 2007 if (TextUtils.isEmpty(customResolverActivity)) { 2008 customResolverActivity = null; 2009 } else { 2010 mCustomResolverComponentName = ComponentName.unflattenFromString( 2011 customResolverActivity); 2012 } 2013 2014 long startTime = SystemClock.uptimeMillis(); 2015 2016 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2017 startTime); 2018 2019 // Set flag to monitor and not change apk file paths when 2020 // scanning install directories. 2021 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2022 2023 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2024 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2025 2026 if (bootClassPath == null) { 2027 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2028 } 2029 2030 if (systemServerClassPath == null) { 2031 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2032 } 2033 2034 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2035 final String[] dexCodeInstructionSets = 2036 getDexCodeInstructionSets( 2037 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2038 2039 /** 2040 * Ensure all external libraries have had dexopt run on them. 2041 */ 2042 if (mSharedLibraries.size() > 0) { 2043 // NOTE: For now, we're compiling these system "shared libraries" 2044 // (and framework jars) into all available architectures. It's possible 2045 // to compile them only when we come across an app that uses them (there's 2046 // already logic for that in scanPackageLI) but that adds some complexity. 2047 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2048 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2049 final String lib = libEntry.path; 2050 if (lib == null) { 2051 continue; 2052 } 2053 2054 try { 2055 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2056 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2057 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2058 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2059 } 2060 } catch (FileNotFoundException e) { 2061 Slog.w(TAG, "Library not found: " + lib); 2062 } catch (IOException e) { 2063 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2064 + e.getMessage()); 2065 } 2066 } 2067 } 2068 } 2069 2070 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2071 2072 final VersionInfo ver = mSettings.getInternalVersion(); 2073 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2074 // when upgrading from pre-M, promote system app permissions from install to runtime 2075 mPromoteSystemApps = 2076 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2077 2078 // save off the names of pre-existing system packages prior to scanning; we don't 2079 // want to automatically grant runtime permissions for new system apps 2080 if (mPromoteSystemApps) { 2081 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2082 while (pkgSettingIter.hasNext()) { 2083 PackageSetting ps = pkgSettingIter.next(); 2084 if (isSystemApp(ps)) { 2085 mExistingSystemPackages.add(ps.name); 2086 } 2087 } 2088 } 2089 2090 // Collect vendor overlay packages. 2091 // (Do this before scanning any apps.) 2092 // For security and version matching reason, only consider 2093 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2094 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2095 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2096 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2097 2098 // Find base frameworks (resource packages without code). 2099 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2100 | PackageParser.PARSE_IS_SYSTEM_DIR 2101 | PackageParser.PARSE_IS_PRIVILEGED, 2102 scanFlags | SCAN_NO_DEX, 0); 2103 2104 // Collected privileged system packages. 2105 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2106 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2107 | PackageParser.PARSE_IS_SYSTEM_DIR 2108 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2109 2110 // Collect ordinary system packages. 2111 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2112 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2113 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2114 2115 // Collect all vendor packages. 2116 File vendorAppDir = new File("/vendor/app"); 2117 try { 2118 vendorAppDir = vendorAppDir.getCanonicalFile(); 2119 } catch (IOException e) { 2120 // failed to look up canonical path, continue with original one 2121 } 2122 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2123 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2124 2125 // Collect all OEM packages. 2126 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2127 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2128 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2129 2130 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2131 mInstaller.moveFiles(); 2132 2133 // Prune any system packages that no longer exist. 2134 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2135 if (!mOnlyCore) { 2136 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2137 while (psit.hasNext()) { 2138 PackageSetting ps = psit.next(); 2139 2140 /* 2141 * If this is not a system app, it can't be a 2142 * disable system app. 2143 */ 2144 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2145 continue; 2146 } 2147 2148 /* 2149 * If the package is scanned, it's not erased. 2150 */ 2151 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2152 if (scannedPkg != null) { 2153 /* 2154 * If the system app is both scanned and in the 2155 * disabled packages list, then it must have been 2156 * added via OTA. Remove it from the currently 2157 * scanned package so the previously user-installed 2158 * application can be scanned. 2159 */ 2160 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2161 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2162 + ps.name + "; removing system app. Last known codePath=" 2163 + ps.codePathString + ", installStatus=" + ps.installStatus 2164 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2165 + scannedPkg.mVersionCode); 2166 removePackageLI(ps, true); 2167 mExpectingBetter.put(ps.name, ps.codePath); 2168 } 2169 2170 continue; 2171 } 2172 2173 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2174 psit.remove(); 2175 logCriticalInfo(Log.WARN, "System package " + ps.name 2176 + " no longer exists; wiping its data"); 2177 removeDataDirsLI(null, ps.name); 2178 } else { 2179 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2180 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2181 possiblyDeletedUpdatedSystemApps.add(ps.name); 2182 } 2183 } 2184 } 2185 } 2186 2187 //look for any incomplete package installations 2188 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2189 //clean up list 2190 for(int i = 0; i < deletePkgsList.size(); i++) { 2191 //clean up here 2192 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2193 } 2194 //delete tmp files 2195 deleteTempPackageFiles(); 2196 2197 // Remove any shared userIDs that have no associated packages 2198 mSettings.pruneSharedUsersLPw(); 2199 2200 if (!mOnlyCore) { 2201 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2202 SystemClock.uptimeMillis()); 2203 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2204 2205 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2206 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2207 2208 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2209 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2210 2211 /** 2212 * Remove disable package settings for any updated system 2213 * apps that were removed via an OTA. If they're not a 2214 * previously-updated app, remove them completely. 2215 * Otherwise, just revoke their system-level permissions. 2216 */ 2217 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2218 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2219 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2220 2221 String msg; 2222 if (deletedPkg == null) { 2223 msg = "Updated system package " + deletedAppName 2224 + " no longer exists; wiping its data"; 2225 removeDataDirsLI(null, deletedAppName); 2226 } else { 2227 msg = "Updated system app + " + deletedAppName 2228 + " no longer present; removing system privileges for " 2229 + deletedAppName; 2230 2231 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2232 2233 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2234 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2235 } 2236 logCriticalInfo(Log.WARN, msg); 2237 } 2238 2239 /** 2240 * Make sure all system apps that we expected to appear on 2241 * the userdata partition actually showed up. If they never 2242 * appeared, crawl back and revive the system version. 2243 */ 2244 for (int i = 0; i < mExpectingBetter.size(); i++) { 2245 final String packageName = mExpectingBetter.keyAt(i); 2246 if (!mPackages.containsKey(packageName)) { 2247 final File scanFile = mExpectingBetter.valueAt(i); 2248 2249 logCriticalInfo(Log.WARN, "Expected better " + packageName 2250 + " but never showed up; reverting to system"); 2251 2252 final int reparseFlags; 2253 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2254 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2255 | PackageParser.PARSE_IS_SYSTEM_DIR 2256 | PackageParser.PARSE_IS_PRIVILEGED; 2257 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2258 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2259 | PackageParser.PARSE_IS_SYSTEM_DIR; 2260 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2261 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2262 | PackageParser.PARSE_IS_SYSTEM_DIR; 2263 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2264 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2265 | PackageParser.PARSE_IS_SYSTEM_DIR; 2266 } else { 2267 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2268 continue; 2269 } 2270 2271 mSettings.enableSystemPackageLPw(packageName); 2272 2273 try { 2274 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2275 } catch (PackageManagerException e) { 2276 Slog.e(TAG, "Failed to parse original system package: " 2277 + e.getMessage()); 2278 } 2279 } 2280 } 2281 } 2282 mExpectingBetter.clear(); 2283 2284 // Now that we know all of the shared libraries, update all clients to have 2285 // the correct library paths. 2286 updateAllSharedLibrariesLPw(); 2287 2288 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2289 // NOTE: We ignore potential failures here during a system scan (like 2290 // the rest of the commands above) because there's precious little we 2291 // can do about it. A settings error is reported, though. 2292 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2293 false /* boot complete */); 2294 } 2295 2296 // Now that we know all the packages we are keeping, 2297 // read and update their last usage times. 2298 mPackageUsage.readLP(); 2299 2300 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2301 SystemClock.uptimeMillis()); 2302 Slog.i(TAG, "Time to scan packages: " 2303 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2304 + " seconds"); 2305 2306 // If the platform SDK has changed since the last time we booted, 2307 // we need to re-grant app permission to catch any new ones that 2308 // appear. This is really a hack, and means that apps can in some 2309 // cases get permissions that the user didn't initially explicitly 2310 // allow... it would be nice to have some better way to handle 2311 // this situation. 2312 int updateFlags = UPDATE_PERMISSIONS_ALL; 2313 if (ver.sdkVersion != mSdkVersion) { 2314 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2315 + mSdkVersion + "; regranting permissions for internal storage"); 2316 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2317 } 2318 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2319 ver.sdkVersion = mSdkVersion; 2320 2321 // If this is the first boot or an update from pre-M, and it is a normal 2322 // boot, then we need to initialize the default preferred apps across 2323 // all defined users. 2324 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2325 for (UserInfo user : sUserManager.getUsers(true)) { 2326 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2327 applyFactoryDefaultBrowserLPw(user.id); 2328 primeDomainVerificationsLPw(user.id); 2329 } 2330 } 2331 2332 // If this is first boot after an OTA, and a normal boot, then 2333 // we need to clear code cache directories. 2334 if (mIsUpgrade && !onlyCore) { 2335 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2336 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2337 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2338 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2339 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2340 } 2341 } 2342 ver.fingerprint = Build.FINGERPRINT; 2343 } 2344 2345 checkDefaultBrowser(); 2346 2347 // clear only after permissions and other defaults have been updated 2348 mExistingSystemPackages.clear(); 2349 mPromoteSystemApps = false; 2350 2351 // All the changes are done during package scanning. 2352 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2353 2354 // can downgrade to reader 2355 mSettings.writeLPr(); 2356 2357 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2358 SystemClock.uptimeMillis()); 2359 2360 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2361 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2362 2363 mInstallerService = new PackageInstallerService(context, this); 2364 2365 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2366 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2367 mIntentFilterVerifierComponent); 2368 2369 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2370 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2371 // both the installer and resolver must be present to enable ephemeral 2372 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2373 if (DEBUG_EPHEMERAL) { 2374 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2375 + " installer:" + ephemeralInstallerComponent); 2376 } 2377 mEphemeralResolverComponent = ephemeralResolverComponent; 2378 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2379 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2380 mEphemeralResolverConnection = 2381 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2382 } else { 2383 if (DEBUG_EPHEMERAL) { 2384 final String missingComponent = 2385 (ephemeralResolverComponent == null) 2386 ? (ephemeralInstallerComponent == null) 2387 ? "resolver and installer" 2388 : "resolver" 2389 : "installer"; 2390 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2391 } 2392 mEphemeralResolverComponent = null; 2393 mEphemeralInstallerComponent = null; 2394 mEphemeralResolverConnection = null; 2395 } 2396 2397 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2398 } // synchronized (mPackages) 2399 } // synchronized (mInstallLock) 2400 2401 // Now after opening every single application zip, make sure they 2402 // are all flushed. Not really needed, but keeps things nice and 2403 // tidy. 2404 Runtime.getRuntime().gc(); 2405 2406 // The initial scanning above does many calls into installd while 2407 // holding the mPackages lock, but we're mostly interested in yelling 2408 // once we have a booted system. 2409 mInstaller.setWarnIfHeld(mPackages); 2410 2411 // Expose private service for system components to use. 2412 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2413 } 2414 2415 @Override 2416 public boolean isFirstBoot() { 2417 return !mRestoredSettings; 2418 } 2419 2420 @Override 2421 public boolean isOnlyCoreApps() { 2422 return mOnlyCore; 2423 } 2424 2425 @Override 2426 public boolean isUpgrade() { 2427 return mIsUpgrade; 2428 } 2429 2430 private String getRequiredVerifierLPr() { 2431 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2432 // We only care about verifier that's installed under system user. 2433 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2434 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2435 2436 String requiredVerifier = null; 2437 2438 final int N = receivers.size(); 2439 for (int i = 0; i < N; i++) { 2440 final ResolveInfo info = receivers.get(i); 2441 2442 if (info.activityInfo == null) { 2443 continue; 2444 } 2445 2446 final String packageName = info.activityInfo.packageName; 2447 2448 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2449 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2450 continue; 2451 } 2452 2453 if (requiredVerifier != null) { 2454 throw new RuntimeException("There can be only one required verifier"); 2455 } 2456 2457 requiredVerifier = packageName; 2458 } 2459 2460 return requiredVerifier; 2461 } 2462 2463 private String getRequiredInstallerLPr() { 2464 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2465 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2466 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2467 2468 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2469 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2470 2471 String requiredInstaller = null; 2472 2473 final int N = installers.size(); 2474 for (int i = 0; i < N; i++) { 2475 final ResolveInfo info = installers.get(i); 2476 final String packageName = info.activityInfo.packageName; 2477 2478 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2479 continue; 2480 } 2481 2482 if (requiredInstaller != null) { 2483 throw new RuntimeException("There must be one required installer"); 2484 } 2485 2486 requiredInstaller = packageName; 2487 } 2488 2489 if (requiredInstaller == null) { 2490 throw new RuntimeException("There must be one required installer"); 2491 } 2492 2493 return requiredInstaller; 2494 } 2495 2496 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2497 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2498 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2499 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2500 2501 ComponentName verifierComponentName = null; 2502 2503 int priority = -1000; 2504 final int N = receivers.size(); 2505 for (int i = 0; i < N; i++) { 2506 final ResolveInfo info = receivers.get(i); 2507 2508 if (info.activityInfo == null) { 2509 continue; 2510 } 2511 2512 final String packageName = info.activityInfo.packageName; 2513 2514 final PackageSetting ps = mSettings.mPackages.get(packageName); 2515 if (ps == null) { 2516 continue; 2517 } 2518 2519 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2520 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2521 continue; 2522 } 2523 2524 // Select the IntentFilterVerifier with the highest priority 2525 if (priority < info.priority) { 2526 priority = info.priority; 2527 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2528 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2529 + verifierComponentName + " with priority: " + info.priority); 2530 } 2531 } 2532 2533 return verifierComponentName; 2534 } 2535 2536 private ComponentName getEphemeralResolverLPr() { 2537 final String[] packageArray = 2538 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2539 if (packageArray.length == 0) { 2540 if (DEBUG_EPHEMERAL) { 2541 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2542 } 2543 return null; 2544 } 2545 2546 Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2547 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, 2548 null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM); 2549 2550 final int N = resolvers.size(); 2551 if (N == 0) { 2552 if (DEBUG_EPHEMERAL) { 2553 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2554 } 2555 return null; 2556 } 2557 2558 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2559 for (int i = 0; i < N; i++) { 2560 final ResolveInfo info = resolvers.get(i); 2561 2562 if (info.serviceInfo == null) { 2563 continue; 2564 } 2565 2566 final String packageName = info.serviceInfo.packageName; 2567 if (!possiblePackages.contains(packageName)) { 2568 if (DEBUG_EPHEMERAL) { 2569 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2570 + " pkg: " + packageName + ", info:" + info); 2571 } 2572 continue; 2573 } 2574 2575 if (DEBUG_EPHEMERAL) { 2576 Slog.v(TAG, "Ephemeral resolver found;" 2577 + " pkg: " + packageName + ", info:" + info); 2578 } 2579 return new ComponentName(packageName, info.serviceInfo.name); 2580 } 2581 if (DEBUG_EPHEMERAL) { 2582 Slog.v(TAG, "Ephemeral resolver NOT found"); 2583 } 2584 return null; 2585 } 2586 2587 private ComponentName getEphemeralInstallerLPr() { 2588 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2589 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2590 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2591 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2592 PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/); 2593 2594 ComponentName ephemeralInstaller = null; 2595 2596 final int N = installers.size(); 2597 for (int i = 0; i < N; i++) { 2598 final ResolveInfo info = installers.get(i); 2599 final String packageName = info.activityInfo.packageName; 2600 2601 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2602 if (DEBUG_EPHEMERAL) { 2603 Slog.d(TAG, "Ephemeral installer is not system app;" 2604 + " pkg: " + packageName + ", info:" + info); 2605 } 2606 continue; 2607 } 2608 2609 if (ephemeralInstaller != null) { 2610 throw new RuntimeException("There must only be one ephemeral installer"); 2611 } 2612 2613 ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name); 2614 } 2615 2616 return ephemeralInstaller; 2617 } 2618 2619 private void primeDomainVerificationsLPw(int userId) { 2620 if (DEBUG_DOMAIN_VERIFICATION) { 2621 Slog.d(TAG, "Priming domain verifications in user " + userId); 2622 } 2623 2624 SystemConfig systemConfig = SystemConfig.getInstance(); 2625 ArraySet<String> packages = systemConfig.getLinkedApps(); 2626 ArraySet<String> domains = new ArraySet<String>(); 2627 2628 for (String packageName : packages) { 2629 PackageParser.Package pkg = mPackages.get(packageName); 2630 if (pkg != null) { 2631 if (!pkg.isSystemApp()) { 2632 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2633 continue; 2634 } 2635 2636 domains.clear(); 2637 for (PackageParser.Activity a : pkg.activities) { 2638 for (ActivityIntentInfo filter : a.intents) { 2639 if (hasValidDomains(filter)) { 2640 domains.addAll(filter.getHostsList()); 2641 } 2642 } 2643 } 2644 2645 if (domains.size() > 0) { 2646 if (DEBUG_DOMAIN_VERIFICATION) { 2647 Slog.v(TAG, " + " + packageName); 2648 } 2649 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2650 // state w.r.t. the formal app-linkage "no verification attempted" state; 2651 // and then 'always' in the per-user state actually used for intent resolution. 2652 final IntentFilterVerificationInfo ivi; 2653 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2654 new ArrayList<String>(domains)); 2655 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2656 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2657 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2658 } else { 2659 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2660 + "' does not handle web links"); 2661 } 2662 } else { 2663 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2664 } 2665 } 2666 2667 scheduleWritePackageRestrictionsLocked(userId); 2668 scheduleWriteSettingsLocked(); 2669 } 2670 2671 private void applyFactoryDefaultBrowserLPw(int userId) { 2672 // The default browser app's package name is stored in a string resource, 2673 // with a product-specific overlay used for vendor customization. 2674 String browserPkg = mContext.getResources().getString( 2675 com.android.internal.R.string.default_browser); 2676 if (!TextUtils.isEmpty(browserPkg)) { 2677 // non-empty string => required to be a known package 2678 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2679 if (ps == null) { 2680 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2681 browserPkg = null; 2682 } else { 2683 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2684 } 2685 } 2686 2687 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2688 // default. If there's more than one, just leave everything alone. 2689 if (browserPkg == null) { 2690 calculateDefaultBrowserLPw(userId); 2691 } 2692 } 2693 2694 private void calculateDefaultBrowserLPw(int userId) { 2695 List<String> allBrowsers = resolveAllBrowserApps(userId); 2696 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2697 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2698 } 2699 2700 private List<String> resolveAllBrowserApps(int userId) { 2701 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2702 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2703 PackageManager.MATCH_ALL, userId); 2704 2705 final int count = list.size(); 2706 List<String> result = new ArrayList<String>(count); 2707 for (int i=0; i<count; i++) { 2708 ResolveInfo info = list.get(i); 2709 if (info.activityInfo == null 2710 || !info.handleAllWebDataURI 2711 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2712 || result.contains(info.activityInfo.packageName)) { 2713 continue; 2714 } 2715 result.add(info.activityInfo.packageName); 2716 } 2717 2718 return result; 2719 } 2720 2721 private boolean packageIsBrowser(String packageName, int userId) { 2722 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2723 PackageManager.MATCH_ALL, userId); 2724 final int N = list.size(); 2725 for (int i = 0; i < N; i++) { 2726 ResolveInfo info = list.get(i); 2727 if (packageName.equals(info.activityInfo.packageName)) { 2728 return true; 2729 } 2730 } 2731 return false; 2732 } 2733 2734 private void checkDefaultBrowser() { 2735 final int myUserId = UserHandle.myUserId(); 2736 final String packageName = getDefaultBrowserPackageName(myUserId); 2737 if (packageName != null) { 2738 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2739 if (info == null) { 2740 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2741 synchronized (mPackages) { 2742 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2743 } 2744 } 2745 } 2746 } 2747 2748 @Override 2749 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2750 throws RemoteException { 2751 try { 2752 return super.onTransact(code, data, reply, flags); 2753 } catch (RuntimeException e) { 2754 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2755 Slog.wtf(TAG, "Package Manager Crash", e); 2756 } 2757 throw e; 2758 } 2759 } 2760 2761 void cleanupInstallFailedPackage(PackageSetting ps) { 2762 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2763 2764 removeDataDirsLI(ps.volumeUuid, ps.name); 2765 if (ps.codePath != null) { 2766 if (ps.codePath.isDirectory()) { 2767 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2768 } else { 2769 ps.codePath.delete(); 2770 } 2771 } 2772 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2773 if (ps.resourcePath.isDirectory()) { 2774 FileUtils.deleteContents(ps.resourcePath); 2775 } 2776 ps.resourcePath.delete(); 2777 } 2778 mSettings.removePackageLPw(ps.name); 2779 } 2780 2781 static int[] appendInts(int[] cur, int[] add) { 2782 if (add == null) return cur; 2783 if (cur == null) return add; 2784 final int N = add.length; 2785 for (int i=0; i<N; i++) { 2786 cur = appendInt(cur, add[i]); 2787 } 2788 return cur; 2789 } 2790 2791 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2792 if (!sUserManager.exists(userId)) return null; 2793 final PackageSetting ps = (PackageSetting) p.mExtras; 2794 if (ps == null) { 2795 return null; 2796 } 2797 2798 final PermissionsState permissionsState = ps.getPermissionsState(); 2799 2800 final int[] gids = permissionsState.computeGids(userId); 2801 final Set<String> permissions = permissionsState.getPermissions(userId); 2802 final PackageUserState state = ps.readUserState(userId); 2803 2804 return PackageParser.generatePackageInfo(p, gids, flags, 2805 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2806 } 2807 2808 @Override 2809 public void checkPackageStartable(String packageName, int userId) { 2810 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2811 2812 synchronized (mPackages) { 2813 final PackageSetting ps = mSettings.mPackages.get(packageName); 2814 if (ps == null) { 2815 throw new SecurityException("Package " + packageName + " was not found!"); 2816 } 2817 2818 if (ps.frozen) { 2819 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2820 } 2821 2822 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2823 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2824 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2825 } 2826 } 2827 } 2828 2829 @Override 2830 public boolean isPackageAvailable(String packageName, int userId) { 2831 if (!sUserManager.exists(userId)) return false; 2832 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2833 synchronized (mPackages) { 2834 PackageParser.Package p = mPackages.get(packageName); 2835 if (p != null) { 2836 final PackageSetting ps = (PackageSetting) p.mExtras; 2837 if (ps != null) { 2838 final PackageUserState state = ps.readUserState(userId); 2839 if (state != null) { 2840 return PackageParser.isAvailable(state); 2841 } 2842 } 2843 } 2844 } 2845 return false; 2846 } 2847 2848 @Override 2849 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2850 if (!sUserManager.exists(userId)) return null; 2851 flags = updateFlagsForPackage(flags, userId, packageName); 2852 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2853 // reader 2854 synchronized (mPackages) { 2855 PackageParser.Package p = mPackages.get(packageName); 2856 if (DEBUG_PACKAGE_INFO) 2857 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2858 if (p != null) { 2859 return generatePackageInfo(p, flags, userId); 2860 } 2861 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2862 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2863 } 2864 } 2865 return null; 2866 } 2867 2868 @Override 2869 public String[] currentToCanonicalPackageNames(String[] names) { 2870 String[] out = new String[names.length]; 2871 // reader 2872 synchronized (mPackages) { 2873 for (int i=names.length-1; i>=0; i--) { 2874 PackageSetting ps = mSettings.mPackages.get(names[i]); 2875 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2876 } 2877 } 2878 return out; 2879 } 2880 2881 @Override 2882 public String[] canonicalToCurrentPackageNames(String[] names) { 2883 String[] out = new String[names.length]; 2884 // reader 2885 synchronized (mPackages) { 2886 for (int i=names.length-1; i>=0; i--) { 2887 String cur = mSettings.mRenamedPackages.get(names[i]); 2888 out[i] = cur != null ? cur : names[i]; 2889 } 2890 } 2891 return out; 2892 } 2893 2894 @Override 2895 public int getPackageUid(String packageName, int userId) { 2896 return getPackageUidEtc(packageName, 0, userId); 2897 } 2898 2899 @Override 2900 public int getPackageUidEtc(String packageName, int flags, int userId) { 2901 if (!sUserManager.exists(userId)) return -1; 2902 flags = updateFlagsForPackage(flags, userId, packageName); 2903 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2904 2905 // reader 2906 synchronized (mPackages) { 2907 final PackageParser.Package p = mPackages.get(packageName); 2908 if (p != null) { 2909 return UserHandle.getUid(userId, p.applicationInfo.uid); 2910 } 2911 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2912 final PackageSetting ps = mSettings.mPackages.get(packageName); 2913 if (ps != null) { 2914 return UserHandle.getUid(userId, ps.appId); 2915 } 2916 } 2917 } 2918 2919 return -1; 2920 } 2921 2922 @Override 2923 public int[] getPackageGids(String packageName, int userId) { 2924 return getPackageGidsEtc(packageName, 0, userId); 2925 } 2926 2927 @Override 2928 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2929 if (!sUserManager.exists(userId)) return null; 2930 flags = updateFlagsForPackage(flags, userId, packageName); 2931 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2932 "getPackageGids"); 2933 2934 // reader 2935 synchronized (mPackages) { 2936 final PackageParser.Package p = mPackages.get(packageName); 2937 if (p != null) { 2938 PackageSetting ps = (PackageSetting) p.mExtras; 2939 return ps.getPermissionsState().computeGids(userId); 2940 } 2941 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2942 final PackageSetting ps = mSettings.mPackages.get(packageName); 2943 if (ps != null) { 2944 return ps.getPermissionsState().computeGids(userId); 2945 } 2946 } 2947 } 2948 2949 return null; 2950 } 2951 2952 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2953 if (bp.perm != null) { 2954 return PackageParser.generatePermissionInfo(bp.perm, flags); 2955 } 2956 PermissionInfo pi = new PermissionInfo(); 2957 pi.name = bp.name; 2958 pi.packageName = bp.sourcePackage; 2959 pi.nonLocalizedLabel = bp.name; 2960 pi.protectionLevel = bp.protectionLevel; 2961 return pi; 2962 } 2963 2964 @Override 2965 public PermissionInfo getPermissionInfo(String name, int flags) { 2966 // reader 2967 synchronized (mPackages) { 2968 final BasePermission p = mSettings.mPermissions.get(name); 2969 if (p != null) { 2970 return generatePermissionInfo(p, flags); 2971 } 2972 return null; 2973 } 2974 } 2975 2976 @Override 2977 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2978 // reader 2979 synchronized (mPackages) { 2980 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2981 for (BasePermission p : mSettings.mPermissions.values()) { 2982 if (group == null) { 2983 if (p.perm == null || p.perm.info.group == null) { 2984 out.add(generatePermissionInfo(p, flags)); 2985 } 2986 } else { 2987 if (p.perm != null && group.equals(p.perm.info.group)) { 2988 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2989 } 2990 } 2991 } 2992 2993 if (out.size() > 0) { 2994 return out; 2995 } 2996 return mPermissionGroups.containsKey(group) ? out : null; 2997 } 2998 } 2999 3000 @Override 3001 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3002 // reader 3003 synchronized (mPackages) { 3004 return PackageParser.generatePermissionGroupInfo( 3005 mPermissionGroups.get(name), flags); 3006 } 3007 } 3008 3009 @Override 3010 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3011 // reader 3012 synchronized (mPackages) { 3013 final int N = mPermissionGroups.size(); 3014 ArrayList<PermissionGroupInfo> out 3015 = new ArrayList<PermissionGroupInfo>(N); 3016 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3017 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3018 } 3019 return out; 3020 } 3021 } 3022 3023 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3024 int userId) { 3025 if (!sUserManager.exists(userId)) return null; 3026 PackageSetting ps = mSettings.mPackages.get(packageName); 3027 if (ps != null) { 3028 if (ps.pkg == null) { 3029 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3030 flags, userId); 3031 if (pInfo != null) { 3032 return pInfo.applicationInfo; 3033 } 3034 return null; 3035 } 3036 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3037 ps.readUserState(userId), userId); 3038 } 3039 return null; 3040 } 3041 3042 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3043 int userId) { 3044 if (!sUserManager.exists(userId)) return null; 3045 PackageSetting ps = mSettings.mPackages.get(packageName); 3046 if (ps != null) { 3047 PackageParser.Package pkg = ps.pkg; 3048 if (pkg == null) { 3049 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 3050 return null; 3051 } 3052 // Only data remains, so we aren't worried about code paths 3053 pkg = new PackageParser.Package(packageName); 3054 pkg.applicationInfo.packageName = packageName; 3055 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3056 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3057 pkg.applicationInfo.uid = ps.appId; 3058 pkg.applicationInfo.initForUser(userId); 3059 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3060 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3061 } 3062 return generatePackageInfo(pkg, flags, userId); 3063 } 3064 return null; 3065 } 3066 3067 @Override 3068 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3069 if (!sUserManager.exists(userId)) return null; 3070 flags = updateFlagsForApplication(flags, userId, packageName); 3071 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3072 // writer 3073 synchronized (mPackages) { 3074 PackageParser.Package p = mPackages.get(packageName); 3075 if (DEBUG_PACKAGE_INFO) Log.v( 3076 TAG, "getApplicationInfo " + packageName 3077 + ": " + p); 3078 if (p != null) { 3079 PackageSetting ps = mSettings.mPackages.get(packageName); 3080 if (ps == null) return null; 3081 // Note: isEnabledLP() does not apply here - always return info 3082 return PackageParser.generateApplicationInfo( 3083 p, flags, ps.readUserState(userId), userId); 3084 } 3085 if ("android".equals(packageName)||"system".equals(packageName)) { 3086 return mAndroidApplication; 3087 } 3088 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 3089 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3090 } 3091 } 3092 return null; 3093 } 3094 3095 @Override 3096 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3097 final IPackageDataObserver observer) { 3098 mContext.enforceCallingOrSelfPermission( 3099 android.Manifest.permission.CLEAR_APP_CACHE, null); 3100 // Queue up an async operation since clearing cache may take a little while. 3101 mHandler.post(new Runnable() { 3102 public void run() { 3103 mHandler.removeCallbacks(this); 3104 int retCode = -1; 3105 synchronized (mInstallLock) { 3106 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3107 if (retCode < 0) { 3108 Slog.w(TAG, "Couldn't clear application caches"); 3109 } 3110 } 3111 if (observer != null) { 3112 try { 3113 observer.onRemoveCompleted(null, (retCode >= 0)); 3114 } catch (RemoteException e) { 3115 Slog.w(TAG, "RemoveException when invoking call back"); 3116 } 3117 } 3118 } 3119 }); 3120 } 3121 3122 @Override 3123 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3124 final IntentSender pi) { 3125 mContext.enforceCallingOrSelfPermission( 3126 android.Manifest.permission.CLEAR_APP_CACHE, null); 3127 // Queue up an async operation since clearing cache may take a little while. 3128 mHandler.post(new Runnable() { 3129 public void run() { 3130 mHandler.removeCallbacks(this); 3131 int retCode = -1; 3132 synchronized (mInstallLock) { 3133 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3134 if (retCode < 0) { 3135 Slog.w(TAG, "Couldn't clear application caches"); 3136 } 3137 } 3138 if(pi != null) { 3139 try { 3140 // Callback via pending intent 3141 int code = (retCode >= 0) ? 1 : 0; 3142 pi.sendIntent(null, code, null, 3143 null, null); 3144 } catch (SendIntentException e1) { 3145 Slog.i(TAG, "Failed to send pending intent"); 3146 } 3147 } 3148 } 3149 }); 3150 } 3151 3152 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3153 synchronized (mInstallLock) { 3154 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3155 throw new IOException("Failed to free enough space"); 3156 } 3157 } 3158 } 3159 3160 /** 3161 * Return if the user key is currently unlocked. 3162 */ 3163 private boolean isUserKeyUnlocked(int userId) { 3164 if (StorageManager.isFileBasedEncryptionEnabled()) { 3165 final IMountService mount = IMountService.Stub 3166 .asInterface(ServiceManager.getService("mount")); 3167 if (mount == null) { 3168 Slog.w(TAG, "Early during boot, assuming locked"); 3169 return false; 3170 } 3171 final long token = Binder.clearCallingIdentity(); 3172 try { 3173 return mount.isUserKeyUnlocked(userId); 3174 } catch (RemoteException e) { 3175 throw e.rethrowAsRuntimeException(); 3176 } finally { 3177 Binder.restoreCallingIdentity(token); 3178 } 3179 } else { 3180 return true; 3181 } 3182 } 3183 3184 /** 3185 * Update given flags based on encryption status of current user. 3186 */ 3187 private int updateFlagsForEncryption(int flags, int userId) { 3188 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3189 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3190 // Caller expressed an explicit opinion about what encryption 3191 // aware/unaware components they want to see, so fall through and 3192 // give them what they want 3193 } else { 3194 // Caller expressed no opinion, so match based on user state 3195 if (isUserKeyUnlocked(userId)) { 3196 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3197 } else { 3198 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3199 } 3200 } 3201 return flags; 3202 } 3203 3204 /** 3205 * Update given flags when being used to request {@link PackageInfo}. 3206 */ 3207 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3208 boolean triaged = true; 3209 if ((flags & PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3210 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS) != 0) { 3211 // Caller is asking for component details, so they'd better be 3212 // asking for specific encryption matching behavior, or be triaged 3213 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3214 | PackageManager.MATCH_ENCRYPTION_AWARE 3215 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3216 triaged = false; 3217 } 3218 } 3219 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3220 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3221 triaged = false; 3222 } 3223 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3224 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie, 3225 new Throwable()); 3226 } 3227 return updateFlagsForEncryption(flags, userId); 3228 } 3229 3230 /** 3231 * Update given flags when being used to request {@link ApplicationInfo}. 3232 */ 3233 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3234 return updateFlagsForPackage(flags, userId, cookie); 3235 } 3236 3237 /** 3238 * Update given flags when being used to request {@link ComponentInfo}. 3239 */ 3240 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3241 boolean triaged = true; 3242 // Caller is asking for component details, so they'd better be 3243 // asking for specific encryption matching behavior, or be triaged 3244 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3245 | PackageManager.MATCH_ENCRYPTION_AWARE 3246 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3247 triaged = false; 3248 } 3249 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3250 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie, 3251 new Throwable()); 3252 } 3253 return updateFlagsForEncryption(flags, userId); 3254 } 3255 3256 /** 3257 * Update given flags when being used to request {@link ResolveInfo}. 3258 */ 3259 private int updateFlagsForResolve(int flags, int userId, Object cookie) { 3260 return updateFlagsForComponent(flags, userId, cookie); 3261 } 3262 3263 @Override 3264 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3265 if (!sUserManager.exists(userId)) return null; 3266 flags = updateFlagsForComponent(flags, userId, component); 3267 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3268 synchronized (mPackages) { 3269 PackageParser.Activity a = mActivities.mActivities.get(component); 3270 3271 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3272 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3273 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3274 if (ps == null) return null; 3275 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3276 userId); 3277 } 3278 if (mResolveComponentName.equals(component)) { 3279 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3280 new PackageUserState(), userId); 3281 } 3282 } 3283 return null; 3284 } 3285 3286 @Override 3287 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3288 String resolvedType) { 3289 synchronized (mPackages) { 3290 if (component.equals(mResolveComponentName)) { 3291 // The resolver supports EVERYTHING! 3292 return true; 3293 } 3294 PackageParser.Activity a = mActivities.mActivities.get(component); 3295 if (a == null) { 3296 return false; 3297 } 3298 for (int i=0; i<a.intents.size(); i++) { 3299 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3300 intent.getData(), intent.getCategories(), TAG) >= 0) { 3301 return true; 3302 } 3303 } 3304 return false; 3305 } 3306 } 3307 3308 @Override 3309 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3310 if (!sUserManager.exists(userId)) return null; 3311 flags = updateFlagsForComponent(flags, userId, component); 3312 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3313 synchronized (mPackages) { 3314 PackageParser.Activity a = mReceivers.mActivities.get(component); 3315 if (DEBUG_PACKAGE_INFO) Log.v( 3316 TAG, "getReceiverInfo " + component + ": " + a); 3317 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3318 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3319 if (ps == null) return null; 3320 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3321 userId); 3322 } 3323 } 3324 return null; 3325 } 3326 3327 @Override 3328 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3329 if (!sUserManager.exists(userId)) return null; 3330 flags = updateFlagsForComponent(flags, userId, component); 3331 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3332 synchronized (mPackages) { 3333 PackageParser.Service s = mServices.mServices.get(component); 3334 if (DEBUG_PACKAGE_INFO) Log.v( 3335 TAG, "getServiceInfo " + component + ": " + s); 3336 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3337 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3338 if (ps == null) return null; 3339 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3340 userId); 3341 } 3342 } 3343 return null; 3344 } 3345 3346 @Override 3347 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3348 if (!sUserManager.exists(userId)) return null; 3349 flags = updateFlagsForComponent(flags, userId, component); 3350 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3351 synchronized (mPackages) { 3352 PackageParser.Provider p = mProviders.mProviders.get(component); 3353 if (DEBUG_PACKAGE_INFO) Log.v( 3354 TAG, "getProviderInfo " + component + ": " + p); 3355 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3356 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3357 if (ps == null) return null; 3358 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3359 userId); 3360 } 3361 } 3362 return null; 3363 } 3364 3365 @Override 3366 public String[] getSystemSharedLibraryNames() { 3367 Set<String> libSet; 3368 synchronized (mPackages) { 3369 libSet = mSharedLibraries.keySet(); 3370 int size = libSet.size(); 3371 if (size > 0) { 3372 String[] libs = new String[size]; 3373 libSet.toArray(libs); 3374 return libs; 3375 } 3376 } 3377 return null; 3378 } 3379 3380 /** 3381 * @hide 3382 */ 3383 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3384 synchronized (mPackages) { 3385 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3386 if (lib != null && lib.apk != null) { 3387 return mPackages.get(lib.apk); 3388 } 3389 } 3390 return null; 3391 } 3392 3393 @Override 3394 public FeatureInfo[] getSystemAvailableFeatures() { 3395 Collection<FeatureInfo> featSet; 3396 synchronized (mPackages) { 3397 featSet = mAvailableFeatures.values(); 3398 int size = featSet.size(); 3399 if (size > 0) { 3400 FeatureInfo[] features = new FeatureInfo[size+1]; 3401 featSet.toArray(features); 3402 FeatureInfo fi = new FeatureInfo(); 3403 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3404 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3405 features[size] = fi; 3406 return features; 3407 } 3408 } 3409 return null; 3410 } 3411 3412 @Override 3413 public boolean hasSystemFeature(String name) { 3414 synchronized (mPackages) { 3415 return mAvailableFeatures.containsKey(name); 3416 } 3417 } 3418 3419 @Override 3420 public int checkPermission(String permName, String pkgName, int userId) { 3421 if (!sUserManager.exists(userId)) { 3422 return PackageManager.PERMISSION_DENIED; 3423 } 3424 3425 synchronized (mPackages) { 3426 final PackageParser.Package p = mPackages.get(pkgName); 3427 if (p != null && p.mExtras != null) { 3428 final PackageSetting ps = (PackageSetting) p.mExtras; 3429 final PermissionsState permissionsState = ps.getPermissionsState(); 3430 if (permissionsState.hasPermission(permName, userId)) { 3431 return PackageManager.PERMISSION_GRANTED; 3432 } 3433 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3434 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3435 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3436 return PackageManager.PERMISSION_GRANTED; 3437 } 3438 } 3439 } 3440 3441 return PackageManager.PERMISSION_DENIED; 3442 } 3443 3444 @Override 3445 public int checkUidPermission(String permName, int uid) { 3446 final int userId = UserHandle.getUserId(uid); 3447 3448 if (!sUserManager.exists(userId)) { 3449 return PackageManager.PERMISSION_DENIED; 3450 } 3451 3452 synchronized (mPackages) { 3453 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3454 if (obj != null) { 3455 final SettingBase ps = (SettingBase) obj; 3456 final PermissionsState permissionsState = ps.getPermissionsState(); 3457 if (permissionsState.hasPermission(permName, userId)) { 3458 return PackageManager.PERMISSION_GRANTED; 3459 } 3460 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3461 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3462 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3463 return PackageManager.PERMISSION_GRANTED; 3464 } 3465 } else { 3466 ArraySet<String> perms = mSystemPermissions.get(uid); 3467 if (perms != null) { 3468 if (perms.contains(permName)) { 3469 return PackageManager.PERMISSION_GRANTED; 3470 } 3471 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3472 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3473 return PackageManager.PERMISSION_GRANTED; 3474 } 3475 } 3476 } 3477 } 3478 3479 return PackageManager.PERMISSION_DENIED; 3480 } 3481 3482 @Override 3483 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3484 if (UserHandle.getCallingUserId() != userId) { 3485 mContext.enforceCallingPermission( 3486 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3487 "isPermissionRevokedByPolicy for user " + userId); 3488 } 3489 3490 if (checkPermission(permission, packageName, userId) 3491 == PackageManager.PERMISSION_GRANTED) { 3492 return false; 3493 } 3494 3495 final long identity = Binder.clearCallingIdentity(); 3496 try { 3497 final int flags = getPermissionFlags(permission, packageName, userId); 3498 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3499 } finally { 3500 Binder.restoreCallingIdentity(identity); 3501 } 3502 } 3503 3504 @Override 3505 public String getPermissionControllerPackageName() { 3506 synchronized (mPackages) { 3507 return mRequiredInstallerPackage; 3508 } 3509 } 3510 3511 /** 3512 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3513 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3514 * @param checkShell TODO(yamasani): 3515 * @param message the message to log on security exception 3516 */ 3517 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3518 boolean checkShell, String message) { 3519 if (userId < 0) { 3520 throw new IllegalArgumentException("Invalid userId " + userId); 3521 } 3522 if (checkShell) { 3523 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3524 } 3525 if (userId == UserHandle.getUserId(callingUid)) return; 3526 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3527 if (requireFullPermission) { 3528 mContext.enforceCallingOrSelfPermission( 3529 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3530 } else { 3531 try { 3532 mContext.enforceCallingOrSelfPermission( 3533 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3534 } catch (SecurityException se) { 3535 mContext.enforceCallingOrSelfPermission( 3536 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3537 } 3538 } 3539 } 3540 } 3541 3542 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3543 if (callingUid == Process.SHELL_UID) { 3544 if (userHandle >= 0 3545 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3546 throw new SecurityException("Shell does not have permission to access user " 3547 + userHandle); 3548 } else if (userHandle < 0) { 3549 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3550 + Debug.getCallers(3)); 3551 } 3552 } 3553 } 3554 3555 private BasePermission findPermissionTreeLP(String permName) { 3556 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3557 if (permName.startsWith(bp.name) && 3558 permName.length() > bp.name.length() && 3559 permName.charAt(bp.name.length()) == '.') { 3560 return bp; 3561 } 3562 } 3563 return null; 3564 } 3565 3566 private BasePermission checkPermissionTreeLP(String permName) { 3567 if (permName != null) { 3568 BasePermission bp = findPermissionTreeLP(permName); 3569 if (bp != null) { 3570 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3571 return bp; 3572 } 3573 throw new SecurityException("Calling uid " 3574 + Binder.getCallingUid() 3575 + " is not allowed to add to permission tree " 3576 + bp.name + " owned by uid " + bp.uid); 3577 } 3578 } 3579 throw new SecurityException("No permission tree found for " + permName); 3580 } 3581 3582 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3583 if (s1 == null) { 3584 return s2 == null; 3585 } 3586 if (s2 == null) { 3587 return false; 3588 } 3589 if (s1.getClass() != s2.getClass()) { 3590 return false; 3591 } 3592 return s1.equals(s2); 3593 } 3594 3595 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3596 if (pi1.icon != pi2.icon) return false; 3597 if (pi1.logo != pi2.logo) return false; 3598 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3599 if (!compareStrings(pi1.name, pi2.name)) return false; 3600 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3601 // We'll take care of setting this one. 3602 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3603 // These are not currently stored in settings. 3604 //if (!compareStrings(pi1.group, pi2.group)) return false; 3605 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3606 //if (pi1.labelRes != pi2.labelRes) return false; 3607 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3608 return true; 3609 } 3610 3611 int permissionInfoFootprint(PermissionInfo info) { 3612 int size = info.name.length(); 3613 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3614 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3615 return size; 3616 } 3617 3618 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3619 int size = 0; 3620 for (BasePermission perm : mSettings.mPermissions.values()) { 3621 if (perm.uid == tree.uid) { 3622 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3623 } 3624 } 3625 return size; 3626 } 3627 3628 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3629 // We calculate the max size of permissions defined by this uid and throw 3630 // if that plus the size of 'info' would exceed our stated maximum. 3631 if (tree.uid != Process.SYSTEM_UID) { 3632 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3633 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3634 throw new SecurityException("Permission tree size cap exceeded"); 3635 } 3636 } 3637 } 3638 3639 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3640 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3641 throw new SecurityException("Label must be specified in permission"); 3642 } 3643 BasePermission tree = checkPermissionTreeLP(info.name); 3644 BasePermission bp = mSettings.mPermissions.get(info.name); 3645 boolean added = bp == null; 3646 boolean changed = true; 3647 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3648 if (added) { 3649 enforcePermissionCapLocked(info, tree); 3650 bp = new BasePermission(info.name, tree.sourcePackage, 3651 BasePermission.TYPE_DYNAMIC); 3652 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3653 throw new SecurityException( 3654 "Not allowed to modify non-dynamic permission " 3655 + info.name); 3656 } else { 3657 if (bp.protectionLevel == fixedLevel 3658 && bp.perm.owner.equals(tree.perm.owner) 3659 && bp.uid == tree.uid 3660 && comparePermissionInfos(bp.perm.info, info)) { 3661 changed = false; 3662 } 3663 } 3664 bp.protectionLevel = fixedLevel; 3665 info = new PermissionInfo(info); 3666 info.protectionLevel = fixedLevel; 3667 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3668 bp.perm.info.packageName = tree.perm.info.packageName; 3669 bp.uid = tree.uid; 3670 if (added) { 3671 mSettings.mPermissions.put(info.name, bp); 3672 } 3673 if (changed) { 3674 if (!async) { 3675 mSettings.writeLPr(); 3676 } else { 3677 scheduleWriteSettingsLocked(); 3678 } 3679 } 3680 return added; 3681 } 3682 3683 @Override 3684 public boolean addPermission(PermissionInfo info) { 3685 synchronized (mPackages) { 3686 return addPermissionLocked(info, false); 3687 } 3688 } 3689 3690 @Override 3691 public boolean addPermissionAsync(PermissionInfo info) { 3692 synchronized (mPackages) { 3693 return addPermissionLocked(info, true); 3694 } 3695 } 3696 3697 @Override 3698 public void removePermission(String name) { 3699 synchronized (mPackages) { 3700 checkPermissionTreeLP(name); 3701 BasePermission bp = mSettings.mPermissions.get(name); 3702 if (bp != null) { 3703 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3704 throw new SecurityException( 3705 "Not allowed to modify non-dynamic permission " 3706 + name); 3707 } 3708 mSettings.mPermissions.remove(name); 3709 mSettings.writeLPr(); 3710 } 3711 } 3712 } 3713 3714 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3715 BasePermission bp) { 3716 int index = pkg.requestedPermissions.indexOf(bp.name); 3717 if (index == -1) { 3718 throw new SecurityException("Package " + pkg.packageName 3719 + " has not requested permission " + bp.name); 3720 } 3721 if (!bp.isRuntime() && !bp.isDevelopment()) { 3722 throw new SecurityException("Permission " + bp.name 3723 + " is not a changeable permission type"); 3724 } 3725 } 3726 3727 @Override 3728 public void grantRuntimePermission(String packageName, String name, final int userId) { 3729 if (!sUserManager.exists(userId)) { 3730 Log.e(TAG, "No such user:" + userId); 3731 return; 3732 } 3733 3734 mContext.enforceCallingOrSelfPermission( 3735 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3736 "grantRuntimePermission"); 3737 3738 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3739 "grantRuntimePermission"); 3740 3741 final int uid; 3742 final SettingBase sb; 3743 3744 synchronized (mPackages) { 3745 final PackageParser.Package pkg = mPackages.get(packageName); 3746 if (pkg == null) { 3747 throw new IllegalArgumentException("Unknown package: " + packageName); 3748 } 3749 3750 final BasePermission bp = mSettings.mPermissions.get(name); 3751 if (bp == null) { 3752 throw new IllegalArgumentException("Unknown permission: " + name); 3753 } 3754 3755 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3756 3757 // If a permission review is required for legacy apps we represent 3758 // their permissions as always granted runtime ones since we need 3759 // to keep the review required permission flag per user while an 3760 // install permission's state is shared across all users. 3761 if (Build.PERMISSIONS_REVIEW_REQUIRED 3762 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3763 && bp.isRuntime()) { 3764 return; 3765 } 3766 3767 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3768 sb = (SettingBase) pkg.mExtras; 3769 if (sb == null) { 3770 throw new IllegalArgumentException("Unknown package: " + packageName); 3771 } 3772 3773 final PermissionsState permissionsState = sb.getPermissionsState(); 3774 3775 final int flags = permissionsState.getPermissionFlags(name, userId); 3776 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3777 throw new SecurityException("Cannot grant system fixed permission: " 3778 + name + " for package: " + packageName); 3779 } 3780 3781 if (bp.isDevelopment()) { 3782 // Development permissions must be handled specially, since they are not 3783 // normal runtime permissions. For now they apply to all users. 3784 if (permissionsState.grantInstallPermission(bp) != 3785 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3786 scheduleWriteSettingsLocked(); 3787 } 3788 return; 3789 } 3790 3791 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3792 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3793 return; 3794 } 3795 3796 final int result = permissionsState.grantRuntimePermission(bp, userId); 3797 switch (result) { 3798 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3799 return; 3800 } 3801 3802 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3803 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3804 mHandler.post(new Runnable() { 3805 @Override 3806 public void run() { 3807 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3808 } 3809 }); 3810 } 3811 break; 3812 } 3813 3814 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3815 3816 // Not critical if that is lost - app has to request again. 3817 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3818 } 3819 3820 // Only need to do this if user is initialized. Otherwise it's a new user 3821 // and there are no processes running as the user yet and there's no need 3822 // to make an expensive call to remount processes for the changed permissions. 3823 if (READ_EXTERNAL_STORAGE.equals(name) 3824 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3825 final long token = Binder.clearCallingIdentity(); 3826 try { 3827 if (sUserManager.isInitialized(userId)) { 3828 MountServiceInternal mountServiceInternal = LocalServices.getService( 3829 MountServiceInternal.class); 3830 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3831 } 3832 } finally { 3833 Binder.restoreCallingIdentity(token); 3834 } 3835 } 3836 } 3837 3838 @Override 3839 public void revokeRuntimePermission(String packageName, String name, int userId) { 3840 if (!sUserManager.exists(userId)) { 3841 Log.e(TAG, "No such user:" + userId); 3842 return; 3843 } 3844 3845 mContext.enforceCallingOrSelfPermission( 3846 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3847 "revokeRuntimePermission"); 3848 3849 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3850 "revokeRuntimePermission"); 3851 3852 final int appId; 3853 3854 synchronized (mPackages) { 3855 final PackageParser.Package pkg = mPackages.get(packageName); 3856 if (pkg == null) { 3857 throw new IllegalArgumentException("Unknown package: " + packageName); 3858 } 3859 3860 final BasePermission bp = mSettings.mPermissions.get(name); 3861 if (bp == null) { 3862 throw new IllegalArgumentException("Unknown permission: " + name); 3863 } 3864 3865 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3866 3867 // If a permission review is required for legacy apps we represent 3868 // their permissions as always granted runtime ones since we need 3869 // to keep the review required permission flag per user while an 3870 // install permission's state is shared across all users. 3871 if (Build.PERMISSIONS_REVIEW_REQUIRED 3872 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3873 && bp.isRuntime()) { 3874 return; 3875 } 3876 3877 SettingBase sb = (SettingBase) pkg.mExtras; 3878 if (sb == null) { 3879 throw new IllegalArgumentException("Unknown package: " + packageName); 3880 } 3881 3882 final PermissionsState permissionsState = sb.getPermissionsState(); 3883 3884 final int flags = permissionsState.getPermissionFlags(name, userId); 3885 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3886 throw new SecurityException("Cannot revoke system fixed permission: " 3887 + name + " for package: " + packageName); 3888 } 3889 3890 if (bp.isDevelopment()) { 3891 // Development permissions must be handled specially, since they are not 3892 // normal runtime permissions. For now they apply to all users. 3893 if (permissionsState.revokeInstallPermission(bp) != 3894 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3895 scheduleWriteSettingsLocked(); 3896 } 3897 return; 3898 } 3899 3900 if (permissionsState.revokeRuntimePermission(bp, userId) == 3901 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3902 return; 3903 } 3904 3905 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3906 3907 // Critical, after this call app should never have the permission. 3908 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3909 3910 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3911 } 3912 3913 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3914 } 3915 3916 @Override 3917 public void resetRuntimePermissions() { 3918 mContext.enforceCallingOrSelfPermission( 3919 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3920 "revokeRuntimePermission"); 3921 3922 int callingUid = Binder.getCallingUid(); 3923 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3924 mContext.enforceCallingOrSelfPermission( 3925 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3926 "resetRuntimePermissions"); 3927 } 3928 3929 synchronized (mPackages) { 3930 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3931 for (int userId : UserManagerService.getInstance().getUserIds()) { 3932 final int packageCount = mPackages.size(); 3933 for (int i = 0; i < packageCount; i++) { 3934 PackageParser.Package pkg = mPackages.valueAt(i); 3935 if (!(pkg.mExtras instanceof PackageSetting)) { 3936 continue; 3937 } 3938 PackageSetting ps = (PackageSetting) pkg.mExtras; 3939 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3940 } 3941 } 3942 } 3943 } 3944 3945 @Override 3946 public int getPermissionFlags(String name, String packageName, int userId) { 3947 if (!sUserManager.exists(userId)) { 3948 return 0; 3949 } 3950 3951 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3952 3953 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3954 "getPermissionFlags"); 3955 3956 synchronized (mPackages) { 3957 final PackageParser.Package pkg = mPackages.get(packageName); 3958 if (pkg == null) { 3959 throw new IllegalArgumentException("Unknown package: " + packageName); 3960 } 3961 3962 final BasePermission bp = mSettings.mPermissions.get(name); 3963 if (bp == null) { 3964 throw new IllegalArgumentException("Unknown permission: " + name); 3965 } 3966 3967 SettingBase sb = (SettingBase) pkg.mExtras; 3968 if (sb == null) { 3969 throw new IllegalArgumentException("Unknown package: " + packageName); 3970 } 3971 3972 PermissionsState permissionsState = sb.getPermissionsState(); 3973 return permissionsState.getPermissionFlags(name, userId); 3974 } 3975 } 3976 3977 @Override 3978 public void updatePermissionFlags(String name, String packageName, int flagMask, 3979 int flagValues, int userId) { 3980 if (!sUserManager.exists(userId)) { 3981 return; 3982 } 3983 3984 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3985 3986 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3987 "updatePermissionFlags"); 3988 3989 // Only the system can change these flags and nothing else. 3990 if (getCallingUid() != Process.SYSTEM_UID) { 3991 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3992 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3993 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3994 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3995 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3996 } 3997 3998 synchronized (mPackages) { 3999 final PackageParser.Package pkg = mPackages.get(packageName); 4000 if (pkg == null) { 4001 throw new IllegalArgumentException("Unknown package: " + packageName); 4002 } 4003 4004 final BasePermission bp = mSettings.mPermissions.get(name); 4005 if (bp == null) { 4006 throw new IllegalArgumentException("Unknown permission: " + name); 4007 } 4008 4009 SettingBase sb = (SettingBase) pkg.mExtras; 4010 if (sb == null) { 4011 throw new IllegalArgumentException("Unknown package: " + packageName); 4012 } 4013 4014 PermissionsState permissionsState = sb.getPermissionsState(); 4015 4016 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4017 4018 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4019 // Install and runtime permissions are stored in different places, 4020 // so figure out what permission changed and persist the change. 4021 if (permissionsState.getInstallPermissionState(name) != null) { 4022 scheduleWriteSettingsLocked(); 4023 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4024 || hadState) { 4025 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4026 } 4027 } 4028 } 4029 } 4030 4031 /** 4032 * Update the permission flags for all packages and runtime permissions of a user in order 4033 * to allow device or profile owner to remove POLICY_FIXED. 4034 */ 4035 @Override 4036 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4037 if (!sUserManager.exists(userId)) { 4038 return; 4039 } 4040 4041 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4042 4043 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4044 "updatePermissionFlagsForAllApps"); 4045 4046 // Only the system can change system fixed flags. 4047 if (getCallingUid() != Process.SYSTEM_UID) { 4048 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4049 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4050 } 4051 4052 synchronized (mPackages) { 4053 boolean changed = false; 4054 final int packageCount = mPackages.size(); 4055 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4056 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4057 SettingBase sb = (SettingBase) pkg.mExtras; 4058 if (sb == null) { 4059 continue; 4060 } 4061 PermissionsState permissionsState = sb.getPermissionsState(); 4062 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4063 userId, flagMask, flagValues); 4064 } 4065 if (changed) { 4066 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4067 } 4068 } 4069 } 4070 4071 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4072 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4073 != PackageManager.PERMISSION_GRANTED 4074 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4075 != PackageManager.PERMISSION_GRANTED) { 4076 throw new SecurityException(message + " requires " 4077 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4078 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4079 } 4080 } 4081 4082 @Override 4083 public boolean shouldShowRequestPermissionRationale(String permissionName, 4084 String packageName, int userId) { 4085 if (UserHandle.getCallingUserId() != userId) { 4086 mContext.enforceCallingPermission( 4087 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4088 "canShowRequestPermissionRationale for user " + userId); 4089 } 4090 4091 final int uid = getPackageUid(packageName, userId); 4092 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4093 return false; 4094 } 4095 4096 if (checkPermission(permissionName, packageName, userId) 4097 == PackageManager.PERMISSION_GRANTED) { 4098 return false; 4099 } 4100 4101 final int flags; 4102 4103 final long identity = Binder.clearCallingIdentity(); 4104 try { 4105 flags = getPermissionFlags(permissionName, 4106 packageName, userId); 4107 } finally { 4108 Binder.restoreCallingIdentity(identity); 4109 } 4110 4111 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4112 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4113 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4114 4115 if ((flags & fixedFlags) != 0) { 4116 return false; 4117 } 4118 4119 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4120 } 4121 4122 @Override 4123 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4124 mContext.enforceCallingOrSelfPermission( 4125 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4126 "addOnPermissionsChangeListener"); 4127 4128 synchronized (mPackages) { 4129 mOnPermissionChangeListeners.addListenerLocked(listener); 4130 } 4131 } 4132 4133 @Override 4134 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4135 synchronized (mPackages) { 4136 mOnPermissionChangeListeners.removeListenerLocked(listener); 4137 } 4138 } 4139 4140 @Override 4141 public boolean isProtectedBroadcast(String actionName) { 4142 synchronized (mPackages) { 4143 if (mProtectedBroadcasts.contains(actionName)) { 4144 return true; 4145 } else if (actionName != null) { 4146 // TODO: remove these terrible hacks 4147 if (actionName.startsWith("android.net.netmon.lingerExpired") 4148 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4149 return true; 4150 } 4151 } 4152 } 4153 return false; 4154 } 4155 4156 @Override 4157 public int checkSignatures(String pkg1, String pkg2) { 4158 synchronized (mPackages) { 4159 final PackageParser.Package p1 = mPackages.get(pkg1); 4160 final PackageParser.Package p2 = mPackages.get(pkg2); 4161 if (p1 == null || p1.mExtras == null 4162 || p2 == null || p2.mExtras == null) { 4163 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4164 } 4165 return compareSignatures(p1.mSignatures, p2.mSignatures); 4166 } 4167 } 4168 4169 @Override 4170 public int checkUidSignatures(int uid1, int uid2) { 4171 // Map to base uids. 4172 uid1 = UserHandle.getAppId(uid1); 4173 uid2 = UserHandle.getAppId(uid2); 4174 // reader 4175 synchronized (mPackages) { 4176 Signature[] s1; 4177 Signature[] s2; 4178 Object obj = mSettings.getUserIdLPr(uid1); 4179 if (obj != null) { 4180 if (obj instanceof SharedUserSetting) { 4181 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4182 } else if (obj instanceof PackageSetting) { 4183 s1 = ((PackageSetting)obj).signatures.mSignatures; 4184 } else { 4185 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4186 } 4187 } else { 4188 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4189 } 4190 obj = mSettings.getUserIdLPr(uid2); 4191 if (obj != null) { 4192 if (obj instanceof SharedUserSetting) { 4193 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4194 } else if (obj instanceof PackageSetting) { 4195 s2 = ((PackageSetting)obj).signatures.mSignatures; 4196 } else { 4197 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4198 } 4199 } else { 4200 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4201 } 4202 return compareSignatures(s1, s2); 4203 } 4204 } 4205 4206 private void killUid(int appId, int userId, String reason) { 4207 final long identity = Binder.clearCallingIdentity(); 4208 try { 4209 IActivityManager am = ActivityManagerNative.getDefault(); 4210 if (am != null) { 4211 try { 4212 am.killUid(appId, userId, reason); 4213 } catch (RemoteException e) { 4214 /* ignore - same process */ 4215 } 4216 } 4217 } finally { 4218 Binder.restoreCallingIdentity(identity); 4219 } 4220 } 4221 4222 /** 4223 * Compares two sets of signatures. Returns: 4224 * <br /> 4225 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4226 * <br /> 4227 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4228 * <br /> 4229 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4230 * <br /> 4231 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4232 * <br /> 4233 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4234 */ 4235 static int compareSignatures(Signature[] s1, Signature[] s2) { 4236 if (s1 == null) { 4237 return s2 == null 4238 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4239 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4240 } 4241 4242 if (s2 == null) { 4243 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4244 } 4245 4246 if (s1.length != s2.length) { 4247 return PackageManager.SIGNATURE_NO_MATCH; 4248 } 4249 4250 // Since both signature sets are of size 1, we can compare without HashSets. 4251 if (s1.length == 1) { 4252 return s1[0].equals(s2[0]) ? 4253 PackageManager.SIGNATURE_MATCH : 4254 PackageManager.SIGNATURE_NO_MATCH; 4255 } 4256 4257 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4258 for (Signature sig : s1) { 4259 set1.add(sig); 4260 } 4261 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4262 for (Signature sig : s2) { 4263 set2.add(sig); 4264 } 4265 // Make sure s2 contains all signatures in s1. 4266 if (set1.equals(set2)) { 4267 return PackageManager.SIGNATURE_MATCH; 4268 } 4269 return PackageManager.SIGNATURE_NO_MATCH; 4270 } 4271 4272 /** 4273 * If the database version for this type of package (internal storage or 4274 * external storage) is less than the version where package signatures 4275 * were updated, return true. 4276 */ 4277 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4278 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4279 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4280 } 4281 4282 /** 4283 * Used for backward compatibility to make sure any packages with 4284 * certificate chains get upgraded to the new style. {@code existingSigs} 4285 * will be in the old format (since they were stored on disk from before the 4286 * system upgrade) and {@code scannedSigs} will be in the newer format. 4287 */ 4288 private int compareSignaturesCompat(PackageSignatures existingSigs, 4289 PackageParser.Package scannedPkg) { 4290 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4291 return PackageManager.SIGNATURE_NO_MATCH; 4292 } 4293 4294 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4295 for (Signature sig : existingSigs.mSignatures) { 4296 existingSet.add(sig); 4297 } 4298 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4299 for (Signature sig : scannedPkg.mSignatures) { 4300 try { 4301 Signature[] chainSignatures = sig.getChainSignatures(); 4302 for (Signature chainSig : chainSignatures) { 4303 scannedCompatSet.add(chainSig); 4304 } 4305 } catch (CertificateEncodingException e) { 4306 scannedCompatSet.add(sig); 4307 } 4308 } 4309 /* 4310 * Make sure the expanded scanned set contains all signatures in the 4311 * existing one. 4312 */ 4313 if (scannedCompatSet.equals(existingSet)) { 4314 // Migrate the old signatures to the new scheme. 4315 existingSigs.assignSignatures(scannedPkg.mSignatures); 4316 // The new KeySets will be re-added later in the scanning process. 4317 synchronized (mPackages) { 4318 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4319 } 4320 return PackageManager.SIGNATURE_MATCH; 4321 } 4322 return PackageManager.SIGNATURE_NO_MATCH; 4323 } 4324 4325 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4326 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4327 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4328 } 4329 4330 private int compareSignaturesRecover(PackageSignatures existingSigs, 4331 PackageParser.Package scannedPkg) { 4332 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4333 return PackageManager.SIGNATURE_NO_MATCH; 4334 } 4335 4336 String msg = null; 4337 try { 4338 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4339 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4340 + scannedPkg.packageName); 4341 return PackageManager.SIGNATURE_MATCH; 4342 } 4343 } catch (CertificateException e) { 4344 msg = e.getMessage(); 4345 } 4346 4347 logCriticalInfo(Log.INFO, 4348 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4349 return PackageManager.SIGNATURE_NO_MATCH; 4350 } 4351 4352 @Override 4353 public String[] getPackagesForUid(int uid) { 4354 uid = UserHandle.getAppId(uid); 4355 // reader 4356 synchronized (mPackages) { 4357 Object obj = mSettings.getUserIdLPr(uid); 4358 if (obj instanceof SharedUserSetting) { 4359 final SharedUserSetting sus = (SharedUserSetting) obj; 4360 final int N = sus.packages.size(); 4361 final String[] res = new String[N]; 4362 final Iterator<PackageSetting> it = sus.packages.iterator(); 4363 int i = 0; 4364 while (it.hasNext()) { 4365 res[i++] = it.next().name; 4366 } 4367 return res; 4368 } else if (obj instanceof PackageSetting) { 4369 final PackageSetting ps = (PackageSetting) obj; 4370 return new String[] { ps.name }; 4371 } 4372 } 4373 return null; 4374 } 4375 4376 @Override 4377 public String getNameForUid(int uid) { 4378 // reader 4379 synchronized (mPackages) { 4380 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4381 if (obj instanceof SharedUserSetting) { 4382 final SharedUserSetting sus = (SharedUserSetting) obj; 4383 return sus.name + ":" + sus.userId; 4384 } else if (obj instanceof PackageSetting) { 4385 final PackageSetting ps = (PackageSetting) obj; 4386 return ps.name; 4387 } 4388 } 4389 return null; 4390 } 4391 4392 @Override 4393 public int getUidForSharedUser(String sharedUserName) { 4394 if(sharedUserName == null) { 4395 return -1; 4396 } 4397 // reader 4398 synchronized (mPackages) { 4399 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4400 if (suid == null) { 4401 return -1; 4402 } 4403 return suid.userId; 4404 } 4405 } 4406 4407 @Override 4408 public int getFlagsForUid(int uid) { 4409 synchronized (mPackages) { 4410 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4411 if (obj instanceof SharedUserSetting) { 4412 final SharedUserSetting sus = (SharedUserSetting) obj; 4413 return sus.pkgFlags; 4414 } else if (obj instanceof PackageSetting) { 4415 final PackageSetting ps = (PackageSetting) obj; 4416 return ps.pkgFlags; 4417 } 4418 } 4419 return 0; 4420 } 4421 4422 @Override 4423 public int getPrivateFlagsForUid(int uid) { 4424 synchronized (mPackages) { 4425 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4426 if (obj instanceof SharedUserSetting) { 4427 final SharedUserSetting sus = (SharedUserSetting) obj; 4428 return sus.pkgPrivateFlags; 4429 } else if (obj instanceof PackageSetting) { 4430 final PackageSetting ps = (PackageSetting) obj; 4431 return ps.pkgPrivateFlags; 4432 } 4433 } 4434 return 0; 4435 } 4436 4437 @Override 4438 public boolean isUidPrivileged(int uid) { 4439 uid = UserHandle.getAppId(uid); 4440 // reader 4441 synchronized (mPackages) { 4442 Object obj = mSettings.getUserIdLPr(uid); 4443 if (obj instanceof SharedUserSetting) { 4444 final SharedUserSetting sus = (SharedUserSetting) obj; 4445 final Iterator<PackageSetting> it = sus.packages.iterator(); 4446 while (it.hasNext()) { 4447 if (it.next().isPrivileged()) { 4448 return true; 4449 } 4450 } 4451 } else if (obj instanceof PackageSetting) { 4452 final PackageSetting ps = (PackageSetting) obj; 4453 return ps.isPrivileged(); 4454 } 4455 } 4456 return false; 4457 } 4458 4459 @Override 4460 public String[] getAppOpPermissionPackages(String permissionName) { 4461 synchronized (mPackages) { 4462 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4463 if (pkgs == null) { 4464 return null; 4465 } 4466 return pkgs.toArray(new String[pkgs.size()]); 4467 } 4468 } 4469 4470 @Override 4471 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4472 int flags, int userId) { 4473 if (!sUserManager.exists(userId)) return null; 4474 flags = updateFlagsForResolve(flags, userId, intent); 4475 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4476 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4477 final ResolveInfo bestChoice = 4478 chooseBestActivity(intent, resolvedType, flags, query, userId); 4479 4480 if (isEphemeralAllowed(intent, query, userId)) { 4481 final EphemeralResolveInfo ai = 4482 getEphemeralResolveInfo(intent, resolvedType, userId); 4483 if (ai != null) { 4484 if (DEBUG_EPHEMERAL) { 4485 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4486 } 4487 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4488 bestChoice.ephemeralResolveInfo = ai; 4489 } 4490 } 4491 return bestChoice; 4492 } 4493 4494 @Override 4495 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4496 IntentFilter filter, int match, ComponentName activity) { 4497 final int userId = UserHandle.getCallingUserId(); 4498 if (DEBUG_PREFERRED) { 4499 Log.v(TAG, "setLastChosenActivity intent=" + intent 4500 + " resolvedType=" + resolvedType 4501 + " flags=" + flags 4502 + " filter=" + filter 4503 + " match=" + match 4504 + " activity=" + activity); 4505 filter.dump(new PrintStreamPrinter(System.out), " "); 4506 } 4507 intent.setComponent(null); 4508 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4509 // Find any earlier preferred or last chosen entries and nuke them 4510 findPreferredActivity(intent, resolvedType, 4511 flags, query, 0, false, true, false, userId); 4512 // Add the new activity as the last chosen for this filter 4513 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4514 "Setting last chosen"); 4515 } 4516 4517 @Override 4518 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4519 final int userId = UserHandle.getCallingUserId(); 4520 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4521 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4522 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4523 false, false, false, userId); 4524 } 4525 4526 4527 private boolean isEphemeralAllowed( 4528 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4529 // Short circuit and return early if possible. 4530 final int callingUser = UserHandle.getCallingUserId(); 4531 if (callingUser != UserHandle.USER_SYSTEM) { 4532 return false; 4533 } 4534 if (mEphemeralResolverConnection == null) { 4535 return false; 4536 } 4537 if (intent.getComponent() != null) { 4538 return false; 4539 } 4540 if (intent.getPackage() != null) { 4541 return false; 4542 } 4543 final boolean isWebUri = hasWebURI(intent); 4544 if (!isWebUri) { 4545 return false; 4546 } 4547 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4548 synchronized (mPackages) { 4549 final int count = resolvedActivites.size(); 4550 for (int n = 0; n < count; n++) { 4551 ResolveInfo info = resolvedActivites.get(n); 4552 String packageName = info.activityInfo.packageName; 4553 PackageSetting ps = mSettings.mPackages.get(packageName); 4554 if (ps != null) { 4555 // Try to get the status from User settings first 4556 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4557 int status = (int) (packedStatus >> 32); 4558 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4559 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4560 if (DEBUG_EPHEMERAL) { 4561 Slog.v(TAG, "DENY ephemeral apps;" 4562 + " pkg: " + packageName + ", status: " + status); 4563 } 4564 return false; 4565 } 4566 } 4567 } 4568 } 4569 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4570 return true; 4571 } 4572 4573 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4574 int userId) { 4575 MessageDigest digest = null; 4576 try { 4577 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4578 } catch (NoSuchAlgorithmException e) { 4579 // If we can't create a digest, ignore ephemeral apps. 4580 return null; 4581 } 4582 4583 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4584 final byte[] digestBytes = digest.digest(hostBytes); 4585 int shaPrefix = 4586 digestBytes[0] << 24 4587 | digestBytes[1] << 16 4588 | digestBytes[2] << 8 4589 | digestBytes[3] << 0; 4590 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4591 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4592 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4593 // No hash prefix match; there are no ephemeral apps for this domain. 4594 return null; 4595 } 4596 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4597 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4598 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4599 continue; 4600 } 4601 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4602 // No filters; this should never happen. 4603 if (filters.isEmpty()) { 4604 continue; 4605 } 4606 // We have a domain match; resolve the filters to see if anything matches. 4607 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4608 for (int j = filters.size() - 1; j >= 0; --j) { 4609 final EphemeralResolveIntentInfo intentInfo = 4610 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4611 ephemeralResolver.addFilter(intentInfo); 4612 } 4613 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4614 intent, resolvedType, false /*defaultOnly*/, userId); 4615 if (!matchedResolveInfoList.isEmpty()) { 4616 return matchedResolveInfoList.get(0); 4617 } 4618 } 4619 // Hash or filter mis-match; no ephemeral apps for this domain. 4620 return null; 4621 } 4622 4623 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4624 int flags, List<ResolveInfo> query, int userId) { 4625 if (query != null) { 4626 final int N = query.size(); 4627 if (N == 1) { 4628 return query.get(0); 4629 } else if (N > 1) { 4630 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4631 // If there is more than one activity with the same priority, 4632 // then let the user decide between them. 4633 ResolveInfo r0 = query.get(0); 4634 ResolveInfo r1 = query.get(1); 4635 if (DEBUG_INTENT_MATCHING || debug) { 4636 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4637 + r1.activityInfo.name + "=" + r1.priority); 4638 } 4639 // If the first activity has a higher priority, or a different 4640 // default, then it is always desirable to pick it. 4641 if (r0.priority != r1.priority 4642 || r0.preferredOrder != r1.preferredOrder 4643 || r0.isDefault != r1.isDefault) { 4644 return query.get(0); 4645 } 4646 // If we have saved a preference for a preferred activity for 4647 // this Intent, use that. 4648 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4649 flags, query, r0.priority, true, false, debug, userId); 4650 if (ri != null) { 4651 return ri; 4652 } 4653 ri = new ResolveInfo(mResolveInfo); 4654 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4655 ri.activityInfo.applicationInfo = new ApplicationInfo( 4656 ri.activityInfo.applicationInfo); 4657 if (userId != 0) { 4658 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4659 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4660 } 4661 // Make sure that the resolver is displayable in car mode 4662 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4663 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4664 return ri; 4665 } 4666 } 4667 return null; 4668 } 4669 4670 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4671 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4672 final int N = query.size(); 4673 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4674 .get(userId); 4675 // Get the list of persistent preferred activities that handle the intent 4676 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4677 List<PersistentPreferredActivity> pprefs = ppir != null 4678 ? ppir.queryIntent(intent, resolvedType, 4679 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4680 : null; 4681 if (pprefs != null && pprefs.size() > 0) { 4682 final int M = pprefs.size(); 4683 for (int i=0; i<M; i++) { 4684 final PersistentPreferredActivity ppa = pprefs.get(i); 4685 if (DEBUG_PREFERRED || debug) { 4686 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4687 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4688 + "\n component=" + ppa.mComponent); 4689 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4690 } 4691 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4692 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4693 if (DEBUG_PREFERRED || debug) { 4694 Slog.v(TAG, "Found persistent preferred activity:"); 4695 if (ai != null) { 4696 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4697 } else { 4698 Slog.v(TAG, " null"); 4699 } 4700 } 4701 if (ai == null) { 4702 // This previously registered persistent preferred activity 4703 // component is no longer known. Ignore it and do NOT remove it. 4704 continue; 4705 } 4706 for (int j=0; j<N; j++) { 4707 final ResolveInfo ri = query.get(j); 4708 if (!ri.activityInfo.applicationInfo.packageName 4709 .equals(ai.applicationInfo.packageName)) { 4710 continue; 4711 } 4712 if (!ri.activityInfo.name.equals(ai.name)) { 4713 continue; 4714 } 4715 // Found a persistent preference that can handle the intent. 4716 if (DEBUG_PREFERRED || debug) { 4717 Slog.v(TAG, "Returning persistent preferred activity: " + 4718 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4719 } 4720 return ri; 4721 } 4722 } 4723 } 4724 return null; 4725 } 4726 4727 // TODO: handle preferred activities missing while user has amnesia 4728 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4729 List<ResolveInfo> query, int priority, boolean always, 4730 boolean removeMatches, boolean debug, int userId) { 4731 if (!sUserManager.exists(userId)) return null; 4732 flags = updateFlagsForResolve(flags, userId, intent); 4733 // writer 4734 synchronized (mPackages) { 4735 if (intent.getSelector() != null) { 4736 intent = intent.getSelector(); 4737 } 4738 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4739 4740 // Try to find a matching persistent preferred activity. 4741 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4742 debug, userId); 4743 4744 // If a persistent preferred activity matched, use it. 4745 if (pri != null) { 4746 return pri; 4747 } 4748 4749 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4750 // Get the list of preferred activities that handle the intent 4751 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4752 List<PreferredActivity> prefs = pir != null 4753 ? pir.queryIntent(intent, resolvedType, 4754 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4755 : null; 4756 if (prefs != null && prefs.size() > 0) { 4757 boolean changed = false; 4758 try { 4759 // First figure out how good the original match set is. 4760 // We will only allow preferred activities that came 4761 // from the same match quality. 4762 int match = 0; 4763 4764 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4765 4766 final int N = query.size(); 4767 for (int j=0; j<N; j++) { 4768 final ResolveInfo ri = query.get(j); 4769 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4770 + ": 0x" + Integer.toHexString(match)); 4771 if (ri.match > match) { 4772 match = ri.match; 4773 } 4774 } 4775 4776 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4777 + Integer.toHexString(match)); 4778 4779 match &= IntentFilter.MATCH_CATEGORY_MASK; 4780 final int M = prefs.size(); 4781 for (int i=0; i<M; i++) { 4782 final PreferredActivity pa = prefs.get(i); 4783 if (DEBUG_PREFERRED || debug) { 4784 Slog.v(TAG, "Checking PreferredActivity ds=" 4785 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4786 + "\n component=" + pa.mPref.mComponent); 4787 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4788 } 4789 if (pa.mPref.mMatch != match) { 4790 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4791 + Integer.toHexString(pa.mPref.mMatch)); 4792 continue; 4793 } 4794 // If it's not an "always" type preferred activity and that's what we're 4795 // looking for, skip it. 4796 if (always && !pa.mPref.mAlways) { 4797 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4798 continue; 4799 } 4800 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4801 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4802 if (DEBUG_PREFERRED || debug) { 4803 Slog.v(TAG, "Found preferred activity:"); 4804 if (ai != null) { 4805 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4806 } else { 4807 Slog.v(TAG, " null"); 4808 } 4809 } 4810 if (ai == null) { 4811 // This previously registered preferred activity 4812 // component is no longer known. Most likely an update 4813 // to the app was installed and in the new version this 4814 // component no longer exists. Clean it up by removing 4815 // it from the preferred activities list, and skip it. 4816 Slog.w(TAG, "Removing dangling preferred activity: " 4817 + pa.mPref.mComponent); 4818 pir.removeFilter(pa); 4819 changed = true; 4820 continue; 4821 } 4822 for (int j=0; j<N; j++) { 4823 final ResolveInfo ri = query.get(j); 4824 if (!ri.activityInfo.applicationInfo.packageName 4825 .equals(ai.applicationInfo.packageName)) { 4826 continue; 4827 } 4828 if (!ri.activityInfo.name.equals(ai.name)) { 4829 continue; 4830 } 4831 4832 if (removeMatches) { 4833 pir.removeFilter(pa); 4834 changed = true; 4835 if (DEBUG_PREFERRED) { 4836 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4837 } 4838 break; 4839 } 4840 4841 // Okay we found a previously set preferred or last chosen app. 4842 // If the result set is different from when this 4843 // was created, we need to clear it and re-ask the 4844 // user their preference, if we're looking for an "always" type entry. 4845 if (always && !pa.mPref.sameSet(query)) { 4846 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4847 + intent + " type " + resolvedType); 4848 if (DEBUG_PREFERRED) { 4849 Slog.v(TAG, "Removing preferred activity since set changed " 4850 + pa.mPref.mComponent); 4851 } 4852 pir.removeFilter(pa); 4853 // Re-add the filter as a "last chosen" entry (!always) 4854 PreferredActivity lastChosen = new PreferredActivity( 4855 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4856 pir.addFilter(lastChosen); 4857 changed = true; 4858 return null; 4859 } 4860 4861 // Yay! Either the set matched or we're looking for the last chosen 4862 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4863 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4864 return ri; 4865 } 4866 } 4867 } finally { 4868 if (changed) { 4869 if (DEBUG_PREFERRED) { 4870 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4871 } 4872 scheduleWritePackageRestrictionsLocked(userId); 4873 } 4874 } 4875 } 4876 } 4877 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4878 return null; 4879 } 4880 4881 /* 4882 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4883 */ 4884 @Override 4885 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4886 int targetUserId) { 4887 mContext.enforceCallingOrSelfPermission( 4888 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4889 List<CrossProfileIntentFilter> matches = 4890 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4891 if (matches != null) { 4892 int size = matches.size(); 4893 for (int i = 0; i < size; i++) { 4894 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4895 } 4896 } 4897 if (hasWebURI(intent)) { 4898 // cross-profile app linking works only towards the parent. 4899 final UserInfo parent = getProfileParent(sourceUserId); 4900 synchronized(mPackages) { 4901 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4902 intent, resolvedType, 0, sourceUserId, parent.id); 4903 return xpDomainInfo != null; 4904 } 4905 } 4906 return false; 4907 } 4908 4909 private UserInfo getProfileParent(int userId) { 4910 final long identity = Binder.clearCallingIdentity(); 4911 try { 4912 return sUserManager.getProfileParent(userId); 4913 } finally { 4914 Binder.restoreCallingIdentity(identity); 4915 } 4916 } 4917 4918 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4919 String resolvedType, int userId) { 4920 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4921 if (resolver != null) { 4922 return resolver.queryIntent(intent, resolvedType, false, userId); 4923 } 4924 return null; 4925 } 4926 4927 @Override 4928 public List<ResolveInfo> queryIntentActivities(Intent intent, 4929 String resolvedType, int flags, int userId) { 4930 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4931 flags = updateFlagsForResolve(flags, userId, intent); 4932 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4933 ComponentName comp = intent.getComponent(); 4934 if (comp == null) { 4935 if (intent.getSelector() != null) { 4936 intent = intent.getSelector(); 4937 comp = intent.getComponent(); 4938 } 4939 } 4940 4941 if (comp != null) { 4942 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4943 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4944 if (ai != null) { 4945 final ResolveInfo ri = new ResolveInfo(); 4946 ri.activityInfo = ai; 4947 list.add(ri); 4948 } 4949 return list; 4950 } 4951 4952 // reader 4953 synchronized (mPackages) { 4954 final String pkgName = intent.getPackage(); 4955 if (pkgName == null) { 4956 List<CrossProfileIntentFilter> matchingFilters = 4957 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4958 // Check for results that need to skip the current profile. 4959 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4960 resolvedType, flags, userId); 4961 if (xpResolveInfo != null) { 4962 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4963 result.add(xpResolveInfo); 4964 return filterIfNotSystemUser(result, userId); 4965 } 4966 4967 // Check for results in the current profile. 4968 List<ResolveInfo> result = mActivities.queryIntent( 4969 intent, resolvedType, flags, userId); 4970 result = filterIfNotSystemUser(result, userId); 4971 4972 // Check for cross profile results. 4973 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4974 xpResolveInfo = queryCrossProfileIntents( 4975 matchingFilters, intent, resolvedType, flags, userId, 4976 hasNonNegativePriorityResult); 4977 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4978 boolean isVisibleToUser = filterIfNotSystemUser( 4979 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4980 if (isVisibleToUser) { 4981 result.add(xpResolveInfo); 4982 Collections.sort(result, mResolvePrioritySorter); 4983 } 4984 } 4985 if (hasWebURI(intent)) { 4986 CrossProfileDomainInfo xpDomainInfo = null; 4987 final UserInfo parent = getProfileParent(userId); 4988 if (parent != null) { 4989 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4990 flags, userId, parent.id); 4991 } 4992 if (xpDomainInfo != null) { 4993 if (xpResolveInfo != null) { 4994 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4995 // in the result. 4996 result.remove(xpResolveInfo); 4997 } 4998 if (result.size() == 0) { 4999 result.add(xpDomainInfo.resolveInfo); 5000 return result; 5001 } 5002 } else if (result.size() <= 1) { 5003 return result; 5004 } 5005 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5006 xpDomainInfo, userId); 5007 Collections.sort(result, mResolvePrioritySorter); 5008 } 5009 return result; 5010 } 5011 final PackageParser.Package pkg = mPackages.get(pkgName); 5012 if (pkg != null) { 5013 return filterIfNotSystemUser( 5014 mActivities.queryIntentForPackage( 5015 intent, resolvedType, flags, pkg.activities, userId), 5016 userId); 5017 } 5018 return new ArrayList<ResolveInfo>(); 5019 } 5020 } 5021 5022 private static class CrossProfileDomainInfo { 5023 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5024 ResolveInfo resolveInfo; 5025 /* Best domain verification status of the activities found in the other profile */ 5026 int bestDomainVerificationStatus; 5027 } 5028 5029 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5030 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5031 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5032 sourceUserId)) { 5033 return null; 5034 } 5035 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5036 resolvedType, flags, parentUserId); 5037 5038 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5039 return null; 5040 } 5041 CrossProfileDomainInfo result = null; 5042 int size = resultTargetUser.size(); 5043 for (int i = 0; i < size; i++) { 5044 ResolveInfo riTargetUser = resultTargetUser.get(i); 5045 // Intent filter verification is only for filters that specify a host. So don't return 5046 // those that handle all web uris. 5047 if (riTargetUser.handleAllWebDataURI) { 5048 continue; 5049 } 5050 String packageName = riTargetUser.activityInfo.packageName; 5051 PackageSetting ps = mSettings.mPackages.get(packageName); 5052 if (ps == null) { 5053 continue; 5054 } 5055 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5056 int status = (int)(verificationState >> 32); 5057 if (result == null) { 5058 result = new CrossProfileDomainInfo(); 5059 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5060 sourceUserId, parentUserId); 5061 result.bestDomainVerificationStatus = status; 5062 } else { 5063 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5064 result.bestDomainVerificationStatus); 5065 } 5066 } 5067 // Don't consider matches with status NEVER across profiles. 5068 if (result != null && result.bestDomainVerificationStatus 5069 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5070 return null; 5071 } 5072 return result; 5073 } 5074 5075 /** 5076 * Verification statuses are ordered from the worse to the best, except for 5077 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5078 */ 5079 private int bestDomainVerificationStatus(int status1, int status2) { 5080 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5081 return status2; 5082 } 5083 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5084 return status1; 5085 } 5086 return (int) MathUtils.max(status1, status2); 5087 } 5088 5089 private boolean isUserEnabled(int userId) { 5090 long callingId = Binder.clearCallingIdentity(); 5091 try { 5092 UserInfo userInfo = sUserManager.getUserInfo(userId); 5093 return userInfo != null && userInfo.isEnabled(); 5094 } finally { 5095 Binder.restoreCallingIdentity(callingId); 5096 } 5097 } 5098 5099 /** 5100 * Filter out activities with systemUserOnly flag set, when current user is not System. 5101 * 5102 * @return filtered list 5103 */ 5104 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5105 if (userId == UserHandle.USER_SYSTEM) { 5106 return resolveInfos; 5107 } 5108 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5109 ResolveInfo info = resolveInfos.get(i); 5110 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5111 resolveInfos.remove(i); 5112 } 5113 } 5114 return resolveInfos; 5115 } 5116 5117 /** 5118 * @param resolveInfos list of resolve infos in descending priority order 5119 * @return if the list contains a resolve info with non-negative priority 5120 */ 5121 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5122 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5123 } 5124 5125 private static boolean hasWebURI(Intent intent) { 5126 if (intent.getData() == null) { 5127 return false; 5128 } 5129 final String scheme = intent.getScheme(); 5130 if (TextUtils.isEmpty(scheme)) { 5131 return false; 5132 } 5133 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5134 } 5135 5136 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5137 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5138 int userId) { 5139 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5140 5141 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5142 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5143 candidates.size()); 5144 } 5145 5146 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5147 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5148 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5149 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5150 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5151 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5152 5153 synchronized (mPackages) { 5154 final int count = candidates.size(); 5155 // First, try to use linked apps. Partition the candidates into four lists: 5156 // one for the final results, one for the "do not use ever", one for "undefined status" 5157 // and finally one for "browser app type". 5158 for (int n=0; n<count; n++) { 5159 ResolveInfo info = candidates.get(n); 5160 String packageName = info.activityInfo.packageName; 5161 PackageSetting ps = mSettings.mPackages.get(packageName); 5162 if (ps != null) { 5163 // Add to the special match all list (Browser use case) 5164 if (info.handleAllWebDataURI) { 5165 matchAllList.add(info); 5166 continue; 5167 } 5168 // Try to get the status from User settings first 5169 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5170 int status = (int)(packedStatus >> 32); 5171 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5172 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5173 if (DEBUG_DOMAIN_VERIFICATION) { 5174 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5175 + " : linkgen=" + linkGeneration); 5176 } 5177 // Use link-enabled generation as preferredOrder, i.e. 5178 // prefer newly-enabled over earlier-enabled. 5179 info.preferredOrder = linkGeneration; 5180 alwaysList.add(info); 5181 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5182 if (DEBUG_DOMAIN_VERIFICATION) { 5183 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5184 } 5185 neverList.add(info); 5186 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5187 if (DEBUG_DOMAIN_VERIFICATION) { 5188 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5189 } 5190 alwaysAskList.add(info); 5191 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5192 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5193 if (DEBUG_DOMAIN_VERIFICATION) { 5194 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5195 } 5196 undefinedList.add(info); 5197 } 5198 } 5199 } 5200 5201 // We'll want to include browser possibilities in a few cases 5202 boolean includeBrowser = false; 5203 5204 // First try to add the "always" resolution(s) for the current user, if any 5205 if (alwaysList.size() > 0) { 5206 result.addAll(alwaysList); 5207 } else { 5208 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5209 result.addAll(undefinedList); 5210 // Maybe add one for the other profile. 5211 if (xpDomainInfo != null && ( 5212 xpDomainInfo.bestDomainVerificationStatus 5213 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5214 result.add(xpDomainInfo.resolveInfo); 5215 } 5216 includeBrowser = true; 5217 } 5218 5219 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5220 // If there were 'always' entries their preferred order has been set, so we also 5221 // back that off to make the alternatives equivalent 5222 if (alwaysAskList.size() > 0) { 5223 for (ResolveInfo i : result) { 5224 i.preferredOrder = 0; 5225 } 5226 result.addAll(alwaysAskList); 5227 includeBrowser = true; 5228 } 5229 5230 if (includeBrowser) { 5231 // Also add browsers (all of them or only the default one) 5232 if (DEBUG_DOMAIN_VERIFICATION) { 5233 Slog.v(TAG, " ...including browsers in candidate set"); 5234 } 5235 if ((matchFlags & MATCH_ALL) != 0) { 5236 result.addAll(matchAllList); 5237 } else { 5238 // Browser/generic handling case. If there's a default browser, go straight 5239 // to that (but only if there is no other higher-priority match). 5240 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5241 int maxMatchPrio = 0; 5242 ResolveInfo defaultBrowserMatch = null; 5243 final int numCandidates = matchAllList.size(); 5244 for (int n = 0; n < numCandidates; n++) { 5245 ResolveInfo info = matchAllList.get(n); 5246 // track the highest overall match priority... 5247 if (info.priority > maxMatchPrio) { 5248 maxMatchPrio = info.priority; 5249 } 5250 // ...and the highest-priority default browser match 5251 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5252 if (defaultBrowserMatch == null 5253 || (defaultBrowserMatch.priority < info.priority)) { 5254 if (debug) { 5255 Slog.v(TAG, "Considering default browser match " + info); 5256 } 5257 defaultBrowserMatch = info; 5258 } 5259 } 5260 } 5261 if (defaultBrowserMatch != null 5262 && defaultBrowserMatch.priority >= maxMatchPrio 5263 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5264 { 5265 if (debug) { 5266 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5267 } 5268 result.add(defaultBrowserMatch); 5269 } else { 5270 result.addAll(matchAllList); 5271 } 5272 } 5273 5274 // If there is nothing selected, add all candidates and remove the ones that the user 5275 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5276 if (result.size() == 0) { 5277 result.addAll(candidates); 5278 result.removeAll(neverList); 5279 } 5280 } 5281 } 5282 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5283 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5284 result.size()); 5285 for (ResolveInfo info : result) { 5286 Slog.v(TAG, " + " + info.activityInfo); 5287 } 5288 } 5289 return result; 5290 } 5291 5292 // Returns a packed value as a long: 5293 // 5294 // high 'int'-sized word: link status: undefined/ask/never/always. 5295 // low 'int'-sized word: relative priority among 'always' results. 5296 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5297 long result = ps.getDomainVerificationStatusForUser(userId); 5298 // if none available, get the master status 5299 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5300 if (ps.getIntentFilterVerificationInfo() != null) { 5301 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5302 } 5303 } 5304 return result; 5305 } 5306 5307 private ResolveInfo querySkipCurrentProfileIntents( 5308 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5309 int flags, int sourceUserId) { 5310 if (matchingFilters != null) { 5311 int size = matchingFilters.size(); 5312 for (int i = 0; i < size; i ++) { 5313 CrossProfileIntentFilter filter = matchingFilters.get(i); 5314 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5315 // Checking if there are activities in the target user that can handle the 5316 // intent. 5317 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5318 resolvedType, flags, sourceUserId); 5319 if (resolveInfo != null) { 5320 return resolveInfo; 5321 } 5322 } 5323 } 5324 } 5325 return null; 5326 } 5327 5328 // Return matching ResolveInfo in target user if any. 5329 private ResolveInfo queryCrossProfileIntents( 5330 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5331 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5332 if (matchingFilters != null) { 5333 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5334 // match the same intent. For performance reasons, it is better not to 5335 // run queryIntent twice for the same userId 5336 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5337 int size = matchingFilters.size(); 5338 for (int i = 0; i < size; i++) { 5339 CrossProfileIntentFilter filter = matchingFilters.get(i); 5340 int targetUserId = filter.getTargetUserId(); 5341 boolean skipCurrentProfile = 5342 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5343 boolean skipCurrentProfileIfNoMatchFound = 5344 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5345 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5346 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5347 // Checking if there are activities in the target user that can handle the 5348 // intent. 5349 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5350 resolvedType, flags, sourceUserId); 5351 if (resolveInfo != null) return resolveInfo; 5352 alreadyTriedUserIds.put(targetUserId, true); 5353 } 5354 } 5355 } 5356 return null; 5357 } 5358 5359 /** 5360 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5361 * will forward the intent to the filter's target user. 5362 * Otherwise, returns null. 5363 */ 5364 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5365 String resolvedType, int flags, int sourceUserId) { 5366 int targetUserId = filter.getTargetUserId(); 5367 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5368 resolvedType, flags, targetUserId); 5369 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5370 && isUserEnabled(targetUserId)) { 5371 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5372 } 5373 return null; 5374 } 5375 5376 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5377 int sourceUserId, int targetUserId) { 5378 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5379 long ident = Binder.clearCallingIdentity(); 5380 boolean targetIsProfile; 5381 try { 5382 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5383 } finally { 5384 Binder.restoreCallingIdentity(ident); 5385 } 5386 String className; 5387 if (targetIsProfile) { 5388 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5389 } else { 5390 className = FORWARD_INTENT_TO_PARENT; 5391 } 5392 ComponentName forwardingActivityComponentName = new ComponentName( 5393 mAndroidApplication.packageName, className); 5394 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5395 sourceUserId); 5396 if (!targetIsProfile) { 5397 forwardingActivityInfo.showUserIcon = targetUserId; 5398 forwardingResolveInfo.noResourceId = true; 5399 } 5400 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5401 forwardingResolveInfo.priority = 0; 5402 forwardingResolveInfo.preferredOrder = 0; 5403 forwardingResolveInfo.match = 0; 5404 forwardingResolveInfo.isDefault = true; 5405 forwardingResolveInfo.filter = filter; 5406 forwardingResolveInfo.targetUserId = targetUserId; 5407 return forwardingResolveInfo; 5408 } 5409 5410 @Override 5411 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5412 Intent[] specifics, String[] specificTypes, Intent intent, 5413 String resolvedType, int flags, int userId) { 5414 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5415 flags = updateFlagsForResolve(flags, userId, intent); 5416 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5417 false, "query intent activity options"); 5418 final String resultsAction = intent.getAction(); 5419 5420 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5421 | PackageManager.GET_RESOLVED_FILTER, userId); 5422 5423 if (DEBUG_INTENT_MATCHING) { 5424 Log.v(TAG, "Query " + intent + ": " + results); 5425 } 5426 5427 int specificsPos = 0; 5428 int N; 5429 5430 // todo: note that the algorithm used here is O(N^2). This 5431 // isn't a problem in our current environment, but if we start running 5432 // into situations where we have more than 5 or 10 matches then this 5433 // should probably be changed to something smarter... 5434 5435 // First we go through and resolve each of the specific items 5436 // that were supplied, taking care of removing any corresponding 5437 // duplicate items in the generic resolve list. 5438 if (specifics != null) { 5439 for (int i=0; i<specifics.length; i++) { 5440 final Intent sintent = specifics[i]; 5441 if (sintent == null) { 5442 continue; 5443 } 5444 5445 if (DEBUG_INTENT_MATCHING) { 5446 Log.v(TAG, "Specific #" + i + ": " + sintent); 5447 } 5448 5449 String action = sintent.getAction(); 5450 if (resultsAction != null && resultsAction.equals(action)) { 5451 // If this action was explicitly requested, then don't 5452 // remove things that have it. 5453 action = null; 5454 } 5455 5456 ResolveInfo ri = null; 5457 ActivityInfo ai = null; 5458 5459 ComponentName comp = sintent.getComponent(); 5460 if (comp == null) { 5461 ri = resolveIntent( 5462 sintent, 5463 specificTypes != null ? specificTypes[i] : null, 5464 flags, userId); 5465 if (ri == null) { 5466 continue; 5467 } 5468 if (ri == mResolveInfo) { 5469 // ACK! Must do something better with this. 5470 } 5471 ai = ri.activityInfo; 5472 comp = new ComponentName(ai.applicationInfo.packageName, 5473 ai.name); 5474 } else { 5475 ai = getActivityInfo(comp, flags, userId); 5476 if (ai == null) { 5477 continue; 5478 } 5479 } 5480 5481 // Look for any generic query activities that are duplicates 5482 // of this specific one, and remove them from the results. 5483 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5484 N = results.size(); 5485 int j; 5486 for (j=specificsPos; j<N; j++) { 5487 ResolveInfo sri = results.get(j); 5488 if ((sri.activityInfo.name.equals(comp.getClassName()) 5489 && sri.activityInfo.applicationInfo.packageName.equals( 5490 comp.getPackageName())) 5491 || (action != null && sri.filter.matchAction(action))) { 5492 results.remove(j); 5493 if (DEBUG_INTENT_MATCHING) Log.v( 5494 TAG, "Removing duplicate item from " + j 5495 + " due to specific " + specificsPos); 5496 if (ri == null) { 5497 ri = sri; 5498 } 5499 j--; 5500 N--; 5501 } 5502 } 5503 5504 // Add this specific item to its proper place. 5505 if (ri == null) { 5506 ri = new ResolveInfo(); 5507 ri.activityInfo = ai; 5508 } 5509 results.add(specificsPos, ri); 5510 ri.specificIndex = i; 5511 specificsPos++; 5512 } 5513 } 5514 5515 // Now we go through the remaining generic results and remove any 5516 // duplicate actions that are found here. 5517 N = results.size(); 5518 for (int i=specificsPos; i<N-1; i++) { 5519 final ResolveInfo rii = results.get(i); 5520 if (rii.filter == null) { 5521 continue; 5522 } 5523 5524 // Iterate over all of the actions of this result's intent 5525 // filter... typically this should be just one. 5526 final Iterator<String> it = rii.filter.actionsIterator(); 5527 if (it == null) { 5528 continue; 5529 } 5530 while (it.hasNext()) { 5531 final String action = it.next(); 5532 if (resultsAction != null && resultsAction.equals(action)) { 5533 // If this action was explicitly requested, then don't 5534 // remove things that have it. 5535 continue; 5536 } 5537 for (int j=i+1; j<N; j++) { 5538 final ResolveInfo rij = results.get(j); 5539 if (rij.filter != null && rij.filter.hasAction(action)) { 5540 results.remove(j); 5541 if (DEBUG_INTENT_MATCHING) Log.v( 5542 TAG, "Removing duplicate item from " + j 5543 + " due to action " + action + " at " + i); 5544 j--; 5545 N--; 5546 } 5547 } 5548 } 5549 5550 // If the caller didn't request filter information, drop it now 5551 // so we don't have to marshall/unmarshall it. 5552 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5553 rii.filter = null; 5554 } 5555 } 5556 5557 // Filter out the caller activity if so requested. 5558 if (caller != null) { 5559 N = results.size(); 5560 for (int i=0; i<N; i++) { 5561 ActivityInfo ainfo = results.get(i).activityInfo; 5562 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5563 && caller.getClassName().equals(ainfo.name)) { 5564 results.remove(i); 5565 break; 5566 } 5567 } 5568 } 5569 5570 // If the caller didn't request filter information, 5571 // drop them now so we don't have to 5572 // marshall/unmarshall it. 5573 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5574 N = results.size(); 5575 for (int i=0; i<N; i++) { 5576 results.get(i).filter = null; 5577 } 5578 } 5579 5580 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5581 return results; 5582 } 5583 5584 @Override 5585 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5586 int userId) { 5587 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5588 flags = updateFlagsForResolve(flags, userId, intent); 5589 ComponentName comp = intent.getComponent(); 5590 if (comp == null) { 5591 if (intent.getSelector() != null) { 5592 intent = intent.getSelector(); 5593 comp = intent.getComponent(); 5594 } 5595 } 5596 if (comp != null) { 5597 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5598 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5599 if (ai != null) { 5600 ResolveInfo ri = new ResolveInfo(); 5601 ri.activityInfo = ai; 5602 list.add(ri); 5603 } 5604 return list; 5605 } 5606 5607 // reader 5608 synchronized (mPackages) { 5609 String pkgName = intent.getPackage(); 5610 if (pkgName == null) { 5611 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5612 } 5613 final PackageParser.Package pkg = mPackages.get(pkgName); 5614 if (pkg != null) { 5615 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5616 userId); 5617 } 5618 return null; 5619 } 5620 } 5621 5622 @Override 5623 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5624 if (!sUserManager.exists(userId)) return null; 5625 flags = updateFlagsForResolve(flags, userId, intent); 5626 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5627 if (query != null) { 5628 if (query.size() >= 1) { 5629 // If there is more than one service with the same priority, 5630 // just arbitrarily pick the first one. 5631 return query.get(0); 5632 } 5633 } 5634 return null; 5635 } 5636 5637 @Override 5638 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5639 int userId) { 5640 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5641 flags = updateFlagsForResolve(flags, userId, intent); 5642 ComponentName comp = intent.getComponent(); 5643 if (comp == null) { 5644 if (intent.getSelector() != null) { 5645 intent = intent.getSelector(); 5646 comp = intent.getComponent(); 5647 } 5648 } 5649 if (comp != null) { 5650 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5651 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5652 if (si != null) { 5653 final ResolveInfo ri = new ResolveInfo(); 5654 ri.serviceInfo = si; 5655 list.add(ri); 5656 } 5657 return list; 5658 } 5659 5660 // reader 5661 synchronized (mPackages) { 5662 String pkgName = intent.getPackage(); 5663 if (pkgName == null) { 5664 return mServices.queryIntent(intent, resolvedType, flags, userId); 5665 } 5666 final PackageParser.Package pkg = mPackages.get(pkgName); 5667 if (pkg != null) { 5668 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5669 userId); 5670 } 5671 return null; 5672 } 5673 } 5674 5675 @Override 5676 public List<ResolveInfo> queryIntentContentProviders( 5677 Intent intent, String resolvedType, int flags, int userId) { 5678 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5679 flags = updateFlagsForResolve(flags, userId, intent); 5680 ComponentName comp = intent.getComponent(); 5681 if (comp == null) { 5682 if (intent.getSelector() != null) { 5683 intent = intent.getSelector(); 5684 comp = intent.getComponent(); 5685 } 5686 } 5687 if (comp != null) { 5688 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5689 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5690 if (pi != null) { 5691 final ResolveInfo ri = new ResolveInfo(); 5692 ri.providerInfo = pi; 5693 list.add(ri); 5694 } 5695 return list; 5696 } 5697 5698 // reader 5699 synchronized (mPackages) { 5700 String pkgName = intent.getPackage(); 5701 if (pkgName == null) { 5702 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5703 } 5704 final PackageParser.Package pkg = mPackages.get(pkgName); 5705 if (pkg != null) { 5706 return mProviders.queryIntentForPackage( 5707 intent, resolvedType, flags, pkg.providers, userId); 5708 } 5709 return null; 5710 } 5711 } 5712 5713 @Override 5714 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5715 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5716 flags = updateFlagsForPackage(flags, userId, null); 5717 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5718 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5719 5720 // writer 5721 synchronized (mPackages) { 5722 ArrayList<PackageInfo> list; 5723 if (listUninstalled) { 5724 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5725 for (PackageSetting ps : mSettings.mPackages.values()) { 5726 PackageInfo pi; 5727 if (ps.pkg != null) { 5728 pi = generatePackageInfo(ps.pkg, flags, userId); 5729 } else { 5730 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5731 } 5732 if (pi != null) { 5733 list.add(pi); 5734 } 5735 } 5736 } else { 5737 list = new ArrayList<PackageInfo>(mPackages.size()); 5738 for (PackageParser.Package p : mPackages.values()) { 5739 PackageInfo pi = generatePackageInfo(p, flags, userId); 5740 if (pi != null) { 5741 list.add(pi); 5742 } 5743 } 5744 } 5745 5746 return new ParceledListSlice<PackageInfo>(list); 5747 } 5748 } 5749 5750 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5751 String[] permissions, boolean[] tmp, int flags, int userId) { 5752 int numMatch = 0; 5753 final PermissionsState permissionsState = ps.getPermissionsState(); 5754 for (int i=0; i<permissions.length; i++) { 5755 final String permission = permissions[i]; 5756 if (permissionsState.hasPermission(permission, userId)) { 5757 tmp[i] = true; 5758 numMatch++; 5759 } else { 5760 tmp[i] = false; 5761 } 5762 } 5763 if (numMatch == 0) { 5764 return; 5765 } 5766 PackageInfo pi; 5767 if (ps.pkg != null) { 5768 pi = generatePackageInfo(ps.pkg, flags, userId); 5769 } else { 5770 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5771 } 5772 // The above might return null in cases of uninstalled apps or install-state 5773 // skew across users/profiles. 5774 if (pi != null) { 5775 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5776 if (numMatch == permissions.length) { 5777 pi.requestedPermissions = permissions; 5778 } else { 5779 pi.requestedPermissions = new String[numMatch]; 5780 numMatch = 0; 5781 for (int i=0; i<permissions.length; i++) { 5782 if (tmp[i]) { 5783 pi.requestedPermissions[numMatch] = permissions[i]; 5784 numMatch++; 5785 } 5786 } 5787 } 5788 } 5789 list.add(pi); 5790 } 5791 } 5792 5793 @Override 5794 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5795 String[] permissions, int flags, int userId) { 5796 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5797 flags = updateFlagsForPackage(flags, userId, permissions); 5798 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5799 5800 // writer 5801 synchronized (mPackages) { 5802 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5803 boolean[] tmpBools = new boolean[permissions.length]; 5804 if (listUninstalled) { 5805 for (PackageSetting ps : mSettings.mPackages.values()) { 5806 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5807 } 5808 } else { 5809 for (PackageParser.Package pkg : mPackages.values()) { 5810 PackageSetting ps = (PackageSetting)pkg.mExtras; 5811 if (ps != null) { 5812 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5813 userId); 5814 } 5815 } 5816 } 5817 5818 return new ParceledListSlice<PackageInfo>(list); 5819 } 5820 } 5821 5822 @Override 5823 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5824 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5825 flags = updateFlagsForApplication(flags, userId, null); 5826 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5827 5828 // writer 5829 synchronized (mPackages) { 5830 ArrayList<ApplicationInfo> list; 5831 if (listUninstalled) { 5832 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5833 for (PackageSetting ps : mSettings.mPackages.values()) { 5834 ApplicationInfo ai; 5835 if (ps.pkg != null) { 5836 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5837 ps.readUserState(userId), userId); 5838 } else { 5839 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5840 } 5841 if (ai != null) { 5842 list.add(ai); 5843 } 5844 } 5845 } else { 5846 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5847 for (PackageParser.Package p : mPackages.values()) { 5848 if (p.mExtras != null) { 5849 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5850 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5851 if (ai != null) { 5852 list.add(ai); 5853 } 5854 } 5855 } 5856 } 5857 5858 return new ParceledListSlice<ApplicationInfo>(list); 5859 } 5860 } 5861 5862 @Override 5863 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5864 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5865 "getEphemeralApplications"); 5866 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5867 "getEphemeralApplications"); 5868 synchronized (mPackages) { 5869 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5870 .getEphemeralApplicationsLPw(userId); 5871 if (ephemeralApps != null) { 5872 return new ParceledListSlice<>(ephemeralApps); 5873 } 5874 } 5875 return null; 5876 } 5877 5878 @Override 5879 public boolean isEphemeralApplication(String packageName, int userId) { 5880 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5881 "isEphemeral"); 5882 if (!isCallerSameApp(packageName)) { 5883 return false; 5884 } 5885 synchronized (mPackages) { 5886 PackageParser.Package pkg = mPackages.get(packageName); 5887 if (pkg != null) { 5888 return pkg.applicationInfo.isEphemeralApp(); 5889 } 5890 } 5891 return false; 5892 } 5893 5894 @Override 5895 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5896 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5897 "getCookie"); 5898 if (!isCallerSameApp(packageName)) { 5899 return null; 5900 } 5901 synchronized (mPackages) { 5902 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5903 packageName, userId); 5904 } 5905 } 5906 5907 @Override 5908 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5909 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5910 "setCookie"); 5911 if (!isCallerSameApp(packageName)) { 5912 return false; 5913 } 5914 synchronized (mPackages) { 5915 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5916 packageName, cookie, userId); 5917 } 5918 } 5919 5920 @Override 5921 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5922 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5923 "getEphemeralApplicationIcon"); 5924 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5925 "getEphemeralApplicationIcon"); 5926 synchronized (mPackages) { 5927 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5928 packageName, userId); 5929 } 5930 } 5931 5932 private boolean isCallerSameApp(String packageName) { 5933 PackageParser.Package pkg = mPackages.get(packageName); 5934 return pkg != null 5935 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5936 } 5937 5938 public List<ApplicationInfo> getPersistentApplications(int flags) { 5939 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5940 5941 // reader 5942 synchronized (mPackages) { 5943 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5944 final int userId = UserHandle.getCallingUserId(); 5945 while (i.hasNext()) { 5946 final PackageParser.Package p = i.next(); 5947 if (p.applicationInfo != null 5948 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5949 && (!mSafeMode || isSystemApp(p))) { 5950 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5951 if (ps != null) { 5952 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5953 ps.readUserState(userId), userId); 5954 if (ai != null) { 5955 finalList.add(ai); 5956 } 5957 } 5958 } 5959 } 5960 } 5961 5962 return finalList; 5963 } 5964 5965 @Override 5966 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5967 if (!sUserManager.exists(userId)) return null; 5968 flags = updateFlagsForComponent(flags, userId, name); 5969 // reader 5970 synchronized (mPackages) { 5971 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5972 PackageSetting ps = provider != null 5973 ? mSettings.mPackages.get(provider.owner.packageName) 5974 : null; 5975 return ps != null 5976 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 5977 && (!mSafeMode || (provider.info.applicationInfo.flags 5978 &ApplicationInfo.FLAG_SYSTEM) != 0) 5979 ? PackageParser.generateProviderInfo(provider, flags, 5980 ps.readUserState(userId), userId) 5981 : null; 5982 } 5983 } 5984 5985 /** 5986 * @deprecated 5987 */ 5988 @Deprecated 5989 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5990 // reader 5991 synchronized (mPackages) { 5992 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5993 .entrySet().iterator(); 5994 final int userId = UserHandle.getCallingUserId(); 5995 while (i.hasNext()) { 5996 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5997 PackageParser.Provider p = entry.getValue(); 5998 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5999 6000 if (ps != null && p.syncable 6001 && (!mSafeMode || (p.info.applicationInfo.flags 6002 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6003 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6004 ps.readUserState(userId), userId); 6005 if (info != null) { 6006 outNames.add(entry.getKey()); 6007 outInfo.add(info); 6008 } 6009 } 6010 } 6011 } 6012 } 6013 6014 @Override 6015 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6016 int uid, int flags) { 6017 final int userId = processName != null ? UserHandle.getUserId(uid) 6018 : UserHandle.getCallingUserId(); 6019 if (!sUserManager.exists(userId)) return null; 6020 flags = updateFlagsForComponent(flags, userId, processName); 6021 6022 ArrayList<ProviderInfo> finalList = null; 6023 // reader 6024 synchronized (mPackages) { 6025 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6026 while (i.hasNext()) { 6027 final PackageParser.Provider p = i.next(); 6028 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6029 if (ps != null && p.info.authority != null 6030 && (processName == null 6031 || (p.info.processName.equals(processName) 6032 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6033 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId) 6034 && (!mSafeMode 6035 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 6036 if (finalList == null) { 6037 finalList = new ArrayList<ProviderInfo>(3); 6038 } 6039 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6040 ps.readUserState(userId), userId); 6041 if (info != null) { 6042 finalList.add(info); 6043 } 6044 } 6045 } 6046 } 6047 6048 if (finalList != null) { 6049 Collections.sort(finalList, mProviderInitOrderSorter); 6050 return new ParceledListSlice<ProviderInfo>(finalList); 6051 } 6052 6053 return null; 6054 } 6055 6056 @Override 6057 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6058 // reader 6059 synchronized (mPackages) { 6060 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6061 return PackageParser.generateInstrumentationInfo(i, flags); 6062 } 6063 } 6064 6065 @Override 6066 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6067 int flags) { 6068 ArrayList<InstrumentationInfo> finalList = 6069 new ArrayList<InstrumentationInfo>(); 6070 6071 // reader 6072 synchronized (mPackages) { 6073 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6074 while (i.hasNext()) { 6075 final PackageParser.Instrumentation p = i.next(); 6076 if (targetPackage == null 6077 || targetPackage.equals(p.info.targetPackage)) { 6078 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6079 flags); 6080 if (ii != null) { 6081 finalList.add(ii); 6082 } 6083 } 6084 } 6085 } 6086 6087 return finalList; 6088 } 6089 6090 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6091 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6092 if (overlays == null) { 6093 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6094 return; 6095 } 6096 for (PackageParser.Package opkg : overlays.values()) { 6097 // Not much to do if idmap fails: we already logged the error 6098 // and we certainly don't want to abort installation of pkg simply 6099 // because an overlay didn't fit properly. For these reasons, 6100 // ignore the return value of createIdmapForPackagePairLI. 6101 createIdmapForPackagePairLI(pkg, opkg); 6102 } 6103 } 6104 6105 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6106 PackageParser.Package opkg) { 6107 if (!opkg.mTrustedOverlay) { 6108 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6109 opkg.baseCodePath + ": overlay not trusted"); 6110 return false; 6111 } 6112 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6113 if (overlaySet == null) { 6114 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6115 opkg.baseCodePath + " but target package has no known overlays"); 6116 return false; 6117 } 6118 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6119 // TODO: generate idmap for split APKs 6120 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 6121 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6122 + opkg.baseCodePath); 6123 return false; 6124 } 6125 PackageParser.Package[] overlayArray = 6126 overlaySet.values().toArray(new PackageParser.Package[0]); 6127 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6128 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6129 return p1.mOverlayPriority - p2.mOverlayPriority; 6130 } 6131 }; 6132 Arrays.sort(overlayArray, cmp); 6133 6134 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6135 int i = 0; 6136 for (PackageParser.Package p : overlayArray) { 6137 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6138 } 6139 return true; 6140 } 6141 6142 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6143 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6144 try { 6145 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6146 } finally { 6147 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6148 } 6149 } 6150 6151 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6152 final File[] files = dir.listFiles(); 6153 if (ArrayUtils.isEmpty(files)) { 6154 Log.d(TAG, "No files in app dir " + dir); 6155 return; 6156 } 6157 6158 if (DEBUG_PACKAGE_SCANNING) { 6159 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6160 + " flags=0x" + Integer.toHexString(parseFlags)); 6161 } 6162 6163 for (File file : files) { 6164 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6165 && !PackageInstallerService.isStageName(file.getName()); 6166 if (!isPackage) { 6167 // Ignore entries which are not packages 6168 continue; 6169 } 6170 try { 6171 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6172 scanFlags, currentTime, null); 6173 } catch (PackageManagerException e) { 6174 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6175 6176 // Delete invalid userdata apps 6177 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6178 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6179 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6180 if (file.isDirectory()) { 6181 mInstaller.rmPackageDir(file.getAbsolutePath()); 6182 } else { 6183 file.delete(); 6184 } 6185 } 6186 } 6187 } 6188 } 6189 6190 private static File getSettingsProblemFile() { 6191 File dataDir = Environment.getDataDirectory(); 6192 File systemDir = new File(dataDir, "system"); 6193 File fname = new File(systemDir, "uiderrors.txt"); 6194 return fname; 6195 } 6196 6197 static void reportSettingsProblem(int priority, String msg) { 6198 logCriticalInfo(priority, msg); 6199 } 6200 6201 static void logCriticalInfo(int priority, String msg) { 6202 Slog.println(priority, TAG, msg); 6203 EventLogTags.writePmCriticalInfo(msg); 6204 try { 6205 File fname = getSettingsProblemFile(); 6206 FileOutputStream out = new FileOutputStream(fname, true); 6207 PrintWriter pw = new FastPrintWriter(out); 6208 SimpleDateFormat formatter = new SimpleDateFormat(); 6209 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6210 pw.println(dateString + ": " + msg); 6211 pw.close(); 6212 FileUtils.setPermissions( 6213 fname.toString(), 6214 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6215 -1, -1); 6216 } catch (java.io.IOException e) { 6217 } 6218 } 6219 6220 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6221 PackageParser.Package pkg, File srcFile, int parseFlags) 6222 throws PackageManagerException { 6223 if (ps != null 6224 && ps.codePath.equals(srcFile) 6225 && ps.timeStamp == srcFile.lastModified() 6226 && !isCompatSignatureUpdateNeeded(pkg) 6227 && !isRecoverSignatureUpdateNeeded(pkg)) { 6228 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6229 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6230 ArraySet<PublicKey> signingKs; 6231 synchronized (mPackages) { 6232 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6233 } 6234 if (ps.signatures.mSignatures != null 6235 && ps.signatures.mSignatures.length != 0 6236 && signingKs != null) { 6237 // Optimization: reuse the existing cached certificates 6238 // if the package appears to be unchanged. 6239 pkg.mSignatures = ps.signatures.mSignatures; 6240 pkg.mSigningKeys = signingKs; 6241 return; 6242 } 6243 6244 Slog.w(TAG, "PackageSetting for " + ps.name 6245 + " is missing signatures. Collecting certs again to recover them."); 6246 } else { 6247 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6248 } 6249 6250 try { 6251 pp.collectCertificates(pkg, parseFlags); 6252 pp.collectManifestDigest(pkg); 6253 } catch (PackageParserException e) { 6254 throw PackageManagerException.from(e); 6255 } 6256 } 6257 6258 /** 6259 * Traces a package scan. 6260 * @see #scanPackageLI(File, int, int, long, UserHandle) 6261 */ 6262 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6263 long currentTime, UserHandle user) throws PackageManagerException { 6264 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6265 try { 6266 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6267 } finally { 6268 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6269 } 6270 } 6271 6272 /** 6273 * Scans a package and returns the newly parsed package. 6274 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6275 */ 6276 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6277 long currentTime, UserHandle user) throws PackageManagerException { 6278 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6279 parseFlags |= mDefParseFlags; 6280 PackageParser pp = new PackageParser(); 6281 pp.setSeparateProcesses(mSeparateProcesses); 6282 pp.setOnlyCoreApps(mOnlyCore); 6283 pp.setDisplayMetrics(mMetrics); 6284 6285 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6286 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6287 } 6288 6289 final PackageParser.Package pkg; 6290 try { 6291 pkg = pp.parsePackage(scanFile, parseFlags); 6292 } catch (PackageParserException e) { 6293 throw PackageManagerException.from(e); 6294 } 6295 6296 PackageSetting ps = null; 6297 PackageSetting updatedPkg; 6298 // reader 6299 synchronized (mPackages) { 6300 // Look to see if we already know about this package. 6301 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6302 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6303 // This package has been renamed to its original name. Let's 6304 // use that. 6305 ps = mSettings.peekPackageLPr(oldName); 6306 } 6307 // If there was no original package, see one for the real package name. 6308 if (ps == null) { 6309 ps = mSettings.peekPackageLPr(pkg.packageName); 6310 } 6311 // Check to see if this package could be hiding/updating a system 6312 // package. Must look for it either under the original or real 6313 // package name depending on our state. 6314 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6315 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6316 } 6317 boolean updatedPkgBetter = false; 6318 // First check if this is a system package that may involve an update 6319 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6320 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6321 // it needs to drop FLAG_PRIVILEGED. 6322 if (locationIsPrivileged(scanFile)) { 6323 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6324 } else { 6325 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6326 } 6327 6328 if (ps != null && !ps.codePath.equals(scanFile)) { 6329 // The path has changed from what was last scanned... check the 6330 // version of the new path against what we have stored to determine 6331 // what to do. 6332 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6333 if (pkg.mVersionCode <= ps.versionCode) { 6334 // The system package has been updated and the code path does not match 6335 // Ignore entry. Skip it. 6336 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6337 + " ignored: updated version " + ps.versionCode 6338 + " better than this " + pkg.mVersionCode); 6339 if (!updatedPkg.codePath.equals(scanFile)) { 6340 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 6341 + ps.name + " changing from " + updatedPkg.codePathString 6342 + " to " + scanFile); 6343 updatedPkg.codePath = scanFile; 6344 updatedPkg.codePathString = scanFile.toString(); 6345 updatedPkg.resourcePath = scanFile; 6346 updatedPkg.resourcePathString = scanFile.toString(); 6347 } 6348 updatedPkg.pkg = pkg; 6349 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6350 "Package " + ps.name + " at " + scanFile 6351 + " ignored: updated version " + ps.versionCode 6352 + " better than this " + pkg.mVersionCode); 6353 } else { 6354 // The current app on the system partition is better than 6355 // what we have updated to on the data partition; switch 6356 // back to the system partition version. 6357 // At this point, its safely assumed that package installation for 6358 // apps in system partition will go through. If not there won't be a working 6359 // version of the app 6360 // writer 6361 synchronized (mPackages) { 6362 // Just remove the loaded entries from package lists. 6363 mPackages.remove(ps.name); 6364 } 6365 6366 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6367 + " reverting from " + ps.codePathString 6368 + ": new version " + pkg.mVersionCode 6369 + " better than installed " + ps.versionCode); 6370 6371 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6372 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6373 synchronized (mInstallLock) { 6374 args.cleanUpResourcesLI(); 6375 } 6376 synchronized (mPackages) { 6377 mSettings.enableSystemPackageLPw(ps.name); 6378 } 6379 updatedPkgBetter = true; 6380 } 6381 } 6382 } 6383 6384 if (updatedPkg != null) { 6385 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6386 // initially 6387 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6388 6389 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6390 // flag set initially 6391 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6392 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6393 } 6394 } 6395 6396 // Verify certificates against what was last scanned 6397 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6398 6399 /* 6400 * A new system app appeared, but we already had a non-system one of the 6401 * same name installed earlier. 6402 */ 6403 boolean shouldHideSystemApp = false; 6404 if (updatedPkg == null && ps != null 6405 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6406 /* 6407 * Check to make sure the signatures match first. If they don't, 6408 * wipe the installed application and its data. 6409 */ 6410 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6411 != PackageManager.SIGNATURE_MATCH) { 6412 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6413 + " signatures don't match existing userdata copy; removing"); 6414 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6415 ps = null; 6416 } else { 6417 /* 6418 * If the newly-added system app is an older version than the 6419 * already installed version, hide it. It will be scanned later 6420 * and re-added like an update. 6421 */ 6422 if (pkg.mVersionCode <= ps.versionCode) { 6423 shouldHideSystemApp = true; 6424 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6425 + " but new version " + pkg.mVersionCode + " better than installed " 6426 + ps.versionCode + "; hiding system"); 6427 } else { 6428 /* 6429 * The newly found system app is a newer version that the 6430 * one previously installed. Simply remove the 6431 * already-installed application and replace it with our own 6432 * while keeping the application data. 6433 */ 6434 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6435 + " reverting from " + ps.codePathString + ": new version " 6436 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6437 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6438 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6439 synchronized (mInstallLock) { 6440 args.cleanUpResourcesLI(); 6441 } 6442 } 6443 } 6444 } 6445 6446 // The apk is forward locked (not public) if its code and resources 6447 // are kept in different files. (except for app in either system or 6448 // vendor path). 6449 // TODO grab this value from PackageSettings 6450 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6451 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6452 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6453 } 6454 } 6455 6456 // TODO: extend to support forward-locked splits 6457 String resourcePath = null; 6458 String baseResourcePath = null; 6459 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6460 if (ps != null && ps.resourcePathString != null) { 6461 resourcePath = ps.resourcePathString; 6462 baseResourcePath = ps.resourcePathString; 6463 } else { 6464 // Should not happen at all. Just log an error. 6465 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6466 } 6467 } else { 6468 resourcePath = pkg.codePath; 6469 baseResourcePath = pkg.baseCodePath; 6470 } 6471 6472 // Set application objects path explicitly. 6473 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6474 pkg.applicationInfo.setCodePath(pkg.codePath); 6475 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6476 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6477 pkg.applicationInfo.setResourcePath(resourcePath); 6478 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6479 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6480 6481 // Note that we invoke the following method only if we are about to unpack an application 6482 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6483 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6484 6485 /* 6486 * If the system app should be overridden by a previously installed 6487 * data, hide the system app now and let the /data/app scan pick it up 6488 * again. 6489 */ 6490 if (shouldHideSystemApp) { 6491 synchronized (mPackages) { 6492 mSettings.disableSystemPackageLPw(pkg.packageName); 6493 } 6494 } 6495 6496 return scannedPkg; 6497 } 6498 6499 private static String fixProcessName(String defProcessName, 6500 String processName, int uid) { 6501 if (processName == null) { 6502 return defProcessName; 6503 } 6504 return processName; 6505 } 6506 6507 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6508 throws PackageManagerException { 6509 if (pkgSetting.signatures.mSignatures != null) { 6510 // Already existing package. Make sure signatures match 6511 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6512 == PackageManager.SIGNATURE_MATCH; 6513 if (!match) { 6514 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6515 == PackageManager.SIGNATURE_MATCH; 6516 } 6517 if (!match) { 6518 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6519 == PackageManager.SIGNATURE_MATCH; 6520 } 6521 if (!match) { 6522 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6523 + pkg.packageName + " signatures do not match the " 6524 + "previously installed version; ignoring!"); 6525 } 6526 } 6527 6528 // Check for shared user signatures 6529 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6530 // Already existing package. Make sure signatures match 6531 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6532 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6533 if (!match) { 6534 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6535 == PackageManager.SIGNATURE_MATCH; 6536 } 6537 if (!match) { 6538 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6539 == PackageManager.SIGNATURE_MATCH; 6540 } 6541 if (!match) { 6542 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6543 "Package " + pkg.packageName 6544 + " has no signatures that match those in shared user " 6545 + pkgSetting.sharedUser.name + "; ignoring!"); 6546 } 6547 } 6548 } 6549 6550 /** 6551 * Enforces that only the system UID or root's UID can call a method exposed 6552 * via Binder. 6553 * 6554 * @param message used as message if SecurityException is thrown 6555 * @throws SecurityException if the caller is not system or root 6556 */ 6557 private static final void enforceSystemOrRoot(String message) { 6558 final int uid = Binder.getCallingUid(); 6559 if (uid != Process.SYSTEM_UID && uid != 0) { 6560 throw new SecurityException(message); 6561 } 6562 } 6563 6564 @Override 6565 public void performFstrimIfNeeded() { 6566 enforceSystemOrRoot("Only the system can request fstrim"); 6567 6568 // Before everything else, see whether we need to fstrim. 6569 try { 6570 IMountService ms = PackageHelper.getMountService(); 6571 if (ms != null) { 6572 final boolean isUpgrade = isUpgrade(); 6573 boolean doTrim = isUpgrade; 6574 if (doTrim) { 6575 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6576 } else { 6577 final long interval = android.provider.Settings.Global.getLong( 6578 mContext.getContentResolver(), 6579 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6580 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6581 if (interval > 0) { 6582 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6583 if (timeSinceLast > interval) { 6584 doTrim = true; 6585 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6586 + "; running immediately"); 6587 } 6588 } 6589 } 6590 if (doTrim) { 6591 if (!isFirstBoot()) { 6592 try { 6593 ActivityManagerNative.getDefault().showBootMessage( 6594 mContext.getResources().getString( 6595 R.string.android_upgrading_fstrim), true); 6596 } catch (RemoteException e) { 6597 } 6598 } 6599 ms.runMaintenance(); 6600 } 6601 } else { 6602 Slog.e(TAG, "Mount service unavailable!"); 6603 } 6604 } catch (RemoteException e) { 6605 // Can't happen; MountService is local 6606 } 6607 } 6608 6609 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6610 List<ResolveInfo> ris = null; 6611 try { 6612 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6613 intent, null, 0, userId); 6614 } catch (RemoteException e) { 6615 } 6616 ArraySet<String> pkgNames = new ArraySet<String>(); 6617 if (ris != null) { 6618 for (ResolveInfo ri : ris) { 6619 pkgNames.add(ri.activityInfo.packageName); 6620 } 6621 } 6622 return pkgNames; 6623 } 6624 6625 @Override 6626 public void notifyPackageUse(String packageName) { 6627 synchronized (mPackages) { 6628 PackageParser.Package p = mPackages.get(packageName); 6629 if (p == null) { 6630 return; 6631 } 6632 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6633 } 6634 } 6635 6636 @Override 6637 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6638 return performDexOptTraced(packageName, instructionSet); 6639 } 6640 6641 public boolean performDexOpt(String packageName, String instructionSet) { 6642 return performDexOptTraced(packageName, instructionSet); 6643 } 6644 6645 private boolean performDexOptTraced(String packageName, String instructionSet) { 6646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6647 try { 6648 return performDexOptInternal(packageName, instructionSet); 6649 } finally { 6650 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6651 } 6652 } 6653 6654 private boolean performDexOptInternal(String packageName, String instructionSet) { 6655 PackageParser.Package p; 6656 final String targetInstructionSet; 6657 synchronized (mPackages) { 6658 p = mPackages.get(packageName); 6659 if (p == null) { 6660 return false; 6661 } 6662 mPackageUsage.write(false); 6663 6664 targetInstructionSet = instructionSet != null ? instructionSet : 6665 getPrimaryInstructionSet(p.applicationInfo); 6666 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6667 return false; 6668 } 6669 } 6670 long callingId = Binder.clearCallingIdentity(); 6671 try { 6672 synchronized (mInstallLock) { 6673 final String[] instructionSets = new String[] { targetInstructionSet }; 6674 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6675 true /* inclDependencies */); 6676 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6677 } 6678 } finally { 6679 Binder.restoreCallingIdentity(callingId); 6680 } 6681 } 6682 6683 public ArraySet<String> getPackagesThatNeedDexOpt() { 6684 ArraySet<String> pkgs = null; 6685 synchronized (mPackages) { 6686 for (PackageParser.Package p : mPackages.values()) { 6687 if (DEBUG_DEXOPT) { 6688 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6689 } 6690 if (!p.mDexOptPerformed.isEmpty()) { 6691 continue; 6692 } 6693 if (pkgs == null) { 6694 pkgs = new ArraySet<String>(); 6695 } 6696 pkgs.add(p.packageName); 6697 } 6698 } 6699 return pkgs; 6700 } 6701 6702 public void shutdown() { 6703 mPackageUsage.write(true); 6704 } 6705 6706 @Override 6707 public void forceDexOpt(String packageName) { 6708 enforceSystemOrRoot("forceDexOpt"); 6709 6710 PackageParser.Package pkg; 6711 synchronized (mPackages) { 6712 pkg = mPackages.get(packageName); 6713 if (pkg == null) { 6714 throw new IllegalArgumentException("Missing package: " + packageName); 6715 } 6716 } 6717 6718 synchronized (mInstallLock) { 6719 final String[] instructionSets = new String[] { 6720 getPrimaryInstructionSet(pkg.applicationInfo) }; 6721 6722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6723 6724 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6725 true /* inclDependencies */); 6726 6727 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6728 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6729 throw new IllegalStateException("Failed to dexopt: " + res); 6730 } 6731 } 6732 } 6733 6734 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6735 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6736 Slog.w(TAG, "Unable to update from " + oldPkg.name 6737 + " to " + newPkg.packageName 6738 + ": old package not in system partition"); 6739 return false; 6740 } else if (mPackages.get(oldPkg.name) != null) { 6741 Slog.w(TAG, "Unable to update from " + oldPkg.name 6742 + " to " + newPkg.packageName 6743 + ": old package still exists"); 6744 return false; 6745 } 6746 return true; 6747 } 6748 6749 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6750 throws PackageManagerException { 6751 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6752 if (res != 0) { 6753 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6754 "Failed to install " + packageName + ": " + res); 6755 } 6756 6757 final int[] users = sUserManager.getUserIds(); 6758 for (int user : users) { 6759 if (user != 0) { 6760 res = mInstaller.createUserData(volumeUuid, packageName, 6761 UserHandle.getUid(user, uid), user, seinfo); 6762 if (res != 0) { 6763 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6764 "Failed to createUserData " + packageName + ": " + res); 6765 } 6766 } 6767 } 6768 } 6769 6770 private int removeDataDirsLI(String volumeUuid, String packageName) { 6771 int[] users = sUserManager.getUserIds(); 6772 int res = 0; 6773 for (int user : users) { 6774 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6775 if (resInner < 0) { 6776 res = resInner; 6777 } 6778 } 6779 6780 return res; 6781 } 6782 6783 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6784 int[] users = sUserManager.getUserIds(); 6785 int res = 0; 6786 for (int user : users) { 6787 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6788 if (resInner < 0) { 6789 res = resInner; 6790 } 6791 } 6792 return res; 6793 } 6794 6795 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6796 PackageParser.Package changingLib) { 6797 if (file.path != null) { 6798 usesLibraryFiles.add(file.path); 6799 return; 6800 } 6801 PackageParser.Package p = mPackages.get(file.apk); 6802 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6803 // If we are doing this while in the middle of updating a library apk, 6804 // then we need to make sure to use that new apk for determining the 6805 // dependencies here. (We haven't yet finished committing the new apk 6806 // to the package manager state.) 6807 if (p == null || p.packageName.equals(changingLib.packageName)) { 6808 p = changingLib; 6809 } 6810 } 6811 if (p != null) { 6812 usesLibraryFiles.addAll(p.getAllCodePaths()); 6813 } 6814 } 6815 6816 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6817 PackageParser.Package changingLib) throws PackageManagerException { 6818 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6819 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6820 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6821 for (int i=0; i<N; i++) { 6822 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6823 if (file == null) { 6824 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6825 "Package " + pkg.packageName + " requires unavailable shared library " 6826 + pkg.usesLibraries.get(i) + "; failing!"); 6827 } 6828 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6829 } 6830 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6831 for (int i=0; i<N; i++) { 6832 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6833 if (file == null) { 6834 Slog.w(TAG, "Package " + pkg.packageName 6835 + " desires unavailable shared library " 6836 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6837 } else { 6838 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6839 } 6840 } 6841 N = usesLibraryFiles.size(); 6842 if (N > 0) { 6843 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6844 } else { 6845 pkg.usesLibraryFiles = null; 6846 } 6847 } 6848 } 6849 6850 private static boolean hasString(List<String> list, List<String> which) { 6851 if (list == null) { 6852 return false; 6853 } 6854 for (int i=list.size()-1; i>=0; i--) { 6855 for (int j=which.size()-1; j>=0; j--) { 6856 if (which.get(j).equals(list.get(i))) { 6857 return true; 6858 } 6859 } 6860 } 6861 return false; 6862 } 6863 6864 private void updateAllSharedLibrariesLPw() { 6865 for (PackageParser.Package pkg : mPackages.values()) { 6866 try { 6867 updateSharedLibrariesLPw(pkg, null); 6868 } catch (PackageManagerException e) { 6869 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6870 } 6871 } 6872 } 6873 6874 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6875 PackageParser.Package changingPkg) { 6876 ArrayList<PackageParser.Package> res = null; 6877 for (PackageParser.Package pkg : mPackages.values()) { 6878 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6879 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6880 if (res == null) { 6881 res = new ArrayList<PackageParser.Package>(); 6882 } 6883 res.add(pkg); 6884 try { 6885 updateSharedLibrariesLPw(pkg, changingPkg); 6886 } catch (PackageManagerException e) { 6887 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6888 } 6889 } 6890 } 6891 return res; 6892 } 6893 6894 /** 6895 * Derive the value of the {@code cpuAbiOverride} based on the provided 6896 * value and an optional stored value from the package settings. 6897 */ 6898 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6899 String cpuAbiOverride = null; 6900 6901 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6902 cpuAbiOverride = null; 6903 } else if (abiOverride != null) { 6904 cpuAbiOverride = abiOverride; 6905 } else if (settings != null) { 6906 cpuAbiOverride = settings.cpuAbiOverrideString; 6907 } 6908 6909 return cpuAbiOverride; 6910 } 6911 6912 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6913 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6914 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6915 try { 6916 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6917 } finally { 6918 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6919 } 6920 } 6921 6922 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6923 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6924 boolean success = false; 6925 try { 6926 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6927 currentTime, user); 6928 success = true; 6929 return res; 6930 } finally { 6931 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6932 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6933 } 6934 } 6935 } 6936 6937 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6938 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6939 final File scanFile = new File(pkg.codePath); 6940 if (pkg.applicationInfo.getCodePath() == null || 6941 pkg.applicationInfo.getResourcePath() == null) { 6942 // Bail out. The resource and code paths haven't been set. 6943 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6944 "Code and resource paths haven't been set correctly"); 6945 } 6946 6947 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6948 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6949 } else { 6950 // Only allow system apps to be flagged as core apps. 6951 pkg.coreApp = false; 6952 } 6953 6954 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6955 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6956 } 6957 6958 if (mCustomResolverComponentName != null && 6959 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6960 setUpCustomResolverActivity(pkg); 6961 } 6962 6963 if (pkg.packageName.equals("android")) { 6964 synchronized (mPackages) { 6965 if (mAndroidApplication != null) { 6966 Slog.w(TAG, "*************************************************"); 6967 Slog.w(TAG, "Core android package being redefined. Skipping."); 6968 Slog.w(TAG, " file=" + scanFile); 6969 Slog.w(TAG, "*************************************************"); 6970 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6971 "Core android package being redefined. Skipping."); 6972 } 6973 6974 // Set up information for our fall-back user intent resolution activity. 6975 mPlatformPackage = pkg; 6976 pkg.mVersionCode = mSdkVersion; 6977 mAndroidApplication = pkg.applicationInfo; 6978 6979 if (!mResolverReplaced) { 6980 mResolveActivity.applicationInfo = mAndroidApplication; 6981 mResolveActivity.name = ResolverActivity.class.getName(); 6982 mResolveActivity.packageName = mAndroidApplication.packageName; 6983 mResolveActivity.processName = "system:ui"; 6984 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6985 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6986 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6987 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6988 mResolveActivity.exported = true; 6989 mResolveActivity.enabled = true; 6990 mResolveInfo.activityInfo = mResolveActivity; 6991 mResolveInfo.priority = 0; 6992 mResolveInfo.preferredOrder = 0; 6993 mResolveInfo.match = 0; 6994 mResolveComponentName = new ComponentName( 6995 mAndroidApplication.packageName, mResolveActivity.name); 6996 } 6997 } 6998 } 6999 7000 if (DEBUG_PACKAGE_SCANNING) { 7001 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7002 Log.d(TAG, "Scanning package " + pkg.packageName); 7003 } 7004 7005 if (mPackages.containsKey(pkg.packageName) 7006 || mSharedLibraries.containsKey(pkg.packageName)) { 7007 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7008 "Application package " + pkg.packageName 7009 + " already installed. Skipping duplicate."); 7010 } 7011 7012 // If we're only installing presumed-existing packages, require that the 7013 // scanned APK is both already known and at the path previously established 7014 // for it. Previously unknown packages we pick up normally, but if we have an 7015 // a priori expectation about this package's install presence, enforce it. 7016 // With a singular exception for new system packages. When an OTA contains 7017 // a new system package, we allow the codepath to change from a system location 7018 // to the user-installed location. If we don't allow this change, any newer, 7019 // user-installed version of the application will be ignored. 7020 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7021 if (mExpectingBetter.containsKey(pkg.packageName)) { 7022 logCriticalInfo(Log.WARN, 7023 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7024 } else { 7025 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7026 if (known != null) { 7027 if (DEBUG_PACKAGE_SCANNING) { 7028 Log.d(TAG, "Examining " + pkg.codePath 7029 + " and requiring known paths " + known.codePathString 7030 + " & " + known.resourcePathString); 7031 } 7032 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7033 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 7034 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7035 "Application package " + pkg.packageName 7036 + " found at " + pkg.applicationInfo.getCodePath() 7037 + " but expected at " + known.codePathString + "; ignoring."); 7038 } 7039 } 7040 } 7041 } 7042 7043 // Initialize package source and resource directories 7044 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7045 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7046 7047 SharedUserSetting suid = null; 7048 PackageSetting pkgSetting = null; 7049 7050 if (!isSystemApp(pkg)) { 7051 // Only system apps can use these features. 7052 pkg.mOriginalPackages = null; 7053 pkg.mRealPackage = null; 7054 pkg.mAdoptPermissions = null; 7055 } 7056 7057 // writer 7058 synchronized (mPackages) { 7059 if (pkg.mSharedUserId != null) { 7060 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7061 if (suid == null) { 7062 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7063 "Creating application package " + pkg.packageName 7064 + " for shared user failed"); 7065 } 7066 if (DEBUG_PACKAGE_SCANNING) { 7067 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7068 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7069 + "): packages=" + suid.packages); 7070 } 7071 } 7072 7073 // Check if we are renaming from an original package name. 7074 PackageSetting origPackage = null; 7075 String realName = null; 7076 if (pkg.mOriginalPackages != null) { 7077 // This package may need to be renamed to a previously 7078 // installed name. Let's check on that... 7079 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7080 if (pkg.mOriginalPackages.contains(renamed)) { 7081 // This package had originally been installed as the 7082 // original name, and we have already taken care of 7083 // transitioning to the new one. Just update the new 7084 // one to continue using the old name. 7085 realName = pkg.mRealPackage; 7086 if (!pkg.packageName.equals(renamed)) { 7087 // Callers into this function may have already taken 7088 // care of renaming the package; only do it here if 7089 // it is not already done. 7090 pkg.setPackageName(renamed); 7091 } 7092 7093 } else { 7094 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7095 if ((origPackage = mSettings.peekPackageLPr( 7096 pkg.mOriginalPackages.get(i))) != null) { 7097 // We do have the package already installed under its 7098 // original name... should we use it? 7099 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7100 // New package is not compatible with original. 7101 origPackage = null; 7102 continue; 7103 } else if (origPackage.sharedUser != null) { 7104 // Make sure uid is compatible between packages. 7105 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7106 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7107 + " to " + pkg.packageName + ": old uid " 7108 + origPackage.sharedUser.name 7109 + " differs from " + pkg.mSharedUserId); 7110 origPackage = null; 7111 continue; 7112 } 7113 } else { 7114 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7115 + pkg.packageName + " to old name " + origPackage.name); 7116 } 7117 break; 7118 } 7119 } 7120 } 7121 } 7122 7123 if (mTransferedPackages.contains(pkg.packageName)) { 7124 Slog.w(TAG, "Package " + pkg.packageName 7125 + " was transferred to another, but its .apk remains"); 7126 } 7127 7128 // Just create the setting, don't add it yet. For already existing packages 7129 // the PkgSetting exists already and doesn't have to be created. 7130 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7131 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7132 pkg.applicationInfo.primaryCpuAbi, 7133 pkg.applicationInfo.secondaryCpuAbi, 7134 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7135 user, false); 7136 if (pkgSetting == null) { 7137 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7138 "Creating application package " + pkg.packageName + " failed"); 7139 } 7140 7141 if (pkgSetting.origPackage != null) { 7142 // If we are first transitioning from an original package, 7143 // fix up the new package's name now. We need to do this after 7144 // looking up the package under its new name, so getPackageLP 7145 // can take care of fiddling things correctly. 7146 pkg.setPackageName(origPackage.name); 7147 7148 // File a report about this. 7149 String msg = "New package " + pkgSetting.realName 7150 + " renamed to replace old package " + pkgSetting.name; 7151 reportSettingsProblem(Log.WARN, msg); 7152 7153 // Make a note of it. 7154 mTransferedPackages.add(origPackage.name); 7155 7156 // No longer need to retain this. 7157 pkgSetting.origPackage = null; 7158 } 7159 7160 if (realName != null) { 7161 // Make a note of it. 7162 mTransferedPackages.add(pkg.packageName); 7163 } 7164 7165 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7166 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7167 } 7168 7169 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7170 // Check all shared libraries and map to their actual file path. 7171 // We only do this here for apps not on a system dir, because those 7172 // are the only ones that can fail an install due to this. We 7173 // will take care of the system apps by updating all of their 7174 // library paths after the scan is done. 7175 updateSharedLibrariesLPw(pkg, null); 7176 } 7177 7178 if (mFoundPolicyFile) { 7179 SELinuxMMAC.assignSeinfoValue(pkg); 7180 } 7181 7182 pkg.applicationInfo.uid = pkgSetting.appId; 7183 pkg.mExtras = pkgSetting; 7184 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7185 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7186 // We just determined the app is signed correctly, so bring 7187 // over the latest parsed certs. 7188 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7189 } else { 7190 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7191 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7192 "Package " + pkg.packageName + " upgrade keys do not match the " 7193 + "previously installed version"); 7194 } else { 7195 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7196 String msg = "System package " + pkg.packageName 7197 + " signature changed; retaining data."; 7198 reportSettingsProblem(Log.WARN, msg); 7199 } 7200 } 7201 } else { 7202 try { 7203 verifySignaturesLP(pkgSetting, pkg); 7204 // We just determined the app is signed correctly, so bring 7205 // over the latest parsed certs. 7206 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7207 } catch (PackageManagerException e) { 7208 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7209 throw e; 7210 } 7211 // The signature has changed, but this package is in the system 7212 // image... let's recover! 7213 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7214 // However... if this package is part of a shared user, but it 7215 // doesn't match the signature of the shared user, let's fail. 7216 // What this means is that you can't change the signatures 7217 // associated with an overall shared user, which doesn't seem all 7218 // that unreasonable. 7219 if (pkgSetting.sharedUser != null) { 7220 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7221 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7222 throw new PackageManagerException( 7223 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7224 "Signature mismatch for shared user : " 7225 + pkgSetting.sharedUser); 7226 } 7227 } 7228 // File a report about this. 7229 String msg = "System package " + pkg.packageName 7230 + " signature changed; retaining data."; 7231 reportSettingsProblem(Log.WARN, msg); 7232 } 7233 } 7234 // Verify that this new package doesn't have any content providers 7235 // that conflict with existing packages. Only do this if the 7236 // package isn't already installed, since we don't want to break 7237 // things that are installed. 7238 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7239 final int N = pkg.providers.size(); 7240 int i; 7241 for (i=0; i<N; i++) { 7242 PackageParser.Provider p = pkg.providers.get(i); 7243 if (p.info.authority != null) { 7244 String names[] = p.info.authority.split(";"); 7245 for (int j = 0; j < names.length; j++) { 7246 if (mProvidersByAuthority.containsKey(names[j])) { 7247 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7248 final String otherPackageName = 7249 ((other != null && other.getComponentName() != null) ? 7250 other.getComponentName().getPackageName() : "?"); 7251 throw new PackageManagerException( 7252 INSTALL_FAILED_CONFLICTING_PROVIDER, 7253 "Can't install because provider name " + names[j] 7254 + " (in package " + pkg.applicationInfo.packageName 7255 + ") is already used by " + otherPackageName); 7256 } 7257 } 7258 } 7259 } 7260 } 7261 7262 if (pkg.mAdoptPermissions != null) { 7263 // This package wants to adopt ownership of permissions from 7264 // another package. 7265 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7266 final String origName = pkg.mAdoptPermissions.get(i); 7267 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7268 if (orig != null) { 7269 if (verifyPackageUpdateLPr(orig, pkg)) { 7270 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7271 + pkg.packageName); 7272 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7273 } 7274 } 7275 } 7276 } 7277 } 7278 7279 final String pkgName = pkg.packageName; 7280 7281 final long scanFileTime = scanFile.lastModified(); 7282 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7283 pkg.applicationInfo.processName = fixProcessName( 7284 pkg.applicationInfo.packageName, 7285 pkg.applicationInfo.processName, 7286 pkg.applicationInfo.uid); 7287 7288 if (pkg != mPlatformPackage) { 7289 // This is a normal package, need to make its data directory. 7290 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7291 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7292 7293 boolean uidError = false; 7294 if (dataPath.exists()) { 7295 int currentUid = 0; 7296 try { 7297 StructStat stat = Os.stat(dataPath.getPath()); 7298 currentUid = stat.st_uid; 7299 } catch (ErrnoException e) { 7300 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7301 } 7302 7303 // If we have mismatched owners for the data path, we have a problem. 7304 if (currentUid != pkg.applicationInfo.uid) { 7305 boolean recovered = false; 7306 if (currentUid == 0) { 7307 // The directory somehow became owned by root. Wow. 7308 // This is probably because the system was stopped while 7309 // installd was in the middle of messing with its libs 7310 // directory. Ask installd to fix that. 7311 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7312 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7313 if (ret >= 0) { 7314 recovered = true; 7315 String msg = "Package " + pkg.packageName 7316 + " unexpectedly changed to uid 0; recovered to " + 7317 + pkg.applicationInfo.uid; 7318 reportSettingsProblem(Log.WARN, msg); 7319 } 7320 } 7321 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7322 || (scanFlags&SCAN_BOOTING) != 0)) { 7323 // If this is a system app, we can at least delete its 7324 // current data so the application will still work. 7325 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7326 if (ret >= 0) { 7327 // TODO: Kill the processes first 7328 // Old data gone! 7329 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7330 ? "System package " : "Third party package "; 7331 String msg = prefix + pkg.packageName 7332 + " has changed from uid: " 7333 + currentUid + " to " 7334 + pkg.applicationInfo.uid + "; old data erased"; 7335 reportSettingsProblem(Log.WARN, msg); 7336 recovered = true; 7337 } 7338 if (!recovered) { 7339 mHasSystemUidErrors = true; 7340 } 7341 } else if (!recovered) { 7342 // If we allow this install to proceed, we will be broken. 7343 // Abort, abort! 7344 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7345 "scanPackageLI"); 7346 } 7347 if (!recovered) { 7348 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7349 + pkg.applicationInfo.uid + "/fs_" 7350 + currentUid; 7351 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7352 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7353 String msg = "Package " + pkg.packageName 7354 + " has mismatched uid: " 7355 + currentUid + " on disk, " 7356 + pkg.applicationInfo.uid + " in settings"; 7357 // writer 7358 synchronized (mPackages) { 7359 mSettings.mReadMessages.append(msg); 7360 mSettings.mReadMessages.append('\n'); 7361 uidError = true; 7362 if (!pkgSetting.uidError) { 7363 reportSettingsProblem(Log.ERROR, msg); 7364 } 7365 } 7366 } 7367 } 7368 7369 // Ensure that directories are prepared 7370 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7371 pkg.applicationInfo.seinfo); 7372 7373 if (mShouldRestoreconData) { 7374 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7375 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7376 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7377 } 7378 } else { 7379 if (DEBUG_PACKAGE_SCANNING) { 7380 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7381 Log.v(TAG, "Want this data dir: " + dataPath); 7382 } 7383 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7384 pkg.applicationInfo.seinfo); 7385 } 7386 7387 // Get all of our default paths setup 7388 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7389 7390 pkgSetting.uidError = uidError; 7391 } 7392 7393 final String path = scanFile.getPath(); 7394 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7395 7396 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7397 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7398 7399 // Some system apps still use directory structure for native libraries 7400 // in which case we might end up not detecting abi solely based on apk 7401 // structure. Try to detect abi based on directory structure. 7402 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7403 pkg.applicationInfo.primaryCpuAbi == null) { 7404 setBundledAppAbisAndRoots(pkg, pkgSetting); 7405 setNativeLibraryPaths(pkg); 7406 } 7407 7408 } else { 7409 if ((scanFlags & SCAN_MOVE) != 0) { 7410 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7411 // but we already have this packages package info in the PackageSetting. We just 7412 // use that and derive the native library path based on the new codepath. 7413 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7414 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7415 } 7416 7417 // Set native library paths again. For moves, the path will be updated based on the 7418 // ABIs we've determined above. For non-moves, the path will be updated based on the 7419 // ABIs we determined during compilation, but the path will depend on the final 7420 // package path (after the rename away from the stage path). 7421 setNativeLibraryPaths(pkg); 7422 } 7423 7424 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7425 final int[] userIds = sUserManager.getUserIds(); 7426 synchronized (mInstallLock) { 7427 // Make sure all user data directories are ready to roll; we're okay 7428 // if they already exist 7429 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7430 for (int userId : userIds) { 7431 if (userId != UserHandle.USER_SYSTEM) { 7432 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7433 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7434 pkg.applicationInfo.seinfo); 7435 } 7436 } 7437 } 7438 7439 // Create a native library symlink only if we have native libraries 7440 // and if the native libraries are 32 bit libraries. We do not provide 7441 // this symlink for 64 bit libraries. 7442 if (pkg.applicationInfo.primaryCpuAbi != null && 7443 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7444 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7445 try { 7446 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7447 for (int userId : userIds) { 7448 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7449 nativeLibPath, userId) < 0) { 7450 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7451 "Failed linking native library dir (user=" + userId + ")"); 7452 } 7453 } 7454 } finally { 7455 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7456 } 7457 } 7458 } 7459 7460 // This is a special case for the "system" package, where the ABI is 7461 // dictated by the zygote configuration (and init.rc). We should keep track 7462 // of this ABI so that we can deal with "normal" applications that run under 7463 // the same UID correctly. 7464 if (mPlatformPackage == pkg) { 7465 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7466 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7467 } 7468 7469 // If there's a mismatch between the abi-override in the package setting 7470 // and the abiOverride specified for the install. Warn about this because we 7471 // would've already compiled the app without taking the package setting into 7472 // account. 7473 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7474 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7475 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7476 " for package: " + pkg.packageName); 7477 } 7478 } 7479 7480 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7481 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7482 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7483 7484 // Copy the derived override back to the parsed package, so that we can 7485 // update the package settings accordingly. 7486 pkg.cpuAbiOverride = cpuAbiOverride; 7487 7488 if (DEBUG_ABI_SELECTION) { 7489 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7490 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7491 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7492 } 7493 7494 // Push the derived path down into PackageSettings so we know what to 7495 // clean up at uninstall time. 7496 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7497 7498 if (DEBUG_ABI_SELECTION) { 7499 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7500 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7501 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7502 } 7503 7504 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7505 // We don't do this here during boot because we can do it all 7506 // at once after scanning all existing packages. 7507 // 7508 // We also do this *before* we perform dexopt on this package, so that 7509 // we can avoid redundant dexopts, and also to make sure we've got the 7510 // code and package path correct. 7511 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7512 pkg, true /* boot complete */); 7513 } 7514 7515 if (mFactoryTest && pkg.requestedPermissions.contains( 7516 android.Manifest.permission.FACTORY_TEST)) { 7517 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7518 } 7519 7520 ArrayList<PackageParser.Package> clientLibPkgs = null; 7521 7522 // writer 7523 synchronized (mPackages) { 7524 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7525 // Only system apps can add new shared libraries. 7526 if (pkg.libraryNames != null) { 7527 for (int i=0; i<pkg.libraryNames.size(); i++) { 7528 String name = pkg.libraryNames.get(i); 7529 boolean allowed = false; 7530 if (pkg.isUpdatedSystemApp()) { 7531 // New library entries can only be added through the 7532 // system image. This is important to get rid of a lot 7533 // of nasty edge cases: for example if we allowed a non- 7534 // system update of the app to add a library, then uninstalling 7535 // the update would make the library go away, and assumptions 7536 // we made such as through app install filtering would now 7537 // have allowed apps on the device which aren't compatible 7538 // with it. Better to just have the restriction here, be 7539 // conservative, and create many fewer cases that can negatively 7540 // impact the user experience. 7541 final PackageSetting sysPs = mSettings 7542 .getDisabledSystemPkgLPr(pkg.packageName); 7543 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7544 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7545 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7546 allowed = true; 7547 break; 7548 } 7549 } 7550 } 7551 } else { 7552 allowed = true; 7553 } 7554 if (allowed) { 7555 if (!mSharedLibraries.containsKey(name)) { 7556 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7557 } else if (!name.equals(pkg.packageName)) { 7558 Slog.w(TAG, "Package " + pkg.packageName + " library " 7559 + name + " already exists; skipping"); 7560 } 7561 } else { 7562 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7563 + name + " that is not declared on system image; skipping"); 7564 } 7565 } 7566 if ((scanFlags & SCAN_BOOTING) == 0) { 7567 // If we are not booting, we need to update any applications 7568 // that are clients of our shared library. If we are booting, 7569 // this will all be done once the scan is complete. 7570 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7571 } 7572 } 7573 } 7574 } 7575 7576 // Request the ActivityManager to kill the process(only for existing packages) 7577 // so that we do not end up in a confused state while the user is still using the older 7578 // version of the application while the new one gets installed. 7579 if ((scanFlags & SCAN_REPLACING) != 0) { 7580 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7581 7582 killApplication(pkg.applicationInfo.packageName, 7583 pkg.applicationInfo.uid, "replace pkg"); 7584 7585 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7586 } 7587 7588 // Also need to kill any apps that are dependent on the library. 7589 if (clientLibPkgs != null) { 7590 for (int i=0; i<clientLibPkgs.size(); i++) { 7591 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7592 killApplication(clientPkg.applicationInfo.packageName, 7593 clientPkg.applicationInfo.uid, "update lib"); 7594 } 7595 } 7596 7597 // Make sure we're not adding any bogus keyset info 7598 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7599 ksms.assertScannedPackageValid(pkg); 7600 7601 // writer 7602 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7603 7604 boolean createIdmapFailed = false; 7605 synchronized (mPackages) { 7606 // We don't expect installation to fail beyond this point 7607 7608 // Add the new setting to mSettings 7609 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7610 // Add the new setting to mPackages 7611 mPackages.put(pkg.applicationInfo.packageName, pkg); 7612 // Make sure we don't accidentally delete its data. 7613 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7614 while (iter.hasNext()) { 7615 PackageCleanItem item = iter.next(); 7616 if (pkgName.equals(item.packageName)) { 7617 iter.remove(); 7618 } 7619 } 7620 7621 // Take care of first install / last update times. 7622 if (currentTime != 0) { 7623 if (pkgSetting.firstInstallTime == 0) { 7624 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7625 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7626 pkgSetting.lastUpdateTime = currentTime; 7627 } 7628 } else if (pkgSetting.firstInstallTime == 0) { 7629 // We need *something*. Take time time stamp of the file. 7630 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7631 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7632 if (scanFileTime != pkgSetting.timeStamp) { 7633 // A package on the system image has changed; consider this 7634 // to be an update. 7635 pkgSetting.lastUpdateTime = scanFileTime; 7636 } 7637 } 7638 7639 // Add the package's KeySets to the global KeySetManagerService 7640 ksms.addScannedPackageLPw(pkg); 7641 7642 int N = pkg.providers.size(); 7643 StringBuilder r = null; 7644 int i; 7645 for (i=0; i<N; i++) { 7646 PackageParser.Provider p = pkg.providers.get(i); 7647 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7648 p.info.processName, pkg.applicationInfo.uid); 7649 mProviders.addProvider(p); 7650 p.syncable = p.info.isSyncable; 7651 if (p.info.authority != null) { 7652 String names[] = p.info.authority.split(";"); 7653 p.info.authority = null; 7654 for (int j = 0; j < names.length; j++) { 7655 if (j == 1 && p.syncable) { 7656 // We only want the first authority for a provider to possibly be 7657 // syncable, so if we already added this provider using a different 7658 // authority clear the syncable flag. We copy the provider before 7659 // changing it because the mProviders object contains a reference 7660 // to a provider that we don't want to change. 7661 // Only do this for the second authority since the resulting provider 7662 // object can be the same for all future authorities for this provider. 7663 p = new PackageParser.Provider(p); 7664 p.syncable = false; 7665 } 7666 if (!mProvidersByAuthority.containsKey(names[j])) { 7667 mProvidersByAuthority.put(names[j], p); 7668 if (p.info.authority == null) { 7669 p.info.authority = names[j]; 7670 } else { 7671 p.info.authority = p.info.authority + ";" + names[j]; 7672 } 7673 if (DEBUG_PACKAGE_SCANNING) { 7674 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7675 Log.d(TAG, "Registered content provider: " + names[j] 7676 + ", className = " + p.info.name + ", isSyncable = " 7677 + p.info.isSyncable); 7678 } 7679 } else { 7680 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7681 Slog.w(TAG, "Skipping provider name " + names[j] + 7682 " (in package " + pkg.applicationInfo.packageName + 7683 "): name already used by " 7684 + ((other != null && other.getComponentName() != null) 7685 ? other.getComponentName().getPackageName() : "?")); 7686 } 7687 } 7688 } 7689 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7690 if (r == null) { 7691 r = new StringBuilder(256); 7692 } else { 7693 r.append(' '); 7694 } 7695 r.append(p.info.name); 7696 } 7697 } 7698 if (r != null) { 7699 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7700 } 7701 7702 N = pkg.services.size(); 7703 r = null; 7704 for (i=0; i<N; i++) { 7705 PackageParser.Service s = pkg.services.get(i); 7706 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7707 s.info.processName, pkg.applicationInfo.uid); 7708 mServices.addService(s); 7709 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7710 if (r == null) { 7711 r = new StringBuilder(256); 7712 } else { 7713 r.append(' '); 7714 } 7715 r.append(s.info.name); 7716 } 7717 } 7718 if (r != null) { 7719 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7720 } 7721 7722 N = pkg.receivers.size(); 7723 r = null; 7724 for (i=0; i<N; i++) { 7725 PackageParser.Activity a = pkg.receivers.get(i); 7726 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7727 a.info.processName, pkg.applicationInfo.uid); 7728 mReceivers.addActivity(a, "receiver"); 7729 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7730 if (r == null) { 7731 r = new StringBuilder(256); 7732 } else { 7733 r.append(' '); 7734 } 7735 r.append(a.info.name); 7736 } 7737 } 7738 if (r != null) { 7739 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7740 } 7741 7742 N = pkg.activities.size(); 7743 r = null; 7744 for (i=0; i<N; i++) { 7745 PackageParser.Activity a = pkg.activities.get(i); 7746 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7747 a.info.processName, pkg.applicationInfo.uid); 7748 mActivities.addActivity(a, "activity"); 7749 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7750 if (r == null) { 7751 r = new StringBuilder(256); 7752 } else { 7753 r.append(' '); 7754 } 7755 r.append(a.info.name); 7756 } 7757 } 7758 if (r != null) { 7759 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7760 } 7761 7762 N = pkg.permissionGroups.size(); 7763 r = null; 7764 for (i=0; i<N; i++) { 7765 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7766 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7767 if (cur == null) { 7768 mPermissionGroups.put(pg.info.name, pg); 7769 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7770 if (r == null) { 7771 r = new StringBuilder(256); 7772 } else { 7773 r.append(' '); 7774 } 7775 r.append(pg.info.name); 7776 } 7777 } else { 7778 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7779 + pg.info.packageName + " ignored: original from " 7780 + cur.info.packageName); 7781 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7782 if (r == null) { 7783 r = new StringBuilder(256); 7784 } else { 7785 r.append(' '); 7786 } 7787 r.append("DUP:"); 7788 r.append(pg.info.name); 7789 } 7790 } 7791 } 7792 if (r != null) { 7793 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7794 } 7795 7796 N = pkg.permissions.size(); 7797 r = null; 7798 for (i=0; i<N; i++) { 7799 PackageParser.Permission p = pkg.permissions.get(i); 7800 7801 // Assume by default that we did not install this permission into the system. 7802 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7803 7804 // Now that permission groups have a special meaning, we ignore permission 7805 // groups for legacy apps to prevent unexpected behavior. In particular, 7806 // permissions for one app being granted to someone just becuase they happen 7807 // to be in a group defined by another app (before this had no implications). 7808 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7809 p.group = mPermissionGroups.get(p.info.group); 7810 // Warn for a permission in an unknown group. 7811 if (p.info.group != null && p.group == null) { 7812 Slog.w(TAG, "Permission " + p.info.name + " from package " 7813 + p.info.packageName + " in an unknown group " + p.info.group); 7814 } 7815 } 7816 7817 ArrayMap<String, BasePermission> permissionMap = 7818 p.tree ? mSettings.mPermissionTrees 7819 : mSettings.mPermissions; 7820 BasePermission bp = permissionMap.get(p.info.name); 7821 7822 // Allow system apps to redefine non-system permissions 7823 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7824 final boolean currentOwnerIsSystem = (bp.perm != null 7825 && isSystemApp(bp.perm.owner)); 7826 if (isSystemApp(p.owner)) { 7827 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7828 // It's a built-in permission and no owner, take ownership now 7829 bp.packageSetting = pkgSetting; 7830 bp.perm = p; 7831 bp.uid = pkg.applicationInfo.uid; 7832 bp.sourcePackage = p.info.packageName; 7833 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7834 } else if (!currentOwnerIsSystem) { 7835 String msg = "New decl " + p.owner + " of permission " 7836 + p.info.name + " is system; overriding " + bp.sourcePackage; 7837 reportSettingsProblem(Log.WARN, msg); 7838 bp = null; 7839 } 7840 } 7841 } 7842 7843 if (bp == null) { 7844 bp = new BasePermission(p.info.name, p.info.packageName, 7845 BasePermission.TYPE_NORMAL); 7846 permissionMap.put(p.info.name, bp); 7847 } 7848 7849 if (bp.perm == null) { 7850 if (bp.sourcePackage == null 7851 || bp.sourcePackage.equals(p.info.packageName)) { 7852 BasePermission tree = findPermissionTreeLP(p.info.name); 7853 if (tree == null 7854 || tree.sourcePackage.equals(p.info.packageName)) { 7855 bp.packageSetting = pkgSetting; 7856 bp.perm = p; 7857 bp.uid = pkg.applicationInfo.uid; 7858 bp.sourcePackage = p.info.packageName; 7859 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7860 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7861 if (r == null) { 7862 r = new StringBuilder(256); 7863 } else { 7864 r.append(' '); 7865 } 7866 r.append(p.info.name); 7867 } 7868 } else { 7869 Slog.w(TAG, "Permission " + p.info.name + " from package " 7870 + p.info.packageName + " ignored: base tree " 7871 + tree.name + " is from package " 7872 + tree.sourcePackage); 7873 } 7874 } else { 7875 Slog.w(TAG, "Permission " + p.info.name + " from package " 7876 + p.info.packageName + " ignored: original from " 7877 + bp.sourcePackage); 7878 } 7879 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7880 if (r == null) { 7881 r = new StringBuilder(256); 7882 } else { 7883 r.append(' '); 7884 } 7885 r.append("DUP:"); 7886 r.append(p.info.name); 7887 } 7888 if (bp.perm == p) { 7889 bp.protectionLevel = p.info.protectionLevel; 7890 } 7891 } 7892 7893 if (r != null) { 7894 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7895 } 7896 7897 N = pkg.instrumentation.size(); 7898 r = null; 7899 for (i=0; i<N; i++) { 7900 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7901 a.info.packageName = pkg.applicationInfo.packageName; 7902 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7903 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7904 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7905 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7906 a.info.dataDir = pkg.applicationInfo.dataDir; 7907 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7908 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7909 7910 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7911 // need other information about the application, like the ABI and what not ? 7912 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7913 mInstrumentation.put(a.getComponentName(), a); 7914 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7915 if (r == null) { 7916 r = new StringBuilder(256); 7917 } else { 7918 r.append(' '); 7919 } 7920 r.append(a.info.name); 7921 } 7922 } 7923 if (r != null) { 7924 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7925 } 7926 7927 if (pkg.protectedBroadcasts != null) { 7928 N = pkg.protectedBroadcasts.size(); 7929 for (i=0; i<N; i++) { 7930 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7931 } 7932 } 7933 7934 pkgSetting.setTimeStamp(scanFileTime); 7935 7936 // Create idmap files for pairs of (packages, overlay packages). 7937 // Note: "android", ie framework-res.apk, is handled by native layers. 7938 if (pkg.mOverlayTarget != null) { 7939 // This is an overlay package. 7940 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7941 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7942 mOverlays.put(pkg.mOverlayTarget, 7943 new ArrayMap<String, PackageParser.Package>()); 7944 } 7945 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7946 map.put(pkg.packageName, pkg); 7947 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7948 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7949 createIdmapFailed = true; 7950 } 7951 } 7952 } else if (mOverlays.containsKey(pkg.packageName) && 7953 !pkg.packageName.equals("android")) { 7954 // This is a regular package, with one or more known overlay packages. 7955 createIdmapsForPackageLI(pkg); 7956 } 7957 } 7958 7959 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7960 7961 if (createIdmapFailed) { 7962 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7963 "scanPackageLI failed to createIdmap"); 7964 } 7965 return pkg; 7966 } 7967 7968 /** 7969 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7970 * is derived purely on the basis of the contents of {@code scanFile} and 7971 * {@code cpuAbiOverride}. 7972 * 7973 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7974 */ 7975 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7976 String cpuAbiOverride, boolean extractLibs) 7977 throws PackageManagerException { 7978 // TODO: We can probably be smarter about this stuff. For installed apps, 7979 // we can calculate this information at install time once and for all. For 7980 // system apps, we can probably assume that this information doesn't change 7981 // after the first boot scan. As things stand, we do lots of unnecessary work. 7982 7983 // Give ourselves some initial paths; we'll come back for another 7984 // pass once we've determined ABI below. 7985 setNativeLibraryPaths(pkg); 7986 7987 // We would never need to extract libs for forward-locked and external packages, 7988 // since the container service will do it for us. We shouldn't attempt to 7989 // extract libs from system app when it was not updated. 7990 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7991 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7992 extractLibs = false; 7993 } 7994 7995 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7996 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7997 7998 NativeLibraryHelper.Handle handle = null; 7999 try { 8000 handle = NativeLibraryHelper.Handle.create(pkg); 8001 // TODO(multiArch): This can be null for apps that didn't go through the 8002 // usual installation process. We can calculate it again, like we 8003 // do during install time. 8004 // 8005 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8006 // unnecessary. 8007 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8008 8009 // Null out the abis so that they can be recalculated. 8010 pkg.applicationInfo.primaryCpuAbi = null; 8011 pkg.applicationInfo.secondaryCpuAbi = null; 8012 if (isMultiArch(pkg.applicationInfo)) { 8013 // Warn if we've set an abiOverride for multi-lib packages.. 8014 // By definition, we need to copy both 32 and 64 bit libraries for 8015 // such packages. 8016 if (pkg.cpuAbiOverride != null 8017 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8018 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8019 } 8020 8021 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8022 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8023 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8024 if (extractLibs) { 8025 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8026 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8027 useIsaSpecificSubdirs); 8028 } else { 8029 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8030 } 8031 } 8032 8033 maybeThrowExceptionForMultiArchCopy( 8034 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8035 8036 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8037 if (extractLibs) { 8038 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8039 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8040 useIsaSpecificSubdirs); 8041 } else { 8042 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8043 } 8044 } 8045 8046 maybeThrowExceptionForMultiArchCopy( 8047 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8048 8049 if (abi64 >= 0) { 8050 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8051 } 8052 8053 if (abi32 >= 0) { 8054 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8055 if (abi64 >= 0) { 8056 pkg.applicationInfo.secondaryCpuAbi = abi; 8057 } else { 8058 pkg.applicationInfo.primaryCpuAbi = abi; 8059 } 8060 } 8061 } else { 8062 String[] abiList = (cpuAbiOverride != null) ? 8063 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8064 8065 // Enable gross and lame hacks for apps that are built with old 8066 // SDK tools. We must scan their APKs for renderscript bitcode and 8067 // not launch them if it's present. Don't bother checking on devices 8068 // that don't have 64 bit support. 8069 boolean needsRenderScriptOverride = false; 8070 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8071 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8072 abiList = Build.SUPPORTED_32_BIT_ABIS; 8073 needsRenderScriptOverride = true; 8074 } 8075 8076 final int copyRet; 8077 if (extractLibs) { 8078 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8079 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8080 } else { 8081 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8082 } 8083 8084 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8085 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8086 "Error unpackaging native libs for app, errorCode=" + copyRet); 8087 } 8088 8089 if (copyRet >= 0) { 8090 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8091 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8092 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8093 } else if (needsRenderScriptOverride) { 8094 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8095 } 8096 } 8097 } catch (IOException ioe) { 8098 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8099 } finally { 8100 IoUtils.closeQuietly(handle); 8101 } 8102 8103 // Now that we've calculated the ABIs and determined if it's an internal app, 8104 // we will go ahead and populate the nativeLibraryPath. 8105 setNativeLibraryPaths(pkg); 8106 } 8107 8108 /** 8109 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8110 * i.e, so that all packages can be run inside a single process if required. 8111 * 8112 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8113 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8114 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8115 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8116 * updating a package that belongs to a shared user. 8117 * 8118 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8119 * adds unnecessary complexity. 8120 */ 8121 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8122 PackageParser.Package scannedPackage, boolean bootComplete) { 8123 String requiredInstructionSet = null; 8124 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8125 requiredInstructionSet = VMRuntime.getInstructionSet( 8126 scannedPackage.applicationInfo.primaryCpuAbi); 8127 } 8128 8129 PackageSetting requirer = null; 8130 for (PackageSetting ps : packagesForUser) { 8131 // If packagesForUser contains scannedPackage, we skip it. This will happen 8132 // when scannedPackage is an update of an existing package. Without this check, 8133 // we will never be able to change the ABI of any package belonging to a shared 8134 // user, even if it's compatible with other packages. 8135 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8136 if (ps.primaryCpuAbiString == null) { 8137 continue; 8138 } 8139 8140 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8141 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8142 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8143 // this but there's not much we can do. 8144 String errorMessage = "Instruction set mismatch, " 8145 + ((requirer == null) ? "[caller]" : requirer) 8146 + " requires " + requiredInstructionSet + " whereas " + ps 8147 + " requires " + instructionSet; 8148 Slog.w(TAG, errorMessage); 8149 } 8150 8151 if (requiredInstructionSet == null) { 8152 requiredInstructionSet = instructionSet; 8153 requirer = ps; 8154 } 8155 } 8156 } 8157 8158 if (requiredInstructionSet != null) { 8159 String adjustedAbi; 8160 if (requirer != null) { 8161 // requirer != null implies that either scannedPackage was null or that scannedPackage 8162 // did not require an ABI, in which case we have to adjust scannedPackage to match 8163 // the ABI of the set (which is the same as requirer's ABI) 8164 adjustedAbi = requirer.primaryCpuAbiString; 8165 if (scannedPackage != null) { 8166 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8167 } 8168 } else { 8169 // requirer == null implies that we're updating all ABIs in the set to 8170 // match scannedPackage. 8171 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8172 } 8173 8174 for (PackageSetting ps : packagesForUser) { 8175 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8176 if (ps.primaryCpuAbiString != null) { 8177 continue; 8178 } 8179 8180 ps.primaryCpuAbiString = adjustedAbi; 8181 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8182 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8183 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 8184 mInstaller.rmdex(ps.codePathString, 8185 getDexCodeInstructionSet(getPreferredInstructionSet())); 8186 } 8187 } 8188 } 8189 } 8190 } 8191 8192 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8193 synchronized (mPackages) { 8194 mResolverReplaced = true; 8195 // Set up information for custom user intent resolution activity. 8196 mResolveActivity.applicationInfo = pkg.applicationInfo; 8197 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8198 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8199 mResolveActivity.processName = pkg.applicationInfo.packageName; 8200 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8201 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8202 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8203 mResolveActivity.theme = 0; 8204 mResolveActivity.exported = true; 8205 mResolveActivity.enabled = true; 8206 mResolveInfo.activityInfo = mResolveActivity; 8207 mResolveInfo.priority = 0; 8208 mResolveInfo.preferredOrder = 0; 8209 mResolveInfo.match = 0; 8210 mResolveComponentName = mCustomResolverComponentName; 8211 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8212 mResolveComponentName); 8213 } 8214 } 8215 8216 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8217 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8218 8219 // Set up information for ephemeral installer activity 8220 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8221 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8222 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8223 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8224 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8225 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8226 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8227 mEphemeralInstallerActivity.theme = 0; 8228 mEphemeralInstallerActivity.exported = true; 8229 mEphemeralInstallerActivity.enabled = true; 8230 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8231 mEphemeralInstallerInfo.priority = 0; 8232 mEphemeralInstallerInfo.preferredOrder = 0; 8233 mEphemeralInstallerInfo.match = 0; 8234 8235 if (DEBUG_EPHEMERAL) { 8236 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8237 } 8238 } 8239 8240 private static String calculateBundledApkRoot(final String codePathString) { 8241 final File codePath = new File(codePathString); 8242 final File codeRoot; 8243 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8244 codeRoot = Environment.getRootDirectory(); 8245 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8246 codeRoot = Environment.getOemDirectory(); 8247 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8248 codeRoot = Environment.getVendorDirectory(); 8249 } else { 8250 // Unrecognized code path; take its top real segment as the apk root: 8251 // e.g. /something/app/blah.apk => /something 8252 try { 8253 File f = codePath.getCanonicalFile(); 8254 File parent = f.getParentFile(); // non-null because codePath is a file 8255 File tmp; 8256 while ((tmp = parent.getParentFile()) != null) { 8257 f = parent; 8258 parent = tmp; 8259 } 8260 codeRoot = f; 8261 Slog.w(TAG, "Unrecognized code path " 8262 + codePath + " - using " + codeRoot); 8263 } catch (IOException e) { 8264 // Can't canonicalize the code path -- shenanigans? 8265 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8266 return Environment.getRootDirectory().getPath(); 8267 } 8268 } 8269 return codeRoot.getPath(); 8270 } 8271 8272 /** 8273 * Derive and set the location of native libraries for the given package, 8274 * which varies depending on where and how the package was installed. 8275 */ 8276 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8277 final ApplicationInfo info = pkg.applicationInfo; 8278 final String codePath = pkg.codePath; 8279 final File codeFile = new File(codePath); 8280 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8281 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8282 8283 info.nativeLibraryRootDir = null; 8284 info.nativeLibraryRootRequiresIsa = false; 8285 info.nativeLibraryDir = null; 8286 info.secondaryNativeLibraryDir = null; 8287 8288 if (isApkFile(codeFile)) { 8289 // Monolithic install 8290 if (bundledApp) { 8291 // If "/system/lib64/apkname" exists, assume that is the per-package 8292 // native library directory to use; otherwise use "/system/lib/apkname". 8293 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8294 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8295 getPrimaryInstructionSet(info)); 8296 8297 // This is a bundled system app so choose the path based on the ABI. 8298 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8299 // is just the default path. 8300 final String apkName = deriveCodePathName(codePath); 8301 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8302 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8303 apkName).getAbsolutePath(); 8304 8305 if (info.secondaryCpuAbi != null) { 8306 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8307 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8308 secondaryLibDir, apkName).getAbsolutePath(); 8309 } 8310 } else if (asecApp) { 8311 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8312 .getAbsolutePath(); 8313 } else { 8314 final String apkName = deriveCodePathName(codePath); 8315 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8316 .getAbsolutePath(); 8317 } 8318 8319 info.nativeLibraryRootRequiresIsa = false; 8320 info.nativeLibraryDir = info.nativeLibraryRootDir; 8321 } else { 8322 // Cluster install 8323 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8324 info.nativeLibraryRootRequiresIsa = true; 8325 8326 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8327 getPrimaryInstructionSet(info)).getAbsolutePath(); 8328 8329 if (info.secondaryCpuAbi != null) { 8330 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8331 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8332 } 8333 } 8334 } 8335 8336 /** 8337 * Calculate the abis and roots for a bundled app. These can uniquely 8338 * be determined from the contents of the system partition, i.e whether 8339 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8340 * of this information, and instead assume that the system was built 8341 * sensibly. 8342 */ 8343 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8344 PackageSetting pkgSetting) { 8345 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8346 8347 // If "/system/lib64/apkname" exists, assume that is the per-package 8348 // native library directory to use; otherwise use "/system/lib/apkname". 8349 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8350 setBundledAppAbi(pkg, apkRoot, apkName); 8351 // pkgSetting might be null during rescan following uninstall of updates 8352 // to a bundled app, so accommodate that possibility. The settings in 8353 // that case will be established later from the parsed package. 8354 // 8355 // If the settings aren't null, sync them up with what we've just derived. 8356 // note that apkRoot isn't stored in the package settings. 8357 if (pkgSetting != null) { 8358 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8359 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8360 } 8361 } 8362 8363 /** 8364 * Deduces the ABI of a bundled app and sets the relevant fields on the 8365 * parsed pkg object. 8366 * 8367 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8368 * under which system libraries are installed. 8369 * @param apkName the name of the installed package. 8370 */ 8371 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8372 final File codeFile = new File(pkg.codePath); 8373 8374 final boolean has64BitLibs; 8375 final boolean has32BitLibs; 8376 if (isApkFile(codeFile)) { 8377 // Monolithic install 8378 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8379 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8380 } else { 8381 // Cluster install 8382 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8383 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8384 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8385 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8386 has64BitLibs = (new File(rootDir, isa)).exists(); 8387 } else { 8388 has64BitLibs = false; 8389 } 8390 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8391 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8392 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8393 has32BitLibs = (new File(rootDir, isa)).exists(); 8394 } else { 8395 has32BitLibs = false; 8396 } 8397 } 8398 8399 if (has64BitLibs && !has32BitLibs) { 8400 // The package has 64 bit libs, but not 32 bit libs. Its primary 8401 // ABI should be 64 bit. We can safely assume here that the bundled 8402 // native libraries correspond to the most preferred ABI in the list. 8403 8404 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8405 pkg.applicationInfo.secondaryCpuAbi = null; 8406 } else if (has32BitLibs && !has64BitLibs) { 8407 // The package has 32 bit libs but not 64 bit libs. Its primary 8408 // ABI should be 32 bit. 8409 8410 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8411 pkg.applicationInfo.secondaryCpuAbi = null; 8412 } else if (has32BitLibs && has64BitLibs) { 8413 // The application has both 64 and 32 bit bundled libraries. We check 8414 // here that the app declares multiArch support, and warn if it doesn't. 8415 // 8416 // We will be lenient here and record both ABIs. The primary will be the 8417 // ABI that's higher on the list, i.e, a device that's configured to prefer 8418 // 64 bit apps will see a 64 bit primary ABI, 8419 8420 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8421 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8422 } 8423 8424 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8425 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8426 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8427 } else { 8428 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8429 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8430 } 8431 } else { 8432 pkg.applicationInfo.primaryCpuAbi = null; 8433 pkg.applicationInfo.secondaryCpuAbi = null; 8434 } 8435 } 8436 8437 private void killApplication(String pkgName, int appId, String reason) { 8438 // Request the ActivityManager to kill the process(only for existing packages) 8439 // so that we do not end up in a confused state while the user is still using the older 8440 // version of the application while the new one gets installed. 8441 IActivityManager am = ActivityManagerNative.getDefault(); 8442 if (am != null) { 8443 try { 8444 am.killApplicationWithAppId(pkgName, appId, reason); 8445 } catch (RemoteException e) { 8446 } 8447 } 8448 } 8449 8450 void removePackageLI(PackageSetting ps, boolean chatty) { 8451 if (DEBUG_INSTALL) { 8452 if (chatty) 8453 Log.d(TAG, "Removing package " + ps.name); 8454 } 8455 8456 // writer 8457 synchronized (mPackages) { 8458 mPackages.remove(ps.name); 8459 final PackageParser.Package pkg = ps.pkg; 8460 if (pkg != null) { 8461 cleanPackageDataStructuresLILPw(pkg, chatty); 8462 } 8463 } 8464 } 8465 8466 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8467 if (DEBUG_INSTALL) { 8468 if (chatty) 8469 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8470 } 8471 8472 // writer 8473 synchronized (mPackages) { 8474 mPackages.remove(pkg.applicationInfo.packageName); 8475 cleanPackageDataStructuresLILPw(pkg, chatty); 8476 } 8477 } 8478 8479 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8480 int N = pkg.providers.size(); 8481 StringBuilder r = null; 8482 int i; 8483 for (i=0; i<N; i++) { 8484 PackageParser.Provider p = pkg.providers.get(i); 8485 mProviders.removeProvider(p); 8486 if (p.info.authority == null) { 8487 8488 /* There was another ContentProvider with this authority when 8489 * this app was installed so this authority is null, 8490 * Ignore it as we don't have to unregister the provider. 8491 */ 8492 continue; 8493 } 8494 String names[] = p.info.authority.split(";"); 8495 for (int j = 0; j < names.length; j++) { 8496 if (mProvidersByAuthority.get(names[j]) == p) { 8497 mProvidersByAuthority.remove(names[j]); 8498 if (DEBUG_REMOVE) { 8499 if (chatty) 8500 Log.d(TAG, "Unregistered content provider: " + names[j] 8501 + ", className = " + p.info.name + ", isSyncable = " 8502 + p.info.isSyncable); 8503 } 8504 } 8505 } 8506 if (DEBUG_REMOVE && chatty) { 8507 if (r == null) { 8508 r = new StringBuilder(256); 8509 } else { 8510 r.append(' '); 8511 } 8512 r.append(p.info.name); 8513 } 8514 } 8515 if (r != null) { 8516 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8517 } 8518 8519 N = pkg.services.size(); 8520 r = null; 8521 for (i=0; i<N; i++) { 8522 PackageParser.Service s = pkg.services.get(i); 8523 mServices.removeService(s); 8524 if (chatty) { 8525 if (r == null) { 8526 r = new StringBuilder(256); 8527 } else { 8528 r.append(' '); 8529 } 8530 r.append(s.info.name); 8531 } 8532 } 8533 if (r != null) { 8534 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8535 } 8536 8537 N = pkg.receivers.size(); 8538 r = null; 8539 for (i=0; i<N; i++) { 8540 PackageParser.Activity a = pkg.receivers.get(i); 8541 mReceivers.removeActivity(a, "receiver"); 8542 if (DEBUG_REMOVE && chatty) { 8543 if (r == null) { 8544 r = new StringBuilder(256); 8545 } else { 8546 r.append(' '); 8547 } 8548 r.append(a.info.name); 8549 } 8550 } 8551 if (r != null) { 8552 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8553 } 8554 8555 N = pkg.activities.size(); 8556 r = null; 8557 for (i=0; i<N; i++) { 8558 PackageParser.Activity a = pkg.activities.get(i); 8559 mActivities.removeActivity(a, "activity"); 8560 if (DEBUG_REMOVE && chatty) { 8561 if (r == null) { 8562 r = new StringBuilder(256); 8563 } else { 8564 r.append(' '); 8565 } 8566 r.append(a.info.name); 8567 } 8568 } 8569 if (r != null) { 8570 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8571 } 8572 8573 N = pkg.permissions.size(); 8574 r = null; 8575 for (i=0; i<N; i++) { 8576 PackageParser.Permission p = pkg.permissions.get(i); 8577 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8578 if (bp == null) { 8579 bp = mSettings.mPermissionTrees.get(p.info.name); 8580 } 8581 if (bp != null && bp.perm == p) { 8582 bp.perm = null; 8583 if (DEBUG_REMOVE && chatty) { 8584 if (r == null) { 8585 r = new StringBuilder(256); 8586 } else { 8587 r.append(' '); 8588 } 8589 r.append(p.info.name); 8590 } 8591 } 8592 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8593 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8594 if (appOpPkgs != null) { 8595 appOpPkgs.remove(pkg.packageName); 8596 } 8597 } 8598 } 8599 if (r != null) { 8600 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8601 } 8602 8603 N = pkg.requestedPermissions.size(); 8604 r = null; 8605 for (i=0; i<N; i++) { 8606 String perm = pkg.requestedPermissions.get(i); 8607 BasePermission bp = mSettings.mPermissions.get(perm); 8608 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8609 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8610 if (appOpPkgs != null) { 8611 appOpPkgs.remove(pkg.packageName); 8612 if (appOpPkgs.isEmpty()) { 8613 mAppOpPermissionPackages.remove(perm); 8614 } 8615 } 8616 } 8617 } 8618 if (r != null) { 8619 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8620 } 8621 8622 N = pkg.instrumentation.size(); 8623 r = null; 8624 for (i=0; i<N; i++) { 8625 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8626 mInstrumentation.remove(a.getComponentName()); 8627 if (DEBUG_REMOVE && chatty) { 8628 if (r == null) { 8629 r = new StringBuilder(256); 8630 } else { 8631 r.append(' '); 8632 } 8633 r.append(a.info.name); 8634 } 8635 } 8636 if (r != null) { 8637 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8638 } 8639 8640 r = null; 8641 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8642 // Only system apps can hold shared libraries. 8643 if (pkg.libraryNames != null) { 8644 for (i=0; i<pkg.libraryNames.size(); i++) { 8645 String name = pkg.libraryNames.get(i); 8646 SharedLibraryEntry cur = mSharedLibraries.get(name); 8647 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8648 mSharedLibraries.remove(name); 8649 if (DEBUG_REMOVE && chatty) { 8650 if (r == null) { 8651 r = new StringBuilder(256); 8652 } else { 8653 r.append(' '); 8654 } 8655 r.append(name); 8656 } 8657 } 8658 } 8659 } 8660 } 8661 if (r != null) { 8662 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8663 } 8664 } 8665 8666 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8667 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8668 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8669 return true; 8670 } 8671 } 8672 return false; 8673 } 8674 8675 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8676 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8677 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8678 8679 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8680 int flags) { 8681 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8682 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8683 } 8684 8685 private void updatePermissionsLPw(String changingPkg, 8686 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8687 // Make sure there are no dangling permission trees. 8688 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8689 while (it.hasNext()) { 8690 final BasePermission bp = it.next(); 8691 if (bp.packageSetting == null) { 8692 // We may not yet have parsed the package, so just see if 8693 // we still know about its settings. 8694 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8695 } 8696 if (bp.packageSetting == null) { 8697 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8698 + " from package " + bp.sourcePackage); 8699 it.remove(); 8700 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8701 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8702 Slog.i(TAG, "Removing old permission tree: " + bp.name 8703 + " from package " + bp.sourcePackage); 8704 flags |= UPDATE_PERMISSIONS_ALL; 8705 it.remove(); 8706 } 8707 } 8708 } 8709 8710 // Make sure all dynamic permissions have been assigned to a package, 8711 // and make sure there are no dangling permissions. 8712 it = mSettings.mPermissions.values().iterator(); 8713 while (it.hasNext()) { 8714 final BasePermission bp = it.next(); 8715 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8716 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8717 + bp.name + " pkg=" + bp.sourcePackage 8718 + " info=" + bp.pendingInfo); 8719 if (bp.packageSetting == null && bp.pendingInfo != null) { 8720 final BasePermission tree = findPermissionTreeLP(bp.name); 8721 if (tree != null && tree.perm != null) { 8722 bp.packageSetting = tree.packageSetting; 8723 bp.perm = new PackageParser.Permission(tree.perm.owner, 8724 new PermissionInfo(bp.pendingInfo)); 8725 bp.perm.info.packageName = tree.perm.info.packageName; 8726 bp.perm.info.name = bp.name; 8727 bp.uid = tree.uid; 8728 } 8729 } 8730 } 8731 if (bp.packageSetting == null) { 8732 // We may not yet have parsed the package, so just see if 8733 // we still know about its settings. 8734 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8735 } 8736 if (bp.packageSetting == null) { 8737 Slog.w(TAG, "Removing dangling permission: " + bp.name 8738 + " from package " + bp.sourcePackage); 8739 it.remove(); 8740 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8741 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8742 Slog.i(TAG, "Removing old permission: " + bp.name 8743 + " from package " + bp.sourcePackage); 8744 flags |= UPDATE_PERMISSIONS_ALL; 8745 it.remove(); 8746 } 8747 } 8748 } 8749 8750 // Now update the permissions for all packages, in particular 8751 // replace the granted permissions of the system packages. 8752 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8753 for (PackageParser.Package pkg : mPackages.values()) { 8754 if (pkg != pkgInfo) { 8755 // Only replace for packages on requested volume 8756 final String volumeUuid = getVolumeUuidForPackage(pkg); 8757 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8758 && Objects.equals(replaceVolumeUuid, volumeUuid); 8759 grantPermissionsLPw(pkg, replace, changingPkg); 8760 } 8761 } 8762 } 8763 8764 if (pkgInfo != null) { 8765 // Only replace for packages on requested volume 8766 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8767 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8768 && Objects.equals(replaceVolumeUuid, volumeUuid); 8769 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8770 } 8771 } 8772 8773 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8774 String packageOfInterest) { 8775 // IMPORTANT: There are two types of permissions: install and runtime. 8776 // Install time permissions are granted when the app is installed to 8777 // all device users and users added in the future. Runtime permissions 8778 // are granted at runtime explicitly to specific users. Normal and signature 8779 // protected permissions are install time permissions. Dangerous permissions 8780 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8781 // otherwise they are runtime permissions. This function does not manage 8782 // runtime permissions except for the case an app targeting Lollipop MR1 8783 // being upgraded to target a newer SDK, in which case dangerous permissions 8784 // are transformed from install time to runtime ones. 8785 8786 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8787 if (ps == null) { 8788 return; 8789 } 8790 8791 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8792 8793 PermissionsState permissionsState = ps.getPermissionsState(); 8794 PermissionsState origPermissions = permissionsState; 8795 8796 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8797 8798 boolean runtimePermissionsRevoked = false; 8799 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8800 8801 boolean changedInstallPermission = false; 8802 8803 if (replace) { 8804 ps.installPermissionsFixed = false; 8805 if (!ps.isSharedUser()) { 8806 origPermissions = new PermissionsState(permissionsState); 8807 permissionsState.reset(); 8808 } else { 8809 // We need to know only about runtime permission changes since the 8810 // calling code always writes the install permissions state but 8811 // the runtime ones are written only if changed. The only cases of 8812 // changed runtime permissions here are promotion of an install to 8813 // runtime and revocation of a runtime from a shared user. 8814 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8815 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8816 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8817 runtimePermissionsRevoked = true; 8818 } 8819 } 8820 } 8821 8822 permissionsState.setGlobalGids(mGlobalGids); 8823 8824 final int N = pkg.requestedPermissions.size(); 8825 for (int i=0; i<N; i++) { 8826 final String name = pkg.requestedPermissions.get(i); 8827 final BasePermission bp = mSettings.mPermissions.get(name); 8828 8829 if (DEBUG_INSTALL) { 8830 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8831 } 8832 8833 if (bp == null || bp.packageSetting == null) { 8834 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8835 Slog.w(TAG, "Unknown permission " + name 8836 + " in package " + pkg.packageName); 8837 } 8838 continue; 8839 } 8840 8841 final String perm = bp.name; 8842 boolean allowedSig = false; 8843 int grant = GRANT_DENIED; 8844 8845 // Keep track of app op permissions. 8846 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8847 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8848 if (pkgs == null) { 8849 pkgs = new ArraySet<>(); 8850 mAppOpPermissionPackages.put(bp.name, pkgs); 8851 } 8852 pkgs.add(pkg.packageName); 8853 } 8854 8855 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8856 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8857 >= Build.VERSION_CODES.M; 8858 switch (level) { 8859 case PermissionInfo.PROTECTION_NORMAL: { 8860 // For all apps normal permissions are install time ones. 8861 grant = GRANT_INSTALL; 8862 } break; 8863 8864 case PermissionInfo.PROTECTION_DANGEROUS: { 8865 // If a permission review is required for legacy apps we represent 8866 // their permissions as always granted runtime ones since we need 8867 // to keep the review required permission flag per user while an 8868 // install permission's state is shared across all users. 8869 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8870 // For legacy apps dangerous permissions are install time ones. 8871 grant = GRANT_INSTALL; 8872 } else if (origPermissions.hasInstallPermission(bp.name)) { 8873 // For legacy apps that became modern, install becomes runtime. 8874 grant = GRANT_UPGRADE; 8875 } else if (mPromoteSystemApps 8876 && isSystemApp(ps) 8877 && mExistingSystemPackages.contains(ps.name)) { 8878 // For legacy system apps, install becomes runtime. 8879 // We cannot check hasInstallPermission() for system apps since those 8880 // permissions were granted implicitly and not persisted pre-M. 8881 grant = GRANT_UPGRADE; 8882 } else { 8883 // For modern apps keep runtime permissions unchanged. 8884 grant = GRANT_RUNTIME; 8885 } 8886 } break; 8887 8888 case PermissionInfo.PROTECTION_SIGNATURE: { 8889 // For all apps signature permissions are install time ones. 8890 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8891 if (allowedSig) { 8892 grant = GRANT_INSTALL; 8893 } 8894 } break; 8895 } 8896 8897 if (DEBUG_INSTALL) { 8898 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8899 } 8900 8901 if (grant != GRANT_DENIED) { 8902 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8903 // If this is an existing, non-system package, then 8904 // we can't add any new permissions to it. 8905 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8906 // Except... if this is a permission that was added 8907 // to the platform (note: need to only do this when 8908 // updating the platform). 8909 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8910 grant = GRANT_DENIED; 8911 } 8912 } 8913 } 8914 8915 switch (grant) { 8916 case GRANT_INSTALL: { 8917 // Revoke this as runtime permission to handle the case of 8918 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8919 for (int userId : UserManagerService.getInstance().getUserIds()) { 8920 if (origPermissions.getRuntimePermissionState( 8921 bp.name, userId) != null) { 8922 // Revoke the runtime permission and clear the flags. 8923 origPermissions.revokeRuntimePermission(bp, userId); 8924 origPermissions.updatePermissionFlags(bp, userId, 8925 PackageManager.MASK_PERMISSION_FLAGS, 0); 8926 // If we revoked a permission permission, we have to write. 8927 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8928 changedRuntimePermissionUserIds, userId); 8929 } 8930 } 8931 // Grant an install permission. 8932 if (permissionsState.grantInstallPermission(bp) != 8933 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8934 changedInstallPermission = true; 8935 } 8936 } break; 8937 8938 case GRANT_RUNTIME: { 8939 // Grant previously granted runtime permissions. 8940 for (int userId : UserManagerService.getInstance().getUserIds()) { 8941 PermissionState permissionState = origPermissions 8942 .getRuntimePermissionState(bp.name, userId); 8943 int flags = permissionState != null 8944 ? permissionState.getFlags() : 0; 8945 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8946 if (permissionsState.grantRuntimePermission(bp, userId) == 8947 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8948 // If we cannot put the permission as it was, we have to write. 8949 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8950 changedRuntimePermissionUserIds, userId); 8951 } 8952 // If the app supports runtime permissions no need for a review. 8953 if (Build.PERMISSIONS_REVIEW_REQUIRED 8954 && appSupportsRuntimePermissions 8955 && (flags & PackageManager 8956 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8957 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8958 // Since we changed the flags, we have to write. 8959 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8960 changedRuntimePermissionUserIds, userId); 8961 } 8962 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8963 && !appSupportsRuntimePermissions) { 8964 // For legacy apps that need a permission review, every new 8965 // runtime permission is granted but it is pending a review. 8966 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8967 permissionsState.grantRuntimePermission(bp, userId); 8968 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8969 // We changed the permission and flags, hence have to write. 8970 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8971 changedRuntimePermissionUserIds, userId); 8972 } 8973 } 8974 // Propagate the permission flags. 8975 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8976 } 8977 } break; 8978 8979 case GRANT_UPGRADE: { 8980 // Grant runtime permissions for a previously held install permission. 8981 PermissionState permissionState = origPermissions 8982 .getInstallPermissionState(bp.name); 8983 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8984 8985 if (origPermissions.revokeInstallPermission(bp) 8986 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8987 // We will be transferring the permission flags, so clear them. 8988 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8989 PackageManager.MASK_PERMISSION_FLAGS, 0); 8990 changedInstallPermission = true; 8991 } 8992 8993 // If the permission is not to be promoted to runtime we ignore it and 8994 // also its other flags as they are not applicable to install permissions. 8995 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8996 for (int userId : currentUserIds) { 8997 if (permissionsState.grantRuntimePermission(bp, userId) != 8998 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8999 // Transfer the permission flags. 9000 permissionsState.updatePermissionFlags(bp, userId, 9001 flags, flags); 9002 // If we granted the permission, we have to write. 9003 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9004 changedRuntimePermissionUserIds, userId); 9005 } 9006 } 9007 } 9008 } break; 9009 9010 default: { 9011 if (packageOfInterest == null 9012 || packageOfInterest.equals(pkg.packageName)) { 9013 Slog.w(TAG, "Not granting permission " + perm 9014 + " to package " + pkg.packageName 9015 + " because it was previously installed without"); 9016 } 9017 } break; 9018 } 9019 } else { 9020 if (permissionsState.revokeInstallPermission(bp) != 9021 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9022 // Also drop the permission flags. 9023 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9024 PackageManager.MASK_PERMISSION_FLAGS, 0); 9025 changedInstallPermission = true; 9026 Slog.i(TAG, "Un-granting permission " + perm 9027 + " from package " + pkg.packageName 9028 + " (protectionLevel=" + bp.protectionLevel 9029 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9030 + ")"); 9031 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9032 // Don't print warning for app op permissions, since it is fine for them 9033 // not to be granted, there is a UI for the user to decide. 9034 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9035 Slog.w(TAG, "Not granting permission " + perm 9036 + " to package " + pkg.packageName 9037 + " (protectionLevel=" + bp.protectionLevel 9038 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9039 + ")"); 9040 } 9041 } 9042 } 9043 } 9044 9045 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9046 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9047 // This is the first that we have heard about this package, so the 9048 // permissions we have now selected are fixed until explicitly 9049 // changed. 9050 ps.installPermissionsFixed = true; 9051 } 9052 9053 // Persist the runtime permissions state for users with changes. If permissions 9054 // were revoked because no app in the shared user declares them we have to 9055 // write synchronously to avoid losing runtime permissions state. 9056 for (int userId : changedRuntimePermissionUserIds) { 9057 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9058 } 9059 9060 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9061 } 9062 9063 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9064 boolean allowed = false; 9065 final int NP = PackageParser.NEW_PERMISSIONS.length; 9066 for (int ip=0; ip<NP; ip++) { 9067 final PackageParser.NewPermissionInfo npi 9068 = PackageParser.NEW_PERMISSIONS[ip]; 9069 if (npi.name.equals(perm) 9070 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9071 allowed = true; 9072 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9073 + pkg.packageName); 9074 break; 9075 } 9076 } 9077 return allowed; 9078 } 9079 9080 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9081 BasePermission bp, PermissionsState origPermissions) { 9082 boolean allowed; 9083 allowed = (compareSignatures( 9084 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9085 == PackageManager.SIGNATURE_MATCH) 9086 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9087 == PackageManager.SIGNATURE_MATCH); 9088 if (!allowed && (bp.protectionLevel 9089 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9090 if (isSystemApp(pkg)) { 9091 // For updated system applications, a system permission 9092 // is granted only if it had been defined by the original application. 9093 if (pkg.isUpdatedSystemApp()) { 9094 final PackageSetting sysPs = mSettings 9095 .getDisabledSystemPkgLPr(pkg.packageName); 9096 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9097 // If the original was granted this permission, we take 9098 // that grant decision as read and propagate it to the 9099 // update. 9100 if (sysPs.isPrivileged()) { 9101 allowed = true; 9102 } 9103 } else { 9104 // The system apk may have been updated with an older 9105 // version of the one on the data partition, but which 9106 // granted a new system permission that it didn't have 9107 // before. In this case we do want to allow the app to 9108 // now get the new permission if the ancestral apk is 9109 // privileged to get it. 9110 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9111 for (int j=0; 9112 j<sysPs.pkg.requestedPermissions.size(); j++) { 9113 if (perm.equals( 9114 sysPs.pkg.requestedPermissions.get(j))) { 9115 allowed = true; 9116 break; 9117 } 9118 } 9119 } 9120 } 9121 } else { 9122 allowed = isPrivilegedApp(pkg); 9123 } 9124 } 9125 } 9126 if (!allowed) { 9127 if (!allowed && (bp.protectionLevel 9128 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9129 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9130 // If this was a previously normal/dangerous permission that got moved 9131 // to a system permission as part of the runtime permission redesign, then 9132 // we still want to blindly grant it to old apps. 9133 allowed = true; 9134 } 9135 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9136 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9137 // If this permission is to be granted to the system installer and 9138 // this app is an installer, then it gets the permission. 9139 allowed = true; 9140 } 9141 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9142 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9143 // If this permission is to be granted to the system verifier and 9144 // this app is a verifier, then it gets the permission. 9145 allowed = true; 9146 } 9147 if (!allowed && (bp.protectionLevel 9148 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9149 && isSystemApp(pkg)) { 9150 // Any pre-installed system app is allowed to get this permission. 9151 allowed = true; 9152 } 9153 if (!allowed && (bp.protectionLevel 9154 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9155 // For development permissions, a development permission 9156 // is granted only if it was already granted. 9157 allowed = origPermissions.hasInstallPermission(perm); 9158 } 9159 } 9160 return allowed; 9161 } 9162 9163 final class ActivityIntentResolver 9164 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9165 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9166 boolean defaultOnly, int userId) { 9167 if (!sUserManager.exists(userId)) return null; 9168 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9169 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9170 } 9171 9172 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9173 int userId) { 9174 if (!sUserManager.exists(userId)) return null; 9175 mFlags = flags; 9176 return super.queryIntent(intent, resolvedType, 9177 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9178 } 9179 9180 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9181 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9182 if (!sUserManager.exists(userId)) return null; 9183 if (packageActivities == null) { 9184 return null; 9185 } 9186 mFlags = flags; 9187 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9188 final int N = packageActivities.size(); 9189 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9190 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9191 9192 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9193 for (int i = 0; i < N; ++i) { 9194 intentFilters = packageActivities.get(i).intents; 9195 if (intentFilters != null && intentFilters.size() > 0) { 9196 PackageParser.ActivityIntentInfo[] array = 9197 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9198 intentFilters.toArray(array); 9199 listCut.add(array); 9200 } 9201 } 9202 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9203 } 9204 9205 public final void addActivity(PackageParser.Activity a, String type) { 9206 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9207 mActivities.put(a.getComponentName(), a); 9208 if (DEBUG_SHOW_INFO) 9209 Log.v( 9210 TAG, " " + type + " " + 9211 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9212 if (DEBUG_SHOW_INFO) 9213 Log.v(TAG, " Class=" + a.info.name); 9214 final int NI = a.intents.size(); 9215 for (int j=0; j<NI; j++) { 9216 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9217 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9218 intent.setPriority(0); 9219 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9220 + a.className + " with priority > 0, forcing to 0"); 9221 } 9222 if (DEBUG_SHOW_INFO) { 9223 Log.v(TAG, " IntentFilter:"); 9224 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9225 } 9226 if (!intent.debugCheck()) { 9227 Log.w(TAG, "==> For Activity " + a.info.name); 9228 } 9229 addFilter(intent); 9230 } 9231 } 9232 9233 public final void removeActivity(PackageParser.Activity a, String type) { 9234 mActivities.remove(a.getComponentName()); 9235 if (DEBUG_SHOW_INFO) { 9236 Log.v(TAG, " " + type + " " 9237 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9238 : a.info.name) + ":"); 9239 Log.v(TAG, " Class=" + a.info.name); 9240 } 9241 final int NI = a.intents.size(); 9242 for (int j=0; j<NI; j++) { 9243 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9244 if (DEBUG_SHOW_INFO) { 9245 Log.v(TAG, " IntentFilter:"); 9246 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9247 } 9248 removeFilter(intent); 9249 } 9250 } 9251 9252 @Override 9253 protected boolean allowFilterResult( 9254 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9255 ActivityInfo filterAi = filter.activity.info; 9256 for (int i=dest.size()-1; i>=0; i--) { 9257 ActivityInfo destAi = dest.get(i).activityInfo; 9258 if (destAi.name == filterAi.name 9259 && destAi.packageName == filterAi.packageName) { 9260 return false; 9261 } 9262 } 9263 return true; 9264 } 9265 9266 @Override 9267 protected ActivityIntentInfo[] newArray(int size) { 9268 return new ActivityIntentInfo[size]; 9269 } 9270 9271 @Override 9272 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9273 if (!sUserManager.exists(userId)) return true; 9274 PackageParser.Package p = filter.activity.owner; 9275 if (p != null) { 9276 PackageSetting ps = (PackageSetting)p.mExtras; 9277 if (ps != null) { 9278 // System apps are never considered stopped for purposes of 9279 // filtering, because there may be no way for the user to 9280 // actually re-launch them. 9281 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9282 && ps.getStopped(userId); 9283 } 9284 } 9285 return false; 9286 } 9287 9288 @Override 9289 protected boolean isPackageForFilter(String packageName, 9290 PackageParser.ActivityIntentInfo info) { 9291 return packageName.equals(info.activity.owner.packageName); 9292 } 9293 9294 @Override 9295 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9296 int match, int userId) { 9297 if (!sUserManager.exists(userId)) return null; 9298 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9299 return null; 9300 } 9301 final PackageParser.Activity activity = info.activity; 9302 if (mSafeMode && (activity.info.applicationInfo.flags 9303 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9304 return null; 9305 } 9306 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9307 if (ps == null) { 9308 return null; 9309 } 9310 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9311 ps.readUserState(userId), userId); 9312 if (ai == null) { 9313 return null; 9314 } 9315 final ResolveInfo res = new ResolveInfo(); 9316 res.activityInfo = ai; 9317 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9318 res.filter = info; 9319 } 9320 if (info != null) { 9321 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9322 } 9323 res.priority = info.getPriority(); 9324 res.preferredOrder = activity.owner.mPreferredOrder; 9325 //System.out.println("Result: " + res.activityInfo.className + 9326 // " = " + res.priority); 9327 res.match = match; 9328 res.isDefault = info.hasDefault; 9329 res.labelRes = info.labelRes; 9330 res.nonLocalizedLabel = info.nonLocalizedLabel; 9331 if (userNeedsBadging(userId)) { 9332 res.noResourceId = true; 9333 } else { 9334 res.icon = info.icon; 9335 } 9336 res.iconResourceId = info.icon; 9337 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9338 return res; 9339 } 9340 9341 @Override 9342 protected void sortResults(List<ResolveInfo> results) { 9343 Collections.sort(results, mResolvePrioritySorter); 9344 } 9345 9346 @Override 9347 protected void dumpFilter(PrintWriter out, String prefix, 9348 PackageParser.ActivityIntentInfo filter) { 9349 out.print(prefix); out.print( 9350 Integer.toHexString(System.identityHashCode(filter.activity))); 9351 out.print(' '); 9352 filter.activity.printComponentShortName(out); 9353 out.print(" filter "); 9354 out.println(Integer.toHexString(System.identityHashCode(filter))); 9355 } 9356 9357 @Override 9358 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9359 return filter.activity; 9360 } 9361 9362 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9363 PackageParser.Activity activity = (PackageParser.Activity)label; 9364 out.print(prefix); out.print( 9365 Integer.toHexString(System.identityHashCode(activity))); 9366 out.print(' '); 9367 activity.printComponentShortName(out); 9368 if (count > 1) { 9369 out.print(" ("); out.print(count); out.print(" filters)"); 9370 } 9371 out.println(); 9372 } 9373 9374// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9375// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9376// final List<ResolveInfo> retList = Lists.newArrayList(); 9377// while (i.hasNext()) { 9378// final ResolveInfo resolveInfo = i.next(); 9379// if (isEnabledLP(resolveInfo.activityInfo)) { 9380// retList.add(resolveInfo); 9381// } 9382// } 9383// return retList; 9384// } 9385 9386 // Keys are String (activity class name), values are Activity. 9387 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9388 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9389 private int mFlags; 9390 } 9391 9392 private final class ServiceIntentResolver 9393 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9394 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9395 boolean defaultOnly, int userId) { 9396 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9397 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9398 } 9399 9400 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9401 int userId) { 9402 if (!sUserManager.exists(userId)) return null; 9403 mFlags = flags; 9404 return super.queryIntent(intent, resolvedType, 9405 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9406 } 9407 9408 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9409 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9410 if (!sUserManager.exists(userId)) return null; 9411 if (packageServices == null) { 9412 return null; 9413 } 9414 mFlags = flags; 9415 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9416 final int N = packageServices.size(); 9417 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9418 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9419 9420 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9421 for (int i = 0; i < N; ++i) { 9422 intentFilters = packageServices.get(i).intents; 9423 if (intentFilters != null && intentFilters.size() > 0) { 9424 PackageParser.ServiceIntentInfo[] array = 9425 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9426 intentFilters.toArray(array); 9427 listCut.add(array); 9428 } 9429 } 9430 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9431 } 9432 9433 public final void addService(PackageParser.Service s) { 9434 mServices.put(s.getComponentName(), s); 9435 if (DEBUG_SHOW_INFO) { 9436 Log.v(TAG, " " 9437 + (s.info.nonLocalizedLabel != null 9438 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9439 Log.v(TAG, " Class=" + s.info.name); 9440 } 9441 final int NI = s.intents.size(); 9442 int j; 9443 for (j=0; j<NI; j++) { 9444 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9445 if (DEBUG_SHOW_INFO) { 9446 Log.v(TAG, " IntentFilter:"); 9447 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9448 } 9449 if (!intent.debugCheck()) { 9450 Log.w(TAG, "==> For Service " + s.info.name); 9451 } 9452 addFilter(intent); 9453 } 9454 } 9455 9456 public final void removeService(PackageParser.Service s) { 9457 mServices.remove(s.getComponentName()); 9458 if (DEBUG_SHOW_INFO) { 9459 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9460 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9461 Log.v(TAG, " Class=" + s.info.name); 9462 } 9463 final int NI = s.intents.size(); 9464 int j; 9465 for (j=0; j<NI; j++) { 9466 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9467 if (DEBUG_SHOW_INFO) { 9468 Log.v(TAG, " IntentFilter:"); 9469 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9470 } 9471 removeFilter(intent); 9472 } 9473 } 9474 9475 @Override 9476 protected boolean allowFilterResult( 9477 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9478 ServiceInfo filterSi = filter.service.info; 9479 for (int i=dest.size()-1; i>=0; i--) { 9480 ServiceInfo destAi = dest.get(i).serviceInfo; 9481 if (destAi.name == filterSi.name 9482 && destAi.packageName == filterSi.packageName) { 9483 return false; 9484 } 9485 } 9486 return true; 9487 } 9488 9489 @Override 9490 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9491 return new PackageParser.ServiceIntentInfo[size]; 9492 } 9493 9494 @Override 9495 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9496 if (!sUserManager.exists(userId)) return true; 9497 PackageParser.Package p = filter.service.owner; 9498 if (p != null) { 9499 PackageSetting ps = (PackageSetting)p.mExtras; 9500 if (ps != null) { 9501 // System apps are never considered stopped for purposes of 9502 // filtering, because there may be no way for the user to 9503 // actually re-launch them. 9504 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9505 && ps.getStopped(userId); 9506 } 9507 } 9508 return false; 9509 } 9510 9511 @Override 9512 protected boolean isPackageForFilter(String packageName, 9513 PackageParser.ServiceIntentInfo info) { 9514 return packageName.equals(info.service.owner.packageName); 9515 } 9516 9517 @Override 9518 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9519 int match, int userId) { 9520 if (!sUserManager.exists(userId)) return null; 9521 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9522 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9523 return null; 9524 } 9525 final PackageParser.Service service = info.service; 9526 if (mSafeMode && (service.info.applicationInfo.flags 9527 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9528 return null; 9529 } 9530 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9531 if (ps == null) { 9532 return null; 9533 } 9534 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9535 ps.readUserState(userId), userId); 9536 if (si == null) { 9537 return null; 9538 } 9539 final ResolveInfo res = new ResolveInfo(); 9540 res.serviceInfo = si; 9541 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9542 res.filter = filter; 9543 } 9544 res.priority = info.getPriority(); 9545 res.preferredOrder = service.owner.mPreferredOrder; 9546 res.match = match; 9547 res.isDefault = info.hasDefault; 9548 res.labelRes = info.labelRes; 9549 res.nonLocalizedLabel = info.nonLocalizedLabel; 9550 res.icon = info.icon; 9551 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9552 return res; 9553 } 9554 9555 @Override 9556 protected void sortResults(List<ResolveInfo> results) { 9557 Collections.sort(results, mResolvePrioritySorter); 9558 } 9559 9560 @Override 9561 protected void dumpFilter(PrintWriter out, String prefix, 9562 PackageParser.ServiceIntentInfo filter) { 9563 out.print(prefix); out.print( 9564 Integer.toHexString(System.identityHashCode(filter.service))); 9565 out.print(' '); 9566 filter.service.printComponentShortName(out); 9567 out.print(" filter "); 9568 out.println(Integer.toHexString(System.identityHashCode(filter))); 9569 } 9570 9571 @Override 9572 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9573 return filter.service; 9574 } 9575 9576 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9577 PackageParser.Service service = (PackageParser.Service)label; 9578 out.print(prefix); out.print( 9579 Integer.toHexString(System.identityHashCode(service))); 9580 out.print(' '); 9581 service.printComponentShortName(out); 9582 if (count > 1) { 9583 out.print(" ("); out.print(count); out.print(" filters)"); 9584 } 9585 out.println(); 9586 } 9587 9588// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9589// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9590// final List<ResolveInfo> retList = Lists.newArrayList(); 9591// while (i.hasNext()) { 9592// final ResolveInfo resolveInfo = (ResolveInfo) i; 9593// if (isEnabledLP(resolveInfo.serviceInfo)) { 9594// retList.add(resolveInfo); 9595// } 9596// } 9597// return retList; 9598// } 9599 9600 // Keys are String (activity class name), values are Activity. 9601 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9602 = new ArrayMap<ComponentName, PackageParser.Service>(); 9603 private int mFlags; 9604 }; 9605 9606 private final class ProviderIntentResolver 9607 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9608 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9609 boolean defaultOnly, int userId) { 9610 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9611 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9612 } 9613 9614 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9615 int userId) { 9616 if (!sUserManager.exists(userId)) 9617 return null; 9618 mFlags = flags; 9619 return super.queryIntent(intent, resolvedType, 9620 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9621 } 9622 9623 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9624 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9625 if (!sUserManager.exists(userId)) 9626 return null; 9627 if (packageProviders == null) { 9628 return null; 9629 } 9630 mFlags = flags; 9631 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9632 final int N = packageProviders.size(); 9633 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9634 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9635 9636 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9637 for (int i = 0; i < N; ++i) { 9638 intentFilters = packageProviders.get(i).intents; 9639 if (intentFilters != null && intentFilters.size() > 0) { 9640 PackageParser.ProviderIntentInfo[] array = 9641 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9642 intentFilters.toArray(array); 9643 listCut.add(array); 9644 } 9645 } 9646 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9647 } 9648 9649 public final void addProvider(PackageParser.Provider p) { 9650 if (mProviders.containsKey(p.getComponentName())) { 9651 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9652 return; 9653 } 9654 9655 mProviders.put(p.getComponentName(), p); 9656 if (DEBUG_SHOW_INFO) { 9657 Log.v(TAG, " " 9658 + (p.info.nonLocalizedLabel != null 9659 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9660 Log.v(TAG, " Class=" + p.info.name); 9661 } 9662 final int NI = p.intents.size(); 9663 int j; 9664 for (j = 0; j < NI; j++) { 9665 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9666 if (DEBUG_SHOW_INFO) { 9667 Log.v(TAG, " IntentFilter:"); 9668 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9669 } 9670 if (!intent.debugCheck()) { 9671 Log.w(TAG, "==> For Provider " + p.info.name); 9672 } 9673 addFilter(intent); 9674 } 9675 } 9676 9677 public final void removeProvider(PackageParser.Provider p) { 9678 mProviders.remove(p.getComponentName()); 9679 if (DEBUG_SHOW_INFO) { 9680 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9681 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9682 Log.v(TAG, " Class=" + p.info.name); 9683 } 9684 final int NI = p.intents.size(); 9685 int j; 9686 for (j = 0; j < NI; j++) { 9687 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9688 if (DEBUG_SHOW_INFO) { 9689 Log.v(TAG, " IntentFilter:"); 9690 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9691 } 9692 removeFilter(intent); 9693 } 9694 } 9695 9696 @Override 9697 protected boolean allowFilterResult( 9698 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9699 ProviderInfo filterPi = filter.provider.info; 9700 for (int i = dest.size() - 1; i >= 0; i--) { 9701 ProviderInfo destPi = dest.get(i).providerInfo; 9702 if (destPi.name == filterPi.name 9703 && destPi.packageName == filterPi.packageName) { 9704 return false; 9705 } 9706 } 9707 return true; 9708 } 9709 9710 @Override 9711 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9712 return new PackageParser.ProviderIntentInfo[size]; 9713 } 9714 9715 @Override 9716 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9717 if (!sUserManager.exists(userId)) 9718 return true; 9719 PackageParser.Package p = filter.provider.owner; 9720 if (p != null) { 9721 PackageSetting ps = (PackageSetting) p.mExtras; 9722 if (ps != null) { 9723 // System apps are never considered stopped for purposes of 9724 // filtering, because there may be no way for the user to 9725 // actually re-launch them. 9726 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9727 && ps.getStopped(userId); 9728 } 9729 } 9730 return false; 9731 } 9732 9733 @Override 9734 protected boolean isPackageForFilter(String packageName, 9735 PackageParser.ProviderIntentInfo info) { 9736 return packageName.equals(info.provider.owner.packageName); 9737 } 9738 9739 @Override 9740 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9741 int match, int userId) { 9742 if (!sUserManager.exists(userId)) 9743 return null; 9744 final PackageParser.ProviderIntentInfo info = filter; 9745 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9746 return null; 9747 } 9748 final PackageParser.Provider provider = info.provider; 9749 if (mSafeMode && (provider.info.applicationInfo.flags 9750 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9751 return null; 9752 } 9753 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9754 if (ps == null) { 9755 return null; 9756 } 9757 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9758 ps.readUserState(userId), userId); 9759 if (pi == null) { 9760 return null; 9761 } 9762 final ResolveInfo res = new ResolveInfo(); 9763 res.providerInfo = pi; 9764 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9765 res.filter = filter; 9766 } 9767 res.priority = info.getPriority(); 9768 res.preferredOrder = provider.owner.mPreferredOrder; 9769 res.match = match; 9770 res.isDefault = info.hasDefault; 9771 res.labelRes = info.labelRes; 9772 res.nonLocalizedLabel = info.nonLocalizedLabel; 9773 res.icon = info.icon; 9774 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9775 return res; 9776 } 9777 9778 @Override 9779 protected void sortResults(List<ResolveInfo> results) { 9780 Collections.sort(results, mResolvePrioritySorter); 9781 } 9782 9783 @Override 9784 protected void dumpFilter(PrintWriter out, String prefix, 9785 PackageParser.ProviderIntentInfo filter) { 9786 out.print(prefix); 9787 out.print( 9788 Integer.toHexString(System.identityHashCode(filter.provider))); 9789 out.print(' '); 9790 filter.provider.printComponentShortName(out); 9791 out.print(" filter "); 9792 out.println(Integer.toHexString(System.identityHashCode(filter))); 9793 } 9794 9795 @Override 9796 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9797 return filter.provider; 9798 } 9799 9800 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9801 PackageParser.Provider provider = (PackageParser.Provider)label; 9802 out.print(prefix); out.print( 9803 Integer.toHexString(System.identityHashCode(provider))); 9804 out.print(' '); 9805 provider.printComponentShortName(out); 9806 if (count > 1) { 9807 out.print(" ("); out.print(count); out.print(" filters)"); 9808 } 9809 out.println(); 9810 } 9811 9812 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9813 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9814 private int mFlags; 9815 } 9816 9817 private static final class EphemeralIntentResolver 9818 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9819 @Override 9820 protected EphemeralResolveIntentInfo[] newArray(int size) { 9821 return new EphemeralResolveIntentInfo[size]; 9822 } 9823 9824 @Override 9825 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9826 return true; 9827 } 9828 9829 @Override 9830 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9831 int userId) { 9832 if (!sUserManager.exists(userId)) { 9833 return null; 9834 } 9835 return info.getEphemeralResolveInfo(); 9836 } 9837 } 9838 9839 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9840 new Comparator<ResolveInfo>() { 9841 public int compare(ResolveInfo r1, ResolveInfo r2) { 9842 int v1 = r1.priority; 9843 int v2 = r2.priority; 9844 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9845 if (v1 != v2) { 9846 return (v1 > v2) ? -1 : 1; 9847 } 9848 v1 = r1.preferredOrder; 9849 v2 = r2.preferredOrder; 9850 if (v1 != v2) { 9851 return (v1 > v2) ? -1 : 1; 9852 } 9853 if (r1.isDefault != r2.isDefault) { 9854 return r1.isDefault ? -1 : 1; 9855 } 9856 v1 = r1.match; 9857 v2 = r2.match; 9858 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9859 if (v1 != v2) { 9860 return (v1 > v2) ? -1 : 1; 9861 } 9862 if (r1.system != r2.system) { 9863 return r1.system ? -1 : 1; 9864 } 9865 if (r1.activityInfo != null) { 9866 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9867 } 9868 if (r1.serviceInfo != null) { 9869 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9870 } 9871 if (r1.providerInfo != null) { 9872 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9873 } 9874 return 0; 9875 } 9876 }; 9877 9878 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9879 new Comparator<ProviderInfo>() { 9880 public int compare(ProviderInfo p1, ProviderInfo p2) { 9881 final int v1 = p1.initOrder; 9882 final int v2 = p2.initOrder; 9883 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9884 } 9885 }; 9886 9887 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9888 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9889 final int[] userIds) { 9890 mHandler.post(new Runnable() { 9891 @Override 9892 public void run() { 9893 try { 9894 final IActivityManager am = ActivityManagerNative.getDefault(); 9895 if (am == null) return; 9896 final int[] resolvedUserIds; 9897 if (userIds == null) { 9898 resolvedUserIds = am.getRunningUserIds(); 9899 } else { 9900 resolvedUserIds = userIds; 9901 } 9902 for (int id : resolvedUserIds) { 9903 final Intent intent = new Intent(action, 9904 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9905 if (extras != null) { 9906 intent.putExtras(extras); 9907 } 9908 if (targetPkg != null) { 9909 intent.setPackage(targetPkg); 9910 } 9911 // Modify the UID when posting to other users 9912 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9913 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9914 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9915 intent.putExtra(Intent.EXTRA_UID, uid); 9916 } 9917 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9918 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9919 if (DEBUG_BROADCASTS) { 9920 RuntimeException here = new RuntimeException("here"); 9921 here.fillInStackTrace(); 9922 Slog.d(TAG, "Sending to user " + id + ": " 9923 + intent.toShortString(false, true, false, false) 9924 + " " + intent.getExtras(), here); 9925 } 9926 am.broadcastIntent(null, intent, null, finishedReceiver, 9927 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9928 null, finishedReceiver != null, false, id); 9929 } 9930 } catch (RemoteException ex) { 9931 } 9932 } 9933 }); 9934 } 9935 9936 /** 9937 * Check if the external storage media is available. This is true if there 9938 * is a mounted external storage medium or if the external storage is 9939 * emulated. 9940 */ 9941 private boolean isExternalMediaAvailable() { 9942 return mMediaMounted || Environment.isExternalStorageEmulated(); 9943 } 9944 9945 @Override 9946 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9947 // writer 9948 synchronized (mPackages) { 9949 if (!isExternalMediaAvailable()) { 9950 // If the external storage is no longer mounted at this point, 9951 // the caller may not have been able to delete all of this 9952 // packages files and can not delete any more. Bail. 9953 return null; 9954 } 9955 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9956 if (lastPackage != null) { 9957 pkgs.remove(lastPackage); 9958 } 9959 if (pkgs.size() > 0) { 9960 return pkgs.get(0); 9961 } 9962 } 9963 return null; 9964 } 9965 9966 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9967 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9968 userId, andCode ? 1 : 0, packageName); 9969 if (mSystemReady) { 9970 msg.sendToTarget(); 9971 } else { 9972 if (mPostSystemReadyMessages == null) { 9973 mPostSystemReadyMessages = new ArrayList<>(); 9974 } 9975 mPostSystemReadyMessages.add(msg); 9976 } 9977 } 9978 9979 void startCleaningPackages() { 9980 // reader 9981 synchronized (mPackages) { 9982 if (!isExternalMediaAvailable()) { 9983 return; 9984 } 9985 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9986 return; 9987 } 9988 } 9989 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9990 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9991 IActivityManager am = ActivityManagerNative.getDefault(); 9992 if (am != null) { 9993 try { 9994 am.startService(null, intent, null, mContext.getOpPackageName(), 9995 UserHandle.USER_SYSTEM); 9996 } catch (RemoteException e) { 9997 } 9998 } 9999 } 10000 10001 @Override 10002 public void installPackage(String originPath, IPackageInstallObserver2 observer, 10003 int installFlags, String installerPackageName, VerificationParams verificationParams, 10004 String packageAbiOverride) { 10005 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 10006 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 10007 } 10008 10009 @Override 10010 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10011 int installFlags, String installerPackageName, VerificationParams verificationParams, 10012 String packageAbiOverride, int userId) { 10013 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10014 10015 final int callingUid = Binder.getCallingUid(); 10016 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 10017 10018 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10019 try { 10020 if (observer != null) { 10021 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10022 } 10023 } catch (RemoteException re) { 10024 } 10025 return; 10026 } 10027 10028 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10029 installFlags |= PackageManager.INSTALL_FROM_ADB; 10030 10031 } else { 10032 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10033 // about installerPackageName. 10034 10035 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10036 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10037 } 10038 10039 UserHandle user; 10040 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10041 user = UserHandle.ALL; 10042 } else { 10043 user = new UserHandle(userId); 10044 } 10045 10046 // Only system components can circumvent runtime permissions when installing. 10047 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10048 && mContext.checkCallingOrSelfPermission(Manifest.permission 10049 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10050 throw new SecurityException("You need the " 10051 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10052 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10053 } 10054 10055 verificationParams.setInstallerUid(callingUid); 10056 10057 final File originFile = new File(originPath); 10058 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10059 10060 final Message msg = mHandler.obtainMessage(INIT_COPY); 10061 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10062 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10063 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10064 msg.obj = params; 10065 10066 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10067 System.identityHashCode(msg.obj)); 10068 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10069 System.identityHashCode(msg.obj)); 10070 10071 mHandler.sendMessage(msg); 10072 } 10073 10074 void installStage(String packageName, File stagedDir, String stagedCid, 10075 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10076 String installerPackageName, int installerUid, UserHandle user) { 10077 if (DEBUG_EPHEMERAL) { 10078 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10079 Slog.d(TAG, "Ephemeral install of " + packageName); 10080 } 10081 } 10082 final VerificationParams verifParams = new VerificationParams( 10083 null, sessionParams.originatingUri, sessionParams.referrerUri, 10084 sessionParams.originatingUid, null); 10085 verifParams.setInstallerUid(installerUid); 10086 10087 final OriginInfo origin; 10088 if (stagedDir != null) { 10089 origin = OriginInfo.fromStagedFile(stagedDir); 10090 } else { 10091 origin = OriginInfo.fromStagedContainer(stagedCid); 10092 } 10093 10094 final Message msg = mHandler.obtainMessage(INIT_COPY); 10095 final InstallParams params = new InstallParams(origin, null, observer, 10096 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10097 verifParams, user, sessionParams.abiOverride, 10098 sessionParams.grantedRuntimePermissions); 10099 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10100 msg.obj = params; 10101 10102 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10103 System.identityHashCode(msg.obj)); 10104 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10105 System.identityHashCode(msg.obj)); 10106 10107 mHandler.sendMessage(msg); 10108 } 10109 10110 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10111 Bundle extras = new Bundle(1); 10112 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10113 10114 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10115 packageName, extras, 0, null, null, new int[] {userId}); 10116 try { 10117 IActivityManager am = ActivityManagerNative.getDefault(); 10118 final boolean isSystem = 10119 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10120 if (isSystem && am.isUserRunning(userId, 0)) { 10121 // The just-installed/enabled app is bundled on the system, so presumed 10122 // to be able to run automatically without needing an explicit launch. 10123 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10124 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10125 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10126 .setPackage(packageName); 10127 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10128 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10129 } 10130 } catch (RemoteException e) { 10131 // shouldn't happen 10132 Slog.w(TAG, "Unable to bootstrap installed package", e); 10133 } 10134 } 10135 10136 @Override 10137 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10138 int userId) { 10139 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10140 PackageSetting pkgSetting; 10141 final int uid = Binder.getCallingUid(); 10142 enforceCrossUserPermission(uid, userId, true, true, 10143 "setApplicationHiddenSetting for user " + userId); 10144 10145 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10146 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10147 return false; 10148 } 10149 10150 long callingId = Binder.clearCallingIdentity(); 10151 try { 10152 boolean sendAdded = false; 10153 boolean sendRemoved = false; 10154 // writer 10155 synchronized (mPackages) { 10156 pkgSetting = mSettings.mPackages.get(packageName); 10157 if (pkgSetting == null) { 10158 return false; 10159 } 10160 if (pkgSetting.getHidden(userId) != hidden) { 10161 pkgSetting.setHidden(hidden, userId); 10162 mSettings.writePackageRestrictionsLPr(userId); 10163 if (hidden) { 10164 sendRemoved = true; 10165 } else { 10166 sendAdded = true; 10167 } 10168 } 10169 } 10170 if (sendAdded) { 10171 sendPackageAddedForUser(packageName, pkgSetting, userId); 10172 return true; 10173 } 10174 if (sendRemoved) { 10175 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10176 "hiding pkg"); 10177 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10178 return true; 10179 } 10180 } finally { 10181 Binder.restoreCallingIdentity(callingId); 10182 } 10183 return false; 10184 } 10185 10186 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10187 int userId) { 10188 final PackageRemovedInfo info = new PackageRemovedInfo(); 10189 info.removedPackage = packageName; 10190 info.removedUsers = new int[] {userId}; 10191 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10192 info.sendBroadcast(false, false, false); 10193 } 10194 10195 /** 10196 * Returns true if application is not found or there was an error. Otherwise it returns 10197 * the hidden state of the package for the given user. 10198 */ 10199 @Override 10200 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10201 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10202 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10203 false, "getApplicationHidden for user " + userId); 10204 PackageSetting pkgSetting; 10205 long callingId = Binder.clearCallingIdentity(); 10206 try { 10207 // writer 10208 synchronized (mPackages) { 10209 pkgSetting = mSettings.mPackages.get(packageName); 10210 if (pkgSetting == null) { 10211 return true; 10212 } 10213 return pkgSetting.getHidden(userId); 10214 } 10215 } finally { 10216 Binder.restoreCallingIdentity(callingId); 10217 } 10218 } 10219 10220 /** 10221 * @hide 10222 */ 10223 @Override 10224 public int installExistingPackageAsUser(String packageName, int userId) { 10225 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10226 null); 10227 PackageSetting pkgSetting; 10228 final int uid = Binder.getCallingUid(); 10229 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10230 + userId); 10231 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10232 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10233 } 10234 10235 long callingId = Binder.clearCallingIdentity(); 10236 try { 10237 boolean sendAdded = false; 10238 10239 // writer 10240 synchronized (mPackages) { 10241 pkgSetting = mSettings.mPackages.get(packageName); 10242 if (pkgSetting == null) { 10243 return PackageManager.INSTALL_FAILED_INVALID_URI; 10244 } 10245 if (!pkgSetting.getInstalled(userId)) { 10246 pkgSetting.setInstalled(true, userId); 10247 pkgSetting.setHidden(false, userId); 10248 mSettings.writePackageRestrictionsLPr(userId); 10249 sendAdded = true; 10250 } 10251 } 10252 10253 if (sendAdded) { 10254 sendPackageAddedForUser(packageName, pkgSetting, userId); 10255 } 10256 } finally { 10257 Binder.restoreCallingIdentity(callingId); 10258 } 10259 10260 return PackageManager.INSTALL_SUCCEEDED; 10261 } 10262 10263 boolean isUserRestricted(int userId, String restrictionKey) { 10264 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10265 if (restrictions.getBoolean(restrictionKey, false)) { 10266 Log.w(TAG, "User is restricted: " + restrictionKey); 10267 return true; 10268 } 10269 return false; 10270 } 10271 10272 @Override 10273 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10274 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10275 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10276 "setPackageSuspended for user " + userId); 10277 10278 long callingId = Binder.clearCallingIdentity(); 10279 try { 10280 synchronized (mPackages) { 10281 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10282 if (pkgSetting != null) { 10283 if (pkgSetting.getSuspended(userId) != suspended) { 10284 pkgSetting.setSuspended(suspended, userId); 10285 mSettings.writePackageRestrictionsLPr(userId); 10286 } 10287 10288 // TODO: 10289 // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up 10290 // * remove app from recents (kill app it if it is running) 10291 // * erase existing notifications for this app 10292 return true; 10293 } 10294 10295 return false; 10296 } 10297 } finally { 10298 Binder.restoreCallingIdentity(callingId); 10299 } 10300 } 10301 10302 @Override 10303 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10304 mContext.enforceCallingOrSelfPermission( 10305 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10306 "Only package verification agents can verify applications"); 10307 10308 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10309 final PackageVerificationResponse response = new PackageVerificationResponse( 10310 verificationCode, Binder.getCallingUid()); 10311 msg.arg1 = id; 10312 msg.obj = response; 10313 mHandler.sendMessage(msg); 10314 } 10315 10316 @Override 10317 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10318 long millisecondsToDelay) { 10319 mContext.enforceCallingOrSelfPermission( 10320 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10321 "Only package verification agents can extend verification timeouts"); 10322 10323 final PackageVerificationState state = mPendingVerification.get(id); 10324 final PackageVerificationResponse response = new PackageVerificationResponse( 10325 verificationCodeAtTimeout, Binder.getCallingUid()); 10326 10327 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10328 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10329 } 10330 if (millisecondsToDelay < 0) { 10331 millisecondsToDelay = 0; 10332 } 10333 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10334 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10335 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10336 } 10337 10338 if ((state != null) && !state.timeoutExtended()) { 10339 state.extendTimeout(); 10340 10341 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10342 msg.arg1 = id; 10343 msg.obj = response; 10344 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10345 } 10346 } 10347 10348 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10349 int verificationCode, UserHandle user) { 10350 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10351 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10352 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10353 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10354 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10355 10356 mContext.sendBroadcastAsUser(intent, user, 10357 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10358 } 10359 10360 private ComponentName matchComponentForVerifier(String packageName, 10361 List<ResolveInfo> receivers) { 10362 ActivityInfo targetReceiver = null; 10363 10364 final int NR = receivers.size(); 10365 for (int i = 0; i < NR; i++) { 10366 final ResolveInfo info = receivers.get(i); 10367 if (info.activityInfo == null) { 10368 continue; 10369 } 10370 10371 if (packageName.equals(info.activityInfo.packageName)) { 10372 targetReceiver = info.activityInfo; 10373 break; 10374 } 10375 } 10376 10377 if (targetReceiver == null) { 10378 return null; 10379 } 10380 10381 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10382 } 10383 10384 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10385 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10386 if (pkgInfo.verifiers.length == 0) { 10387 return null; 10388 } 10389 10390 final int N = pkgInfo.verifiers.length; 10391 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10392 for (int i = 0; i < N; i++) { 10393 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10394 10395 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10396 receivers); 10397 if (comp == null) { 10398 continue; 10399 } 10400 10401 final int verifierUid = getUidForVerifier(verifierInfo); 10402 if (verifierUid == -1) { 10403 continue; 10404 } 10405 10406 if (DEBUG_VERIFY) { 10407 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10408 + " with the correct signature"); 10409 } 10410 sufficientVerifiers.add(comp); 10411 verificationState.addSufficientVerifier(verifierUid); 10412 } 10413 10414 return sufficientVerifiers; 10415 } 10416 10417 private int getUidForVerifier(VerifierInfo verifierInfo) { 10418 synchronized (mPackages) { 10419 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10420 if (pkg == null) { 10421 return -1; 10422 } else if (pkg.mSignatures.length != 1) { 10423 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10424 + " has more than one signature; ignoring"); 10425 return -1; 10426 } 10427 10428 /* 10429 * If the public key of the package's signature does not match 10430 * our expected public key, then this is a different package and 10431 * we should skip. 10432 */ 10433 10434 final byte[] expectedPublicKey; 10435 try { 10436 final Signature verifierSig = pkg.mSignatures[0]; 10437 final PublicKey publicKey = verifierSig.getPublicKey(); 10438 expectedPublicKey = publicKey.getEncoded(); 10439 } catch (CertificateException e) { 10440 return -1; 10441 } 10442 10443 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10444 10445 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10446 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10447 + " does not have the expected public key; ignoring"); 10448 return -1; 10449 } 10450 10451 return pkg.applicationInfo.uid; 10452 } 10453 } 10454 10455 @Override 10456 public void finishPackageInstall(int token) { 10457 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10458 10459 if (DEBUG_INSTALL) { 10460 Slog.v(TAG, "BM finishing package install for " + token); 10461 } 10462 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10463 10464 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10465 mHandler.sendMessage(msg); 10466 } 10467 10468 /** 10469 * Get the verification agent timeout. 10470 * 10471 * @return verification timeout in milliseconds 10472 */ 10473 private long getVerificationTimeout() { 10474 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10475 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10476 DEFAULT_VERIFICATION_TIMEOUT); 10477 } 10478 10479 /** 10480 * Get the default verification agent response code. 10481 * 10482 * @return default verification response code 10483 */ 10484 private int getDefaultVerificationResponse() { 10485 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10486 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10487 DEFAULT_VERIFICATION_RESPONSE); 10488 } 10489 10490 /** 10491 * Check whether or not package verification has been enabled. 10492 * 10493 * @return true if verification should be performed 10494 */ 10495 private boolean isVerificationEnabled(int userId, int installFlags) { 10496 if (!DEFAULT_VERIFY_ENABLE) { 10497 return false; 10498 } 10499 // Ephemeral apps don't get the full verification treatment 10500 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10501 if (DEBUG_EPHEMERAL) { 10502 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10503 } 10504 return false; 10505 } 10506 10507 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10508 10509 // Check if installing from ADB 10510 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10511 // Do not run verification in a test harness environment 10512 if (ActivityManager.isRunningInTestHarness()) { 10513 return false; 10514 } 10515 if (ensureVerifyAppsEnabled) { 10516 return true; 10517 } 10518 // Check if the developer does not want package verification for ADB installs 10519 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10520 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10521 return false; 10522 } 10523 } 10524 10525 if (ensureVerifyAppsEnabled) { 10526 return true; 10527 } 10528 10529 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10530 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10531 } 10532 10533 @Override 10534 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10535 throws RemoteException { 10536 mContext.enforceCallingOrSelfPermission( 10537 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10538 "Only intentfilter verification agents can verify applications"); 10539 10540 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10541 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10542 Binder.getCallingUid(), verificationCode, failedDomains); 10543 msg.arg1 = id; 10544 msg.obj = response; 10545 mHandler.sendMessage(msg); 10546 } 10547 10548 @Override 10549 public int getIntentVerificationStatus(String packageName, int userId) { 10550 synchronized (mPackages) { 10551 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10552 } 10553 } 10554 10555 @Override 10556 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10557 mContext.enforceCallingOrSelfPermission( 10558 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10559 10560 boolean result = false; 10561 synchronized (mPackages) { 10562 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10563 } 10564 if (result) { 10565 scheduleWritePackageRestrictionsLocked(userId); 10566 } 10567 return result; 10568 } 10569 10570 @Override 10571 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10572 synchronized (mPackages) { 10573 return mSettings.getIntentFilterVerificationsLPr(packageName); 10574 } 10575 } 10576 10577 @Override 10578 public List<IntentFilter> getAllIntentFilters(String packageName) { 10579 if (TextUtils.isEmpty(packageName)) { 10580 return Collections.<IntentFilter>emptyList(); 10581 } 10582 synchronized (mPackages) { 10583 PackageParser.Package pkg = mPackages.get(packageName); 10584 if (pkg == null || pkg.activities == null) { 10585 return Collections.<IntentFilter>emptyList(); 10586 } 10587 final int count = pkg.activities.size(); 10588 ArrayList<IntentFilter> result = new ArrayList<>(); 10589 for (int n=0; n<count; n++) { 10590 PackageParser.Activity activity = pkg.activities.get(n); 10591 if (activity.intents != null && activity.intents.size() > 0) { 10592 result.addAll(activity.intents); 10593 } 10594 } 10595 return result; 10596 } 10597 } 10598 10599 @Override 10600 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10601 mContext.enforceCallingOrSelfPermission( 10602 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10603 10604 synchronized (mPackages) { 10605 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10606 if (packageName != null) { 10607 result |= updateIntentVerificationStatus(packageName, 10608 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10609 userId); 10610 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10611 packageName, userId); 10612 } 10613 return result; 10614 } 10615 } 10616 10617 @Override 10618 public String getDefaultBrowserPackageName(int userId) { 10619 synchronized (mPackages) { 10620 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10621 } 10622 } 10623 10624 /** 10625 * Get the "allow unknown sources" setting. 10626 * 10627 * @return the current "allow unknown sources" setting 10628 */ 10629 private int getUnknownSourcesSettings() { 10630 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10631 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10632 -1); 10633 } 10634 10635 @Override 10636 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10637 final int uid = Binder.getCallingUid(); 10638 // writer 10639 synchronized (mPackages) { 10640 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10641 if (targetPackageSetting == null) { 10642 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10643 } 10644 10645 PackageSetting installerPackageSetting; 10646 if (installerPackageName != null) { 10647 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10648 if (installerPackageSetting == null) { 10649 throw new IllegalArgumentException("Unknown installer package: " 10650 + installerPackageName); 10651 } 10652 } else { 10653 installerPackageSetting = null; 10654 } 10655 10656 Signature[] callerSignature; 10657 Object obj = mSettings.getUserIdLPr(uid); 10658 if (obj != null) { 10659 if (obj instanceof SharedUserSetting) { 10660 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10661 } else if (obj instanceof PackageSetting) { 10662 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10663 } else { 10664 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10665 } 10666 } else { 10667 throw new SecurityException("Unknown calling uid " + uid); 10668 } 10669 10670 // Verify: can't set installerPackageName to a package that is 10671 // not signed with the same cert as the caller. 10672 if (installerPackageSetting != null) { 10673 if (compareSignatures(callerSignature, 10674 installerPackageSetting.signatures.mSignatures) 10675 != PackageManager.SIGNATURE_MATCH) { 10676 throw new SecurityException( 10677 "Caller does not have same cert as new installer package " 10678 + installerPackageName); 10679 } 10680 } 10681 10682 // Verify: if target already has an installer package, it must 10683 // be signed with the same cert as the caller. 10684 if (targetPackageSetting.installerPackageName != null) { 10685 PackageSetting setting = mSettings.mPackages.get( 10686 targetPackageSetting.installerPackageName); 10687 // If the currently set package isn't valid, then it's always 10688 // okay to change it. 10689 if (setting != null) { 10690 if (compareSignatures(callerSignature, 10691 setting.signatures.mSignatures) 10692 != PackageManager.SIGNATURE_MATCH) { 10693 throw new SecurityException( 10694 "Caller does not have same cert as old installer package " 10695 + targetPackageSetting.installerPackageName); 10696 } 10697 } 10698 } 10699 10700 // Okay! 10701 targetPackageSetting.installerPackageName = installerPackageName; 10702 scheduleWriteSettingsLocked(); 10703 } 10704 } 10705 10706 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10707 // Queue up an async operation since the package installation may take a little while. 10708 mHandler.post(new Runnable() { 10709 public void run() { 10710 mHandler.removeCallbacks(this); 10711 // Result object to be returned 10712 PackageInstalledInfo res = new PackageInstalledInfo(); 10713 res.returnCode = currentStatus; 10714 res.uid = -1; 10715 res.pkg = null; 10716 res.removedInfo = new PackageRemovedInfo(); 10717 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10718 args.doPreInstall(res.returnCode); 10719 synchronized (mInstallLock) { 10720 installPackageTracedLI(args, res); 10721 } 10722 args.doPostInstall(res.returnCode, res.uid); 10723 } 10724 10725 // A restore should be performed at this point if (a) the install 10726 // succeeded, (b) the operation is not an update, and (c) the new 10727 // package has not opted out of backup participation. 10728 final boolean update = res.removedInfo.removedPackage != null; 10729 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10730 boolean doRestore = !update 10731 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10732 10733 // Set up the post-install work request bookkeeping. This will be used 10734 // and cleaned up by the post-install event handling regardless of whether 10735 // there's a restore pass performed. Token values are >= 1. 10736 int token; 10737 if (mNextInstallToken < 0) mNextInstallToken = 1; 10738 token = mNextInstallToken++; 10739 10740 PostInstallData data = new PostInstallData(args, res); 10741 mRunningInstalls.put(token, data); 10742 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10743 10744 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10745 // Pass responsibility to the Backup Manager. It will perform a 10746 // restore if appropriate, then pass responsibility back to the 10747 // Package Manager to run the post-install observer callbacks 10748 // and broadcasts. 10749 IBackupManager bm = IBackupManager.Stub.asInterface( 10750 ServiceManager.getService(Context.BACKUP_SERVICE)); 10751 if (bm != null) { 10752 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10753 + " to BM for possible restore"); 10754 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10755 try { 10756 // TODO: http://b/22388012 10757 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10758 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10759 } else { 10760 doRestore = false; 10761 } 10762 } catch (RemoteException e) { 10763 // can't happen; the backup manager is local 10764 } catch (Exception e) { 10765 Slog.e(TAG, "Exception trying to enqueue restore", e); 10766 doRestore = false; 10767 } 10768 } else { 10769 Slog.e(TAG, "Backup Manager not found!"); 10770 doRestore = false; 10771 } 10772 } 10773 10774 if (!doRestore) { 10775 // No restore possible, or the Backup Manager was mysteriously not 10776 // available -- just fire the post-install work request directly. 10777 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10778 10779 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10780 10781 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10782 mHandler.sendMessage(msg); 10783 } 10784 } 10785 }); 10786 } 10787 10788 private abstract class HandlerParams { 10789 private static final int MAX_RETRIES = 4; 10790 10791 /** 10792 * Number of times startCopy() has been attempted and had a non-fatal 10793 * error. 10794 */ 10795 private int mRetries = 0; 10796 10797 /** User handle for the user requesting the information or installation. */ 10798 private final UserHandle mUser; 10799 String traceMethod; 10800 int traceCookie; 10801 10802 HandlerParams(UserHandle user) { 10803 mUser = user; 10804 } 10805 10806 UserHandle getUser() { 10807 return mUser; 10808 } 10809 10810 HandlerParams setTraceMethod(String traceMethod) { 10811 this.traceMethod = traceMethod; 10812 return this; 10813 } 10814 10815 HandlerParams setTraceCookie(int traceCookie) { 10816 this.traceCookie = traceCookie; 10817 return this; 10818 } 10819 10820 final boolean startCopy() { 10821 boolean res; 10822 try { 10823 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10824 10825 if (++mRetries > MAX_RETRIES) { 10826 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10827 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10828 handleServiceError(); 10829 return false; 10830 } else { 10831 handleStartCopy(); 10832 res = true; 10833 } 10834 } catch (RemoteException e) { 10835 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10836 mHandler.sendEmptyMessage(MCS_RECONNECT); 10837 res = false; 10838 } 10839 handleReturnCode(); 10840 return res; 10841 } 10842 10843 final void serviceError() { 10844 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10845 handleServiceError(); 10846 handleReturnCode(); 10847 } 10848 10849 abstract void handleStartCopy() throws RemoteException; 10850 abstract void handleServiceError(); 10851 abstract void handleReturnCode(); 10852 } 10853 10854 class MeasureParams extends HandlerParams { 10855 private final PackageStats mStats; 10856 private boolean mSuccess; 10857 10858 private final IPackageStatsObserver mObserver; 10859 10860 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10861 super(new UserHandle(stats.userHandle)); 10862 mObserver = observer; 10863 mStats = stats; 10864 } 10865 10866 @Override 10867 public String toString() { 10868 return "MeasureParams{" 10869 + Integer.toHexString(System.identityHashCode(this)) 10870 + " " + mStats.packageName + "}"; 10871 } 10872 10873 @Override 10874 void handleStartCopy() throws RemoteException { 10875 synchronized (mInstallLock) { 10876 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10877 } 10878 10879 if (mSuccess) { 10880 final boolean mounted; 10881 if (Environment.isExternalStorageEmulated()) { 10882 mounted = true; 10883 } else { 10884 final String status = Environment.getExternalStorageState(); 10885 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10886 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10887 } 10888 10889 if (mounted) { 10890 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10891 10892 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10893 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10894 10895 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10896 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10897 10898 // Always subtract cache size, since it's a subdirectory 10899 mStats.externalDataSize -= mStats.externalCacheSize; 10900 10901 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10902 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10903 10904 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10905 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10906 } 10907 } 10908 } 10909 10910 @Override 10911 void handleReturnCode() { 10912 if (mObserver != null) { 10913 try { 10914 mObserver.onGetStatsCompleted(mStats, mSuccess); 10915 } catch (RemoteException e) { 10916 Slog.i(TAG, "Observer no longer exists."); 10917 } 10918 } 10919 } 10920 10921 @Override 10922 void handleServiceError() { 10923 Slog.e(TAG, "Could not measure application " + mStats.packageName 10924 + " external storage"); 10925 } 10926 } 10927 10928 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10929 throws RemoteException { 10930 long result = 0; 10931 for (File path : paths) { 10932 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10933 } 10934 return result; 10935 } 10936 10937 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10938 for (File path : paths) { 10939 try { 10940 mcs.clearDirectory(path.getAbsolutePath()); 10941 } catch (RemoteException e) { 10942 } 10943 } 10944 } 10945 10946 static class OriginInfo { 10947 /** 10948 * Location where install is coming from, before it has been 10949 * copied/renamed into place. This could be a single monolithic APK 10950 * file, or a cluster directory. This location may be untrusted. 10951 */ 10952 final File file; 10953 final String cid; 10954 10955 /** 10956 * Flag indicating that {@link #file} or {@link #cid} has already been 10957 * staged, meaning downstream users don't need to defensively copy the 10958 * contents. 10959 */ 10960 final boolean staged; 10961 10962 /** 10963 * Flag indicating that {@link #file} or {@link #cid} is an already 10964 * installed app that is being moved. 10965 */ 10966 final boolean existing; 10967 10968 final String resolvedPath; 10969 final File resolvedFile; 10970 10971 static OriginInfo fromNothing() { 10972 return new OriginInfo(null, null, false, false); 10973 } 10974 10975 static OriginInfo fromUntrustedFile(File file) { 10976 return new OriginInfo(file, null, false, false); 10977 } 10978 10979 static OriginInfo fromExistingFile(File file) { 10980 return new OriginInfo(file, null, false, true); 10981 } 10982 10983 static OriginInfo fromStagedFile(File file) { 10984 return new OriginInfo(file, null, true, false); 10985 } 10986 10987 static OriginInfo fromStagedContainer(String cid) { 10988 return new OriginInfo(null, cid, true, false); 10989 } 10990 10991 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10992 this.file = file; 10993 this.cid = cid; 10994 this.staged = staged; 10995 this.existing = existing; 10996 10997 if (cid != null) { 10998 resolvedPath = PackageHelper.getSdDir(cid); 10999 resolvedFile = new File(resolvedPath); 11000 } else if (file != null) { 11001 resolvedPath = file.getAbsolutePath(); 11002 resolvedFile = file; 11003 } else { 11004 resolvedPath = null; 11005 resolvedFile = null; 11006 } 11007 } 11008 } 11009 11010 static class MoveInfo { 11011 final int moveId; 11012 final String fromUuid; 11013 final String toUuid; 11014 final String packageName; 11015 final String dataAppName; 11016 final int appId; 11017 final String seinfo; 11018 11019 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11020 String dataAppName, int appId, String seinfo) { 11021 this.moveId = moveId; 11022 this.fromUuid = fromUuid; 11023 this.toUuid = toUuid; 11024 this.packageName = packageName; 11025 this.dataAppName = dataAppName; 11026 this.appId = appId; 11027 this.seinfo = seinfo; 11028 } 11029 } 11030 11031 class InstallParams extends HandlerParams { 11032 final OriginInfo origin; 11033 final MoveInfo move; 11034 final IPackageInstallObserver2 observer; 11035 int installFlags; 11036 final String installerPackageName; 11037 final String volumeUuid; 11038 final VerificationParams verificationParams; 11039 private InstallArgs mArgs; 11040 private int mRet; 11041 final String packageAbiOverride; 11042 final String[] grantedRuntimePermissions; 11043 11044 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11045 int installFlags, String installerPackageName, String volumeUuid, 11046 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 11047 String[] grantedPermissions) { 11048 super(user); 11049 this.origin = origin; 11050 this.move = move; 11051 this.observer = observer; 11052 this.installFlags = installFlags; 11053 this.installerPackageName = installerPackageName; 11054 this.volumeUuid = volumeUuid; 11055 this.verificationParams = verificationParams; 11056 this.packageAbiOverride = packageAbiOverride; 11057 this.grantedRuntimePermissions = grantedPermissions; 11058 } 11059 11060 @Override 11061 public String toString() { 11062 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11063 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11064 } 11065 11066 public ManifestDigest getManifestDigest() { 11067 if (verificationParams == null) { 11068 return null; 11069 } 11070 return verificationParams.getManifestDigest(); 11071 } 11072 11073 private int installLocationPolicy(PackageInfoLite pkgLite) { 11074 String packageName = pkgLite.packageName; 11075 int installLocation = pkgLite.installLocation; 11076 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11077 // reader 11078 synchronized (mPackages) { 11079 PackageParser.Package pkg = mPackages.get(packageName); 11080 if (pkg != null) { 11081 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11082 // Check for downgrading. 11083 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11084 try { 11085 checkDowngrade(pkg, pkgLite); 11086 } catch (PackageManagerException e) { 11087 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11088 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11089 } 11090 } 11091 // Check for updated system application. 11092 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11093 if (onSd) { 11094 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11095 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11096 } 11097 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11098 } else { 11099 if (onSd) { 11100 // Install flag overrides everything. 11101 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11102 } 11103 // If current upgrade specifies particular preference 11104 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11105 // Application explicitly specified internal. 11106 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11107 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11108 // App explictly prefers external. Let policy decide 11109 } else { 11110 // Prefer previous location 11111 if (isExternal(pkg)) { 11112 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11113 } 11114 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11115 } 11116 } 11117 } else { 11118 // Invalid install. Return error code 11119 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11120 } 11121 } 11122 } 11123 // All the special cases have been taken care of. 11124 // Return result based on recommended install location. 11125 if (onSd) { 11126 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11127 } 11128 return pkgLite.recommendedInstallLocation; 11129 } 11130 11131 /* 11132 * Invoke remote method to get package information and install 11133 * location values. Override install location based on default 11134 * policy if needed and then create install arguments based 11135 * on the install location. 11136 */ 11137 public void handleStartCopy() throws RemoteException { 11138 int ret = PackageManager.INSTALL_SUCCEEDED; 11139 11140 // If we're already staged, we've firmly committed to an install location 11141 if (origin.staged) { 11142 if (origin.file != null) { 11143 installFlags |= PackageManager.INSTALL_INTERNAL; 11144 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11145 } else if (origin.cid != null) { 11146 installFlags |= PackageManager.INSTALL_EXTERNAL; 11147 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11148 } else { 11149 throw new IllegalStateException("Invalid stage location"); 11150 } 11151 } 11152 11153 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11154 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11155 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11156 PackageInfoLite pkgLite = null; 11157 11158 if (onInt && onSd) { 11159 // Check if both bits are set. 11160 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11161 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11162 } else if (onSd && ephemeral) { 11163 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11164 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11165 } else { 11166 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11167 packageAbiOverride); 11168 11169 if (DEBUG_EPHEMERAL && ephemeral) { 11170 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11171 } 11172 11173 /* 11174 * If we have too little free space, try to free cache 11175 * before giving up. 11176 */ 11177 if (!origin.staged && pkgLite.recommendedInstallLocation 11178 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11179 // TODO: focus freeing disk space on the target device 11180 final StorageManager storage = StorageManager.from(mContext); 11181 final long lowThreshold = storage.getStorageLowBytes( 11182 Environment.getDataDirectory()); 11183 11184 final long sizeBytes = mContainerService.calculateInstalledSize( 11185 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11186 11187 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 11188 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11189 installFlags, packageAbiOverride); 11190 } 11191 11192 /* 11193 * The cache free must have deleted the file we 11194 * downloaded to install. 11195 * 11196 * TODO: fix the "freeCache" call to not delete 11197 * the file we care about. 11198 */ 11199 if (pkgLite.recommendedInstallLocation 11200 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11201 pkgLite.recommendedInstallLocation 11202 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11203 } 11204 } 11205 } 11206 11207 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11208 int loc = pkgLite.recommendedInstallLocation; 11209 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11210 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11211 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11212 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11213 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11214 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11215 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11216 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11217 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11218 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11219 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11220 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11221 } else { 11222 // Override with defaults if needed. 11223 loc = installLocationPolicy(pkgLite); 11224 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11225 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11226 } else if (!onSd && !onInt) { 11227 // Override install location with flags 11228 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11229 // Set the flag to install on external media. 11230 installFlags |= PackageManager.INSTALL_EXTERNAL; 11231 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11232 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11233 if (DEBUG_EPHEMERAL) { 11234 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11235 } 11236 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11237 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11238 |PackageManager.INSTALL_INTERNAL); 11239 } else { 11240 // Make sure the flag for installing on external 11241 // media is unset 11242 installFlags |= PackageManager.INSTALL_INTERNAL; 11243 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11244 } 11245 } 11246 } 11247 } 11248 11249 final InstallArgs args = createInstallArgs(this); 11250 mArgs = args; 11251 11252 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11253 // TODO: http://b/22976637 11254 // Apps installed for "all" users use the device owner to verify the app 11255 UserHandle verifierUser = getUser(); 11256 if (verifierUser == UserHandle.ALL) { 11257 verifierUser = UserHandle.SYSTEM; 11258 } 11259 11260 /* 11261 * Determine if we have any installed package verifiers. If we 11262 * do, then we'll defer to them to verify the packages. 11263 */ 11264 final int requiredUid = mRequiredVerifierPackage == null ? -1 11265 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 11266 if (!origin.existing && requiredUid != -1 11267 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11268 final Intent verification = new Intent( 11269 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11270 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11271 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11272 PACKAGE_MIME_TYPE); 11273 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11274 11275 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11276 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 11277 verifierUser.getIdentifier()); 11278 11279 if (DEBUG_VERIFY) { 11280 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11281 + verification.toString() + " with " + pkgLite.verifiers.length 11282 + " optional verifiers"); 11283 } 11284 11285 final int verificationId = mPendingVerificationToken++; 11286 11287 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11288 11289 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11290 installerPackageName); 11291 11292 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11293 installFlags); 11294 11295 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11296 pkgLite.packageName); 11297 11298 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11299 pkgLite.versionCode); 11300 11301 if (verificationParams != null) { 11302 if (verificationParams.getVerificationURI() != null) { 11303 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11304 verificationParams.getVerificationURI()); 11305 } 11306 if (verificationParams.getOriginatingURI() != null) { 11307 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11308 verificationParams.getOriginatingURI()); 11309 } 11310 if (verificationParams.getReferrer() != null) { 11311 verification.putExtra(Intent.EXTRA_REFERRER, 11312 verificationParams.getReferrer()); 11313 } 11314 if (verificationParams.getOriginatingUid() >= 0) { 11315 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11316 verificationParams.getOriginatingUid()); 11317 } 11318 if (verificationParams.getInstallerUid() >= 0) { 11319 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11320 verificationParams.getInstallerUid()); 11321 } 11322 } 11323 11324 final PackageVerificationState verificationState = new PackageVerificationState( 11325 requiredUid, args); 11326 11327 mPendingVerification.append(verificationId, verificationState); 11328 11329 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11330 receivers, verificationState); 11331 11332 /* 11333 * If any sufficient verifiers were listed in the package 11334 * manifest, attempt to ask them. 11335 */ 11336 if (sufficientVerifiers != null) { 11337 final int N = sufficientVerifiers.size(); 11338 if (N == 0) { 11339 Slog.i(TAG, "Additional verifiers required, but none installed."); 11340 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11341 } else { 11342 for (int i = 0; i < N; i++) { 11343 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11344 11345 final Intent sufficientIntent = new Intent(verification); 11346 sufficientIntent.setComponent(verifierComponent); 11347 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11348 } 11349 } 11350 } 11351 11352 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11353 mRequiredVerifierPackage, receivers); 11354 if (ret == PackageManager.INSTALL_SUCCEEDED 11355 && mRequiredVerifierPackage != null) { 11356 Trace.asyncTraceBegin( 11357 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11358 /* 11359 * Send the intent to the required verification agent, 11360 * but only start the verification timeout after the 11361 * target BroadcastReceivers have run. 11362 */ 11363 verification.setComponent(requiredVerifierComponent); 11364 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11365 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11366 new BroadcastReceiver() { 11367 @Override 11368 public void onReceive(Context context, Intent intent) { 11369 final Message msg = mHandler 11370 .obtainMessage(CHECK_PENDING_VERIFICATION); 11371 msg.arg1 = verificationId; 11372 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11373 } 11374 }, null, 0, null, null); 11375 11376 /* 11377 * We don't want the copy to proceed until verification 11378 * succeeds, so null out this field. 11379 */ 11380 mArgs = null; 11381 } 11382 } else { 11383 /* 11384 * No package verification is enabled, so immediately start 11385 * the remote call to initiate copy using temporary file. 11386 */ 11387 ret = args.copyApk(mContainerService, true); 11388 } 11389 } 11390 11391 mRet = ret; 11392 } 11393 11394 @Override 11395 void handleReturnCode() { 11396 // If mArgs is null, then MCS couldn't be reached. When it 11397 // reconnects, it will try again to install. At that point, this 11398 // will succeed. 11399 if (mArgs != null) { 11400 processPendingInstall(mArgs, mRet); 11401 } 11402 } 11403 11404 @Override 11405 void handleServiceError() { 11406 mArgs = createInstallArgs(this); 11407 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11408 } 11409 11410 public boolean isForwardLocked() { 11411 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11412 } 11413 } 11414 11415 /** 11416 * Used during creation of InstallArgs 11417 * 11418 * @param installFlags package installation flags 11419 * @return true if should be installed on external storage 11420 */ 11421 private static boolean installOnExternalAsec(int installFlags) { 11422 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11423 return false; 11424 } 11425 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11426 return true; 11427 } 11428 return false; 11429 } 11430 11431 /** 11432 * Used during creation of InstallArgs 11433 * 11434 * @param installFlags package installation flags 11435 * @return true if should be installed as forward locked 11436 */ 11437 private static boolean installForwardLocked(int installFlags) { 11438 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11439 } 11440 11441 private InstallArgs createInstallArgs(InstallParams params) { 11442 if (params.move != null) { 11443 return new MoveInstallArgs(params); 11444 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11445 return new AsecInstallArgs(params); 11446 } else { 11447 return new FileInstallArgs(params); 11448 } 11449 } 11450 11451 /** 11452 * Create args that describe an existing installed package. Typically used 11453 * when cleaning up old installs, or used as a move source. 11454 */ 11455 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11456 String resourcePath, String[] instructionSets) { 11457 final boolean isInAsec; 11458 if (installOnExternalAsec(installFlags)) { 11459 /* Apps on SD card are always in ASEC containers. */ 11460 isInAsec = true; 11461 } else if (installForwardLocked(installFlags) 11462 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11463 /* 11464 * Forward-locked apps are only in ASEC containers if they're the 11465 * new style 11466 */ 11467 isInAsec = true; 11468 } else { 11469 isInAsec = false; 11470 } 11471 11472 if (isInAsec) { 11473 return new AsecInstallArgs(codePath, instructionSets, 11474 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11475 } else { 11476 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11477 } 11478 } 11479 11480 static abstract class InstallArgs { 11481 /** @see InstallParams#origin */ 11482 final OriginInfo origin; 11483 /** @see InstallParams#move */ 11484 final MoveInfo move; 11485 11486 final IPackageInstallObserver2 observer; 11487 // Always refers to PackageManager flags only 11488 final int installFlags; 11489 final String installerPackageName; 11490 final String volumeUuid; 11491 final ManifestDigest manifestDigest; 11492 final UserHandle user; 11493 final String abiOverride; 11494 final String[] installGrantPermissions; 11495 /** If non-null, drop an async trace when the install completes */ 11496 final String traceMethod; 11497 final int traceCookie; 11498 11499 // The list of instruction sets supported by this app. This is currently 11500 // only used during the rmdex() phase to clean up resources. We can get rid of this 11501 // if we move dex files under the common app path. 11502 /* nullable */ String[] instructionSets; 11503 11504 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11505 int installFlags, String installerPackageName, String volumeUuid, 11506 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11507 String abiOverride, String[] installGrantPermissions, 11508 String traceMethod, int traceCookie) { 11509 this.origin = origin; 11510 this.move = move; 11511 this.installFlags = installFlags; 11512 this.observer = observer; 11513 this.installerPackageName = installerPackageName; 11514 this.volumeUuid = volumeUuid; 11515 this.manifestDigest = manifestDigest; 11516 this.user = user; 11517 this.instructionSets = instructionSets; 11518 this.abiOverride = abiOverride; 11519 this.installGrantPermissions = installGrantPermissions; 11520 this.traceMethod = traceMethod; 11521 this.traceCookie = traceCookie; 11522 } 11523 11524 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11525 abstract int doPreInstall(int status); 11526 11527 /** 11528 * Rename package into final resting place. All paths on the given 11529 * scanned package should be updated to reflect the rename. 11530 */ 11531 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11532 abstract int doPostInstall(int status, int uid); 11533 11534 /** @see PackageSettingBase#codePathString */ 11535 abstract String getCodePath(); 11536 /** @see PackageSettingBase#resourcePathString */ 11537 abstract String getResourcePath(); 11538 11539 // Need installer lock especially for dex file removal. 11540 abstract void cleanUpResourcesLI(); 11541 abstract boolean doPostDeleteLI(boolean delete); 11542 11543 /** 11544 * Called before the source arguments are copied. This is used mostly 11545 * for MoveParams when it needs to read the source file to put it in the 11546 * destination. 11547 */ 11548 int doPreCopy() { 11549 return PackageManager.INSTALL_SUCCEEDED; 11550 } 11551 11552 /** 11553 * Called after the source arguments are copied. This is used mostly for 11554 * MoveParams when it needs to read the source file to put it in the 11555 * destination. 11556 * 11557 * @return 11558 */ 11559 int doPostCopy(int uid) { 11560 return PackageManager.INSTALL_SUCCEEDED; 11561 } 11562 11563 protected boolean isFwdLocked() { 11564 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11565 } 11566 11567 protected boolean isExternalAsec() { 11568 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11569 } 11570 11571 protected boolean isEphemeral() { 11572 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11573 } 11574 11575 UserHandle getUser() { 11576 return user; 11577 } 11578 } 11579 11580 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11581 if (!allCodePaths.isEmpty()) { 11582 if (instructionSets == null) { 11583 throw new IllegalStateException("instructionSet == null"); 11584 } 11585 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11586 for (String codePath : allCodePaths) { 11587 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11588 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11589 if (retCode < 0) { 11590 Slog.w(TAG, "Couldn't remove dex file for package: " 11591 + " at location " + codePath + ", retcode=" + retCode); 11592 // we don't consider this to be a failure of the core package deletion 11593 } 11594 } 11595 } 11596 } 11597 } 11598 11599 /** 11600 * Logic to handle installation of non-ASEC applications, including copying 11601 * and renaming logic. 11602 */ 11603 class FileInstallArgs extends InstallArgs { 11604 private File codeFile; 11605 private File resourceFile; 11606 11607 // Example topology: 11608 // /data/app/com.example/base.apk 11609 // /data/app/com.example/split_foo.apk 11610 // /data/app/com.example/lib/arm/libfoo.so 11611 // /data/app/com.example/lib/arm64/libfoo.so 11612 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11613 11614 /** New install */ 11615 FileInstallArgs(InstallParams params) { 11616 super(params.origin, params.move, params.observer, params.installFlags, 11617 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11618 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11619 params.grantedRuntimePermissions, 11620 params.traceMethod, params.traceCookie); 11621 if (isFwdLocked()) { 11622 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11623 } 11624 } 11625 11626 /** Existing install */ 11627 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11628 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11629 null, null, null, 0); 11630 this.codeFile = (codePath != null) ? new File(codePath) : null; 11631 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11632 } 11633 11634 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11635 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11636 try { 11637 return doCopyApk(imcs, temp); 11638 } finally { 11639 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11640 } 11641 } 11642 11643 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11644 if (origin.staged) { 11645 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11646 codeFile = origin.file; 11647 resourceFile = origin.file; 11648 return PackageManager.INSTALL_SUCCEEDED; 11649 } 11650 11651 try { 11652 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11653 final File tempDir = 11654 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11655 codeFile = tempDir; 11656 resourceFile = tempDir; 11657 } catch (IOException e) { 11658 Slog.w(TAG, "Failed to create copy file: " + e); 11659 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11660 } 11661 11662 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11663 @Override 11664 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11665 if (!FileUtils.isValidExtFilename(name)) { 11666 throw new IllegalArgumentException("Invalid filename: " + name); 11667 } 11668 try { 11669 final File file = new File(codeFile, name); 11670 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11671 O_RDWR | O_CREAT, 0644); 11672 Os.chmod(file.getAbsolutePath(), 0644); 11673 return new ParcelFileDescriptor(fd); 11674 } catch (ErrnoException e) { 11675 throw new RemoteException("Failed to open: " + e.getMessage()); 11676 } 11677 } 11678 }; 11679 11680 int ret = PackageManager.INSTALL_SUCCEEDED; 11681 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11682 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11683 Slog.e(TAG, "Failed to copy package"); 11684 return ret; 11685 } 11686 11687 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11688 NativeLibraryHelper.Handle handle = null; 11689 try { 11690 handle = NativeLibraryHelper.Handle.create(codeFile); 11691 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11692 abiOverride); 11693 } catch (IOException e) { 11694 Slog.e(TAG, "Copying native libraries failed", e); 11695 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11696 } finally { 11697 IoUtils.closeQuietly(handle); 11698 } 11699 11700 return ret; 11701 } 11702 11703 int doPreInstall(int status) { 11704 if (status != PackageManager.INSTALL_SUCCEEDED) { 11705 cleanUp(); 11706 } 11707 return status; 11708 } 11709 11710 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11711 if (status != PackageManager.INSTALL_SUCCEEDED) { 11712 cleanUp(); 11713 return false; 11714 } 11715 11716 final File targetDir = codeFile.getParentFile(); 11717 final File beforeCodeFile = codeFile; 11718 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11719 11720 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11721 try { 11722 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11723 } catch (ErrnoException e) { 11724 Slog.w(TAG, "Failed to rename", e); 11725 return false; 11726 } 11727 11728 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11729 Slog.w(TAG, "Failed to restorecon"); 11730 return false; 11731 } 11732 11733 // Reflect the rename internally 11734 codeFile = afterCodeFile; 11735 resourceFile = afterCodeFile; 11736 11737 // Reflect the rename in scanned details 11738 pkg.codePath = afterCodeFile.getAbsolutePath(); 11739 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11740 pkg.baseCodePath); 11741 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11742 pkg.splitCodePaths); 11743 11744 // Reflect the rename in app info 11745 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11746 pkg.applicationInfo.setCodePath(pkg.codePath); 11747 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11748 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11749 pkg.applicationInfo.setResourcePath(pkg.codePath); 11750 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11751 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11752 11753 return true; 11754 } 11755 11756 int doPostInstall(int status, int uid) { 11757 if (status != PackageManager.INSTALL_SUCCEEDED) { 11758 cleanUp(); 11759 } 11760 return status; 11761 } 11762 11763 @Override 11764 String getCodePath() { 11765 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11766 } 11767 11768 @Override 11769 String getResourcePath() { 11770 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11771 } 11772 11773 private boolean cleanUp() { 11774 if (codeFile == null || !codeFile.exists()) { 11775 return false; 11776 } 11777 11778 if (codeFile.isDirectory()) { 11779 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11780 } else { 11781 codeFile.delete(); 11782 } 11783 11784 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11785 resourceFile.delete(); 11786 } 11787 11788 return true; 11789 } 11790 11791 void cleanUpResourcesLI() { 11792 // Try enumerating all code paths before deleting 11793 List<String> allCodePaths = Collections.EMPTY_LIST; 11794 if (codeFile != null && codeFile.exists()) { 11795 try { 11796 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11797 allCodePaths = pkg.getAllCodePaths(); 11798 } catch (PackageParserException e) { 11799 // Ignored; we tried our best 11800 } 11801 } 11802 11803 cleanUp(); 11804 removeDexFiles(allCodePaths, instructionSets); 11805 } 11806 11807 boolean doPostDeleteLI(boolean delete) { 11808 // XXX err, shouldn't we respect the delete flag? 11809 cleanUpResourcesLI(); 11810 return true; 11811 } 11812 } 11813 11814 private boolean isAsecExternal(String cid) { 11815 final String asecPath = PackageHelper.getSdFilesystem(cid); 11816 return !asecPath.startsWith(mAsecInternalPath); 11817 } 11818 11819 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11820 PackageManagerException { 11821 if (copyRet < 0) { 11822 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11823 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11824 throw new PackageManagerException(copyRet, message); 11825 } 11826 } 11827 } 11828 11829 /** 11830 * Extract the MountService "container ID" from the full code path of an 11831 * .apk. 11832 */ 11833 static String cidFromCodePath(String fullCodePath) { 11834 int eidx = fullCodePath.lastIndexOf("/"); 11835 String subStr1 = fullCodePath.substring(0, eidx); 11836 int sidx = subStr1.lastIndexOf("/"); 11837 return subStr1.substring(sidx+1, eidx); 11838 } 11839 11840 /** 11841 * Logic to handle installation of ASEC applications, including copying and 11842 * renaming logic. 11843 */ 11844 class AsecInstallArgs extends InstallArgs { 11845 static final String RES_FILE_NAME = "pkg.apk"; 11846 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11847 11848 String cid; 11849 String packagePath; 11850 String resourcePath; 11851 11852 /** New install */ 11853 AsecInstallArgs(InstallParams params) { 11854 super(params.origin, params.move, params.observer, params.installFlags, 11855 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11856 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11857 params.grantedRuntimePermissions, 11858 params.traceMethod, params.traceCookie); 11859 } 11860 11861 /** Existing install */ 11862 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11863 boolean isExternal, boolean isForwardLocked) { 11864 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11865 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11866 instructionSets, null, null, null, 0); 11867 // Hackily pretend we're still looking at a full code path 11868 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11869 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11870 } 11871 11872 // Extract cid from fullCodePath 11873 int eidx = fullCodePath.lastIndexOf("/"); 11874 String subStr1 = fullCodePath.substring(0, eidx); 11875 int sidx = subStr1.lastIndexOf("/"); 11876 cid = subStr1.substring(sidx+1, eidx); 11877 setMountPath(subStr1); 11878 } 11879 11880 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11881 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11882 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11883 instructionSets, null, null, null, 0); 11884 this.cid = cid; 11885 setMountPath(PackageHelper.getSdDir(cid)); 11886 } 11887 11888 void createCopyFile() { 11889 cid = mInstallerService.allocateExternalStageCidLegacy(); 11890 } 11891 11892 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11893 if (origin.staged && origin.cid != null) { 11894 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11895 cid = origin.cid; 11896 setMountPath(PackageHelper.getSdDir(cid)); 11897 return PackageManager.INSTALL_SUCCEEDED; 11898 } 11899 11900 if (temp) { 11901 createCopyFile(); 11902 } else { 11903 /* 11904 * Pre-emptively destroy the container since it's destroyed if 11905 * copying fails due to it existing anyway. 11906 */ 11907 PackageHelper.destroySdDir(cid); 11908 } 11909 11910 final String newMountPath = imcs.copyPackageToContainer( 11911 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11912 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11913 11914 if (newMountPath != null) { 11915 setMountPath(newMountPath); 11916 return PackageManager.INSTALL_SUCCEEDED; 11917 } else { 11918 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11919 } 11920 } 11921 11922 @Override 11923 String getCodePath() { 11924 return packagePath; 11925 } 11926 11927 @Override 11928 String getResourcePath() { 11929 return resourcePath; 11930 } 11931 11932 int doPreInstall(int status) { 11933 if (status != PackageManager.INSTALL_SUCCEEDED) { 11934 // Destroy container 11935 PackageHelper.destroySdDir(cid); 11936 } else { 11937 boolean mounted = PackageHelper.isContainerMounted(cid); 11938 if (!mounted) { 11939 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11940 Process.SYSTEM_UID); 11941 if (newMountPath != null) { 11942 setMountPath(newMountPath); 11943 } else { 11944 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11945 } 11946 } 11947 } 11948 return status; 11949 } 11950 11951 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11952 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11953 String newMountPath = null; 11954 if (PackageHelper.isContainerMounted(cid)) { 11955 // Unmount the container 11956 if (!PackageHelper.unMountSdDir(cid)) { 11957 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11958 return false; 11959 } 11960 } 11961 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11962 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11963 " which might be stale. Will try to clean up."); 11964 // Clean up the stale container and proceed to recreate. 11965 if (!PackageHelper.destroySdDir(newCacheId)) { 11966 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11967 return false; 11968 } 11969 // Successfully cleaned up stale container. Try to rename again. 11970 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11971 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11972 + " inspite of cleaning it up."); 11973 return false; 11974 } 11975 } 11976 if (!PackageHelper.isContainerMounted(newCacheId)) { 11977 Slog.w(TAG, "Mounting container " + newCacheId); 11978 newMountPath = PackageHelper.mountSdDir(newCacheId, 11979 getEncryptKey(), Process.SYSTEM_UID); 11980 } else { 11981 newMountPath = PackageHelper.getSdDir(newCacheId); 11982 } 11983 if (newMountPath == null) { 11984 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11985 return false; 11986 } 11987 Log.i(TAG, "Succesfully renamed " + cid + 11988 " to " + newCacheId + 11989 " at new path: " + newMountPath); 11990 cid = newCacheId; 11991 11992 final File beforeCodeFile = new File(packagePath); 11993 setMountPath(newMountPath); 11994 final File afterCodeFile = new File(packagePath); 11995 11996 // Reflect the rename in scanned details 11997 pkg.codePath = afterCodeFile.getAbsolutePath(); 11998 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11999 pkg.baseCodePath); 12000 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 12001 pkg.splitCodePaths); 12002 12003 // Reflect the rename in app info 12004 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12005 pkg.applicationInfo.setCodePath(pkg.codePath); 12006 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12007 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12008 pkg.applicationInfo.setResourcePath(pkg.codePath); 12009 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12010 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12011 12012 return true; 12013 } 12014 12015 private void setMountPath(String mountPath) { 12016 final File mountFile = new File(mountPath); 12017 12018 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12019 if (monolithicFile.exists()) { 12020 packagePath = monolithicFile.getAbsolutePath(); 12021 if (isFwdLocked()) { 12022 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12023 } else { 12024 resourcePath = packagePath; 12025 } 12026 } else { 12027 packagePath = mountFile.getAbsolutePath(); 12028 resourcePath = packagePath; 12029 } 12030 } 12031 12032 int doPostInstall(int status, int uid) { 12033 if (status != PackageManager.INSTALL_SUCCEEDED) { 12034 cleanUp(); 12035 } else { 12036 final int groupOwner; 12037 final String protectedFile; 12038 if (isFwdLocked()) { 12039 groupOwner = UserHandle.getSharedAppGid(uid); 12040 protectedFile = RES_FILE_NAME; 12041 } else { 12042 groupOwner = -1; 12043 protectedFile = null; 12044 } 12045 12046 if (uid < Process.FIRST_APPLICATION_UID 12047 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12048 Slog.e(TAG, "Failed to finalize " + cid); 12049 PackageHelper.destroySdDir(cid); 12050 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12051 } 12052 12053 boolean mounted = PackageHelper.isContainerMounted(cid); 12054 if (!mounted) { 12055 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12056 } 12057 } 12058 return status; 12059 } 12060 12061 private void cleanUp() { 12062 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12063 12064 // Destroy secure container 12065 PackageHelper.destroySdDir(cid); 12066 } 12067 12068 private List<String> getAllCodePaths() { 12069 final File codeFile = new File(getCodePath()); 12070 if (codeFile != null && codeFile.exists()) { 12071 try { 12072 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12073 return pkg.getAllCodePaths(); 12074 } catch (PackageParserException e) { 12075 // Ignored; we tried our best 12076 } 12077 } 12078 return Collections.EMPTY_LIST; 12079 } 12080 12081 void cleanUpResourcesLI() { 12082 // Enumerate all code paths before deleting 12083 cleanUpResourcesLI(getAllCodePaths()); 12084 } 12085 12086 private void cleanUpResourcesLI(List<String> allCodePaths) { 12087 cleanUp(); 12088 removeDexFiles(allCodePaths, instructionSets); 12089 } 12090 12091 String getPackageName() { 12092 return getAsecPackageName(cid); 12093 } 12094 12095 boolean doPostDeleteLI(boolean delete) { 12096 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12097 final List<String> allCodePaths = getAllCodePaths(); 12098 boolean mounted = PackageHelper.isContainerMounted(cid); 12099 if (mounted) { 12100 // Unmount first 12101 if (PackageHelper.unMountSdDir(cid)) { 12102 mounted = false; 12103 } 12104 } 12105 if (!mounted && delete) { 12106 cleanUpResourcesLI(allCodePaths); 12107 } 12108 return !mounted; 12109 } 12110 12111 @Override 12112 int doPreCopy() { 12113 if (isFwdLocked()) { 12114 if (!PackageHelper.fixSdPermissions(cid, 12115 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 12116 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12117 } 12118 } 12119 12120 return PackageManager.INSTALL_SUCCEEDED; 12121 } 12122 12123 @Override 12124 int doPostCopy(int uid) { 12125 if (isFwdLocked()) { 12126 if (uid < Process.FIRST_APPLICATION_UID 12127 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12128 RES_FILE_NAME)) { 12129 Slog.e(TAG, "Failed to finalize " + cid); 12130 PackageHelper.destroySdDir(cid); 12131 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12132 } 12133 } 12134 12135 return PackageManager.INSTALL_SUCCEEDED; 12136 } 12137 } 12138 12139 /** 12140 * Logic to handle movement of existing installed applications. 12141 */ 12142 class MoveInstallArgs extends InstallArgs { 12143 private File codeFile; 12144 private File resourceFile; 12145 12146 /** New install */ 12147 MoveInstallArgs(InstallParams params) { 12148 super(params.origin, params.move, params.observer, params.installFlags, 12149 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 12150 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12151 params.grantedRuntimePermissions, 12152 params.traceMethod, params.traceCookie); 12153 } 12154 12155 int copyApk(IMediaContainerService imcs, boolean temp) { 12156 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12157 + move.fromUuid + " to " + move.toUuid); 12158 synchronized (mInstaller) { 12159 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12160 move.dataAppName, move.appId, move.seinfo) != 0) { 12161 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12162 } 12163 } 12164 12165 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12166 resourceFile = codeFile; 12167 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12168 12169 return PackageManager.INSTALL_SUCCEEDED; 12170 } 12171 12172 int doPreInstall(int status) { 12173 if (status != PackageManager.INSTALL_SUCCEEDED) { 12174 cleanUp(move.toUuid); 12175 } 12176 return status; 12177 } 12178 12179 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12180 if (status != PackageManager.INSTALL_SUCCEEDED) { 12181 cleanUp(move.toUuid); 12182 return false; 12183 } 12184 12185 // Reflect the move in app info 12186 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12187 pkg.applicationInfo.setCodePath(pkg.codePath); 12188 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12189 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12190 pkg.applicationInfo.setResourcePath(pkg.codePath); 12191 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12192 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12193 12194 return true; 12195 } 12196 12197 int doPostInstall(int status, int uid) { 12198 if (status == PackageManager.INSTALL_SUCCEEDED) { 12199 cleanUp(move.fromUuid); 12200 } else { 12201 cleanUp(move.toUuid); 12202 } 12203 return status; 12204 } 12205 12206 @Override 12207 String getCodePath() { 12208 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12209 } 12210 12211 @Override 12212 String getResourcePath() { 12213 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12214 } 12215 12216 private boolean cleanUp(String volumeUuid) { 12217 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12218 move.dataAppName); 12219 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12220 synchronized (mInstallLock) { 12221 // Clean up both app data and code 12222 removeDataDirsLI(volumeUuid, move.packageName); 12223 if (codeFile.isDirectory()) { 12224 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 12225 } else { 12226 codeFile.delete(); 12227 } 12228 } 12229 return true; 12230 } 12231 12232 void cleanUpResourcesLI() { 12233 throw new UnsupportedOperationException(); 12234 } 12235 12236 boolean doPostDeleteLI(boolean delete) { 12237 throw new UnsupportedOperationException(); 12238 } 12239 } 12240 12241 static String getAsecPackageName(String packageCid) { 12242 int idx = packageCid.lastIndexOf("-"); 12243 if (idx == -1) { 12244 return packageCid; 12245 } 12246 return packageCid.substring(0, idx); 12247 } 12248 12249 // Utility method used to create code paths based on package name and available index. 12250 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12251 String idxStr = ""; 12252 int idx = 1; 12253 // Fall back to default value of idx=1 if prefix is not 12254 // part of oldCodePath 12255 if (oldCodePath != null) { 12256 String subStr = oldCodePath; 12257 // Drop the suffix right away 12258 if (suffix != null && subStr.endsWith(suffix)) { 12259 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12260 } 12261 // If oldCodePath already contains prefix find out the 12262 // ending index to either increment or decrement. 12263 int sidx = subStr.lastIndexOf(prefix); 12264 if (sidx != -1) { 12265 subStr = subStr.substring(sidx + prefix.length()); 12266 if (subStr != null) { 12267 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12268 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12269 } 12270 try { 12271 idx = Integer.parseInt(subStr); 12272 if (idx <= 1) { 12273 idx++; 12274 } else { 12275 idx--; 12276 } 12277 } catch(NumberFormatException e) { 12278 } 12279 } 12280 } 12281 } 12282 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12283 return prefix + idxStr; 12284 } 12285 12286 private File getNextCodePath(File targetDir, String packageName) { 12287 int suffix = 1; 12288 File result; 12289 do { 12290 result = new File(targetDir, packageName + "-" + suffix); 12291 suffix++; 12292 } while (result.exists()); 12293 return result; 12294 } 12295 12296 // Utility method that returns the relative package path with respect 12297 // to the installation directory. Like say for /data/data/com.test-1.apk 12298 // string com.test-1 is returned. 12299 static String deriveCodePathName(String codePath) { 12300 if (codePath == null) { 12301 return null; 12302 } 12303 final File codeFile = new File(codePath); 12304 final String name = codeFile.getName(); 12305 if (codeFile.isDirectory()) { 12306 return name; 12307 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12308 final int lastDot = name.lastIndexOf('.'); 12309 return name.substring(0, lastDot); 12310 } else { 12311 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12312 return null; 12313 } 12314 } 12315 12316 static class PackageInstalledInfo { 12317 String name; 12318 int uid; 12319 // The set of users that originally had this package installed. 12320 int[] origUsers; 12321 // The set of users that now have this package installed. 12322 int[] newUsers; 12323 PackageParser.Package pkg; 12324 int returnCode; 12325 String returnMsg; 12326 PackageRemovedInfo removedInfo; 12327 12328 public void setError(int code, String msg) { 12329 returnCode = code; 12330 returnMsg = msg; 12331 Slog.w(TAG, msg); 12332 } 12333 12334 public void setError(String msg, PackageParserException e) { 12335 returnCode = e.error; 12336 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12337 Slog.w(TAG, msg, e); 12338 } 12339 12340 public void setError(String msg, PackageManagerException e) { 12341 returnCode = e.error; 12342 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12343 Slog.w(TAG, msg, e); 12344 } 12345 12346 // In some error cases we want to convey more info back to the observer 12347 String origPackage; 12348 String origPermission; 12349 } 12350 12351 /* 12352 * Install a non-existing package. 12353 */ 12354 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12355 UserHandle user, String installerPackageName, String volumeUuid, 12356 PackageInstalledInfo res) { 12357 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12358 12359 // Remember this for later, in case we need to rollback this install 12360 String pkgName = pkg.packageName; 12361 12362 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12363 // TODO: b/23350563 12364 final boolean dataDirExists = Environment 12365 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12366 12367 synchronized(mPackages) { 12368 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12369 // A package with the same name is already installed, though 12370 // it has been renamed to an older name. The package we 12371 // are trying to install should be installed as an update to 12372 // the existing one, but that has not been requested, so bail. 12373 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12374 + " without first uninstalling package running as " 12375 + mSettings.mRenamedPackages.get(pkgName)); 12376 return; 12377 } 12378 if (mPackages.containsKey(pkgName)) { 12379 // Don't allow installation over an existing package with the same name. 12380 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12381 + " without first uninstalling."); 12382 return; 12383 } 12384 } 12385 12386 try { 12387 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12388 System.currentTimeMillis(), user); 12389 12390 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12391 // delete the partially installed application. the data directory will have to be 12392 // restored if it was already existing 12393 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12394 // remove package from internal structures. Note that we want deletePackageX to 12395 // delete the package data and cache directories that it created in 12396 // scanPackageLocked, unless those directories existed before we even tried to 12397 // install. 12398 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12399 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12400 res.removedInfo, true); 12401 } 12402 12403 } catch (PackageManagerException e) { 12404 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12405 } 12406 12407 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12408 } 12409 12410 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12411 // Can't rotate keys during boot or if sharedUser. 12412 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12413 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12414 return false; 12415 } 12416 // app is using upgradeKeySets; make sure all are valid 12417 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12418 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12419 for (int i = 0; i < upgradeKeySets.length; i++) { 12420 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12421 Slog.wtf(TAG, "Package " 12422 + (oldPs.name != null ? oldPs.name : "<null>") 12423 + " contains upgrade-key-set reference to unknown key-set: " 12424 + upgradeKeySets[i] 12425 + " reverting to signatures check."); 12426 return false; 12427 } 12428 } 12429 return true; 12430 } 12431 12432 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12433 // Upgrade keysets are being used. Determine if new package has a superset of the 12434 // required keys. 12435 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12436 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12437 for (int i = 0; i < upgradeKeySets.length; i++) { 12438 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12439 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12440 return true; 12441 } 12442 } 12443 return false; 12444 } 12445 12446 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12447 UserHandle user, String installerPackageName, String volumeUuid, 12448 PackageInstalledInfo res) { 12449 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12450 12451 final PackageParser.Package oldPackage; 12452 final String pkgName = pkg.packageName; 12453 final int[] allUsers; 12454 final boolean[] perUserInstalled; 12455 12456 // First find the old package info and check signatures 12457 synchronized(mPackages) { 12458 oldPackage = mPackages.get(pkgName); 12459 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12460 if (isEphemeral && !oldIsEphemeral) { 12461 // can't downgrade from full to ephemeral 12462 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12463 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12464 return; 12465 } 12466 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12467 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12468 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12469 if(!checkUpgradeKeySetLP(ps, pkg)) { 12470 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12471 "New package not signed by keys specified by upgrade-keysets: " 12472 + pkgName); 12473 return; 12474 } 12475 } else { 12476 // default to original signature matching 12477 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12478 != PackageManager.SIGNATURE_MATCH) { 12479 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12480 "New package has a different signature: " + pkgName); 12481 return; 12482 } 12483 } 12484 12485 // In case of rollback, remember per-user/profile install state 12486 allUsers = sUserManager.getUserIds(); 12487 perUserInstalled = new boolean[allUsers.length]; 12488 for (int i = 0; i < allUsers.length; i++) { 12489 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12490 } 12491 } 12492 12493 boolean sysPkg = (isSystemApp(oldPackage)); 12494 if (sysPkg) { 12495 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12496 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12497 } else { 12498 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12499 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12500 } 12501 } 12502 12503 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12504 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12505 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12506 String volumeUuid, PackageInstalledInfo res) { 12507 String pkgName = deletedPackage.packageName; 12508 boolean deletedPkg = true; 12509 boolean updatedSettings = false; 12510 12511 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12512 + deletedPackage); 12513 long origUpdateTime; 12514 if (pkg.mExtras != null) { 12515 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12516 } else { 12517 origUpdateTime = 0; 12518 } 12519 12520 // First delete the existing package while retaining the data directory 12521 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12522 res.removedInfo, true)) { 12523 // If the existing package wasn't successfully deleted 12524 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12525 deletedPkg = false; 12526 } else { 12527 // Successfully deleted the old package; proceed with replace. 12528 12529 // If deleted package lived in a container, give users a chance to 12530 // relinquish resources before killing. 12531 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12532 if (DEBUG_INSTALL) { 12533 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12534 } 12535 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12536 final ArrayList<String> pkgList = new ArrayList<String>(1); 12537 pkgList.add(deletedPackage.applicationInfo.packageName); 12538 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12539 } 12540 12541 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12542 try { 12543 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12544 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12545 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12546 perUserInstalled, res, user); 12547 updatedSettings = true; 12548 } catch (PackageManagerException e) { 12549 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12550 } 12551 } 12552 12553 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12554 // remove package from internal structures. Note that we want deletePackageX to 12555 // delete the package data and cache directories that it created in 12556 // scanPackageLocked, unless those directories existed before we even tried to 12557 // install. 12558 if(updatedSettings) { 12559 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12560 deletePackageLI( 12561 pkgName, null, true, allUsers, perUserInstalled, 12562 PackageManager.DELETE_KEEP_DATA, 12563 res.removedInfo, true); 12564 } 12565 // Since we failed to install the new package we need to restore the old 12566 // package that we deleted. 12567 if (deletedPkg) { 12568 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12569 File restoreFile = new File(deletedPackage.codePath); 12570 // Parse old package 12571 boolean oldExternal = isExternal(deletedPackage); 12572 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12573 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12574 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12575 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12576 try { 12577 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12578 null); 12579 } catch (PackageManagerException e) { 12580 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12581 + e.getMessage()); 12582 return; 12583 } 12584 // Restore of old package succeeded. Update permissions. 12585 // writer 12586 synchronized (mPackages) { 12587 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12588 UPDATE_PERMISSIONS_ALL); 12589 // can downgrade to reader 12590 mSettings.writeLPr(); 12591 } 12592 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12593 } 12594 } 12595 } 12596 12597 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12598 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12599 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12600 String volumeUuid, PackageInstalledInfo res) { 12601 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12602 + ", old=" + deletedPackage); 12603 boolean disabledSystem = false; 12604 boolean updatedSettings = false; 12605 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12606 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12607 != 0) { 12608 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12609 } 12610 String packageName = deletedPackage.packageName; 12611 if (packageName == null) { 12612 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12613 "Attempt to delete null packageName."); 12614 return; 12615 } 12616 PackageParser.Package oldPkg; 12617 PackageSetting oldPkgSetting; 12618 // reader 12619 synchronized (mPackages) { 12620 oldPkg = mPackages.get(packageName); 12621 oldPkgSetting = mSettings.mPackages.get(packageName); 12622 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12623 (oldPkgSetting == null)) { 12624 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12625 "Couldn't find package:" + packageName + " information"); 12626 return; 12627 } 12628 } 12629 12630 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12631 12632 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12633 res.removedInfo.removedPackage = packageName; 12634 // Remove existing system package 12635 removePackageLI(oldPkgSetting, true); 12636 // writer 12637 synchronized (mPackages) { 12638 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12639 if (!disabledSystem && deletedPackage != null) { 12640 // We didn't need to disable the .apk as a current system package, 12641 // which means we are replacing another update that is already 12642 // installed. We need to make sure to delete the older one's .apk. 12643 res.removedInfo.args = createInstallArgsForExisting(0, 12644 deletedPackage.applicationInfo.getCodePath(), 12645 deletedPackage.applicationInfo.getResourcePath(), 12646 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12647 } else { 12648 res.removedInfo.args = null; 12649 } 12650 } 12651 12652 // Successfully disabled the old package. Now proceed with re-installation 12653 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12654 12655 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12656 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12657 12658 PackageParser.Package newPackage = null; 12659 try { 12660 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12661 if (newPackage.mExtras != null) { 12662 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12663 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12664 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12665 12666 // is the update attempting to change shared user? that isn't going to work... 12667 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12668 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12669 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12670 + " to " + newPkgSetting.sharedUser); 12671 updatedSettings = true; 12672 } 12673 } 12674 12675 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12676 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12677 perUserInstalled, res, user); 12678 updatedSettings = true; 12679 } 12680 12681 } catch (PackageManagerException e) { 12682 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12683 } 12684 12685 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12686 // Re installation failed. Restore old information 12687 // Remove new pkg information 12688 if (newPackage != null) { 12689 removeInstalledPackageLI(newPackage, true); 12690 } 12691 // Add back the old system package 12692 try { 12693 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12694 } catch (PackageManagerException e) { 12695 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12696 } 12697 // Restore the old system information in Settings 12698 synchronized (mPackages) { 12699 if (disabledSystem) { 12700 mSettings.enableSystemPackageLPw(packageName); 12701 } 12702 if (updatedSettings) { 12703 mSettings.setInstallerPackageName(packageName, 12704 oldPkgSetting.installerPackageName); 12705 } 12706 mSettings.writeLPr(); 12707 } 12708 } 12709 } 12710 12711 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12712 // Collect all used permissions in the UID 12713 ArraySet<String> usedPermissions = new ArraySet<>(); 12714 final int packageCount = su.packages.size(); 12715 for (int i = 0; i < packageCount; i++) { 12716 PackageSetting ps = su.packages.valueAt(i); 12717 if (ps.pkg == null) { 12718 continue; 12719 } 12720 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12721 for (int j = 0; j < requestedPermCount; j++) { 12722 String permission = ps.pkg.requestedPermissions.get(j); 12723 BasePermission bp = mSettings.mPermissions.get(permission); 12724 if (bp != null) { 12725 usedPermissions.add(permission); 12726 } 12727 } 12728 } 12729 12730 PermissionsState permissionsState = su.getPermissionsState(); 12731 // Prune install permissions 12732 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12733 final int installPermCount = installPermStates.size(); 12734 for (int i = installPermCount - 1; i >= 0; i--) { 12735 PermissionState permissionState = installPermStates.get(i); 12736 if (!usedPermissions.contains(permissionState.getName())) { 12737 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12738 if (bp != null) { 12739 permissionsState.revokeInstallPermission(bp); 12740 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12741 PackageManager.MASK_PERMISSION_FLAGS, 0); 12742 } 12743 } 12744 } 12745 12746 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12747 12748 // Prune runtime permissions 12749 for (int userId : allUserIds) { 12750 List<PermissionState> runtimePermStates = permissionsState 12751 .getRuntimePermissionStates(userId); 12752 final int runtimePermCount = runtimePermStates.size(); 12753 for (int i = runtimePermCount - 1; i >= 0; i--) { 12754 PermissionState permissionState = runtimePermStates.get(i); 12755 if (!usedPermissions.contains(permissionState.getName())) { 12756 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12757 if (bp != null) { 12758 permissionsState.revokeRuntimePermission(bp, userId); 12759 permissionsState.updatePermissionFlags(bp, userId, 12760 PackageManager.MASK_PERMISSION_FLAGS, 0); 12761 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12762 runtimePermissionChangedUserIds, userId); 12763 } 12764 } 12765 } 12766 } 12767 12768 return runtimePermissionChangedUserIds; 12769 } 12770 12771 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12772 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12773 UserHandle user) { 12774 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12775 12776 String pkgName = newPackage.packageName; 12777 synchronized (mPackages) { 12778 //write settings. the installStatus will be incomplete at this stage. 12779 //note that the new package setting would have already been 12780 //added to mPackages. It hasn't been persisted yet. 12781 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12782 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12783 mSettings.writeLPr(); 12784 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12785 } 12786 12787 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12788 synchronized (mPackages) { 12789 updatePermissionsLPw(newPackage.packageName, newPackage, 12790 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12791 ? UPDATE_PERMISSIONS_ALL : 0)); 12792 // For system-bundled packages, we assume that installing an upgraded version 12793 // of the package implies that the user actually wants to run that new code, 12794 // so we enable the package. 12795 PackageSetting ps = mSettings.mPackages.get(pkgName); 12796 if (ps != null) { 12797 if (isSystemApp(newPackage)) { 12798 // NB: implicit assumption that system package upgrades apply to all users 12799 if (DEBUG_INSTALL) { 12800 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12801 } 12802 if (res.origUsers != null) { 12803 for (int userHandle : res.origUsers) { 12804 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12805 userHandle, installerPackageName); 12806 } 12807 } 12808 // Also convey the prior install/uninstall state 12809 if (allUsers != null && perUserInstalled != null) { 12810 for (int i = 0; i < allUsers.length; i++) { 12811 if (DEBUG_INSTALL) { 12812 Slog.d(TAG, " user " + allUsers[i] 12813 + " => " + perUserInstalled[i]); 12814 } 12815 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12816 } 12817 // these install state changes will be persisted in the 12818 // upcoming call to mSettings.writeLPr(). 12819 } 12820 } 12821 // It's implied that when a user requests installation, they want the app to be 12822 // installed and enabled. 12823 int userId = user.getIdentifier(); 12824 if (userId != UserHandle.USER_ALL) { 12825 ps.setInstalled(true, userId); 12826 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12827 } 12828 } 12829 res.name = pkgName; 12830 res.uid = newPackage.applicationInfo.uid; 12831 res.pkg = newPackage; 12832 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12833 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12834 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12835 //to update install status 12836 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12837 mSettings.writeLPr(); 12838 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12839 } 12840 12841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12842 } 12843 12844 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12845 try { 12846 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12847 installPackageLI(args, res); 12848 } finally { 12849 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12850 } 12851 } 12852 12853 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12854 final int installFlags = args.installFlags; 12855 final String installerPackageName = args.installerPackageName; 12856 final String volumeUuid = args.volumeUuid; 12857 final File tmpPackageFile = new File(args.getCodePath()); 12858 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12859 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12860 || (args.volumeUuid != null)); 12861 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12862 boolean replace = false; 12863 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12864 if (args.move != null) { 12865 // moving a complete application; perfom an initial scan on the new install location 12866 scanFlags |= SCAN_INITIAL; 12867 } 12868 // Result object to be returned 12869 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12870 12871 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12872 12873 // Sanity check 12874 if (ephemeral && (forwardLocked || onExternal)) { 12875 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12876 + " external=" + onExternal); 12877 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12878 return; 12879 } 12880 12881 // Retrieve PackageSettings and parse package 12882 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12883 | PackageParser.PARSE_ENFORCE_CODE 12884 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12885 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12886 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12887 PackageParser pp = new PackageParser(); 12888 pp.setSeparateProcesses(mSeparateProcesses); 12889 pp.setDisplayMetrics(mMetrics); 12890 12891 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12892 final PackageParser.Package pkg; 12893 try { 12894 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12895 } catch (PackageParserException e) { 12896 res.setError("Failed parse during installPackageLI", e); 12897 return; 12898 } finally { 12899 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12900 } 12901 12902 // Mark that we have an install time CPU ABI override. 12903 pkg.cpuAbiOverride = args.abiOverride; 12904 12905 String pkgName = res.name = pkg.packageName; 12906 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12907 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12908 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12909 return; 12910 } 12911 } 12912 12913 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12914 try { 12915 pp.collectCertificates(pkg, parseFlags); 12916 } catch (PackageParserException e) { 12917 res.setError("Failed collect during installPackageLI", e); 12918 return; 12919 } finally { 12920 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12921 } 12922 12923 /* If the installer passed in a manifest digest, compare it now. */ 12924 if (args.manifestDigest != null) { 12925 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12926 try { 12927 pp.collectManifestDigest(pkg); 12928 } catch (PackageParserException e) { 12929 res.setError("Failed collect during installPackageLI", e); 12930 return; 12931 } finally { 12932 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12933 } 12934 12935 if (DEBUG_INSTALL) { 12936 final String parsedManifest = pkg.manifestDigest == null ? "null" 12937 : pkg.manifestDigest.toString(); 12938 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12939 + parsedManifest); 12940 } 12941 12942 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12943 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12944 return; 12945 } 12946 } else if (DEBUG_INSTALL) { 12947 final String parsedManifest = pkg.manifestDigest == null 12948 ? "null" : pkg.manifestDigest.toString(); 12949 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12950 } 12951 12952 // Get rid of all references to package scan path via parser. 12953 pp = null; 12954 String oldCodePath = null; 12955 boolean systemApp = false; 12956 synchronized (mPackages) { 12957 // Check if installing already existing package 12958 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12959 String oldName = mSettings.mRenamedPackages.get(pkgName); 12960 if (pkg.mOriginalPackages != null 12961 && pkg.mOriginalPackages.contains(oldName) 12962 && mPackages.containsKey(oldName)) { 12963 // This package is derived from an original package, 12964 // and this device has been updating from that original 12965 // name. We must continue using the original name, so 12966 // rename the new package here. 12967 pkg.setPackageName(oldName); 12968 pkgName = pkg.packageName; 12969 replace = true; 12970 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12971 + oldName + " pkgName=" + pkgName); 12972 } else if (mPackages.containsKey(pkgName)) { 12973 // This package, under its official name, already exists 12974 // on the device; we should replace it. 12975 replace = true; 12976 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12977 } 12978 12979 // Prevent apps opting out from runtime permissions 12980 if (replace) { 12981 PackageParser.Package oldPackage = mPackages.get(pkgName); 12982 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12983 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12984 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12985 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12986 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12987 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12988 + " doesn't support runtime permissions but the old" 12989 + " target SDK " + oldTargetSdk + " does."); 12990 return; 12991 } 12992 } 12993 } 12994 12995 PackageSetting ps = mSettings.mPackages.get(pkgName); 12996 if (ps != null) { 12997 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12998 12999 // Quick sanity check that we're signed correctly if updating; 13000 // we'll check this again later when scanning, but we want to 13001 // bail early here before tripping over redefined permissions. 13002 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13003 if (!checkUpgradeKeySetLP(ps, pkg)) { 13004 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13005 + pkg.packageName + " upgrade keys do not match the " 13006 + "previously installed version"); 13007 return; 13008 } 13009 } else { 13010 try { 13011 verifySignaturesLP(ps, pkg); 13012 } catch (PackageManagerException e) { 13013 res.setError(e.error, e.getMessage()); 13014 return; 13015 } 13016 } 13017 13018 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13019 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13020 systemApp = (ps.pkg.applicationInfo.flags & 13021 ApplicationInfo.FLAG_SYSTEM) != 0; 13022 } 13023 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13024 } 13025 13026 // Check whether the newly-scanned package wants to define an already-defined perm 13027 int N = pkg.permissions.size(); 13028 for (int i = N-1; i >= 0; i--) { 13029 PackageParser.Permission perm = pkg.permissions.get(i); 13030 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13031 if (bp != null) { 13032 // If the defining package is signed with our cert, it's okay. This 13033 // also includes the "updating the same package" case, of course. 13034 // "updating same package" could also involve key-rotation. 13035 final boolean sigsOk; 13036 if (bp.sourcePackage.equals(pkg.packageName) 13037 && (bp.packageSetting instanceof PackageSetting) 13038 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13039 scanFlags))) { 13040 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13041 } else { 13042 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13043 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13044 } 13045 if (!sigsOk) { 13046 // If the owning package is the system itself, we log but allow 13047 // install to proceed; we fail the install on all other permission 13048 // redefinitions. 13049 if (!bp.sourcePackage.equals("android")) { 13050 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13051 + pkg.packageName + " attempting to redeclare permission " 13052 + perm.info.name + " already owned by " + bp.sourcePackage); 13053 res.origPermission = perm.info.name; 13054 res.origPackage = bp.sourcePackage; 13055 return; 13056 } else { 13057 Slog.w(TAG, "Package " + pkg.packageName 13058 + " attempting to redeclare system permission " 13059 + perm.info.name + "; ignoring new declaration"); 13060 pkg.permissions.remove(i); 13061 } 13062 } 13063 } 13064 } 13065 13066 } 13067 13068 if (systemApp) { 13069 if (onExternal) { 13070 // Abort update; system app can't be replaced with app on sdcard 13071 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13072 "Cannot install updates to system apps on sdcard"); 13073 return; 13074 } else if (ephemeral) { 13075 // Abort update; system app can't be replaced with an ephemeral app 13076 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13077 "Cannot update a system app with an ephemeral app"); 13078 return; 13079 } 13080 } 13081 13082 if (args.move != null) { 13083 // We did an in-place move, so dex is ready to roll 13084 scanFlags |= SCAN_NO_DEX; 13085 scanFlags |= SCAN_MOVE; 13086 13087 synchronized (mPackages) { 13088 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13089 if (ps == null) { 13090 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13091 "Missing settings for moved package " + pkgName); 13092 } 13093 13094 // We moved the entire application as-is, so bring over the 13095 // previously derived ABI information. 13096 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13097 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13098 } 13099 13100 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13101 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13102 scanFlags |= SCAN_NO_DEX; 13103 13104 try { 13105 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13106 true /* extract libs */); 13107 } catch (PackageManagerException pme) { 13108 Slog.e(TAG, "Error deriving application ABI", pme); 13109 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13110 return; 13111 } 13112 } 13113 13114 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13115 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13116 return; 13117 } 13118 13119 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13120 13121 if (replace) { 13122 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13123 installerPackageName, volumeUuid, res); 13124 } else { 13125 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13126 args.user, installerPackageName, volumeUuid, res); 13127 } 13128 synchronized (mPackages) { 13129 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13130 if (ps != null) { 13131 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13132 } 13133 } 13134 } 13135 13136 private void startIntentFilterVerifications(int userId, boolean replacing, 13137 PackageParser.Package pkg) { 13138 if (mIntentFilterVerifierComponent == null) { 13139 Slog.w(TAG, "No IntentFilter verification will not be done as " 13140 + "there is no IntentFilterVerifier available!"); 13141 return; 13142 } 13143 13144 final int verifierUid = getPackageUid( 13145 mIntentFilterVerifierComponent.getPackageName(), 13146 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13147 13148 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13149 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13150 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13151 mHandler.sendMessage(msg); 13152 } 13153 13154 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13155 PackageParser.Package pkg) { 13156 int size = pkg.activities.size(); 13157 if (size == 0) { 13158 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13159 "No activity, so no need to verify any IntentFilter!"); 13160 return; 13161 } 13162 13163 final boolean hasDomainURLs = hasDomainURLs(pkg); 13164 if (!hasDomainURLs) { 13165 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13166 "No domain URLs, so no need to verify any IntentFilter!"); 13167 return; 13168 } 13169 13170 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13171 + " if any IntentFilter from the " + size 13172 + " Activities needs verification ..."); 13173 13174 int count = 0; 13175 final String packageName = pkg.packageName; 13176 13177 synchronized (mPackages) { 13178 // If this is a new install and we see that we've already run verification for this 13179 // package, we have nothing to do: it means the state was restored from backup. 13180 if (!replacing) { 13181 IntentFilterVerificationInfo ivi = 13182 mSettings.getIntentFilterVerificationLPr(packageName); 13183 if (ivi != null) { 13184 if (DEBUG_DOMAIN_VERIFICATION) { 13185 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13186 + ivi.getStatusString()); 13187 } 13188 return; 13189 } 13190 } 13191 13192 // If any filters need to be verified, then all need to be. 13193 boolean needToVerify = false; 13194 for (PackageParser.Activity a : pkg.activities) { 13195 for (ActivityIntentInfo filter : a.intents) { 13196 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13197 if (DEBUG_DOMAIN_VERIFICATION) { 13198 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13199 } 13200 needToVerify = true; 13201 break; 13202 } 13203 } 13204 } 13205 13206 if (needToVerify) { 13207 final int verificationId = mIntentFilterVerificationToken++; 13208 for (PackageParser.Activity a : pkg.activities) { 13209 for (ActivityIntentInfo filter : a.intents) { 13210 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13211 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13212 "Verification needed for IntentFilter:" + filter.toString()); 13213 mIntentFilterVerifier.addOneIntentFilterVerification( 13214 verifierUid, userId, verificationId, filter, packageName); 13215 count++; 13216 } 13217 } 13218 } 13219 } 13220 } 13221 13222 if (count > 0) { 13223 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13224 + " IntentFilter verification" + (count > 1 ? "s" : "") 13225 + " for userId:" + userId); 13226 mIntentFilterVerifier.startVerifications(userId); 13227 } else { 13228 if (DEBUG_DOMAIN_VERIFICATION) { 13229 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13230 } 13231 } 13232 } 13233 13234 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13235 final ComponentName cn = filter.activity.getComponentName(); 13236 final String packageName = cn.getPackageName(); 13237 13238 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13239 packageName); 13240 if (ivi == null) { 13241 return true; 13242 } 13243 int status = ivi.getStatus(); 13244 switch (status) { 13245 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13246 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13247 return true; 13248 13249 default: 13250 // Nothing to do 13251 return false; 13252 } 13253 } 13254 13255 private static boolean isMultiArch(ApplicationInfo info) { 13256 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13257 } 13258 13259 private static boolean isExternal(PackageParser.Package pkg) { 13260 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13261 } 13262 13263 private static boolean isExternal(PackageSetting ps) { 13264 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13265 } 13266 13267 private static boolean isEphemeral(PackageParser.Package pkg) { 13268 return pkg.applicationInfo.isEphemeralApp(); 13269 } 13270 13271 private static boolean isEphemeral(PackageSetting ps) { 13272 return ps.pkg != null && isEphemeral(ps.pkg); 13273 } 13274 13275 private static boolean isSystemApp(PackageParser.Package pkg) { 13276 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13277 } 13278 13279 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13280 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13281 } 13282 13283 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13284 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13285 } 13286 13287 private static boolean isSystemApp(PackageSetting ps) { 13288 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13289 } 13290 13291 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13292 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13293 } 13294 13295 private int packageFlagsToInstallFlags(PackageSetting ps) { 13296 int installFlags = 0; 13297 if (isEphemeral(ps)) { 13298 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13299 } 13300 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13301 // This existing package was an external ASEC install when we have 13302 // the external flag without a UUID 13303 installFlags |= PackageManager.INSTALL_EXTERNAL; 13304 } 13305 if (ps.isForwardLocked()) { 13306 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13307 } 13308 return installFlags; 13309 } 13310 13311 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13312 if (isExternal(pkg)) { 13313 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13314 return StorageManager.UUID_PRIMARY_PHYSICAL; 13315 } else { 13316 return pkg.volumeUuid; 13317 } 13318 } else { 13319 return StorageManager.UUID_PRIVATE_INTERNAL; 13320 } 13321 } 13322 13323 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13324 if (isExternal(pkg)) { 13325 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13326 return mSettings.getExternalVersion(); 13327 } else { 13328 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13329 } 13330 } else { 13331 return mSettings.getInternalVersion(); 13332 } 13333 } 13334 13335 private void deleteTempPackageFiles() { 13336 final FilenameFilter filter = new FilenameFilter() { 13337 public boolean accept(File dir, String name) { 13338 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13339 } 13340 }; 13341 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13342 file.delete(); 13343 } 13344 } 13345 13346 @Override 13347 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13348 int flags) { 13349 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13350 flags); 13351 } 13352 13353 @Override 13354 public void deletePackage(final String packageName, 13355 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13356 mContext.enforceCallingOrSelfPermission( 13357 android.Manifest.permission.DELETE_PACKAGES, null); 13358 Preconditions.checkNotNull(packageName); 13359 Preconditions.checkNotNull(observer); 13360 final int uid = Binder.getCallingUid(); 13361 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13362 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13363 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13364 mContext.enforceCallingOrSelfPermission( 13365 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13366 "deletePackage for user " + userId); 13367 } 13368 13369 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13370 try { 13371 observer.onPackageDeleted(packageName, 13372 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13373 } catch (RemoteException re) { 13374 } 13375 return; 13376 } 13377 13378 for (int currentUserId : users) { 13379 if (getBlockUninstallForUser(packageName, currentUserId)) { 13380 try { 13381 observer.onPackageDeleted(packageName, 13382 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13383 } catch (RemoteException re) { 13384 } 13385 return; 13386 } 13387 } 13388 13389 if (DEBUG_REMOVE) { 13390 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13391 } 13392 // Queue up an async operation since the package deletion may take a little while. 13393 mHandler.post(new Runnable() { 13394 public void run() { 13395 mHandler.removeCallbacks(this); 13396 final int returnCode = deletePackageX(packageName, userId, flags); 13397 try { 13398 observer.onPackageDeleted(packageName, returnCode, null); 13399 } catch (RemoteException e) { 13400 Log.i(TAG, "Observer no longer exists."); 13401 } //end catch 13402 } //end run 13403 }); 13404 } 13405 13406 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13407 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13408 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13409 try { 13410 if (dpm != null) { 13411 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13412 /* callingUserOnly =*/ false); 13413 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13414 : deviceOwnerComponentName.getPackageName(); 13415 // Does the package contains the device owner? 13416 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13417 // this check is probably not needed, since DO should be registered as a device 13418 // admin on some user too. (Original bug for this: b/17657954) 13419 if (packageName.equals(deviceOwnerPackageName)) { 13420 return true; 13421 } 13422 // Does it contain a device admin for any user? 13423 int[] users; 13424 if (userId == UserHandle.USER_ALL) { 13425 users = sUserManager.getUserIds(); 13426 } else { 13427 users = new int[]{userId}; 13428 } 13429 for (int i = 0; i < users.length; ++i) { 13430 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13431 return true; 13432 } 13433 } 13434 } 13435 } catch (RemoteException e) { 13436 } 13437 return false; 13438 } 13439 13440 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13441 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13442 } 13443 13444 /** 13445 * This method is an internal method that could be get invoked either 13446 * to delete an installed package or to clean up a failed installation. 13447 * After deleting an installed package, a broadcast is sent to notify any 13448 * listeners that the package has been installed. For cleaning up a failed 13449 * installation, the broadcast is not necessary since the package's 13450 * installation wouldn't have sent the initial broadcast either 13451 * The key steps in deleting a package are 13452 * deleting the package information in internal structures like mPackages, 13453 * deleting the packages base directories through installd 13454 * updating mSettings to reflect current status 13455 * persisting settings for later use 13456 * sending a broadcast if necessary 13457 */ 13458 private int deletePackageX(String packageName, int userId, int flags) { 13459 final PackageRemovedInfo info = new PackageRemovedInfo(); 13460 final boolean res; 13461 13462 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13463 ? UserHandle.ALL : new UserHandle(userId); 13464 13465 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13466 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13467 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13468 } 13469 13470 boolean removedForAllUsers = false; 13471 boolean systemUpdate = false; 13472 13473 PackageParser.Package uninstalledPkg; 13474 13475 // for the uninstall-updates case and restricted profiles, remember the per- 13476 // userhandle installed state 13477 int[] allUsers; 13478 boolean[] perUserInstalled; 13479 synchronized (mPackages) { 13480 uninstalledPkg = mPackages.get(packageName); 13481 PackageSetting ps = mSettings.mPackages.get(packageName); 13482 allUsers = sUserManager.getUserIds(); 13483 perUserInstalled = new boolean[allUsers.length]; 13484 for (int i = 0; i < allUsers.length; i++) { 13485 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13486 } 13487 } 13488 13489 synchronized (mInstallLock) { 13490 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13491 res = deletePackageLI(packageName, removeForUser, 13492 true, allUsers, perUserInstalled, 13493 flags | REMOVE_CHATTY, info, true); 13494 systemUpdate = info.isRemovedPackageSystemUpdate; 13495 synchronized (mPackages) { 13496 if (res) { 13497 if (!systemUpdate && mPackages.get(packageName) == null) { 13498 removedForAllUsers = true; 13499 } 13500 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13501 } 13502 } 13503 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13504 + " removedForAllUsers=" + removedForAllUsers); 13505 } 13506 13507 if (res) { 13508 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13509 13510 // If the removed package was a system update, the old system package 13511 // was re-enabled; we need to broadcast this information 13512 if (systemUpdate) { 13513 Bundle extras = new Bundle(1); 13514 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13515 ? info.removedAppId : info.uid); 13516 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13517 13518 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13519 extras, 0, null, null, null); 13520 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13521 extras, 0, null, null, null); 13522 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13523 null, 0, packageName, null, null); 13524 } 13525 } 13526 // Force a gc here. 13527 Runtime.getRuntime().gc(); 13528 // Delete the resources here after sending the broadcast to let 13529 // other processes clean up before deleting resources. 13530 if (info.args != null) { 13531 synchronized (mInstallLock) { 13532 info.args.doPostDeleteLI(true); 13533 } 13534 } 13535 13536 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13537 } 13538 13539 class PackageRemovedInfo { 13540 String removedPackage; 13541 int uid = -1; 13542 int removedAppId = -1; 13543 int[] removedUsers = null; 13544 boolean isRemovedPackageSystemUpdate = false; 13545 // Clean up resources deleted packages. 13546 InstallArgs args = null; 13547 13548 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13549 Bundle extras = new Bundle(1); 13550 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13551 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13552 if (replacing) { 13553 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13554 } 13555 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13556 if (removedPackage != null) { 13557 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13558 extras, 0, null, null, removedUsers); 13559 if (fullRemove && !replacing) { 13560 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13561 extras, 0, null, null, removedUsers); 13562 } 13563 } 13564 if (removedAppId >= 0) { 13565 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13566 removedUsers); 13567 } 13568 } 13569 } 13570 13571 /* 13572 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13573 * flag is not set, the data directory is removed as well. 13574 * make sure this flag is set for partially installed apps. If not its meaningless to 13575 * delete a partially installed application. 13576 */ 13577 private void removePackageDataLI(PackageSetting ps, 13578 int[] allUserHandles, boolean[] perUserInstalled, 13579 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13580 String packageName = ps.name; 13581 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13582 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13583 // Retrieve object to delete permissions for shared user later on 13584 final PackageSetting deletedPs; 13585 // reader 13586 synchronized (mPackages) { 13587 deletedPs = mSettings.mPackages.get(packageName); 13588 if (outInfo != null) { 13589 outInfo.removedPackage = packageName; 13590 outInfo.removedUsers = deletedPs != null 13591 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13592 : null; 13593 } 13594 } 13595 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13596 removeDataDirsLI(ps.volumeUuid, packageName); 13597 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13598 } 13599 // writer 13600 synchronized (mPackages) { 13601 if (deletedPs != null) { 13602 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13603 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13604 clearDefaultBrowserIfNeeded(packageName); 13605 if (outInfo != null) { 13606 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13607 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13608 } 13609 updatePermissionsLPw(deletedPs.name, null, 0); 13610 if (deletedPs.sharedUser != null) { 13611 // Remove permissions associated with package. Since runtime 13612 // permissions are per user we have to kill the removed package 13613 // or packages running under the shared user of the removed 13614 // package if revoking the permissions requested only by the removed 13615 // package is successful and this causes a change in gids. 13616 for (int userId : UserManagerService.getInstance().getUserIds()) { 13617 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13618 userId); 13619 if (userIdToKill == UserHandle.USER_ALL 13620 || userIdToKill >= UserHandle.USER_SYSTEM) { 13621 // If gids changed for this user, kill all affected packages. 13622 mHandler.post(new Runnable() { 13623 @Override 13624 public void run() { 13625 // This has to happen with no lock held. 13626 killApplication(deletedPs.name, deletedPs.appId, 13627 KILL_APP_REASON_GIDS_CHANGED); 13628 } 13629 }); 13630 break; 13631 } 13632 } 13633 } 13634 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13635 } 13636 // make sure to preserve per-user disabled state if this removal was just 13637 // a downgrade of a system app to the factory package 13638 if (allUserHandles != null && perUserInstalled != null) { 13639 if (DEBUG_REMOVE) { 13640 Slog.d(TAG, "Propagating install state across downgrade"); 13641 } 13642 for (int i = 0; i < allUserHandles.length; i++) { 13643 if (DEBUG_REMOVE) { 13644 Slog.d(TAG, " user " + allUserHandles[i] 13645 + " => " + perUserInstalled[i]); 13646 } 13647 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13648 } 13649 } 13650 } 13651 // can downgrade to reader 13652 if (writeSettings) { 13653 // Save settings now 13654 mSettings.writeLPr(); 13655 } 13656 } 13657 if (outInfo != null) { 13658 // A user ID was deleted here. Go through all users and remove it 13659 // from KeyStore. 13660 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13661 } 13662 } 13663 13664 static boolean locationIsPrivileged(File path) { 13665 try { 13666 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13667 .getCanonicalPath(); 13668 return path.getCanonicalPath().startsWith(privilegedAppDir); 13669 } catch (IOException e) { 13670 Slog.e(TAG, "Unable to access code path " + path); 13671 } 13672 return false; 13673 } 13674 13675 /* 13676 * Tries to delete system package. 13677 */ 13678 private boolean deleteSystemPackageLI(PackageSetting newPs, 13679 int[] allUserHandles, boolean[] perUserInstalled, 13680 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13681 final boolean applyUserRestrictions 13682 = (allUserHandles != null) && (perUserInstalled != null); 13683 PackageSetting disabledPs = null; 13684 // Confirm if the system package has been updated 13685 // An updated system app can be deleted. This will also have to restore 13686 // the system pkg from system partition 13687 // reader 13688 synchronized (mPackages) { 13689 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13690 } 13691 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13692 + " disabledPs=" + disabledPs); 13693 if (disabledPs == null) { 13694 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13695 return false; 13696 } else if (DEBUG_REMOVE) { 13697 Slog.d(TAG, "Deleting system pkg from data partition"); 13698 } 13699 if (DEBUG_REMOVE) { 13700 if (applyUserRestrictions) { 13701 Slog.d(TAG, "Remembering install states:"); 13702 for (int i = 0; i < allUserHandles.length; i++) { 13703 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13704 } 13705 } 13706 } 13707 // Delete the updated package 13708 outInfo.isRemovedPackageSystemUpdate = true; 13709 if (disabledPs.versionCode < newPs.versionCode) { 13710 // Delete data for downgrades 13711 flags &= ~PackageManager.DELETE_KEEP_DATA; 13712 } else { 13713 // Preserve data by setting flag 13714 flags |= PackageManager.DELETE_KEEP_DATA; 13715 } 13716 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13717 allUserHandles, perUserInstalled, outInfo, writeSettings); 13718 if (!ret) { 13719 return false; 13720 } 13721 // writer 13722 synchronized (mPackages) { 13723 // Reinstate the old system package 13724 mSettings.enableSystemPackageLPw(newPs.name); 13725 // Remove any native libraries from the upgraded package. 13726 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13727 } 13728 // Install the system package 13729 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13730 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13731 if (locationIsPrivileged(disabledPs.codePath)) { 13732 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13733 } 13734 13735 final PackageParser.Package newPkg; 13736 try { 13737 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13738 } catch (PackageManagerException e) { 13739 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13740 return false; 13741 } 13742 13743 // writer 13744 synchronized (mPackages) { 13745 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13746 13747 // Propagate the permissions state as we do not want to drop on the floor 13748 // runtime permissions. The update permissions method below will take 13749 // care of removing obsolete permissions and grant install permissions. 13750 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13751 updatePermissionsLPw(newPkg.packageName, newPkg, 13752 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13753 13754 if (applyUserRestrictions) { 13755 if (DEBUG_REMOVE) { 13756 Slog.d(TAG, "Propagating install state across reinstall"); 13757 } 13758 for (int i = 0; i < allUserHandles.length; i++) { 13759 if (DEBUG_REMOVE) { 13760 Slog.d(TAG, " user " + allUserHandles[i] 13761 + " => " + perUserInstalled[i]); 13762 } 13763 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13764 13765 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13766 } 13767 // Regardless of writeSettings we need to ensure that this restriction 13768 // state propagation is persisted 13769 mSettings.writeAllUsersPackageRestrictionsLPr(); 13770 } 13771 // can downgrade to reader here 13772 if (writeSettings) { 13773 mSettings.writeLPr(); 13774 } 13775 } 13776 return true; 13777 } 13778 13779 private boolean deleteInstalledPackageLI(PackageSetting ps, 13780 boolean deleteCodeAndResources, int flags, 13781 int[] allUserHandles, boolean[] perUserInstalled, 13782 PackageRemovedInfo outInfo, boolean writeSettings) { 13783 if (outInfo != null) { 13784 outInfo.uid = ps.appId; 13785 } 13786 13787 // Delete package data from internal structures and also remove data if flag is set 13788 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13789 13790 // Delete application code and resources 13791 if (deleteCodeAndResources && (outInfo != null)) { 13792 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13793 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13794 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13795 } 13796 return true; 13797 } 13798 13799 @Override 13800 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13801 int userId) { 13802 mContext.enforceCallingOrSelfPermission( 13803 android.Manifest.permission.DELETE_PACKAGES, null); 13804 synchronized (mPackages) { 13805 PackageSetting ps = mSettings.mPackages.get(packageName); 13806 if (ps == null) { 13807 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13808 return false; 13809 } 13810 if (!ps.getInstalled(userId)) { 13811 // Can't block uninstall for an app that is not installed or enabled. 13812 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13813 return false; 13814 } 13815 ps.setBlockUninstall(blockUninstall, userId); 13816 mSettings.writePackageRestrictionsLPr(userId); 13817 } 13818 return true; 13819 } 13820 13821 @Override 13822 public boolean getBlockUninstallForUser(String packageName, int userId) { 13823 synchronized (mPackages) { 13824 PackageSetting ps = mSettings.mPackages.get(packageName); 13825 if (ps == null) { 13826 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13827 return false; 13828 } 13829 return ps.getBlockUninstall(userId); 13830 } 13831 } 13832 13833 @Override 13834 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13835 int callingUid = Binder.getCallingUid(); 13836 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13837 throw new SecurityException( 13838 "setRequiredForSystemUser can only be run by the system or root"); 13839 } 13840 synchronized (mPackages) { 13841 PackageSetting ps = mSettings.mPackages.get(packageName); 13842 if (ps == null) { 13843 Log.w(TAG, "Package doesn't exist: " + packageName); 13844 return false; 13845 } 13846 if (systemUserApp) { 13847 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13848 } else { 13849 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13850 } 13851 mSettings.writeLPr(); 13852 } 13853 return true; 13854 } 13855 13856 /* 13857 * This method handles package deletion in general 13858 */ 13859 private boolean deletePackageLI(String packageName, UserHandle user, 13860 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13861 int flags, PackageRemovedInfo outInfo, 13862 boolean writeSettings) { 13863 if (packageName == null) { 13864 Slog.w(TAG, "Attempt to delete null packageName."); 13865 return false; 13866 } 13867 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13868 PackageSetting ps; 13869 boolean dataOnly = false; 13870 int removeUser = -1; 13871 int appId = -1; 13872 synchronized (mPackages) { 13873 ps = mSettings.mPackages.get(packageName); 13874 if (ps == null) { 13875 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13876 return false; 13877 } 13878 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13879 && user.getIdentifier() != UserHandle.USER_ALL) { 13880 // The caller is asking that the package only be deleted for a single 13881 // user. To do this, we just mark its uninstalled state and delete 13882 // its data. If this is a system app, we only allow this to happen if 13883 // they have set the special DELETE_SYSTEM_APP which requests different 13884 // semantics than normal for uninstalling system apps. 13885 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13886 final int userId = user.getIdentifier(); 13887 ps.setUserState(userId, 13888 COMPONENT_ENABLED_STATE_DEFAULT, 13889 false, //installed 13890 true, //stopped 13891 true, //notLaunched 13892 false, //hidden 13893 false, //suspended 13894 null, null, null, 13895 false, // blockUninstall 13896 ps.readUserState(userId).domainVerificationStatus, 0); 13897 if (!isSystemApp(ps)) { 13898 // Do not uninstall the APK if an app should be cached 13899 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13900 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13901 // Other user still have this package installed, so all 13902 // we need to do is clear this user's data and save that 13903 // it is uninstalled. 13904 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13905 removeUser = user.getIdentifier(); 13906 appId = ps.appId; 13907 scheduleWritePackageRestrictionsLocked(removeUser); 13908 } else { 13909 // We need to set it back to 'installed' so the uninstall 13910 // broadcasts will be sent correctly. 13911 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13912 ps.setInstalled(true, user.getIdentifier()); 13913 } 13914 } else { 13915 // This is a system app, so we assume that the 13916 // other users still have this package installed, so all 13917 // we need to do is clear this user's data and save that 13918 // it is uninstalled. 13919 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13920 removeUser = user.getIdentifier(); 13921 appId = ps.appId; 13922 scheduleWritePackageRestrictionsLocked(removeUser); 13923 } 13924 } 13925 } 13926 13927 if (removeUser >= 0) { 13928 // From above, we determined that we are deleting this only 13929 // for a single user. Continue the work here. 13930 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13931 if (outInfo != null) { 13932 outInfo.removedPackage = packageName; 13933 outInfo.removedAppId = appId; 13934 outInfo.removedUsers = new int[] {removeUser}; 13935 } 13936 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13937 removeKeystoreDataIfNeeded(removeUser, appId); 13938 schedulePackageCleaning(packageName, removeUser, false); 13939 synchronized (mPackages) { 13940 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13941 scheduleWritePackageRestrictionsLocked(removeUser); 13942 } 13943 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13944 } 13945 return true; 13946 } 13947 13948 if (dataOnly) { 13949 // Delete application data first 13950 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13951 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13952 return true; 13953 } 13954 13955 boolean ret = false; 13956 if (isSystemApp(ps)) { 13957 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13958 // When an updated system application is deleted we delete the existing resources as well and 13959 // fall back to existing code in system partition 13960 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13961 flags, outInfo, writeSettings); 13962 } else { 13963 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13964 // Kill application pre-emptively especially for apps on sd. 13965 killApplication(packageName, ps.appId, "uninstall pkg"); 13966 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13967 allUserHandles, perUserInstalled, 13968 outInfo, writeSettings); 13969 } 13970 13971 return ret; 13972 } 13973 13974 private final static class ClearStorageConnection implements ServiceConnection { 13975 IMediaContainerService mContainerService; 13976 13977 @Override 13978 public void onServiceConnected(ComponentName name, IBinder service) { 13979 synchronized (this) { 13980 mContainerService = IMediaContainerService.Stub.asInterface(service); 13981 notifyAll(); 13982 } 13983 } 13984 13985 @Override 13986 public void onServiceDisconnected(ComponentName name) { 13987 } 13988 } 13989 13990 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13991 final boolean mounted; 13992 if (Environment.isExternalStorageEmulated()) { 13993 mounted = true; 13994 } else { 13995 final String status = Environment.getExternalStorageState(); 13996 13997 mounted = status.equals(Environment.MEDIA_MOUNTED) 13998 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13999 } 14000 14001 if (!mounted) { 14002 return; 14003 } 14004 14005 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 14006 int[] users; 14007 if (userId == UserHandle.USER_ALL) { 14008 users = sUserManager.getUserIds(); 14009 } else { 14010 users = new int[] { userId }; 14011 } 14012 final ClearStorageConnection conn = new ClearStorageConnection(); 14013 if (mContext.bindServiceAsUser( 14014 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 14015 try { 14016 for (int curUser : users) { 14017 long timeout = SystemClock.uptimeMillis() + 5000; 14018 synchronized (conn) { 14019 long now = SystemClock.uptimeMillis(); 14020 while (conn.mContainerService == null && now < timeout) { 14021 try { 14022 conn.wait(timeout - now); 14023 } catch (InterruptedException e) { 14024 } 14025 } 14026 } 14027 if (conn.mContainerService == null) { 14028 return; 14029 } 14030 14031 final UserEnvironment userEnv = new UserEnvironment(curUser); 14032 clearDirectory(conn.mContainerService, 14033 userEnv.buildExternalStorageAppCacheDirs(packageName)); 14034 if (allData) { 14035 clearDirectory(conn.mContainerService, 14036 userEnv.buildExternalStorageAppDataDirs(packageName)); 14037 clearDirectory(conn.mContainerService, 14038 userEnv.buildExternalStorageAppMediaDirs(packageName)); 14039 } 14040 } 14041 } finally { 14042 mContext.unbindService(conn); 14043 } 14044 } 14045 } 14046 14047 @Override 14048 public void clearApplicationUserData(final String packageName, 14049 final IPackageDataObserver observer, final int userId) { 14050 mContext.enforceCallingOrSelfPermission( 14051 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 14052 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 14053 // Queue up an async operation since the package deletion may take a little while. 14054 mHandler.post(new Runnable() { 14055 public void run() { 14056 mHandler.removeCallbacks(this); 14057 final boolean succeeded; 14058 synchronized (mInstallLock) { 14059 succeeded = clearApplicationUserDataLI(packageName, userId); 14060 } 14061 clearExternalStorageDataSync(packageName, userId, true); 14062 if (succeeded) { 14063 // invoke DeviceStorageMonitor's update method to clear any notifications 14064 DeviceStorageMonitorInternal 14065 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14066 if (dsm != null) { 14067 dsm.checkMemory(); 14068 } 14069 } 14070 if(observer != null) { 14071 try { 14072 observer.onRemoveCompleted(packageName, succeeded); 14073 } catch (RemoteException e) { 14074 Log.i(TAG, "Observer no longer exists."); 14075 } 14076 } //end if observer 14077 } //end run 14078 }); 14079 } 14080 14081 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14082 if (packageName == null) { 14083 Slog.w(TAG, "Attempt to delete null packageName."); 14084 return false; 14085 } 14086 14087 // Try finding details about the requested package 14088 PackageParser.Package pkg; 14089 synchronized (mPackages) { 14090 pkg = mPackages.get(packageName); 14091 if (pkg == null) { 14092 final PackageSetting ps = mSettings.mPackages.get(packageName); 14093 if (ps != null) { 14094 pkg = ps.pkg; 14095 } 14096 } 14097 14098 if (pkg == null) { 14099 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14100 return false; 14101 } 14102 14103 PackageSetting ps = (PackageSetting) pkg.mExtras; 14104 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14105 } 14106 14107 // Always delete data directories for package, even if we found no other 14108 // record of app. This helps users recover from UID mismatches without 14109 // resorting to a full data wipe. 14110 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 14111 if (retCode < 0) { 14112 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 14113 return false; 14114 } 14115 14116 final int appId = pkg.applicationInfo.uid; 14117 removeKeystoreDataIfNeeded(userId, appId); 14118 14119 // Create a native library symlink only if we have native libraries 14120 // and if the native libraries are 32 bit libraries. We do not provide 14121 // this symlink for 64 bit libraries. 14122 if (pkg.applicationInfo.primaryCpuAbi != null && 14123 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14124 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14125 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14126 nativeLibPath, userId) < 0) { 14127 Slog.w(TAG, "Failed linking native library dir"); 14128 return false; 14129 } 14130 } 14131 14132 return true; 14133 } 14134 14135 /** 14136 * Reverts user permission state changes (permissions and flags) in 14137 * all packages for a given user. 14138 * 14139 * @param userId The device user for which to do a reset. 14140 */ 14141 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14142 final int packageCount = mPackages.size(); 14143 for (int i = 0; i < packageCount; i++) { 14144 PackageParser.Package pkg = mPackages.valueAt(i); 14145 PackageSetting ps = (PackageSetting) pkg.mExtras; 14146 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14147 } 14148 } 14149 14150 /** 14151 * Reverts user permission state changes (permissions and flags). 14152 * 14153 * @param ps The package for which to reset. 14154 * @param userId The device user for which to do a reset. 14155 */ 14156 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14157 final PackageSetting ps, final int userId) { 14158 if (ps.pkg == null) { 14159 return; 14160 } 14161 14162 // These are flags that can change base on user actions. 14163 final int userSettableMask = FLAG_PERMISSION_USER_SET 14164 | FLAG_PERMISSION_USER_FIXED 14165 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14166 | FLAG_PERMISSION_REVIEW_REQUIRED; 14167 14168 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14169 | FLAG_PERMISSION_POLICY_FIXED; 14170 14171 boolean writeInstallPermissions = false; 14172 boolean writeRuntimePermissions = false; 14173 14174 final int permissionCount = ps.pkg.requestedPermissions.size(); 14175 for (int i = 0; i < permissionCount; i++) { 14176 String permission = ps.pkg.requestedPermissions.get(i); 14177 14178 BasePermission bp = mSettings.mPermissions.get(permission); 14179 if (bp == null) { 14180 continue; 14181 } 14182 14183 // If shared user we just reset the state to which only this app contributed. 14184 if (ps.sharedUser != null) { 14185 boolean used = false; 14186 final int packageCount = ps.sharedUser.packages.size(); 14187 for (int j = 0; j < packageCount; j++) { 14188 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14189 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14190 && pkg.pkg.requestedPermissions.contains(permission)) { 14191 used = true; 14192 break; 14193 } 14194 } 14195 if (used) { 14196 continue; 14197 } 14198 } 14199 14200 PermissionsState permissionsState = ps.getPermissionsState(); 14201 14202 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14203 14204 // Always clear the user settable flags. 14205 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14206 bp.name) != null; 14207 // If permission review is enabled and this is a legacy app, mark the 14208 // permission as requiring a review as this is the initial state. 14209 int flags = 0; 14210 if (Build.PERMISSIONS_REVIEW_REQUIRED 14211 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14212 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14213 } 14214 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14215 if (hasInstallState) { 14216 writeInstallPermissions = true; 14217 } else { 14218 writeRuntimePermissions = true; 14219 } 14220 } 14221 14222 // Below is only runtime permission handling. 14223 if (!bp.isRuntime()) { 14224 continue; 14225 } 14226 14227 // Never clobber system or policy. 14228 if ((oldFlags & policyOrSystemFlags) != 0) { 14229 continue; 14230 } 14231 14232 // If this permission was granted by default, make sure it is. 14233 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14234 if (permissionsState.grantRuntimePermission(bp, userId) 14235 != PERMISSION_OPERATION_FAILURE) { 14236 writeRuntimePermissions = true; 14237 } 14238 // If permission review is enabled the permissions for a legacy apps 14239 // are represented as constantly granted runtime ones, so don't revoke. 14240 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14241 // Otherwise, reset the permission. 14242 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14243 switch (revokeResult) { 14244 case PERMISSION_OPERATION_SUCCESS: { 14245 writeRuntimePermissions = true; 14246 } break; 14247 14248 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14249 writeRuntimePermissions = true; 14250 final int appId = ps.appId; 14251 mHandler.post(new Runnable() { 14252 @Override 14253 public void run() { 14254 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14255 } 14256 }); 14257 } break; 14258 } 14259 } 14260 } 14261 14262 // Synchronously write as we are taking permissions away. 14263 if (writeRuntimePermissions) { 14264 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14265 } 14266 14267 // Synchronously write as we are taking permissions away. 14268 if (writeInstallPermissions) { 14269 mSettings.writeLPr(); 14270 } 14271 } 14272 14273 /** 14274 * Remove entries from the keystore daemon. Will only remove it if the 14275 * {@code appId} is valid. 14276 */ 14277 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14278 if (appId < 0) { 14279 return; 14280 } 14281 14282 final KeyStore keyStore = KeyStore.getInstance(); 14283 if (keyStore != null) { 14284 if (userId == UserHandle.USER_ALL) { 14285 for (final int individual : sUserManager.getUserIds()) { 14286 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14287 } 14288 } else { 14289 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14290 } 14291 } else { 14292 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14293 } 14294 } 14295 14296 @Override 14297 public void deleteApplicationCacheFiles(final String packageName, 14298 final IPackageDataObserver observer) { 14299 mContext.enforceCallingOrSelfPermission( 14300 android.Manifest.permission.DELETE_CACHE_FILES, null); 14301 // Queue up an async operation since the package deletion may take a little while. 14302 final int userId = UserHandle.getCallingUserId(); 14303 mHandler.post(new Runnable() { 14304 public void run() { 14305 mHandler.removeCallbacks(this); 14306 final boolean succeded; 14307 synchronized (mInstallLock) { 14308 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14309 } 14310 clearExternalStorageDataSync(packageName, userId, false); 14311 if (observer != null) { 14312 try { 14313 observer.onRemoveCompleted(packageName, succeded); 14314 } catch (RemoteException e) { 14315 Log.i(TAG, "Observer no longer exists."); 14316 } 14317 } //end if observer 14318 } //end run 14319 }); 14320 } 14321 14322 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14323 if (packageName == null) { 14324 Slog.w(TAG, "Attempt to delete null packageName."); 14325 return false; 14326 } 14327 PackageParser.Package p; 14328 synchronized (mPackages) { 14329 p = mPackages.get(packageName); 14330 } 14331 if (p == null) { 14332 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14333 return false; 14334 } 14335 final ApplicationInfo applicationInfo = p.applicationInfo; 14336 if (applicationInfo == null) { 14337 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14338 return false; 14339 } 14340 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14341 if (retCode < 0) { 14342 Slog.w(TAG, "Couldn't remove cache files for package: " 14343 + packageName + " u" + userId); 14344 return false; 14345 } 14346 return true; 14347 } 14348 14349 @Override 14350 public void getPackageSizeInfo(final String packageName, int userHandle, 14351 final IPackageStatsObserver observer) { 14352 mContext.enforceCallingOrSelfPermission( 14353 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14354 if (packageName == null) { 14355 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14356 } 14357 14358 PackageStats stats = new PackageStats(packageName, userHandle); 14359 14360 /* 14361 * Queue up an async operation since the package measurement may take a 14362 * little while. 14363 */ 14364 Message msg = mHandler.obtainMessage(INIT_COPY); 14365 msg.obj = new MeasureParams(stats, observer); 14366 mHandler.sendMessage(msg); 14367 } 14368 14369 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14370 PackageStats pStats) { 14371 if (packageName == null) { 14372 Slog.w(TAG, "Attempt to get size of null packageName."); 14373 return false; 14374 } 14375 PackageParser.Package p; 14376 boolean dataOnly = false; 14377 String libDirRoot = null; 14378 String asecPath = null; 14379 PackageSetting ps = null; 14380 synchronized (mPackages) { 14381 p = mPackages.get(packageName); 14382 ps = mSettings.mPackages.get(packageName); 14383 if(p == null) { 14384 dataOnly = true; 14385 if((ps == null) || (ps.pkg == null)) { 14386 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14387 return false; 14388 } 14389 p = ps.pkg; 14390 } 14391 if (ps != null) { 14392 libDirRoot = ps.legacyNativeLibraryPathString; 14393 } 14394 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14395 final long token = Binder.clearCallingIdentity(); 14396 try { 14397 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14398 if (secureContainerId != null) { 14399 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14400 } 14401 } finally { 14402 Binder.restoreCallingIdentity(token); 14403 } 14404 } 14405 } 14406 String publicSrcDir = null; 14407 if(!dataOnly) { 14408 final ApplicationInfo applicationInfo = p.applicationInfo; 14409 if (applicationInfo == null) { 14410 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14411 return false; 14412 } 14413 if (p.isForwardLocked()) { 14414 publicSrcDir = applicationInfo.getBaseResourcePath(); 14415 } 14416 } 14417 // TODO: extend to measure size of split APKs 14418 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14419 // not just the first level. 14420 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14421 // just the primary. 14422 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14423 14424 String apkPath; 14425 File packageDir = new File(p.codePath); 14426 14427 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14428 apkPath = packageDir.getAbsolutePath(); 14429 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14430 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14431 libDirRoot = null; 14432 } 14433 } else { 14434 apkPath = p.baseCodePath; 14435 } 14436 14437 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14438 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14439 if (res < 0) { 14440 return false; 14441 } 14442 14443 // Fix-up for forward-locked applications in ASEC containers. 14444 if (!isExternal(p)) { 14445 pStats.codeSize += pStats.externalCodeSize; 14446 pStats.externalCodeSize = 0L; 14447 } 14448 14449 return true; 14450 } 14451 14452 14453 @Override 14454 public void addPackageToPreferred(String packageName) { 14455 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14456 } 14457 14458 @Override 14459 public void removePackageFromPreferred(String packageName) { 14460 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14461 } 14462 14463 @Override 14464 public List<PackageInfo> getPreferredPackages(int flags) { 14465 return new ArrayList<PackageInfo>(); 14466 } 14467 14468 private int getUidTargetSdkVersionLockedLPr(int uid) { 14469 Object obj = mSettings.getUserIdLPr(uid); 14470 if (obj instanceof SharedUserSetting) { 14471 final SharedUserSetting sus = (SharedUserSetting) obj; 14472 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14473 final Iterator<PackageSetting> it = sus.packages.iterator(); 14474 while (it.hasNext()) { 14475 final PackageSetting ps = it.next(); 14476 if (ps.pkg != null) { 14477 int v = ps.pkg.applicationInfo.targetSdkVersion; 14478 if (v < vers) vers = v; 14479 } 14480 } 14481 return vers; 14482 } else if (obj instanceof PackageSetting) { 14483 final PackageSetting ps = (PackageSetting) obj; 14484 if (ps.pkg != null) { 14485 return ps.pkg.applicationInfo.targetSdkVersion; 14486 } 14487 } 14488 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14489 } 14490 14491 @Override 14492 public void addPreferredActivity(IntentFilter filter, int match, 14493 ComponentName[] set, ComponentName activity, int userId) { 14494 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14495 "Adding preferred"); 14496 } 14497 14498 private void addPreferredActivityInternal(IntentFilter filter, int match, 14499 ComponentName[] set, ComponentName activity, boolean always, int userId, 14500 String opname) { 14501 // writer 14502 int callingUid = Binder.getCallingUid(); 14503 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14504 if (filter.countActions() == 0) { 14505 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14506 return; 14507 } 14508 synchronized (mPackages) { 14509 if (mContext.checkCallingOrSelfPermission( 14510 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14511 != PackageManager.PERMISSION_GRANTED) { 14512 if (getUidTargetSdkVersionLockedLPr(callingUid) 14513 < Build.VERSION_CODES.FROYO) { 14514 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14515 + callingUid); 14516 return; 14517 } 14518 mContext.enforceCallingOrSelfPermission( 14519 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14520 } 14521 14522 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14523 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14524 + userId + ":"); 14525 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14526 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14527 scheduleWritePackageRestrictionsLocked(userId); 14528 } 14529 } 14530 14531 @Override 14532 public void replacePreferredActivity(IntentFilter filter, int match, 14533 ComponentName[] set, ComponentName activity, int userId) { 14534 if (filter.countActions() != 1) { 14535 throw new IllegalArgumentException( 14536 "replacePreferredActivity expects filter to have only 1 action."); 14537 } 14538 if (filter.countDataAuthorities() != 0 14539 || filter.countDataPaths() != 0 14540 || filter.countDataSchemes() > 1 14541 || filter.countDataTypes() != 0) { 14542 throw new IllegalArgumentException( 14543 "replacePreferredActivity expects filter to have no data authorities, " + 14544 "paths, or types; and at most one scheme."); 14545 } 14546 14547 final int callingUid = Binder.getCallingUid(); 14548 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14549 synchronized (mPackages) { 14550 if (mContext.checkCallingOrSelfPermission( 14551 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14552 != PackageManager.PERMISSION_GRANTED) { 14553 if (getUidTargetSdkVersionLockedLPr(callingUid) 14554 < Build.VERSION_CODES.FROYO) { 14555 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14556 + Binder.getCallingUid()); 14557 return; 14558 } 14559 mContext.enforceCallingOrSelfPermission( 14560 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14561 } 14562 14563 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14564 if (pir != null) { 14565 // Get all of the existing entries that exactly match this filter. 14566 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14567 if (existing != null && existing.size() == 1) { 14568 PreferredActivity cur = existing.get(0); 14569 if (DEBUG_PREFERRED) { 14570 Slog.i(TAG, "Checking replace of preferred:"); 14571 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14572 if (!cur.mPref.mAlways) { 14573 Slog.i(TAG, " -- CUR; not mAlways!"); 14574 } else { 14575 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14576 Slog.i(TAG, " -- CUR: mSet=" 14577 + Arrays.toString(cur.mPref.mSetComponents)); 14578 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14579 Slog.i(TAG, " -- NEW: mMatch=" 14580 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14581 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14582 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14583 } 14584 } 14585 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14586 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14587 && cur.mPref.sameSet(set)) { 14588 // Setting the preferred activity to what it happens to be already 14589 if (DEBUG_PREFERRED) { 14590 Slog.i(TAG, "Replacing with same preferred activity " 14591 + cur.mPref.mShortComponent + " for user " 14592 + userId + ":"); 14593 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14594 } 14595 return; 14596 } 14597 } 14598 14599 if (existing != null) { 14600 if (DEBUG_PREFERRED) { 14601 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14602 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14603 } 14604 for (int i = 0; i < existing.size(); i++) { 14605 PreferredActivity pa = existing.get(i); 14606 if (DEBUG_PREFERRED) { 14607 Slog.i(TAG, "Removing existing preferred activity " 14608 + pa.mPref.mComponent + ":"); 14609 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14610 } 14611 pir.removeFilter(pa); 14612 } 14613 } 14614 } 14615 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14616 "Replacing preferred"); 14617 } 14618 } 14619 14620 @Override 14621 public void clearPackagePreferredActivities(String packageName) { 14622 final int uid = Binder.getCallingUid(); 14623 // writer 14624 synchronized (mPackages) { 14625 PackageParser.Package pkg = mPackages.get(packageName); 14626 if (pkg == null || pkg.applicationInfo.uid != uid) { 14627 if (mContext.checkCallingOrSelfPermission( 14628 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14629 != PackageManager.PERMISSION_GRANTED) { 14630 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14631 < Build.VERSION_CODES.FROYO) { 14632 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14633 + Binder.getCallingUid()); 14634 return; 14635 } 14636 mContext.enforceCallingOrSelfPermission( 14637 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14638 } 14639 } 14640 14641 int user = UserHandle.getCallingUserId(); 14642 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14643 scheduleWritePackageRestrictionsLocked(user); 14644 } 14645 } 14646 } 14647 14648 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14649 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14650 ArrayList<PreferredActivity> removed = null; 14651 boolean changed = false; 14652 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14653 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14654 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14655 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14656 continue; 14657 } 14658 Iterator<PreferredActivity> it = pir.filterIterator(); 14659 while (it.hasNext()) { 14660 PreferredActivity pa = it.next(); 14661 // Mark entry for removal only if it matches the package name 14662 // and the entry is of type "always". 14663 if (packageName == null || 14664 (pa.mPref.mComponent.getPackageName().equals(packageName) 14665 && pa.mPref.mAlways)) { 14666 if (removed == null) { 14667 removed = new ArrayList<PreferredActivity>(); 14668 } 14669 removed.add(pa); 14670 } 14671 } 14672 if (removed != null) { 14673 for (int j=0; j<removed.size(); j++) { 14674 PreferredActivity pa = removed.get(j); 14675 pir.removeFilter(pa); 14676 } 14677 changed = true; 14678 } 14679 } 14680 return changed; 14681 } 14682 14683 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14684 private void clearIntentFilterVerificationsLPw(int userId) { 14685 final int packageCount = mPackages.size(); 14686 for (int i = 0; i < packageCount; i++) { 14687 PackageParser.Package pkg = mPackages.valueAt(i); 14688 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14689 } 14690 } 14691 14692 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14693 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14694 if (userId == UserHandle.USER_ALL) { 14695 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14696 sUserManager.getUserIds())) { 14697 for (int oneUserId : sUserManager.getUserIds()) { 14698 scheduleWritePackageRestrictionsLocked(oneUserId); 14699 } 14700 } 14701 } else { 14702 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14703 scheduleWritePackageRestrictionsLocked(userId); 14704 } 14705 } 14706 } 14707 14708 void clearDefaultBrowserIfNeeded(String packageName) { 14709 for (int oneUserId : sUserManager.getUserIds()) { 14710 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14711 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14712 if (packageName.equals(defaultBrowserPackageName)) { 14713 setDefaultBrowserPackageName(null, oneUserId); 14714 } 14715 } 14716 } 14717 14718 @Override 14719 public void resetApplicationPreferences(int userId) { 14720 mContext.enforceCallingOrSelfPermission( 14721 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14722 // writer 14723 synchronized (mPackages) { 14724 final long identity = Binder.clearCallingIdentity(); 14725 try { 14726 clearPackagePreferredActivitiesLPw(null, userId); 14727 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14728 // TODO: We have to reset the default SMS and Phone. This requires 14729 // significant refactoring to keep all default apps in the package 14730 // manager (cleaner but more work) or have the services provide 14731 // callbacks to the package manager to request a default app reset. 14732 applyFactoryDefaultBrowserLPw(userId); 14733 clearIntentFilterVerificationsLPw(userId); 14734 primeDomainVerificationsLPw(userId); 14735 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14736 scheduleWritePackageRestrictionsLocked(userId); 14737 } finally { 14738 Binder.restoreCallingIdentity(identity); 14739 } 14740 } 14741 } 14742 14743 @Override 14744 public int getPreferredActivities(List<IntentFilter> outFilters, 14745 List<ComponentName> outActivities, String packageName) { 14746 14747 int num = 0; 14748 final int userId = UserHandle.getCallingUserId(); 14749 // reader 14750 synchronized (mPackages) { 14751 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14752 if (pir != null) { 14753 final Iterator<PreferredActivity> it = pir.filterIterator(); 14754 while (it.hasNext()) { 14755 final PreferredActivity pa = it.next(); 14756 if (packageName == null 14757 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14758 && pa.mPref.mAlways)) { 14759 if (outFilters != null) { 14760 outFilters.add(new IntentFilter(pa)); 14761 } 14762 if (outActivities != null) { 14763 outActivities.add(pa.mPref.mComponent); 14764 } 14765 } 14766 } 14767 } 14768 } 14769 14770 return num; 14771 } 14772 14773 @Override 14774 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14775 int userId) { 14776 int callingUid = Binder.getCallingUid(); 14777 if (callingUid != Process.SYSTEM_UID) { 14778 throw new SecurityException( 14779 "addPersistentPreferredActivity can only be run by the system"); 14780 } 14781 if (filter.countActions() == 0) { 14782 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14783 return; 14784 } 14785 synchronized (mPackages) { 14786 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14787 " :"); 14788 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14789 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14790 new PersistentPreferredActivity(filter, activity)); 14791 scheduleWritePackageRestrictionsLocked(userId); 14792 } 14793 } 14794 14795 @Override 14796 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14797 int callingUid = Binder.getCallingUid(); 14798 if (callingUid != Process.SYSTEM_UID) { 14799 throw new SecurityException( 14800 "clearPackagePersistentPreferredActivities can only be run by the system"); 14801 } 14802 ArrayList<PersistentPreferredActivity> removed = null; 14803 boolean changed = false; 14804 synchronized (mPackages) { 14805 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14806 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14807 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14808 .valueAt(i); 14809 if (userId != thisUserId) { 14810 continue; 14811 } 14812 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14813 while (it.hasNext()) { 14814 PersistentPreferredActivity ppa = it.next(); 14815 // Mark entry for removal only if it matches the package name. 14816 if (ppa.mComponent.getPackageName().equals(packageName)) { 14817 if (removed == null) { 14818 removed = new ArrayList<PersistentPreferredActivity>(); 14819 } 14820 removed.add(ppa); 14821 } 14822 } 14823 if (removed != null) { 14824 for (int j=0; j<removed.size(); j++) { 14825 PersistentPreferredActivity ppa = removed.get(j); 14826 ppir.removeFilter(ppa); 14827 } 14828 changed = true; 14829 } 14830 } 14831 14832 if (changed) { 14833 scheduleWritePackageRestrictionsLocked(userId); 14834 } 14835 } 14836 } 14837 14838 /** 14839 * Common machinery for picking apart a restored XML blob and passing 14840 * it to a caller-supplied functor to be applied to the running system. 14841 */ 14842 private void restoreFromXml(XmlPullParser parser, int userId, 14843 String expectedStartTag, BlobXmlRestorer functor) 14844 throws IOException, XmlPullParserException { 14845 int type; 14846 while ((type = parser.next()) != XmlPullParser.START_TAG 14847 && type != XmlPullParser.END_DOCUMENT) { 14848 } 14849 if (type != XmlPullParser.START_TAG) { 14850 // oops didn't find a start tag?! 14851 if (DEBUG_BACKUP) { 14852 Slog.e(TAG, "Didn't find start tag during restore"); 14853 } 14854 return; 14855 } 14856 14857 // this is supposed to be TAG_PREFERRED_BACKUP 14858 if (!expectedStartTag.equals(parser.getName())) { 14859 if (DEBUG_BACKUP) { 14860 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14861 } 14862 return; 14863 } 14864 14865 // skip interfering stuff, then we're aligned with the backing implementation 14866 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14867 functor.apply(parser, userId); 14868 } 14869 14870 private interface BlobXmlRestorer { 14871 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14872 } 14873 14874 /** 14875 * Non-Binder method, support for the backup/restore mechanism: write the 14876 * full set of preferred activities in its canonical XML format. Returns the 14877 * XML output as a byte array, or null if there is none. 14878 */ 14879 @Override 14880 public byte[] getPreferredActivityBackup(int userId) { 14881 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14882 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14883 } 14884 14885 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14886 try { 14887 final XmlSerializer serializer = new FastXmlSerializer(); 14888 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14889 serializer.startDocument(null, true); 14890 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14891 14892 synchronized (mPackages) { 14893 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14894 } 14895 14896 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14897 serializer.endDocument(); 14898 serializer.flush(); 14899 } catch (Exception e) { 14900 if (DEBUG_BACKUP) { 14901 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14902 } 14903 return null; 14904 } 14905 14906 return dataStream.toByteArray(); 14907 } 14908 14909 @Override 14910 public void restorePreferredActivities(byte[] backup, int userId) { 14911 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14912 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14913 } 14914 14915 try { 14916 final XmlPullParser parser = Xml.newPullParser(); 14917 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14918 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14919 new BlobXmlRestorer() { 14920 @Override 14921 public void apply(XmlPullParser parser, int userId) 14922 throws XmlPullParserException, IOException { 14923 synchronized (mPackages) { 14924 mSettings.readPreferredActivitiesLPw(parser, userId); 14925 } 14926 } 14927 } ); 14928 } catch (Exception e) { 14929 if (DEBUG_BACKUP) { 14930 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14931 } 14932 } 14933 } 14934 14935 /** 14936 * Non-Binder method, support for the backup/restore mechanism: write the 14937 * default browser (etc) settings in its canonical XML format. Returns the default 14938 * browser XML representation as a byte array, or null if there is none. 14939 */ 14940 @Override 14941 public byte[] getDefaultAppsBackup(int userId) { 14942 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14943 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14944 } 14945 14946 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14947 try { 14948 final XmlSerializer serializer = new FastXmlSerializer(); 14949 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14950 serializer.startDocument(null, true); 14951 serializer.startTag(null, TAG_DEFAULT_APPS); 14952 14953 synchronized (mPackages) { 14954 mSettings.writeDefaultAppsLPr(serializer, userId); 14955 } 14956 14957 serializer.endTag(null, TAG_DEFAULT_APPS); 14958 serializer.endDocument(); 14959 serializer.flush(); 14960 } catch (Exception e) { 14961 if (DEBUG_BACKUP) { 14962 Slog.e(TAG, "Unable to write default apps for backup", e); 14963 } 14964 return null; 14965 } 14966 14967 return dataStream.toByteArray(); 14968 } 14969 14970 @Override 14971 public void restoreDefaultApps(byte[] backup, int userId) { 14972 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14973 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14974 } 14975 14976 try { 14977 final XmlPullParser parser = Xml.newPullParser(); 14978 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14979 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14980 new BlobXmlRestorer() { 14981 @Override 14982 public void apply(XmlPullParser parser, int userId) 14983 throws XmlPullParserException, IOException { 14984 synchronized (mPackages) { 14985 mSettings.readDefaultAppsLPw(parser, userId); 14986 } 14987 } 14988 } ); 14989 } catch (Exception e) { 14990 if (DEBUG_BACKUP) { 14991 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14992 } 14993 } 14994 } 14995 14996 @Override 14997 public byte[] getIntentFilterVerificationBackup(int userId) { 14998 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14999 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 15000 } 15001 15002 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15003 try { 15004 final XmlSerializer serializer = new FastXmlSerializer(); 15005 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15006 serializer.startDocument(null, true); 15007 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 15008 15009 synchronized (mPackages) { 15010 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 15011 } 15012 15013 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 15014 serializer.endDocument(); 15015 serializer.flush(); 15016 } catch (Exception e) { 15017 if (DEBUG_BACKUP) { 15018 Slog.e(TAG, "Unable to write default apps for backup", e); 15019 } 15020 return null; 15021 } 15022 15023 return dataStream.toByteArray(); 15024 } 15025 15026 @Override 15027 public void restoreIntentFilterVerification(byte[] backup, int userId) { 15028 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15029 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15030 } 15031 15032 try { 15033 final XmlPullParser parser = Xml.newPullParser(); 15034 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15035 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 15036 new BlobXmlRestorer() { 15037 @Override 15038 public void apply(XmlPullParser parser, int userId) 15039 throws XmlPullParserException, IOException { 15040 synchronized (mPackages) { 15041 mSettings.readAllDomainVerificationsLPr(parser, userId); 15042 mSettings.writeLPr(); 15043 } 15044 } 15045 } ); 15046 } catch (Exception e) { 15047 if (DEBUG_BACKUP) { 15048 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15049 } 15050 } 15051 } 15052 15053 @Override 15054 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15055 int sourceUserId, int targetUserId, int flags) { 15056 mContext.enforceCallingOrSelfPermission( 15057 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15058 int callingUid = Binder.getCallingUid(); 15059 enforceOwnerRights(ownerPackage, callingUid); 15060 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15061 if (intentFilter.countActions() == 0) { 15062 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15063 return; 15064 } 15065 synchronized (mPackages) { 15066 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15067 ownerPackage, targetUserId, flags); 15068 CrossProfileIntentResolver resolver = 15069 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15070 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15071 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15072 if (existing != null) { 15073 int size = existing.size(); 15074 for (int i = 0; i < size; i++) { 15075 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15076 return; 15077 } 15078 } 15079 } 15080 resolver.addFilter(newFilter); 15081 scheduleWritePackageRestrictionsLocked(sourceUserId); 15082 } 15083 } 15084 15085 @Override 15086 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15087 mContext.enforceCallingOrSelfPermission( 15088 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15089 int callingUid = Binder.getCallingUid(); 15090 enforceOwnerRights(ownerPackage, callingUid); 15091 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15092 synchronized (mPackages) { 15093 CrossProfileIntentResolver resolver = 15094 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15095 ArraySet<CrossProfileIntentFilter> set = 15096 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15097 for (CrossProfileIntentFilter filter : set) { 15098 if (filter.getOwnerPackage().equals(ownerPackage)) { 15099 resolver.removeFilter(filter); 15100 } 15101 } 15102 scheduleWritePackageRestrictionsLocked(sourceUserId); 15103 } 15104 } 15105 15106 // Enforcing that callingUid is owning pkg on userId 15107 private void enforceOwnerRights(String pkg, int callingUid) { 15108 // The system owns everything. 15109 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15110 return; 15111 } 15112 int callingUserId = UserHandle.getUserId(callingUid); 15113 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15114 if (pi == null) { 15115 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15116 + callingUserId); 15117 } 15118 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15119 throw new SecurityException("Calling uid " + callingUid 15120 + " does not own package " + pkg); 15121 } 15122 } 15123 15124 @Override 15125 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15126 Intent intent = new Intent(Intent.ACTION_MAIN); 15127 intent.addCategory(Intent.CATEGORY_HOME); 15128 15129 final int callingUserId = UserHandle.getCallingUserId(); 15130 List<ResolveInfo> list = queryIntentActivities(intent, null, 15131 PackageManager.GET_META_DATA, callingUserId); 15132 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15133 true, false, false, callingUserId); 15134 15135 allHomeCandidates.clear(); 15136 if (list != null) { 15137 for (ResolveInfo ri : list) { 15138 allHomeCandidates.add(ri); 15139 } 15140 } 15141 return (preferred == null || preferred.activityInfo == null) 15142 ? null 15143 : new ComponentName(preferred.activityInfo.packageName, 15144 preferred.activityInfo.name); 15145 } 15146 15147 @Override 15148 public void setApplicationEnabledSetting(String appPackageName, 15149 int newState, int flags, int userId, String callingPackage) { 15150 if (!sUserManager.exists(userId)) return; 15151 if (callingPackage == null) { 15152 callingPackage = Integer.toString(Binder.getCallingUid()); 15153 } 15154 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15155 } 15156 15157 @Override 15158 public void setComponentEnabledSetting(ComponentName componentName, 15159 int newState, int flags, int userId) { 15160 if (!sUserManager.exists(userId)) return; 15161 setEnabledSetting(componentName.getPackageName(), 15162 componentName.getClassName(), newState, flags, userId, null); 15163 } 15164 15165 private void setEnabledSetting(final String packageName, String className, int newState, 15166 final int flags, int userId, String callingPackage) { 15167 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15168 || newState == COMPONENT_ENABLED_STATE_ENABLED 15169 || newState == COMPONENT_ENABLED_STATE_DISABLED 15170 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15171 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15172 throw new IllegalArgumentException("Invalid new component state: " 15173 + newState); 15174 } 15175 PackageSetting pkgSetting; 15176 final int uid = Binder.getCallingUid(); 15177 final int permission = mContext.checkCallingOrSelfPermission( 15178 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15179 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15180 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15181 boolean sendNow = false; 15182 boolean isApp = (className == null); 15183 String componentName = isApp ? packageName : className; 15184 int packageUid = -1; 15185 ArrayList<String> components; 15186 15187 // writer 15188 synchronized (mPackages) { 15189 pkgSetting = mSettings.mPackages.get(packageName); 15190 if (pkgSetting == null) { 15191 if (className == null) { 15192 throw new IllegalArgumentException( 15193 "Unknown package: " + packageName); 15194 } 15195 throw new IllegalArgumentException( 15196 "Unknown component: " + packageName 15197 + "/" + className); 15198 } 15199 // Allow root and verify that userId is not being specified by a different user 15200 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15201 throw new SecurityException( 15202 "Permission Denial: attempt to change component state from pid=" 15203 + Binder.getCallingPid() 15204 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15205 } 15206 if (className == null) { 15207 // We're dealing with an application/package level state change 15208 if (pkgSetting.getEnabled(userId) == newState) { 15209 // Nothing to do 15210 return; 15211 } 15212 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15213 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15214 // Don't care about who enables an app. 15215 callingPackage = null; 15216 } 15217 pkgSetting.setEnabled(newState, userId, callingPackage); 15218 // pkgSetting.pkg.mSetEnabled = newState; 15219 } else { 15220 // We're dealing with a component level state change 15221 // First, verify that this is a valid class name. 15222 PackageParser.Package pkg = pkgSetting.pkg; 15223 if (pkg == null || !pkg.hasComponentClassName(className)) { 15224 if (pkg != null && 15225 pkg.applicationInfo.targetSdkVersion >= 15226 Build.VERSION_CODES.JELLY_BEAN) { 15227 throw new IllegalArgumentException("Component class " + className 15228 + " does not exist in " + packageName); 15229 } else { 15230 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15231 + className + " does not exist in " + packageName); 15232 } 15233 } 15234 switch (newState) { 15235 case COMPONENT_ENABLED_STATE_ENABLED: 15236 if (!pkgSetting.enableComponentLPw(className, userId)) { 15237 return; 15238 } 15239 break; 15240 case COMPONENT_ENABLED_STATE_DISABLED: 15241 if (!pkgSetting.disableComponentLPw(className, userId)) { 15242 return; 15243 } 15244 break; 15245 case COMPONENT_ENABLED_STATE_DEFAULT: 15246 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15247 return; 15248 } 15249 break; 15250 default: 15251 Slog.e(TAG, "Invalid new component state: " + newState); 15252 return; 15253 } 15254 } 15255 scheduleWritePackageRestrictionsLocked(userId); 15256 components = mPendingBroadcasts.get(userId, packageName); 15257 final boolean newPackage = components == null; 15258 if (newPackage) { 15259 components = new ArrayList<String>(); 15260 } 15261 if (!components.contains(componentName)) { 15262 components.add(componentName); 15263 } 15264 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15265 sendNow = true; 15266 // Purge entry from pending broadcast list if another one exists already 15267 // since we are sending one right away. 15268 mPendingBroadcasts.remove(userId, packageName); 15269 } else { 15270 if (newPackage) { 15271 mPendingBroadcasts.put(userId, packageName, components); 15272 } 15273 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15274 // Schedule a message 15275 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15276 } 15277 } 15278 } 15279 15280 long callingId = Binder.clearCallingIdentity(); 15281 try { 15282 if (sendNow) { 15283 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15284 sendPackageChangedBroadcast(packageName, 15285 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15286 } 15287 } finally { 15288 Binder.restoreCallingIdentity(callingId); 15289 } 15290 } 15291 15292 private void sendPackageChangedBroadcast(String packageName, 15293 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15294 if (DEBUG_INSTALL) 15295 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15296 + componentNames); 15297 Bundle extras = new Bundle(4); 15298 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15299 String nameList[] = new String[componentNames.size()]; 15300 componentNames.toArray(nameList); 15301 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15302 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15303 extras.putInt(Intent.EXTRA_UID, packageUid); 15304 // If this is not reporting a change of the overall package, then only send it 15305 // to registered receivers. We don't want to launch a swath of apps for every 15306 // little component state change. 15307 final int flags = !componentNames.contains(packageName) 15308 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15309 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15310 new int[] {UserHandle.getUserId(packageUid)}); 15311 } 15312 15313 @Override 15314 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15315 if (!sUserManager.exists(userId)) return; 15316 final int uid = Binder.getCallingUid(); 15317 final int permission = mContext.checkCallingOrSelfPermission( 15318 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15319 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15320 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15321 // writer 15322 synchronized (mPackages) { 15323 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15324 allowedByPermission, uid, userId)) { 15325 scheduleWritePackageRestrictionsLocked(userId); 15326 } 15327 } 15328 } 15329 15330 @Override 15331 public String getInstallerPackageName(String packageName) { 15332 // reader 15333 synchronized (mPackages) { 15334 return mSettings.getInstallerPackageNameLPr(packageName); 15335 } 15336 } 15337 15338 @Override 15339 public int getApplicationEnabledSetting(String packageName, int userId) { 15340 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15341 int uid = Binder.getCallingUid(); 15342 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15343 // reader 15344 synchronized (mPackages) { 15345 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15346 } 15347 } 15348 15349 @Override 15350 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15351 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15352 int uid = Binder.getCallingUid(); 15353 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15354 // reader 15355 synchronized (mPackages) { 15356 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15357 } 15358 } 15359 15360 @Override 15361 public void enterSafeMode() { 15362 enforceSystemOrRoot("Only the system can request entering safe mode"); 15363 15364 if (!mSystemReady) { 15365 mSafeMode = true; 15366 } 15367 } 15368 15369 @Override 15370 public void systemReady() { 15371 mSystemReady = true; 15372 15373 // Read the compatibilty setting when the system is ready. 15374 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15375 mContext.getContentResolver(), 15376 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15377 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15378 if (DEBUG_SETTINGS) { 15379 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15380 } 15381 15382 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15383 15384 synchronized (mPackages) { 15385 // Verify that all of the preferred activity components actually 15386 // exist. It is possible for applications to be updated and at 15387 // that point remove a previously declared activity component that 15388 // had been set as a preferred activity. We try to clean this up 15389 // the next time we encounter that preferred activity, but it is 15390 // possible for the user flow to never be able to return to that 15391 // situation so here we do a sanity check to make sure we haven't 15392 // left any junk around. 15393 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15394 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15395 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15396 removed.clear(); 15397 for (PreferredActivity pa : pir.filterSet()) { 15398 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15399 removed.add(pa); 15400 } 15401 } 15402 if (removed.size() > 0) { 15403 for (int r=0; r<removed.size(); r++) { 15404 PreferredActivity pa = removed.get(r); 15405 Slog.w(TAG, "Removing dangling preferred activity: " 15406 + pa.mPref.mComponent); 15407 pir.removeFilter(pa); 15408 } 15409 mSettings.writePackageRestrictionsLPr( 15410 mSettings.mPreferredActivities.keyAt(i)); 15411 } 15412 } 15413 15414 for (int userId : UserManagerService.getInstance().getUserIds()) { 15415 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15416 grantPermissionsUserIds = ArrayUtils.appendInt( 15417 grantPermissionsUserIds, userId); 15418 } 15419 } 15420 } 15421 sUserManager.systemReady(); 15422 15423 // If we upgraded grant all default permissions before kicking off. 15424 for (int userId : grantPermissionsUserIds) { 15425 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15426 } 15427 15428 // Kick off any messages waiting for system ready 15429 if (mPostSystemReadyMessages != null) { 15430 for (Message msg : mPostSystemReadyMessages) { 15431 msg.sendToTarget(); 15432 } 15433 mPostSystemReadyMessages = null; 15434 } 15435 15436 // Watch for external volumes that come and go over time 15437 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15438 storage.registerListener(mStorageListener); 15439 15440 mInstallerService.systemReady(); 15441 mPackageDexOptimizer.systemReady(); 15442 15443 MountServiceInternal mountServiceInternal = LocalServices.getService( 15444 MountServiceInternal.class); 15445 mountServiceInternal.addExternalStoragePolicy( 15446 new MountServiceInternal.ExternalStorageMountPolicy() { 15447 @Override 15448 public int getMountMode(int uid, String packageName) { 15449 if (Process.isIsolated(uid)) { 15450 return Zygote.MOUNT_EXTERNAL_NONE; 15451 } 15452 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15453 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15454 } 15455 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15456 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15457 } 15458 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15459 return Zygote.MOUNT_EXTERNAL_READ; 15460 } 15461 return Zygote.MOUNT_EXTERNAL_WRITE; 15462 } 15463 15464 @Override 15465 public boolean hasExternalStorage(int uid, String packageName) { 15466 return true; 15467 } 15468 }); 15469 } 15470 15471 @Override 15472 public boolean isSafeMode() { 15473 return mSafeMode; 15474 } 15475 15476 @Override 15477 public boolean hasSystemUidErrors() { 15478 return mHasSystemUidErrors; 15479 } 15480 15481 static String arrayToString(int[] array) { 15482 StringBuffer buf = new StringBuffer(128); 15483 buf.append('['); 15484 if (array != null) { 15485 for (int i=0; i<array.length; i++) { 15486 if (i > 0) buf.append(", "); 15487 buf.append(array[i]); 15488 } 15489 } 15490 buf.append(']'); 15491 return buf.toString(); 15492 } 15493 15494 static class DumpState { 15495 public static final int DUMP_LIBS = 1 << 0; 15496 public static final int DUMP_FEATURES = 1 << 1; 15497 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15498 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15499 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15500 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15501 public static final int DUMP_PERMISSIONS = 1 << 6; 15502 public static final int DUMP_PACKAGES = 1 << 7; 15503 public static final int DUMP_SHARED_USERS = 1 << 8; 15504 public static final int DUMP_MESSAGES = 1 << 9; 15505 public static final int DUMP_PROVIDERS = 1 << 10; 15506 public static final int DUMP_VERIFIERS = 1 << 11; 15507 public static final int DUMP_PREFERRED = 1 << 12; 15508 public static final int DUMP_PREFERRED_XML = 1 << 13; 15509 public static final int DUMP_KEYSETS = 1 << 14; 15510 public static final int DUMP_VERSION = 1 << 15; 15511 public static final int DUMP_INSTALLS = 1 << 16; 15512 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15513 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15514 15515 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15516 15517 private int mTypes; 15518 15519 private int mOptions; 15520 15521 private boolean mTitlePrinted; 15522 15523 private SharedUserSetting mSharedUser; 15524 15525 public boolean isDumping(int type) { 15526 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15527 return true; 15528 } 15529 15530 return (mTypes & type) != 0; 15531 } 15532 15533 public void setDump(int type) { 15534 mTypes |= type; 15535 } 15536 15537 public boolean isOptionEnabled(int option) { 15538 return (mOptions & option) != 0; 15539 } 15540 15541 public void setOptionEnabled(int option) { 15542 mOptions |= option; 15543 } 15544 15545 public boolean onTitlePrinted() { 15546 final boolean printed = mTitlePrinted; 15547 mTitlePrinted = true; 15548 return printed; 15549 } 15550 15551 public boolean getTitlePrinted() { 15552 return mTitlePrinted; 15553 } 15554 15555 public void setTitlePrinted(boolean enabled) { 15556 mTitlePrinted = enabled; 15557 } 15558 15559 public SharedUserSetting getSharedUser() { 15560 return mSharedUser; 15561 } 15562 15563 public void setSharedUser(SharedUserSetting user) { 15564 mSharedUser = user; 15565 } 15566 } 15567 15568 @Override 15569 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15570 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15571 (new PackageManagerShellCommand(this)).exec( 15572 this, in, out, err, args, resultReceiver); 15573 } 15574 15575 @Override 15576 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15577 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15578 != PackageManager.PERMISSION_GRANTED) { 15579 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15580 + Binder.getCallingPid() 15581 + ", uid=" + Binder.getCallingUid() 15582 + " without permission " 15583 + android.Manifest.permission.DUMP); 15584 return; 15585 } 15586 15587 DumpState dumpState = new DumpState(); 15588 boolean fullPreferred = false; 15589 boolean checkin = false; 15590 15591 String packageName = null; 15592 ArraySet<String> permissionNames = null; 15593 15594 int opti = 0; 15595 while (opti < args.length) { 15596 String opt = args[opti]; 15597 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15598 break; 15599 } 15600 opti++; 15601 15602 if ("-a".equals(opt)) { 15603 // Right now we only know how to print all. 15604 } else if ("-h".equals(opt)) { 15605 pw.println("Package manager dump options:"); 15606 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15607 pw.println(" --checkin: dump for a checkin"); 15608 pw.println(" -f: print details of intent filters"); 15609 pw.println(" -h: print this help"); 15610 pw.println(" cmd may be one of:"); 15611 pw.println(" l[ibraries]: list known shared libraries"); 15612 pw.println(" f[eatures]: list device features"); 15613 pw.println(" k[eysets]: print known keysets"); 15614 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15615 pw.println(" perm[issions]: dump permissions"); 15616 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15617 pw.println(" pref[erred]: print preferred package settings"); 15618 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15619 pw.println(" prov[iders]: dump content providers"); 15620 pw.println(" p[ackages]: dump installed packages"); 15621 pw.println(" s[hared-users]: dump shared user IDs"); 15622 pw.println(" m[essages]: print collected runtime messages"); 15623 pw.println(" v[erifiers]: print package verifier info"); 15624 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15625 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15626 pw.println(" version: print database version info"); 15627 pw.println(" write: write current settings now"); 15628 pw.println(" installs: details about install sessions"); 15629 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15630 pw.println(" <package.name>: info about given package"); 15631 return; 15632 } else if ("--checkin".equals(opt)) { 15633 checkin = true; 15634 } else if ("-f".equals(opt)) { 15635 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15636 } else { 15637 pw.println("Unknown argument: " + opt + "; use -h for help"); 15638 } 15639 } 15640 15641 // Is the caller requesting to dump a particular piece of data? 15642 if (opti < args.length) { 15643 String cmd = args[opti]; 15644 opti++; 15645 // Is this a package name? 15646 if ("android".equals(cmd) || cmd.contains(".")) { 15647 packageName = cmd; 15648 // When dumping a single package, we always dump all of its 15649 // filter information since the amount of data will be reasonable. 15650 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15651 } else if ("check-permission".equals(cmd)) { 15652 if (opti >= args.length) { 15653 pw.println("Error: check-permission missing permission argument"); 15654 return; 15655 } 15656 String perm = args[opti]; 15657 opti++; 15658 if (opti >= args.length) { 15659 pw.println("Error: check-permission missing package argument"); 15660 return; 15661 } 15662 String pkg = args[opti]; 15663 opti++; 15664 int user = UserHandle.getUserId(Binder.getCallingUid()); 15665 if (opti < args.length) { 15666 try { 15667 user = Integer.parseInt(args[opti]); 15668 } catch (NumberFormatException e) { 15669 pw.println("Error: check-permission user argument is not a number: " 15670 + args[opti]); 15671 return; 15672 } 15673 } 15674 pw.println(checkPermission(perm, pkg, user)); 15675 return; 15676 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15677 dumpState.setDump(DumpState.DUMP_LIBS); 15678 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15679 dumpState.setDump(DumpState.DUMP_FEATURES); 15680 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15681 if (opti >= args.length) { 15682 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15683 | DumpState.DUMP_SERVICE_RESOLVERS 15684 | DumpState.DUMP_RECEIVER_RESOLVERS 15685 | DumpState.DUMP_CONTENT_RESOLVERS); 15686 } else { 15687 while (opti < args.length) { 15688 String name = args[opti]; 15689 if ("a".equals(name) || "activity".equals(name)) { 15690 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15691 } else if ("s".equals(name) || "service".equals(name)) { 15692 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15693 } else if ("r".equals(name) || "receiver".equals(name)) { 15694 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15695 } else if ("c".equals(name) || "content".equals(name)) { 15696 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15697 } else { 15698 pw.println("Error: unknown resolver table type: " + name); 15699 return; 15700 } 15701 opti++; 15702 } 15703 } 15704 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15705 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15706 } else if ("permission".equals(cmd)) { 15707 if (opti >= args.length) { 15708 pw.println("Error: permission requires permission name"); 15709 return; 15710 } 15711 permissionNames = new ArraySet<>(); 15712 while (opti < args.length) { 15713 permissionNames.add(args[opti]); 15714 opti++; 15715 } 15716 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15717 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15718 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15719 dumpState.setDump(DumpState.DUMP_PREFERRED); 15720 } else if ("preferred-xml".equals(cmd)) { 15721 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15722 if (opti < args.length && "--full".equals(args[opti])) { 15723 fullPreferred = true; 15724 opti++; 15725 } 15726 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15727 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15728 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15729 dumpState.setDump(DumpState.DUMP_PACKAGES); 15730 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15731 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15732 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15733 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15734 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15735 dumpState.setDump(DumpState.DUMP_MESSAGES); 15736 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15737 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15738 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15739 || "intent-filter-verifiers".equals(cmd)) { 15740 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15741 } else if ("version".equals(cmd)) { 15742 dumpState.setDump(DumpState.DUMP_VERSION); 15743 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15744 dumpState.setDump(DumpState.DUMP_KEYSETS); 15745 } else if ("installs".equals(cmd)) { 15746 dumpState.setDump(DumpState.DUMP_INSTALLS); 15747 } else if ("write".equals(cmd)) { 15748 synchronized (mPackages) { 15749 mSettings.writeLPr(); 15750 pw.println("Settings written."); 15751 return; 15752 } 15753 } 15754 } 15755 15756 if (checkin) { 15757 pw.println("vers,1"); 15758 } 15759 15760 // reader 15761 synchronized (mPackages) { 15762 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15763 if (!checkin) { 15764 if (dumpState.onTitlePrinted()) 15765 pw.println(); 15766 pw.println("Database versions:"); 15767 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15768 } 15769 } 15770 15771 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15772 if (!checkin) { 15773 if (dumpState.onTitlePrinted()) 15774 pw.println(); 15775 pw.println("Verifiers:"); 15776 pw.print(" Required: "); 15777 pw.print(mRequiredVerifierPackage); 15778 pw.print(" (uid="); 15779 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15780 pw.println(")"); 15781 } else if (mRequiredVerifierPackage != null) { 15782 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15783 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15784 } 15785 } 15786 15787 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15788 packageName == null) { 15789 if (mIntentFilterVerifierComponent != null) { 15790 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15791 if (!checkin) { 15792 if (dumpState.onTitlePrinted()) 15793 pw.println(); 15794 pw.println("Intent Filter Verifier:"); 15795 pw.print(" Using: "); 15796 pw.print(verifierPackageName); 15797 pw.print(" (uid="); 15798 pw.print(getPackageUid(verifierPackageName, 0)); 15799 pw.println(")"); 15800 } else if (verifierPackageName != null) { 15801 pw.print("ifv,"); pw.print(verifierPackageName); 15802 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15803 } 15804 } else { 15805 pw.println(); 15806 pw.println("No Intent Filter Verifier available!"); 15807 } 15808 } 15809 15810 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15811 boolean printedHeader = false; 15812 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15813 while (it.hasNext()) { 15814 String name = it.next(); 15815 SharedLibraryEntry ent = mSharedLibraries.get(name); 15816 if (!checkin) { 15817 if (!printedHeader) { 15818 if (dumpState.onTitlePrinted()) 15819 pw.println(); 15820 pw.println("Libraries:"); 15821 printedHeader = true; 15822 } 15823 pw.print(" "); 15824 } else { 15825 pw.print("lib,"); 15826 } 15827 pw.print(name); 15828 if (!checkin) { 15829 pw.print(" -> "); 15830 } 15831 if (ent.path != null) { 15832 if (!checkin) { 15833 pw.print("(jar) "); 15834 pw.print(ent.path); 15835 } else { 15836 pw.print(",jar,"); 15837 pw.print(ent.path); 15838 } 15839 } else { 15840 if (!checkin) { 15841 pw.print("(apk) "); 15842 pw.print(ent.apk); 15843 } else { 15844 pw.print(",apk,"); 15845 pw.print(ent.apk); 15846 } 15847 } 15848 pw.println(); 15849 } 15850 } 15851 15852 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15853 if (dumpState.onTitlePrinted()) 15854 pw.println(); 15855 if (!checkin) { 15856 pw.println("Features:"); 15857 } 15858 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15859 while (it.hasNext()) { 15860 String name = it.next(); 15861 if (!checkin) { 15862 pw.print(" "); 15863 } else { 15864 pw.print("feat,"); 15865 } 15866 pw.println(name); 15867 } 15868 } 15869 15870 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15871 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15872 : "Activity Resolver Table:", " ", packageName, 15873 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15874 dumpState.setTitlePrinted(true); 15875 } 15876 } 15877 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15878 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15879 : "Receiver Resolver Table:", " ", packageName, 15880 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15881 dumpState.setTitlePrinted(true); 15882 } 15883 } 15884 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15885 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15886 : "Service Resolver Table:", " ", packageName, 15887 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15888 dumpState.setTitlePrinted(true); 15889 } 15890 } 15891 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15892 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15893 : "Provider Resolver Table:", " ", packageName, 15894 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15895 dumpState.setTitlePrinted(true); 15896 } 15897 } 15898 15899 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15900 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15901 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15902 int user = mSettings.mPreferredActivities.keyAt(i); 15903 if (pir.dump(pw, 15904 dumpState.getTitlePrinted() 15905 ? "\nPreferred Activities User " + user + ":" 15906 : "Preferred Activities User " + user + ":", " ", 15907 packageName, true, false)) { 15908 dumpState.setTitlePrinted(true); 15909 } 15910 } 15911 } 15912 15913 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15914 pw.flush(); 15915 FileOutputStream fout = new FileOutputStream(fd); 15916 BufferedOutputStream str = new BufferedOutputStream(fout); 15917 XmlSerializer serializer = new FastXmlSerializer(); 15918 try { 15919 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15920 serializer.startDocument(null, true); 15921 serializer.setFeature( 15922 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15923 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15924 serializer.endDocument(); 15925 serializer.flush(); 15926 } catch (IllegalArgumentException e) { 15927 pw.println("Failed writing: " + e); 15928 } catch (IllegalStateException e) { 15929 pw.println("Failed writing: " + e); 15930 } catch (IOException e) { 15931 pw.println("Failed writing: " + e); 15932 } 15933 } 15934 15935 if (!checkin 15936 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15937 && packageName == null) { 15938 pw.println(); 15939 int count = mSettings.mPackages.size(); 15940 if (count == 0) { 15941 pw.println("No applications!"); 15942 pw.println(); 15943 } else { 15944 final String prefix = " "; 15945 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15946 if (allPackageSettings.size() == 0) { 15947 pw.println("No domain preferred apps!"); 15948 pw.println(); 15949 } else { 15950 pw.println("App verification status:"); 15951 pw.println(); 15952 count = 0; 15953 for (PackageSetting ps : allPackageSettings) { 15954 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15955 if (ivi == null || ivi.getPackageName() == null) continue; 15956 pw.println(prefix + "Package: " + ivi.getPackageName()); 15957 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15958 pw.println(prefix + "Status: " + ivi.getStatusString()); 15959 pw.println(); 15960 count++; 15961 } 15962 if (count == 0) { 15963 pw.println(prefix + "No app verification established."); 15964 pw.println(); 15965 } 15966 for (int userId : sUserManager.getUserIds()) { 15967 pw.println("App linkages for user " + userId + ":"); 15968 pw.println(); 15969 count = 0; 15970 for (PackageSetting ps : allPackageSettings) { 15971 final long status = ps.getDomainVerificationStatusForUser(userId); 15972 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15973 continue; 15974 } 15975 pw.println(prefix + "Package: " + ps.name); 15976 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15977 String statusStr = IntentFilterVerificationInfo. 15978 getStatusStringFromValue(status); 15979 pw.println(prefix + "Status: " + statusStr); 15980 pw.println(); 15981 count++; 15982 } 15983 if (count == 0) { 15984 pw.println(prefix + "No configured app linkages."); 15985 pw.println(); 15986 } 15987 } 15988 } 15989 } 15990 } 15991 15992 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15993 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15994 if (packageName == null && permissionNames == null) { 15995 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15996 if (iperm == 0) { 15997 if (dumpState.onTitlePrinted()) 15998 pw.println(); 15999 pw.println("AppOp Permissions:"); 16000 } 16001 pw.print(" AppOp Permission "); 16002 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16003 pw.println(":"); 16004 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16005 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16006 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16007 } 16008 } 16009 } 16010 } 16011 16012 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16013 boolean printedSomething = false; 16014 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16015 if (packageName != null && !packageName.equals(p.info.packageName)) { 16016 continue; 16017 } 16018 if (!printedSomething) { 16019 if (dumpState.onTitlePrinted()) 16020 pw.println(); 16021 pw.println("Registered ContentProviders:"); 16022 printedSomething = true; 16023 } 16024 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16025 pw.print(" "); pw.println(p.toString()); 16026 } 16027 printedSomething = false; 16028 for (Map.Entry<String, PackageParser.Provider> entry : 16029 mProvidersByAuthority.entrySet()) { 16030 PackageParser.Provider p = entry.getValue(); 16031 if (packageName != null && !packageName.equals(p.info.packageName)) { 16032 continue; 16033 } 16034 if (!printedSomething) { 16035 if (dumpState.onTitlePrinted()) 16036 pw.println(); 16037 pw.println("ContentProvider Authorities:"); 16038 printedSomething = true; 16039 } 16040 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16041 pw.print(" "); pw.println(p.toString()); 16042 if (p.info != null && p.info.applicationInfo != null) { 16043 final String appInfo = p.info.applicationInfo.toString(); 16044 pw.print(" applicationInfo="); pw.println(appInfo); 16045 } 16046 } 16047 } 16048 16049 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16050 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16051 } 16052 16053 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16054 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16055 } 16056 16057 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16058 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16059 } 16060 16061 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16062 // XXX should handle packageName != null by dumping only install data that 16063 // the given package is involved with. 16064 if (dumpState.onTitlePrinted()) pw.println(); 16065 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16066 } 16067 16068 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16069 if (dumpState.onTitlePrinted()) pw.println(); 16070 mSettings.dumpReadMessagesLPr(pw, dumpState); 16071 16072 pw.println(); 16073 pw.println("Package warning messages:"); 16074 BufferedReader in = null; 16075 String line = null; 16076 try { 16077 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16078 while ((line = in.readLine()) != null) { 16079 if (line.contains("ignored: updated version")) continue; 16080 pw.println(line); 16081 } 16082 } catch (IOException ignored) { 16083 } finally { 16084 IoUtils.closeQuietly(in); 16085 } 16086 } 16087 16088 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16089 BufferedReader in = null; 16090 String line = null; 16091 try { 16092 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16093 while ((line = in.readLine()) != null) { 16094 if (line.contains("ignored: updated version")) continue; 16095 pw.print("msg,"); 16096 pw.println(line); 16097 } 16098 } catch (IOException ignored) { 16099 } finally { 16100 IoUtils.closeQuietly(in); 16101 } 16102 } 16103 } 16104 } 16105 16106 private String dumpDomainString(String packageName) { 16107 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16108 List<IntentFilter> filters = getAllIntentFilters(packageName); 16109 16110 ArraySet<String> result = new ArraySet<>(); 16111 if (iviList.size() > 0) { 16112 for (IntentFilterVerificationInfo ivi : iviList) { 16113 for (String host : ivi.getDomains()) { 16114 result.add(host); 16115 } 16116 } 16117 } 16118 if (filters != null && filters.size() > 0) { 16119 for (IntentFilter filter : filters) { 16120 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16121 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16122 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16123 result.addAll(filter.getHostsList()); 16124 } 16125 } 16126 } 16127 16128 StringBuilder sb = new StringBuilder(result.size() * 16); 16129 for (String domain : result) { 16130 if (sb.length() > 0) sb.append(" "); 16131 sb.append(domain); 16132 } 16133 return sb.toString(); 16134 } 16135 16136 // ------- apps on sdcard specific code ------- 16137 static final boolean DEBUG_SD_INSTALL = false; 16138 16139 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16140 16141 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16142 16143 private boolean mMediaMounted = false; 16144 16145 static String getEncryptKey() { 16146 try { 16147 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16148 SD_ENCRYPTION_KEYSTORE_NAME); 16149 if (sdEncKey == null) { 16150 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16151 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16152 if (sdEncKey == null) { 16153 Slog.e(TAG, "Failed to create encryption keys"); 16154 return null; 16155 } 16156 } 16157 return sdEncKey; 16158 } catch (NoSuchAlgorithmException nsae) { 16159 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16160 return null; 16161 } catch (IOException ioe) { 16162 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16163 return null; 16164 } 16165 } 16166 16167 /* 16168 * Update media status on PackageManager. 16169 */ 16170 @Override 16171 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16172 int callingUid = Binder.getCallingUid(); 16173 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16174 throw new SecurityException("Media status can only be updated by the system"); 16175 } 16176 // reader; this apparently protects mMediaMounted, but should probably 16177 // be a different lock in that case. 16178 synchronized (mPackages) { 16179 Log.i(TAG, "Updating external media status from " 16180 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16181 + (mediaStatus ? "mounted" : "unmounted")); 16182 if (DEBUG_SD_INSTALL) 16183 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16184 + ", mMediaMounted=" + mMediaMounted); 16185 if (mediaStatus == mMediaMounted) { 16186 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16187 : 0, -1); 16188 mHandler.sendMessage(msg); 16189 return; 16190 } 16191 mMediaMounted = mediaStatus; 16192 } 16193 // Queue up an async operation since the package installation may take a 16194 // little while. 16195 mHandler.post(new Runnable() { 16196 public void run() { 16197 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16198 } 16199 }); 16200 } 16201 16202 /** 16203 * Called by MountService when the initial ASECs to scan are available. 16204 * Should block until all the ASEC containers are finished being scanned. 16205 */ 16206 public void scanAvailableAsecs() { 16207 updateExternalMediaStatusInner(true, false, false); 16208 if (mShouldRestoreconData) { 16209 SELinuxMMAC.setRestoreconDone(); 16210 mShouldRestoreconData = false; 16211 } 16212 } 16213 16214 /* 16215 * Collect information of applications on external media, map them against 16216 * existing containers and update information based on current mount status. 16217 * Please note that we always have to report status if reportStatus has been 16218 * set to true especially when unloading packages. 16219 */ 16220 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16221 boolean externalStorage) { 16222 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16223 int[] uidArr = EmptyArray.INT; 16224 16225 final String[] list = PackageHelper.getSecureContainerList(); 16226 if (ArrayUtils.isEmpty(list)) { 16227 Log.i(TAG, "No secure containers found"); 16228 } else { 16229 // Process list of secure containers and categorize them 16230 // as active or stale based on their package internal state. 16231 16232 // reader 16233 synchronized (mPackages) { 16234 for (String cid : list) { 16235 // Leave stages untouched for now; installer service owns them 16236 if (PackageInstallerService.isStageName(cid)) continue; 16237 16238 if (DEBUG_SD_INSTALL) 16239 Log.i(TAG, "Processing container " + cid); 16240 String pkgName = getAsecPackageName(cid); 16241 if (pkgName == null) { 16242 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16243 continue; 16244 } 16245 if (DEBUG_SD_INSTALL) 16246 Log.i(TAG, "Looking for pkg : " + pkgName); 16247 16248 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16249 if (ps == null) { 16250 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16251 continue; 16252 } 16253 16254 /* 16255 * Skip packages that are not external if we're unmounting 16256 * external storage. 16257 */ 16258 if (externalStorage && !isMounted && !isExternal(ps)) { 16259 continue; 16260 } 16261 16262 final AsecInstallArgs args = new AsecInstallArgs(cid, 16263 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16264 // The package status is changed only if the code path 16265 // matches between settings and the container id. 16266 if (ps.codePathString != null 16267 && ps.codePathString.startsWith(args.getCodePath())) { 16268 if (DEBUG_SD_INSTALL) { 16269 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16270 + " at code path: " + ps.codePathString); 16271 } 16272 16273 // We do have a valid package installed on sdcard 16274 processCids.put(args, ps.codePathString); 16275 final int uid = ps.appId; 16276 if (uid != -1) { 16277 uidArr = ArrayUtils.appendInt(uidArr, uid); 16278 } 16279 } else { 16280 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16281 + ps.codePathString); 16282 } 16283 } 16284 } 16285 16286 Arrays.sort(uidArr); 16287 } 16288 16289 // Process packages with valid entries. 16290 if (isMounted) { 16291 if (DEBUG_SD_INSTALL) 16292 Log.i(TAG, "Loading packages"); 16293 loadMediaPackages(processCids, uidArr, externalStorage); 16294 startCleaningPackages(); 16295 mInstallerService.onSecureContainersAvailable(); 16296 } else { 16297 if (DEBUG_SD_INSTALL) 16298 Log.i(TAG, "Unloading packages"); 16299 unloadMediaPackages(processCids, uidArr, reportStatus); 16300 } 16301 } 16302 16303 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16304 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16305 final int size = infos.size(); 16306 final String[] packageNames = new String[size]; 16307 final int[] packageUids = new int[size]; 16308 for (int i = 0; i < size; i++) { 16309 final ApplicationInfo info = infos.get(i); 16310 packageNames[i] = info.packageName; 16311 packageUids[i] = info.uid; 16312 } 16313 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16314 finishedReceiver); 16315 } 16316 16317 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16318 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16319 sendResourcesChangedBroadcast(mediaStatus, replacing, 16320 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16321 } 16322 16323 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16324 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16325 int size = pkgList.length; 16326 if (size > 0) { 16327 // Send broadcasts here 16328 Bundle extras = new Bundle(); 16329 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16330 if (uidArr != null) { 16331 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16332 } 16333 if (replacing) { 16334 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16335 } 16336 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16337 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16338 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16339 } 16340 } 16341 16342 /* 16343 * Look at potentially valid container ids from processCids If package 16344 * information doesn't match the one on record or package scanning fails, 16345 * the cid is added to list of removeCids. We currently don't delete stale 16346 * containers. 16347 */ 16348 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16349 boolean externalStorage) { 16350 ArrayList<String> pkgList = new ArrayList<String>(); 16351 Set<AsecInstallArgs> keys = processCids.keySet(); 16352 16353 for (AsecInstallArgs args : keys) { 16354 String codePath = processCids.get(args); 16355 if (DEBUG_SD_INSTALL) 16356 Log.i(TAG, "Loading container : " + args.cid); 16357 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16358 try { 16359 // Make sure there are no container errors first. 16360 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16361 Slog.e(TAG, "Failed to mount cid : " + args.cid 16362 + " when installing from sdcard"); 16363 continue; 16364 } 16365 // Check code path here. 16366 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16367 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16368 + " does not match one in settings " + codePath); 16369 continue; 16370 } 16371 // Parse package 16372 int parseFlags = mDefParseFlags; 16373 if (args.isExternalAsec()) { 16374 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16375 } 16376 if (args.isFwdLocked()) { 16377 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16378 } 16379 16380 synchronized (mInstallLock) { 16381 PackageParser.Package pkg = null; 16382 try { 16383 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16384 } catch (PackageManagerException e) { 16385 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16386 } 16387 // Scan the package 16388 if (pkg != null) { 16389 /* 16390 * TODO why is the lock being held? doPostInstall is 16391 * called in other places without the lock. This needs 16392 * to be straightened out. 16393 */ 16394 // writer 16395 synchronized (mPackages) { 16396 retCode = PackageManager.INSTALL_SUCCEEDED; 16397 pkgList.add(pkg.packageName); 16398 // Post process args 16399 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16400 pkg.applicationInfo.uid); 16401 } 16402 } else { 16403 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16404 } 16405 } 16406 16407 } finally { 16408 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16409 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16410 } 16411 } 16412 } 16413 // writer 16414 synchronized (mPackages) { 16415 // If the platform SDK has changed since the last time we booted, 16416 // we need to re-grant app permission to catch any new ones that 16417 // appear. This is really a hack, and means that apps can in some 16418 // cases get permissions that the user didn't initially explicitly 16419 // allow... it would be nice to have some better way to handle 16420 // this situation. 16421 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16422 : mSettings.getInternalVersion(); 16423 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16424 : StorageManager.UUID_PRIVATE_INTERNAL; 16425 16426 int updateFlags = UPDATE_PERMISSIONS_ALL; 16427 if (ver.sdkVersion != mSdkVersion) { 16428 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16429 + mSdkVersion + "; regranting permissions for external"); 16430 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16431 } 16432 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16433 16434 // Yay, everything is now upgraded 16435 ver.forceCurrent(); 16436 16437 // can downgrade to reader 16438 // Persist settings 16439 mSettings.writeLPr(); 16440 } 16441 // Send a broadcast to let everyone know we are done processing 16442 if (pkgList.size() > 0) { 16443 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16444 } 16445 } 16446 16447 /* 16448 * Utility method to unload a list of specified containers 16449 */ 16450 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16451 // Just unmount all valid containers. 16452 for (AsecInstallArgs arg : cidArgs) { 16453 synchronized (mInstallLock) { 16454 arg.doPostDeleteLI(false); 16455 } 16456 } 16457 } 16458 16459 /* 16460 * Unload packages mounted on external media. This involves deleting package 16461 * data from internal structures, sending broadcasts about diabled packages, 16462 * gc'ing to free up references, unmounting all secure containers 16463 * corresponding to packages on external media, and posting a 16464 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16465 * that we always have to post this message if status has been requested no 16466 * matter what. 16467 */ 16468 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16469 final boolean reportStatus) { 16470 if (DEBUG_SD_INSTALL) 16471 Log.i(TAG, "unloading media packages"); 16472 ArrayList<String> pkgList = new ArrayList<String>(); 16473 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16474 final Set<AsecInstallArgs> keys = processCids.keySet(); 16475 for (AsecInstallArgs args : keys) { 16476 String pkgName = args.getPackageName(); 16477 if (DEBUG_SD_INSTALL) 16478 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16479 // Delete package internally 16480 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16481 synchronized (mInstallLock) { 16482 boolean res = deletePackageLI(pkgName, null, false, null, null, 16483 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16484 if (res) { 16485 pkgList.add(pkgName); 16486 } else { 16487 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16488 failedList.add(args); 16489 } 16490 } 16491 } 16492 16493 // reader 16494 synchronized (mPackages) { 16495 // We didn't update the settings after removing each package; 16496 // write them now for all packages. 16497 mSettings.writeLPr(); 16498 } 16499 16500 // We have to absolutely send UPDATED_MEDIA_STATUS only 16501 // after confirming that all the receivers processed the ordered 16502 // broadcast when packages get disabled, force a gc to clean things up. 16503 // and unload all the containers. 16504 if (pkgList.size() > 0) { 16505 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16506 new IIntentReceiver.Stub() { 16507 public void performReceive(Intent intent, int resultCode, String data, 16508 Bundle extras, boolean ordered, boolean sticky, 16509 int sendingUser) throws RemoteException { 16510 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16511 reportStatus ? 1 : 0, 1, keys); 16512 mHandler.sendMessage(msg); 16513 } 16514 }); 16515 } else { 16516 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16517 keys); 16518 mHandler.sendMessage(msg); 16519 } 16520 } 16521 16522 private void loadPrivatePackages(final VolumeInfo vol) { 16523 mHandler.post(new Runnable() { 16524 @Override 16525 public void run() { 16526 loadPrivatePackagesInner(vol); 16527 } 16528 }); 16529 } 16530 16531 private void loadPrivatePackagesInner(VolumeInfo vol) { 16532 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16533 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16534 16535 final VersionInfo ver; 16536 final List<PackageSetting> packages; 16537 synchronized (mPackages) { 16538 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16539 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16540 } 16541 16542 for (PackageSetting ps : packages) { 16543 synchronized (mInstallLock) { 16544 final PackageParser.Package pkg; 16545 try { 16546 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16547 loaded.add(pkg.applicationInfo); 16548 } catch (PackageManagerException e) { 16549 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16550 } 16551 16552 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16553 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16554 } 16555 } 16556 } 16557 16558 synchronized (mPackages) { 16559 int updateFlags = UPDATE_PERMISSIONS_ALL; 16560 if (ver.sdkVersion != mSdkVersion) { 16561 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16562 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16563 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16564 } 16565 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16566 16567 // Yay, everything is now upgraded 16568 ver.forceCurrent(); 16569 16570 mSettings.writeLPr(); 16571 } 16572 16573 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16574 sendResourcesChangedBroadcast(true, false, loaded, null); 16575 } 16576 16577 private void unloadPrivatePackages(final VolumeInfo vol) { 16578 mHandler.post(new Runnable() { 16579 @Override 16580 public void run() { 16581 unloadPrivatePackagesInner(vol); 16582 } 16583 }); 16584 } 16585 16586 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16587 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16588 synchronized (mInstallLock) { 16589 synchronized (mPackages) { 16590 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16591 for (PackageSetting ps : packages) { 16592 if (ps.pkg == null) continue; 16593 16594 final ApplicationInfo info = ps.pkg.applicationInfo; 16595 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16596 if (deletePackageLI(ps.name, null, false, null, null, 16597 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16598 unloaded.add(info); 16599 } else { 16600 Slog.w(TAG, "Failed to unload " + ps.codePath); 16601 } 16602 } 16603 16604 mSettings.writeLPr(); 16605 } 16606 } 16607 16608 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16609 sendResourcesChangedBroadcast(false, false, unloaded, null); 16610 } 16611 16612 /** 16613 * Examine all users present on given mounted volume, and destroy data 16614 * belonging to users that are no longer valid, or whose user ID has been 16615 * recycled. 16616 */ 16617 private void reconcileUsers(String volumeUuid) { 16618 final File[] files = FileUtils 16619 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16620 for (File file : files) { 16621 if (!file.isDirectory()) continue; 16622 16623 final int userId; 16624 final UserInfo info; 16625 try { 16626 userId = Integer.parseInt(file.getName()); 16627 info = sUserManager.getUserInfo(userId); 16628 } catch (NumberFormatException e) { 16629 Slog.w(TAG, "Invalid user directory " + file); 16630 continue; 16631 } 16632 16633 boolean destroyUser = false; 16634 if (info == null) { 16635 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16636 + " because no matching user was found"); 16637 destroyUser = true; 16638 } else { 16639 try { 16640 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16641 } catch (IOException e) { 16642 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16643 + " because we failed to enforce serial number: " + e); 16644 destroyUser = true; 16645 } 16646 } 16647 16648 if (destroyUser) { 16649 synchronized (mInstallLock) { 16650 mInstaller.removeUserDataDirs(volumeUuid, userId); 16651 } 16652 } 16653 } 16654 16655 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16656 final UserManager um = mContext.getSystemService(UserManager.class); 16657 for (UserInfo user : um.getUsers()) { 16658 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16659 if (userDir.exists()) continue; 16660 16661 try { 16662 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16663 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16664 } catch (IOException e) { 16665 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16666 } 16667 } 16668 } 16669 16670 /** 16671 * Examine all apps present on given mounted volume, and destroy apps that 16672 * aren't expected, either due to uninstallation or reinstallation on 16673 * another volume. 16674 */ 16675 private void reconcileApps(String volumeUuid) { 16676 final File[] files = FileUtils 16677 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16678 for (File file : files) { 16679 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16680 && !PackageInstallerService.isStageName(file.getName()); 16681 if (!isPackage) { 16682 // Ignore entries which are not packages 16683 continue; 16684 } 16685 16686 boolean destroyApp = false; 16687 String packageName = null; 16688 try { 16689 final PackageLite pkg = PackageParser.parsePackageLite(file, 16690 PackageParser.PARSE_MUST_BE_APK); 16691 packageName = pkg.packageName; 16692 16693 synchronized (mPackages) { 16694 final PackageSetting ps = mSettings.mPackages.get(packageName); 16695 if (ps == null) { 16696 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16697 + volumeUuid + " because we found no install record"); 16698 destroyApp = true; 16699 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16700 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16701 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16702 destroyApp = true; 16703 } 16704 } 16705 16706 } catch (PackageParserException e) { 16707 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16708 destroyApp = true; 16709 } 16710 16711 if (destroyApp) { 16712 synchronized (mInstallLock) { 16713 if (packageName != null) { 16714 removeDataDirsLI(volumeUuid, packageName); 16715 } 16716 if (file.isDirectory()) { 16717 mInstaller.rmPackageDir(file.getAbsolutePath()); 16718 } else { 16719 file.delete(); 16720 } 16721 } 16722 } 16723 } 16724 } 16725 16726 private void unfreezePackage(String packageName) { 16727 synchronized (mPackages) { 16728 final PackageSetting ps = mSettings.mPackages.get(packageName); 16729 if (ps != null) { 16730 ps.frozen = false; 16731 } 16732 } 16733 } 16734 16735 @Override 16736 public int movePackage(final String packageName, final String volumeUuid) { 16737 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16738 16739 final int moveId = mNextMoveId.getAndIncrement(); 16740 mHandler.post(new Runnable() { 16741 @Override 16742 public void run() { 16743 try { 16744 movePackageInternal(packageName, volumeUuid, moveId); 16745 } catch (PackageManagerException e) { 16746 Slog.w(TAG, "Failed to move " + packageName, e); 16747 mMoveCallbacks.notifyStatusChanged(moveId, 16748 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16749 } 16750 } 16751 }); 16752 return moveId; 16753 } 16754 16755 private void movePackageInternal(final String packageName, final String volumeUuid, 16756 final int moveId) throws PackageManagerException { 16757 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16758 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16759 final PackageManager pm = mContext.getPackageManager(); 16760 16761 final boolean currentAsec; 16762 final String currentVolumeUuid; 16763 final File codeFile; 16764 final String installerPackageName; 16765 final String packageAbiOverride; 16766 final int appId; 16767 final String seinfo; 16768 final String label; 16769 16770 // reader 16771 synchronized (mPackages) { 16772 final PackageParser.Package pkg = mPackages.get(packageName); 16773 final PackageSetting ps = mSettings.mPackages.get(packageName); 16774 if (pkg == null || ps == null) { 16775 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16776 } 16777 16778 if (pkg.applicationInfo.isSystemApp()) { 16779 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16780 "Cannot move system application"); 16781 } 16782 16783 if (pkg.applicationInfo.isExternalAsec()) { 16784 currentAsec = true; 16785 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16786 } else if (pkg.applicationInfo.isForwardLocked()) { 16787 currentAsec = true; 16788 currentVolumeUuid = "forward_locked"; 16789 } else { 16790 currentAsec = false; 16791 currentVolumeUuid = ps.volumeUuid; 16792 16793 final File probe = new File(pkg.codePath); 16794 final File probeOat = new File(probe, "oat"); 16795 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16796 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16797 "Move only supported for modern cluster style installs"); 16798 } 16799 } 16800 16801 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16802 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16803 "Package already moved to " + volumeUuid); 16804 } 16805 16806 if (ps.frozen) { 16807 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16808 "Failed to move already frozen package"); 16809 } 16810 ps.frozen = true; 16811 16812 codeFile = new File(pkg.codePath); 16813 installerPackageName = ps.installerPackageName; 16814 packageAbiOverride = ps.cpuAbiOverrideString; 16815 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16816 seinfo = pkg.applicationInfo.seinfo; 16817 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16818 } 16819 16820 // Now that we're guarded by frozen state, kill app during move 16821 final long token = Binder.clearCallingIdentity(); 16822 try { 16823 killApplication(packageName, appId, "move pkg"); 16824 } finally { 16825 Binder.restoreCallingIdentity(token); 16826 } 16827 16828 final Bundle extras = new Bundle(); 16829 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16830 extras.putString(Intent.EXTRA_TITLE, label); 16831 mMoveCallbacks.notifyCreated(moveId, extras); 16832 16833 int installFlags; 16834 final boolean moveCompleteApp; 16835 final File measurePath; 16836 16837 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16838 installFlags = INSTALL_INTERNAL; 16839 moveCompleteApp = !currentAsec; 16840 measurePath = Environment.getDataAppDirectory(volumeUuid); 16841 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16842 installFlags = INSTALL_EXTERNAL; 16843 moveCompleteApp = false; 16844 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16845 } else { 16846 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16847 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16848 || !volume.isMountedWritable()) { 16849 unfreezePackage(packageName); 16850 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16851 "Move location not mounted private volume"); 16852 } 16853 16854 Preconditions.checkState(!currentAsec); 16855 16856 installFlags = INSTALL_INTERNAL; 16857 moveCompleteApp = true; 16858 measurePath = Environment.getDataAppDirectory(volumeUuid); 16859 } 16860 16861 final PackageStats stats = new PackageStats(null, -1); 16862 synchronized (mInstaller) { 16863 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16864 unfreezePackage(packageName); 16865 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16866 "Failed to measure package size"); 16867 } 16868 } 16869 16870 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16871 + stats.dataSize); 16872 16873 final long startFreeBytes = measurePath.getFreeSpace(); 16874 final long sizeBytes; 16875 if (moveCompleteApp) { 16876 sizeBytes = stats.codeSize + stats.dataSize; 16877 } else { 16878 sizeBytes = stats.codeSize; 16879 } 16880 16881 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16882 unfreezePackage(packageName); 16883 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16884 "Not enough free space to move"); 16885 } 16886 16887 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16888 16889 final CountDownLatch installedLatch = new CountDownLatch(1); 16890 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16891 @Override 16892 public void onUserActionRequired(Intent intent) throws RemoteException { 16893 throw new IllegalStateException(); 16894 } 16895 16896 @Override 16897 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16898 Bundle extras) throws RemoteException { 16899 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16900 + PackageManager.installStatusToString(returnCode, msg)); 16901 16902 installedLatch.countDown(); 16903 16904 // Regardless of success or failure of the move operation, 16905 // always unfreeze the package 16906 unfreezePackage(packageName); 16907 16908 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16909 switch (status) { 16910 case PackageInstaller.STATUS_SUCCESS: 16911 mMoveCallbacks.notifyStatusChanged(moveId, 16912 PackageManager.MOVE_SUCCEEDED); 16913 break; 16914 case PackageInstaller.STATUS_FAILURE_STORAGE: 16915 mMoveCallbacks.notifyStatusChanged(moveId, 16916 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16917 break; 16918 default: 16919 mMoveCallbacks.notifyStatusChanged(moveId, 16920 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16921 break; 16922 } 16923 } 16924 }; 16925 16926 final MoveInfo move; 16927 if (moveCompleteApp) { 16928 // Kick off a thread to report progress estimates 16929 new Thread() { 16930 @Override 16931 public void run() { 16932 while (true) { 16933 try { 16934 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16935 break; 16936 } 16937 } catch (InterruptedException ignored) { 16938 } 16939 16940 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16941 final int progress = 10 + (int) MathUtils.constrain( 16942 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16943 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16944 } 16945 } 16946 }.start(); 16947 16948 final String dataAppName = codeFile.getName(); 16949 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16950 dataAppName, appId, seinfo); 16951 } else { 16952 move = null; 16953 } 16954 16955 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16956 16957 final Message msg = mHandler.obtainMessage(INIT_COPY); 16958 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16959 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16960 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16961 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16962 msg.obj = params; 16963 16964 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16965 System.identityHashCode(msg.obj)); 16966 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16967 System.identityHashCode(msg.obj)); 16968 16969 mHandler.sendMessage(msg); 16970 } 16971 16972 @Override 16973 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16974 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16975 16976 final int realMoveId = mNextMoveId.getAndIncrement(); 16977 final Bundle extras = new Bundle(); 16978 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16979 mMoveCallbacks.notifyCreated(realMoveId, extras); 16980 16981 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16982 @Override 16983 public void onCreated(int moveId, Bundle extras) { 16984 // Ignored 16985 } 16986 16987 @Override 16988 public void onStatusChanged(int moveId, int status, long estMillis) { 16989 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16990 } 16991 }; 16992 16993 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16994 storage.setPrimaryStorageUuid(volumeUuid, callback); 16995 return realMoveId; 16996 } 16997 16998 @Override 16999 public int getMoveStatus(int moveId) { 17000 mContext.enforceCallingOrSelfPermission( 17001 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17002 return mMoveCallbacks.mLastStatus.get(moveId); 17003 } 17004 17005 @Override 17006 public void registerMoveCallback(IPackageMoveObserver callback) { 17007 mContext.enforceCallingOrSelfPermission( 17008 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17009 mMoveCallbacks.register(callback); 17010 } 17011 17012 @Override 17013 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17014 mContext.enforceCallingOrSelfPermission( 17015 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17016 mMoveCallbacks.unregister(callback); 17017 } 17018 17019 @Override 17020 public boolean setInstallLocation(int loc) { 17021 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17022 null); 17023 if (getInstallLocation() == loc) { 17024 return true; 17025 } 17026 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17027 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17028 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17029 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17030 return true; 17031 } 17032 return false; 17033 } 17034 17035 @Override 17036 public int getInstallLocation() { 17037 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17038 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17039 PackageHelper.APP_INSTALL_AUTO); 17040 } 17041 17042 /** Called by UserManagerService */ 17043 void cleanUpUser(UserManagerService userManager, int userHandle) { 17044 synchronized (mPackages) { 17045 mDirtyUsers.remove(userHandle); 17046 mUserNeedsBadging.delete(userHandle); 17047 mSettings.removeUserLPw(userHandle); 17048 mPendingBroadcasts.remove(userHandle); 17049 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17050 } 17051 synchronized (mInstallLock) { 17052 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17053 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17054 final String volumeUuid = vol.getFsUuid(); 17055 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17056 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17057 } 17058 synchronized (mPackages) { 17059 removeUnusedPackagesLILPw(userManager, userHandle); 17060 } 17061 } 17062 } 17063 17064 /** 17065 * We're removing userHandle and would like to remove any downloaded packages 17066 * that are no longer in use by any other user. 17067 * @param userHandle the user being removed 17068 */ 17069 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17070 final boolean DEBUG_CLEAN_APKS = false; 17071 int [] users = userManager.getUserIds(); 17072 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17073 while (psit.hasNext()) { 17074 PackageSetting ps = psit.next(); 17075 if (ps.pkg == null) { 17076 continue; 17077 } 17078 final String packageName = ps.pkg.packageName; 17079 // Skip over if system app 17080 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17081 continue; 17082 } 17083 if (DEBUG_CLEAN_APKS) { 17084 Slog.i(TAG, "Checking package " + packageName); 17085 } 17086 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17087 if (keep) { 17088 if (DEBUG_CLEAN_APKS) { 17089 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17090 } 17091 } else { 17092 for (int i = 0; i < users.length; i++) { 17093 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17094 keep = true; 17095 if (DEBUG_CLEAN_APKS) { 17096 Slog.i(TAG, " Keeping package " + packageName + " for user " 17097 + users[i]); 17098 } 17099 break; 17100 } 17101 } 17102 } 17103 if (!keep) { 17104 if (DEBUG_CLEAN_APKS) { 17105 Slog.i(TAG, " Removing package " + packageName); 17106 } 17107 mHandler.post(new Runnable() { 17108 public void run() { 17109 deletePackageX(packageName, userHandle, 0); 17110 } //end run 17111 }); 17112 } 17113 } 17114 } 17115 17116 /** Called by UserManagerService */ 17117 void createNewUser(int userHandle) { 17118 synchronized (mInstallLock) { 17119 mInstaller.createUserConfig(userHandle); 17120 mSettings.createNewUserLI(this, mInstaller, userHandle); 17121 } 17122 synchronized (mPackages) { 17123 applyFactoryDefaultBrowserLPw(userHandle); 17124 primeDomainVerificationsLPw(userHandle); 17125 } 17126 } 17127 17128 void newUserCreated(final int userHandle) { 17129 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17130 // If permission review for legacy apps is required, we represent 17131 // dagerous permissions for such apps as always granted runtime 17132 // permissions to keep per user flag state whether review is needed. 17133 // Hence, if a new user is added we have to propagate dangerous 17134 // permission grants for these legacy apps. 17135 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17136 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17137 | UPDATE_PERMISSIONS_REPLACE_ALL); 17138 } 17139 } 17140 17141 @Override 17142 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17143 mContext.enforceCallingOrSelfPermission( 17144 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17145 "Only package verification agents can read the verifier device identity"); 17146 17147 synchronized (mPackages) { 17148 return mSettings.getVerifierDeviceIdentityLPw(); 17149 } 17150 } 17151 17152 @Override 17153 public void setPermissionEnforced(String permission, boolean enforced) { 17154 // TODO: Now that we no longer change GID for storage, this should to away. 17155 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17156 "setPermissionEnforced"); 17157 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17158 synchronized (mPackages) { 17159 if (mSettings.mReadExternalStorageEnforced == null 17160 || mSettings.mReadExternalStorageEnforced != enforced) { 17161 mSettings.mReadExternalStorageEnforced = enforced; 17162 mSettings.writeLPr(); 17163 } 17164 } 17165 // kill any non-foreground processes so we restart them and 17166 // grant/revoke the GID. 17167 final IActivityManager am = ActivityManagerNative.getDefault(); 17168 if (am != null) { 17169 final long token = Binder.clearCallingIdentity(); 17170 try { 17171 am.killProcessesBelowForeground("setPermissionEnforcement"); 17172 } catch (RemoteException e) { 17173 } finally { 17174 Binder.restoreCallingIdentity(token); 17175 } 17176 } 17177 } else { 17178 throw new IllegalArgumentException("No selective enforcement for " + permission); 17179 } 17180 } 17181 17182 @Override 17183 @Deprecated 17184 public boolean isPermissionEnforced(String permission) { 17185 return true; 17186 } 17187 17188 @Override 17189 public boolean isStorageLow() { 17190 final long token = Binder.clearCallingIdentity(); 17191 try { 17192 final DeviceStorageMonitorInternal 17193 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17194 if (dsm != null) { 17195 return dsm.isMemoryLow(); 17196 } else { 17197 return false; 17198 } 17199 } finally { 17200 Binder.restoreCallingIdentity(token); 17201 } 17202 } 17203 17204 @Override 17205 public IPackageInstaller getPackageInstaller() { 17206 return mInstallerService; 17207 } 17208 17209 private boolean userNeedsBadging(int userId) { 17210 int index = mUserNeedsBadging.indexOfKey(userId); 17211 if (index < 0) { 17212 final UserInfo userInfo; 17213 final long token = Binder.clearCallingIdentity(); 17214 try { 17215 userInfo = sUserManager.getUserInfo(userId); 17216 } finally { 17217 Binder.restoreCallingIdentity(token); 17218 } 17219 final boolean b; 17220 if (userInfo != null && userInfo.isManagedProfile()) { 17221 b = true; 17222 } else { 17223 b = false; 17224 } 17225 mUserNeedsBadging.put(userId, b); 17226 return b; 17227 } 17228 return mUserNeedsBadging.valueAt(index); 17229 } 17230 17231 @Override 17232 public KeySet getKeySetByAlias(String packageName, String alias) { 17233 if (packageName == null || alias == null) { 17234 return null; 17235 } 17236 synchronized(mPackages) { 17237 final PackageParser.Package pkg = mPackages.get(packageName); 17238 if (pkg == null) { 17239 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17240 throw new IllegalArgumentException("Unknown package: " + packageName); 17241 } 17242 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17243 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17244 } 17245 } 17246 17247 @Override 17248 public KeySet getSigningKeySet(String packageName) { 17249 if (packageName == null) { 17250 return null; 17251 } 17252 synchronized(mPackages) { 17253 final PackageParser.Package pkg = mPackages.get(packageName); 17254 if (pkg == null) { 17255 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17256 throw new IllegalArgumentException("Unknown package: " + packageName); 17257 } 17258 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17259 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17260 throw new SecurityException("May not access signing KeySet of other apps."); 17261 } 17262 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17263 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17264 } 17265 } 17266 17267 @Override 17268 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17269 if (packageName == null || ks == null) { 17270 return false; 17271 } 17272 synchronized(mPackages) { 17273 final PackageParser.Package pkg = mPackages.get(packageName); 17274 if (pkg == null) { 17275 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17276 throw new IllegalArgumentException("Unknown package: " + packageName); 17277 } 17278 IBinder ksh = ks.getToken(); 17279 if (ksh instanceof KeySetHandle) { 17280 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17281 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17282 } 17283 return false; 17284 } 17285 } 17286 17287 @Override 17288 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17289 if (packageName == null || ks == null) { 17290 return false; 17291 } 17292 synchronized(mPackages) { 17293 final PackageParser.Package pkg = mPackages.get(packageName); 17294 if (pkg == null) { 17295 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17296 throw new IllegalArgumentException("Unknown package: " + packageName); 17297 } 17298 IBinder ksh = ks.getToken(); 17299 if (ksh instanceof KeySetHandle) { 17300 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17301 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17302 } 17303 return false; 17304 } 17305 } 17306 17307 private void deletePackageIfUnusedLPr(final String packageName) { 17308 PackageSetting ps = mSettings.mPackages.get(packageName); 17309 if (ps == null) { 17310 return; 17311 } 17312 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17313 // TODO Implement atomic delete if package is unused 17314 // It is currently possible that the package will be deleted even if it is installed 17315 // after this method returns. 17316 mHandler.post(new Runnable() { 17317 public void run() { 17318 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17319 } 17320 }); 17321 } 17322 } 17323 17324 /** 17325 * Check and throw if the given before/after packages would be considered a 17326 * downgrade. 17327 */ 17328 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17329 throws PackageManagerException { 17330 if (after.versionCode < before.mVersionCode) { 17331 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17332 "Update version code " + after.versionCode + " is older than current " 17333 + before.mVersionCode); 17334 } else if (after.versionCode == before.mVersionCode) { 17335 if (after.baseRevisionCode < before.baseRevisionCode) { 17336 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17337 "Update base revision code " + after.baseRevisionCode 17338 + " is older than current " + before.baseRevisionCode); 17339 } 17340 17341 if (!ArrayUtils.isEmpty(after.splitNames)) { 17342 for (int i = 0; i < after.splitNames.length; i++) { 17343 final String splitName = after.splitNames[i]; 17344 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17345 if (j != -1) { 17346 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17347 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17348 "Update split " + splitName + " revision code " 17349 + after.splitRevisionCodes[i] + " is older than current " 17350 + before.splitRevisionCodes[j]); 17351 } 17352 } 17353 } 17354 } 17355 } 17356 } 17357 17358 private static class MoveCallbacks extends Handler { 17359 private static final int MSG_CREATED = 1; 17360 private static final int MSG_STATUS_CHANGED = 2; 17361 17362 private final RemoteCallbackList<IPackageMoveObserver> 17363 mCallbacks = new RemoteCallbackList<>(); 17364 17365 private final SparseIntArray mLastStatus = new SparseIntArray(); 17366 17367 public MoveCallbacks(Looper looper) { 17368 super(looper); 17369 } 17370 17371 public void register(IPackageMoveObserver callback) { 17372 mCallbacks.register(callback); 17373 } 17374 17375 public void unregister(IPackageMoveObserver callback) { 17376 mCallbacks.unregister(callback); 17377 } 17378 17379 @Override 17380 public void handleMessage(Message msg) { 17381 final SomeArgs args = (SomeArgs) msg.obj; 17382 final int n = mCallbacks.beginBroadcast(); 17383 for (int i = 0; i < n; i++) { 17384 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17385 try { 17386 invokeCallback(callback, msg.what, args); 17387 } catch (RemoteException ignored) { 17388 } 17389 } 17390 mCallbacks.finishBroadcast(); 17391 args.recycle(); 17392 } 17393 17394 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17395 throws RemoteException { 17396 switch (what) { 17397 case MSG_CREATED: { 17398 callback.onCreated(args.argi1, (Bundle) args.arg2); 17399 break; 17400 } 17401 case MSG_STATUS_CHANGED: { 17402 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17403 break; 17404 } 17405 } 17406 } 17407 17408 private void notifyCreated(int moveId, Bundle extras) { 17409 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17410 17411 final SomeArgs args = SomeArgs.obtain(); 17412 args.argi1 = moveId; 17413 args.arg2 = extras; 17414 obtainMessage(MSG_CREATED, args).sendToTarget(); 17415 } 17416 17417 private void notifyStatusChanged(int moveId, int status) { 17418 notifyStatusChanged(moveId, status, -1); 17419 } 17420 17421 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17422 Slog.v(TAG, "Move " + moveId + " status " + status); 17423 17424 final SomeArgs args = SomeArgs.obtain(); 17425 args.argi1 = moveId; 17426 args.argi2 = status; 17427 args.arg3 = estMillis; 17428 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17429 17430 synchronized (mLastStatus) { 17431 mLastStatus.put(moveId, status); 17432 } 17433 } 17434 } 17435 17436 private final static class OnPermissionChangeListeners extends Handler { 17437 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17438 17439 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17440 new RemoteCallbackList<>(); 17441 17442 public OnPermissionChangeListeners(Looper looper) { 17443 super(looper); 17444 } 17445 17446 @Override 17447 public void handleMessage(Message msg) { 17448 switch (msg.what) { 17449 case MSG_ON_PERMISSIONS_CHANGED: { 17450 final int uid = msg.arg1; 17451 handleOnPermissionsChanged(uid); 17452 } break; 17453 } 17454 } 17455 17456 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17457 mPermissionListeners.register(listener); 17458 17459 } 17460 17461 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17462 mPermissionListeners.unregister(listener); 17463 } 17464 17465 public void onPermissionsChanged(int uid) { 17466 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17467 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17468 } 17469 } 17470 17471 private void handleOnPermissionsChanged(int uid) { 17472 final int count = mPermissionListeners.beginBroadcast(); 17473 try { 17474 for (int i = 0; i < count; i++) { 17475 IOnPermissionsChangeListener callback = mPermissionListeners 17476 .getBroadcastItem(i); 17477 try { 17478 callback.onPermissionsChanged(uid); 17479 } catch (RemoteException e) { 17480 Log.e(TAG, "Permission listener is dead", e); 17481 } 17482 } 17483 } finally { 17484 mPermissionListeners.finishBroadcast(); 17485 } 17486 } 17487 } 17488 17489 private class PackageManagerInternalImpl extends PackageManagerInternal { 17490 @Override 17491 public void setLocationPackagesProvider(PackagesProvider provider) { 17492 synchronized (mPackages) { 17493 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17494 } 17495 } 17496 17497 @Override 17498 public void setImePackagesProvider(PackagesProvider provider) { 17499 synchronized (mPackages) { 17500 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17501 } 17502 } 17503 17504 @Override 17505 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17506 synchronized (mPackages) { 17507 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17508 } 17509 } 17510 17511 @Override 17512 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17513 synchronized (mPackages) { 17514 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17515 } 17516 } 17517 17518 @Override 17519 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17520 synchronized (mPackages) { 17521 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17522 } 17523 } 17524 17525 @Override 17526 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17527 synchronized (mPackages) { 17528 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17529 } 17530 } 17531 17532 @Override 17533 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17534 synchronized (mPackages) { 17535 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17536 } 17537 } 17538 17539 @Override 17540 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17541 synchronized (mPackages) { 17542 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17543 packageName, userId); 17544 } 17545 } 17546 17547 @Override 17548 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17549 synchronized (mPackages) { 17550 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17551 packageName, userId); 17552 } 17553 } 17554 17555 @Override 17556 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17557 synchronized (mPackages) { 17558 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17559 packageName, userId); 17560 } 17561 } 17562 17563 @Override 17564 public void setKeepUninstalledPackages(final List<String> packageList) { 17565 Preconditions.checkNotNull(packageList); 17566 List<String> removedFromList = null; 17567 synchronized (mPackages) { 17568 if (mKeepUninstalledPackages != null) { 17569 final int packagesCount = mKeepUninstalledPackages.size(); 17570 for (int i = 0; i < packagesCount; i++) { 17571 String oldPackage = mKeepUninstalledPackages.get(i); 17572 if (packageList != null && packageList.contains(oldPackage)) { 17573 continue; 17574 } 17575 if (removedFromList == null) { 17576 removedFromList = new ArrayList<>(); 17577 } 17578 removedFromList.add(oldPackage); 17579 } 17580 } 17581 mKeepUninstalledPackages = new ArrayList<>(packageList); 17582 if (removedFromList != null) { 17583 final int removedCount = removedFromList.size(); 17584 for (int i = 0; i < removedCount; i++) { 17585 deletePackageIfUnusedLPr(removedFromList.get(i)); 17586 } 17587 } 17588 } 17589 } 17590 17591 @Override 17592 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17593 synchronized (mPackages) { 17594 // If we do not support permission review, done. 17595 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17596 return false; 17597 } 17598 17599 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17600 if (packageSetting == null) { 17601 return false; 17602 } 17603 17604 // Permission review applies only to apps not supporting the new permission model. 17605 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17606 return false; 17607 } 17608 17609 // Legacy apps have the permission and get user consent on launch. 17610 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17611 return permissionsState.isPermissionReviewRequired(userId); 17612 } 17613 } 17614 } 17615 17616 @Override 17617 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17618 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17619 synchronized (mPackages) { 17620 final long identity = Binder.clearCallingIdentity(); 17621 try { 17622 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17623 packageNames, userId); 17624 } finally { 17625 Binder.restoreCallingIdentity(identity); 17626 } 17627 } 17628 } 17629 17630 private static void enforceSystemOrPhoneCaller(String tag) { 17631 int callingUid = Binder.getCallingUid(); 17632 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17633 throw new SecurityException( 17634 "Cannot call " + tag + " from UID " + callingUid); 17635 } 17636 } 17637} 17638