PackageManagerService.java revision 369d3dcda03090c314ad2a350335b060eeb1bbd6
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_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 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_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 71import static android.system.OsConstants.O_CREAT; 72import static android.system.OsConstants.O_RDWR; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 77import static com.android.internal.util.ArrayUtils.appendInt; 78import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 87 88import android.Manifest; 89import android.app.ActivityManager; 90import android.app.ActivityManagerNative; 91import android.app.AppGlobals; 92import android.app.IActivityManager; 93import android.app.admin.IDevicePolicyManager; 94import android.app.backup.IBackupManager; 95import android.app.usage.UsageStats; 96import android.app.usage.UsageStatsManager; 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.FeatureInfo; 109import android.content.pm.IOnPermissionsChangeListener; 110import android.content.pm.IPackageDataObserver; 111import android.content.pm.IPackageDeleteObserver; 112import android.content.pm.IPackageDeleteObserver2; 113import android.content.pm.IPackageInstallObserver2; 114import android.content.pm.IPackageInstaller; 115import android.content.pm.IPackageManager; 116import android.content.pm.IPackageMoveObserver; 117import android.content.pm.IPackageStatsObserver; 118import android.content.pm.InstrumentationInfo; 119import android.content.pm.IntentFilterVerificationInfo; 120import android.content.pm.KeySet; 121import android.content.pm.ManifestDigest; 122import android.content.pm.PackageCleanItem; 123import android.content.pm.PackageInfo; 124import android.content.pm.PackageInfoLite; 125import android.content.pm.PackageInstaller; 126import android.content.pm.PackageManager; 127import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 128import android.content.pm.PackageManagerInternal; 129import android.content.pm.PackageParser; 130import android.content.pm.PackageParser.ActivityIntentInfo; 131import android.content.pm.PackageParser.PackageLite; 132import android.content.pm.PackageParser.PackageParserException; 133import android.content.pm.PackageStats; 134import android.content.pm.PackageUserState; 135import android.content.pm.ParceledListSlice; 136import android.content.pm.PermissionGroupInfo; 137import android.content.pm.PermissionInfo; 138import android.content.pm.ProviderInfo; 139import android.content.pm.ResolveInfo; 140import android.content.pm.ServiceInfo; 141import android.content.pm.Signature; 142import android.content.pm.UserInfo; 143import android.content.pm.VerificationParams; 144import android.content.pm.VerifierDeviceIdentity; 145import android.content.pm.VerifierInfo; 146import android.content.res.Resources; 147import android.hardware.display.DisplayManager; 148import android.net.Uri; 149import android.os.Debug; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Environment; 154import android.os.Environment.UserEnvironment; 155import android.os.FileUtils; 156import android.os.Handler; 157import android.os.IBinder; 158import android.os.Looper; 159import android.os.Message; 160import android.os.Parcel; 161import android.os.ParcelFileDescriptor; 162import android.os.Process; 163import android.os.RemoteCallbackList; 164import android.os.RemoteException; 165import android.os.SELinux; 166import android.os.ServiceManager; 167import android.os.SystemClock; 168import android.os.SystemProperties; 169import android.os.Trace; 170import android.os.UserHandle; 171import android.os.UserManager; 172import android.os.storage.IMountService; 173import android.os.storage.MountServiceInternal; 174import android.os.storage.StorageEventListener; 175import android.os.storage.StorageManager; 176import android.os.storage.VolumeInfo; 177import android.os.storage.VolumeRecord; 178import android.security.KeyStore; 179import android.security.SystemKeyStore; 180import android.system.ErrnoException; 181import android.system.Os; 182import android.system.StructStat; 183import android.text.TextUtils; 184import android.text.format.DateUtils; 185import android.util.ArrayMap; 186import android.util.ArraySet; 187import android.util.AtomicFile; 188import android.util.DisplayMetrics; 189import android.util.EventLog; 190import android.util.ExceptionUtils; 191import android.util.Log; 192import android.util.LogPrinter; 193import android.util.MathUtils; 194import android.util.PrintStreamPrinter; 195import android.util.Slog; 196import android.util.SparseArray; 197import android.util.SparseBooleanArray; 198import android.util.SparseIntArray; 199import android.util.Xml; 200import android.view.Display; 201 202import dalvik.system.DexFile; 203import dalvik.system.VMRuntime; 204 205import libcore.io.IoUtils; 206import libcore.util.EmptyArray; 207 208import com.android.internal.R; 209import com.android.internal.annotations.GuardedBy; 210import com.android.internal.app.IMediaContainerService; 211import com.android.internal.app.ResolverActivity; 212import com.android.internal.content.NativeLibraryHelper; 213import com.android.internal.content.PackageHelper; 214import com.android.internal.os.IParcelFileDescriptorFactory; 215import com.android.internal.os.SomeArgs; 216import com.android.internal.os.Zygote; 217import com.android.internal.util.ArrayUtils; 218import com.android.internal.util.FastPrintWriter; 219import com.android.internal.util.FastXmlSerializer; 220import com.android.internal.util.IndentingPrintWriter; 221import com.android.internal.util.Preconditions; 222import com.android.server.EventLogTags; 223import com.android.server.FgThread; 224import com.android.server.IntentResolver; 225import com.android.server.LocalServices; 226import com.android.server.ServiceThread; 227import com.android.server.SystemConfig; 228import com.android.server.Watchdog; 229import com.android.server.pm.PermissionsState.PermissionState; 230import com.android.server.pm.Settings.DatabaseVersion; 231import com.android.server.pm.Settings.VersionInfo; 232import com.android.server.storage.DeviceStorageMonitorInternal; 233 234import org.xmlpull.v1.XmlPullParser; 235import org.xmlpull.v1.XmlPullParserException; 236import org.xmlpull.v1.XmlSerializer; 237 238import java.io.BufferedInputStream; 239import java.io.BufferedOutputStream; 240import java.io.BufferedReader; 241import java.io.ByteArrayInputStream; 242import java.io.ByteArrayOutputStream; 243import java.io.File; 244import java.io.FileDescriptor; 245import java.io.FileNotFoundException; 246import java.io.FileOutputStream; 247import java.io.FileReader; 248import java.io.FilenameFilter; 249import java.io.IOException; 250import java.io.InputStream; 251import java.io.PrintWriter; 252import java.nio.charset.StandardCharsets; 253import java.security.NoSuchAlgorithmException; 254import java.security.PublicKey; 255import java.security.cert.CertificateEncodingException; 256import java.security.cert.CertificateException; 257import java.text.SimpleDateFormat; 258import java.util.ArrayList; 259import java.util.Arrays; 260import java.util.Collection; 261import java.util.Collections; 262import java.util.Comparator; 263import java.util.Date; 264import java.util.Iterator; 265import java.util.List; 266import java.util.Map; 267import java.util.Objects; 268import java.util.Set; 269import java.util.concurrent.CountDownLatch; 270import java.util.concurrent.TimeUnit; 271import java.util.concurrent.atomic.AtomicBoolean; 272import java.util.concurrent.atomic.AtomicInteger; 273import java.util.concurrent.atomic.AtomicLong; 274 275/** 276 * Keep track of all those .apks everywhere. 277 * 278 * This is very central to the platform's security; please run the unit 279 * tests whenever making modifications here: 280 * 281runtest -c android.content.pm.PackageManagerTests frameworks-core 282 * 283 * {@hide} 284 */ 285public class PackageManagerService extends IPackageManager.Stub { 286 static final String TAG = "PackageManager"; 287 static final boolean DEBUG_SETTINGS = false; 288 static final boolean DEBUG_PREFERRED = false; 289 static final boolean DEBUG_UPGRADE = false; 290 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 291 private static final boolean DEBUG_BACKUP = false; 292 private static final boolean DEBUG_INSTALL = false; 293 private static final boolean DEBUG_REMOVE = false; 294 private static final boolean DEBUG_BROADCASTS = false; 295 private static final boolean DEBUG_SHOW_INFO = false; 296 private static final boolean DEBUG_PACKAGE_INFO = false; 297 private static final boolean DEBUG_INTENT_MATCHING = false; 298 private static final boolean DEBUG_PACKAGE_SCANNING = false; 299 private static final boolean DEBUG_VERIFY = false; 300 private static final boolean DEBUG_DEXOPT = false; 301 private static final boolean DEBUG_ABI_SELECTION = false; 302 303 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 304 305 private static final int RADIO_UID = Process.PHONE_UID; 306 private static final int LOG_UID = Process.LOG_UID; 307 private static final int NFC_UID = Process.NFC_UID; 308 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 309 private static final int SHELL_UID = Process.SHELL_UID; 310 311 // Cap the size of permission trees that 3rd party apps can define 312 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 313 314 // Suffix used during package installation when copying/moving 315 // package apks to install directory. 316 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 317 318 static final int SCAN_NO_DEX = 1<<1; 319 static final int SCAN_FORCE_DEX = 1<<2; 320 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 321 static final int SCAN_NEW_INSTALL = 1<<4; 322 static final int SCAN_NO_PATHS = 1<<5; 323 static final int SCAN_UPDATE_TIME = 1<<6; 324 static final int SCAN_DEFER_DEX = 1<<7; 325 static final int SCAN_BOOTING = 1<<8; 326 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 327 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 328 static final int SCAN_REPLACING = 1<<11; 329 static final int SCAN_REQUIRE_KNOWN = 1<<12; 330 static final int SCAN_MOVE = 1<<13; 331 static final int SCAN_INITIAL = 1<<14; 332 333 static final int REMOVE_CHATTY = 1<<16; 334 335 private static final int[] EMPTY_INT_ARRAY = new int[0]; 336 337 /** 338 * Timeout (in milliseconds) after which the watchdog should declare that 339 * our handler thread is wedged. The usual default for such things is one 340 * minute but we sometimes do very lengthy I/O operations on this thread, 341 * such as installing multi-gigabyte applications, so ours needs to be longer. 342 */ 343 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 344 345 /** 346 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 347 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 348 * settings entry if available, otherwise we use the hardcoded default. If it's been 349 * more than this long since the last fstrim, we force one during the boot sequence. 350 * 351 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 352 * one gets run at the next available charging+idle time. This final mandatory 353 * no-fstrim check kicks in only of the other scheduling criteria is never met. 354 */ 355 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 356 357 /** 358 * Whether verification is enabled by default. 359 */ 360 private static final boolean DEFAULT_VERIFY_ENABLE = true; 361 362 /** 363 * The default maximum time to wait for the verification agent to return in 364 * milliseconds. 365 */ 366 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 367 368 /** 369 * The default response for package verification timeout. 370 * 371 * This can be either PackageManager.VERIFICATION_ALLOW or 372 * PackageManager.VERIFICATION_REJECT. 373 */ 374 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 375 376 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 377 378 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 379 DEFAULT_CONTAINER_PACKAGE, 380 "com.android.defcontainer.DefaultContainerService"); 381 382 private static final String KILL_APP_REASON_GIDS_CHANGED = 383 "permission grant or revoke changed gids"; 384 385 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 386 "permissions revoked"; 387 388 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 389 390 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 391 392 /** Permission grant: not grant the permission. */ 393 private static final int GRANT_DENIED = 1; 394 395 /** Permission grant: grant the permission as an install permission. */ 396 private static final int GRANT_INSTALL = 2; 397 398 /** Permission grant: grant the permission as an install permission for a legacy app. */ 399 private static final int GRANT_INSTALL_LEGACY = 3; 400 401 /** Permission grant: grant the permission as a runtime one. */ 402 private static final int GRANT_RUNTIME = 4; 403 404 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 405 private static final int GRANT_UPGRADE = 5; 406 407 /** Canonical intent used to identify what counts as a "web browser" app */ 408 private static final Intent sBrowserIntent; 409 static { 410 sBrowserIntent = new Intent(); 411 sBrowserIntent.setAction(Intent.ACTION_VIEW); 412 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 413 sBrowserIntent.setData(Uri.parse("http:")); 414 } 415 416 final ServiceThread mHandlerThread; 417 418 final PackageHandler mHandler; 419 420 /** 421 * Messages for {@link #mHandler} that need to wait for system ready before 422 * being dispatched. 423 */ 424 private ArrayList<Message> mPostSystemReadyMessages; 425 426 final int mSdkVersion = Build.VERSION.SDK_INT; 427 428 final Context mContext; 429 final boolean mFactoryTest; 430 final boolean mOnlyCore; 431 final boolean mLazyDexOpt; 432 final long mDexOptLRUThresholdInMills; 433 final DisplayMetrics mMetrics; 434 final int mDefParseFlags; 435 final String[] mSeparateProcesses; 436 final boolean mIsUpgrade; 437 438 // This is where all application persistent data goes. 439 final File mAppDataDir; 440 441 // This is where all application persistent data goes for secondary users. 442 final File mUserAppDataDir; 443 444 /** The location for ASEC container files on internal storage. */ 445 final String mAsecInternalPath; 446 447 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 448 // LOCK HELD. Can be called with mInstallLock held. 449 @GuardedBy("mInstallLock") 450 final Installer mInstaller; 451 452 /** Directory where installed third-party apps stored */ 453 final File mAppInstallDir; 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 public static final class SharedLibraryEntry { 516 public final String path; 517 public final String apk; 518 519 SharedLibraryEntry(String _path, String _apk) { 520 path = _path; 521 apk = _apk; 522 } 523 } 524 525 // Currently known shared libraries. 526 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 527 new ArrayMap<String, SharedLibraryEntry>(); 528 529 // All available activities, for your resolving pleasure. 530 final ActivityIntentResolver mActivities = 531 new ActivityIntentResolver(); 532 533 // All available receivers, for your resolving pleasure. 534 final ActivityIntentResolver mReceivers = 535 new ActivityIntentResolver(); 536 537 // All available services, for your resolving pleasure. 538 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 539 540 // All available providers, for your resolving pleasure. 541 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 542 543 // Mapping from provider base names (first directory in content URI codePath) 544 // to the provider information. 545 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 546 new ArrayMap<String, PackageParser.Provider>(); 547 548 // Mapping from instrumentation class names to info about them. 549 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 550 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 551 552 // Mapping from permission names to info about them. 553 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 554 new ArrayMap<String, PackageParser.PermissionGroup>(); 555 556 // Packages whose data we have transfered into another package, thus 557 // should no longer exist. 558 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 559 560 // Broadcast actions that are only available to the system. 561 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 562 563 /** List of packages waiting for verification. */ 564 final SparseArray<PackageVerificationState> mPendingVerification 565 = new SparseArray<PackageVerificationState>(); 566 567 /** Set of packages associated with each app op permission. */ 568 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 569 570 final PackageInstallerService mInstallerService; 571 572 private final PackageDexOptimizer mPackageDexOptimizer; 573 574 private AtomicInteger mNextMoveId = new AtomicInteger(); 575 private final MoveCallbacks mMoveCallbacks; 576 577 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 578 579 // Cache of users who need badging. 580 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 581 582 /** Token for keys in mPendingVerification. */ 583 private int mPendingVerificationToken = 0; 584 585 volatile boolean mSystemReady; 586 volatile boolean mSafeMode; 587 volatile boolean mHasSystemUidErrors; 588 589 ApplicationInfo mAndroidApplication; 590 final ActivityInfo mResolveActivity = new ActivityInfo(); 591 final ResolveInfo mResolveInfo = new ResolveInfo(); 592 ComponentName mResolveComponentName; 593 PackageParser.Package mPlatformPackage; 594 ComponentName mCustomResolverComponentName; 595 596 boolean mResolverReplaced = false; 597 598 private final ComponentName mIntentFilterVerifierComponent; 599 private int mIntentFilterVerificationToken = 0; 600 601 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 602 = new SparseArray<IntentFilterVerificationState>(); 603 604 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 605 new DefaultPermissionGrantPolicy(this); 606 607 private static class IFVerificationParams { 608 PackageParser.Package pkg; 609 boolean replacing; 610 int userId; 611 int verifierUid; 612 613 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 614 int _userId, int _verifierUid) { 615 pkg = _pkg; 616 replacing = _replacing; 617 userId = _userId; 618 replacing = _replacing; 619 verifierUid = _verifierUid; 620 } 621 } 622 623 private interface IntentFilterVerifier<T extends IntentFilter> { 624 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 625 T filter, String packageName); 626 void startVerifications(int userId); 627 void receiveVerificationResponse(int verificationId); 628 } 629 630 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 631 private Context mContext; 632 private ComponentName mIntentFilterVerifierComponent; 633 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 634 635 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 636 mContext = context; 637 mIntentFilterVerifierComponent = verifierComponent; 638 } 639 640 private String getDefaultScheme() { 641 return IntentFilter.SCHEME_HTTPS; 642 } 643 644 @Override 645 public void startVerifications(int userId) { 646 // Launch verifications requests 647 int count = mCurrentIntentFilterVerifications.size(); 648 for (int n=0; n<count; n++) { 649 int verificationId = mCurrentIntentFilterVerifications.get(n); 650 final IntentFilterVerificationState ivs = 651 mIntentFilterVerificationStates.get(verificationId); 652 653 String packageName = ivs.getPackageName(); 654 655 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 656 final int filterCount = filters.size(); 657 ArraySet<String> domainsSet = new ArraySet<>(); 658 for (int m=0; m<filterCount; m++) { 659 PackageParser.ActivityIntentInfo filter = filters.get(m); 660 domainsSet.addAll(filter.getHostsList()); 661 } 662 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 663 synchronized (mPackages) { 664 if (mSettings.createIntentFilterVerificationIfNeededLPw( 665 packageName, domainsList) != null) { 666 scheduleWriteSettingsLocked(); 667 } 668 } 669 sendVerificationRequest(userId, verificationId, ivs); 670 } 671 mCurrentIntentFilterVerifications.clear(); 672 } 673 674 private void sendVerificationRequest(int userId, int verificationId, 675 IntentFilterVerificationState ivs) { 676 677 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 678 verificationIntent.putExtra( 679 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 680 verificationId); 681 verificationIntent.putExtra( 682 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 683 getDefaultScheme()); 684 verificationIntent.putExtra( 685 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 686 ivs.getHostsString()); 687 verificationIntent.putExtra( 688 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 689 ivs.getPackageName()); 690 verificationIntent.setComponent(mIntentFilterVerifierComponent); 691 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 692 693 UserHandle user = new UserHandle(userId); 694 mContext.sendBroadcastAsUser(verificationIntent, user); 695 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 696 "Sending IntentFilter verification broadcast"); 697 } 698 699 public void receiveVerificationResponse(int verificationId) { 700 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 701 702 final boolean verified = ivs.isVerified(); 703 704 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 705 final int count = filters.size(); 706 if (DEBUG_DOMAIN_VERIFICATION) { 707 Slog.i(TAG, "Received verification response " + verificationId 708 + " for " + count + " filters, verified=" + verified); 709 } 710 for (int n=0; n<count; n++) { 711 PackageParser.ActivityIntentInfo filter = filters.get(n); 712 filter.setVerified(verified); 713 714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 715 + " verified with result:" + verified + " and hosts:" 716 + ivs.getHostsString()); 717 } 718 719 mIntentFilterVerificationStates.remove(verificationId); 720 721 final String packageName = ivs.getPackageName(); 722 IntentFilterVerificationInfo ivi = null; 723 724 synchronized (mPackages) { 725 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 726 } 727 if (ivi == null) { 728 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 729 + verificationId + " packageName:" + packageName); 730 return; 731 } 732 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 733 "Updating IntentFilterVerificationInfo for package " + packageName 734 +" verificationId:" + verificationId); 735 736 synchronized (mPackages) { 737 if (verified) { 738 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 739 } else { 740 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 741 } 742 scheduleWriteSettingsLocked(); 743 744 final int userId = ivs.getUserId(); 745 if (userId != UserHandle.USER_ALL) { 746 final int userStatus = 747 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 748 749 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 750 boolean needUpdate = false; 751 752 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 753 // already been set by the User thru the Disambiguation dialog 754 switch (userStatus) { 755 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 756 if (verified) { 757 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 758 } else { 759 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 760 } 761 needUpdate = true; 762 break; 763 764 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 765 if (verified) { 766 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 767 needUpdate = true; 768 } 769 break; 770 771 default: 772 // Nothing to do 773 } 774 775 if (needUpdate) { 776 mSettings.updateIntentFilterVerificationStatusLPw( 777 packageName, updatedStatus, userId); 778 scheduleWritePackageRestrictionsLocked(userId); 779 } 780 } 781 } 782 } 783 784 @Override 785 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 786 ActivityIntentInfo filter, String packageName) { 787 if (!hasValidDomains(filter)) { 788 return false; 789 } 790 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 791 if (ivs == null) { 792 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 793 packageName); 794 } 795 if (DEBUG_DOMAIN_VERIFICATION) { 796 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 797 } 798 ivs.addFilter(filter); 799 return true; 800 } 801 802 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 803 int userId, int verificationId, String packageName) { 804 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 805 verifierUid, userId, packageName); 806 ivs.setPendingState(); 807 synchronized (mPackages) { 808 mIntentFilterVerificationStates.append(verificationId, ivs); 809 mCurrentIntentFilterVerifications.add(verificationId); 810 } 811 return ivs; 812 } 813 } 814 815 private static boolean hasValidDomains(ActivityIntentInfo filter) { 816 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 817 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 818 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 819 } 820 821 private IntentFilterVerifier mIntentFilterVerifier; 822 823 // Set of pending broadcasts for aggregating enable/disable of components. 824 static class PendingPackageBroadcasts { 825 // for each user id, a map of <package name -> components within that package> 826 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 827 828 public PendingPackageBroadcasts() { 829 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 830 } 831 832 public ArrayList<String> get(int userId, String packageName) { 833 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 834 return packages.get(packageName); 835 } 836 837 public void put(int userId, String packageName, ArrayList<String> components) { 838 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 839 packages.put(packageName, components); 840 } 841 842 public void remove(int userId, String packageName) { 843 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 844 if (packages != null) { 845 packages.remove(packageName); 846 } 847 } 848 849 public void remove(int userId) { 850 mUidMap.remove(userId); 851 } 852 853 public int userIdCount() { 854 return mUidMap.size(); 855 } 856 857 public int userIdAt(int n) { 858 return mUidMap.keyAt(n); 859 } 860 861 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 862 return mUidMap.get(userId); 863 } 864 865 public int size() { 866 // total number of pending broadcast entries across all userIds 867 int num = 0; 868 for (int i = 0; i< mUidMap.size(); i++) { 869 num += mUidMap.valueAt(i).size(); 870 } 871 return num; 872 } 873 874 public void clear() { 875 mUidMap.clear(); 876 } 877 878 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 879 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 880 if (map == null) { 881 map = new ArrayMap<String, ArrayList<String>>(); 882 mUidMap.put(userId, map); 883 } 884 return map; 885 } 886 } 887 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 888 889 // Service Connection to remote media container service to copy 890 // package uri's from external media onto secure containers 891 // or internal storage. 892 private IMediaContainerService mContainerService = null; 893 894 static final int SEND_PENDING_BROADCAST = 1; 895 static final int MCS_BOUND = 3; 896 static final int END_COPY = 4; 897 static final int INIT_COPY = 5; 898 static final int MCS_UNBIND = 6; 899 static final int START_CLEANING_PACKAGE = 7; 900 static final int FIND_INSTALL_LOC = 8; 901 static final int POST_INSTALL = 9; 902 static final int MCS_RECONNECT = 10; 903 static final int MCS_GIVE_UP = 11; 904 static final int UPDATED_MEDIA_STATUS = 12; 905 static final int WRITE_SETTINGS = 13; 906 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 907 static final int PACKAGE_VERIFIED = 15; 908 static final int CHECK_PENDING_VERIFICATION = 16; 909 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 910 static final int INTENT_FILTER_VERIFIED = 18; 911 912 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 913 914 // Delay time in millisecs 915 static final int BROADCAST_DELAY = 10 * 1000; 916 917 static UserManagerService sUserManager; 918 919 // Stores a list of users whose package restrictions file needs to be updated 920 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 921 922 final private DefaultContainerConnection mDefContainerConn = 923 new DefaultContainerConnection(); 924 class DefaultContainerConnection implements ServiceConnection { 925 public void onServiceConnected(ComponentName name, IBinder service) { 926 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 927 IMediaContainerService imcs = 928 IMediaContainerService.Stub.asInterface(service); 929 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 930 } 931 932 public void onServiceDisconnected(ComponentName name) { 933 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 934 } 935 } 936 937 // Recordkeeping of restore-after-install operations that are currently in flight 938 // between the Package Manager and the Backup Manager 939 class PostInstallData { 940 public InstallArgs args; 941 public PackageInstalledInfo res; 942 943 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 944 args = _a; 945 res = _r; 946 } 947 } 948 949 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 950 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 951 952 // XML tags for backup/restore of various bits of state 953 private static final String TAG_PREFERRED_BACKUP = "pa"; 954 private static final String TAG_DEFAULT_APPS = "da"; 955 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 956 957 final String mRequiredVerifierPackage; 958 final String mRequiredInstallerPackage; 959 960 private final PackageUsage mPackageUsage = new PackageUsage(); 961 962 private class PackageUsage { 963 private static final int WRITE_INTERVAL 964 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 965 966 private final Object mFileLock = new Object(); 967 private final AtomicLong mLastWritten = new AtomicLong(0); 968 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 969 970 private boolean mIsHistoricalPackageUsageAvailable = true; 971 972 boolean isHistoricalPackageUsageAvailable() { 973 return mIsHistoricalPackageUsageAvailable; 974 } 975 976 void write(boolean force) { 977 if (force) { 978 writeInternal(); 979 return; 980 } 981 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 982 && !DEBUG_DEXOPT) { 983 return; 984 } 985 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 986 new Thread("PackageUsage_DiskWriter") { 987 @Override 988 public void run() { 989 try { 990 writeInternal(); 991 } finally { 992 mBackgroundWriteRunning.set(false); 993 } 994 } 995 }.start(); 996 } 997 } 998 999 private void writeInternal() { 1000 synchronized (mPackages) { 1001 synchronized (mFileLock) { 1002 AtomicFile file = getFile(); 1003 FileOutputStream f = null; 1004 try { 1005 f = file.startWrite(); 1006 BufferedOutputStream out = new BufferedOutputStream(f); 1007 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1008 StringBuilder sb = new StringBuilder(); 1009 for (PackageParser.Package pkg : mPackages.values()) { 1010 if (pkg.mLastPackageUsageTimeInMills == 0) { 1011 continue; 1012 } 1013 sb.setLength(0); 1014 sb.append(pkg.packageName); 1015 sb.append(' '); 1016 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1017 sb.append('\n'); 1018 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1019 } 1020 out.flush(); 1021 file.finishWrite(f); 1022 } catch (IOException e) { 1023 if (f != null) { 1024 file.failWrite(f); 1025 } 1026 Log.e(TAG, "Failed to write package usage times", e); 1027 } 1028 } 1029 } 1030 mLastWritten.set(SystemClock.elapsedRealtime()); 1031 } 1032 1033 void readLP() { 1034 synchronized (mFileLock) { 1035 AtomicFile file = getFile(); 1036 BufferedInputStream in = null; 1037 try { 1038 in = new BufferedInputStream(file.openRead()); 1039 StringBuffer sb = new StringBuffer(); 1040 while (true) { 1041 String packageName = readToken(in, sb, ' '); 1042 if (packageName == null) { 1043 break; 1044 } 1045 String timeInMillisString = readToken(in, sb, '\n'); 1046 if (timeInMillisString == null) { 1047 throw new IOException("Failed to find last usage time for package " 1048 + packageName); 1049 } 1050 PackageParser.Package pkg = mPackages.get(packageName); 1051 if (pkg == null) { 1052 continue; 1053 } 1054 long timeInMillis; 1055 try { 1056 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1057 } catch (NumberFormatException e) { 1058 throw new IOException("Failed to parse " + timeInMillisString 1059 + " as a long.", e); 1060 } 1061 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1062 } 1063 } catch (FileNotFoundException expected) { 1064 mIsHistoricalPackageUsageAvailable = false; 1065 } catch (IOException e) { 1066 Log.w(TAG, "Failed to read package usage times", e); 1067 } finally { 1068 IoUtils.closeQuietly(in); 1069 } 1070 } 1071 mLastWritten.set(SystemClock.elapsedRealtime()); 1072 } 1073 1074 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1075 throws IOException { 1076 sb.setLength(0); 1077 while (true) { 1078 int ch = in.read(); 1079 if (ch == -1) { 1080 if (sb.length() == 0) { 1081 return null; 1082 } 1083 throw new IOException("Unexpected EOF"); 1084 } 1085 if (ch == endOfToken) { 1086 return sb.toString(); 1087 } 1088 sb.append((char)ch); 1089 } 1090 } 1091 1092 private AtomicFile getFile() { 1093 File dataDir = Environment.getDataDirectory(); 1094 File systemDir = new File(dataDir, "system"); 1095 File fname = new File(systemDir, "package-usage.list"); 1096 return new AtomicFile(fname); 1097 } 1098 } 1099 1100 class PackageHandler extends Handler { 1101 private boolean mBound = false; 1102 final ArrayList<HandlerParams> mPendingInstalls = 1103 new ArrayList<HandlerParams>(); 1104 1105 private boolean connectToService() { 1106 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1107 " DefaultContainerService"); 1108 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1111 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 mBound = true; 1114 return true; 1115 } 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1117 return false; 1118 } 1119 1120 private void disconnectService() { 1121 mContainerService = null; 1122 mBound = false; 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1124 mContext.unbindService(mDefContainerConn); 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 1128 PackageHandler(Looper looper) { 1129 super(looper); 1130 } 1131 1132 public void handleMessage(Message msg) { 1133 try { 1134 doHandleMessage(msg); 1135 } finally { 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } 1138 } 1139 1140 void doHandleMessage(Message msg) { 1141 switch (msg.what) { 1142 case INIT_COPY: { 1143 HandlerParams params = (HandlerParams) msg.obj; 1144 int idx = mPendingInstalls.size(); 1145 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1146 // If a bind was already initiated we dont really 1147 // need to do anything. The pending install 1148 // will be processed later on. 1149 if (!mBound) { 1150 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1151 System.identityHashCode(mHandler)); 1152 // If this is the only one pending we might 1153 // have to bind to the service again. 1154 if (!connectToService()) { 1155 Slog.e(TAG, "Failed to bind to media container service"); 1156 params.serviceError(); 1157 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1158 System.identityHashCode(mHandler)); 1159 if (params.traceMethod != null) { 1160 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1161 params.traceCookie); 1162 } 1163 return; 1164 } else { 1165 // Once we bind to the service, the first 1166 // pending request will be processed. 1167 mPendingInstalls.add(idx, params); 1168 } 1169 } else { 1170 mPendingInstalls.add(idx, params); 1171 // Already bound to the service. Just make 1172 // sure we trigger off processing the first request. 1173 if (idx == 0) { 1174 mHandler.sendEmptyMessage(MCS_BOUND); 1175 } 1176 } 1177 break; 1178 } 1179 case MCS_BOUND: { 1180 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1181 if (msg.obj != null) { 1182 mContainerService = (IMediaContainerService) msg.obj; 1183 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1184 System.identityHashCode(mHandler)); 1185 } 1186 if (mContainerService == null) { 1187 if (!mBound) { 1188 // Something seriously wrong since we are not bound and we are not 1189 // waiting for connection. Bail out. 1190 Slog.e(TAG, "Cannot bind to media container service"); 1191 for (HandlerParams params : mPendingInstalls) { 1192 // Indicate service bind error 1193 params.serviceError(); 1194 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1195 System.identityHashCode(params)); 1196 if (params.traceMethod != null) { 1197 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1198 params.traceMethod, params.traceCookie); 1199 } 1200 return; 1201 } 1202 mPendingInstalls.clear(); 1203 } else { 1204 Slog.w(TAG, "Waiting to connect to media container service"); 1205 } 1206 } else if (mPendingInstalls.size() > 0) { 1207 HandlerParams params = mPendingInstalls.get(0); 1208 if (params != null) { 1209 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1210 System.identityHashCode(params)); 1211 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1212 if (params.startCopy()) { 1213 // We are done... look for more work or to 1214 // go idle. 1215 if (DEBUG_SD_INSTALL) Log.i(TAG, 1216 "Checking for more work or unbind..."); 1217 // Delete pending install 1218 if (mPendingInstalls.size() > 0) { 1219 mPendingInstalls.remove(0); 1220 } 1221 if (mPendingInstalls.size() == 0) { 1222 if (mBound) { 1223 if (DEBUG_SD_INSTALL) Log.i(TAG, 1224 "Posting delayed MCS_UNBIND"); 1225 removeMessages(MCS_UNBIND); 1226 Message ubmsg = obtainMessage(MCS_UNBIND); 1227 // Unbind after a little delay, to avoid 1228 // continual thrashing. 1229 sendMessageDelayed(ubmsg, 10000); 1230 } 1231 } else { 1232 // There are more pending requests in queue. 1233 // Just post MCS_BOUND message to trigger processing 1234 // of next pending install. 1235 if (DEBUG_SD_INSTALL) Log.i(TAG, 1236 "Posting MCS_BOUND for next work"); 1237 mHandler.sendEmptyMessage(MCS_BOUND); 1238 } 1239 } 1240 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1241 } 1242 } else { 1243 // Should never happen ideally. 1244 Slog.w(TAG, "Empty queue"); 1245 } 1246 break; 1247 } 1248 case MCS_RECONNECT: { 1249 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1250 if (mPendingInstalls.size() > 0) { 1251 if (mBound) { 1252 disconnectService(); 1253 } 1254 if (!connectToService()) { 1255 Slog.e(TAG, "Failed to bind to media container service"); 1256 for (HandlerParams params : mPendingInstalls) { 1257 // Indicate service bind error 1258 params.serviceError(); 1259 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1260 System.identityHashCode(params)); 1261 } 1262 mPendingInstalls.clear(); 1263 } 1264 } 1265 break; 1266 } 1267 case MCS_UNBIND: { 1268 // If there is no actual work left, then time to unbind. 1269 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1270 1271 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1272 if (mBound) { 1273 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1274 1275 disconnectService(); 1276 } 1277 } else if (mPendingInstalls.size() > 0) { 1278 // There are more pending requests in queue. 1279 // Just post MCS_BOUND message to trigger processing 1280 // of next pending install. 1281 mHandler.sendEmptyMessage(MCS_BOUND); 1282 } 1283 1284 break; 1285 } 1286 case MCS_GIVE_UP: { 1287 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1288 HandlerParams params = mPendingInstalls.remove(0); 1289 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1290 System.identityHashCode(params)); 1291 break; 1292 } 1293 case SEND_PENDING_BROADCAST: { 1294 String packages[]; 1295 ArrayList<String> components[]; 1296 int size = 0; 1297 int uids[]; 1298 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1299 synchronized (mPackages) { 1300 if (mPendingBroadcasts == null) { 1301 return; 1302 } 1303 size = mPendingBroadcasts.size(); 1304 if (size <= 0) { 1305 // Nothing to be done. Just return 1306 return; 1307 } 1308 packages = new String[size]; 1309 components = new ArrayList[size]; 1310 uids = new int[size]; 1311 int i = 0; // filling out the above arrays 1312 1313 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1314 int packageUserId = mPendingBroadcasts.userIdAt(n); 1315 Iterator<Map.Entry<String, ArrayList<String>>> it 1316 = mPendingBroadcasts.packagesForUserId(packageUserId) 1317 .entrySet().iterator(); 1318 while (it.hasNext() && i < size) { 1319 Map.Entry<String, ArrayList<String>> ent = it.next(); 1320 packages[i] = ent.getKey(); 1321 components[i] = ent.getValue(); 1322 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1323 uids[i] = (ps != null) 1324 ? UserHandle.getUid(packageUserId, ps.appId) 1325 : -1; 1326 i++; 1327 } 1328 } 1329 size = i; 1330 mPendingBroadcasts.clear(); 1331 } 1332 // Send broadcasts 1333 for (int i = 0; i < size; i++) { 1334 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 break; 1338 } 1339 case START_CLEANING_PACKAGE: { 1340 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1341 final String packageName = (String)msg.obj; 1342 final int userId = msg.arg1; 1343 final boolean andCode = msg.arg2 != 0; 1344 synchronized (mPackages) { 1345 if (userId == UserHandle.USER_ALL) { 1346 int[] users = sUserManager.getUserIds(); 1347 for (int user : users) { 1348 mSettings.addPackageToCleanLPw( 1349 new PackageCleanItem(user, packageName, andCode)); 1350 } 1351 } else { 1352 mSettings.addPackageToCleanLPw( 1353 new PackageCleanItem(userId, packageName, andCode)); 1354 } 1355 } 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 startCleaningPackages(); 1358 } break; 1359 case POST_INSTALL: { 1360 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1361 PostInstallData data = mRunningInstalls.get(msg.arg1); 1362 mRunningInstalls.delete(msg.arg1); 1363 boolean deleteOld = false; 1364 1365 if (data != null) { 1366 InstallArgs args = data.args; 1367 PackageInstalledInfo res = data.res; 1368 1369 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1370 final String packageName = res.pkg.applicationInfo.packageName; 1371 res.removedInfo.sendBroadcast(false, true, false); 1372 Bundle extras = new Bundle(1); 1373 extras.putInt(Intent.EXTRA_UID, res.uid); 1374 1375 // Now that we successfully installed the package, grant runtime 1376 // permissions if requested before broadcasting the install. 1377 if ((args.installFlags 1378 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1379 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1380 args.installGrantPermissions); 1381 } 1382 1383 // Determine the set of users who are adding this 1384 // package for the first time vs. those who are seeing 1385 // an update. 1386 int[] firstUsers; 1387 int[] updateUsers = new int[0]; 1388 if (res.origUsers == null || res.origUsers.length == 0) { 1389 firstUsers = res.newUsers; 1390 } else { 1391 firstUsers = new int[0]; 1392 for (int i=0; i<res.newUsers.length; i++) { 1393 int user = res.newUsers[i]; 1394 boolean isNew = true; 1395 for (int j=0; j<res.origUsers.length; j++) { 1396 if (res.origUsers[j] == user) { 1397 isNew = false; 1398 break; 1399 } 1400 } 1401 if (isNew) { 1402 int[] newFirst = new int[firstUsers.length+1]; 1403 System.arraycopy(firstUsers, 0, newFirst, 0, 1404 firstUsers.length); 1405 newFirst[firstUsers.length] = user; 1406 firstUsers = newFirst; 1407 } else { 1408 int[] newUpdate = new int[updateUsers.length+1]; 1409 System.arraycopy(updateUsers, 0, newUpdate, 0, 1410 updateUsers.length); 1411 newUpdate[updateUsers.length] = user; 1412 updateUsers = newUpdate; 1413 } 1414 } 1415 } 1416 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1417 packageName, extras, null, null, firstUsers); 1418 final boolean update = res.removedInfo.removedPackage != null; 1419 if (update) { 1420 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1421 } 1422 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1423 packageName, extras, null, null, updateUsers); 1424 if (update) { 1425 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1426 packageName, extras, null, null, updateUsers); 1427 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1428 null, null, packageName, null, updateUsers); 1429 1430 // treat asec-hosted packages like removable media on upgrade 1431 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1432 if (DEBUG_INSTALL) { 1433 Slog.i(TAG, "upgrading pkg " + res.pkg 1434 + " is ASEC-hosted -> AVAILABLE"); 1435 } 1436 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1437 ArrayList<String> pkgList = new ArrayList<String>(1); 1438 pkgList.add(packageName); 1439 sendResourcesChangedBroadcast(true, true, 1440 pkgList,uidArray, null); 1441 } 1442 } 1443 if (res.removedInfo.args != null) { 1444 // Remove the replaced package's older resources safely now 1445 deleteOld = true; 1446 } 1447 1448 // If this app is a browser and it's newly-installed for some 1449 // users, clear any default-browser state in those users 1450 if (firstUsers.length > 0) { 1451 // the app's nature doesn't depend on the user, so we can just 1452 // check its browser nature in any user and generalize. 1453 if (packageIsBrowser(packageName, firstUsers[0])) { 1454 synchronized (mPackages) { 1455 for (int userId : firstUsers) { 1456 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1457 } 1458 } 1459 } 1460 } 1461 // Log current value of "unknown sources" setting 1462 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1463 getUnknownSourcesSettings()); 1464 } 1465 // Force a gc to clear up things 1466 Runtime.getRuntime().gc(); 1467 // We delete after a gc for applications on sdcard. 1468 if (deleteOld) { 1469 synchronized (mInstallLock) { 1470 res.removedInfo.args.doPostDeleteLI(true); 1471 } 1472 } 1473 if (args.observer != null) { 1474 try { 1475 Bundle extras = extrasForInstallResult(res); 1476 args.observer.onPackageInstalled(res.name, res.returnCode, 1477 res.returnMsg, extras); 1478 } catch (RemoteException e) { 1479 Slog.i(TAG, "Observer no longer exists."); 1480 } 1481 } 1482 if (args.traceMethod != null) { 1483 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1484 args.traceCookie); 1485 } 1486 return; 1487 } else { 1488 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1489 } 1490 1491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1492 } break; 1493 case UPDATED_MEDIA_STATUS: { 1494 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1495 boolean reportStatus = msg.arg1 == 1; 1496 boolean doGc = msg.arg2 == 1; 1497 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1498 if (doGc) { 1499 // Force a gc to clear up stale containers. 1500 Runtime.getRuntime().gc(); 1501 } 1502 if (msg.obj != null) { 1503 @SuppressWarnings("unchecked") 1504 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1506 // Unload containers 1507 unloadAllContainers(args); 1508 } 1509 if (reportStatus) { 1510 try { 1511 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1512 PackageHelper.getMountService().finishMediaUpdate(); 1513 } catch (RemoteException e) { 1514 Log.e(TAG, "MountService not running?"); 1515 } 1516 } 1517 } break; 1518 case WRITE_SETTINGS: { 1519 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1520 synchronized (mPackages) { 1521 removeMessages(WRITE_SETTINGS); 1522 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1523 mSettings.writeLPr(); 1524 mDirtyUsers.clear(); 1525 } 1526 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1527 } break; 1528 case WRITE_PACKAGE_RESTRICTIONS: { 1529 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1530 synchronized (mPackages) { 1531 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1532 for (int userId : mDirtyUsers) { 1533 mSettings.writePackageRestrictionsLPr(userId); 1534 } 1535 mDirtyUsers.clear(); 1536 } 1537 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1538 } break; 1539 case CHECK_PENDING_VERIFICATION: { 1540 final int verificationId = msg.arg1; 1541 final PackageVerificationState state = mPendingVerification.get(verificationId); 1542 1543 if ((state != null) && !state.timeoutExtended()) { 1544 final InstallArgs args = state.getInstallArgs(); 1545 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1546 1547 Slog.i(TAG, "Verification timed out for " + originUri); 1548 mPendingVerification.remove(verificationId); 1549 1550 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1551 1552 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1553 Slog.i(TAG, "Continuing with installation of " + originUri); 1554 state.setVerifierResponse(Binder.getCallingUid(), 1555 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1556 broadcastPackageVerified(verificationId, originUri, 1557 PackageManager.VERIFICATION_ALLOW, 1558 state.getInstallArgs().getUser()); 1559 try { 1560 ret = args.copyApk(mContainerService, true); 1561 } catch (RemoteException e) { 1562 Slog.e(TAG, "Could not contact the ContainerService"); 1563 } 1564 } else { 1565 broadcastPackageVerified(verificationId, originUri, 1566 PackageManager.VERIFICATION_REJECT, 1567 state.getInstallArgs().getUser()); 1568 } 1569 1570 Trace.asyncTraceEnd( 1571 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1572 1573 processPendingInstall(args, ret); 1574 mHandler.sendEmptyMessage(MCS_UNBIND); 1575 } 1576 break; 1577 } 1578 case PACKAGE_VERIFIED: { 1579 final int verificationId = msg.arg1; 1580 1581 final PackageVerificationState state = mPendingVerification.get(verificationId); 1582 if (state == null) { 1583 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1584 break; 1585 } 1586 1587 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1588 1589 state.setVerifierResponse(response.callerUid, response.code); 1590 1591 if (state.isVerificationComplete()) { 1592 mPendingVerification.remove(verificationId); 1593 1594 final InstallArgs args = state.getInstallArgs(); 1595 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1596 1597 int ret; 1598 if (state.isInstallAllowed()) { 1599 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1600 broadcastPackageVerified(verificationId, originUri, 1601 response.code, state.getInstallArgs().getUser()); 1602 try { 1603 ret = args.copyApk(mContainerService, true); 1604 } catch (RemoteException e) { 1605 Slog.e(TAG, "Could not contact the ContainerService"); 1606 } 1607 } else { 1608 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1609 } 1610 1611 Trace.asyncTraceEnd( 1612 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1613 1614 processPendingInstall(args, ret); 1615 mHandler.sendEmptyMessage(MCS_UNBIND); 1616 } 1617 1618 break; 1619 } 1620 case START_INTENT_FILTER_VERIFICATIONS: { 1621 IFVerificationParams params = (IFVerificationParams) msg.obj; 1622 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1623 params.replacing, params.pkg); 1624 break; 1625 } 1626 case INTENT_FILTER_VERIFIED: { 1627 final int verificationId = msg.arg1; 1628 1629 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1630 verificationId); 1631 if (state == null) { 1632 Slog.w(TAG, "Invalid IntentFilter verification token " 1633 + verificationId + " received"); 1634 break; 1635 } 1636 1637 final int userId = state.getUserId(); 1638 1639 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1640 "Processing IntentFilter verification with token:" 1641 + verificationId + " and userId:" + userId); 1642 1643 final IntentFilterVerificationResponse response = 1644 (IntentFilterVerificationResponse) msg.obj; 1645 1646 state.setVerifierResponse(response.callerUid, response.code); 1647 1648 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1649 "IntentFilter verification with token:" + verificationId 1650 + " and userId:" + userId 1651 + " is settings verifier response with response code:" 1652 + response.code); 1653 1654 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1655 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1656 + response.getFailedDomainsString()); 1657 } 1658 1659 if (state.isVerificationComplete()) { 1660 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1661 } else { 1662 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1663 "IntentFilter verification with token:" + verificationId 1664 + " was not said to be complete"); 1665 } 1666 1667 break; 1668 } 1669 } 1670 } 1671 } 1672 1673 private StorageEventListener mStorageListener = new StorageEventListener() { 1674 @Override 1675 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1676 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1677 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1678 final String volumeUuid = vol.getFsUuid(); 1679 1680 // Clean up any users or apps that were removed or recreated 1681 // while this volume was missing 1682 reconcileUsers(volumeUuid); 1683 reconcileApps(volumeUuid); 1684 1685 // Clean up any install sessions that expired or were 1686 // cancelled while this volume was missing 1687 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1688 1689 loadPrivatePackages(vol); 1690 1691 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1692 unloadPrivatePackages(vol); 1693 } 1694 } 1695 1696 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1697 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1698 updateExternalMediaStatus(true, false); 1699 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1700 updateExternalMediaStatus(false, false); 1701 } 1702 } 1703 } 1704 1705 @Override 1706 public void onVolumeForgotten(String fsUuid) { 1707 if (TextUtils.isEmpty(fsUuid)) { 1708 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1709 return; 1710 } 1711 1712 // Remove any apps installed on the forgotten volume 1713 synchronized (mPackages) { 1714 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1715 for (PackageSetting ps : packages) { 1716 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1717 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1718 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1719 } 1720 1721 mSettings.onVolumeForgotten(fsUuid); 1722 mSettings.writeLPr(); 1723 } 1724 } 1725 }; 1726 1727 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1728 String[] grantedPermissions) { 1729 if (userId >= UserHandle.USER_SYSTEM) { 1730 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1731 } else if (userId == UserHandle.USER_ALL) { 1732 final int[] userIds; 1733 synchronized (mPackages) { 1734 userIds = UserManagerService.getInstance().getUserIds(); 1735 } 1736 for (int someUserId : userIds) { 1737 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1738 } 1739 } 1740 1741 // We could have touched GID membership, so flush out packages.list 1742 synchronized (mPackages) { 1743 mSettings.writePackageListLPr(); 1744 } 1745 } 1746 1747 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1748 String[] grantedPermissions) { 1749 SettingBase sb = (SettingBase) pkg.mExtras; 1750 if (sb == null) { 1751 return; 1752 } 1753 1754 PermissionsState permissionsState = sb.getPermissionsState(); 1755 1756 for (String permission : pkg.requestedPermissions) { 1757 BasePermission bp = mSettings.mPermissions.get(permission); 1758 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1759 || ArrayUtils.contains(grantedPermissions, permission))) { 1760 permissionsState.grantRuntimePermission(bp, userId); 1761 } 1762 } 1763 } 1764 1765 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1766 Bundle extras = null; 1767 switch (res.returnCode) { 1768 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1769 extras = new Bundle(); 1770 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1771 res.origPermission); 1772 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1773 res.origPackage); 1774 break; 1775 } 1776 case PackageManager.INSTALL_SUCCEEDED: { 1777 extras = new Bundle(); 1778 extras.putBoolean(Intent.EXTRA_REPLACING, 1779 res.removedInfo != null && res.removedInfo.removedPackage != null); 1780 break; 1781 } 1782 } 1783 return extras; 1784 } 1785 1786 void scheduleWriteSettingsLocked() { 1787 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1788 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1789 } 1790 } 1791 1792 void scheduleWritePackageRestrictionsLocked(int userId) { 1793 if (!sUserManager.exists(userId)) return; 1794 mDirtyUsers.add(userId); 1795 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1796 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1797 } 1798 } 1799 1800 public static PackageManagerService main(Context context, Installer installer, 1801 boolean factoryTest, boolean onlyCore) { 1802 PackageManagerService m = new PackageManagerService(context, installer, 1803 factoryTest, onlyCore); 1804 ServiceManager.addService("package", m); 1805 return m; 1806 } 1807 1808 static String[] splitString(String str, char sep) { 1809 int count = 1; 1810 int i = 0; 1811 while ((i=str.indexOf(sep, i)) >= 0) { 1812 count++; 1813 i++; 1814 } 1815 1816 String[] res = new String[count]; 1817 i=0; 1818 count = 0; 1819 int lastI=0; 1820 while ((i=str.indexOf(sep, i)) >= 0) { 1821 res[count] = str.substring(lastI, i); 1822 count++; 1823 i++; 1824 lastI = i; 1825 } 1826 res[count] = str.substring(lastI, str.length()); 1827 return res; 1828 } 1829 1830 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1831 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1832 Context.DISPLAY_SERVICE); 1833 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1834 } 1835 1836 public PackageManagerService(Context context, Installer installer, 1837 boolean factoryTest, boolean onlyCore) { 1838 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1839 SystemClock.uptimeMillis()); 1840 1841 if (mSdkVersion <= 0) { 1842 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1843 } 1844 1845 mContext = context; 1846 mFactoryTest = factoryTest; 1847 mOnlyCore = onlyCore; 1848 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1849 mMetrics = new DisplayMetrics(); 1850 mSettings = new Settings(mPackages); 1851 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1852 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1853 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1854 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1855 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1856 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1857 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1858 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1859 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1860 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1861 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1862 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1863 1864 // TODO: add a property to control this? 1865 long dexOptLRUThresholdInMinutes; 1866 if (mLazyDexOpt) { 1867 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1868 } else { 1869 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1870 } 1871 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1872 1873 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1874 if (separateProcesses != null && separateProcesses.length() > 0) { 1875 if ("*".equals(separateProcesses)) { 1876 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1877 mSeparateProcesses = null; 1878 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1879 } else { 1880 mDefParseFlags = 0; 1881 mSeparateProcesses = separateProcesses.split(","); 1882 Slog.w(TAG, "Running with debug.separate_processes: " 1883 + separateProcesses); 1884 } 1885 } else { 1886 mDefParseFlags = 0; 1887 mSeparateProcesses = null; 1888 } 1889 1890 mInstaller = installer; 1891 mPackageDexOptimizer = new PackageDexOptimizer(this); 1892 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1893 1894 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1895 FgThread.get().getLooper()); 1896 1897 getDefaultDisplayMetrics(context, mMetrics); 1898 1899 SystemConfig systemConfig = SystemConfig.getInstance(); 1900 mGlobalGids = systemConfig.getGlobalGids(); 1901 mSystemPermissions = systemConfig.getSystemPermissions(); 1902 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1903 1904 synchronized (mInstallLock) { 1905 // writer 1906 synchronized (mPackages) { 1907 mHandlerThread = new ServiceThread(TAG, 1908 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1909 mHandlerThread.start(); 1910 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1911 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1912 1913 File dataDir = Environment.getDataDirectory(); 1914 mAppDataDir = new File(dataDir, "data"); 1915 mAppInstallDir = new File(dataDir, "app"); 1916 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1917 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1918 mUserAppDataDir = new File(dataDir, "user"); 1919 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1920 1921 sUserManager = new UserManagerService(context, this, 1922 mInstallLock, mPackages); 1923 1924 // Propagate permission configuration in to package manager. 1925 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1926 = systemConfig.getPermissions(); 1927 for (int i=0; i<permConfig.size(); i++) { 1928 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1929 BasePermission bp = mSettings.mPermissions.get(perm.name); 1930 if (bp == null) { 1931 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1932 mSettings.mPermissions.put(perm.name, bp); 1933 } 1934 if (perm.gids != null) { 1935 bp.setGids(perm.gids, perm.perUser); 1936 } 1937 } 1938 1939 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1940 for (int i=0; i<libConfig.size(); i++) { 1941 mSharedLibraries.put(libConfig.keyAt(i), 1942 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1943 } 1944 1945 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1946 1947 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1948 1949 String customResolverActivity = Resources.getSystem().getString( 1950 R.string.config_customResolverActivity); 1951 if (TextUtils.isEmpty(customResolverActivity)) { 1952 customResolverActivity = null; 1953 } else { 1954 mCustomResolverComponentName = ComponentName.unflattenFromString( 1955 customResolverActivity); 1956 } 1957 1958 long startTime = SystemClock.uptimeMillis(); 1959 1960 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1961 startTime); 1962 1963 // Set flag to monitor and not change apk file paths when 1964 // scanning install directories. 1965 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1966 1967 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1968 1969 /** 1970 * Add everything in the in the boot class path to the 1971 * list of process files because dexopt will have been run 1972 * if necessary during zygote startup. 1973 */ 1974 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1975 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1976 1977 if (bootClassPath != null) { 1978 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1979 for (String element : bootClassPathElements) { 1980 alreadyDexOpted.add(element); 1981 } 1982 } else { 1983 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1984 } 1985 1986 if (systemServerClassPath != null) { 1987 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1988 for (String element : systemServerClassPathElements) { 1989 alreadyDexOpted.add(element); 1990 } 1991 } else { 1992 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1993 } 1994 1995 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1996 final String[] dexCodeInstructionSets = 1997 getDexCodeInstructionSets( 1998 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1999 2000 /** 2001 * Ensure all external libraries have had dexopt run on them. 2002 */ 2003 if (mSharedLibraries.size() > 0) { 2004 // NOTE: For now, we're compiling these system "shared libraries" 2005 // (and framework jars) into all available architectures. It's possible 2006 // to compile them only when we come across an app that uses them (there's 2007 // already logic for that in scanPackageLI) but that adds some complexity. 2008 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2009 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2010 final String lib = libEntry.path; 2011 if (lib == null) { 2012 continue; 2013 } 2014 2015 try { 2016 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2017 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2018 alreadyDexOpted.add(lib); 2019 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2020 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2021 } 2022 } catch (FileNotFoundException e) { 2023 Slog.w(TAG, "Library not found: " + lib); 2024 } catch (IOException e) { 2025 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2026 + e.getMessage()); 2027 } 2028 } 2029 } 2030 } 2031 2032 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2033 2034 // Gross hack for now: we know this file doesn't contain any 2035 // code, so don't dexopt it to avoid the resulting log spew. 2036 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2037 2038 // Gross hack for now: we know this file is only part of 2039 // the boot class path for art, so don't dexopt it to 2040 // avoid the resulting log spew. 2041 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2042 2043 /** 2044 * There are a number of commands implemented in Java, which 2045 * we currently need to do the dexopt on so that they can be 2046 * run from a non-root shell. 2047 */ 2048 String[] frameworkFiles = frameworkDir.list(); 2049 if (frameworkFiles != null) { 2050 // TODO: We could compile these only for the most preferred ABI. We should 2051 // first double check that the dex files for these commands are not referenced 2052 // by other system apps. 2053 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2054 for (int i=0; i<frameworkFiles.length; i++) { 2055 File libPath = new File(frameworkDir, frameworkFiles[i]); 2056 String path = libPath.getPath(); 2057 // Skip the file if we already did it. 2058 if (alreadyDexOpted.contains(path)) { 2059 continue; 2060 } 2061 // Skip the file if it is not a type we want to dexopt. 2062 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2063 continue; 2064 } 2065 try { 2066 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2067 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2068 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 2069 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2070 } 2071 } catch (FileNotFoundException e) { 2072 Slog.w(TAG, "Jar not found: " + path); 2073 } catch (IOException e) { 2074 Slog.w(TAG, "Exception reading jar: " + path, e); 2075 } 2076 } 2077 } 2078 } 2079 2080 final VersionInfo ver = mSettings.getInternalVersion(); 2081 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2082 // when upgrading from pre-M, promote system app permissions from install to runtime 2083 mPromoteSystemApps = 2084 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2085 2086 // save off the names of pre-existing system packages prior to scanning; we don't 2087 // want to automatically grant runtime permissions for new system apps 2088 if (mPromoteSystemApps) { 2089 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2090 while (pkgSettingIter.hasNext()) { 2091 PackageSetting ps = pkgSettingIter.next(); 2092 if (isSystemApp(ps)) { 2093 mExistingSystemPackages.add(ps.name); 2094 } 2095 } 2096 } 2097 2098 // Collect vendor overlay packages. 2099 // (Do this before scanning any apps.) 2100 // For security and version matching reason, only consider 2101 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2102 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2103 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2104 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2105 2106 // Find base frameworks (resource packages without code). 2107 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2108 | PackageParser.PARSE_IS_SYSTEM_DIR 2109 | PackageParser.PARSE_IS_PRIVILEGED, 2110 scanFlags | SCAN_NO_DEX, 0); 2111 2112 // Collected privileged system packages. 2113 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2114 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR 2116 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2117 2118 // Collect ordinary system packages. 2119 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2120 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2121 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2122 2123 // Collect all vendor packages. 2124 File vendorAppDir = new File("/vendor/app"); 2125 try { 2126 vendorAppDir = vendorAppDir.getCanonicalFile(); 2127 } catch (IOException e) { 2128 // failed to look up canonical path, continue with original one 2129 } 2130 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2131 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2132 2133 // Collect all OEM packages. 2134 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2135 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2136 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2137 2138 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2139 mInstaller.moveFiles(); 2140 2141 // Prune any system packages that no longer exist. 2142 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2143 if (!mOnlyCore) { 2144 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2145 while (psit.hasNext()) { 2146 PackageSetting ps = psit.next(); 2147 2148 /* 2149 * If this is not a system app, it can't be a 2150 * disable system app. 2151 */ 2152 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2153 continue; 2154 } 2155 2156 /* 2157 * If the package is scanned, it's not erased. 2158 */ 2159 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2160 if (scannedPkg != null) { 2161 /* 2162 * If the system app is both scanned and in the 2163 * disabled packages list, then it must have been 2164 * added via OTA. Remove it from the currently 2165 * scanned package so the previously user-installed 2166 * application can be scanned. 2167 */ 2168 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2169 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2170 + ps.name + "; removing system app. Last known codePath=" 2171 + ps.codePathString + ", installStatus=" + ps.installStatus 2172 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2173 + scannedPkg.mVersionCode); 2174 removePackageLI(ps, true); 2175 mExpectingBetter.put(ps.name, ps.codePath); 2176 } 2177 2178 continue; 2179 } 2180 2181 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2182 psit.remove(); 2183 logCriticalInfo(Log.WARN, "System package " + ps.name 2184 + " no longer exists; wiping its data"); 2185 removeDataDirsLI(null, ps.name); 2186 } else { 2187 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2188 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2189 possiblyDeletedUpdatedSystemApps.add(ps.name); 2190 } 2191 } 2192 } 2193 } 2194 2195 //look for any incomplete package installations 2196 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2197 //clean up list 2198 for(int i = 0; i < deletePkgsList.size(); i++) { 2199 //clean up here 2200 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2201 } 2202 //delete tmp files 2203 deleteTempPackageFiles(); 2204 2205 // Remove any shared userIDs that have no associated packages 2206 mSettings.pruneSharedUsersLPw(); 2207 2208 if (!mOnlyCore) { 2209 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2210 SystemClock.uptimeMillis()); 2211 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2212 2213 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2214 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2215 2216 /** 2217 * Remove disable package settings for any updated system 2218 * apps that were removed via an OTA. If they're not a 2219 * previously-updated app, remove them completely. 2220 * Otherwise, just revoke their system-level permissions. 2221 */ 2222 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2223 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2224 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2225 2226 String msg; 2227 if (deletedPkg == null) { 2228 msg = "Updated system package " + deletedAppName 2229 + " no longer exists; wiping its data"; 2230 removeDataDirsLI(null, deletedAppName); 2231 } else { 2232 msg = "Updated system app + " + deletedAppName 2233 + " no longer present; removing system privileges for " 2234 + deletedAppName; 2235 2236 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2237 2238 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2239 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2240 } 2241 logCriticalInfo(Log.WARN, msg); 2242 } 2243 2244 /** 2245 * Make sure all system apps that we expected to appear on 2246 * the userdata partition actually showed up. If they never 2247 * appeared, crawl back and revive the system version. 2248 */ 2249 for (int i = 0; i < mExpectingBetter.size(); i++) { 2250 final String packageName = mExpectingBetter.keyAt(i); 2251 if (!mPackages.containsKey(packageName)) { 2252 final File scanFile = mExpectingBetter.valueAt(i); 2253 2254 logCriticalInfo(Log.WARN, "Expected better " + packageName 2255 + " but never showed up; reverting to system"); 2256 2257 final int reparseFlags; 2258 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2259 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2260 | PackageParser.PARSE_IS_SYSTEM_DIR 2261 | PackageParser.PARSE_IS_PRIVILEGED; 2262 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2263 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2264 | PackageParser.PARSE_IS_SYSTEM_DIR; 2265 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2266 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2267 | PackageParser.PARSE_IS_SYSTEM_DIR; 2268 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2269 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2270 | PackageParser.PARSE_IS_SYSTEM_DIR; 2271 } else { 2272 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2273 continue; 2274 } 2275 2276 mSettings.enableSystemPackageLPw(packageName); 2277 2278 try { 2279 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, UserHandle.SYSTEM); 2280 } catch (PackageManagerException e) { 2281 Slog.e(TAG, "Failed to parse original system package: " 2282 + e.getMessage()); 2283 } 2284 } 2285 } 2286 } 2287 mExpectingBetter.clear(); 2288 2289 // Now that we know all of the shared libraries, update all clients to have 2290 // the correct library paths. 2291 updateAllSharedLibrariesLPw(); 2292 2293 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2294 // NOTE: We ignore potential failures here during a system scan (like 2295 // the rest of the commands above) because there's precious little we 2296 // can do about it. A settings error is reported, though. 2297 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2298 false /* force dexopt */, false /* defer dexopt */, 2299 false /* boot complete */); 2300 } 2301 2302 // Now that we know all the packages we are keeping, 2303 // read and update their last usage times. 2304 mPackageUsage.readLP(); 2305 2306 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2307 SystemClock.uptimeMillis()); 2308 Slog.i(TAG, "Time to scan packages: " 2309 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2310 + " seconds"); 2311 2312 // If the platform SDK has changed since the last time we booted, 2313 // we need to re-grant app permission to catch any new ones that 2314 // appear. This is really a hack, and means that apps can in some 2315 // cases get permissions that the user didn't initially explicitly 2316 // allow... it would be nice to have some better way to handle 2317 // this situation. 2318 int updateFlags = UPDATE_PERMISSIONS_ALL; 2319 if (ver.sdkVersion != mSdkVersion) { 2320 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2321 + mSdkVersion + "; regranting permissions for internal storage"); 2322 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2323 } 2324 updatePermissionsLPw(null, null, updateFlags); 2325 ver.sdkVersion = mSdkVersion; 2326 2327 // If this is the first boot or an update from pre-M, and it is a normal 2328 // boot, then we need to initialize the default preferred apps across 2329 // all defined users. 2330 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2331 for (UserInfo user : sUserManager.getUsers(true)) { 2332 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2333 applyFactoryDefaultBrowserLPw(user.id); 2334 primeDomainVerificationsLPw(user.id); 2335 } 2336 } 2337 2338 // If this is first boot after an OTA, and a normal boot, then 2339 // we need to clear code cache directories. 2340 if (mIsUpgrade && !onlyCore) { 2341 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2342 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2343 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2344 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2345 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2346 } 2347 } 2348 ver.fingerprint = Build.FINGERPRINT; 2349 } 2350 2351 checkDefaultBrowser(); 2352 2353 // clear only after permissions and other defaults have been updated 2354 mExistingSystemPackages.clear(); 2355 mPromoteSystemApps = false; 2356 2357 // All the changes are done during package scanning. 2358 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2359 2360 // can downgrade to reader 2361 mSettings.writeLPr(); 2362 2363 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2364 SystemClock.uptimeMillis()); 2365 2366 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2367 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2368 2369 mInstallerService = new PackageInstallerService(context, this); 2370 2371 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2372 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2373 mIntentFilterVerifierComponent); 2374 2375 } // synchronized (mPackages) 2376 } // synchronized (mInstallLock) 2377 2378 // Now after opening every single application zip, make sure they 2379 // are all flushed. Not really needed, but keeps things nice and 2380 // tidy. 2381 Runtime.getRuntime().gc(); 2382 2383 // Expose private service for system components to use. 2384 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2385 } 2386 2387 @Override 2388 public boolean isFirstBoot() { 2389 return !mRestoredSettings; 2390 } 2391 2392 @Override 2393 public boolean isOnlyCoreApps() { 2394 return mOnlyCore; 2395 } 2396 2397 @Override 2398 public boolean isUpgrade() { 2399 return mIsUpgrade; 2400 } 2401 2402 private String getRequiredVerifierLPr() { 2403 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2404 // We only care about verifier that's installed under system user. 2405 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2406 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2407 2408 String requiredVerifier = null; 2409 2410 final int N = receivers.size(); 2411 for (int i = 0; i < N; i++) { 2412 final ResolveInfo info = receivers.get(i); 2413 2414 if (info.activityInfo == null) { 2415 continue; 2416 } 2417 2418 final String packageName = info.activityInfo.packageName; 2419 2420 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2421 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2422 continue; 2423 } 2424 2425 if (requiredVerifier != null) { 2426 throw new RuntimeException("There can be only one required verifier"); 2427 } 2428 2429 requiredVerifier = packageName; 2430 } 2431 2432 return requiredVerifier; 2433 } 2434 2435 private String getRequiredInstallerLPr() { 2436 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2437 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2438 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2439 2440 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2441 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2442 2443 String requiredInstaller = null; 2444 2445 final int N = installers.size(); 2446 for (int i = 0; i < N; i++) { 2447 final ResolveInfo info = installers.get(i); 2448 final String packageName = info.activityInfo.packageName; 2449 2450 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2451 continue; 2452 } 2453 2454 if (requiredInstaller != null) { 2455 throw new RuntimeException("There must be one required installer"); 2456 } 2457 2458 requiredInstaller = packageName; 2459 } 2460 2461 if (requiredInstaller == null) { 2462 throw new RuntimeException("There must be one required installer"); 2463 } 2464 2465 return requiredInstaller; 2466 } 2467 2468 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2469 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2470 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2471 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2472 2473 ComponentName verifierComponentName = null; 2474 2475 int priority = -1000; 2476 final int N = receivers.size(); 2477 for (int i = 0; i < N; i++) { 2478 final ResolveInfo info = receivers.get(i); 2479 2480 if (info.activityInfo == null) { 2481 continue; 2482 } 2483 2484 final String packageName = info.activityInfo.packageName; 2485 2486 final PackageSetting ps = mSettings.mPackages.get(packageName); 2487 if (ps == null) { 2488 continue; 2489 } 2490 2491 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2492 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2493 continue; 2494 } 2495 2496 // Select the IntentFilterVerifier with the highest priority 2497 if (priority < info.priority) { 2498 priority = info.priority; 2499 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2500 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2501 + verifierComponentName + " with priority: " + info.priority); 2502 } 2503 } 2504 2505 return verifierComponentName; 2506 } 2507 2508 private void primeDomainVerificationsLPw(int userId) { 2509 if (DEBUG_DOMAIN_VERIFICATION) { 2510 Slog.d(TAG, "Priming domain verifications in user " + userId); 2511 } 2512 2513 SystemConfig systemConfig = SystemConfig.getInstance(); 2514 ArraySet<String> packages = systemConfig.getLinkedApps(); 2515 ArraySet<String> domains = new ArraySet<String>(); 2516 2517 for (String packageName : packages) { 2518 PackageParser.Package pkg = mPackages.get(packageName); 2519 if (pkg != null) { 2520 if (!pkg.isSystemApp()) { 2521 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2522 continue; 2523 } 2524 2525 domains.clear(); 2526 for (PackageParser.Activity a : pkg.activities) { 2527 for (ActivityIntentInfo filter : a.intents) { 2528 if (hasValidDomains(filter)) { 2529 domains.addAll(filter.getHostsList()); 2530 } 2531 } 2532 } 2533 2534 if (domains.size() > 0) { 2535 if (DEBUG_DOMAIN_VERIFICATION) { 2536 Slog.v(TAG, " + " + packageName); 2537 } 2538 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2539 // state w.r.t. the formal app-linkage "no verification attempted" state; 2540 // and then 'always' in the per-user state actually used for intent resolution. 2541 final IntentFilterVerificationInfo ivi; 2542 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2543 new ArrayList<String>(domains)); 2544 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2545 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2546 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2547 } else { 2548 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2549 + "' does not handle web links"); 2550 } 2551 } else { 2552 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2553 } 2554 } 2555 2556 scheduleWritePackageRestrictionsLocked(userId); 2557 scheduleWriteSettingsLocked(); 2558 } 2559 2560 private void applyFactoryDefaultBrowserLPw(int userId) { 2561 // The default browser app's package name is stored in a string resource, 2562 // with a product-specific overlay used for vendor customization. 2563 String browserPkg = mContext.getResources().getString( 2564 com.android.internal.R.string.default_browser); 2565 if (!TextUtils.isEmpty(browserPkg)) { 2566 // non-empty string => required to be a known package 2567 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2568 if (ps == null) { 2569 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2570 browserPkg = null; 2571 } else { 2572 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2573 } 2574 } 2575 2576 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2577 // default. If there's more than one, just leave everything alone. 2578 if (browserPkg == null) { 2579 calculateDefaultBrowserLPw(userId); 2580 } 2581 } 2582 2583 private void calculateDefaultBrowserLPw(int userId) { 2584 List<String> allBrowsers = resolveAllBrowserApps(userId); 2585 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2586 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2587 } 2588 2589 private List<String> resolveAllBrowserApps(int userId) { 2590 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2591 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2592 PackageManager.MATCH_ALL, userId); 2593 2594 final int count = list.size(); 2595 List<String> result = new ArrayList<String>(count); 2596 for (int i=0; i<count; i++) { 2597 ResolveInfo info = list.get(i); 2598 if (info.activityInfo == null 2599 || !info.handleAllWebDataURI 2600 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2601 || result.contains(info.activityInfo.packageName)) { 2602 continue; 2603 } 2604 result.add(info.activityInfo.packageName); 2605 } 2606 2607 return result; 2608 } 2609 2610 private boolean packageIsBrowser(String packageName, int userId) { 2611 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2612 PackageManager.MATCH_ALL, userId); 2613 final int N = list.size(); 2614 for (int i = 0; i < N; i++) { 2615 ResolveInfo info = list.get(i); 2616 if (packageName.equals(info.activityInfo.packageName)) { 2617 return true; 2618 } 2619 } 2620 return false; 2621 } 2622 2623 private void checkDefaultBrowser() { 2624 final int myUserId = UserHandle.myUserId(); 2625 final String packageName = getDefaultBrowserPackageName(myUserId); 2626 if (packageName != null) { 2627 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2628 if (info == null) { 2629 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2630 synchronized (mPackages) { 2631 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2632 } 2633 } 2634 } 2635 } 2636 2637 @Override 2638 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2639 throws RemoteException { 2640 try { 2641 return super.onTransact(code, data, reply, flags); 2642 } catch (RuntimeException e) { 2643 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2644 Slog.wtf(TAG, "Package Manager Crash", e); 2645 } 2646 throw e; 2647 } 2648 } 2649 2650 void cleanupInstallFailedPackage(PackageSetting ps) { 2651 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2652 2653 removeDataDirsLI(ps.volumeUuid, ps.name); 2654 if (ps.codePath != null) { 2655 if (ps.codePath.isDirectory()) { 2656 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2657 } else { 2658 ps.codePath.delete(); 2659 } 2660 } 2661 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2662 if (ps.resourcePath.isDirectory()) { 2663 FileUtils.deleteContents(ps.resourcePath); 2664 } 2665 ps.resourcePath.delete(); 2666 } 2667 mSettings.removePackageLPw(ps.name); 2668 } 2669 2670 static int[] appendInts(int[] cur, int[] add) { 2671 if (add == null) return cur; 2672 if (cur == null) return add; 2673 final int N = add.length; 2674 for (int i=0; i<N; i++) { 2675 cur = appendInt(cur, add[i]); 2676 } 2677 return cur; 2678 } 2679 2680 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2681 if (!sUserManager.exists(userId)) return null; 2682 final PackageSetting ps = (PackageSetting) p.mExtras; 2683 if (ps == null) { 2684 return null; 2685 } 2686 2687 final PermissionsState permissionsState = ps.getPermissionsState(); 2688 2689 final int[] gids = permissionsState.computeGids(userId); 2690 final Set<String> permissions = permissionsState.getPermissions(userId); 2691 final PackageUserState state = ps.readUserState(userId); 2692 2693 return PackageParser.generatePackageInfo(p, gids, flags, 2694 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2695 } 2696 2697 @Override 2698 public boolean isPackageFrozen(String packageName) { 2699 synchronized (mPackages) { 2700 final PackageSetting ps = mSettings.mPackages.get(packageName); 2701 if (ps != null) { 2702 return ps.frozen; 2703 } 2704 } 2705 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2706 return true; 2707 } 2708 2709 @Override 2710 public boolean isPackageAvailable(String packageName, int userId) { 2711 if (!sUserManager.exists(userId)) return false; 2712 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2713 synchronized (mPackages) { 2714 PackageParser.Package p = mPackages.get(packageName); 2715 if (p != null) { 2716 final PackageSetting ps = (PackageSetting) p.mExtras; 2717 if (ps != null) { 2718 final PackageUserState state = ps.readUserState(userId); 2719 if (state != null) { 2720 return PackageParser.isAvailable(state); 2721 } 2722 } 2723 } 2724 } 2725 return false; 2726 } 2727 2728 @Override 2729 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2730 if (!sUserManager.exists(userId)) return null; 2731 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2732 // reader 2733 synchronized (mPackages) { 2734 PackageParser.Package p = mPackages.get(packageName); 2735 if (DEBUG_PACKAGE_INFO) 2736 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2737 if (p != null) { 2738 return generatePackageInfo(p, flags, userId); 2739 } 2740 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2741 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2742 } 2743 } 2744 return null; 2745 } 2746 2747 @Override 2748 public String[] currentToCanonicalPackageNames(String[] names) { 2749 String[] out = new String[names.length]; 2750 // reader 2751 synchronized (mPackages) { 2752 for (int i=names.length-1; i>=0; i--) { 2753 PackageSetting ps = mSettings.mPackages.get(names[i]); 2754 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2755 } 2756 } 2757 return out; 2758 } 2759 2760 @Override 2761 public String[] canonicalToCurrentPackageNames(String[] names) { 2762 String[] out = new String[names.length]; 2763 // reader 2764 synchronized (mPackages) { 2765 for (int i=names.length-1; i>=0; i--) { 2766 String cur = mSettings.mRenamedPackages.get(names[i]); 2767 out[i] = cur != null ? cur : names[i]; 2768 } 2769 } 2770 return out; 2771 } 2772 2773 @Override 2774 public int getPackageUid(String packageName, int userId) { 2775 if (!sUserManager.exists(userId)) return -1; 2776 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2777 2778 // reader 2779 synchronized (mPackages) { 2780 PackageParser.Package p = mPackages.get(packageName); 2781 if(p != null) { 2782 return UserHandle.getUid(userId, p.applicationInfo.uid); 2783 } 2784 PackageSetting ps = mSettings.mPackages.get(packageName); 2785 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2786 return -1; 2787 } 2788 return UserHandle.getUid(userId, ps.pkg.applicationInfo.uid); 2789 } 2790 } 2791 2792 @Override 2793 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2794 if (!sUserManager.exists(userId)) { 2795 return null; 2796 } 2797 2798 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2799 "getPackageGids"); 2800 2801 // reader 2802 synchronized (mPackages) { 2803 PackageParser.Package p = mPackages.get(packageName); 2804 if (DEBUG_PACKAGE_INFO) { 2805 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2806 } 2807 if (p != null) { 2808 PackageSetting ps = (PackageSetting) p.mExtras; 2809 return ps.getPermissionsState().computeGids(userId); 2810 } 2811 } 2812 2813 return null; 2814 } 2815 2816 static PermissionInfo generatePermissionInfo( 2817 BasePermission bp, int flags) { 2818 if (bp.perm != null) { 2819 return PackageParser.generatePermissionInfo(bp.perm, flags); 2820 } 2821 PermissionInfo pi = new PermissionInfo(); 2822 pi.name = bp.name; 2823 pi.packageName = bp.sourcePackage; 2824 pi.nonLocalizedLabel = bp.name; 2825 pi.protectionLevel = bp.protectionLevel; 2826 return pi; 2827 } 2828 2829 @Override 2830 public PermissionInfo getPermissionInfo(String name, int flags) { 2831 // reader 2832 synchronized (mPackages) { 2833 final BasePermission p = mSettings.mPermissions.get(name); 2834 if (p != null) { 2835 return generatePermissionInfo(p, flags); 2836 } 2837 return null; 2838 } 2839 } 2840 2841 @Override 2842 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2843 // reader 2844 synchronized (mPackages) { 2845 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2846 for (BasePermission p : mSettings.mPermissions.values()) { 2847 if (group == null) { 2848 if (p.perm == null || p.perm.info.group == null) { 2849 out.add(generatePermissionInfo(p, flags)); 2850 } 2851 } else { 2852 if (p.perm != null && group.equals(p.perm.info.group)) { 2853 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2854 } 2855 } 2856 } 2857 2858 if (out.size() > 0) { 2859 return out; 2860 } 2861 return mPermissionGroups.containsKey(group) ? out : null; 2862 } 2863 } 2864 2865 @Override 2866 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2867 // reader 2868 synchronized (mPackages) { 2869 return PackageParser.generatePermissionGroupInfo( 2870 mPermissionGroups.get(name), flags); 2871 } 2872 } 2873 2874 @Override 2875 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2876 // reader 2877 synchronized (mPackages) { 2878 final int N = mPermissionGroups.size(); 2879 ArrayList<PermissionGroupInfo> out 2880 = new ArrayList<PermissionGroupInfo>(N); 2881 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2882 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2883 } 2884 return out; 2885 } 2886 } 2887 2888 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2889 int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 PackageSetting ps = mSettings.mPackages.get(packageName); 2892 if (ps != null) { 2893 if (ps.pkg == null) { 2894 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2895 flags, userId); 2896 if (pInfo != null) { 2897 return pInfo.applicationInfo; 2898 } 2899 return null; 2900 } 2901 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2902 ps.readUserState(userId), userId); 2903 } 2904 return null; 2905 } 2906 2907 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2908 int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 PackageSetting ps = mSettings.mPackages.get(packageName); 2911 if (ps != null) { 2912 PackageParser.Package pkg = ps.pkg; 2913 if (pkg == null) { 2914 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2915 return null; 2916 } 2917 // Only data remains, so we aren't worried about code paths 2918 pkg = new PackageParser.Package(packageName); 2919 pkg.applicationInfo.packageName = packageName; 2920 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2921 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2922 pkg.applicationInfo.dataDir = Environment 2923 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2924 .getAbsolutePath(); 2925 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2926 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2927 } 2928 return generatePackageInfo(pkg, flags, userId); 2929 } 2930 return null; 2931 } 2932 2933 @Override 2934 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2935 if (!sUserManager.exists(userId)) return null; 2936 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2937 // writer 2938 synchronized (mPackages) { 2939 PackageParser.Package p = mPackages.get(packageName); 2940 if (DEBUG_PACKAGE_INFO) Log.v( 2941 TAG, "getApplicationInfo " + packageName 2942 + ": " + p); 2943 if (p != null) { 2944 PackageSetting ps = mSettings.mPackages.get(packageName); 2945 if (ps == null) return null; 2946 // Note: isEnabledLP() does not apply here - always return info 2947 return PackageParser.generateApplicationInfo( 2948 p, flags, ps.readUserState(userId), userId); 2949 } 2950 if ("android".equals(packageName)||"system".equals(packageName)) { 2951 return mAndroidApplication; 2952 } 2953 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2954 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2955 } 2956 } 2957 return null; 2958 } 2959 2960 @Override 2961 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2962 final IPackageDataObserver observer) { 2963 mContext.enforceCallingOrSelfPermission( 2964 android.Manifest.permission.CLEAR_APP_CACHE, null); 2965 // Queue up an async operation since clearing cache may take a little while. 2966 mHandler.post(new Runnable() { 2967 public void run() { 2968 mHandler.removeCallbacks(this); 2969 int retCode = -1; 2970 synchronized (mInstallLock) { 2971 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2972 if (retCode < 0) { 2973 Slog.w(TAG, "Couldn't clear application caches"); 2974 } 2975 } 2976 if (observer != null) { 2977 try { 2978 observer.onRemoveCompleted(null, (retCode >= 0)); 2979 } catch (RemoteException e) { 2980 Slog.w(TAG, "RemoveException when invoking call back"); 2981 } 2982 } 2983 } 2984 }); 2985 } 2986 2987 @Override 2988 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2989 final IntentSender pi) { 2990 mContext.enforceCallingOrSelfPermission( 2991 android.Manifest.permission.CLEAR_APP_CACHE, null); 2992 // Queue up an async operation since clearing cache may take a little while. 2993 mHandler.post(new Runnable() { 2994 public void run() { 2995 mHandler.removeCallbacks(this); 2996 int retCode = -1; 2997 synchronized (mInstallLock) { 2998 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2999 if (retCode < 0) { 3000 Slog.w(TAG, "Couldn't clear application caches"); 3001 } 3002 } 3003 if(pi != null) { 3004 try { 3005 // Callback via pending intent 3006 int code = (retCode >= 0) ? 1 : 0; 3007 pi.sendIntent(null, code, null, 3008 null, null); 3009 } catch (SendIntentException e1) { 3010 Slog.i(TAG, "Failed to send pending intent"); 3011 } 3012 } 3013 } 3014 }); 3015 } 3016 3017 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3018 synchronized (mInstallLock) { 3019 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3020 throw new IOException("Failed to free enough space"); 3021 } 3022 } 3023 } 3024 3025 @Override 3026 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3027 if (!sUserManager.exists(userId)) return null; 3028 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3029 synchronized (mPackages) { 3030 PackageParser.Activity a = mActivities.mActivities.get(component); 3031 3032 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3033 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3034 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3035 if (ps == null) return null; 3036 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3037 userId); 3038 } 3039 if (mResolveComponentName.equals(component)) { 3040 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3041 new PackageUserState(), userId); 3042 } 3043 } 3044 return null; 3045 } 3046 3047 @Override 3048 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3049 String resolvedType) { 3050 synchronized (mPackages) { 3051 if (component.equals(mResolveComponentName)) { 3052 // The resolver supports EVERYTHING! 3053 return true; 3054 } 3055 PackageParser.Activity a = mActivities.mActivities.get(component); 3056 if (a == null) { 3057 return false; 3058 } 3059 for (int i=0; i<a.intents.size(); i++) { 3060 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3061 intent.getData(), intent.getCategories(), TAG) >= 0) { 3062 return true; 3063 } 3064 } 3065 return false; 3066 } 3067 } 3068 3069 @Override 3070 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3071 if (!sUserManager.exists(userId)) return null; 3072 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3073 synchronized (mPackages) { 3074 PackageParser.Activity a = mReceivers.mActivities.get(component); 3075 if (DEBUG_PACKAGE_INFO) Log.v( 3076 TAG, "getReceiverInfo " + component + ": " + a); 3077 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3078 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3079 if (ps == null) return null; 3080 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3081 userId); 3082 } 3083 } 3084 return null; 3085 } 3086 3087 @Override 3088 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3089 if (!sUserManager.exists(userId)) return null; 3090 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3091 synchronized (mPackages) { 3092 PackageParser.Service s = mServices.mServices.get(component); 3093 if (DEBUG_PACKAGE_INFO) Log.v( 3094 TAG, "getServiceInfo " + component + ": " + s); 3095 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3096 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3097 if (ps == null) return null; 3098 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3099 userId); 3100 } 3101 } 3102 return null; 3103 } 3104 3105 @Override 3106 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3107 if (!sUserManager.exists(userId)) return null; 3108 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3109 synchronized (mPackages) { 3110 PackageParser.Provider p = mProviders.mProviders.get(component); 3111 if (DEBUG_PACKAGE_INFO) Log.v( 3112 TAG, "getProviderInfo " + component + ": " + p); 3113 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3114 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3115 if (ps == null) return null; 3116 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3117 userId); 3118 } 3119 } 3120 return null; 3121 } 3122 3123 @Override 3124 public String[] getSystemSharedLibraryNames() { 3125 Set<String> libSet; 3126 synchronized (mPackages) { 3127 libSet = mSharedLibraries.keySet(); 3128 int size = libSet.size(); 3129 if (size > 0) { 3130 String[] libs = new String[size]; 3131 libSet.toArray(libs); 3132 return libs; 3133 } 3134 } 3135 return null; 3136 } 3137 3138 /** 3139 * @hide 3140 */ 3141 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3142 synchronized (mPackages) { 3143 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3144 if (lib != null && lib.apk != null) { 3145 return mPackages.get(lib.apk); 3146 } 3147 } 3148 return null; 3149 } 3150 3151 @Override 3152 public FeatureInfo[] getSystemAvailableFeatures() { 3153 Collection<FeatureInfo> featSet; 3154 synchronized (mPackages) { 3155 featSet = mAvailableFeatures.values(); 3156 int size = featSet.size(); 3157 if (size > 0) { 3158 FeatureInfo[] features = new FeatureInfo[size+1]; 3159 featSet.toArray(features); 3160 FeatureInfo fi = new FeatureInfo(); 3161 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3162 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3163 features[size] = fi; 3164 return features; 3165 } 3166 } 3167 return null; 3168 } 3169 3170 @Override 3171 public boolean hasSystemFeature(String name) { 3172 synchronized (mPackages) { 3173 return mAvailableFeatures.containsKey(name); 3174 } 3175 } 3176 3177 private void checkValidCaller(int uid, int userId) { 3178 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3179 return; 3180 3181 throw new SecurityException("Caller uid=" + uid 3182 + " is not privileged to communicate with user=" + userId); 3183 } 3184 3185 @Override 3186 public int checkPermission(String permName, String pkgName, int userId) { 3187 if (!sUserManager.exists(userId)) { 3188 return PackageManager.PERMISSION_DENIED; 3189 } 3190 3191 synchronized (mPackages) { 3192 final PackageParser.Package p = mPackages.get(pkgName); 3193 if (p != null && p.mExtras != null) { 3194 final PackageSetting ps = (PackageSetting) p.mExtras; 3195 final PermissionsState permissionsState = ps.getPermissionsState(); 3196 if (permissionsState.hasPermission(permName, userId)) { 3197 return PackageManager.PERMISSION_GRANTED; 3198 } 3199 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3200 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3201 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3202 return PackageManager.PERMISSION_GRANTED; 3203 } 3204 } 3205 } 3206 3207 return PackageManager.PERMISSION_DENIED; 3208 } 3209 3210 @Override 3211 public int checkUidPermission(String permName, int uid) { 3212 final int userId = UserHandle.getUserId(uid); 3213 3214 if (!sUserManager.exists(userId)) { 3215 return PackageManager.PERMISSION_DENIED; 3216 } 3217 3218 synchronized (mPackages) { 3219 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3220 if (obj != null) { 3221 final SettingBase ps = (SettingBase) obj; 3222 final PermissionsState permissionsState = ps.getPermissionsState(); 3223 if (permissionsState.hasPermission(permName, userId)) { 3224 return PackageManager.PERMISSION_GRANTED; 3225 } 3226 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3227 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3228 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3229 return PackageManager.PERMISSION_GRANTED; 3230 } 3231 } else { 3232 ArraySet<String> perms = mSystemPermissions.get(uid); 3233 if (perms != null) { 3234 if (perms.contains(permName)) { 3235 return PackageManager.PERMISSION_GRANTED; 3236 } 3237 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3238 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3239 return PackageManager.PERMISSION_GRANTED; 3240 } 3241 } 3242 } 3243 } 3244 3245 return PackageManager.PERMISSION_DENIED; 3246 } 3247 3248 @Override 3249 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3250 if (UserHandle.getCallingUserId() != userId) { 3251 mContext.enforceCallingPermission( 3252 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3253 "isPermissionRevokedByPolicy for user " + userId); 3254 } 3255 3256 if (checkPermission(permission, packageName, userId) 3257 == PackageManager.PERMISSION_GRANTED) { 3258 return false; 3259 } 3260 3261 final long identity = Binder.clearCallingIdentity(); 3262 try { 3263 final int flags = getPermissionFlags(permission, packageName, userId); 3264 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3265 } finally { 3266 Binder.restoreCallingIdentity(identity); 3267 } 3268 } 3269 3270 @Override 3271 public String getPermissionControllerPackageName() { 3272 synchronized (mPackages) { 3273 return mRequiredInstallerPackage; 3274 } 3275 } 3276 3277 /** 3278 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3279 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3280 * @param checkShell TODO(yamasani): 3281 * @param message the message to log on security exception 3282 */ 3283 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3284 boolean checkShell, String message) { 3285 if (userId < 0) { 3286 throw new IllegalArgumentException("Invalid userId " + userId); 3287 } 3288 if (checkShell) { 3289 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3290 } 3291 if (userId == UserHandle.getUserId(callingUid)) return; 3292 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3293 if (requireFullPermission) { 3294 mContext.enforceCallingOrSelfPermission( 3295 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3296 } else { 3297 try { 3298 mContext.enforceCallingOrSelfPermission( 3299 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3300 } catch (SecurityException se) { 3301 mContext.enforceCallingOrSelfPermission( 3302 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3303 } 3304 } 3305 } 3306 } 3307 3308 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3309 if (callingUid == Process.SHELL_UID) { 3310 if (userHandle >= 0 3311 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3312 throw new SecurityException("Shell does not have permission to access user " 3313 + userHandle); 3314 } else if (userHandle < 0) { 3315 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3316 + Debug.getCallers(3)); 3317 } 3318 } 3319 } 3320 3321 private BasePermission findPermissionTreeLP(String permName) { 3322 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3323 if (permName.startsWith(bp.name) && 3324 permName.length() > bp.name.length() && 3325 permName.charAt(bp.name.length()) == '.') { 3326 return bp; 3327 } 3328 } 3329 return null; 3330 } 3331 3332 private BasePermission checkPermissionTreeLP(String permName) { 3333 if (permName != null) { 3334 BasePermission bp = findPermissionTreeLP(permName); 3335 if (bp != null) { 3336 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3337 return bp; 3338 } 3339 throw new SecurityException("Calling uid " 3340 + Binder.getCallingUid() 3341 + " is not allowed to add to permission tree " 3342 + bp.name + " owned by uid " + bp.uid); 3343 } 3344 } 3345 throw new SecurityException("No permission tree found for " + permName); 3346 } 3347 3348 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3349 if (s1 == null) { 3350 return s2 == null; 3351 } 3352 if (s2 == null) { 3353 return false; 3354 } 3355 if (s1.getClass() != s2.getClass()) { 3356 return false; 3357 } 3358 return s1.equals(s2); 3359 } 3360 3361 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3362 if (pi1.icon != pi2.icon) return false; 3363 if (pi1.logo != pi2.logo) return false; 3364 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3365 if (!compareStrings(pi1.name, pi2.name)) return false; 3366 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3367 // We'll take care of setting this one. 3368 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3369 // These are not currently stored in settings. 3370 //if (!compareStrings(pi1.group, pi2.group)) return false; 3371 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3372 //if (pi1.labelRes != pi2.labelRes) return false; 3373 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3374 return true; 3375 } 3376 3377 int permissionInfoFootprint(PermissionInfo info) { 3378 int size = info.name.length(); 3379 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3380 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3381 return size; 3382 } 3383 3384 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3385 int size = 0; 3386 for (BasePermission perm : mSettings.mPermissions.values()) { 3387 if (perm.uid == tree.uid) { 3388 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3389 } 3390 } 3391 return size; 3392 } 3393 3394 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3395 // We calculate the max size of permissions defined by this uid and throw 3396 // if that plus the size of 'info' would exceed our stated maximum. 3397 if (tree.uid != Process.SYSTEM_UID) { 3398 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3399 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3400 throw new SecurityException("Permission tree size cap exceeded"); 3401 } 3402 } 3403 } 3404 3405 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3406 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3407 throw new SecurityException("Label must be specified in permission"); 3408 } 3409 BasePermission tree = checkPermissionTreeLP(info.name); 3410 BasePermission bp = mSettings.mPermissions.get(info.name); 3411 boolean added = bp == null; 3412 boolean changed = true; 3413 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3414 if (added) { 3415 enforcePermissionCapLocked(info, tree); 3416 bp = new BasePermission(info.name, tree.sourcePackage, 3417 BasePermission.TYPE_DYNAMIC); 3418 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3419 throw new SecurityException( 3420 "Not allowed to modify non-dynamic permission " 3421 + info.name); 3422 } else { 3423 if (bp.protectionLevel == fixedLevel 3424 && bp.perm.owner.equals(tree.perm.owner) 3425 && bp.uid == tree.uid 3426 && comparePermissionInfos(bp.perm.info, info)) { 3427 changed = false; 3428 } 3429 } 3430 bp.protectionLevel = fixedLevel; 3431 info = new PermissionInfo(info); 3432 info.protectionLevel = fixedLevel; 3433 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3434 bp.perm.info.packageName = tree.perm.info.packageName; 3435 bp.uid = tree.uid; 3436 if (added) { 3437 mSettings.mPermissions.put(info.name, bp); 3438 } 3439 if (changed) { 3440 if (!async) { 3441 mSettings.writeLPr(); 3442 } else { 3443 scheduleWriteSettingsLocked(); 3444 } 3445 } 3446 return added; 3447 } 3448 3449 @Override 3450 public boolean addPermission(PermissionInfo info) { 3451 synchronized (mPackages) { 3452 return addPermissionLocked(info, false); 3453 } 3454 } 3455 3456 @Override 3457 public boolean addPermissionAsync(PermissionInfo info) { 3458 synchronized (mPackages) { 3459 return addPermissionLocked(info, true); 3460 } 3461 } 3462 3463 @Override 3464 public void removePermission(String name) { 3465 synchronized (mPackages) { 3466 checkPermissionTreeLP(name); 3467 BasePermission bp = mSettings.mPermissions.get(name); 3468 if (bp != null) { 3469 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3470 throw new SecurityException( 3471 "Not allowed to modify non-dynamic permission " 3472 + name); 3473 } 3474 mSettings.mPermissions.remove(name); 3475 mSettings.writeLPr(); 3476 } 3477 } 3478 } 3479 3480 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3481 BasePermission bp) { 3482 int index = pkg.requestedPermissions.indexOf(bp.name); 3483 if (index == -1) { 3484 throw new SecurityException("Package " + pkg.packageName 3485 + " has not requested permission " + bp.name); 3486 } 3487 if (!bp.isRuntime() && !bp.isDevelopment()) { 3488 throw new SecurityException("Permission " + bp.name 3489 + " is not a changeable permission type"); 3490 } 3491 } 3492 3493 @Override 3494 public void grantRuntimePermission(String packageName, String name, final int userId) { 3495 if (!sUserManager.exists(userId)) { 3496 Log.e(TAG, "No such user:" + userId); 3497 return; 3498 } 3499 3500 mContext.enforceCallingOrSelfPermission( 3501 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3502 "grantRuntimePermission"); 3503 3504 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3505 "grantRuntimePermission"); 3506 3507 final int uid; 3508 final SettingBase sb; 3509 3510 synchronized (mPackages) { 3511 final PackageParser.Package pkg = mPackages.get(packageName); 3512 if (pkg == null) { 3513 throw new IllegalArgumentException("Unknown package: " + packageName); 3514 } 3515 3516 final BasePermission bp = mSettings.mPermissions.get(name); 3517 if (bp == null) { 3518 throw new IllegalArgumentException("Unknown permission: " + name); 3519 } 3520 3521 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3522 3523 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3524 sb = (SettingBase) pkg.mExtras; 3525 if (sb == null) { 3526 throw new IllegalArgumentException("Unknown package: " + packageName); 3527 } 3528 3529 final PermissionsState permissionsState = sb.getPermissionsState(); 3530 3531 final int flags = permissionsState.getPermissionFlags(name, userId); 3532 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3533 throw new SecurityException("Cannot grant system fixed permission: " 3534 + name + " for package: " + packageName); 3535 } 3536 3537 if (bp.isDevelopment()) { 3538 // Development permissions must be handled specially, since they are not 3539 // normal runtime permissions. For now they apply to all users. 3540 if (permissionsState.grantInstallPermission(bp) != 3541 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3542 scheduleWriteSettingsLocked(); 3543 } 3544 return; 3545 } 3546 3547 final int result = permissionsState.grantRuntimePermission(bp, userId); 3548 switch (result) { 3549 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3550 return; 3551 } 3552 3553 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3554 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3555 mHandler.post(new Runnable() { 3556 @Override 3557 public void run() { 3558 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3559 } 3560 }); 3561 } break; 3562 } 3563 3564 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3565 3566 // Not critical if that is lost - app has to request again. 3567 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3568 } 3569 3570 // Only need to do this if user is initialized. Otherwise it's a new user 3571 // and there are no processes running as the user yet and there's no need 3572 // to make an expensive call to remount processes for the changed permissions. 3573 if (READ_EXTERNAL_STORAGE.equals(name) 3574 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3575 final long token = Binder.clearCallingIdentity(); 3576 try { 3577 if (sUserManager.isInitialized(userId)) { 3578 MountServiceInternal mountServiceInternal = LocalServices.getService( 3579 MountServiceInternal.class); 3580 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3581 } 3582 } finally { 3583 Binder.restoreCallingIdentity(token); 3584 } 3585 } 3586 } 3587 3588 @Override 3589 public void revokeRuntimePermission(String packageName, String name, int userId) { 3590 if (!sUserManager.exists(userId)) { 3591 Log.e(TAG, "No such user:" + userId); 3592 return; 3593 } 3594 3595 mContext.enforceCallingOrSelfPermission( 3596 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3597 "revokeRuntimePermission"); 3598 3599 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3600 "revokeRuntimePermission"); 3601 3602 final int appId; 3603 3604 synchronized (mPackages) { 3605 final PackageParser.Package pkg = mPackages.get(packageName); 3606 if (pkg == null) { 3607 throw new IllegalArgumentException("Unknown package: " + packageName); 3608 } 3609 3610 final BasePermission bp = mSettings.mPermissions.get(name); 3611 if (bp == null) { 3612 throw new IllegalArgumentException("Unknown permission: " + name); 3613 } 3614 3615 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3616 3617 SettingBase sb = (SettingBase) pkg.mExtras; 3618 if (sb == null) { 3619 throw new IllegalArgumentException("Unknown package: " + packageName); 3620 } 3621 3622 final PermissionsState permissionsState = sb.getPermissionsState(); 3623 3624 final int flags = permissionsState.getPermissionFlags(name, userId); 3625 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3626 throw new SecurityException("Cannot revoke system fixed permission: " 3627 + name + " for package: " + packageName); 3628 } 3629 3630 if (bp.isDevelopment()) { 3631 // Development permissions must be handled specially, since they are not 3632 // normal runtime permissions. For now they apply to all users. 3633 if (permissionsState.revokeInstallPermission(bp) != 3634 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3635 scheduleWriteSettingsLocked(); 3636 } 3637 return; 3638 } 3639 3640 if (permissionsState.revokeRuntimePermission(bp, userId) == 3641 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3642 return; 3643 } 3644 3645 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3646 3647 // Critical, after this call app should never have the permission. 3648 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3649 3650 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3651 } 3652 3653 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3654 } 3655 3656 @Override 3657 public void resetRuntimePermissions() { 3658 mContext.enforceCallingOrSelfPermission( 3659 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3660 "revokeRuntimePermission"); 3661 3662 int callingUid = Binder.getCallingUid(); 3663 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3664 mContext.enforceCallingOrSelfPermission( 3665 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3666 "resetRuntimePermissions"); 3667 } 3668 3669 synchronized (mPackages) { 3670 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3671 for (int userId : UserManagerService.getInstance().getUserIds()) { 3672 final int packageCount = mPackages.size(); 3673 for (int i = 0; i < packageCount; i++) { 3674 PackageParser.Package pkg = mPackages.valueAt(i); 3675 if (!(pkg.mExtras instanceof PackageSetting)) { 3676 continue; 3677 } 3678 PackageSetting ps = (PackageSetting) pkg.mExtras; 3679 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3680 } 3681 } 3682 } 3683 } 3684 3685 @Override 3686 public int getPermissionFlags(String name, String packageName, int userId) { 3687 if (!sUserManager.exists(userId)) { 3688 return 0; 3689 } 3690 3691 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3692 3693 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3694 "getPermissionFlags"); 3695 3696 synchronized (mPackages) { 3697 final PackageParser.Package pkg = mPackages.get(packageName); 3698 if (pkg == null) { 3699 throw new IllegalArgumentException("Unknown package: " + packageName); 3700 } 3701 3702 final BasePermission bp = mSettings.mPermissions.get(name); 3703 if (bp == null) { 3704 throw new IllegalArgumentException("Unknown permission: " + name); 3705 } 3706 3707 SettingBase sb = (SettingBase) pkg.mExtras; 3708 if (sb == null) { 3709 throw new IllegalArgumentException("Unknown package: " + packageName); 3710 } 3711 3712 PermissionsState permissionsState = sb.getPermissionsState(); 3713 return permissionsState.getPermissionFlags(name, userId); 3714 } 3715 } 3716 3717 @Override 3718 public void updatePermissionFlags(String name, String packageName, int flagMask, 3719 int flagValues, int userId) { 3720 if (!sUserManager.exists(userId)) { 3721 return; 3722 } 3723 3724 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3725 3726 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3727 "updatePermissionFlags"); 3728 3729 // Only the system can change these flags and nothing else. 3730 if (getCallingUid() != Process.SYSTEM_UID) { 3731 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3732 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3733 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3734 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3735 } 3736 3737 synchronized (mPackages) { 3738 final PackageParser.Package pkg = mPackages.get(packageName); 3739 if (pkg == null) { 3740 throw new IllegalArgumentException("Unknown package: " + packageName); 3741 } 3742 3743 final BasePermission bp = mSettings.mPermissions.get(name); 3744 if (bp == null) { 3745 throw new IllegalArgumentException("Unknown permission: " + name); 3746 } 3747 3748 SettingBase sb = (SettingBase) pkg.mExtras; 3749 if (sb == null) { 3750 throw new IllegalArgumentException("Unknown package: " + packageName); 3751 } 3752 3753 PermissionsState permissionsState = sb.getPermissionsState(); 3754 3755 // Only the package manager can change flags for system component permissions. 3756 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3757 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3758 return; 3759 } 3760 3761 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3762 3763 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3764 // Install and runtime permissions are stored in different places, 3765 // so figure out what permission changed and persist the change. 3766 if (permissionsState.getInstallPermissionState(name) != null) { 3767 scheduleWriteSettingsLocked(); 3768 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3769 || hadState) { 3770 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3771 } 3772 } 3773 } 3774 } 3775 3776 /** 3777 * Update the permission flags for all packages and runtime permissions of a user in order 3778 * to allow device or profile owner to remove POLICY_FIXED. 3779 */ 3780 @Override 3781 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3782 if (!sUserManager.exists(userId)) { 3783 return; 3784 } 3785 3786 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3787 3788 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3789 "updatePermissionFlagsForAllApps"); 3790 3791 // Only the system can change system fixed flags. 3792 if (getCallingUid() != Process.SYSTEM_UID) { 3793 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3794 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3795 } 3796 3797 synchronized (mPackages) { 3798 boolean changed = false; 3799 final int packageCount = mPackages.size(); 3800 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3801 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3802 SettingBase sb = (SettingBase) pkg.mExtras; 3803 if (sb == null) { 3804 continue; 3805 } 3806 PermissionsState permissionsState = sb.getPermissionsState(); 3807 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3808 userId, flagMask, flagValues); 3809 } 3810 if (changed) { 3811 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3812 } 3813 } 3814 } 3815 3816 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3817 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3818 != PackageManager.PERMISSION_GRANTED 3819 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3820 != PackageManager.PERMISSION_GRANTED) { 3821 throw new SecurityException(message + " requires " 3822 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3823 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3824 } 3825 } 3826 3827 @Override 3828 public boolean shouldShowRequestPermissionRationale(String permissionName, 3829 String packageName, int userId) { 3830 if (UserHandle.getCallingUserId() != userId) { 3831 mContext.enforceCallingPermission( 3832 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3833 "canShowRequestPermissionRationale for user " + userId); 3834 } 3835 3836 final int uid = getPackageUid(packageName, userId); 3837 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3838 return false; 3839 } 3840 3841 if (checkPermission(permissionName, packageName, userId) 3842 == PackageManager.PERMISSION_GRANTED) { 3843 return false; 3844 } 3845 3846 final int flags; 3847 3848 final long identity = Binder.clearCallingIdentity(); 3849 try { 3850 flags = getPermissionFlags(permissionName, 3851 packageName, userId); 3852 } finally { 3853 Binder.restoreCallingIdentity(identity); 3854 } 3855 3856 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3857 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3858 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3859 3860 if ((flags & fixedFlags) != 0) { 3861 return false; 3862 } 3863 3864 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3865 } 3866 3867 @Override 3868 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3869 mContext.enforceCallingOrSelfPermission( 3870 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3871 "addOnPermissionsChangeListener"); 3872 3873 synchronized (mPackages) { 3874 mOnPermissionChangeListeners.addListenerLocked(listener); 3875 } 3876 } 3877 3878 @Override 3879 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3880 synchronized (mPackages) { 3881 mOnPermissionChangeListeners.removeListenerLocked(listener); 3882 } 3883 } 3884 3885 @Override 3886 public boolean isProtectedBroadcast(String actionName) { 3887 synchronized (mPackages) { 3888 return mProtectedBroadcasts.contains(actionName); 3889 } 3890 } 3891 3892 @Override 3893 public int checkSignatures(String pkg1, String pkg2) { 3894 synchronized (mPackages) { 3895 final PackageParser.Package p1 = mPackages.get(pkg1); 3896 final PackageParser.Package p2 = mPackages.get(pkg2); 3897 if (p1 == null || p1.mExtras == null 3898 || p2 == null || p2.mExtras == null) { 3899 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3900 } 3901 return compareSignatures(p1.mSignatures, p2.mSignatures); 3902 } 3903 } 3904 3905 @Override 3906 public int checkUidSignatures(int uid1, int uid2) { 3907 // Map to base uids. 3908 uid1 = UserHandle.getAppId(uid1); 3909 uid2 = UserHandle.getAppId(uid2); 3910 // reader 3911 synchronized (mPackages) { 3912 Signature[] s1; 3913 Signature[] s2; 3914 Object obj = mSettings.getUserIdLPr(uid1); 3915 if (obj != null) { 3916 if (obj instanceof SharedUserSetting) { 3917 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3918 } else if (obj instanceof PackageSetting) { 3919 s1 = ((PackageSetting)obj).signatures.mSignatures; 3920 } else { 3921 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3922 } 3923 } else { 3924 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3925 } 3926 obj = mSettings.getUserIdLPr(uid2); 3927 if (obj != null) { 3928 if (obj instanceof SharedUserSetting) { 3929 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3930 } else if (obj instanceof PackageSetting) { 3931 s2 = ((PackageSetting)obj).signatures.mSignatures; 3932 } else { 3933 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3934 } 3935 } else { 3936 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3937 } 3938 return compareSignatures(s1, s2); 3939 } 3940 } 3941 3942 private void killUid(int appId, int userId, String reason) { 3943 final long identity = Binder.clearCallingIdentity(); 3944 try { 3945 IActivityManager am = ActivityManagerNative.getDefault(); 3946 if (am != null) { 3947 try { 3948 am.killUid(appId, userId, reason); 3949 } catch (RemoteException e) { 3950 /* ignore - same process */ 3951 } 3952 } 3953 } finally { 3954 Binder.restoreCallingIdentity(identity); 3955 } 3956 } 3957 3958 /** 3959 * Compares two sets of signatures. Returns: 3960 * <br /> 3961 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3962 * <br /> 3963 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3964 * <br /> 3965 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3966 * <br /> 3967 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3968 * <br /> 3969 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3970 */ 3971 static int compareSignatures(Signature[] s1, Signature[] s2) { 3972 if (s1 == null) { 3973 return s2 == null 3974 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3975 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3976 } 3977 3978 if (s2 == null) { 3979 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3980 } 3981 3982 if (s1.length != s2.length) { 3983 return PackageManager.SIGNATURE_NO_MATCH; 3984 } 3985 3986 // Since both signature sets are of size 1, we can compare without HashSets. 3987 if (s1.length == 1) { 3988 return s1[0].equals(s2[0]) ? 3989 PackageManager.SIGNATURE_MATCH : 3990 PackageManager.SIGNATURE_NO_MATCH; 3991 } 3992 3993 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3994 for (Signature sig : s1) { 3995 set1.add(sig); 3996 } 3997 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3998 for (Signature sig : s2) { 3999 set2.add(sig); 4000 } 4001 // Make sure s2 contains all signatures in s1. 4002 if (set1.equals(set2)) { 4003 return PackageManager.SIGNATURE_MATCH; 4004 } 4005 return PackageManager.SIGNATURE_NO_MATCH; 4006 } 4007 4008 /** 4009 * If the database version for this type of package (internal storage or 4010 * external storage) is less than the version where package signatures 4011 * were updated, return true. 4012 */ 4013 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4014 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4015 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4016 } 4017 4018 /** 4019 * Used for backward compatibility to make sure any packages with 4020 * certificate chains get upgraded to the new style. {@code existingSigs} 4021 * will be in the old format (since they were stored on disk from before the 4022 * system upgrade) and {@code scannedSigs} will be in the newer format. 4023 */ 4024 private int compareSignaturesCompat(PackageSignatures existingSigs, 4025 PackageParser.Package scannedPkg) { 4026 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4027 return PackageManager.SIGNATURE_NO_MATCH; 4028 } 4029 4030 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4031 for (Signature sig : existingSigs.mSignatures) { 4032 existingSet.add(sig); 4033 } 4034 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4035 for (Signature sig : scannedPkg.mSignatures) { 4036 try { 4037 Signature[] chainSignatures = sig.getChainSignatures(); 4038 for (Signature chainSig : chainSignatures) { 4039 scannedCompatSet.add(chainSig); 4040 } 4041 } catch (CertificateEncodingException e) { 4042 scannedCompatSet.add(sig); 4043 } 4044 } 4045 /* 4046 * Make sure the expanded scanned set contains all signatures in the 4047 * existing one. 4048 */ 4049 if (scannedCompatSet.equals(existingSet)) { 4050 // Migrate the old signatures to the new scheme. 4051 existingSigs.assignSignatures(scannedPkg.mSignatures); 4052 // The new KeySets will be re-added later in the scanning process. 4053 synchronized (mPackages) { 4054 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4055 } 4056 return PackageManager.SIGNATURE_MATCH; 4057 } 4058 return PackageManager.SIGNATURE_NO_MATCH; 4059 } 4060 4061 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4062 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4063 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4064 } 4065 4066 private int compareSignaturesRecover(PackageSignatures existingSigs, 4067 PackageParser.Package scannedPkg) { 4068 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4069 return PackageManager.SIGNATURE_NO_MATCH; 4070 } 4071 4072 String msg = null; 4073 try { 4074 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4075 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4076 + scannedPkg.packageName); 4077 return PackageManager.SIGNATURE_MATCH; 4078 } 4079 } catch (CertificateException e) { 4080 msg = e.getMessage(); 4081 } 4082 4083 logCriticalInfo(Log.INFO, 4084 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4085 return PackageManager.SIGNATURE_NO_MATCH; 4086 } 4087 4088 @Override 4089 public String[] getPackagesForUid(int uid) { 4090 uid = UserHandle.getAppId(uid); 4091 // reader 4092 synchronized (mPackages) { 4093 Object obj = mSettings.getUserIdLPr(uid); 4094 if (obj instanceof SharedUserSetting) { 4095 final SharedUserSetting sus = (SharedUserSetting) obj; 4096 final int N = sus.packages.size(); 4097 final String[] res = new String[N]; 4098 final Iterator<PackageSetting> it = sus.packages.iterator(); 4099 int i = 0; 4100 while (it.hasNext()) { 4101 res[i++] = it.next().name; 4102 } 4103 return res; 4104 } else if (obj instanceof PackageSetting) { 4105 final PackageSetting ps = (PackageSetting) obj; 4106 return new String[] { ps.name }; 4107 } 4108 } 4109 return null; 4110 } 4111 4112 @Override 4113 public String getNameForUid(int uid) { 4114 // reader 4115 synchronized (mPackages) { 4116 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4117 if (obj instanceof SharedUserSetting) { 4118 final SharedUserSetting sus = (SharedUserSetting) obj; 4119 return sus.name + ":" + sus.userId; 4120 } else if (obj instanceof PackageSetting) { 4121 final PackageSetting ps = (PackageSetting) obj; 4122 return ps.name; 4123 } 4124 } 4125 return null; 4126 } 4127 4128 @Override 4129 public int getUidForSharedUser(String sharedUserName) { 4130 if(sharedUserName == null) { 4131 return -1; 4132 } 4133 // reader 4134 synchronized (mPackages) { 4135 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4136 if (suid == null) { 4137 return -1; 4138 } 4139 return suid.userId; 4140 } 4141 } 4142 4143 @Override 4144 public int getFlagsForUid(int uid) { 4145 synchronized (mPackages) { 4146 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4147 if (obj instanceof SharedUserSetting) { 4148 final SharedUserSetting sus = (SharedUserSetting) obj; 4149 return sus.pkgFlags; 4150 } else if (obj instanceof PackageSetting) { 4151 final PackageSetting ps = (PackageSetting) obj; 4152 return ps.pkgFlags; 4153 } 4154 } 4155 return 0; 4156 } 4157 4158 @Override 4159 public int getPrivateFlagsForUid(int uid) { 4160 synchronized (mPackages) { 4161 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4162 if (obj instanceof SharedUserSetting) { 4163 final SharedUserSetting sus = (SharedUserSetting) obj; 4164 return sus.pkgPrivateFlags; 4165 } else if (obj instanceof PackageSetting) { 4166 final PackageSetting ps = (PackageSetting) obj; 4167 return ps.pkgPrivateFlags; 4168 } 4169 } 4170 return 0; 4171 } 4172 4173 @Override 4174 public boolean isUidPrivileged(int uid) { 4175 uid = UserHandle.getAppId(uid); 4176 // reader 4177 synchronized (mPackages) { 4178 Object obj = mSettings.getUserIdLPr(uid); 4179 if (obj instanceof SharedUserSetting) { 4180 final SharedUserSetting sus = (SharedUserSetting) obj; 4181 final Iterator<PackageSetting> it = sus.packages.iterator(); 4182 while (it.hasNext()) { 4183 if (it.next().isPrivileged()) { 4184 return true; 4185 } 4186 } 4187 } else if (obj instanceof PackageSetting) { 4188 final PackageSetting ps = (PackageSetting) obj; 4189 return ps.isPrivileged(); 4190 } 4191 } 4192 return false; 4193 } 4194 4195 @Override 4196 public String[] getAppOpPermissionPackages(String permissionName) { 4197 synchronized (mPackages) { 4198 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4199 if (pkgs == null) { 4200 return null; 4201 } 4202 return pkgs.toArray(new String[pkgs.size()]); 4203 } 4204 } 4205 4206 @Override 4207 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4208 int flags, int userId) { 4209 if (!sUserManager.exists(userId)) return null; 4210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4211 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4212 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4213 } 4214 4215 @Override 4216 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4217 IntentFilter filter, int match, ComponentName activity) { 4218 final int userId = UserHandle.getCallingUserId(); 4219 if (DEBUG_PREFERRED) { 4220 Log.v(TAG, "setLastChosenActivity intent=" + intent 4221 + " resolvedType=" + resolvedType 4222 + " flags=" + flags 4223 + " filter=" + filter 4224 + " match=" + match 4225 + " activity=" + activity); 4226 filter.dump(new PrintStreamPrinter(System.out), " "); 4227 } 4228 intent.setComponent(null); 4229 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4230 // Find any earlier preferred or last chosen entries and nuke them 4231 findPreferredActivity(intent, resolvedType, 4232 flags, query, 0, false, true, false, userId); 4233 // Add the new activity as the last chosen for this filter 4234 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4235 "Setting last chosen"); 4236 } 4237 4238 @Override 4239 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4240 final int userId = UserHandle.getCallingUserId(); 4241 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4242 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4243 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4244 false, false, false, userId); 4245 } 4246 4247 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4248 int flags, List<ResolveInfo> query, int userId) { 4249 if (query != null) { 4250 final int N = query.size(); 4251 if (N == 1) { 4252 return query.get(0); 4253 } else if (N > 1) { 4254 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4255 // If there is more than one activity with the same priority, 4256 // then let the user decide between them. 4257 ResolveInfo r0 = query.get(0); 4258 ResolveInfo r1 = query.get(1); 4259 if (DEBUG_INTENT_MATCHING || debug) { 4260 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4261 + r1.activityInfo.name + "=" + r1.priority); 4262 } 4263 // If the first activity has a higher priority, or a different 4264 // default, then it is always desireable to pick it. 4265 if (r0.priority != r1.priority 4266 || r0.preferredOrder != r1.preferredOrder 4267 || r0.isDefault != r1.isDefault) { 4268 return query.get(0); 4269 } 4270 // If we have saved a preference for a preferred activity for 4271 // this Intent, use that. 4272 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4273 flags, query, r0.priority, true, false, debug, userId); 4274 if (ri != null) { 4275 return ri; 4276 } 4277 ri = new ResolveInfo(mResolveInfo); 4278 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4279 ri.activityInfo.applicationInfo = new ApplicationInfo( 4280 ri.activityInfo.applicationInfo); 4281 if (userId != 0) { 4282 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4283 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4284 } 4285 // Make sure that the resolver is displayable in car mode 4286 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4287 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4288 return ri; 4289 } 4290 } 4291 return null; 4292 } 4293 4294 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4295 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4296 final int N = query.size(); 4297 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4298 .get(userId); 4299 // Get the list of persistent preferred activities that handle the intent 4300 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4301 List<PersistentPreferredActivity> pprefs = ppir != null 4302 ? ppir.queryIntent(intent, resolvedType, 4303 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4304 : null; 4305 if (pprefs != null && pprefs.size() > 0) { 4306 final int M = pprefs.size(); 4307 for (int i=0; i<M; i++) { 4308 final PersistentPreferredActivity ppa = pprefs.get(i); 4309 if (DEBUG_PREFERRED || debug) { 4310 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4311 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4312 + "\n component=" + ppa.mComponent); 4313 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4314 } 4315 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4316 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4317 if (DEBUG_PREFERRED || debug) { 4318 Slog.v(TAG, "Found persistent preferred activity:"); 4319 if (ai != null) { 4320 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4321 } else { 4322 Slog.v(TAG, " null"); 4323 } 4324 } 4325 if (ai == null) { 4326 // This previously registered persistent preferred activity 4327 // component is no longer known. Ignore it and do NOT remove it. 4328 continue; 4329 } 4330 for (int j=0; j<N; j++) { 4331 final ResolveInfo ri = query.get(j); 4332 if (!ri.activityInfo.applicationInfo.packageName 4333 .equals(ai.applicationInfo.packageName)) { 4334 continue; 4335 } 4336 if (!ri.activityInfo.name.equals(ai.name)) { 4337 continue; 4338 } 4339 // Found a persistent preference that can handle the intent. 4340 if (DEBUG_PREFERRED || debug) { 4341 Slog.v(TAG, "Returning persistent preferred activity: " + 4342 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4343 } 4344 return ri; 4345 } 4346 } 4347 } 4348 return null; 4349 } 4350 4351 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4352 List<ResolveInfo> query, int priority, boolean always, 4353 boolean removeMatches, boolean debug, int userId) { 4354 if (!sUserManager.exists(userId)) return null; 4355 // writer 4356 synchronized (mPackages) { 4357 if (intent.getSelector() != null) { 4358 intent = intent.getSelector(); 4359 } 4360 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4361 4362 // Try to find a matching persistent preferred activity. 4363 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4364 debug, userId); 4365 4366 // If a persistent preferred activity matched, use it. 4367 if (pri != null) { 4368 return pri; 4369 } 4370 4371 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4372 // Get the list of preferred activities that handle the intent 4373 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4374 List<PreferredActivity> prefs = pir != null 4375 ? pir.queryIntent(intent, resolvedType, 4376 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4377 : null; 4378 if (prefs != null && prefs.size() > 0) { 4379 boolean changed = false; 4380 try { 4381 // First figure out how good the original match set is. 4382 // We will only allow preferred activities that came 4383 // from the same match quality. 4384 int match = 0; 4385 4386 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4387 4388 final int N = query.size(); 4389 for (int j=0; j<N; j++) { 4390 final ResolveInfo ri = query.get(j); 4391 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4392 + ": 0x" + Integer.toHexString(match)); 4393 if (ri.match > match) { 4394 match = ri.match; 4395 } 4396 } 4397 4398 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4399 + Integer.toHexString(match)); 4400 4401 match &= IntentFilter.MATCH_CATEGORY_MASK; 4402 final int M = prefs.size(); 4403 for (int i=0; i<M; i++) { 4404 final PreferredActivity pa = prefs.get(i); 4405 if (DEBUG_PREFERRED || debug) { 4406 Slog.v(TAG, "Checking PreferredActivity ds=" 4407 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4408 + "\n component=" + pa.mPref.mComponent); 4409 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4410 } 4411 if (pa.mPref.mMatch != match) { 4412 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4413 + Integer.toHexString(pa.mPref.mMatch)); 4414 continue; 4415 } 4416 // If it's not an "always" type preferred activity and that's what we're 4417 // looking for, skip it. 4418 if (always && !pa.mPref.mAlways) { 4419 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4420 continue; 4421 } 4422 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4423 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4424 if (DEBUG_PREFERRED || debug) { 4425 Slog.v(TAG, "Found preferred activity:"); 4426 if (ai != null) { 4427 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4428 } else { 4429 Slog.v(TAG, " null"); 4430 } 4431 } 4432 if (ai == null) { 4433 // This previously registered preferred activity 4434 // component is no longer known. Most likely an update 4435 // to the app was installed and in the new version this 4436 // component no longer exists. Clean it up by removing 4437 // it from the preferred activities list, and skip it. 4438 Slog.w(TAG, "Removing dangling preferred activity: " 4439 + pa.mPref.mComponent); 4440 pir.removeFilter(pa); 4441 changed = true; 4442 continue; 4443 } 4444 for (int j=0; j<N; j++) { 4445 final ResolveInfo ri = query.get(j); 4446 if (!ri.activityInfo.applicationInfo.packageName 4447 .equals(ai.applicationInfo.packageName)) { 4448 continue; 4449 } 4450 if (!ri.activityInfo.name.equals(ai.name)) { 4451 continue; 4452 } 4453 4454 if (removeMatches) { 4455 pir.removeFilter(pa); 4456 changed = true; 4457 if (DEBUG_PREFERRED) { 4458 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4459 } 4460 break; 4461 } 4462 4463 // Okay we found a previously set preferred or last chosen app. 4464 // If the result set is different from when this 4465 // was created, we need to clear it and re-ask the 4466 // user their preference, if we're looking for an "always" type entry. 4467 if (always && !pa.mPref.sameSet(query)) { 4468 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4469 + intent + " type " + resolvedType); 4470 if (DEBUG_PREFERRED) { 4471 Slog.v(TAG, "Removing preferred activity since set changed " 4472 + pa.mPref.mComponent); 4473 } 4474 pir.removeFilter(pa); 4475 // Re-add the filter as a "last chosen" entry (!always) 4476 PreferredActivity lastChosen = new PreferredActivity( 4477 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4478 pir.addFilter(lastChosen); 4479 changed = true; 4480 return null; 4481 } 4482 4483 // Yay! Either the set matched or we're looking for the last chosen 4484 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4485 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4486 return ri; 4487 } 4488 } 4489 } finally { 4490 if (changed) { 4491 if (DEBUG_PREFERRED) { 4492 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4493 } 4494 scheduleWritePackageRestrictionsLocked(userId); 4495 } 4496 } 4497 } 4498 } 4499 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4500 return null; 4501 } 4502 4503 /* 4504 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4505 */ 4506 @Override 4507 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4508 int targetUserId) { 4509 mContext.enforceCallingOrSelfPermission( 4510 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4511 List<CrossProfileIntentFilter> matches = 4512 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4513 if (matches != null) { 4514 int size = matches.size(); 4515 for (int i = 0; i < size; i++) { 4516 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4517 } 4518 } 4519 if (hasWebURI(intent)) { 4520 // cross-profile app linking works only towards the parent. 4521 final UserInfo parent = getProfileParent(sourceUserId); 4522 synchronized(mPackages) { 4523 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4524 intent, resolvedType, 0, sourceUserId, parent.id); 4525 return xpDomainInfo != null; 4526 } 4527 } 4528 return false; 4529 } 4530 4531 private UserInfo getProfileParent(int userId) { 4532 final long identity = Binder.clearCallingIdentity(); 4533 try { 4534 return sUserManager.getProfileParent(userId); 4535 } finally { 4536 Binder.restoreCallingIdentity(identity); 4537 } 4538 } 4539 4540 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4541 String resolvedType, int userId) { 4542 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4543 if (resolver != null) { 4544 return resolver.queryIntent(intent, resolvedType, false, userId); 4545 } 4546 return null; 4547 } 4548 4549 @Override 4550 public List<ResolveInfo> queryIntentActivities(Intent intent, 4551 String resolvedType, int flags, int userId) { 4552 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4553 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4554 ComponentName comp = intent.getComponent(); 4555 if (comp == null) { 4556 if (intent.getSelector() != null) { 4557 intent = intent.getSelector(); 4558 comp = intent.getComponent(); 4559 } 4560 } 4561 4562 if (comp != null) { 4563 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4564 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4565 if (ai != null) { 4566 final ResolveInfo ri = new ResolveInfo(); 4567 ri.activityInfo = ai; 4568 list.add(ri); 4569 } 4570 return list; 4571 } 4572 4573 // reader 4574 synchronized (mPackages) { 4575 final String pkgName = intent.getPackage(); 4576 if (pkgName == null) { 4577 List<CrossProfileIntentFilter> matchingFilters = 4578 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4579 // Check for results that need to skip the current profile. 4580 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4581 resolvedType, flags, userId); 4582 if (xpResolveInfo != null) { 4583 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4584 result.add(xpResolveInfo); 4585 return filterIfNotSystemUser(result, userId); 4586 } 4587 4588 // Check for results in the current profile. 4589 List<ResolveInfo> result = mActivities.queryIntent( 4590 intent, resolvedType, flags, userId); 4591 4592 // Check for cross profile results. 4593 xpResolveInfo = queryCrossProfileIntents( 4594 matchingFilters, intent, resolvedType, flags, userId); 4595 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4596 result.add(xpResolveInfo); 4597 Collections.sort(result, mResolvePrioritySorter); 4598 } 4599 result = filterIfNotSystemUser(result, userId); 4600 if (hasWebURI(intent)) { 4601 CrossProfileDomainInfo xpDomainInfo = null; 4602 final UserInfo parent = getProfileParent(userId); 4603 if (parent != null) { 4604 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4605 flags, userId, parent.id); 4606 } 4607 if (xpDomainInfo != null) { 4608 if (xpResolveInfo != null) { 4609 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4610 // in the result. 4611 result.remove(xpResolveInfo); 4612 } 4613 if (result.size() == 0) { 4614 result.add(xpDomainInfo.resolveInfo); 4615 return result; 4616 } 4617 } else if (result.size() <= 1) { 4618 return result; 4619 } 4620 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4621 xpDomainInfo, userId); 4622 Collections.sort(result, mResolvePrioritySorter); 4623 } 4624 return result; 4625 } 4626 final PackageParser.Package pkg = mPackages.get(pkgName); 4627 if (pkg != null) { 4628 return filterIfNotSystemUser( 4629 mActivities.queryIntentForPackage( 4630 intent, resolvedType, flags, pkg.activities, userId), 4631 userId); 4632 } 4633 return new ArrayList<ResolveInfo>(); 4634 } 4635 } 4636 4637 private static class CrossProfileDomainInfo { 4638 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4639 ResolveInfo resolveInfo; 4640 /* Best domain verification status of the activities found in the other profile */ 4641 int bestDomainVerificationStatus; 4642 } 4643 4644 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4645 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4646 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4647 sourceUserId)) { 4648 return null; 4649 } 4650 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4651 resolvedType, flags, parentUserId); 4652 4653 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4654 return null; 4655 } 4656 CrossProfileDomainInfo result = null; 4657 int size = resultTargetUser.size(); 4658 for (int i = 0; i < size; i++) { 4659 ResolveInfo riTargetUser = resultTargetUser.get(i); 4660 // Intent filter verification is only for filters that specify a host. So don't return 4661 // those that handle all web uris. 4662 if (riTargetUser.handleAllWebDataURI) { 4663 continue; 4664 } 4665 String packageName = riTargetUser.activityInfo.packageName; 4666 PackageSetting ps = mSettings.mPackages.get(packageName); 4667 if (ps == null) { 4668 continue; 4669 } 4670 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4671 int status = (int)(verificationState >> 32); 4672 if (result == null) { 4673 result = new CrossProfileDomainInfo(); 4674 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4675 sourceUserId, parentUserId); 4676 result.bestDomainVerificationStatus = status; 4677 } else { 4678 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4679 result.bestDomainVerificationStatus); 4680 } 4681 } 4682 // Don't consider matches with status NEVER across profiles. 4683 if (result != null && result.bestDomainVerificationStatus 4684 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4685 return null; 4686 } 4687 return result; 4688 } 4689 4690 /** 4691 * Verification statuses are ordered from the worse to the best, except for 4692 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4693 */ 4694 private int bestDomainVerificationStatus(int status1, int status2) { 4695 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4696 return status2; 4697 } 4698 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4699 return status1; 4700 } 4701 return (int) MathUtils.max(status1, status2); 4702 } 4703 4704 private boolean isUserEnabled(int userId) { 4705 long callingId = Binder.clearCallingIdentity(); 4706 try { 4707 UserInfo userInfo = sUserManager.getUserInfo(userId); 4708 return userInfo != null && userInfo.isEnabled(); 4709 } finally { 4710 Binder.restoreCallingIdentity(callingId); 4711 } 4712 } 4713 4714 /** 4715 * Filter out activities with systemUserOnly flag set, when current user is not System. 4716 * 4717 * @return filtered list 4718 */ 4719 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4720 if (userId == UserHandle.USER_SYSTEM) { 4721 return resolveInfos; 4722 } 4723 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4724 ResolveInfo info = resolveInfos.get(i); 4725 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4726 resolveInfos.remove(i); 4727 } 4728 } 4729 return resolveInfos; 4730 } 4731 4732 private static boolean hasWebURI(Intent intent) { 4733 if (intent.getData() == null) { 4734 return false; 4735 } 4736 final String scheme = intent.getScheme(); 4737 if (TextUtils.isEmpty(scheme)) { 4738 return false; 4739 } 4740 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4741 } 4742 4743 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4744 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4745 int userId) { 4746 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4747 4748 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4749 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4750 candidates.size()); 4751 } 4752 4753 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4754 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4755 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4756 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4757 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4758 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4759 4760 synchronized (mPackages) { 4761 final int count = candidates.size(); 4762 // First, try to use linked apps. Partition the candidates into four lists: 4763 // one for the final results, one for the "do not use ever", one for "undefined status" 4764 // and finally one for "browser app type". 4765 for (int n=0; n<count; n++) { 4766 ResolveInfo info = candidates.get(n); 4767 String packageName = info.activityInfo.packageName; 4768 PackageSetting ps = mSettings.mPackages.get(packageName); 4769 if (ps != null) { 4770 // Add to the special match all list (Browser use case) 4771 if (info.handleAllWebDataURI) { 4772 matchAllList.add(info); 4773 continue; 4774 } 4775 // Try to get the status from User settings first 4776 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4777 int status = (int)(packedStatus >> 32); 4778 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4779 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4780 if (DEBUG_DOMAIN_VERIFICATION) { 4781 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4782 + " : linkgen=" + linkGeneration); 4783 } 4784 // Use link-enabled generation as preferredOrder, i.e. 4785 // prefer newly-enabled over earlier-enabled. 4786 info.preferredOrder = linkGeneration; 4787 alwaysList.add(info); 4788 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4789 if (DEBUG_DOMAIN_VERIFICATION) { 4790 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4791 } 4792 neverList.add(info); 4793 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4794 if (DEBUG_DOMAIN_VERIFICATION) { 4795 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4796 } 4797 alwaysAskList.add(info); 4798 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4799 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4800 if (DEBUG_DOMAIN_VERIFICATION) { 4801 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4802 } 4803 undefinedList.add(info); 4804 } 4805 } 4806 } 4807 4808 // We'll want to include browser possibilities in a few cases 4809 boolean includeBrowser = false; 4810 4811 // First try to add the "always" resolution(s) for the current user, if any 4812 if (alwaysList.size() > 0) { 4813 result.addAll(alwaysList); 4814 // if there is an "always" for the parent user, add it. 4815 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4816 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4817 result.add(xpDomainInfo.resolveInfo); 4818 } else { 4819 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4820 result.addAll(undefinedList); 4821 if (xpDomainInfo != null && ( 4822 xpDomainInfo.bestDomainVerificationStatus 4823 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4824 || xpDomainInfo.bestDomainVerificationStatus 4825 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4826 result.add(xpDomainInfo.resolveInfo); 4827 } 4828 includeBrowser = true; 4829 } 4830 4831 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4832 // If there were 'always' entries their preferred order has been set, so we also 4833 // back that off to make the alternatives equivalent 4834 if (alwaysAskList.size() > 0) { 4835 for (ResolveInfo i : result) { 4836 i.preferredOrder = 0; 4837 } 4838 result.addAll(alwaysAskList); 4839 includeBrowser = true; 4840 } 4841 4842 if (includeBrowser) { 4843 // Also add browsers (all of them or only the default one) 4844 if (DEBUG_DOMAIN_VERIFICATION) { 4845 Slog.v(TAG, " ...including browsers in candidate set"); 4846 } 4847 if ((matchFlags & MATCH_ALL) != 0) { 4848 result.addAll(matchAllList); 4849 } else { 4850 // Browser/generic handling case. If there's a default browser, go straight 4851 // to that (but only if there is no other higher-priority match). 4852 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4853 int maxMatchPrio = 0; 4854 ResolveInfo defaultBrowserMatch = null; 4855 final int numCandidates = matchAllList.size(); 4856 for (int n = 0; n < numCandidates; n++) { 4857 ResolveInfo info = matchAllList.get(n); 4858 // track the highest overall match priority... 4859 if (info.priority > maxMatchPrio) { 4860 maxMatchPrio = info.priority; 4861 } 4862 // ...and the highest-priority default browser match 4863 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4864 if (defaultBrowserMatch == null 4865 || (defaultBrowserMatch.priority < info.priority)) { 4866 if (debug) { 4867 Slog.v(TAG, "Considering default browser match " + info); 4868 } 4869 defaultBrowserMatch = info; 4870 } 4871 } 4872 } 4873 if (defaultBrowserMatch != null 4874 && defaultBrowserMatch.priority >= maxMatchPrio 4875 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4876 { 4877 if (debug) { 4878 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4879 } 4880 result.add(defaultBrowserMatch); 4881 } else { 4882 result.addAll(matchAllList); 4883 } 4884 } 4885 4886 // If there is nothing selected, add all candidates and remove the ones that the user 4887 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4888 if (result.size() == 0) { 4889 result.addAll(candidates); 4890 result.removeAll(neverList); 4891 } 4892 } 4893 } 4894 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4895 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4896 result.size()); 4897 for (ResolveInfo info : result) { 4898 Slog.v(TAG, " + " + info.activityInfo); 4899 } 4900 } 4901 return result; 4902 } 4903 4904 // Returns a packed value as a long: 4905 // 4906 // high 'int'-sized word: link status: undefined/ask/never/always. 4907 // low 'int'-sized word: relative priority among 'always' results. 4908 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4909 long result = ps.getDomainVerificationStatusForUser(userId); 4910 // if none available, get the master status 4911 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4912 if (ps.getIntentFilterVerificationInfo() != null) { 4913 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4914 } 4915 } 4916 return result; 4917 } 4918 4919 private ResolveInfo querySkipCurrentProfileIntents( 4920 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4921 int flags, int sourceUserId) { 4922 if (matchingFilters != null) { 4923 int size = matchingFilters.size(); 4924 for (int i = 0; i < size; i ++) { 4925 CrossProfileIntentFilter filter = matchingFilters.get(i); 4926 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4927 // Checking if there are activities in the target user that can handle the 4928 // intent. 4929 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4930 resolvedType, flags, sourceUserId); 4931 if (resolveInfo != null) { 4932 return resolveInfo; 4933 } 4934 } 4935 } 4936 } 4937 return null; 4938 } 4939 4940 // Return matching ResolveInfo if any for skip current profile intent filters. 4941 private ResolveInfo queryCrossProfileIntents( 4942 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4943 int flags, int sourceUserId) { 4944 if (matchingFilters != null) { 4945 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4946 // match the same intent. For performance reasons, it is better not to 4947 // run queryIntent twice for the same userId 4948 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4949 int size = matchingFilters.size(); 4950 for (int i = 0; i < size; i++) { 4951 CrossProfileIntentFilter filter = matchingFilters.get(i); 4952 int targetUserId = filter.getTargetUserId(); 4953 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4954 && !alreadyTriedUserIds.get(targetUserId)) { 4955 // Checking if there are activities in the target user that can handle the 4956 // intent. 4957 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4958 resolvedType, flags, sourceUserId); 4959 if (resolveInfo != null) return resolveInfo; 4960 alreadyTriedUserIds.put(targetUserId, true); 4961 } 4962 } 4963 } 4964 return null; 4965 } 4966 4967 /** 4968 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4969 * will forward the intent to the filter's target user. 4970 * Otherwise, returns null. 4971 */ 4972 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4973 String resolvedType, int flags, int sourceUserId) { 4974 int targetUserId = filter.getTargetUserId(); 4975 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4976 resolvedType, flags, targetUserId); 4977 if (resultTargetUser != null && !resultTargetUser.isEmpty() 4978 && isUserEnabled(targetUserId)) { 4979 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 4980 } 4981 return null; 4982 } 4983 4984 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 4985 int sourceUserId, int targetUserId) { 4986 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4987 long ident = Binder.clearCallingIdentity(); 4988 boolean targetIsProfile; 4989 try { 4990 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4991 } finally { 4992 Binder.restoreCallingIdentity(ident); 4993 } 4994 String className; 4995 if (targetIsProfile) { 4996 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4997 } else { 4998 className = FORWARD_INTENT_TO_PARENT; 4999 } 5000 ComponentName forwardingActivityComponentName = new ComponentName( 5001 mAndroidApplication.packageName, className); 5002 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5003 sourceUserId); 5004 if (!targetIsProfile) { 5005 forwardingActivityInfo.showUserIcon = targetUserId; 5006 forwardingResolveInfo.noResourceId = true; 5007 } 5008 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5009 forwardingResolveInfo.priority = 0; 5010 forwardingResolveInfo.preferredOrder = 0; 5011 forwardingResolveInfo.match = 0; 5012 forwardingResolveInfo.isDefault = true; 5013 forwardingResolveInfo.filter = filter; 5014 forwardingResolveInfo.targetUserId = targetUserId; 5015 return forwardingResolveInfo; 5016 } 5017 5018 @Override 5019 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5020 Intent[] specifics, String[] specificTypes, Intent intent, 5021 String resolvedType, int flags, int userId) { 5022 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5023 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5024 false, "query intent activity options"); 5025 final String resultsAction = intent.getAction(); 5026 5027 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5028 | PackageManager.GET_RESOLVED_FILTER, userId); 5029 5030 if (DEBUG_INTENT_MATCHING) { 5031 Log.v(TAG, "Query " + intent + ": " + results); 5032 } 5033 5034 int specificsPos = 0; 5035 int N; 5036 5037 // todo: note that the algorithm used here is O(N^2). This 5038 // isn't a problem in our current environment, but if we start running 5039 // into situations where we have more than 5 or 10 matches then this 5040 // should probably be changed to something smarter... 5041 5042 // First we go through and resolve each of the specific items 5043 // that were supplied, taking care of removing any corresponding 5044 // duplicate items in the generic resolve list. 5045 if (specifics != null) { 5046 for (int i=0; i<specifics.length; i++) { 5047 final Intent sintent = specifics[i]; 5048 if (sintent == null) { 5049 continue; 5050 } 5051 5052 if (DEBUG_INTENT_MATCHING) { 5053 Log.v(TAG, "Specific #" + i + ": " + sintent); 5054 } 5055 5056 String action = sintent.getAction(); 5057 if (resultsAction != null && resultsAction.equals(action)) { 5058 // If this action was explicitly requested, then don't 5059 // remove things that have it. 5060 action = null; 5061 } 5062 5063 ResolveInfo ri = null; 5064 ActivityInfo ai = null; 5065 5066 ComponentName comp = sintent.getComponent(); 5067 if (comp == null) { 5068 ri = resolveIntent( 5069 sintent, 5070 specificTypes != null ? specificTypes[i] : null, 5071 flags, userId); 5072 if (ri == null) { 5073 continue; 5074 } 5075 if (ri == mResolveInfo) { 5076 // ACK! Must do something better with this. 5077 } 5078 ai = ri.activityInfo; 5079 comp = new ComponentName(ai.applicationInfo.packageName, 5080 ai.name); 5081 } else { 5082 ai = getActivityInfo(comp, flags, userId); 5083 if (ai == null) { 5084 continue; 5085 } 5086 } 5087 5088 // Look for any generic query activities that are duplicates 5089 // of this specific one, and remove them from the results. 5090 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5091 N = results.size(); 5092 int j; 5093 for (j=specificsPos; j<N; j++) { 5094 ResolveInfo sri = results.get(j); 5095 if ((sri.activityInfo.name.equals(comp.getClassName()) 5096 && sri.activityInfo.applicationInfo.packageName.equals( 5097 comp.getPackageName())) 5098 || (action != null && sri.filter.matchAction(action))) { 5099 results.remove(j); 5100 if (DEBUG_INTENT_MATCHING) Log.v( 5101 TAG, "Removing duplicate item from " + j 5102 + " due to specific " + specificsPos); 5103 if (ri == null) { 5104 ri = sri; 5105 } 5106 j--; 5107 N--; 5108 } 5109 } 5110 5111 // Add this specific item to its proper place. 5112 if (ri == null) { 5113 ri = new ResolveInfo(); 5114 ri.activityInfo = ai; 5115 } 5116 results.add(specificsPos, ri); 5117 ri.specificIndex = i; 5118 specificsPos++; 5119 } 5120 } 5121 5122 // Now we go through the remaining generic results and remove any 5123 // duplicate actions that are found here. 5124 N = results.size(); 5125 for (int i=specificsPos; i<N-1; i++) { 5126 final ResolveInfo rii = results.get(i); 5127 if (rii.filter == null) { 5128 continue; 5129 } 5130 5131 // Iterate over all of the actions of this result's intent 5132 // filter... typically this should be just one. 5133 final Iterator<String> it = rii.filter.actionsIterator(); 5134 if (it == null) { 5135 continue; 5136 } 5137 while (it.hasNext()) { 5138 final String action = it.next(); 5139 if (resultsAction != null && resultsAction.equals(action)) { 5140 // If this action was explicitly requested, then don't 5141 // remove things that have it. 5142 continue; 5143 } 5144 for (int j=i+1; j<N; j++) { 5145 final ResolveInfo rij = results.get(j); 5146 if (rij.filter != null && rij.filter.hasAction(action)) { 5147 results.remove(j); 5148 if (DEBUG_INTENT_MATCHING) Log.v( 5149 TAG, "Removing duplicate item from " + j 5150 + " due to action " + action + " at " + i); 5151 j--; 5152 N--; 5153 } 5154 } 5155 } 5156 5157 // If the caller didn't request filter information, drop it now 5158 // so we don't have to marshall/unmarshall it. 5159 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5160 rii.filter = null; 5161 } 5162 } 5163 5164 // Filter out the caller activity if so requested. 5165 if (caller != null) { 5166 N = results.size(); 5167 for (int i=0; i<N; i++) { 5168 ActivityInfo ainfo = results.get(i).activityInfo; 5169 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5170 && caller.getClassName().equals(ainfo.name)) { 5171 results.remove(i); 5172 break; 5173 } 5174 } 5175 } 5176 5177 // If the caller didn't request filter information, 5178 // drop them now so we don't have to 5179 // marshall/unmarshall it. 5180 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5181 N = results.size(); 5182 for (int i=0; i<N; i++) { 5183 results.get(i).filter = null; 5184 } 5185 } 5186 5187 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5188 return results; 5189 } 5190 5191 @Override 5192 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5193 int userId) { 5194 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5195 ComponentName comp = intent.getComponent(); 5196 if (comp == null) { 5197 if (intent.getSelector() != null) { 5198 intent = intent.getSelector(); 5199 comp = intent.getComponent(); 5200 } 5201 } 5202 if (comp != null) { 5203 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5204 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5205 if (ai != null) { 5206 ResolveInfo ri = new ResolveInfo(); 5207 ri.activityInfo = ai; 5208 list.add(ri); 5209 } 5210 return list; 5211 } 5212 5213 // reader 5214 synchronized (mPackages) { 5215 String pkgName = intent.getPackage(); 5216 if (pkgName == null) { 5217 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5218 } 5219 final PackageParser.Package pkg = mPackages.get(pkgName); 5220 if (pkg != null) { 5221 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5222 userId); 5223 } 5224 return null; 5225 } 5226 } 5227 5228 @Override 5229 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5230 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5231 if (!sUserManager.exists(userId)) return null; 5232 if (query != null) { 5233 if (query.size() >= 1) { 5234 // If there is more than one service with the same priority, 5235 // just arbitrarily pick the first one. 5236 return query.get(0); 5237 } 5238 } 5239 return null; 5240 } 5241 5242 @Override 5243 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5244 int userId) { 5245 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5246 ComponentName comp = intent.getComponent(); 5247 if (comp == null) { 5248 if (intent.getSelector() != null) { 5249 intent = intent.getSelector(); 5250 comp = intent.getComponent(); 5251 } 5252 } 5253 if (comp != null) { 5254 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5255 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5256 if (si != null) { 5257 final ResolveInfo ri = new ResolveInfo(); 5258 ri.serviceInfo = si; 5259 list.add(ri); 5260 } 5261 return list; 5262 } 5263 5264 // reader 5265 synchronized (mPackages) { 5266 String pkgName = intent.getPackage(); 5267 if (pkgName == null) { 5268 return mServices.queryIntent(intent, resolvedType, flags, userId); 5269 } 5270 final PackageParser.Package pkg = mPackages.get(pkgName); 5271 if (pkg != null) { 5272 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5273 userId); 5274 } 5275 return null; 5276 } 5277 } 5278 5279 @Override 5280 public List<ResolveInfo> queryIntentContentProviders( 5281 Intent intent, String resolvedType, int flags, int userId) { 5282 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5283 ComponentName comp = intent.getComponent(); 5284 if (comp == null) { 5285 if (intent.getSelector() != null) { 5286 intent = intent.getSelector(); 5287 comp = intent.getComponent(); 5288 } 5289 } 5290 if (comp != null) { 5291 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5292 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5293 if (pi != null) { 5294 final ResolveInfo ri = new ResolveInfo(); 5295 ri.providerInfo = pi; 5296 list.add(ri); 5297 } 5298 return list; 5299 } 5300 5301 // reader 5302 synchronized (mPackages) { 5303 String pkgName = intent.getPackage(); 5304 if (pkgName == null) { 5305 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5306 } 5307 final PackageParser.Package pkg = mPackages.get(pkgName); 5308 if (pkg != null) { 5309 return mProviders.queryIntentForPackage( 5310 intent, resolvedType, flags, pkg.providers, userId); 5311 } 5312 return null; 5313 } 5314 } 5315 5316 @Override 5317 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5318 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5319 5320 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5321 5322 // writer 5323 synchronized (mPackages) { 5324 ArrayList<PackageInfo> list; 5325 if (listUninstalled) { 5326 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5327 for (PackageSetting ps : mSettings.mPackages.values()) { 5328 PackageInfo pi; 5329 if (ps.pkg != null) { 5330 pi = generatePackageInfo(ps.pkg, flags, userId); 5331 } else { 5332 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5333 } 5334 if (pi != null) { 5335 list.add(pi); 5336 } 5337 } 5338 } else { 5339 list = new ArrayList<PackageInfo>(mPackages.size()); 5340 for (PackageParser.Package p : mPackages.values()) { 5341 PackageInfo pi = generatePackageInfo(p, flags, userId); 5342 if (pi != null) { 5343 list.add(pi); 5344 } 5345 } 5346 } 5347 5348 return new ParceledListSlice<PackageInfo>(list); 5349 } 5350 } 5351 5352 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5353 String[] permissions, boolean[] tmp, int flags, int userId) { 5354 int numMatch = 0; 5355 final PermissionsState permissionsState = ps.getPermissionsState(); 5356 for (int i=0; i<permissions.length; i++) { 5357 final String permission = permissions[i]; 5358 if (permissionsState.hasPermission(permission, userId)) { 5359 tmp[i] = true; 5360 numMatch++; 5361 } else { 5362 tmp[i] = false; 5363 } 5364 } 5365 if (numMatch == 0) { 5366 return; 5367 } 5368 PackageInfo pi; 5369 if (ps.pkg != null) { 5370 pi = generatePackageInfo(ps.pkg, flags, userId); 5371 } else { 5372 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5373 } 5374 // The above might return null in cases of uninstalled apps or install-state 5375 // skew across users/profiles. 5376 if (pi != null) { 5377 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5378 if (numMatch == permissions.length) { 5379 pi.requestedPermissions = permissions; 5380 } else { 5381 pi.requestedPermissions = new String[numMatch]; 5382 numMatch = 0; 5383 for (int i=0; i<permissions.length; i++) { 5384 if (tmp[i]) { 5385 pi.requestedPermissions[numMatch] = permissions[i]; 5386 numMatch++; 5387 } 5388 } 5389 } 5390 } 5391 list.add(pi); 5392 } 5393 } 5394 5395 @Override 5396 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5397 String[] permissions, int flags, int userId) { 5398 if (!sUserManager.exists(userId)) return null; 5399 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5400 5401 // writer 5402 synchronized (mPackages) { 5403 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5404 boolean[] tmpBools = new boolean[permissions.length]; 5405 if (listUninstalled) { 5406 for (PackageSetting ps : mSettings.mPackages.values()) { 5407 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5408 } 5409 } else { 5410 for (PackageParser.Package pkg : mPackages.values()) { 5411 PackageSetting ps = (PackageSetting)pkg.mExtras; 5412 if (ps != null) { 5413 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5414 userId); 5415 } 5416 } 5417 } 5418 5419 return new ParceledListSlice<PackageInfo>(list); 5420 } 5421 } 5422 5423 @Override 5424 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5425 if (!sUserManager.exists(userId)) return null; 5426 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5427 5428 // writer 5429 synchronized (mPackages) { 5430 ArrayList<ApplicationInfo> list; 5431 if (listUninstalled) { 5432 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5433 for (PackageSetting ps : mSettings.mPackages.values()) { 5434 ApplicationInfo ai; 5435 if (ps.pkg != null) { 5436 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5437 ps.readUserState(userId), userId); 5438 } else { 5439 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5440 } 5441 if (ai != null) { 5442 list.add(ai); 5443 } 5444 } 5445 } else { 5446 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5447 for (PackageParser.Package p : mPackages.values()) { 5448 if (p.mExtras != null) { 5449 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5450 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5451 if (ai != null) { 5452 list.add(ai); 5453 } 5454 } 5455 } 5456 } 5457 5458 return new ParceledListSlice<ApplicationInfo>(list); 5459 } 5460 } 5461 5462 public List<ApplicationInfo> getPersistentApplications(int flags) { 5463 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5464 5465 // reader 5466 synchronized (mPackages) { 5467 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5468 final int userId = UserHandle.getCallingUserId(); 5469 while (i.hasNext()) { 5470 final PackageParser.Package p = i.next(); 5471 if (p.applicationInfo != null 5472 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5473 && (!mSafeMode || isSystemApp(p))) { 5474 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5475 if (ps != null) { 5476 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5477 ps.readUserState(userId), userId); 5478 if (ai != null) { 5479 finalList.add(ai); 5480 } 5481 } 5482 } 5483 } 5484 } 5485 5486 return finalList; 5487 } 5488 5489 @Override 5490 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5491 if (!sUserManager.exists(userId)) return null; 5492 // reader 5493 synchronized (mPackages) { 5494 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5495 PackageSetting ps = provider != null 5496 ? mSettings.mPackages.get(provider.owner.packageName) 5497 : null; 5498 return ps != null 5499 && mSettings.isEnabledLPr(provider.info, flags, userId) 5500 && (!mSafeMode || (provider.info.applicationInfo.flags 5501 &ApplicationInfo.FLAG_SYSTEM) != 0) 5502 ? PackageParser.generateProviderInfo(provider, flags, 5503 ps.readUserState(userId), userId) 5504 : null; 5505 } 5506 } 5507 5508 /** 5509 * @deprecated 5510 */ 5511 @Deprecated 5512 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5513 // reader 5514 synchronized (mPackages) { 5515 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5516 .entrySet().iterator(); 5517 final int userId = UserHandle.getCallingUserId(); 5518 while (i.hasNext()) { 5519 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5520 PackageParser.Provider p = entry.getValue(); 5521 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5522 5523 if (ps != null && p.syncable 5524 && (!mSafeMode || (p.info.applicationInfo.flags 5525 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5526 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5527 ps.readUserState(userId), userId); 5528 if (info != null) { 5529 outNames.add(entry.getKey()); 5530 outInfo.add(info); 5531 } 5532 } 5533 } 5534 } 5535 } 5536 5537 @Override 5538 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5539 int uid, int flags) { 5540 ArrayList<ProviderInfo> finalList = null; 5541 // reader 5542 synchronized (mPackages) { 5543 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5544 final int userId = processName != null ? 5545 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5546 while (i.hasNext()) { 5547 final PackageParser.Provider p = i.next(); 5548 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5549 if (ps != null && p.info.authority != null 5550 && (processName == null 5551 || (p.info.processName.equals(processName) 5552 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5553 && mSettings.isEnabledLPr(p.info, flags, userId) 5554 && (!mSafeMode 5555 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5556 if (finalList == null) { 5557 finalList = new ArrayList<ProviderInfo>(3); 5558 } 5559 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5560 ps.readUserState(userId), userId); 5561 if (info != null) { 5562 finalList.add(info); 5563 } 5564 } 5565 } 5566 } 5567 5568 if (finalList != null) { 5569 Collections.sort(finalList, mProviderInitOrderSorter); 5570 return new ParceledListSlice<ProviderInfo>(finalList); 5571 } 5572 5573 return null; 5574 } 5575 5576 @Override 5577 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5578 int flags) { 5579 // reader 5580 synchronized (mPackages) { 5581 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5582 return PackageParser.generateInstrumentationInfo(i, flags); 5583 } 5584 } 5585 5586 @Override 5587 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5588 int flags) { 5589 ArrayList<InstrumentationInfo> finalList = 5590 new ArrayList<InstrumentationInfo>(); 5591 5592 // reader 5593 synchronized (mPackages) { 5594 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5595 while (i.hasNext()) { 5596 final PackageParser.Instrumentation p = i.next(); 5597 if (targetPackage == null 5598 || targetPackage.equals(p.info.targetPackage)) { 5599 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5600 flags); 5601 if (ii != null) { 5602 finalList.add(ii); 5603 } 5604 } 5605 } 5606 } 5607 5608 return finalList; 5609 } 5610 5611 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5612 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5613 if (overlays == null) { 5614 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5615 return; 5616 } 5617 for (PackageParser.Package opkg : overlays.values()) { 5618 // Not much to do if idmap fails: we already logged the error 5619 // and we certainly don't want to abort installation of pkg simply 5620 // because an overlay didn't fit properly. For these reasons, 5621 // ignore the return value of createIdmapForPackagePairLI. 5622 createIdmapForPackagePairLI(pkg, opkg); 5623 } 5624 } 5625 5626 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5627 PackageParser.Package opkg) { 5628 if (!opkg.mTrustedOverlay) { 5629 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5630 opkg.baseCodePath + ": overlay not trusted"); 5631 return false; 5632 } 5633 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5634 if (overlaySet == null) { 5635 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5636 opkg.baseCodePath + " but target package has no known overlays"); 5637 return false; 5638 } 5639 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5640 // TODO: generate idmap for split APKs 5641 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5642 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5643 + opkg.baseCodePath); 5644 return false; 5645 } 5646 PackageParser.Package[] overlayArray = 5647 overlaySet.values().toArray(new PackageParser.Package[0]); 5648 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5649 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5650 return p1.mOverlayPriority - p2.mOverlayPriority; 5651 } 5652 }; 5653 Arrays.sort(overlayArray, cmp); 5654 5655 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5656 int i = 0; 5657 for (PackageParser.Package p : overlayArray) { 5658 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5659 } 5660 return true; 5661 } 5662 5663 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5664 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5665 try { 5666 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5667 } finally { 5668 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5669 } 5670 } 5671 5672 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5673 final File[] files = dir.listFiles(); 5674 if (ArrayUtils.isEmpty(files)) { 5675 Log.d(TAG, "No files in app dir " + dir); 5676 return; 5677 } 5678 5679 if (DEBUG_PACKAGE_SCANNING) { 5680 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5681 + " flags=0x" + Integer.toHexString(parseFlags)); 5682 } 5683 5684 for (File file : files) { 5685 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5686 && !PackageInstallerService.isStageName(file.getName()); 5687 if (!isPackage) { 5688 // Ignore entries which are not packages 5689 continue; 5690 } 5691 try { 5692 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5693 scanFlags, currentTime, UserHandle.SYSTEM); 5694 } catch (PackageManagerException e) { 5695 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5696 5697 // Delete invalid userdata apps 5698 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5699 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5700 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5701 if (file.isDirectory()) { 5702 mInstaller.rmPackageDir(file.getAbsolutePath()); 5703 } else { 5704 file.delete(); 5705 } 5706 } 5707 } 5708 } 5709 } 5710 5711 private static File getSettingsProblemFile() { 5712 File dataDir = Environment.getDataDirectory(); 5713 File systemDir = new File(dataDir, "system"); 5714 File fname = new File(systemDir, "uiderrors.txt"); 5715 return fname; 5716 } 5717 5718 static void reportSettingsProblem(int priority, String msg) { 5719 logCriticalInfo(priority, msg); 5720 } 5721 5722 static void logCriticalInfo(int priority, String msg) { 5723 Slog.println(priority, TAG, msg); 5724 EventLogTags.writePmCriticalInfo(msg); 5725 try { 5726 File fname = getSettingsProblemFile(); 5727 FileOutputStream out = new FileOutputStream(fname, true); 5728 PrintWriter pw = new FastPrintWriter(out); 5729 SimpleDateFormat formatter = new SimpleDateFormat(); 5730 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5731 pw.println(dateString + ": " + msg); 5732 pw.close(); 5733 FileUtils.setPermissions( 5734 fname.toString(), 5735 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5736 -1, -1); 5737 } catch (java.io.IOException e) { 5738 } 5739 } 5740 5741 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5742 PackageParser.Package pkg, File srcFile, int parseFlags) 5743 throws PackageManagerException { 5744 if (ps != null 5745 && ps.codePath.equals(srcFile) 5746 && ps.timeStamp == srcFile.lastModified() 5747 && !isCompatSignatureUpdateNeeded(pkg) 5748 && !isRecoverSignatureUpdateNeeded(pkg)) { 5749 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5750 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5751 ArraySet<PublicKey> signingKs; 5752 synchronized (mPackages) { 5753 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5754 } 5755 if (ps.signatures.mSignatures != null 5756 && ps.signatures.mSignatures.length != 0 5757 && signingKs != null) { 5758 // Optimization: reuse the existing cached certificates 5759 // if the package appears to be unchanged. 5760 pkg.mSignatures = ps.signatures.mSignatures; 5761 pkg.mSigningKeys = signingKs; 5762 return; 5763 } 5764 5765 Slog.w(TAG, "PackageSetting for " + ps.name 5766 + " is missing signatures. Collecting certs again to recover them."); 5767 } else { 5768 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5769 } 5770 5771 try { 5772 pp.collectCertificates(pkg, parseFlags); 5773 pp.collectManifestDigest(pkg); 5774 } catch (PackageParserException e) { 5775 throw PackageManagerException.from(e); 5776 } 5777 } 5778 5779 /** 5780 * Traces a package scan. 5781 * @see #scanPackageLI(File, int, int, long, UserHandle) 5782 */ 5783 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5784 long currentTime, UserHandle user) throws PackageManagerException { 5785 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5786 try { 5787 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5788 } finally { 5789 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5790 } 5791 } 5792 5793 /** 5794 * Scans a package and returns the newly parsed package. 5795 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5796 */ 5797 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5798 long currentTime, UserHandle user) throws PackageManagerException { 5799 Preconditions.checkNotNull(user); 5800 5801 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5802 parseFlags |= mDefParseFlags; 5803 PackageParser pp = new PackageParser(); 5804 pp.setSeparateProcesses(mSeparateProcesses); 5805 pp.setOnlyCoreApps(mOnlyCore); 5806 pp.setDisplayMetrics(mMetrics); 5807 5808 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5809 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5810 } 5811 5812 final PackageParser.Package pkg; 5813 try { 5814 pkg = pp.parsePackage(scanFile, parseFlags); 5815 } catch (PackageParserException e) { 5816 throw PackageManagerException.from(e); 5817 } 5818 5819 PackageSetting ps = null; 5820 PackageSetting updatedPkg; 5821 // reader 5822 synchronized (mPackages) { 5823 // Look to see if we already know about this package. 5824 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5825 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5826 // This package has been renamed to its original name. Let's 5827 // use that. 5828 ps = mSettings.peekPackageLPr(oldName); 5829 } 5830 // If there was no original package, see one for the real package name. 5831 if (ps == null) { 5832 ps = mSettings.peekPackageLPr(pkg.packageName); 5833 } 5834 // Check to see if this package could be hiding/updating a system 5835 // package. Must look for it either under the original or real 5836 // package name depending on our state. 5837 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5838 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5839 } 5840 boolean updatedPkgBetter = false; 5841 // First check if this is a system package that may involve an update 5842 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 5843 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5844 // it needs to drop FLAG_PRIVILEGED. 5845 if (locationIsPrivileged(scanFile)) { 5846 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5847 } else { 5848 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5849 } 5850 5851 if (ps != null && !ps.codePath.equals(scanFile)) { 5852 // The path has changed from what was last scanned... check the 5853 // version of the new path against what we have stored to determine 5854 // what to do. 5855 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5856 if (pkg.mVersionCode <= ps.versionCode) { 5857 // The system package has been updated and the code path does not match 5858 // Ignore entry. Skip it. 5859 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5860 + " ignored: updated version " + ps.versionCode 5861 + " better than this " + pkg.mVersionCode); 5862 if (!updatedPkg.codePath.equals(scanFile)) { 5863 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5864 + ps.name + " changing from " + updatedPkg.codePathString 5865 + " to " + scanFile); 5866 updatedPkg.codePath = scanFile; 5867 updatedPkg.codePathString = scanFile.toString(); 5868 updatedPkg.resourcePath = scanFile; 5869 updatedPkg.resourcePathString = scanFile.toString(); 5870 } 5871 updatedPkg.pkg = pkg; 5872 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5873 "Package " + ps.name + " at " + scanFile 5874 + " ignored: updated version " + ps.versionCode 5875 + " better than this " + pkg.mVersionCode); 5876 } else { 5877 // The current app on the system partition is better than 5878 // what we have updated to on the data partition; switch 5879 // back to the system partition version. 5880 // At this point, its safely assumed that package installation for 5881 // apps in system partition will go through. If not there won't be a working 5882 // version of the app 5883 // writer 5884 synchronized (mPackages) { 5885 // Just remove the loaded entries from package lists. 5886 mPackages.remove(ps.name); 5887 } 5888 5889 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5890 + " reverting from " + ps.codePathString 5891 + ": new version " + pkg.mVersionCode 5892 + " better than installed " + ps.versionCode); 5893 5894 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5895 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5896 synchronized (mInstallLock) { 5897 args.cleanUpResourcesLI(); 5898 } 5899 synchronized (mPackages) { 5900 mSettings.enableSystemPackageLPw(ps.name); 5901 } 5902 updatedPkgBetter = true; 5903 } 5904 } 5905 } 5906 5907 if (updatedPkg != null) { 5908 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5909 // initially 5910 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5911 5912 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5913 // flag set initially 5914 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5915 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5916 } 5917 } 5918 5919 // Verify certificates against what was last scanned 5920 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5921 5922 /* 5923 * A new system app appeared, but we already had a non-system one of the 5924 * same name installed earlier. 5925 */ 5926 boolean shouldHideSystemApp = false; 5927 if (updatedPkg == null && ps != null 5928 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5929 /* 5930 * Check to make sure the signatures match first. If they don't, 5931 * wipe the installed application and its data. 5932 */ 5933 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5934 != PackageManager.SIGNATURE_MATCH) { 5935 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5936 + " signatures don't match existing userdata copy; removing"); 5937 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5938 ps = null; 5939 } else { 5940 /* 5941 * If the newly-added system app is an older version than the 5942 * already installed version, hide it. It will be scanned later 5943 * and re-added like an update. 5944 */ 5945 if (pkg.mVersionCode <= ps.versionCode) { 5946 shouldHideSystemApp = true; 5947 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5948 + " but new version " + pkg.mVersionCode + " better than installed " 5949 + ps.versionCode + "; hiding system"); 5950 } else { 5951 /* 5952 * The newly found system app is a newer version that the 5953 * one previously installed. Simply remove the 5954 * already-installed application and replace it with our own 5955 * while keeping the application data. 5956 */ 5957 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5958 + " reverting from " + ps.codePathString + ": new version " 5959 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5960 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5961 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5962 synchronized (mInstallLock) { 5963 args.cleanUpResourcesLI(); 5964 } 5965 } 5966 } 5967 } 5968 5969 // The apk is forward locked (not public) if its code and resources 5970 // are kept in different files. (except for app in either system or 5971 // vendor path). 5972 // TODO grab this value from PackageSettings 5973 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5974 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5975 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5976 } 5977 } 5978 5979 // TODO: extend to support forward-locked splits 5980 String resourcePath = null; 5981 String baseResourcePath = null; 5982 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5983 if (ps != null && ps.resourcePathString != null) { 5984 resourcePath = ps.resourcePathString; 5985 baseResourcePath = ps.resourcePathString; 5986 } else { 5987 // Should not happen at all. Just log an error. 5988 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5989 } 5990 } else { 5991 resourcePath = pkg.codePath; 5992 baseResourcePath = pkg.baseCodePath; 5993 } 5994 5995 // Set application objects path explicitly. 5996 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5997 pkg.applicationInfo.setCodePath(pkg.codePath); 5998 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5999 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6000 pkg.applicationInfo.setResourcePath(resourcePath); 6001 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6002 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6003 6004 // Note that we invoke the following method only if we are about to unpack an application 6005 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6006 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6007 6008 /* 6009 * If the system app should be overridden by a previously installed 6010 * data, hide the system app now and let the /data/app scan pick it up 6011 * again. 6012 */ 6013 if (shouldHideSystemApp) { 6014 synchronized (mPackages) { 6015 mSettings.disableSystemPackageLPw(pkg.packageName); 6016 } 6017 } 6018 6019 return scannedPkg; 6020 } 6021 6022 private static String fixProcessName(String defProcessName, 6023 String processName, int uid) { 6024 if (processName == null) { 6025 return defProcessName; 6026 } 6027 return processName; 6028 } 6029 6030 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6031 throws PackageManagerException { 6032 if (pkgSetting.signatures.mSignatures != null) { 6033 // Already existing package. Make sure signatures match 6034 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6035 == PackageManager.SIGNATURE_MATCH; 6036 if (!match) { 6037 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6038 == PackageManager.SIGNATURE_MATCH; 6039 } 6040 if (!match) { 6041 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6042 == PackageManager.SIGNATURE_MATCH; 6043 } 6044 if (!match) { 6045 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6046 + pkg.packageName + " signatures do not match the " 6047 + "previously installed version; ignoring!"); 6048 } 6049 } 6050 6051 // Check for shared user signatures 6052 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6053 // Already existing package. Make sure signatures match 6054 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6055 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6056 if (!match) { 6057 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6058 == PackageManager.SIGNATURE_MATCH; 6059 } 6060 if (!match) { 6061 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6062 == PackageManager.SIGNATURE_MATCH; 6063 } 6064 if (!match) { 6065 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6066 "Package " + pkg.packageName 6067 + " has no signatures that match those in shared user " 6068 + pkgSetting.sharedUser.name + "; ignoring!"); 6069 } 6070 } 6071 } 6072 6073 /** 6074 * Enforces that only the system UID or root's UID can call a method exposed 6075 * via Binder. 6076 * 6077 * @param message used as message if SecurityException is thrown 6078 * @throws SecurityException if the caller is not system or root 6079 */ 6080 private static final void enforceSystemOrRoot(String message) { 6081 final int uid = Binder.getCallingUid(); 6082 if (uid != Process.SYSTEM_UID && uid != 0) { 6083 throw new SecurityException(message); 6084 } 6085 } 6086 6087 @Override 6088 public void performBootDexOpt() { 6089 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6090 6091 // Before everything else, see whether we need to fstrim. 6092 try { 6093 IMountService ms = PackageHelper.getMountService(); 6094 if (ms != null) { 6095 final boolean isUpgrade = isUpgrade(); 6096 boolean doTrim = isUpgrade; 6097 if (doTrim) { 6098 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6099 } else { 6100 final long interval = android.provider.Settings.Global.getLong( 6101 mContext.getContentResolver(), 6102 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6103 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6104 if (interval > 0) { 6105 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6106 if (timeSinceLast > interval) { 6107 doTrim = true; 6108 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6109 + "; running immediately"); 6110 } 6111 } 6112 } 6113 if (doTrim) { 6114 if (!isFirstBoot()) { 6115 try { 6116 ActivityManagerNative.getDefault().showBootMessage( 6117 mContext.getResources().getString( 6118 R.string.android_upgrading_fstrim), true); 6119 } catch (RemoteException e) { 6120 } 6121 } 6122 ms.runMaintenance(); 6123 } 6124 } else { 6125 Slog.e(TAG, "Mount service unavailable!"); 6126 } 6127 } catch (RemoteException e) { 6128 // Can't happen; MountService is local 6129 } 6130 6131 final ArraySet<PackageParser.Package> pkgs; 6132 synchronized (mPackages) { 6133 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6134 } 6135 6136 if (pkgs != null) { 6137 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6138 // in case the device runs out of space. 6139 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6140 // Give priority to core apps. 6141 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6142 PackageParser.Package pkg = it.next(); 6143 if (pkg.coreApp) { 6144 if (DEBUG_DEXOPT) { 6145 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6146 } 6147 sortedPkgs.add(pkg); 6148 it.remove(); 6149 } 6150 } 6151 // Give priority to system apps that listen for pre boot complete. 6152 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6153 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6154 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6155 PackageParser.Package pkg = it.next(); 6156 if (pkgNames.contains(pkg.packageName)) { 6157 if (DEBUG_DEXOPT) { 6158 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6159 } 6160 sortedPkgs.add(pkg); 6161 it.remove(); 6162 } 6163 } 6164 // Filter out packages that aren't recently used. 6165 filterRecentlyUsedApps(pkgs); 6166 // Add all remaining apps. 6167 for (PackageParser.Package pkg : pkgs) { 6168 if (DEBUG_DEXOPT) { 6169 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6170 } 6171 sortedPkgs.add(pkg); 6172 } 6173 6174 // If we want to be lazy, filter everything that wasn't recently used. 6175 if (mLazyDexOpt) { 6176 filterRecentlyUsedApps(sortedPkgs); 6177 } 6178 6179 int i = 0; 6180 int total = sortedPkgs.size(); 6181 File dataDir = Environment.getDataDirectory(); 6182 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6183 if (lowThreshold == 0) { 6184 throw new IllegalStateException("Invalid low memory threshold"); 6185 } 6186 for (PackageParser.Package pkg : sortedPkgs) { 6187 long usableSpace = dataDir.getUsableSpace(); 6188 if (usableSpace < lowThreshold) { 6189 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6190 break; 6191 } 6192 performBootDexOpt(pkg, ++i, total); 6193 } 6194 } 6195 } 6196 6197 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6198 // Filter out packages that aren't recently used. 6199 // 6200 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6201 // should do a full dexopt. 6202 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6203 int total = pkgs.size(); 6204 int skipped = 0; 6205 long now = System.currentTimeMillis(); 6206 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6207 PackageParser.Package pkg = i.next(); 6208 long then = pkg.mLastPackageUsageTimeInMills; 6209 if (then + mDexOptLRUThresholdInMills < now) { 6210 if (DEBUG_DEXOPT) { 6211 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6212 ((then == 0) ? "never" : new Date(then))); 6213 } 6214 i.remove(); 6215 skipped++; 6216 } 6217 } 6218 if (DEBUG_DEXOPT) { 6219 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6220 } 6221 } 6222 } 6223 6224 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6225 List<ResolveInfo> ris = null; 6226 try { 6227 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6228 intent, null, 0, userId); 6229 } catch (RemoteException e) { 6230 } 6231 ArraySet<String> pkgNames = new ArraySet<String>(); 6232 if (ris != null) { 6233 for (ResolveInfo ri : ris) { 6234 pkgNames.add(ri.activityInfo.packageName); 6235 } 6236 } 6237 return pkgNames; 6238 } 6239 6240 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6241 if (DEBUG_DEXOPT) { 6242 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6243 } 6244 if (!isFirstBoot()) { 6245 try { 6246 ActivityManagerNative.getDefault().showBootMessage( 6247 mContext.getResources().getString(R.string.android_upgrading_apk, 6248 curr, total), true); 6249 } catch (RemoteException e) { 6250 } 6251 } 6252 PackageParser.Package p = pkg; 6253 synchronized (mInstallLock) { 6254 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6255 false /* force dex */, false /* defer */, true /* include dependencies */, 6256 false /* boot complete */, false /*useJit*/); 6257 } 6258 } 6259 6260 @Override 6261 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6262 return performDexOptTraced(packageName, instructionSet, false); 6263 } 6264 6265 public boolean performDexOpt( 6266 String packageName, String instructionSet, boolean backgroundDexopt) { 6267 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6268 } 6269 6270 private boolean performDexOptTraced( 6271 String packageName, String instructionSet, boolean backgroundDexopt) { 6272 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6273 try { 6274 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6275 } finally { 6276 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6277 } 6278 } 6279 6280 private boolean performDexOptInternal( 6281 String packageName, String instructionSet, boolean backgroundDexopt) { 6282 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6283 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6284 if (!dexopt && !updateUsage) { 6285 // We aren't going to dexopt or update usage, so bail early. 6286 return false; 6287 } 6288 PackageParser.Package p; 6289 final String targetInstructionSet; 6290 synchronized (mPackages) { 6291 p = mPackages.get(packageName); 6292 if (p == null) { 6293 return false; 6294 } 6295 if (updateUsage) { 6296 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6297 } 6298 mPackageUsage.write(false); 6299 if (!dexopt) { 6300 // We aren't going to dexopt, so bail early. 6301 return false; 6302 } 6303 6304 targetInstructionSet = instructionSet != null ? instructionSet : 6305 getPrimaryInstructionSet(p.applicationInfo); 6306 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6307 return false; 6308 } 6309 } 6310 long callingId = Binder.clearCallingIdentity(); 6311 try { 6312 synchronized (mInstallLock) { 6313 final String[] instructionSets = new String[] { targetInstructionSet }; 6314 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6315 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6316 true /* boot complete */, false /*useJit*/); 6317 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6318 } 6319 } finally { 6320 Binder.restoreCallingIdentity(callingId); 6321 } 6322 } 6323 6324 public ArraySet<String> getPackagesThatNeedDexOpt() { 6325 ArraySet<String> pkgs = null; 6326 synchronized (mPackages) { 6327 for (PackageParser.Package p : mPackages.values()) { 6328 if (DEBUG_DEXOPT) { 6329 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6330 } 6331 if (!p.mDexOptPerformed.isEmpty()) { 6332 continue; 6333 } 6334 if (pkgs == null) { 6335 pkgs = new ArraySet<String>(); 6336 } 6337 pkgs.add(p.packageName); 6338 } 6339 } 6340 return pkgs; 6341 } 6342 6343 public void shutdown() { 6344 mPackageUsage.write(true); 6345 } 6346 6347 @Override 6348 public void forceDexOpt(String packageName) { 6349 enforceSystemOrRoot("forceDexOpt"); 6350 6351 PackageParser.Package pkg; 6352 synchronized (mPackages) { 6353 pkg = mPackages.get(packageName); 6354 if (pkg == null) { 6355 throw new IllegalArgumentException("Missing package: " + packageName); 6356 } 6357 } 6358 6359 synchronized (mInstallLock) { 6360 final String[] instructionSets = new String[] { 6361 getPrimaryInstructionSet(pkg.applicationInfo) }; 6362 6363 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6364 6365 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6366 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6367 true /* boot complete */, false /*useJit*/); 6368 6369 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6370 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6371 throw new IllegalStateException("Failed to dexopt: " + res); 6372 } 6373 } 6374 } 6375 6376 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6377 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6378 Slog.w(TAG, "Unable to update from " + oldPkg.name 6379 + " to " + newPkg.packageName 6380 + ": old package not in system partition"); 6381 return false; 6382 } else if (mPackages.get(oldPkg.name) != null) { 6383 Slog.w(TAG, "Unable to update from " + oldPkg.name 6384 + " to " + newPkg.packageName 6385 + ": old package still exists"); 6386 return false; 6387 } 6388 return true; 6389 } 6390 6391 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6392 int[] users = sUserManager.getUserIds(); 6393 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6394 if (res < 0) { 6395 return res; 6396 } 6397 for (int user : users) { 6398 if (user != 0) { 6399 res = mInstaller.createUserData(volumeUuid, packageName, 6400 UserHandle.getUid(user, uid), user, seinfo); 6401 if (res < 0) { 6402 return res; 6403 } 6404 } 6405 } 6406 return res; 6407 } 6408 6409 private int removeDataDirsLI(String volumeUuid, String packageName) { 6410 int[] users = sUserManager.getUserIds(); 6411 int res = 0; 6412 for (int user : users) { 6413 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6414 if (resInner < 0) { 6415 res = resInner; 6416 } 6417 } 6418 6419 return res; 6420 } 6421 6422 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6423 int[] users = sUserManager.getUserIds(); 6424 int res = 0; 6425 for (int user : users) { 6426 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6427 if (resInner < 0) { 6428 res = resInner; 6429 } 6430 } 6431 return res; 6432 } 6433 6434 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6435 PackageParser.Package changingLib) { 6436 if (file.path != null) { 6437 usesLibraryFiles.add(file.path); 6438 return; 6439 } 6440 PackageParser.Package p = mPackages.get(file.apk); 6441 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6442 // If we are doing this while in the middle of updating a library apk, 6443 // then we need to make sure to use that new apk for determining the 6444 // dependencies here. (We haven't yet finished committing the new apk 6445 // to the package manager state.) 6446 if (p == null || p.packageName.equals(changingLib.packageName)) { 6447 p = changingLib; 6448 } 6449 } 6450 if (p != null) { 6451 usesLibraryFiles.addAll(p.getAllCodePaths()); 6452 } 6453 } 6454 6455 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6456 PackageParser.Package changingLib) throws PackageManagerException { 6457 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6458 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6459 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6460 for (int i=0; i<N; i++) { 6461 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6462 if (file == null) { 6463 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6464 "Package " + pkg.packageName + " requires unavailable shared library " 6465 + pkg.usesLibraries.get(i) + "; failing!"); 6466 } 6467 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6468 } 6469 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6470 for (int i=0; i<N; i++) { 6471 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6472 if (file == null) { 6473 Slog.w(TAG, "Package " + pkg.packageName 6474 + " desires unavailable shared library " 6475 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6476 } else { 6477 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6478 } 6479 } 6480 N = usesLibraryFiles.size(); 6481 if (N > 0) { 6482 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6483 } else { 6484 pkg.usesLibraryFiles = null; 6485 } 6486 } 6487 } 6488 6489 private static boolean hasString(List<String> list, List<String> which) { 6490 if (list == null) { 6491 return false; 6492 } 6493 for (int i=list.size()-1; i>=0; i--) { 6494 for (int j=which.size()-1; j>=0; j--) { 6495 if (which.get(j).equals(list.get(i))) { 6496 return true; 6497 } 6498 } 6499 } 6500 return false; 6501 } 6502 6503 private void updateAllSharedLibrariesLPw() { 6504 for (PackageParser.Package pkg : mPackages.values()) { 6505 try { 6506 updateSharedLibrariesLPw(pkg, null); 6507 } catch (PackageManagerException e) { 6508 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6509 } 6510 } 6511 } 6512 6513 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6514 PackageParser.Package changingPkg) { 6515 ArrayList<PackageParser.Package> res = null; 6516 for (PackageParser.Package pkg : mPackages.values()) { 6517 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6518 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6519 if (res == null) { 6520 res = new ArrayList<PackageParser.Package>(); 6521 } 6522 res.add(pkg); 6523 try { 6524 updateSharedLibrariesLPw(pkg, changingPkg); 6525 } catch (PackageManagerException e) { 6526 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6527 } 6528 } 6529 } 6530 return res; 6531 } 6532 6533 /** 6534 * Derive the value of the {@code cpuAbiOverride} based on the provided 6535 * value and an optional stored value from the package settings. 6536 */ 6537 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6538 String cpuAbiOverride = null; 6539 6540 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6541 cpuAbiOverride = null; 6542 } else if (abiOverride != null) { 6543 cpuAbiOverride = abiOverride; 6544 } else if (settings != null) { 6545 cpuAbiOverride = settings.cpuAbiOverrideString; 6546 } 6547 6548 return cpuAbiOverride; 6549 } 6550 6551 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6552 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6553 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6554 try { 6555 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6556 } finally { 6557 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6558 } 6559 } 6560 6561 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6562 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6563 boolean success = false; 6564 try { 6565 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6566 currentTime, user); 6567 success = true; 6568 return res; 6569 } finally { 6570 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6571 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6572 } 6573 } 6574 } 6575 6576 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6577 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6578 final File scanFile = new File(pkg.codePath); 6579 if (pkg.applicationInfo.getCodePath() == null || 6580 pkg.applicationInfo.getResourcePath() == null) { 6581 // Bail out. The resource and code paths haven't been set. 6582 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6583 "Code and resource paths haven't been set correctly"); 6584 } 6585 6586 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6587 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6588 } else { 6589 // Only allow system apps to be flagged as core apps. 6590 pkg.coreApp = false; 6591 } 6592 6593 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6594 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6595 } 6596 6597 if (mCustomResolverComponentName != null && 6598 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6599 setUpCustomResolverActivity(pkg); 6600 } 6601 6602 if (pkg.packageName.equals("android")) { 6603 synchronized (mPackages) { 6604 if (mAndroidApplication != null) { 6605 Slog.w(TAG, "*************************************************"); 6606 Slog.w(TAG, "Core android package being redefined. Skipping."); 6607 Slog.w(TAG, " file=" + scanFile); 6608 Slog.w(TAG, "*************************************************"); 6609 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6610 "Core android package being redefined. Skipping."); 6611 } 6612 6613 // Set up information for our fall-back user intent resolution activity. 6614 mPlatformPackage = pkg; 6615 pkg.mVersionCode = mSdkVersion; 6616 mAndroidApplication = pkg.applicationInfo; 6617 6618 if (!mResolverReplaced) { 6619 mResolveActivity.applicationInfo = mAndroidApplication; 6620 mResolveActivity.name = ResolverActivity.class.getName(); 6621 mResolveActivity.packageName = mAndroidApplication.packageName; 6622 mResolveActivity.processName = "system:ui"; 6623 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6624 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6625 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6626 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6627 mResolveActivity.exported = true; 6628 mResolveActivity.enabled = true; 6629 mResolveInfo.activityInfo = mResolveActivity; 6630 mResolveInfo.priority = 0; 6631 mResolveInfo.preferredOrder = 0; 6632 mResolveInfo.match = 0; 6633 mResolveComponentName = new ComponentName( 6634 mAndroidApplication.packageName, mResolveActivity.name); 6635 } 6636 } 6637 } 6638 6639 if (DEBUG_PACKAGE_SCANNING) { 6640 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6641 Log.d(TAG, "Scanning package " + pkg.packageName); 6642 } 6643 6644 if (mPackages.containsKey(pkg.packageName) 6645 || mSharedLibraries.containsKey(pkg.packageName)) { 6646 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6647 "Application package " + pkg.packageName 6648 + " already installed. Skipping duplicate."); 6649 } 6650 6651 // If we're only installing presumed-existing packages, require that the 6652 // scanned APK is both already known and at the path previously established 6653 // for it. Previously unknown packages we pick up normally, but if we have an 6654 // a priori expectation about this package's install presence, enforce it. 6655 // With a singular exception for new system packages. When an OTA contains 6656 // a new system package, we allow the codepath to change from a system location 6657 // to the user-installed location. If we don't allow this change, any newer, 6658 // user-installed version of the application will be ignored. 6659 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6660 if (mExpectingBetter.containsKey(pkg.packageName)) { 6661 logCriticalInfo(Log.WARN, 6662 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6663 } else { 6664 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6665 if (known != null) { 6666 if (DEBUG_PACKAGE_SCANNING) { 6667 Log.d(TAG, "Examining " + pkg.codePath 6668 + " and requiring known paths " + known.codePathString 6669 + " & " + known.resourcePathString); 6670 } 6671 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6672 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6673 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6674 "Application package " + pkg.packageName 6675 + " found at " + pkg.applicationInfo.getCodePath() 6676 + " but expected at " + known.codePathString + "; ignoring."); 6677 } 6678 } 6679 } 6680 } 6681 6682 // Initialize package source and resource directories 6683 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6684 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6685 6686 SharedUserSetting suid = null; 6687 PackageSetting pkgSetting = null; 6688 6689 if (!isSystemApp(pkg)) { 6690 // Only system apps can use these features. 6691 pkg.mOriginalPackages = null; 6692 pkg.mRealPackage = null; 6693 pkg.mAdoptPermissions = null; 6694 } 6695 6696 // writer 6697 synchronized (mPackages) { 6698 if (pkg.mSharedUserId != null) { 6699 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6700 if (suid == null) { 6701 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6702 "Creating application package " + pkg.packageName 6703 + " for shared user failed"); 6704 } 6705 if (DEBUG_PACKAGE_SCANNING) { 6706 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6707 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6708 + "): packages=" + suid.packages); 6709 } 6710 } 6711 6712 // Check if we are renaming from an original package name. 6713 PackageSetting origPackage = null; 6714 String realName = null; 6715 if (pkg.mOriginalPackages != null) { 6716 // This package may need to be renamed to a previously 6717 // installed name. Let's check on that... 6718 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6719 if (pkg.mOriginalPackages.contains(renamed)) { 6720 // This package had originally been installed as the 6721 // original name, and we have already taken care of 6722 // transitioning to the new one. Just update the new 6723 // one to continue using the old name. 6724 realName = pkg.mRealPackage; 6725 if (!pkg.packageName.equals(renamed)) { 6726 // Callers into this function may have already taken 6727 // care of renaming the package; only do it here if 6728 // it is not already done. 6729 pkg.setPackageName(renamed); 6730 } 6731 6732 } else { 6733 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6734 if ((origPackage = mSettings.peekPackageLPr( 6735 pkg.mOriginalPackages.get(i))) != null) { 6736 // We do have the package already installed under its 6737 // original name... should we use it? 6738 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6739 // New package is not compatible with original. 6740 origPackage = null; 6741 continue; 6742 } else if (origPackage.sharedUser != null) { 6743 // Make sure uid is compatible between packages. 6744 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6745 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6746 + " to " + pkg.packageName + ": old uid " 6747 + origPackage.sharedUser.name 6748 + " differs from " + pkg.mSharedUserId); 6749 origPackage = null; 6750 continue; 6751 } 6752 } else { 6753 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6754 + pkg.packageName + " to old name " + origPackage.name); 6755 } 6756 break; 6757 } 6758 } 6759 } 6760 } 6761 6762 if (mTransferedPackages.contains(pkg.packageName)) { 6763 Slog.w(TAG, "Package " + pkg.packageName 6764 + " was transferred to another, but its .apk remains"); 6765 } 6766 6767 // Just create the setting, don't add it yet. For already existing packages 6768 // the PkgSetting exists already and doesn't have to be created. 6769 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6770 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6771 pkg.applicationInfo.primaryCpuAbi, 6772 pkg.applicationInfo.secondaryCpuAbi, 6773 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6774 user, false); 6775 if (pkgSetting == null) { 6776 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6777 "Creating application package " + pkg.packageName + " failed"); 6778 } 6779 6780 if (pkgSetting.origPackage != null) { 6781 // If we are first transitioning from an original package, 6782 // fix up the new package's name now. We need to do this after 6783 // looking up the package under its new name, so getPackageLP 6784 // can take care of fiddling things correctly. 6785 pkg.setPackageName(origPackage.name); 6786 6787 // File a report about this. 6788 String msg = "New package " + pkgSetting.realName 6789 + " renamed to replace old package " + pkgSetting.name; 6790 reportSettingsProblem(Log.WARN, msg); 6791 6792 // Make a note of it. 6793 mTransferedPackages.add(origPackage.name); 6794 6795 // No longer need to retain this. 6796 pkgSetting.origPackage = null; 6797 } 6798 6799 if (realName != null) { 6800 // Make a note of it. 6801 mTransferedPackages.add(pkg.packageName); 6802 } 6803 6804 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6805 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6806 } 6807 6808 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6809 // Check all shared libraries and map to their actual file path. 6810 // We only do this here for apps not on a system dir, because those 6811 // are the only ones that can fail an install due to this. We 6812 // will take care of the system apps by updating all of their 6813 // library paths after the scan is done. 6814 updateSharedLibrariesLPw(pkg, null); 6815 } 6816 6817 if (mFoundPolicyFile) { 6818 SELinuxMMAC.assignSeinfoValue(pkg); 6819 } 6820 6821 pkg.applicationInfo.uid = pkgSetting.appId; 6822 pkg.mExtras = pkgSetting; 6823 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6824 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6825 // We just determined the app is signed correctly, so bring 6826 // over the latest parsed certs. 6827 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6828 } else { 6829 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6830 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6831 "Package " + pkg.packageName + " upgrade keys do not match the " 6832 + "previously installed version"); 6833 } else { 6834 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6835 String msg = "System package " + pkg.packageName 6836 + " signature changed; retaining data."; 6837 reportSettingsProblem(Log.WARN, msg); 6838 } 6839 } 6840 } else { 6841 try { 6842 verifySignaturesLP(pkgSetting, pkg); 6843 // We just determined the app is signed correctly, so bring 6844 // over the latest parsed certs. 6845 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6846 } catch (PackageManagerException e) { 6847 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6848 throw e; 6849 } 6850 // The signature has changed, but this package is in the system 6851 // image... let's recover! 6852 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6853 // However... if this package is part of a shared user, but it 6854 // doesn't match the signature of the shared user, let's fail. 6855 // What this means is that you can't change the signatures 6856 // associated with an overall shared user, which doesn't seem all 6857 // that unreasonable. 6858 if (pkgSetting.sharedUser != null) { 6859 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6860 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6861 throw new PackageManagerException( 6862 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6863 "Signature mismatch for shared user : " 6864 + pkgSetting.sharedUser); 6865 } 6866 } 6867 // File a report about this. 6868 String msg = "System package " + pkg.packageName 6869 + " signature changed; retaining data."; 6870 reportSettingsProblem(Log.WARN, msg); 6871 } 6872 } 6873 // Verify that this new package doesn't have any content providers 6874 // that conflict with existing packages. Only do this if the 6875 // package isn't already installed, since we don't want to break 6876 // things that are installed. 6877 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6878 final int N = pkg.providers.size(); 6879 int i; 6880 for (i=0; i<N; i++) { 6881 PackageParser.Provider p = pkg.providers.get(i); 6882 if (p.info.authority != null) { 6883 String names[] = p.info.authority.split(";"); 6884 for (int j = 0; j < names.length; j++) { 6885 if (mProvidersByAuthority.containsKey(names[j])) { 6886 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6887 final String otherPackageName = 6888 ((other != null && other.getComponentName() != null) ? 6889 other.getComponentName().getPackageName() : "?"); 6890 throw new PackageManagerException( 6891 INSTALL_FAILED_CONFLICTING_PROVIDER, 6892 "Can't install because provider name " + names[j] 6893 + " (in package " + pkg.applicationInfo.packageName 6894 + ") is already used by " + otherPackageName); 6895 } 6896 } 6897 } 6898 } 6899 } 6900 6901 if (pkg.mAdoptPermissions != null) { 6902 // This package wants to adopt ownership of permissions from 6903 // another package. 6904 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6905 final String origName = pkg.mAdoptPermissions.get(i); 6906 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6907 if (orig != null) { 6908 if (verifyPackageUpdateLPr(orig, pkg)) { 6909 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6910 + pkg.packageName); 6911 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6912 } 6913 } 6914 } 6915 } 6916 } 6917 6918 final String pkgName = pkg.packageName; 6919 6920 final long scanFileTime = scanFile.lastModified(); 6921 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6922 pkg.applicationInfo.processName = fixProcessName( 6923 pkg.applicationInfo.packageName, 6924 pkg.applicationInfo.processName, 6925 pkg.applicationInfo.uid); 6926 6927 File dataPath; 6928 if (mPlatformPackage == pkg) { 6929 // The system package is special. 6930 dataPath = new File(Environment.getDataDirectory(), "system"); 6931 6932 pkg.applicationInfo.dataDir = dataPath.getPath(); 6933 6934 } else { 6935 // This is a normal package, need to make its data directory. 6936 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6937 UserHandle.USER_SYSTEM, pkg.packageName); 6938 6939 boolean uidError = false; 6940 if (dataPath.exists()) { 6941 int currentUid = 0; 6942 try { 6943 StructStat stat = Os.stat(dataPath.getPath()); 6944 currentUid = stat.st_uid; 6945 } catch (ErrnoException e) { 6946 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6947 } 6948 6949 // If we have mismatched owners for the data path, we have a problem. 6950 if (currentUid != pkg.applicationInfo.uid) { 6951 boolean recovered = false; 6952 if (currentUid == 0) { 6953 // The directory somehow became owned by root. Wow. 6954 // This is probably because the system was stopped while 6955 // installd was in the middle of messing with its libs 6956 // directory. Ask installd to fix that. 6957 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6958 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6959 if (ret >= 0) { 6960 recovered = true; 6961 String msg = "Package " + pkg.packageName 6962 + " unexpectedly changed to uid 0; recovered to " + 6963 + pkg.applicationInfo.uid; 6964 reportSettingsProblem(Log.WARN, msg); 6965 } 6966 } 6967 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6968 || (scanFlags&SCAN_BOOTING) != 0)) { 6969 // If this is a system app, we can at least delete its 6970 // current data so the application will still work. 6971 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6972 if (ret >= 0) { 6973 // TODO: Kill the processes first 6974 // Old data gone! 6975 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6976 ? "System package " : "Third party package "; 6977 String msg = prefix + pkg.packageName 6978 + " has changed from uid: " 6979 + currentUid + " to " 6980 + pkg.applicationInfo.uid + "; old data erased"; 6981 reportSettingsProblem(Log.WARN, msg); 6982 recovered = true; 6983 6984 // And now re-install the app. 6985 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6986 pkg.applicationInfo.seinfo); 6987 if (ret == -1) { 6988 // Ack should not happen! 6989 msg = prefix + pkg.packageName 6990 + " could not have data directory re-created after delete."; 6991 reportSettingsProblem(Log.WARN, msg); 6992 throw new PackageManagerException( 6993 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6994 } 6995 } 6996 if (!recovered) { 6997 mHasSystemUidErrors = true; 6998 } 6999 } else if (!recovered) { 7000 // If we allow this install to proceed, we will be broken. 7001 // Abort, abort! 7002 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7003 "scanPackageLI"); 7004 } 7005 if (!recovered) { 7006 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7007 + pkg.applicationInfo.uid + "/fs_" 7008 + currentUid; 7009 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7010 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7011 String msg = "Package " + pkg.packageName 7012 + " has mismatched uid: " 7013 + currentUid + " on disk, " 7014 + pkg.applicationInfo.uid + " in settings"; 7015 // writer 7016 synchronized (mPackages) { 7017 mSettings.mReadMessages.append(msg); 7018 mSettings.mReadMessages.append('\n'); 7019 uidError = true; 7020 if (!pkgSetting.uidError) { 7021 reportSettingsProblem(Log.ERROR, msg); 7022 } 7023 } 7024 } 7025 } 7026 pkg.applicationInfo.dataDir = dataPath.getPath(); 7027 if (mShouldRestoreconData) { 7028 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7029 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7030 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7031 } 7032 } else { 7033 if (DEBUG_PACKAGE_SCANNING) { 7034 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7035 Log.v(TAG, "Want this data dir: " + dataPath); 7036 } 7037 //invoke installer to do the actual installation 7038 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7039 pkg.applicationInfo.seinfo); 7040 if (ret < 0) { 7041 // Error from installer 7042 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7043 "Unable to create data dirs [errorCode=" + ret + "]"); 7044 } 7045 7046 if (dataPath.exists()) { 7047 pkg.applicationInfo.dataDir = dataPath.getPath(); 7048 } else { 7049 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7050 pkg.applicationInfo.dataDir = null; 7051 } 7052 } 7053 7054 pkgSetting.uidError = uidError; 7055 } 7056 7057 final String path = scanFile.getPath(); 7058 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7059 7060 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7061 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7062 7063 // Some system apps still use directory structure for native libraries 7064 // in which case we might end up not detecting abi solely based on apk 7065 // structure. Try to detect abi based on directory structure. 7066 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7067 pkg.applicationInfo.primaryCpuAbi == null) { 7068 setBundledAppAbisAndRoots(pkg, pkgSetting); 7069 setNativeLibraryPaths(pkg); 7070 } 7071 7072 } else { 7073 if ((scanFlags & SCAN_MOVE) != 0) { 7074 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7075 // but we already have this packages package info in the PackageSetting. We just 7076 // use that and derive the native library path based on the new codepath. 7077 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7078 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7079 } 7080 7081 // Set native library paths again. For moves, the path will be updated based on the 7082 // ABIs we've determined above. For non-moves, the path will be updated based on the 7083 // ABIs we determined during compilation, but the path will depend on the final 7084 // package path (after the rename away from the stage path). 7085 setNativeLibraryPaths(pkg); 7086 } 7087 7088 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7089 final int[] userIds = sUserManager.getUserIds(); 7090 synchronized (mInstallLock) { 7091 // Make sure all user data directories are ready to roll; we're okay 7092 // if they already exist 7093 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7094 for (int userId : userIds) { 7095 if (userId != UserHandle.USER_SYSTEM) { 7096 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7097 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7098 pkg.applicationInfo.seinfo); 7099 } 7100 } 7101 } 7102 7103 // Create a native library symlink only if we have native libraries 7104 // and if the native libraries are 32 bit libraries. We do not provide 7105 // this symlink for 64 bit libraries. 7106 if (pkg.applicationInfo.primaryCpuAbi != null && 7107 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7108 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7109 try { 7110 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7111 for (int userId : userIds) { 7112 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7113 nativeLibPath, userId) < 0) { 7114 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7115 "Failed linking native library dir (user=" + userId + ")"); 7116 } 7117 } 7118 } finally { 7119 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7120 } 7121 } 7122 } 7123 7124 // This is a special case for the "system" package, where the ABI is 7125 // dictated by the zygote configuration (and init.rc). We should keep track 7126 // of this ABI so that we can deal with "normal" applications that run under 7127 // the same UID correctly. 7128 if (mPlatformPackage == pkg) { 7129 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7130 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7131 } 7132 7133 // If there's a mismatch between the abi-override in the package setting 7134 // and the abiOverride specified for the install. Warn about this because we 7135 // would've already compiled the app without taking the package setting into 7136 // account. 7137 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7138 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7139 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7140 " for package: " + pkg.packageName); 7141 } 7142 } 7143 7144 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7145 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7146 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7147 7148 // Copy the derived override back to the parsed package, so that we can 7149 // update the package settings accordingly. 7150 pkg.cpuAbiOverride = cpuAbiOverride; 7151 7152 if (DEBUG_ABI_SELECTION) { 7153 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7154 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7155 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7156 } 7157 7158 // Push the derived path down into PackageSettings so we know what to 7159 // clean up at uninstall time. 7160 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7161 7162 if (DEBUG_ABI_SELECTION) { 7163 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7164 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7165 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7166 } 7167 7168 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7169 // We don't do this here during boot because we can do it all 7170 // at once after scanning all existing packages. 7171 // 7172 // We also do this *before* we perform dexopt on this package, so that 7173 // we can avoid redundant dexopts, and also to make sure we've got the 7174 // code and package path correct. 7175 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7176 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7177 } 7178 7179 if ((scanFlags & SCAN_NO_DEX) == 0) { 7180 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7181 7182 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7183 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7184 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7185 7186 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7187 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7188 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7189 } 7190 } 7191 if (mFactoryTest && pkg.requestedPermissions.contains( 7192 android.Manifest.permission.FACTORY_TEST)) { 7193 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7194 } 7195 7196 ArrayList<PackageParser.Package> clientLibPkgs = null; 7197 7198 // writer 7199 synchronized (mPackages) { 7200 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7201 // Only system apps can add new shared libraries. 7202 if (pkg.libraryNames != null) { 7203 for (int i=0; i<pkg.libraryNames.size(); i++) { 7204 String name = pkg.libraryNames.get(i); 7205 boolean allowed = false; 7206 if (pkg.isUpdatedSystemApp()) { 7207 // New library entries can only be added through the 7208 // system image. This is important to get rid of a lot 7209 // of nasty edge cases: for example if we allowed a non- 7210 // system update of the app to add a library, then uninstalling 7211 // the update would make the library go away, and assumptions 7212 // we made such as through app install filtering would now 7213 // have allowed apps on the device which aren't compatible 7214 // with it. Better to just have the restriction here, be 7215 // conservative, and create many fewer cases that can negatively 7216 // impact the user experience. 7217 final PackageSetting sysPs = mSettings 7218 .getDisabledSystemPkgLPr(pkg.packageName); 7219 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7220 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7221 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7222 allowed = true; 7223 break; 7224 } 7225 } 7226 } 7227 } else { 7228 allowed = true; 7229 } 7230 if (allowed) { 7231 if (!mSharedLibraries.containsKey(name)) { 7232 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7233 } else if (!name.equals(pkg.packageName)) { 7234 Slog.w(TAG, "Package " + pkg.packageName + " library " 7235 + name + " already exists; skipping"); 7236 } 7237 } else { 7238 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7239 + name + " that is not declared on system image; skipping"); 7240 } 7241 } 7242 if ((scanFlags&SCAN_BOOTING) == 0) { 7243 // If we are not booting, we need to update any applications 7244 // that are clients of our shared library. If we are booting, 7245 // this will all be done once the scan is complete. 7246 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7247 } 7248 } 7249 } 7250 } 7251 7252 // We also need to dexopt any apps that are dependent on this library. Note that 7253 // if these fail, we should abort the install since installing the library will 7254 // result in some apps being broken. 7255 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7256 try { 7257 if (clientLibPkgs != null) { 7258 if ((scanFlags & SCAN_NO_DEX) == 0) { 7259 for (int i = 0; i < clientLibPkgs.size(); i++) { 7260 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7261 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7262 null /* instruction sets */, forceDex, 7263 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7264 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7265 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7266 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7267 "scanPackageLI failed to dexopt clientLibPkgs"); 7268 } 7269 } 7270 } 7271 } 7272 } finally { 7273 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7274 } 7275 7276 // Request the ActivityManager to kill the process(only for existing packages) 7277 // so that we do not end up in a confused state while the user is still using the older 7278 // version of the application while the new one gets installed. 7279 if ((scanFlags & SCAN_REPLACING) != 0) { 7280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7281 7282 killApplication(pkg.applicationInfo.packageName, 7283 pkg.applicationInfo.uid, "replace pkg"); 7284 7285 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7286 } 7287 7288 // Also need to kill any apps that are dependent on the library. 7289 if (clientLibPkgs != null) { 7290 for (int i=0; i<clientLibPkgs.size(); i++) { 7291 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7292 killApplication(clientPkg.applicationInfo.packageName, 7293 clientPkg.applicationInfo.uid, "update lib"); 7294 } 7295 } 7296 7297 // Make sure we're not adding any bogus keyset info 7298 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7299 ksms.assertScannedPackageValid(pkg); 7300 7301 // writer 7302 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7303 7304 boolean createIdmapFailed = false; 7305 synchronized (mPackages) { 7306 // We don't expect installation to fail beyond this point 7307 7308 // Add the new setting to mSettings 7309 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7310 // Add the new setting to mPackages 7311 mPackages.put(pkg.applicationInfo.packageName, pkg); 7312 // Make sure we don't accidentally delete its data. 7313 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7314 while (iter.hasNext()) { 7315 PackageCleanItem item = iter.next(); 7316 if (pkgName.equals(item.packageName)) { 7317 iter.remove(); 7318 } 7319 } 7320 7321 // Take care of first install / last update times. 7322 if (currentTime != 0) { 7323 if (pkgSetting.firstInstallTime == 0) { 7324 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7325 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7326 pkgSetting.lastUpdateTime = currentTime; 7327 } 7328 } else if (pkgSetting.firstInstallTime == 0) { 7329 // We need *something*. Take time time stamp of the file. 7330 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7331 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7332 if (scanFileTime != pkgSetting.timeStamp) { 7333 // A package on the system image has changed; consider this 7334 // to be an update. 7335 pkgSetting.lastUpdateTime = scanFileTime; 7336 } 7337 } 7338 7339 // Add the package's KeySets to the global KeySetManagerService 7340 ksms.addScannedPackageLPw(pkg); 7341 7342 int N = pkg.providers.size(); 7343 StringBuilder r = null; 7344 int i; 7345 for (i=0; i<N; i++) { 7346 PackageParser.Provider p = pkg.providers.get(i); 7347 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7348 p.info.processName, pkg.applicationInfo.uid); 7349 mProviders.addProvider(p); 7350 p.syncable = p.info.isSyncable; 7351 if (p.info.authority != null) { 7352 String names[] = p.info.authority.split(";"); 7353 p.info.authority = null; 7354 for (int j = 0; j < names.length; j++) { 7355 if (j == 1 && p.syncable) { 7356 // We only want the first authority for a provider to possibly be 7357 // syncable, so if we already added this provider using a different 7358 // authority clear the syncable flag. We copy the provider before 7359 // changing it because the mProviders object contains a reference 7360 // to a provider that we don't want to change. 7361 // Only do this for the second authority since the resulting provider 7362 // object can be the same for all future authorities for this provider. 7363 p = new PackageParser.Provider(p); 7364 p.syncable = false; 7365 } 7366 if (!mProvidersByAuthority.containsKey(names[j])) { 7367 mProvidersByAuthority.put(names[j], p); 7368 if (p.info.authority == null) { 7369 p.info.authority = names[j]; 7370 } else { 7371 p.info.authority = p.info.authority + ";" + names[j]; 7372 } 7373 if (DEBUG_PACKAGE_SCANNING) { 7374 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7375 Log.d(TAG, "Registered content provider: " + names[j] 7376 + ", className = " + p.info.name + ", isSyncable = " 7377 + p.info.isSyncable); 7378 } 7379 } else { 7380 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7381 Slog.w(TAG, "Skipping provider name " + names[j] + 7382 " (in package " + pkg.applicationInfo.packageName + 7383 "): name already used by " 7384 + ((other != null && other.getComponentName() != null) 7385 ? other.getComponentName().getPackageName() : "?")); 7386 } 7387 } 7388 } 7389 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7390 if (r == null) { 7391 r = new StringBuilder(256); 7392 } else { 7393 r.append(' '); 7394 } 7395 r.append(p.info.name); 7396 } 7397 } 7398 if (r != null) { 7399 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7400 } 7401 7402 N = pkg.services.size(); 7403 r = null; 7404 for (i=0; i<N; i++) { 7405 PackageParser.Service s = pkg.services.get(i); 7406 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7407 s.info.processName, pkg.applicationInfo.uid); 7408 mServices.addService(s); 7409 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7410 if (r == null) { 7411 r = new StringBuilder(256); 7412 } else { 7413 r.append(' '); 7414 } 7415 r.append(s.info.name); 7416 } 7417 } 7418 if (r != null) { 7419 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7420 } 7421 7422 N = pkg.receivers.size(); 7423 r = null; 7424 for (i=0; i<N; i++) { 7425 PackageParser.Activity a = pkg.receivers.get(i); 7426 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7427 a.info.processName, pkg.applicationInfo.uid); 7428 mReceivers.addActivity(a, "receiver"); 7429 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7430 if (r == null) { 7431 r = new StringBuilder(256); 7432 } else { 7433 r.append(' '); 7434 } 7435 r.append(a.info.name); 7436 } 7437 } 7438 if (r != null) { 7439 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7440 } 7441 7442 N = pkg.activities.size(); 7443 r = null; 7444 for (i=0; i<N; i++) { 7445 PackageParser.Activity a = pkg.activities.get(i); 7446 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7447 a.info.processName, pkg.applicationInfo.uid); 7448 mActivities.addActivity(a, "activity"); 7449 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7450 if (r == null) { 7451 r = new StringBuilder(256); 7452 } else { 7453 r.append(' '); 7454 } 7455 r.append(a.info.name); 7456 } 7457 } 7458 if (r != null) { 7459 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7460 } 7461 7462 N = pkg.permissionGroups.size(); 7463 r = null; 7464 for (i=0; i<N; i++) { 7465 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7466 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7467 if (cur == null) { 7468 mPermissionGroups.put(pg.info.name, pg); 7469 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7470 if (r == null) { 7471 r = new StringBuilder(256); 7472 } else { 7473 r.append(' '); 7474 } 7475 r.append(pg.info.name); 7476 } 7477 } else { 7478 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7479 + pg.info.packageName + " ignored: original from " 7480 + cur.info.packageName); 7481 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7482 if (r == null) { 7483 r = new StringBuilder(256); 7484 } else { 7485 r.append(' '); 7486 } 7487 r.append("DUP:"); 7488 r.append(pg.info.name); 7489 } 7490 } 7491 } 7492 if (r != null) { 7493 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7494 } 7495 7496 N = pkg.permissions.size(); 7497 r = null; 7498 for (i=0; i<N; i++) { 7499 PackageParser.Permission p = pkg.permissions.get(i); 7500 7501 // Assume by default that we did not install this permission into the system. 7502 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7503 7504 // Now that permission groups have a special meaning, we ignore permission 7505 // groups for legacy apps to prevent unexpected behavior. In particular, 7506 // permissions for one app being granted to someone just becuase they happen 7507 // to be in a group defined by another app (before this had no implications). 7508 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7509 p.group = mPermissionGroups.get(p.info.group); 7510 // Warn for a permission in an unknown group. 7511 if (p.info.group != null && p.group == null) { 7512 Slog.w(TAG, "Permission " + p.info.name + " from package " 7513 + p.info.packageName + " in an unknown group " + p.info.group); 7514 } 7515 } 7516 7517 ArrayMap<String, BasePermission> permissionMap = 7518 p.tree ? mSettings.mPermissionTrees 7519 : mSettings.mPermissions; 7520 BasePermission bp = permissionMap.get(p.info.name); 7521 7522 // Allow system apps to redefine non-system permissions 7523 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7524 final boolean currentOwnerIsSystem = (bp.perm != null 7525 && isSystemApp(bp.perm.owner)); 7526 if (isSystemApp(p.owner)) { 7527 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7528 // It's a built-in permission and no owner, take ownership now 7529 bp.packageSetting = pkgSetting; 7530 bp.perm = p; 7531 bp.uid = pkg.applicationInfo.uid; 7532 bp.sourcePackage = p.info.packageName; 7533 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7534 } else if (!currentOwnerIsSystem) { 7535 String msg = "New decl " + p.owner + " of permission " 7536 + p.info.name + " is system; overriding " + bp.sourcePackage; 7537 reportSettingsProblem(Log.WARN, msg); 7538 bp = null; 7539 } 7540 } 7541 } 7542 7543 if (bp == null) { 7544 bp = new BasePermission(p.info.name, p.info.packageName, 7545 BasePermission.TYPE_NORMAL); 7546 permissionMap.put(p.info.name, bp); 7547 } 7548 7549 if (bp.perm == null) { 7550 if (bp.sourcePackage == null 7551 || bp.sourcePackage.equals(p.info.packageName)) { 7552 BasePermission tree = findPermissionTreeLP(p.info.name); 7553 if (tree == null 7554 || tree.sourcePackage.equals(p.info.packageName)) { 7555 bp.packageSetting = pkgSetting; 7556 bp.perm = p; 7557 bp.uid = pkg.applicationInfo.uid; 7558 bp.sourcePackage = p.info.packageName; 7559 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7560 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7561 if (r == null) { 7562 r = new StringBuilder(256); 7563 } else { 7564 r.append(' '); 7565 } 7566 r.append(p.info.name); 7567 } 7568 } else { 7569 Slog.w(TAG, "Permission " + p.info.name + " from package " 7570 + p.info.packageName + " ignored: base tree " 7571 + tree.name + " is from package " 7572 + tree.sourcePackage); 7573 } 7574 } else { 7575 Slog.w(TAG, "Permission " + p.info.name + " from package " 7576 + p.info.packageName + " ignored: original from " 7577 + bp.sourcePackage); 7578 } 7579 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7580 if (r == null) { 7581 r = new StringBuilder(256); 7582 } else { 7583 r.append(' '); 7584 } 7585 r.append("DUP:"); 7586 r.append(p.info.name); 7587 } 7588 if (bp.perm == p) { 7589 bp.protectionLevel = p.info.protectionLevel; 7590 } 7591 } 7592 7593 if (r != null) { 7594 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7595 } 7596 7597 N = pkg.instrumentation.size(); 7598 r = null; 7599 for (i=0; i<N; i++) { 7600 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7601 a.info.packageName = pkg.applicationInfo.packageName; 7602 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7603 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7604 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7605 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7606 a.info.dataDir = pkg.applicationInfo.dataDir; 7607 7608 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7609 // need other information about the application, like the ABI and what not ? 7610 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7611 mInstrumentation.put(a.getComponentName(), a); 7612 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7613 if (r == null) { 7614 r = new StringBuilder(256); 7615 } else { 7616 r.append(' '); 7617 } 7618 r.append(a.info.name); 7619 } 7620 } 7621 if (r != null) { 7622 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7623 } 7624 7625 if (pkg.protectedBroadcasts != null) { 7626 N = pkg.protectedBroadcasts.size(); 7627 for (i=0; i<N; i++) { 7628 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7629 } 7630 } 7631 7632 pkgSetting.setTimeStamp(scanFileTime); 7633 7634 // Create idmap files for pairs of (packages, overlay packages). 7635 // Note: "android", ie framework-res.apk, is handled by native layers. 7636 if (pkg.mOverlayTarget != null) { 7637 // This is an overlay package. 7638 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7639 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7640 mOverlays.put(pkg.mOverlayTarget, 7641 new ArrayMap<String, PackageParser.Package>()); 7642 } 7643 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7644 map.put(pkg.packageName, pkg); 7645 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7646 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7647 createIdmapFailed = true; 7648 } 7649 } 7650 } else if (mOverlays.containsKey(pkg.packageName) && 7651 !pkg.packageName.equals("android")) { 7652 // This is a regular package, with one or more known overlay packages. 7653 createIdmapsForPackageLI(pkg); 7654 } 7655 } 7656 7657 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7658 7659 if (createIdmapFailed) { 7660 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7661 "scanPackageLI failed to createIdmap"); 7662 } 7663 return pkg; 7664 } 7665 7666 /** 7667 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7668 * is derived purely on the basis of the contents of {@code scanFile} and 7669 * {@code cpuAbiOverride}. 7670 * 7671 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7672 */ 7673 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7674 String cpuAbiOverride, boolean extractLibs) 7675 throws PackageManagerException { 7676 // TODO: We can probably be smarter about this stuff. For installed apps, 7677 // we can calculate this information at install time once and for all. For 7678 // system apps, we can probably assume that this information doesn't change 7679 // after the first boot scan. As things stand, we do lots of unnecessary work. 7680 7681 // Give ourselves some initial paths; we'll come back for another 7682 // pass once we've determined ABI below. 7683 setNativeLibraryPaths(pkg); 7684 7685 // We would never need to extract libs for forward-locked and external packages, 7686 // since the container service will do it for us. We shouldn't attempt to 7687 // extract libs from system app when it was not updated. 7688 if (pkg.isForwardLocked() || isExternal(pkg) || 7689 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7690 extractLibs = false; 7691 } 7692 7693 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7694 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7695 7696 NativeLibraryHelper.Handle handle = null; 7697 try { 7698 handle = NativeLibraryHelper.Handle.create(pkg); 7699 // TODO(multiArch): This can be null for apps that didn't go through the 7700 // usual installation process. We can calculate it again, like we 7701 // do during install time. 7702 // 7703 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7704 // unnecessary. 7705 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7706 7707 // Null out the abis so that they can be recalculated. 7708 pkg.applicationInfo.primaryCpuAbi = null; 7709 pkg.applicationInfo.secondaryCpuAbi = null; 7710 if (isMultiArch(pkg.applicationInfo)) { 7711 // Warn if we've set an abiOverride for multi-lib packages.. 7712 // By definition, we need to copy both 32 and 64 bit libraries for 7713 // such packages. 7714 if (pkg.cpuAbiOverride != null 7715 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7716 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7717 } 7718 7719 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7720 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7721 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7722 if (extractLibs) { 7723 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7724 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7725 useIsaSpecificSubdirs); 7726 } else { 7727 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7728 } 7729 } 7730 7731 maybeThrowExceptionForMultiArchCopy( 7732 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7733 7734 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7735 if (extractLibs) { 7736 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7737 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7738 useIsaSpecificSubdirs); 7739 } else { 7740 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7741 } 7742 } 7743 7744 maybeThrowExceptionForMultiArchCopy( 7745 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7746 7747 if (abi64 >= 0) { 7748 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7749 } 7750 7751 if (abi32 >= 0) { 7752 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7753 if (abi64 >= 0) { 7754 pkg.applicationInfo.secondaryCpuAbi = abi; 7755 } else { 7756 pkg.applicationInfo.primaryCpuAbi = abi; 7757 } 7758 } 7759 } else { 7760 String[] abiList = (cpuAbiOverride != null) ? 7761 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7762 7763 // Enable gross and lame hacks for apps that are built with old 7764 // SDK tools. We must scan their APKs for renderscript bitcode and 7765 // not launch them if it's present. Don't bother checking on devices 7766 // that don't have 64 bit support. 7767 boolean needsRenderScriptOverride = false; 7768 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7769 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7770 abiList = Build.SUPPORTED_32_BIT_ABIS; 7771 needsRenderScriptOverride = true; 7772 } 7773 7774 final int copyRet; 7775 if (extractLibs) { 7776 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7777 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7778 } else { 7779 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7780 } 7781 7782 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7783 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7784 "Error unpackaging native libs for app, errorCode=" + copyRet); 7785 } 7786 7787 if (copyRet >= 0) { 7788 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7789 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7790 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7791 } else if (needsRenderScriptOverride) { 7792 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7793 } 7794 } 7795 } catch (IOException ioe) { 7796 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7797 } finally { 7798 IoUtils.closeQuietly(handle); 7799 } 7800 7801 // Now that we've calculated the ABIs and determined if it's an internal app, 7802 // we will go ahead and populate the nativeLibraryPath. 7803 setNativeLibraryPaths(pkg); 7804 } 7805 7806 /** 7807 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7808 * i.e, so that all packages can be run inside a single process if required. 7809 * 7810 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7811 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7812 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7813 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7814 * updating a package that belongs to a shared user. 7815 * 7816 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7817 * adds unnecessary complexity. 7818 */ 7819 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7820 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7821 boolean bootComplete) { 7822 String requiredInstructionSet = null; 7823 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7824 requiredInstructionSet = VMRuntime.getInstructionSet( 7825 scannedPackage.applicationInfo.primaryCpuAbi); 7826 } 7827 7828 PackageSetting requirer = null; 7829 for (PackageSetting ps : packagesForUser) { 7830 // If packagesForUser contains scannedPackage, we skip it. This will happen 7831 // when scannedPackage is an update of an existing package. Without this check, 7832 // we will never be able to change the ABI of any package belonging to a shared 7833 // user, even if it's compatible with other packages. 7834 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7835 if (ps.primaryCpuAbiString == null) { 7836 continue; 7837 } 7838 7839 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7840 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7841 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7842 // this but there's not much we can do. 7843 String errorMessage = "Instruction set mismatch, " 7844 + ((requirer == null) ? "[caller]" : requirer) 7845 + " requires " + requiredInstructionSet + " whereas " + ps 7846 + " requires " + instructionSet; 7847 Slog.w(TAG, errorMessage); 7848 } 7849 7850 if (requiredInstructionSet == null) { 7851 requiredInstructionSet = instructionSet; 7852 requirer = ps; 7853 } 7854 } 7855 } 7856 7857 if (requiredInstructionSet != null) { 7858 String adjustedAbi; 7859 if (requirer != null) { 7860 // requirer != null implies that either scannedPackage was null or that scannedPackage 7861 // did not require an ABI, in which case we have to adjust scannedPackage to match 7862 // the ABI of the set (which is the same as requirer's ABI) 7863 adjustedAbi = requirer.primaryCpuAbiString; 7864 if (scannedPackage != null) { 7865 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7866 } 7867 } else { 7868 // requirer == null implies that we're updating all ABIs in the set to 7869 // match scannedPackage. 7870 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7871 } 7872 7873 for (PackageSetting ps : packagesForUser) { 7874 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7875 if (ps.primaryCpuAbiString != null) { 7876 continue; 7877 } 7878 7879 ps.primaryCpuAbiString = adjustedAbi; 7880 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7881 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7882 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7883 7884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7885 7886 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7887 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7888 bootComplete, false /*useJit*/); 7889 7890 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7891 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7892 ps.primaryCpuAbiString = null; 7893 ps.pkg.applicationInfo.primaryCpuAbi = null; 7894 return; 7895 } else { 7896 mInstaller.rmdex(ps.codePathString, 7897 getDexCodeInstructionSet(getPreferredInstructionSet())); 7898 } 7899 } 7900 } 7901 } 7902 } 7903 } 7904 7905 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7906 synchronized (mPackages) { 7907 mResolverReplaced = true; 7908 // Set up information for custom user intent resolution activity. 7909 mResolveActivity.applicationInfo = pkg.applicationInfo; 7910 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7911 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7912 mResolveActivity.processName = pkg.applicationInfo.packageName; 7913 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7914 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7915 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7916 mResolveActivity.theme = 0; 7917 mResolveActivity.exported = true; 7918 mResolveActivity.enabled = true; 7919 mResolveInfo.activityInfo = mResolveActivity; 7920 mResolveInfo.priority = 0; 7921 mResolveInfo.preferredOrder = 0; 7922 mResolveInfo.match = 0; 7923 mResolveComponentName = mCustomResolverComponentName; 7924 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7925 mResolveComponentName); 7926 } 7927 } 7928 7929 private static String calculateBundledApkRoot(final String codePathString) { 7930 final File codePath = new File(codePathString); 7931 final File codeRoot; 7932 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7933 codeRoot = Environment.getRootDirectory(); 7934 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7935 codeRoot = Environment.getOemDirectory(); 7936 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7937 codeRoot = Environment.getVendorDirectory(); 7938 } else { 7939 // Unrecognized code path; take its top real segment as the apk root: 7940 // e.g. /something/app/blah.apk => /something 7941 try { 7942 File f = codePath.getCanonicalFile(); 7943 File parent = f.getParentFile(); // non-null because codePath is a file 7944 File tmp; 7945 while ((tmp = parent.getParentFile()) != null) { 7946 f = parent; 7947 parent = tmp; 7948 } 7949 codeRoot = f; 7950 Slog.w(TAG, "Unrecognized code path " 7951 + codePath + " - using " + codeRoot); 7952 } catch (IOException e) { 7953 // Can't canonicalize the code path -- shenanigans? 7954 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7955 return Environment.getRootDirectory().getPath(); 7956 } 7957 } 7958 return codeRoot.getPath(); 7959 } 7960 7961 /** 7962 * Derive and set the location of native libraries for the given package, 7963 * which varies depending on where and how the package was installed. 7964 */ 7965 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7966 final ApplicationInfo info = pkg.applicationInfo; 7967 final String codePath = pkg.codePath; 7968 final File codeFile = new File(codePath); 7969 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7970 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7971 7972 info.nativeLibraryRootDir = null; 7973 info.nativeLibraryRootRequiresIsa = false; 7974 info.nativeLibraryDir = null; 7975 info.secondaryNativeLibraryDir = null; 7976 7977 if (isApkFile(codeFile)) { 7978 // Monolithic install 7979 if (bundledApp) { 7980 // If "/system/lib64/apkname" exists, assume that is the per-package 7981 // native library directory to use; otherwise use "/system/lib/apkname". 7982 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7983 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7984 getPrimaryInstructionSet(info)); 7985 7986 // This is a bundled system app so choose the path based on the ABI. 7987 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7988 // is just the default path. 7989 final String apkName = deriveCodePathName(codePath); 7990 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7991 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7992 apkName).getAbsolutePath(); 7993 7994 if (info.secondaryCpuAbi != null) { 7995 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7996 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7997 secondaryLibDir, apkName).getAbsolutePath(); 7998 } 7999 } else if (asecApp) { 8000 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8001 .getAbsolutePath(); 8002 } else { 8003 final String apkName = deriveCodePathName(codePath); 8004 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8005 .getAbsolutePath(); 8006 } 8007 8008 info.nativeLibraryRootRequiresIsa = false; 8009 info.nativeLibraryDir = info.nativeLibraryRootDir; 8010 } else { 8011 // Cluster install 8012 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8013 info.nativeLibraryRootRequiresIsa = true; 8014 8015 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8016 getPrimaryInstructionSet(info)).getAbsolutePath(); 8017 8018 if (info.secondaryCpuAbi != null) { 8019 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8020 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8021 } 8022 } 8023 } 8024 8025 /** 8026 * Calculate the abis and roots for a bundled app. These can uniquely 8027 * be determined from the contents of the system partition, i.e whether 8028 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8029 * of this information, and instead assume that the system was built 8030 * sensibly. 8031 */ 8032 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8033 PackageSetting pkgSetting) { 8034 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8035 8036 // If "/system/lib64/apkname" exists, assume that is the per-package 8037 // native library directory to use; otherwise use "/system/lib/apkname". 8038 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8039 setBundledAppAbi(pkg, apkRoot, apkName); 8040 // pkgSetting might be null during rescan following uninstall of updates 8041 // to a bundled app, so accommodate that possibility. The settings in 8042 // that case will be established later from the parsed package. 8043 // 8044 // If the settings aren't null, sync them up with what we've just derived. 8045 // note that apkRoot isn't stored in the package settings. 8046 if (pkgSetting != null) { 8047 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8048 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8049 } 8050 } 8051 8052 /** 8053 * Deduces the ABI of a bundled app and sets the relevant fields on the 8054 * parsed pkg object. 8055 * 8056 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8057 * under which system libraries are installed. 8058 * @param apkName the name of the installed package. 8059 */ 8060 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8061 final File codeFile = new File(pkg.codePath); 8062 8063 final boolean has64BitLibs; 8064 final boolean has32BitLibs; 8065 if (isApkFile(codeFile)) { 8066 // Monolithic install 8067 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8068 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8069 } else { 8070 // Cluster install 8071 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8072 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8073 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8074 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8075 has64BitLibs = (new File(rootDir, isa)).exists(); 8076 } else { 8077 has64BitLibs = false; 8078 } 8079 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8080 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8081 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8082 has32BitLibs = (new File(rootDir, isa)).exists(); 8083 } else { 8084 has32BitLibs = false; 8085 } 8086 } 8087 8088 if (has64BitLibs && !has32BitLibs) { 8089 // The package has 64 bit libs, but not 32 bit libs. Its primary 8090 // ABI should be 64 bit. We can safely assume here that the bundled 8091 // native libraries correspond to the most preferred ABI in the list. 8092 8093 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8094 pkg.applicationInfo.secondaryCpuAbi = null; 8095 } else if (has32BitLibs && !has64BitLibs) { 8096 // The package has 32 bit libs but not 64 bit libs. Its primary 8097 // ABI should be 32 bit. 8098 8099 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8100 pkg.applicationInfo.secondaryCpuAbi = null; 8101 } else if (has32BitLibs && has64BitLibs) { 8102 // The application has both 64 and 32 bit bundled libraries. We check 8103 // here that the app declares multiArch support, and warn if it doesn't. 8104 // 8105 // We will be lenient here and record both ABIs. The primary will be the 8106 // ABI that's higher on the list, i.e, a device that's configured to prefer 8107 // 64 bit apps will see a 64 bit primary ABI, 8108 8109 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8110 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8111 } 8112 8113 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8114 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8115 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8116 } else { 8117 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8118 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8119 } 8120 } else { 8121 pkg.applicationInfo.primaryCpuAbi = null; 8122 pkg.applicationInfo.secondaryCpuAbi = null; 8123 } 8124 } 8125 8126 private void killApplication(String pkgName, int appId, String reason) { 8127 // Request the ActivityManager to kill the process(only for existing packages) 8128 // so that we do not end up in a confused state while the user is still using the older 8129 // version of the application while the new one gets installed. 8130 IActivityManager am = ActivityManagerNative.getDefault(); 8131 if (am != null) { 8132 try { 8133 am.killApplicationWithAppId(pkgName, appId, reason); 8134 } catch (RemoteException e) { 8135 } 8136 } 8137 } 8138 8139 void removePackageLI(PackageSetting ps, boolean chatty) { 8140 if (DEBUG_INSTALL) { 8141 if (chatty) 8142 Log.d(TAG, "Removing package " + ps.name); 8143 } 8144 8145 // writer 8146 synchronized (mPackages) { 8147 mPackages.remove(ps.name); 8148 final PackageParser.Package pkg = ps.pkg; 8149 if (pkg != null) { 8150 cleanPackageDataStructuresLILPw(pkg, chatty); 8151 } 8152 } 8153 } 8154 8155 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8156 if (DEBUG_INSTALL) { 8157 if (chatty) 8158 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8159 } 8160 8161 // writer 8162 synchronized (mPackages) { 8163 mPackages.remove(pkg.applicationInfo.packageName); 8164 cleanPackageDataStructuresLILPw(pkg, chatty); 8165 } 8166 } 8167 8168 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8169 int N = pkg.providers.size(); 8170 StringBuilder r = null; 8171 int i; 8172 for (i=0; i<N; i++) { 8173 PackageParser.Provider p = pkg.providers.get(i); 8174 mProviders.removeProvider(p); 8175 if (p.info.authority == null) { 8176 8177 /* There was another ContentProvider with this authority when 8178 * this app was installed so this authority is null, 8179 * Ignore it as we don't have to unregister the provider. 8180 */ 8181 continue; 8182 } 8183 String names[] = p.info.authority.split(";"); 8184 for (int j = 0; j < names.length; j++) { 8185 if (mProvidersByAuthority.get(names[j]) == p) { 8186 mProvidersByAuthority.remove(names[j]); 8187 if (DEBUG_REMOVE) { 8188 if (chatty) 8189 Log.d(TAG, "Unregistered content provider: " + names[j] 8190 + ", className = " + p.info.name + ", isSyncable = " 8191 + p.info.isSyncable); 8192 } 8193 } 8194 } 8195 if (DEBUG_REMOVE && chatty) { 8196 if (r == null) { 8197 r = new StringBuilder(256); 8198 } else { 8199 r.append(' '); 8200 } 8201 r.append(p.info.name); 8202 } 8203 } 8204 if (r != null) { 8205 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8206 } 8207 8208 N = pkg.services.size(); 8209 r = null; 8210 for (i=0; i<N; i++) { 8211 PackageParser.Service s = pkg.services.get(i); 8212 mServices.removeService(s); 8213 if (chatty) { 8214 if (r == null) { 8215 r = new StringBuilder(256); 8216 } else { 8217 r.append(' '); 8218 } 8219 r.append(s.info.name); 8220 } 8221 } 8222 if (r != null) { 8223 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8224 } 8225 8226 N = pkg.receivers.size(); 8227 r = null; 8228 for (i=0; i<N; i++) { 8229 PackageParser.Activity a = pkg.receivers.get(i); 8230 mReceivers.removeActivity(a, "receiver"); 8231 if (DEBUG_REMOVE && chatty) { 8232 if (r == null) { 8233 r = new StringBuilder(256); 8234 } else { 8235 r.append(' '); 8236 } 8237 r.append(a.info.name); 8238 } 8239 } 8240 if (r != null) { 8241 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8242 } 8243 8244 N = pkg.activities.size(); 8245 r = null; 8246 for (i=0; i<N; i++) { 8247 PackageParser.Activity a = pkg.activities.get(i); 8248 mActivities.removeActivity(a, "activity"); 8249 if (DEBUG_REMOVE && chatty) { 8250 if (r == null) { 8251 r = new StringBuilder(256); 8252 } else { 8253 r.append(' '); 8254 } 8255 r.append(a.info.name); 8256 } 8257 } 8258 if (r != null) { 8259 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8260 } 8261 8262 N = pkg.permissions.size(); 8263 r = null; 8264 for (i=0; i<N; i++) { 8265 PackageParser.Permission p = pkg.permissions.get(i); 8266 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8267 if (bp == null) { 8268 bp = mSettings.mPermissionTrees.get(p.info.name); 8269 } 8270 if (bp != null && bp.perm == p) { 8271 bp.perm = null; 8272 if (DEBUG_REMOVE && chatty) { 8273 if (r == null) { 8274 r = new StringBuilder(256); 8275 } else { 8276 r.append(' '); 8277 } 8278 r.append(p.info.name); 8279 } 8280 } 8281 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8282 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8283 if (appOpPerms != null) { 8284 appOpPerms.remove(pkg.packageName); 8285 } 8286 } 8287 } 8288 if (r != null) { 8289 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8290 } 8291 8292 N = pkg.requestedPermissions.size(); 8293 r = null; 8294 for (i=0; i<N; i++) { 8295 String perm = pkg.requestedPermissions.get(i); 8296 BasePermission bp = mSettings.mPermissions.get(perm); 8297 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8298 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8299 if (appOpPerms != null) { 8300 appOpPerms.remove(pkg.packageName); 8301 if (appOpPerms.isEmpty()) { 8302 mAppOpPermissionPackages.remove(perm); 8303 } 8304 } 8305 } 8306 } 8307 if (r != null) { 8308 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8309 } 8310 8311 N = pkg.instrumentation.size(); 8312 r = null; 8313 for (i=0; i<N; i++) { 8314 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8315 mInstrumentation.remove(a.getComponentName()); 8316 if (DEBUG_REMOVE && chatty) { 8317 if (r == null) { 8318 r = new StringBuilder(256); 8319 } else { 8320 r.append(' '); 8321 } 8322 r.append(a.info.name); 8323 } 8324 } 8325 if (r != null) { 8326 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8327 } 8328 8329 r = null; 8330 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8331 // Only system apps can hold shared libraries. 8332 if (pkg.libraryNames != null) { 8333 for (i=0; i<pkg.libraryNames.size(); i++) { 8334 String name = pkg.libraryNames.get(i); 8335 SharedLibraryEntry cur = mSharedLibraries.get(name); 8336 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8337 mSharedLibraries.remove(name); 8338 if (DEBUG_REMOVE && chatty) { 8339 if (r == null) { 8340 r = new StringBuilder(256); 8341 } else { 8342 r.append(' '); 8343 } 8344 r.append(name); 8345 } 8346 } 8347 } 8348 } 8349 } 8350 if (r != null) { 8351 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8352 } 8353 } 8354 8355 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8356 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8357 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8358 return true; 8359 } 8360 } 8361 return false; 8362 } 8363 8364 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8365 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8366 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8367 8368 private void updatePermissionsLPw(String changingPkg, 8369 PackageParser.Package pkgInfo, int flags) { 8370 // Make sure there are no dangling permission trees. 8371 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8372 while (it.hasNext()) { 8373 final BasePermission bp = it.next(); 8374 if (bp.packageSetting == null) { 8375 // We may not yet have parsed the package, so just see if 8376 // we still know about its settings. 8377 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8378 } 8379 if (bp.packageSetting == null) { 8380 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8381 + " from package " + bp.sourcePackage); 8382 it.remove(); 8383 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8384 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8385 Slog.i(TAG, "Removing old permission tree: " + bp.name 8386 + " from package " + bp.sourcePackage); 8387 flags |= UPDATE_PERMISSIONS_ALL; 8388 it.remove(); 8389 } 8390 } 8391 } 8392 8393 // Make sure all dynamic permissions have been assigned to a package, 8394 // and make sure there are no dangling permissions. 8395 it = mSettings.mPermissions.values().iterator(); 8396 while (it.hasNext()) { 8397 final BasePermission bp = it.next(); 8398 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8399 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8400 + bp.name + " pkg=" + bp.sourcePackage 8401 + " info=" + bp.pendingInfo); 8402 if (bp.packageSetting == null && bp.pendingInfo != null) { 8403 final BasePermission tree = findPermissionTreeLP(bp.name); 8404 if (tree != null && tree.perm != null) { 8405 bp.packageSetting = tree.packageSetting; 8406 bp.perm = new PackageParser.Permission(tree.perm.owner, 8407 new PermissionInfo(bp.pendingInfo)); 8408 bp.perm.info.packageName = tree.perm.info.packageName; 8409 bp.perm.info.name = bp.name; 8410 bp.uid = tree.uid; 8411 } 8412 } 8413 } 8414 if (bp.packageSetting == null) { 8415 // We may not yet have parsed the package, so just see if 8416 // we still know about its settings. 8417 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8418 } 8419 if (bp.packageSetting == null) { 8420 Slog.w(TAG, "Removing dangling permission: " + bp.name 8421 + " from package " + bp.sourcePackage); 8422 it.remove(); 8423 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8424 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8425 Slog.i(TAG, "Removing old permission: " + bp.name 8426 + " from package " + bp.sourcePackage); 8427 flags |= UPDATE_PERMISSIONS_ALL; 8428 it.remove(); 8429 } 8430 } 8431 } 8432 8433 // Now update the permissions for all packages, in particular 8434 // replace the granted permissions of the system packages. 8435 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8436 for (PackageParser.Package pkg : mPackages.values()) { 8437 if (pkg != pkgInfo) { 8438 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8439 changingPkg); 8440 } 8441 } 8442 } 8443 8444 if (pkgInfo != null) { 8445 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8446 } 8447 } 8448 8449 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8450 String packageOfInterest) { 8451 // IMPORTANT: There are two types of permissions: install and runtime. 8452 // Install time permissions are granted when the app is installed to 8453 // all device users and users added in the future. Runtime permissions 8454 // are granted at runtime explicitly to specific users. Normal and signature 8455 // protected permissions are install time permissions. Dangerous permissions 8456 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8457 // otherwise they are runtime permissions. This function does not manage 8458 // runtime permissions except for the case an app targeting Lollipop MR1 8459 // being upgraded to target a newer SDK, in which case dangerous permissions 8460 // are transformed from install time to runtime ones. 8461 8462 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8463 if (ps == null) { 8464 return; 8465 } 8466 8467 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8468 8469 PermissionsState permissionsState = ps.getPermissionsState(); 8470 PermissionsState origPermissions = permissionsState; 8471 8472 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8473 8474 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8475 8476 boolean changedInstallPermission = false; 8477 8478 if (replace) { 8479 ps.installPermissionsFixed = false; 8480 if (!ps.isSharedUser()) { 8481 origPermissions = new PermissionsState(permissionsState); 8482 permissionsState.reset(); 8483 } 8484 } 8485 8486 permissionsState.setGlobalGids(mGlobalGids); 8487 8488 final int N = pkg.requestedPermissions.size(); 8489 for (int i=0; i<N; i++) { 8490 final String name = pkg.requestedPermissions.get(i); 8491 final BasePermission bp = mSettings.mPermissions.get(name); 8492 8493 if (DEBUG_INSTALL) { 8494 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8495 } 8496 8497 if (bp == null || bp.packageSetting == null) { 8498 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8499 Slog.w(TAG, "Unknown permission " + name 8500 + " in package " + pkg.packageName); 8501 } 8502 continue; 8503 } 8504 8505 final String perm = bp.name; 8506 boolean allowedSig = false; 8507 int grant = GRANT_DENIED; 8508 8509 // Keep track of app op permissions. 8510 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8511 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8512 if (pkgs == null) { 8513 pkgs = new ArraySet<>(); 8514 mAppOpPermissionPackages.put(bp.name, pkgs); 8515 } 8516 pkgs.add(pkg.packageName); 8517 } 8518 8519 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8520 switch (level) { 8521 case PermissionInfo.PROTECTION_NORMAL: { 8522 // For all apps normal permissions are install time ones. 8523 grant = GRANT_INSTALL; 8524 } break; 8525 8526 case PermissionInfo.PROTECTION_DANGEROUS: { 8527 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8528 // For legacy apps dangerous permissions are install time ones. 8529 grant = GRANT_INSTALL_LEGACY; 8530 } else if (origPermissions.hasInstallPermission(bp.name)) { 8531 // For legacy apps that became modern, install becomes runtime. 8532 grant = GRANT_UPGRADE; 8533 } else if (mPromoteSystemApps 8534 && isSystemApp(ps) 8535 && mExistingSystemPackages.contains(ps.name)) { 8536 // For legacy system apps, install becomes runtime. 8537 // We cannot check hasInstallPermission() for system apps since those 8538 // permissions were granted implicitly and not persisted pre-M. 8539 grant = GRANT_UPGRADE; 8540 } else { 8541 // For modern apps keep runtime permissions unchanged. 8542 grant = GRANT_RUNTIME; 8543 } 8544 } break; 8545 8546 case PermissionInfo.PROTECTION_SIGNATURE: { 8547 // For all apps signature permissions are install time ones. 8548 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8549 if (allowedSig) { 8550 grant = GRANT_INSTALL; 8551 } 8552 } break; 8553 } 8554 8555 if (DEBUG_INSTALL) { 8556 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8557 } 8558 8559 if (grant != GRANT_DENIED) { 8560 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8561 // If this is an existing, non-system package, then 8562 // we can't add any new permissions to it. 8563 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8564 // Except... if this is a permission that was added 8565 // to the platform (note: need to only do this when 8566 // updating the platform). 8567 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8568 grant = GRANT_DENIED; 8569 } 8570 } 8571 } 8572 8573 switch (grant) { 8574 case GRANT_INSTALL: { 8575 // Revoke this as runtime permission to handle the case of 8576 // a runtime permission being downgraded to an install one. 8577 for (int userId : UserManagerService.getInstance().getUserIds()) { 8578 if (origPermissions.getRuntimePermissionState( 8579 bp.name, userId) != null) { 8580 // Revoke the runtime permission and clear the flags. 8581 origPermissions.revokeRuntimePermission(bp, userId); 8582 origPermissions.updatePermissionFlags(bp, userId, 8583 PackageManager.MASK_PERMISSION_FLAGS, 0); 8584 // If we revoked a permission permission, we have to write. 8585 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8586 changedRuntimePermissionUserIds, userId); 8587 } 8588 } 8589 // Grant an install permission. 8590 if (permissionsState.grantInstallPermission(bp) != 8591 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8592 changedInstallPermission = true; 8593 } 8594 } break; 8595 8596 case GRANT_INSTALL_LEGACY: { 8597 // Grant an install permission. 8598 if (permissionsState.grantInstallPermission(bp) != 8599 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8600 changedInstallPermission = true; 8601 } 8602 } break; 8603 8604 case GRANT_RUNTIME: { 8605 // Grant previously granted runtime permissions. 8606 for (int userId : UserManagerService.getInstance().getUserIds()) { 8607 PermissionState permissionState = origPermissions 8608 .getRuntimePermissionState(bp.name, userId); 8609 final int flags = permissionState != null 8610 ? permissionState.getFlags() : 0; 8611 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8612 if (permissionsState.grantRuntimePermission(bp, userId) == 8613 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8614 // If we cannot put the permission as it was, we have to write. 8615 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8616 changedRuntimePermissionUserIds, userId); 8617 } 8618 } 8619 // Propagate the permission flags. 8620 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8621 } 8622 } break; 8623 8624 case GRANT_UPGRADE: { 8625 // Grant runtime permissions for a previously held install permission. 8626 PermissionState permissionState = origPermissions 8627 .getInstallPermissionState(bp.name); 8628 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8629 8630 if (origPermissions.revokeInstallPermission(bp) 8631 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8632 // We will be transferring the permission flags, so clear them. 8633 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8634 PackageManager.MASK_PERMISSION_FLAGS, 0); 8635 changedInstallPermission = true; 8636 } 8637 8638 // If the permission is not to be promoted to runtime we ignore it and 8639 // also its other flags as they are not applicable to install permissions. 8640 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8641 for (int userId : currentUserIds) { 8642 if (permissionsState.grantRuntimePermission(bp, userId) != 8643 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8644 // Transfer the permission flags. 8645 permissionsState.updatePermissionFlags(bp, userId, 8646 flags, flags); 8647 // If we granted the permission, we have to write. 8648 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8649 changedRuntimePermissionUserIds, userId); 8650 } 8651 } 8652 } 8653 } break; 8654 8655 default: { 8656 if (packageOfInterest == null 8657 || packageOfInterest.equals(pkg.packageName)) { 8658 Slog.w(TAG, "Not granting permission " + perm 8659 + " to package " + pkg.packageName 8660 + " because it was previously installed without"); 8661 } 8662 } break; 8663 } 8664 } else { 8665 if (permissionsState.revokeInstallPermission(bp) != 8666 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8667 // Also drop the permission flags. 8668 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8669 PackageManager.MASK_PERMISSION_FLAGS, 0); 8670 changedInstallPermission = true; 8671 Slog.i(TAG, "Un-granting permission " + perm 8672 + " from package " + pkg.packageName 8673 + " (protectionLevel=" + bp.protectionLevel 8674 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8675 + ")"); 8676 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8677 // Don't print warning for app op permissions, since it is fine for them 8678 // not to be granted, there is a UI for the user to decide. 8679 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8680 Slog.w(TAG, "Not granting permission " + perm 8681 + " to package " + pkg.packageName 8682 + " (protectionLevel=" + bp.protectionLevel 8683 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8684 + ")"); 8685 } 8686 } 8687 } 8688 } 8689 8690 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8691 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8692 // This is the first that we have heard about this package, so the 8693 // permissions we have now selected are fixed until explicitly 8694 // changed. 8695 ps.installPermissionsFixed = true; 8696 } 8697 8698 // Persist the runtime permissions state for users with changes. 8699 for (int userId : changedRuntimePermissionUserIds) { 8700 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8701 } 8702 8703 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8704 } 8705 8706 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8707 boolean allowed = false; 8708 final int NP = PackageParser.NEW_PERMISSIONS.length; 8709 for (int ip=0; ip<NP; ip++) { 8710 final PackageParser.NewPermissionInfo npi 8711 = PackageParser.NEW_PERMISSIONS[ip]; 8712 if (npi.name.equals(perm) 8713 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8714 allowed = true; 8715 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8716 + pkg.packageName); 8717 break; 8718 } 8719 } 8720 return allowed; 8721 } 8722 8723 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8724 BasePermission bp, PermissionsState origPermissions) { 8725 boolean allowed; 8726 allowed = (compareSignatures( 8727 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8728 == PackageManager.SIGNATURE_MATCH) 8729 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8730 == PackageManager.SIGNATURE_MATCH); 8731 if (!allowed && (bp.protectionLevel 8732 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8733 if (isSystemApp(pkg)) { 8734 // For updated system applications, a system permission 8735 // is granted only if it had been defined by the original application. 8736 if (pkg.isUpdatedSystemApp()) { 8737 final PackageSetting sysPs = mSettings 8738 .getDisabledSystemPkgLPr(pkg.packageName); 8739 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8740 // If the original was granted this permission, we take 8741 // that grant decision as read and propagate it to the 8742 // update. 8743 if (sysPs.isPrivileged()) { 8744 allowed = true; 8745 } 8746 } else { 8747 // The system apk may have been updated with an older 8748 // version of the one on the data partition, but which 8749 // granted a new system permission that it didn't have 8750 // before. In this case we do want to allow the app to 8751 // now get the new permission if the ancestral apk is 8752 // privileged to get it. 8753 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8754 for (int j=0; 8755 j<sysPs.pkg.requestedPermissions.size(); j++) { 8756 if (perm.equals( 8757 sysPs.pkg.requestedPermissions.get(j))) { 8758 allowed = true; 8759 break; 8760 } 8761 } 8762 } 8763 } 8764 } else { 8765 allowed = isPrivilegedApp(pkg); 8766 } 8767 } 8768 } 8769 if (!allowed) { 8770 if (!allowed && (bp.protectionLevel 8771 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8772 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8773 // If this was a previously normal/dangerous permission that got moved 8774 // to a system permission as part of the runtime permission redesign, then 8775 // we still want to blindly grant it to old apps. 8776 allowed = true; 8777 } 8778 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8779 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8780 // If this permission is to be granted to the system installer and 8781 // this app is an installer, then it gets the permission. 8782 allowed = true; 8783 } 8784 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8785 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8786 // If this permission is to be granted to the system verifier and 8787 // this app is a verifier, then it gets the permission. 8788 allowed = true; 8789 } 8790 if (!allowed && (bp.protectionLevel 8791 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8792 && isSystemApp(pkg)) { 8793 // Any pre-installed system app is allowed to get this permission. 8794 allowed = true; 8795 } 8796 if (!allowed && (bp.protectionLevel 8797 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8798 // For development permissions, a development permission 8799 // is granted only if it was already granted. 8800 allowed = origPermissions.hasInstallPermission(perm); 8801 } 8802 } 8803 return allowed; 8804 } 8805 8806 final class ActivityIntentResolver 8807 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8808 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8809 boolean defaultOnly, int userId) { 8810 if (!sUserManager.exists(userId)) return null; 8811 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8812 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8813 } 8814 8815 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8816 int userId) { 8817 if (!sUserManager.exists(userId)) return null; 8818 mFlags = flags; 8819 return super.queryIntent(intent, resolvedType, 8820 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8821 } 8822 8823 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8824 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8825 if (!sUserManager.exists(userId)) return null; 8826 if (packageActivities == null) { 8827 return null; 8828 } 8829 mFlags = flags; 8830 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8831 final int N = packageActivities.size(); 8832 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8833 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8834 8835 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8836 for (int i = 0; i < N; ++i) { 8837 intentFilters = packageActivities.get(i).intents; 8838 if (intentFilters != null && intentFilters.size() > 0) { 8839 PackageParser.ActivityIntentInfo[] array = 8840 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8841 intentFilters.toArray(array); 8842 listCut.add(array); 8843 } 8844 } 8845 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8846 } 8847 8848 public final void addActivity(PackageParser.Activity a, String type) { 8849 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8850 mActivities.put(a.getComponentName(), a); 8851 if (DEBUG_SHOW_INFO) 8852 Log.v( 8853 TAG, " " + type + " " + 8854 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8855 if (DEBUG_SHOW_INFO) 8856 Log.v(TAG, " Class=" + a.info.name); 8857 final int NI = a.intents.size(); 8858 for (int j=0; j<NI; j++) { 8859 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8860 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8861 intent.setPriority(0); 8862 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8863 + a.className + " with priority > 0, forcing to 0"); 8864 } 8865 if (DEBUG_SHOW_INFO) { 8866 Log.v(TAG, " IntentFilter:"); 8867 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8868 } 8869 if (!intent.debugCheck()) { 8870 Log.w(TAG, "==> For Activity " + a.info.name); 8871 } 8872 addFilter(intent); 8873 } 8874 } 8875 8876 public final void removeActivity(PackageParser.Activity a, String type) { 8877 mActivities.remove(a.getComponentName()); 8878 if (DEBUG_SHOW_INFO) { 8879 Log.v(TAG, " " + type + " " 8880 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8881 : a.info.name) + ":"); 8882 Log.v(TAG, " Class=" + a.info.name); 8883 } 8884 final int NI = a.intents.size(); 8885 for (int j=0; j<NI; j++) { 8886 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8887 if (DEBUG_SHOW_INFO) { 8888 Log.v(TAG, " IntentFilter:"); 8889 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8890 } 8891 removeFilter(intent); 8892 } 8893 } 8894 8895 @Override 8896 protected boolean allowFilterResult( 8897 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8898 ActivityInfo filterAi = filter.activity.info; 8899 for (int i=dest.size()-1; i>=0; i--) { 8900 ActivityInfo destAi = dest.get(i).activityInfo; 8901 if (destAi.name == filterAi.name 8902 && destAi.packageName == filterAi.packageName) { 8903 return false; 8904 } 8905 } 8906 return true; 8907 } 8908 8909 @Override 8910 protected ActivityIntentInfo[] newArray(int size) { 8911 return new ActivityIntentInfo[size]; 8912 } 8913 8914 @Override 8915 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8916 if (!sUserManager.exists(userId)) return true; 8917 PackageParser.Package p = filter.activity.owner; 8918 if (p != null) { 8919 PackageSetting ps = (PackageSetting)p.mExtras; 8920 if (ps != null) { 8921 // System apps are never considered stopped for purposes of 8922 // filtering, because there may be no way for the user to 8923 // actually re-launch them. 8924 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8925 && ps.getStopped(userId); 8926 } 8927 } 8928 return false; 8929 } 8930 8931 @Override 8932 protected boolean isPackageForFilter(String packageName, 8933 PackageParser.ActivityIntentInfo info) { 8934 return packageName.equals(info.activity.owner.packageName); 8935 } 8936 8937 @Override 8938 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8939 int match, int userId) { 8940 if (!sUserManager.exists(userId)) return null; 8941 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8942 return null; 8943 } 8944 final PackageParser.Activity activity = info.activity; 8945 if (mSafeMode && (activity.info.applicationInfo.flags 8946 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8947 return null; 8948 } 8949 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8950 if (ps == null) { 8951 return null; 8952 } 8953 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8954 ps.readUserState(userId), userId); 8955 if (ai == null) { 8956 return null; 8957 } 8958 final ResolveInfo res = new ResolveInfo(); 8959 res.activityInfo = ai; 8960 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8961 res.filter = info; 8962 } 8963 if (info != null) { 8964 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8965 } 8966 res.priority = info.getPriority(); 8967 res.preferredOrder = activity.owner.mPreferredOrder; 8968 //System.out.println("Result: " + res.activityInfo.className + 8969 // " = " + res.priority); 8970 res.match = match; 8971 res.isDefault = info.hasDefault; 8972 res.labelRes = info.labelRes; 8973 res.nonLocalizedLabel = info.nonLocalizedLabel; 8974 if (userNeedsBadging(userId)) { 8975 res.noResourceId = true; 8976 } else { 8977 res.icon = info.icon; 8978 } 8979 res.iconResourceId = info.icon; 8980 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8981 return res; 8982 } 8983 8984 @Override 8985 protected void sortResults(List<ResolveInfo> results) { 8986 Collections.sort(results, mResolvePrioritySorter); 8987 } 8988 8989 @Override 8990 protected void dumpFilter(PrintWriter out, String prefix, 8991 PackageParser.ActivityIntentInfo filter) { 8992 out.print(prefix); out.print( 8993 Integer.toHexString(System.identityHashCode(filter.activity))); 8994 out.print(' '); 8995 filter.activity.printComponentShortName(out); 8996 out.print(" filter "); 8997 out.println(Integer.toHexString(System.identityHashCode(filter))); 8998 } 8999 9000 @Override 9001 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9002 return filter.activity; 9003 } 9004 9005 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9006 PackageParser.Activity activity = (PackageParser.Activity)label; 9007 out.print(prefix); out.print( 9008 Integer.toHexString(System.identityHashCode(activity))); 9009 out.print(' '); 9010 activity.printComponentShortName(out); 9011 if (count > 1) { 9012 out.print(" ("); out.print(count); out.print(" filters)"); 9013 } 9014 out.println(); 9015 } 9016 9017// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9018// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9019// final List<ResolveInfo> retList = Lists.newArrayList(); 9020// while (i.hasNext()) { 9021// final ResolveInfo resolveInfo = i.next(); 9022// if (isEnabledLP(resolveInfo.activityInfo)) { 9023// retList.add(resolveInfo); 9024// } 9025// } 9026// return retList; 9027// } 9028 9029 // Keys are String (activity class name), values are Activity. 9030 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9031 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9032 private int mFlags; 9033 } 9034 9035 private final class ServiceIntentResolver 9036 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9037 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9038 boolean defaultOnly, int userId) { 9039 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9040 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9041 } 9042 9043 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9044 int userId) { 9045 if (!sUserManager.exists(userId)) return null; 9046 mFlags = flags; 9047 return super.queryIntent(intent, resolvedType, 9048 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9049 } 9050 9051 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9052 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9053 if (!sUserManager.exists(userId)) return null; 9054 if (packageServices == null) { 9055 return null; 9056 } 9057 mFlags = flags; 9058 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9059 final int N = packageServices.size(); 9060 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9061 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9062 9063 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9064 for (int i = 0; i < N; ++i) { 9065 intentFilters = packageServices.get(i).intents; 9066 if (intentFilters != null && intentFilters.size() > 0) { 9067 PackageParser.ServiceIntentInfo[] array = 9068 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9069 intentFilters.toArray(array); 9070 listCut.add(array); 9071 } 9072 } 9073 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9074 } 9075 9076 public final void addService(PackageParser.Service s) { 9077 mServices.put(s.getComponentName(), s); 9078 if (DEBUG_SHOW_INFO) { 9079 Log.v(TAG, " " 9080 + (s.info.nonLocalizedLabel != null 9081 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9082 Log.v(TAG, " Class=" + s.info.name); 9083 } 9084 final int NI = s.intents.size(); 9085 int j; 9086 for (j=0; j<NI; j++) { 9087 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9088 if (DEBUG_SHOW_INFO) { 9089 Log.v(TAG, " IntentFilter:"); 9090 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9091 } 9092 if (!intent.debugCheck()) { 9093 Log.w(TAG, "==> For Service " + s.info.name); 9094 } 9095 addFilter(intent); 9096 } 9097 } 9098 9099 public final void removeService(PackageParser.Service s) { 9100 mServices.remove(s.getComponentName()); 9101 if (DEBUG_SHOW_INFO) { 9102 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9103 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9104 Log.v(TAG, " Class=" + s.info.name); 9105 } 9106 final int NI = s.intents.size(); 9107 int j; 9108 for (j=0; j<NI; j++) { 9109 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9110 if (DEBUG_SHOW_INFO) { 9111 Log.v(TAG, " IntentFilter:"); 9112 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9113 } 9114 removeFilter(intent); 9115 } 9116 } 9117 9118 @Override 9119 protected boolean allowFilterResult( 9120 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9121 ServiceInfo filterSi = filter.service.info; 9122 for (int i=dest.size()-1; i>=0; i--) { 9123 ServiceInfo destAi = dest.get(i).serviceInfo; 9124 if (destAi.name == filterSi.name 9125 && destAi.packageName == filterSi.packageName) { 9126 return false; 9127 } 9128 } 9129 return true; 9130 } 9131 9132 @Override 9133 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9134 return new PackageParser.ServiceIntentInfo[size]; 9135 } 9136 9137 @Override 9138 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9139 if (!sUserManager.exists(userId)) return true; 9140 PackageParser.Package p = filter.service.owner; 9141 if (p != null) { 9142 PackageSetting ps = (PackageSetting)p.mExtras; 9143 if (ps != null) { 9144 // System apps are never considered stopped for purposes of 9145 // filtering, because there may be no way for the user to 9146 // actually re-launch them. 9147 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9148 && ps.getStopped(userId); 9149 } 9150 } 9151 return false; 9152 } 9153 9154 @Override 9155 protected boolean isPackageForFilter(String packageName, 9156 PackageParser.ServiceIntentInfo info) { 9157 return packageName.equals(info.service.owner.packageName); 9158 } 9159 9160 @Override 9161 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9162 int match, int userId) { 9163 if (!sUserManager.exists(userId)) return null; 9164 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9165 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9166 return null; 9167 } 9168 final PackageParser.Service service = info.service; 9169 if (mSafeMode && (service.info.applicationInfo.flags 9170 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9171 return null; 9172 } 9173 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9174 if (ps == null) { 9175 return null; 9176 } 9177 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9178 ps.readUserState(userId), userId); 9179 if (si == null) { 9180 return null; 9181 } 9182 final ResolveInfo res = new ResolveInfo(); 9183 res.serviceInfo = si; 9184 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9185 res.filter = filter; 9186 } 9187 res.priority = info.getPriority(); 9188 res.preferredOrder = service.owner.mPreferredOrder; 9189 res.match = match; 9190 res.isDefault = info.hasDefault; 9191 res.labelRes = info.labelRes; 9192 res.nonLocalizedLabel = info.nonLocalizedLabel; 9193 res.icon = info.icon; 9194 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9195 return res; 9196 } 9197 9198 @Override 9199 protected void sortResults(List<ResolveInfo> results) { 9200 Collections.sort(results, mResolvePrioritySorter); 9201 } 9202 9203 @Override 9204 protected void dumpFilter(PrintWriter out, String prefix, 9205 PackageParser.ServiceIntentInfo filter) { 9206 out.print(prefix); out.print( 9207 Integer.toHexString(System.identityHashCode(filter.service))); 9208 out.print(' '); 9209 filter.service.printComponentShortName(out); 9210 out.print(" filter "); 9211 out.println(Integer.toHexString(System.identityHashCode(filter))); 9212 } 9213 9214 @Override 9215 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9216 return filter.service; 9217 } 9218 9219 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9220 PackageParser.Service service = (PackageParser.Service)label; 9221 out.print(prefix); out.print( 9222 Integer.toHexString(System.identityHashCode(service))); 9223 out.print(' '); 9224 service.printComponentShortName(out); 9225 if (count > 1) { 9226 out.print(" ("); out.print(count); out.print(" filters)"); 9227 } 9228 out.println(); 9229 } 9230 9231// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9232// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9233// final List<ResolveInfo> retList = Lists.newArrayList(); 9234// while (i.hasNext()) { 9235// final ResolveInfo resolveInfo = (ResolveInfo) i; 9236// if (isEnabledLP(resolveInfo.serviceInfo)) { 9237// retList.add(resolveInfo); 9238// } 9239// } 9240// return retList; 9241// } 9242 9243 // Keys are String (activity class name), values are Activity. 9244 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9245 = new ArrayMap<ComponentName, PackageParser.Service>(); 9246 private int mFlags; 9247 }; 9248 9249 private final class ProviderIntentResolver 9250 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9251 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9252 boolean defaultOnly, int userId) { 9253 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9254 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9255 } 9256 9257 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9258 int userId) { 9259 if (!sUserManager.exists(userId)) 9260 return null; 9261 mFlags = flags; 9262 return super.queryIntent(intent, resolvedType, 9263 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9264 } 9265 9266 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9267 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9268 if (!sUserManager.exists(userId)) 9269 return null; 9270 if (packageProviders == null) { 9271 return null; 9272 } 9273 mFlags = flags; 9274 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9275 final int N = packageProviders.size(); 9276 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9277 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9278 9279 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9280 for (int i = 0; i < N; ++i) { 9281 intentFilters = packageProviders.get(i).intents; 9282 if (intentFilters != null && intentFilters.size() > 0) { 9283 PackageParser.ProviderIntentInfo[] array = 9284 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9285 intentFilters.toArray(array); 9286 listCut.add(array); 9287 } 9288 } 9289 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9290 } 9291 9292 public final void addProvider(PackageParser.Provider p) { 9293 if (mProviders.containsKey(p.getComponentName())) { 9294 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9295 return; 9296 } 9297 9298 mProviders.put(p.getComponentName(), p); 9299 if (DEBUG_SHOW_INFO) { 9300 Log.v(TAG, " " 9301 + (p.info.nonLocalizedLabel != null 9302 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9303 Log.v(TAG, " Class=" + p.info.name); 9304 } 9305 final int NI = p.intents.size(); 9306 int j; 9307 for (j = 0; j < NI; j++) { 9308 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9309 if (DEBUG_SHOW_INFO) { 9310 Log.v(TAG, " IntentFilter:"); 9311 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9312 } 9313 if (!intent.debugCheck()) { 9314 Log.w(TAG, "==> For Provider " + p.info.name); 9315 } 9316 addFilter(intent); 9317 } 9318 } 9319 9320 public final void removeProvider(PackageParser.Provider p) { 9321 mProviders.remove(p.getComponentName()); 9322 if (DEBUG_SHOW_INFO) { 9323 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9324 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9325 Log.v(TAG, " Class=" + p.info.name); 9326 } 9327 final int NI = p.intents.size(); 9328 int j; 9329 for (j = 0; j < NI; j++) { 9330 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9331 if (DEBUG_SHOW_INFO) { 9332 Log.v(TAG, " IntentFilter:"); 9333 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9334 } 9335 removeFilter(intent); 9336 } 9337 } 9338 9339 @Override 9340 protected boolean allowFilterResult( 9341 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9342 ProviderInfo filterPi = filter.provider.info; 9343 for (int i = dest.size() - 1; i >= 0; i--) { 9344 ProviderInfo destPi = dest.get(i).providerInfo; 9345 if (destPi.name == filterPi.name 9346 && destPi.packageName == filterPi.packageName) { 9347 return false; 9348 } 9349 } 9350 return true; 9351 } 9352 9353 @Override 9354 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9355 return new PackageParser.ProviderIntentInfo[size]; 9356 } 9357 9358 @Override 9359 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9360 if (!sUserManager.exists(userId)) 9361 return true; 9362 PackageParser.Package p = filter.provider.owner; 9363 if (p != null) { 9364 PackageSetting ps = (PackageSetting) p.mExtras; 9365 if (ps != null) { 9366 // System apps are never considered stopped for purposes of 9367 // filtering, because there may be no way for the user to 9368 // actually re-launch them. 9369 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9370 && ps.getStopped(userId); 9371 } 9372 } 9373 return false; 9374 } 9375 9376 @Override 9377 protected boolean isPackageForFilter(String packageName, 9378 PackageParser.ProviderIntentInfo info) { 9379 return packageName.equals(info.provider.owner.packageName); 9380 } 9381 9382 @Override 9383 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9384 int match, int userId) { 9385 if (!sUserManager.exists(userId)) 9386 return null; 9387 final PackageParser.ProviderIntentInfo info = filter; 9388 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9389 return null; 9390 } 9391 final PackageParser.Provider provider = info.provider; 9392 if (mSafeMode && (provider.info.applicationInfo.flags 9393 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9394 return null; 9395 } 9396 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9397 if (ps == null) { 9398 return null; 9399 } 9400 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9401 ps.readUserState(userId), userId); 9402 if (pi == null) { 9403 return null; 9404 } 9405 final ResolveInfo res = new ResolveInfo(); 9406 res.providerInfo = pi; 9407 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9408 res.filter = filter; 9409 } 9410 res.priority = info.getPriority(); 9411 res.preferredOrder = provider.owner.mPreferredOrder; 9412 res.match = match; 9413 res.isDefault = info.hasDefault; 9414 res.labelRes = info.labelRes; 9415 res.nonLocalizedLabel = info.nonLocalizedLabel; 9416 res.icon = info.icon; 9417 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9418 return res; 9419 } 9420 9421 @Override 9422 protected void sortResults(List<ResolveInfo> results) { 9423 Collections.sort(results, mResolvePrioritySorter); 9424 } 9425 9426 @Override 9427 protected void dumpFilter(PrintWriter out, String prefix, 9428 PackageParser.ProviderIntentInfo filter) { 9429 out.print(prefix); 9430 out.print( 9431 Integer.toHexString(System.identityHashCode(filter.provider))); 9432 out.print(' '); 9433 filter.provider.printComponentShortName(out); 9434 out.print(" filter "); 9435 out.println(Integer.toHexString(System.identityHashCode(filter))); 9436 } 9437 9438 @Override 9439 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9440 return filter.provider; 9441 } 9442 9443 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9444 PackageParser.Provider provider = (PackageParser.Provider)label; 9445 out.print(prefix); out.print( 9446 Integer.toHexString(System.identityHashCode(provider))); 9447 out.print(' '); 9448 provider.printComponentShortName(out); 9449 if (count > 1) { 9450 out.print(" ("); out.print(count); out.print(" filters)"); 9451 } 9452 out.println(); 9453 } 9454 9455 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9456 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9457 private int mFlags; 9458 }; 9459 9460 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9461 new Comparator<ResolveInfo>() { 9462 public int compare(ResolveInfo r1, ResolveInfo r2) { 9463 int v1 = r1.priority; 9464 int v2 = r2.priority; 9465 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9466 if (v1 != v2) { 9467 return (v1 > v2) ? -1 : 1; 9468 } 9469 v1 = r1.preferredOrder; 9470 v2 = r2.preferredOrder; 9471 if (v1 != v2) { 9472 return (v1 > v2) ? -1 : 1; 9473 } 9474 if (r1.isDefault != r2.isDefault) { 9475 return r1.isDefault ? -1 : 1; 9476 } 9477 v1 = r1.match; 9478 v2 = r2.match; 9479 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9480 if (v1 != v2) { 9481 return (v1 > v2) ? -1 : 1; 9482 } 9483 if (r1.system != r2.system) { 9484 return r1.system ? -1 : 1; 9485 } 9486 return 0; 9487 } 9488 }; 9489 9490 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9491 new Comparator<ProviderInfo>() { 9492 public int compare(ProviderInfo p1, ProviderInfo p2) { 9493 final int v1 = p1.initOrder; 9494 final int v2 = p2.initOrder; 9495 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9496 } 9497 }; 9498 9499 final void sendPackageBroadcast(final String action, final String pkg, 9500 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9501 final int[] userIds) { 9502 mHandler.post(new Runnable() { 9503 @Override 9504 public void run() { 9505 try { 9506 final IActivityManager am = ActivityManagerNative.getDefault(); 9507 if (am == null) return; 9508 final int[] resolvedUserIds; 9509 if (userIds == null) { 9510 resolvedUserIds = am.getRunningUserIds(); 9511 } else { 9512 resolvedUserIds = userIds; 9513 } 9514 for (int id : resolvedUserIds) { 9515 final Intent intent = new Intent(action, 9516 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9517 if (extras != null) { 9518 intent.putExtras(extras); 9519 } 9520 if (targetPkg != null) { 9521 intent.setPackage(targetPkg); 9522 } 9523 // Modify the UID when posting to other users 9524 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9525 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9526 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9527 intent.putExtra(Intent.EXTRA_UID, uid); 9528 } 9529 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9530 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9531 if (DEBUG_BROADCASTS) { 9532 RuntimeException here = new RuntimeException("here"); 9533 here.fillInStackTrace(); 9534 Slog.d(TAG, "Sending to user " + id + ": " 9535 + intent.toShortString(false, true, false, false) 9536 + " " + intent.getExtras(), here); 9537 } 9538 am.broadcastIntent(null, intent, null, finishedReceiver, 9539 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9540 null, finishedReceiver != null, false, id); 9541 } 9542 } catch (RemoteException ex) { 9543 } 9544 } 9545 }); 9546 } 9547 9548 /** 9549 * Check if the external storage media is available. This is true if there 9550 * is a mounted external storage medium or if the external storage is 9551 * emulated. 9552 */ 9553 private boolean isExternalMediaAvailable() { 9554 return mMediaMounted || Environment.isExternalStorageEmulated(); 9555 } 9556 9557 @Override 9558 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9559 // writer 9560 synchronized (mPackages) { 9561 if (!isExternalMediaAvailable()) { 9562 // If the external storage is no longer mounted at this point, 9563 // the caller may not have been able to delete all of this 9564 // packages files and can not delete any more. Bail. 9565 return null; 9566 } 9567 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9568 if (lastPackage != null) { 9569 pkgs.remove(lastPackage); 9570 } 9571 if (pkgs.size() > 0) { 9572 return pkgs.get(0); 9573 } 9574 } 9575 return null; 9576 } 9577 9578 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9579 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9580 userId, andCode ? 1 : 0, packageName); 9581 if (mSystemReady) { 9582 msg.sendToTarget(); 9583 } else { 9584 if (mPostSystemReadyMessages == null) { 9585 mPostSystemReadyMessages = new ArrayList<>(); 9586 } 9587 mPostSystemReadyMessages.add(msg); 9588 } 9589 } 9590 9591 void startCleaningPackages() { 9592 // reader 9593 synchronized (mPackages) { 9594 if (!isExternalMediaAvailable()) { 9595 return; 9596 } 9597 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9598 return; 9599 } 9600 } 9601 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9602 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9603 IActivityManager am = ActivityManagerNative.getDefault(); 9604 if (am != null) { 9605 try { 9606 am.startService(null, intent, null, mContext.getOpPackageName(), 9607 UserHandle.USER_SYSTEM); 9608 } catch (RemoteException e) { 9609 } 9610 } 9611 } 9612 9613 @Override 9614 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9615 int installFlags, String installerPackageName, VerificationParams verificationParams, 9616 String packageAbiOverride) { 9617 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9618 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9619 } 9620 9621 @Override 9622 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9623 int installFlags, String installerPackageName, VerificationParams verificationParams, 9624 String packageAbiOverride, int userId) { 9625 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9626 9627 final int callingUid = Binder.getCallingUid(); 9628 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9629 9630 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9631 try { 9632 if (observer != null) { 9633 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9634 } 9635 } catch (RemoteException re) { 9636 } 9637 return; 9638 } 9639 9640 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9641 installFlags |= PackageManager.INSTALL_FROM_ADB; 9642 9643 } else { 9644 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9645 // about installerPackageName. 9646 9647 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9648 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9649 } 9650 9651 UserHandle user; 9652 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9653 user = UserHandle.ALL; 9654 } else { 9655 user = new UserHandle(userId); 9656 } 9657 9658 // Only system components can circumvent runtime permissions when installing. 9659 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9660 && mContext.checkCallingOrSelfPermission(Manifest.permission 9661 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9662 throw new SecurityException("You need the " 9663 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9664 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9665 } 9666 9667 verificationParams.setInstallerUid(callingUid); 9668 9669 final File originFile = new File(originPath); 9670 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9671 9672 final Message msg = mHandler.obtainMessage(INIT_COPY); 9673 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9674 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9675 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9676 msg.obj = params; 9677 9678 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9679 System.identityHashCode(msg.obj)); 9680 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9681 System.identityHashCode(msg.obj)); 9682 9683 mHandler.sendMessage(msg); 9684 } 9685 9686 void installStage(String packageName, File stagedDir, String stagedCid, 9687 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9688 String installerPackageName, int installerUid, UserHandle user) { 9689 final VerificationParams verifParams = new VerificationParams( 9690 null, sessionParams.originatingUri, sessionParams.referrerUri, 9691 sessionParams.originatingUid, null); 9692 verifParams.setInstallerUid(installerUid); 9693 9694 final OriginInfo origin; 9695 if (stagedDir != null) { 9696 origin = OriginInfo.fromStagedFile(stagedDir); 9697 } else { 9698 origin = OriginInfo.fromStagedContainer(stagedCid); 9699 } 9700 9701 final Message msg = mHandler.obtainMessage(INIT_COPY); 9702 final InstallParams params = new InstallParams(origin, null, observer, 9703 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9704 verifParams, user, sessionParams.abiOverride, 9705 sessionParams.grantedRuntimePermissions); 9706 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9707 msg.obj = params; 9708 9709 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9710 System.identityHashCode(msg.obj)); 9711 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9712 System.identityHashCode(msg.obj)); 9713 9714 mHandler.sendMessage(msg); 9715 } 9716 9717 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9718 Bundle extras = new Bundle(1); 9719 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9720 9721 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9722 packageName, extras, null, null, new int[] {userId}); 9723 try { 9724 IActivityManager am = ActivityManagerNative.getDefault(); 9725 final boolean isSystem = 9726 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9727 if (isSystem && am.isUserRunning(userId, false)) { 9728 // The just-installed/enabled app is bundled on the system, so presumed 9729 // to be able to run automatically without needing an explicit launch. 9730 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9731 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9732 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9733 .setPackage(packageName); 9734 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9735 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9736 } 9737 } catch (RemoteException e) { 9738 // shouldn't happen 9739 Slog.w(TAG, "Unable to bootstrap installed package", e); 9740 } 9741 } 9742 9743 @Override 9744 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9745 int userId) { 9746 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9747 PackageSetting pkgSetting; 9748 final int uid = Binder.getCallingUid(); 9749 enforceCrossUserPermission(uid, userId, true, true, 9750 "setApplicationHiddenSetting for user " + userId); 9751 9752 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9753 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9754 return false; 9755 } 9756 9757 long callingId = Binder.clearCallingIdentity(); 9758 try { 9759 boolean sendAdded = false; 9760 boolean sendRemoved = false; 9761 // writer 9762 synchronized (mPackages) { 9763 pkgSetting = mSettings.mPackages.get(packageName); 9764 if (pkgSetting == null) { 9765 return false; 9766 } 9767 if (pkgSetting.getHidden(userId) != hidden) { 9768 pkgSetting.setHidden(hidden, userId); 9769 mSettings.writePackageRestrictionsLPr(userId); 9770 if (hidden) { 9771 sendRemoved = true; 9772 } else { 9773 sendAdded = true; 9774 } 9775 } 9776 } 9777 if (sendAdded) { 9778 sendPackageAddedForUser(packageName, pkgSetting, userId); 9779 return true; 9780 } 9781 if (sendRemoved) { 9782 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9783 "hiding pkg"); 9784 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9785 return true; 9786 } 9787 } finally { 9788 Binder.restoreCallingIdentity(callingId); 9789 } 9790 return false; 9791 } 9792 9793 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9794 int userId) { 9795 final PackageRemovedInfo info = new PackageRemovedInfo(); 9796 info.removedPackage = packageName; 9797 info.removedUsers = new int[] {userId}; 9798 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9799 info.sendBroadcast(false, false, false); 9800 } 9801 9802 /** 9803 * Returns true if application is not found or there was an error. Otherwise it returns 9804 * the hidden state of the package for the given user. 9805 */ 9806 @Override 9807 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9808 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9809 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9810 false, "getApplicationHidden for user " + userId); 9811 PackageSetting pkgSetting; 9812 long callingId = Binder.clearCallingIdentity(); 9813 try { 9814 // writer 9815 synchronized (mPackages) { 9816 pkgSetting = mSettings.mPackages.get(packageName); 9817 if (pkgSetting == null) { 9818 return true; 9819 } 9820 return pkgSetting.getHidden(userId); 9821 } 9822 } finally { 9823 Binder.restoreCallingIdentity(callingId); 9824 } 9825 } 9826 9827 /** 9828 * @hide 9829 */ 9830 @Override 9831 public int installExistingPackageAsUser(String packageName, int userId) { 9832 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9833 null); 9834 PackageSetting pkgSetting; 9835 final int uid = Binder.getCallingUid(); 9836 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9837 + userId); 9838 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9839 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9840 } 9841 9842 long callingId = Binder.clearCallingIdentity(); 9843 try { 9844 boolean sendAdded = false; 9845 9846 // writer 9847 synchronized (mPackages) { 9848 pkgSetting = mSettings.mPackages.get(packageName); 9849 if (pkgSetting == null) { 9850 return PackageManager.INSTALL_FAILED_INVALID_URI; 9851 } 9852 if (!pkgSetting.getInstalled(userId)) { 9853 pkgSetting.setInstalled(true, userId); 9854 pkgSetting.setHidden(false, userId); 9855 mSettings.writePackageRestrictionsLPr(userId); 9856 sendAdded = true; 9857 } 9858 } 9859 9860 if (sendAdded) { 9861 sendPackageAddedForUser(packageName, pkgSetting, userId); 9862 } 9863 } finally { 9864 Binder.restoreCallingIdentity(callingId); 9865 } 9866 9867 return PackageManager.INSTALL_SUCCEEDED; 9868 } 9869 9870 boolean isUserRestricted(int userId, String restrictionKey) { 9871 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9872 if (restrictions.getBoolean(restrictionKey, false)) { 9873 Log.w(TAG, "User is restricted: " + restrictionKey); 9874 return true; 9875 } 9876 return false; 9877 } 9878 9879 @Override 9880 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9881 mContext.enforceCallingOrSelfPermission( 9882 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9883 "Only package verification agents can verify applications"); 9884 9885 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9886 final PackageVerificationResponse response = new PackageVerificationResponse( 9887 verificationCode, Binder.getCallingUid()); 9888 msg.arg1 = id; 9889 msg.obj = response; 9890 mHandler.sendMessage(msg); 9891 } 9892 9893 @Override 9894 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9895 long millisecondsToDelay) { 9896 mContext.enforceCallingOrSelfPermission( 9897 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9898 "Only package verification agents can extend verification timeouts"); 9899 9900 final PackageVerificationState state = mPendingVerification.get(id); 9901 final PackageVerificationResponse response = new PackageVerificationResponse( 9902 verificationCodeAtTimeout, Binder.getCallingUid()); 9903 9904 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9905 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9906 } 9907 if (millisecondsToDelay < 0) { 9908 millisecondsToDelay = 0; 9909 } 9910 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9911 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9912 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9913 } 9914 9915 if ((state != null) && !state.timeoutExtended()) { 9916 state.extendTimeout(); 9917 9918 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9919 msg.arg1 = id; 9920 msg.obj = response; 9921 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9922 } 9923 } 9924 9925 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9926 int verificationCode, UserHandle user) { 9927 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9928 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9929 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9930 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9931 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9932 9933 mContext.sendBroadcastAsUser(intent, user, 9934 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9935 } 9936 9937 private ComponentName matchComponentForVerifier(String packageName, 9938 List<ResolveInfo> receivers) { 9939 ActivityInfo targetReceiver = null; 9940 9941 final int NR = receivers.size(); 9942 for (int i = 0; i < NR; i++) { 9943 final ResolveInfo info = receivers.get(i); 9944 if (info.activityInfo == null) { 9945 continue; 9946 } 9947 9948 if (packageName.equals(info.activityInfo.packageName)) { 9949 targetReceiver = info.activityInfo; 9950 break; 9951 } 9952 } 9953 9954 if (targetReceiver == null) { 9955 return null; 9956 } 9957 9958 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9959 } 9960 9961 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9962 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9963 if (pkgInfo.verifiers.length == 0) { 9964 return null; 9965 } 9966 9967 final int N = pkgInfo.verifiers.length; 9968 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9969 for (int i = 0; i < N; i++) { 9970 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9971 9972 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9973 receivers); 9974 if (comp == null) { 9975 continue; 9976 } 9977 9978 final int verifierUid = getUidForVerifier(verifierInfo); 9979 if (verifierUid == -1) { 9980 continue; 9981 } 9982 9983 if (DEBUG_VERIFY) { 9984 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9985 + " with the correct signature"); 9986 } 9987 sufficientVerifiers.add(comp); 9988 verificationState.addSufficientVerifier(verifierUid); 9989 } 9990 9991 return sufficientVerifiers; 9992 } 9993 9994 private int getUidForVerifier(VerifierInfo verifierInfo) { 9995 synchronized (mPackages) { 9996 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9997 if (pkg == null) { 9998 return -1; 9999 } else if (pkg.mSignatures.length != 1) { 10000 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10001 + " has more than one signature; ignoring"); 10002 return -1; 10003 } 10004 10005 /* 10006 * If the public key of the package's signature does not match 10007 * our expected public key, then this is a different package and 10008 * we should skip. 10009 */ 10010 10011 final byte[] expectedPublicKey; 10012 try { 10013 final Signature verifierSig = pkg.mSignatures[0]; 10014 final PublicKey publicKey = verifierSig.getPublicKey(); 10015 expectedPublicKey = publicKey.getEncoded(); 10016 } catch (CertificateException e) { 10017 return -1; 10018 } 10019 10020 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10021 10022 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10023 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10024 + " does not have the expected public key; ignoring"); 10025 return -1; 10026 } 10027 10028 return pkg.applicationInfo.uid; 10029 } 10030 } 10031 10032 @Override 10033 public void finishPackageInstall(int token) { 10034 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10035 10036 if (DEBUG_INSTALL) { 10037 Slog.v(TAG, "BM finishing package install for " + token); 10038 } 10039 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10040 10041 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10042 mHandler.sendMessage(msg); 10043 } 10044 10045 /** 10046 * Get the verification agent timeout. 10047 * 10048 * @return verification timeout in milliseconds 10049 */ 10050 private long getVerificationTimeout() { 10051 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10052 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10053 DEFAULT_VERIFICATION_TIMEOUT); 10054 } 10055 10056 /** 10057 * Get the default verification agent response code. 10058 * 10059 * @return default verification response code 10060 */ 10061 private int getDefaultVerificationResponse() { 10062 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10063 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10064 DEFAULT_VERIFICATION_RESPONSE); 10065 } 10066 10067 /** 10068 * Check whether or not package verification has been enabled. 10069 * 10070 * @return true if verification should be performed 10071 */ 10072 private boolean isVerificationEnabled(int userId, int installFlags) { 10073 if (!DEFAULT_VERIFY_ENABLE) { 10074 return false; 10075 } 10076 10077 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10078 10079 // Check if installing from ADB 10080 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10081 // Do not run verification in a test harness environment 10082 if (ActivityManager.isRunningInTestHarness()) { 10083 return false; 10084 } 10085 if (ensureVerifyAppsEnabled) { 10086 return true; 10087 } 10088 // Check if the developer does not want package verification for ADB installs 10089 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10090 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10091 return false; 10092 } 10093 } 10094 10095 if (ensureVerifyAppsEnabled) { 10096 return true; 10097 } 10098 10099 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10100 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10101 } 10102 10103 @Override 10104 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10105 throws RemoteException { 10106 mContext.enforceCallingOrSelfPermission( 10107 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10108 "Only intentfilter verification agents can verify applications"); 10109 10110 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10111 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10112 Binder.getCallingUid(), verificationCode, failedDomains); 10113 msg.arg1 = id; 10114 msg.obj = response; 10115 mHandler.sendMessage(msg); 10116 } 10117 10118 @Override 10119 public int getIntentVerificationStatus(String packageName, int userId) { 10120 synchronized (mPackages) { 10121 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10122 } 10123 } 10124 10125 @Override 10126 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10127 mContext.enforceCallingOrSelfPermission( 10128 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10129 10130 boolean result = false; 10131 synchronized (mPackages) { 10132 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10133 } 10134 if (result) { 10135 scheduleWritePackageRestrictionsLocked(userId); 10136 } 10137 return result; 10138 } 10139 10140 @Override 10141 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10142 synchronized (mPackages) { 10143 return mSettings.getIntentFilterVerificationsLPr(packageName); 10144 } 10145 } 10146 10147 @Override 10148 public List<IntentFilter> getAllIntentFilters(String packageName) { 10149 if (TextUtils.isEmpty(packageName)) { 10150 return Collections.<IntentFilter>emptyList(); 10151 } 10152 synchronized (mPackages) { 10153 PackageParser.Package pkg = mPackages.get(packageName); 10154 if (pkg == null || pkg.activities == null) { 10155 return Collections.<IntentFilter>emptyList(); 10156 } 10157 final int count = pkg.activities.size(); 10158 ArrayList<IntentFilter> result = new ArrayList<>(); 10159 for (int n=0; n<count; n++) { 10160 PackageParser.Activity activity = pkg.activities.get(n); 10161 if (activity.intents != null || activity.intents.size() > 0) { 10162 result.addAll(activity.intents); 10163 } 10164 } 10165 return result; 10166 } 10167 } 10168 10169 @Override 10170 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10171 mContext.enforceCallingOrSelfPermission( 10172 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10173 10174 synchronized (mPackages) { 10175 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10176 if (packageName != null) { 10177 result |= updateIntentVerificationStatus(packageName, 10178 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10179 userId); 10180 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10181 packageName, userId); 10182 } 10183 return result; 10184 } 10185 } 10186 10187 @Override 10188 public String getDefaultBrowserPackageName(int userId) { 10189 synchronized (mPackages) { 10190 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10191 } 10192 } 10193 10194 /** 10195 * Get the "allow unknown sources" setting. 10196 * 10197 * @return the current "allow unknown sources" setting 10198 */ 10199 private int getUnknownSourcesSettings() { 10200 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10201 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10202 -1); 10203 } 10204 10205 @Override 10206 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10207 final int uid = Binder.getCallingUid(); 10208 // writer 10209 synchronized (mPackages) { 10210 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10211 if (targetPackageSetting == null) { 10212 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10213 } 10214 10215 PackageSetting installerPackageSetting; 10216 if (installerPackageName != null) { 10217 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10218 if (installerPackageSetting == null) { 10219 throw new IllegalArgumentException("Unknown installer package: " 10220 + installerPackageName); 10221 } 10222 } else { 10223 installerPackageSetting = null; 10224 } 10225 10226 Signature[] callerSignature; 10227 Object obj = mSettings.getUserIdLPr(uid); 10228 if (obj != null) { 10229 if (obj instanceof SharedUserSetting) { 10230 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10231 } else if (obj instanceof PackageSetting) { 10232 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10233 } else { 10234 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10235 } 10236 } else { 10237 throw new SecurityException("Unknown calling uid " + uid); 10238 } 10239 10240 // Verify: can't set installerPackageName to a package that is 10241 // not signed with the same cert as the caller. 10242 if (installerPackageSetting != null) { 10243 if (compareSignatures(callerSignature, 10244 installerPackageSetting.signatures.mSignatures) 10245 != PackageManager.SIGNATURE_MATCH) { 10246 throw new SecurityException( 10247 "Caller does not have same cert as new installer package " 10248 + installerPackageName); 10249 } 10250 } 10251 10252 // Verify: if target already has an installer package, it must 10253 // be signed with the same cert as the caller. 10254 if (targetPackageSetting.installerPackageName != null) { 10255 PackageSetting setting = mSettings.mPackages.get( 10256 targetPackageSetting.installerPackageName); 10257 // If the currently set package isn't valid, then it's always 10258 // okay to change it. 10259 if (setting != null) { 10260 if (compareSignatures(callerSignature, 10261 setting.signatures.mSignatures) 10262 != PackageManager.SIGNATURE_MATCH) { 10263 throw new SecurityException( 10264 "Caller does not have same cert as old installer package " 10265 + targetPackageSetting.installerPackageName); 10266 } 10267 } 10268 } 10269 10270 // Okay! 10271 targetPackageSetting.installerPackageName = installerPackageName; 10272 scheduleWriteSettingsLocked(); 10273 } 10274 } 10275 10276 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10277 // Queue up an async operation since the package installation may take a little while. 10278 mHandler.post(new Runnable() { 10279 public void run() { 10280 mHandler.removeCallbacks(this); 10281 // Result object to be returned 10282 PackageInstalledInfo res = new PackageInstalledInfo(); 10283 res.returnCode = currentStatus; 10284 res.uid = -1; 10285 res.pkg = null; 10286 res.removedInfo = new PackageRemovedInfo(); 10287 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10288 args.doPreInstall(res.returnCode); 10289 synchronized (mInstallLock) { 10290 installPackageTracedLI(args, res); 10291 } 10292 args.doPostInstall(res.returnCode, res.uid); 10293 } 10294 10295 // A restore should be performed at this point if (a) the install 10296 // succeeded, (b) the operation is not an update, and (c) the new 10297 // package has not opted out of backup participation. 10298 final boolean update = res.removedInfo.removedPackage != null; 10299 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10300 boolean doRestore = !update 10301 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10302 10303 // Set up the post-install work request bookkeeping. This will be used 10304 // and cleaned up by the post-install event handling regardless of whether 10305 // there's a restore pass performed. Token values are >= 1. 10306 int token; 10307 if (mNextInstallToken < 0) mNextInstallToken = 1; 10308 token = mNextInstallToken++; 10309 10310 PostInstallData data = new PostInstallData(args, res); 10311 mRunningInstalls.put(token, data); 10312 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10313 10314 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10315 // Pass responsibility to the Backup Manager. It will perform a 10316 // restore if appropriate, then pass responsibility back to the 10317 // Package Manager to run the post-install observer callbacks 10318 // and broadcasts. 10319 IBackupManager bm = IBackupManager.Stub.asInterface( 10320 ServiceManager.getService(Context.BACKUP_SERVICE)); 10321 if (bm != null) { 10322 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10323 + " to BM for possible restore"); 10324 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10325 try { 10326 // TODO: http://b/22388012 10327 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10328 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10329 } else { 10330 doRestore = false; 10331 } 10332 } catch (RemoteException e) { 10333 // can't happen; the backup manager is local 10334 } catch (Exception e) { 10335 Slog.e(TAG, "Exception trying to enqueue restore", e); 10336 doRestore = false; 10337 } 10338 } else { 10339 Slog.e(TAG, "Backup Manager not found!"); 10340 doRestore = false; 10341 } 10342 } 10343 10344 if (!doRestore) { 10345 // No restore possible, or the Backup Manager was mysteriously not 10346 // available -- just fire the post-install work request directly. 10347 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10348 10349 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10350 10351 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10352 mHandler.sendMessage(msg); 10353 } 10354 } 10355 }); 10356 } 10357 10358 private abstract class HandlerParams { 10359 private static final int MAX_RETRIES = 4; 10360 10361 /** 10362 * Number of times startCopy() has been attempted and had a non-fatal 10363 * error. 10364 */ 10365 private int mRetries = 0; 10366 10367 /** User handle for the user requesting the information or installation. */ 10368 private final UserHandle mUser; 10369 String traceMethod; 10370 int traceCookie; 10371 10372 HandlerParams(UserHandle user) { 10373 mUser = user; 10374 } 10375 10376 UserHandle getUser() { 10377 return mUser; 10378 } 10379 10380 HandlerParams setTraceMethod(String traceMethod) { 10381 this.traceMethod = traceMethod; 10382 return this; 10383 } 10384 10385 HandlerParams setTraceCookie(int traceCookie) { 10386 this.traceCookie = traceCookie; 10387 return this; 10388 } 10389 10390 final boolean startCopy() { 10391 boolean res; 10392 try { 10393 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10394 10395 if (++mRetries > MAX_RETRIES) { 10396 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10397 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10398 handleServiceError(); 10399 return false; 10400 } else { 10401 handleStartCopy(); 10402 res = true; 10403 } 10404 } catch (RemoteException e) { 10405 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10406 mHandler.sendEmptyMessage(MCS_RECONNECT); 10407 res = false; 10408 } 10409 handleReturnCode(); 10410 return res; 10411 } 10412 10413 final void serviceError() { 10414 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10415 handleServiceError(); 10416 handleReturnCode(); 10417 } 10418 10419 abstract void handleStartCopy() throws RemoteException; 10420 abstract void handleServiceError(); 10421 abstract void handleReturnCode(); 10422 } 10423 10424 class MeasureParams extends HandlerParams { 10425 private final PackageStats mStats; 10426 private boolean mSuccess; 10427 10428 private final IPackageStatsObserver mObserver; 10429 10430 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10431 super(new UserHandle(stats.userHandle)); 10432 mObserver = observer; 10433 mStats = stats; 10434 } 10435 10436 @Override 10437 public String toString() { 10438 return "MeasureParams{" 10439 + Integer.toHexString(System.identityHashCode(this)) 10440 + " " + mStats.packageName + "}"; 10441 } 10442 10443 @Override 10444 void handleStartCopy() throws RemoteException { 10445 synchronized (mInstallLock) { 10446 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10447 } 10448 10449 if (mSuccess) { 10450 final boolean mounted; 10451 if (Environment.isExternalStorageEmulated()) { 10452 mounted = true; 10453 } else { 10454 final String status = Environment.getExternalStorageState(); 10455 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10456 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10457 } 10458 10459 if (mounted) { 10460 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10461 10462 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10463 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10464 10465 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10466 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10467 10468 // Always subtract cache size, since it's a subdirectory 10469 mStats.externalDataSize -= mStats.externalCacheSize; 10470 10471 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10472 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10473 10474 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10475 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10476 } 10477 } 10478 } 10479 10480 @Override 10481 void handleReturnCode() { 10482 if (mObserver != null) { 10483 try { 10484 mObserver.onGetStatsCompleted(mStats, mSuccess); 10485 } catch (RemoteException e) { 10486 Slog.i(TAG, "Observer no longer exists."); 10487 } 10488 } 10489 } 10490 10491 @Override 10492 void handleServiceError() { 10493 Slog.e(TAG, "Could not measure application " + mStats.packageName 10494 + " external storage"); 10495 } 10496 } 10497 10498 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10499 throws RemoteException { 10500 long result = 0; 10501 for (File path : paths) { 10502 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10503 } 10504 return result; 10505 } 10506 10507 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10508 for (File path : paths) { 10509 try { 10510 mcs.clearDirectory(path.getAbsolutePath()); 10511 } catch (RemoteException e) { 10512 } 10513 } 10514 } 10515 10516 static class OriginInfo { 10517 /** 10518 * Location where install is coming from, before it has been 10519 * copied/renamed into place. This could be a single monolithic APK 10520 * file, or a cluster directory. This location may be untrusted. 10521 */ 10522 final File file; 10523 final String cid; 10524 10525 /** 10526 * Flag indicating that {@link #file} or {@link #cid} has already been 10527 * staged, meaning downstream users don't need to defensively copy the 10528 * contents. 10529 */ 10530 final boolean staged; 10531 10532 /** 10533 * Flag indicating that {@link #file} or {@link #cid} is an already 10534 * installed app that is being moved. 10535 */ 10536 final boolean existing; 10537 10538 final String resolvedPath; 10539 final File resolvedFile; 10540 10541 static OriginInfo fromNothing() { 10542 return new OriginInfo(null, null, false, false); 10543 } 10544 10545 static OriginInfo fromUntrustedFile(File file) { 10546 return new OriginInfo(file, null, false, false); 10547 } 10548 10549 static OriginInfo fromExistingFile(File file) { 10550 return new OriginInfo(file, null, false, true); 10551 } 10552 10553 static OriginInfo fromStagedFile(File file) { 10554 return new OriginInfo(file, null, true, false); 10555 } 10556 10557 static OriginInfo fromStagedContainer(String cid) { 10558 return new OriginInfo(null, cid, true, false); 10559 } 10560 10561 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10562 this.file = file; 10563 this.cid = cid; 10564 this.staged = staged; 10565 this.existing = existing; 10566 10567 if (cid != null) { 10568 resolvedPath = PackageHelper.getSdDir(cid); 10569 resolvedFile = new File(resolvedPath); 10570 } else if (file != null) { 10571 resolvedPath = file.getAbsolutePath(); 10572 resolvedFile = file; 10573 } else { 10574 resolvedPath = null; 10575 resolvedFile = null; 10576 } 10577 } 10578 } 10579 10580 class MoveInfo { 10581 final int moveId; 10582 final String fromUuid; 10583 final String toUuid; 10584 final String packageName; 10585 final String dataAppName; 10586 final int appId; 10587 final String seinfo; 10588 10589 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10590 String dataAppName, int appId, String seinfo) { 10591 this.moveId = moveId; 10592 this.fromUuid = fromUuid; 10593 this.toUuid = toUuid; 10594 this.packageName = packageName; 10595 this.dataAppName = dataAppName; 10596 this.appId = appId; 10597 this.seinfo = seinfo; 10598 } 10599 } 10600 10601 class InstallParams extends HandlerParams { 10602 final OriginInfo origin; 10603 final MoveInfo move; 10604 final IPackageInstallObserver2 observer; 10605 int installFlags; 10606 final String installerPackageName; 10607 final String volumeUuid; 10608 final VerificationParams verificationParams; 10609 private InstallArgs mArgs; 10610 private int mRet; 10611 final String packageAbiOverride; 10612 final String[] grantedRuntimePermissions; 10613 10614 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10615 int installFlags, String installerPackageName, String volumeUuid, 10616 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10617 String[] grantedPermissions) { 10618 super(user); 10619 this.origin = origin; 10620 this.move = move; 10621 this.observer = observer; 10622 this.installFlags = installFlags; 10623 this.installerPackageName = installerPackageName; 10624 this.volumeUuid = volumeUuid; 10625 this.verificationParams = verificationParams; 10626 this.packageAbiOverride = packageAbiOverride; 10627 this.grantedRuntimePermissions = grantedPermissions; 10628 } 10629 10630 @Override 10631 public String toString() { 10632 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10633 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10634 } 10635 10636 public ManifestDigest getManifestDigest() { 10637 if (verificationParams == null) { 10638 return null; 10639 } 10640 return verificationParams.getManifestDigest(); 10641 } 10642 10643 private int installLocationPolicy(PackageInfoLite pkgLite) { 10644 String packageName = pkgLite.packageName; 10645 int installLocation = pkgLite.installLocation; 10646 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10647 // reader 10648 synchronized (mPackages) { 10649 PackageParser.Package pkg = mPackages.get(packageName); 10650 if (pkg != null) { 10651 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10652 // Check for downgrading. 10653 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10654 try { 10655 checkDowngrade(pkg, pkgLite); 10656 } catch (PackageManagerException e) { 10657 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10658 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10659 } 10660 } 10661 // Check for updated system application. 10662 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10663 if (onSd) { 10664 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10665 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10666 } 10667 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10668 } else { 10669 if (onSd) { 10670 // Install flag overrides everything. 10671 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10672 } 10673 // If current upgrade specifies particular preference 10674 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10675 // Application explicitly specified internal. 10676 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10677 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10678 // App explictly prefers external. Let policy decide 10679 } else { 10680 // Prefer previous location 10681 if (isExternal(pkg)) { 10682 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10683 } 10684 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10685 } 10686 } 10687 } else { 10688 // Invalid install. Return error code 10689 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10690 } 10691 } 10692 } 10693 // All the special cases have been taken care of. 10694 // Return result based on recommended install location. 10695 if (onSd) { 10696 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10697 } 10698 return pkgLite.recommendedInstallLocation; 10699 } 10700 10701 /* 10702 * Invoke remote method to get package information and install 10703 * location values. Override install location based on default 10704 * policy if needed and then create install arguments based 10705 * on the install location. 10706 */ 10707 public void handleStartCopy() throws RemoteException { 10708 int ret = PackageManager.INSTALL_SUCCEEDED; 10709 10710 // If we're already staged, we've firmly committed to an install location 10711 if (origin.staged) { 10712 if (origin.file != null) { 10713 installFlags |= PackageManager.INSTALL_INTERNAL; 10714 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10715 } else if (origin.cid != null) { 10716 installFlags |= PackageManager.INSTALL_EXTERNAL; 10717 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10718 } else { 10719 throw new IllegalStateException("Invalid stage location"); 10720 } 10721 } 10722 10723 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10724 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10725 PackageInfoLite pkgLite = null; 10726 10727 if (onInt && onSd) { 10728 // Check if both bits are set. 10729 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10730 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10731 } else { 10732 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10733 packageAbiOverride); 10734 10735 /* 10736 * If we have too little free space, try to free cache 10737 * before giving up. 10738 */ 10739 if (!origin.staged && pkgLite.recommendedInstallLocation 10740 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10741 // TODO: focus freeing disk space on the target device 10742 final StorageManager storage = StorageManager.from(mContext); 10743 final long lowThreshold = storage.getStorageLowBytes( 10744 Environment.getDataDirectory()); 10745 10746 final long sizeBytes = mContainerService.calculateInstalledSize( 10747 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10748 10749 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10750 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10751 installFlags, packageAbiOverride); 10752 } 10753 10754 /* 10755 * The cache free must have deleted the file we 10756 * downloaded to install. 10757 * 10758 * TODO: fix the "freeCache" call to not delete 10759 * the file we care about. 10760 */ 10761 if (pkgLite.recommendedInstallLocation 10762 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10763 pkgLite.recommendedInstallLocation 10764 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10765 } 10766 } 10767 } 10768 10769 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10770 int loc = pkgLite.recommendedInstallLocation; 10771 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10772 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10773 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10774 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10775 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10776 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10777 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10778 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10779 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10780 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10781 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10782 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10783 } else { 10784 // Override with defaults if needed. 10785 loc = installLocationPolicy(pkgLite); 10786 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10787 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10788 } else if (!onSd && !onInt) { 10789 // Override install location with flags 10790 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10791 // Set the flag to install on external media. 10792 installFlags |= PackageManager.INSTALL_EXTERNAL; 10793 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10794 } else { 10795 // Make sure the flag for installing on external 10796 // media is unset 10797 installFlags |= PackageManager.INSTALL_INTERNAL; 10798 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10799 } 10800 } 10801 } 10802 } 10803 10804 final InstallArgs args = createInstallArgs(this); 10805 mArgs = args; 10806 10807 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10808 // TODO: http://b/22976637 10809 // Apps installed for "all" users use the device owner to verify the app 10810 UserHandle verifierUser = getUser(); 10811 if (verifierUser == UserHandle.ALL) { 10812 verifierUser = UserHandle.SYSTEM; 10813 } 10814 10815 /* 10816 * Determine if we have any installed package verifiers. If we 10817 * do, then we'll defer to them to verify the packages. 10818 */ 10819 final int requiredUid = mRequiredVerifierPackage == null ? -1 10820 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10821 if (!origin.existing && requiredUid != -1 10822 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10823 final Intent verification = new Intent( 10824 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10825 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10826 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10827 PACKAGE_MIME_TYPE); 10828 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10829 10830 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10831 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10832 verifierUser.getIdentifier()); 10833 10834 if (DEBUG_VERIFY) { 10835 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10836 + verification.toString() + " with " + pkgLite.verifiers.length 10837 + " optional verifiers"); 10838 } 10839 10840 final int verificationId = mPendingVerificationToken++; 10841 10842 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10843 10844 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10845 installerPackageName); 10846 10847 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10848 installFlags); 10849 10850 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10851 pkgLite.packageName); 10852 10853 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10854 pkgLite.versionCode); 10855 10856 if (verificationParams != null) { 10857 if (verificationParams.getVerificationURI() != null) { 10858 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10859 verificationParams.getVerificationURI()); 10860 } 10861 if (verificationParams.getOriginatingURI() != null) { 10862 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10863 verificationParams.getOriginatingURI()); 10864 } 10865 if (verificationParams.getReferrer() != null) { 10866 verification.putExtra(Intent.EXTRA_REFERRER, 10867 verificationParams.getReferrer()); 10868 } 10869 if (verificationParams.getOriginatingUid() >= 0) { 10870 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10871 verificationParams.getOriginatingUid()); 10872 } 10873 if (verificationParams.getInstallerUid() >= 0) { 10874 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10875 verificationParams.getInstallerUid()); 10876 } 10877 } 10878 10879 final PackageVerificationState verificationState = new PackageVerificationState( 10880 requiredUid, args); 10881 10882 mPendingVerification.append(verificationId, verificationState); 10883 10884 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10885 receivers, verificationState); 10886 10887 /* 10888 * If any sufficient verifiers were listed in the package 10889 * manifest, attempt to ask them. 10890 */ 10891 if (sufficientVerifiers != null) { 10892 final int N = sufficientVerifiers.size(); 10893 if (N == 0) { 10894 Slog.i(TAG, "Additional verifiers required, but none installed."); 10895 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10896 } else { 10897 for (int i = 0; i < N; i++) { 10898 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10899 10900 final Intent sufficientIntent = new Intent(verification); 10901 sufficientIntent.setComponent(verifierComponent); 10902 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10903 } 10904 } 10905 } 10906 10907 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10908 mRequiredVerifierPackage, receivers); 10909 if (ret == PackageManager.INSTALL_SUCCEEDED 10910 && mRequiredVerifierPackage != null) { 10911 Trace.asyncTraceBegin( 10912 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10913 /* 10914 * Send the intent to the required verification agent, 10915 * but only start the verification timeout after the 10916 * target BroadcastReceivers have run. 10917 */ 10918 verification.setComponent(requiredVerifierComponent); 10919 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10920 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10921 new BroadcastReceiver() { 10922 @Override 10923 public void onReceive(Context context, Intent intent) { 10924 final Message msg = mHandler 10925 .obtainMessage(CHECK_PENDING_VERIFICATION); 10926 msg.arg1 = verificationId; 10927 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10928 } 10929 }, null, 0, null, null); 10930 10931 /* 10932 * We don't want the copy to proceed until verification 10933 * succeeds, so null out this field. 10934 */ 10935 mArgs = null; 10936 } 10937 } else { 10938 /* 10939 * No package verification is enabled, so immediately start 10940 * the remote call to initiate copy using temporary file. 10941 */ 10942 ret = args.copyApk(mContainerService, true); 10943 } 10944 } 10945 10946 mRet = ret; 10947 } 10948 10949 @Override 10950 void handleReturnCode() { 10951 // If mArgs is null, then MCS couldn't be reached. When it 10952 // reconnects, it will try again to install. At that point, this 10953 // will succeed. 10954 if (mArgs != null) { 10955 processPendingInstall(mArgs, mRet); 10956 } 10957 } 10958 10959 @Override 10960 void handleServiceError() { 10961 mArgs = createInstallArgs(this); 10962 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10963 } 10964 10965 public boolean isForwardLocked() { 10966 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10967 } 10968 } 10969 10970 /** 10971 * Used during creation of InstallArgs 10972 * 10973 * @param installFlags package installation flags 10974 * @return true if should be installed on external storage 10975 */ 10976 private static boolean installOnExternalAsec(int installFlags) { 10977 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10978 return false; 10979 } 10980 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10981 return true; 10982 } 10983 return false; 10984 } 10985 10986 /** 10987 * Used during creation of InstallArgs 10988 * 10989 * @param installFlags package installation flags 10990 * @return true if should be installed as forward locked 10991 */ 10992 private static boolean installForwardLocked(int installFlags) { 10993 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10994 } 10995 10996 private InstallArgs createInstallArgs(InstallParams params) { 10997 if (params.move != null) { 10998 return new MoveInstallArgs(params); 10999 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11000 return new AsecInstallArgs(params); 11001 } else { 11002 return new FileInstallArgs(params); 11003 } 11004 } 11005 11006 /** 11007 * Create args that describe an existing installed package. Typically used 11008 * when cleaning up old installs, or used as a move source. 11009 */ 11010 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11011 String resourcePath, String[] instructionSets) { 11012 final boolean isInAsec; 11013 if (installOnExternalAsec(installFlags)) { 11014 /* Apps on SD card are always in ASEC containers. */ 11015 isInAsec = true; 11016 } else if (installForwardLocked(installFlags) 11017 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11018 /* 11019 * Forward-locked apps are only in ASEC containers if they're the 11020 * new style 11021 */ 11022 isInAsec = true; 11023 } else { 11024 isInAsec = false; 11025 } 11026 11027 if (isInAsec) { 11028 return new AsecInstallArgs(codePath, instructionSets, 11029 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11030 } else { 11031 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11032 } 11033 } 11034 11035 static abstract class InstallArgs { 11036 /** @see InstallParams#origin */ 11037 final OriginInfo origin; 11038 /** @see InstallParams#move */ 11039 final MoveInfo move; 11040 11041 final IPackageInstallObserver2 observer; 11042 // Always refers to PackageManager flags only 11043 final int installFlags; 11044 final String installerPackageName; 11045 final String volumeUuid; 11046 final ManifestDigest manifestDigest; 11047 final UserHandle user; 11048 final String abiOverride; 11049 final String[] installGrantPermissions; 11050 /** If non-null, drop an async trace when the install completes */ 11051 final String traceMethod; 11052 final int traceCookie; 11053 11054 // The list of instruction sets supported by this app. This is currently 11055 // only used during the rmdex() phase to clean up resources. We can get rid of this 11056 // if we move dex files under the common app path. 11057 /* nullable */ String[] instructionSets; 11058 11059 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11060 int installFlags, String installerPackageName, String volumeUuid, 11061 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11062 String abiOverride, String[] installGrantPermissions, 11063 String traceMethod, int traceCookie) { 11064 this.origin = origin; 11065 this.move = move; 11066 this.installFlags = installFlags; 11067 this.observer = observer; 11068 this.installerPackageName = installerPackageName; 11069 this.volumeUuid = volumeUuid; 11070 this.manifestDigest = manifestDigest; 11071 this.user = user; 11072 this.instructionSets = instructionSets; 11073 this.abiOverride = abiOverride; 11074 this.installGrantPermissions = installGrantPermissions; 11075 this.traceMethod = traceMethod; 11076 this.traceCookie = traceCookie; 11077 } 11078 11079 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11080 abstract int doPreInstall(int status); 11081 11082 /** 11083 * Rename package into final resting place. All paths on the given 11084 * scanned package should be updated to reflect the rename. 11085 */ 11086 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11087 abstract int doPostInstall(int status, int uid); 11088 11089 /** @see PackageSettingBase#codePathString */ 11090 abstract String getCodePath(); 11091 /** @see PackageSettingBase#resourcePathString */ 11092 abstract String getResourcePath(); 11093 11094 // Need installer lock especially for dex file removal. 11095 abstract void cleanUpResourcesLI(); 11096 abstract boolean doPostDeleteLI(boolean delete); 11097 11098 /** 11099 * Called before the source arguments are copied. This is used mostly 11100 * for MoveParams when it needs to read the source file to put it in the 11101 * destination. 11102 */ 11103 int doPreCopy() { 11104 return PackageManager.INSTALL_SUCCEEDED; 11105 } 11106 11107 /** 11108 * Called after the source arguments are copied. This is used mostly for 11109 * MoveParams when it needs to read the source file to put it in the 11110 * destination. 11111 * 11112 * @return 11113 */ 11114 int doPostCopy(int uid) { 11115 return PackageManager.INSTALL_SUCCEEDED; 11116 } 11117 11118 protected boolean isFwdLocked() { 11119 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11120 } 11121 11122 protected boolean isExternalAsec() { 11123 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11124 } 11125 11126 UserHandle getUser() { 11127 return user; 11128 } 11129 } 11130 11131 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11132 if (!allCodePaths.isEmpty()) { 11133 if (instructionSets == null) { 11134 throw new IllegalStateException("instructionSet == null"); 11135 } 11136 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11137 for (String codePath : allCodePaths) { 11138 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11139 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11140 if (retCode < 0) { 11141 Slog.w(TAG, "Couldn't remove dex file for package: " 11142 + " at location " + codePath + ", retcode=" + retCode); 11143 // we don't consider this to be a failure of the core package deletion 11144 } 11145 } 11146 } 11147 } 11148 } 11149 11150 /** 11151 * Logic to handle installation of non-ASEC applications, including copying 11152 * and renaming logic. 11153 */ 11154 class FileInstallArgs extends InstallArgs { 11155 private File codeFile; 11156 private File resourceFile; 11157 11158 // Example topology: 11159 // /data/app/com.example/base.apk 11160 // /data/app/com.example/split_foo.apk 11161 // /data/app/com.example/lib/arm/libfoo.so 11162 // /data/app/com.example/lib/arm64/libfoo.so 11163 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11164 11165 /** New install */ 11166 FileInstallArgs(InstallParams params) { 11167 super(params.origin, params.move, params.observer, params.installFlags, 11168 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11169 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11170 params.grantedRuntimePermissions, 11171 params.traceMethod, params.traceCookie); 11172 if (isFwdLocked()) { 11173 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11174 } 11175 } 11176 11177 /** Existing install */ 11178 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11179 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11180 null, null, null, 0); 11181 this.codeFile = (codePath != null) ? new File(codePath) : null; 11182 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11183 } 11184 11185 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11186 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11187 try { 11188 return doCopyApk(imcs, temp); 11189 } finally { 11190 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11191 } 11192 } 11193 11194 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11195 if (origin.staged) { 11196 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11197 codeFile = origin.file; 11198 resourceFile = origin.file; 11199 return PackageManager.INSTALL_SUCCEEDED; 11200 } 11201 11202 try { 11203 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11204 codeFile = tempDir; 11205 resourceFile = tempDir; 11206 } catch (IOException e) { 11207 Slog.w(TAG, "Failed to create copy file: " + e); 11208 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11209 } 11210 11211 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11212 @Override 11213 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11214 if (!FileUtils.isValidExtFilename(name)) { 11215 throw new IllegalArgumentException("Invalid filename: " + name); 11216 } 11217 try { 11218 final File file = new File(codeFile, name); 11219 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11220 O_RDWR | O_CREAT, 0644); 11221 Os.chmod(file.getAbsolutePath(), 0644); 11222 return new ParcelFileDescriptor(fd); 11223 } catch (ErrnoException e) { 11224 throw new RemoteException("Failed to open: " + e.getMessage()); 11225 } 11226 } 11227 }; 11228 11229 int ret = PackageManager.INSTALL_SUCCEEDED; 11230 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11231 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11232 Slog.e(TAG, "Failed to copy package"); 11233 return ret; 11234 } 11235 11236 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11237 NativeLibraryHelper.Handle handle = null; 11238 try { 11239 handle = NativeLibraryHelper.Handle.create(codeFile); 11240 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11241 abiOverride); 11242 } catch (IOException e) { 11243 Slog.e(TAG, "Copying native libraries failed", e); 11244 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11245 } finally { 11246 IoUtils.closeQuietly(handle); 11247 } 11248 11249 return ret; 11250 } 11251 11252 int doPreInstall(int status) { 11253 if (status != PackageManager.INSTALL_SUCCEEDED) { 11254 cleanUp(); 11255 } 11256 return status; 11257 } 11258 11259 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11260 if (status != PackageManager.INSTALL_SUCCEEDED) { 11261 cleanUp(); 11262 return false; 11263 } 11264 11265 final File targetDir = codeFile.getParentFile(); 11266 final File beforeCodeFile = codeFile; 11267 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11268 11269 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11270 try { 11271 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11272 } catch (ErrnoException e) { 11273 Slog.w(TAG, "Failed to rename", e); 11274 return false; 11275 } 11276 11277 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11278 Slog.w(TAG, "Failed to restorecon"); 11279 return false; 11280 } 11281 11282 // Reflect the rename internally 11283 codeFile = afterCodeFile; 11284 resourceFile = afterCodeFile; 11285 11286 // Reflect the rename in scanned details 11287 pkg.codePath = afterCodeFile.getAbsolutePath(); 11288 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11289 pkg.baseCodePath); 11290 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11291 pkg.splitCodePaths); 11292 11293 // Reflect the rename in app info 11294 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11295 pkg.applicationInfo.setCodePath(pkg.codePath); 11296 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11297 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11298 pkg.applicationInfo.setResourcePath(pkg.codePath); 11299 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11300 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11301 11302 return true; 11303 } 11304 11305 int doPostInstall(int status, int uid) { 11306 if (status != PackageManager.INSTALL_SUCCEEDED) { 11307 cleanUp(); 11308 } 11309 return status; 11310 } 11311 11312 @Override 11313 String getCodePath() { 11314 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11315 } 11316 11317 @Override 11318 String getResourcePath() { 11319 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11320 } 11321 11322 private boolean cleanUp() { 11323 if (codeFile == null || !codeFile.exists()) { 11324 return false; 11325 } 11326 11327 if (codeFile.isDirectory()) { 11328 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11329 } else { 11330 codeFile.delete(); 11331 } 11332 11333 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11334 resourceFile.delete(); 11335 } 11336 11337 return true; 11338 } 11339 11340 void cleanUpResourcesLI() { 11341 // Try enumerating all code paths before deleting 11342 List<String> allCodePaths = Collections.EMPTY_LIST; 11343 if (codeFile != null && codeFile.exists()) { 11344 try { 11345 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11346 allCodePaths = pkg.getAllCodePaths(); 11347 } catch (PackageParserException e) { 11348 // Ignored; we tried our best 11349 } 11350 } 11351 11352 cleanUp(); 11353 removeDexFiles(allCodePaths, instructionSets); 11354 } 11355 11356 boolean doPostDeleteLI(boolean delete) { 11357 // XXX err, shouldn't we respect the delete flag? 11358 cleanUpResourcesLI(); 11359 return true; 11360 } 11361 } 11362 11363 private boolean isAsecExternal(String cid) { 11364 final String asecPath = PackageHelper.getSdFilesystem(cid); 11365 return !asecPath.startsWith(mAsecInternalPath); 11366 } 11367 11368 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11369 PackageManagerException { 11370 if (copyRet < 0) { 11371 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11372 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11373 throw new PackageManagerException(copyRet, message); 11374 } 11375 } 11376 } 11377 11378 /** 11379 * Extract the MountService "container ID" from the full code path of an 11380 * .apk. 11381 */ 11382 static String cidFromCodePath(String fullCodePath) { 11383 int eidx = fullCodePath.lastIndexOf("/"); 11384 String subStr1 = fullCodePath.substring(0, eidx); 11385 int sidx = subStr1.lastIndexOf("/"); 11386 return subStr1.substring(sidx+1, eidx); 11387 } 11388 11389 /** 11390 * Logic to handle installation of ASEC applications, including copying and 11391 * renaming logic. 11392 */ 11393 class AsecInstallArgs extends InstallArgs { 11394 static final String RES_FILE_NAME = "pkg.apk"; 11395 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11396 11397 String cid; 11398 String packagePath; 11399 String resourcePath; 11400 11401 /** New install */ 11402 AsecInstallArgs(InstallParams params) { 11403 super(params.origin, params.move, params.observer, params.installFlags, 11404 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11405 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11406 params.grantedRuntimePermissions, 11407 params.traceMethod, params.traceCookie); 11408 } 11409 11410 /** Existing install */ 11411 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11412 boolean isExternal, boolean isForwardLocked) { 11413 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11414 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11415 instructionSets, null, null, null, 0); 11416 // Hackily pretend we're still looking at a full code path 11417 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11418 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11419 } 11420 11421 // Extract cid from fullCodePath 11422 int eidx = fullCodePath.lastIndexOf("/"); 11423 String subStr1 = fullCodePath.substring(0, eidx); 11424 int sidx = subStr1.lastIndexOf("/"); 11425 cid = subStr1.substring(sidx+1, eidx); 11426 setMountPath(subStr1); 11427 } 11428 11429 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11430 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11431 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11432 instructionSets, null, null, null, 0); 11433 this.cid = cid; 11434 setMountPath(PackageHelper.getSdDir(cid)); 11435 } 11436 11437 void createCopyFile() { 11438 cid = mInstallerService.allocateExternalStageCidLegacy(); 11439 } 11440 11441 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11442 if (origin.staged) { 11443 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11444 cid = origin.cid; 11445 setMountPath(PackageHelper.getSdDir(cid)); 11446 return PackageManager.INSTALL_SUCCEEDED; 11447 } 11448 11449 if (temp) { 11450 createCopyFile(); 11451 } else { 11452 /* 11453 * Pre-emptively destroy the container since it's destroyed if 11454 * copying fails due to it existing anyway. 11455 */ 11456 PackageHelper.destroySdDir(cid); 11457 } 11458 11459 final String newMountPath = imcs.copyPackageToContainer( 11460 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11461 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11462 11463 if (newMountPath != null) { 11464 setMountPath(newMountPath); 11465 return PackageManager.INSTALL_SUCCEEDED; 11466 } else { 11467 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11468 } 11469 } 11470 11471 @Override 11472 String getCodePath() { 11473 return packagePath; 11474 } 11475 11476 @Override 11477 String getResourcePath() { 11478 return resourcePath; 11479 } 11480 11481 int doPreInstall(int status) { 11482 if (status != PackageManager.INSTALL_SUCCEEDED) { 11483 // Destroy container 11484 PackageHelper.destroySdDir(cid); 11485 } else { 11486 boolean mounted = PackageHelper.isContainerMounted(cid); 11487 if (!mounted) { 11488 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11489 Process.SYSTEM_UID); 11490 if (newMountPath != null) { 11491 setMountPath(newMountPath); 11492 } else { 11493 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11494 } 11495 } 11496 } 11497 return status; 11498 } 11499 11500 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11501 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11502 String newMountPath = null; 11503 if (PackageHelper.isContainerMounted(cid)) { 11504 // Unmount the container 11505 if (!PackageHelper.unMountSdDir(cid)) { 11506 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11507 return false; 11508 } 11509 } 11510 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11511 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11512 " which might be stale. Will try to clean up."); 11513 // Clean up the stale container and proceed to recreate. 11514 if (!PackageHelper.destroySdDir(newCacheId)) { 11515 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11516 return false; 11517 } 11518 // Successfully cleaned up stale container. Try to rename again. 11519 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11520 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11521 + " inspite of cleaning it up."); 11522 return false; 11523 } 11524 } 11525 if (!PackageHelper.isContainerMounted(newCacheId)) { 11526 Slog.w(TAG, "Mounting container " + newCacheId); 11527 newMountPath = PackageHelper.mountSdDir(newCacheId, 11528 getEncryptKey(), Process.SYSTEM_UID); 11529 } else { 11530 newMountPath = PackageHelper.getSdDir(newCacheId); 11531 } 11532 if (newMountPath == null) { 11533 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11534 return false; 11535 } 11536 Log.i(TAG, "Succesfully renamed " + cid + 11537 " to " + newCacheId + 11538 " at new path: " + newMountPath); 11539 cid = newCacheId; 11540 11541 final File beforeCodeFile = new File(packagePath); 11542 setMountPath(newMountPath); 11543 final File afterCodeFile = new File(packagePath); 11544 11545 // Reflect the rename in scanned details 11546 pkg.codePath = afterCodeFile.getAbsolutePath(); 11547 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11548 pkg.baseCodePath); 11549 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11550 pkg.splitCodePaths); 11551 11552 // Reflect the rename in app info 11553 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11554 pkg.applicationInfo.setCodePath(pkg.codePath); 11555 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11556 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11557 pkg.applicationInfo.setResourcePath(pkg.codePath); 11558 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11559 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11560 11561 return true; 11562 } 11563 11564 private void setMountPath(String mountPath) { 11565 final File mountFile = new File(mountPath); 11566 11567 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11568 if (monolithicFile.exists()) { 11569 packagePath = monolithicFile.getAbsolutePath(); 11570 if (isFwdLocked()) { 11571 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11572 } else { 11573 resourcePath = packagePath; 11574 } 11575 } else { 11576 packagePath = mountFile.getAbsolutePath(); 11577 resourcePath = packagePath; 11578 } 11579 } 11580 11581 int doPostInstall(int status, int uid) { 11582 if (status != PackageManager.INSTALL_SUCCEEDED) { 11583 cleanUp(); 11584 } else { 11585 final int groupOwner; 11586 final String protectedFile; 11587 if (isFwdLocked()) { 11588 groupOwner = UserHandle.getSharedAppGid(uid); 11589 protectedFile = RES_FILE_NAME; 11590 } else { 11591 groupOwner = -1; 11592 protectedFile = null; 11593 } 11594 11595 if (uid < Process.FIRST_APPLICATION_UID 11596 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11597 Slog.e(TAG, "Failed to finalize " + cid); 11598 PackageHelper.destroySdDir(cid); 11599 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11600 } 11601 11602 boolean mounted = PackageHelper.isContainerMounted(cid); 11603 if (!mounted) { 11604 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11605 } 11606 } 11607 return status; 11608 } 11609 11610 private void cleanUp() { 11611 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11612 11613 // Destroy secure container 11614 PackageHelper.destroySdDir(cid); 11615 } 11616 11617 private List<String> getAllCodePaths() { 11618 final File codeFile = new File(getCodePath()); 11619 if (codeFile != null && codeFile.exists()) { 11620 try { 11621 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11622 return pkg.getAllCodePaths(); 11623 } catch (PackageParserException e) { 11624 // Ignored; we tried our best 11625 } 11626 } 11627 return Collections.EMPTY_LIST; 11628 } 11629 11630 void cleanUpResourcesLI() { 11631 // Enumerate all code paths before deleting 11632 cleanUpResourcesLI(getAllCodePaths()); 11633 } 11634 11635 private void cleanUpResourcesLI(List<String> allCodePaths) { 11636 cleanUp(); 11637 removeDexFiles(allCodePaths, instructionSets); 11638 } 11639 11640 String getPackageName() { 11641 return getAsecPackageName(cid); 11642 } 11643 11644 boolean doPostDeleteLI(boolean delete) { 11645 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11646 final List<String> allCodePaths = getAllCodePaths(); 11647 boolean mounted = PackageHelper.isContainerMounted(cid); 11648 if (mounted) { 11649 // Unmount first 11650 if (PackageHelper.unMountSdDir(cid)) { 11651 mounted = false; 11652 } 11653 } 11654 if (!mounted && delete) { 11655 cleanUpResourcesLI(allCodePaths); 11656 } 11657 return !mounted; 11658 } 11659 11660 @Override 11661 int doPreCopy() { 11662 if (isFwdLocked()) { 11663 if (!PackageHelper.fixSdPermissions(cid, 11664 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11665 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11666 } 11667 } 11668 11669 return PackageManager.INSTALL_SUCCEEDED; 11670 } 11671 11672 @Override 11673 int doPostCopy(int uid) { 11674 if (isFwdLocked()) { 11675 if (uid < Process.FIRST_APPLICATION_UID 11676 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11677 RES_FILE_NAME)) { 11678 Slog.e(TAG, "Failed to finalize " + cid); 11679 PackageHelper.destroySdDir(cid); 11680 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11681 } 11682 } 11683 11684 return PackageManager.INSTALL_SUCCEEDED; 11685 } 11686 } 11687 11688 /** 11689 * Logic to handle movement of existing installed applications. 11690 */ 11691 class MoveInstallArgs extends InstallArgs { 11692 private File codeFile; 11693 private File resourceFile; 11694 11695 /** New install */ 11696 MoveInstallArgs(InstallParams params) { 11697 super(params.origin, params.move, params.observer, params.installFlags, 11698 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11699 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11700 params.grantedRuntimePermissions, 11701 params.traceMethod, params.traceCookie); 11702 } 11703 11704 int copyApk(IMediaContainerService imcs, boolean temp) { 11705 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11706 + move.fromUuid + " to " + move.toUuid); 11707 synchronized (mInstaller) { 11708 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11709 move.dataAppName, move.appId, move.seinfo) != 0) { 11710 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11711 } 11712 } 11713 11714 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11715 resourceFile = codeFile; 11716 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11717 11718 return PackageManager.INSTALL_SUCCEEDED; 11719 } 11720 11721 int doPreInstall(int status) { 11722 if (status != PackageManager.INSTALL_SUCCEEDED) { 11723 cleanUp(move.toUuid); 11724 } 11725 return status; 11726 } 11727 11728 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11729 if (status != PackageManager.INSTALL_SUCCEEDED) { 11730 cleanUp(move.toUuid); 11731 return false; 11732 } 11733 11734 // Reflect the move in app info 11735 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11736 pkg.applicationInfo.setCodePath(pkg.codePath); 11737 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11738 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11739 pkg.applicationInfo.setResourcePath(pkg.codePath); 11740 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11741 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11742 11743 return true; 11744 } 11745 11746 int doPostInstall(int status, int uid) { 11747 if (status == PackageManager.INSTALL_SUCCEEDED) { 11748 cleanUp(move.fromUuid); 11749 } else { 11750 cleanUp(move.toUuid); 11751 } 11752 return status; 11753 } 11754 11755 @Override 11756 String getCodePath() { 11757 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11758 } 11759 11760 @Override 11761 String getResourcePath() { 11762 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11763 } 11764 11765 private boolean cleanUp(String volumeUuid) { 11766 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11767 move.dataAppName); 11768 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11769 synchronized (mInstallLock) { 11770 // Clean up both app data and code 11771 removeDataDirsLI(volumeUuid, move.packageName); 11772 if (codeFile.isDirectory()) { 11773 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11774 } else { 11775 codeFile.delete(); 11776 } 11777 } 11778 return true; 11779 } 11780 11781 void cleanUpResourcesLI() { 11782 throw new UnsupportedOperationException(); 11783 } 11784 11785 boolean doPostDeleteLI(boolean delete) { 11786 throw new UnsupportedOperationException(); 11787 } 11788 } 11789 11790 static String getAsecPackageName(String packageCid) { 11791 int idx = packageCid.lastIndexOf("-"); 11792 if (idx == -1) { 11793 return packageCid; 11794 } 11795 return packageCid.substring(0, idx); 11796 } 11797 11798 // Utility method used to create code paths based on package name and available index. 11799 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11800 String idxStr = ""; 11801 int idx = 1; 11802 // Fall back to default value of idx=1 if prefix is not 11803 // part of oldCodePath 11804 if (oldCodePath != null) { 11805 String subStr = oldCodePath; 11806 // Drop the suffix right away 11807 if (suffix != null && subStr.endsWith(suffix)) { 11808 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11809 } 11810 // If oldCodePath already contains prefix find out the 11811 // ending index to either increment or decrement. 11812 int sidx = subStr.lastIndexOf(prefix); 11813 if (sidx != -1) { 11814 subStr = subStr.substring(sidx + prefix.length()); 11815 if (subStr != null) { 11816 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11817 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11818 } 11819 try { 11820 idx = Integer.parseInt(subStr); 11821 if (idx <= 1) { 11822 idx++; 11823 } else { 11824 idx--; 11825 } 11826 } catch(NumberFormatException e) { 11827 } 11828 } 11829 } 11830 } 11831 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11832 return prefix + idxStr; 11833 } 11834 11835 private File getNextCodePath(File targetDir, String packageName) { 11836 int suffix = 1; 11837 File result; 11838 do { 11839 result = new File(targetDir, packageName + "-" + suffix); 11840 suffix++; 11841 } while (result.exists()); 11842 return result; 11843 } 11844 11845 // Utility method that returns the relative package path with respect 11846 // to the installation directory. Like say for /data/data/com.test-1.apk 11847 // string com.test-1 is returned. 11848 static String deriveCodePathName(String codePath) { 11849 if (codePath == null) { 11850 return null; 11851 } 11852 final File codeFile = new File(codePath); 11853 final String name = codeFile.getName(); 11854 if (codeFile.isDirectory()) { 11855 return name; 11856 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11857 final int lastDot = name.lastIndexOf('.'); 11858 return name.substring(0, lastDot); 11859 } else { 11860 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11861 return null; 11862 } 11863 } 11864 11865 class PackageInstalledInfo { 11866 String name; 11867 int uid; 11868 // The set of users that originally had this package installed. 11869 int[] origUsers; 11870 // The set of users that now have this package installed. 11871 int[] newUsers; 11872 PackageParser.Package pkg; 11873 int returnCode; 11874 String returnMsg; 11875 PackageRemovedInfo removedInfo; 11876 11877 public void setError(int code, String msg) { 11878 returnCode = code; 11879 returnMsg = msg; 11880 Slog.w(TAG, msg); 11881 } 11882 11883 public void setError(String msg, PackageParserException e) { 11884 returnCode = e.error; 11885 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11886 Slog.w(TAG, msg, e); 11887 } 11888 11889 public void setError(String msg, PackageManagerException e) { 11890 returnCode = e.error; 11891 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11892 Slog.w(TAG, msg, e); 11893 } 11894 11895 // In some error cases we want to convey more info back to the observer 11896 String origPackage; 11897 String origPermission; 11898 } 11899 11900 /* 11901 * Install a non-existing package. 11902 */ 11903 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11904 UserHandle user, String installerPackageName, String volumeUuid, 11905 PackageInstalledInfo res) { 11906 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11907 11908 // Remember this for later, in case we need to rollback this install 11909 String pkgName = pkg.packageName; 11910 11911 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11912 // TODO: b/23350563 11913 final boolean dataDirExists = Environment 11914 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11915 11916 synchronized(mPackages) { 11917 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11918 // A package with the same name is already installed, though 11919 // it has been renamed to an older name. The package we 11920 // are trying to install should be installed as an update to 11921 // the existing one, but that has not been requested, so bail. 11922 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11923 + " without first uninstalling package running as " 11924 + mSettings.mRenamedPackages.get(pkgName)); 11925 return; 11926 } 11927 if (mPackages.containsKey(pkgName)) { 11928 // Don't allow installation over an existing package with the same name. 11929 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11930 + " without first uninstalling."); 11931 return; 11932 } 11933 } 11934 11935 try { 11936 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11937 System.currentTimeMillis(), user); 11938 11939 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11940 // delete the partially installed application. the data directory will have to be 11941 // restored if it was already existing 11942 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11943 // remove package from internal structures. Note that we want deletePackageX to 11944 // delete the package data and cache directories that it created in 11945 // scanPackageLocked, unless those directories existed before we even tried to 11946 // install. 11947 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11948 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11949 res.removedInfo, true); 11950 } 11951 11952 } catch (PackageManagerException e) { 11953 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11954 } 11955 11956 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11957 } 11958 11959 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11960 // Can't rotate keys during boot or if sharedUser. 11961 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11962 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11963 return false; 11964 } 11965 // app is using upgradeKeySets; make sure all are valid 11966 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11967 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11968 for (int i = 0; i < upgradeKeySets.length; i++) { 11969 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11970 Slog.wtf(TAG, "Package " 11971 + (oldPs.name != null ? oldPs.name : "<null>") 11972 + " contains upgrade-key-set reference to unknown key-set: " 11973 + upgradeKeySets[i] 11974 + " reverting to signatures check."); 11975 return false; 11976 } 11977 } 11978 return true; 11979 } 11980 11981 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11982 // Upgrade keysets are being used. Determine if new package has a superset of the 11983 // required keys. 11984 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11985 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11986 for (int i = 0; i < upgradeKeySets.length; i++) { 11987 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11988 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11989 return true; 11990 } 11991 } 11992 return false; 11993 } 11994 11995 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11996 UserHandle user, String installerPackageName, String volumeUuid, 11997 PackageInstalledInfo res) { 11998 final PackageParser.Package oldPackage; 11999 final String pkgName = pkg.packageName; 12000 final int[] allUsers; 12001 final boolean[] perUserInstalled; 12002 12003 // First find the old package info and check signatures 12004 synchronized(mPackages) { 12005 oldPackage = mPackages.get(pkgName); 12006 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12007 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12008 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12009 if(!checkUpgradeKeySetLP(ps, pkg)) { 12010 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12011 "New package not signed by keys specified by upgrade-keysets: " 12012 + pkgName); 12013 return; 12014 } 12015 } else { 12016 // default to original signature matching 12017 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12018 != PackageManager.SIGNATURE_MATCH) { 12019 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12020 "New package has a different signature: " + pkgName); 12021 return; 12022 } 12023 } 12024 12025 // In case of rollback, remember per-user/profile install state 12026 allUsers = sUserManager.getUserIds(); 12027 perUserInstalled = new boolean[allUsers.length]; 12028 for (int i = 0; i < allUsers.length; i++) { 12029 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12030 } 12031 } 12032 12033 boolean sysPkg = (isSystemApp(oldPackage)); 12034 if (sysPkg) { 12035 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12036 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12037 } else { 12038 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12039 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12040 } 12041 } 12042 12043 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12044 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12045 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12046 String volumeUuid, PackageInstalledInfo res) { 12047 String pkgName = deletedPackage.packageName; 12048 boolean deletedPkg = true; 12049 boolean updatedSettings = false; 12050 12051 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12052 + deletedPackage); 12053 long origUpdateTime; 12054 if (pkg.mExtras != null) { 12055 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12056 } else { 12057 origUpdateTime = 0; 12058 } 12059 12060 // First delete the existing package while retaining the data directory 12061 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12062 res.removedInfo, true)) { 12063 // If the existing package wasn't successfully deleted 12064 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12065 deletedPkg = false; 12066 } else { 12067 // Successfully deleted the old package; proceed with replace. 12068 12069 // If deleted package lived in a container, give users a chance to 12070 // relinquish resources before killing. 12071 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12072 if (DEBUG_INSTALL) { 12073 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12074 } 12075 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12076 final ArrayList<String> pkgList = new ArrayList<String>(1); 12077 pkgList.add(deletedPackage.applicationInfo.packageName); 12078 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12079 } 12080 12081 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12082 try { 12083 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12084 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12085 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12086 perUserInstalled, res, user); 12087 updatedSettings = true; 12088 } catch (PackageManagerException e) { 12089 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12090 } 12091 } 12092 12093 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12094 // remove package from internal structures. Note that we want deletePackageX to 12095 // delete the package data and cache directories that it created in 12096 // scanPackageLocked, unless those directories existed before we even tried to 12097 // install. 12098 if(updatedSettings) { 12099 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12100 deletePackageLI( 12101 pkgName, null, true, allUsers, perUserInstalled, 12102 PackageManager.DELETE_KEEP_DATA, 12103 res.removedInfo, true); 12104 } 12105 // Since we failed to install the new package we need to restore the old 12106 // package that we deleted. 12107 if (deletedPkg) { 12108 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12109 File restoreFile = new File(deletedPackage.codePath); 12110 // Parse old package 12111 boolean oldExternal = isExternal(deletedPackage); 12112 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12113 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12114 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12115 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12116 try { 12117 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12118 UserHandle.SYSTEM); 12119 } catch (PackageManagerException e) { 12120 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12121 + e.getMessage()); 12122 return; 12123 } 12124 // Restore of old package succeeded. Update permissions. 12125 // writer 12126 synchronized (mPackages) { 12127 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12128 UPDATE_PERMISSIONS_ALL); 12129 // can downgrade to reader 12130 mSettings.writeLPr(); 12131 } 12132 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12133 } 12134 } 12135 } 12136 12137 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12138 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12139 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12140 String volumeUuid, PackageInstalledInfo res) { 12141 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12142 + ", old=" + deletedPackage); 12143 boolean disabledSystem = false; 12144 boolean updatedSettings = false; 12145 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12146 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12147 != 0) { 12148 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12149 } 12150 String packageName = deletedPackage.packageName; 12151 if (packageName == null) { 12152 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12153 "Attempt to delete null packageName."); 12154 return; 12155 } 12156 PackageParser.Package oldPkg; 12157 PackageSetting oldPkgSetting; 12158 // reader 12159 synchronized (mPackages) { 12160 oldPkg = mPackages.get(packageName); 12161 oldPkgSetting = mSettings.mPackages.get(packageName); 12162 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12163 (oldPkgSetting == null)) { 12164 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12165 "Couldn't find package:" + packageName + " information"); 12166 return; 12167 } 12168 } 12169 12170 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12171 12172 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12173 res.removedInfo.removedPackage = packageName; 12174 // Remove existing system package 12175 removePackageLI(oldPkgSetting, true); 12176 // writer 12177 synchronized (mPackages) { 12178 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12179 if (!disabledSystem && deletedPackage != null) { 12180 // We didn't need to disable the .apk as a current system package, 12181 // which means we are replacing another update that is already 12182 // installed. We need to make sure to delete the older one's .apk. 12183 res.removedInfo.args = createInstallArgsForExisting(0, 12184 deletedPackage.applicationInfo.getCodePath(), 12185 deletedPackage.applicationInfo.getResourcePath(), 12186 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12187 } else { 12188 res.removedInfo.args = null; 12189 } 12190 } 12191 12192 // Successfully disabled the old package. Now proceed with re-installation 12193 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12194 12195 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12196 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12197 12198 PackageParser.Package newPackage = null; 12199 try { 12200 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12201 if (newPackage.mExtras != null) { 12202 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12203 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12204 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12205 12206 // is the update attempting to change shared user? that isn't going to work... 12207 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12208 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12209 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12210 + " to " + newPkgSetting.sharedUser); 12211 updatedSettings = true; 12212 } 12213 } 12214 12215 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12216 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12217 perUserInstalled, res, user); 12218 updatedSettings = true; 12219 } 12220 12221 } catch (PackageManagerException e) { 12222 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12223 } 12224 12225 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12226 // Re installation failed. Restore old information 12227 // Remove new pkg information 12228 if (newPackage != null) { 12229 removeInstalledPackageLI(newPackage, true); 12230 } 12231 // Add back the old system package 12232 try { 12233 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12234 } catch (PackageManagerException e) { 12235 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12236 } 12237 // Restore the old system information in Settings 12238 synchronized (mPackages) { 12239 if (disabledSystem) { 12240 mSettings.enableSystemPackageLPw(packageName); 12241 } 12242 if (updatedSettings) { 12243 mSettings.setInstallerPackageName(packageName, 12244 oldPkgSetting.installerPackageName); 12245 } 12246 mSettings.writeLPr(); 12247 } 12248 } 12249 } 12250 12251 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12252 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12253 UserHandle user) { 12254 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12255 12256 String pkgName = newPackage.packageName; 12257 synchronized (mPackages) { 12258 //write settings. the installStatus will be incomplete at this stage. 12259 //note that the new package setting would have already been 12260 //added to mPackages. It hasn't been persisted yet. 12261 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12262 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12263 mSettings.writeLPr(); 12264 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12265 } 12266 12267 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12268 synchronized (mPackages) { 12269 updatePermissionsLPw(newPackage.packageName, newPackage, 12270 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12271 ? UPDATE_PERMISSIONS_ALL : 0)); 12272 // For system-bundled packages, we assume that installing an upgraded version 12273 // of the package implies that the user actually wants to run that new code, 12274 // so we enable the package. 12275 PackageSetting ps = mSettings.mPackages.get(pkgName); 12276 if (ps != null) { 12277 if (isSystemApp(newPackage)) { 12278 // NB: implicit assumption that system package upgrades apply to all users 12279 if (DEBUG_INSTALL) { 12280 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12281 } 12282 if (res.origUsers != null) { 12283 for (int userHandle : res.origUsers) { 12284 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12285 userHandle, installerPackageName); 12286 } 12287 } 12288 // Also convey the prior install/uninstall state 12289 if (allUsers != null && perUserInstalled != null) { 12290 for (int i = 0; i < allUsers.length; i++) { 12291 if (DEBUG_INSTALL) { 12292 Slog.d(TAG, " user " + allUsers[i] 12293 + " => " + perUserInstalled[i]); 12294 } 12295 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12296 } 12297 // these install state changes will be persisted in the 12298 // upcoming call to mSettings.writeLPr(). 12299 } 12300 } 12301 // It's implied that when a user requests installation, they want the app to be 12302 // installed and enabled. 12303 int userId = user.getIdentifier(); 12304 if (userId != UserHandle.USER_ALL) { 12305 ps.setInstalled(true, userId); 12306 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12307 } 12308 } 12309 res.name = pkgName; 12310 res.uid = newPackage.applicationInfo.uid; 12311 res.pkg = newPackage; 12312 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12313 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12314 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12315 //to update install status 12316 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12317 mSettings.writeLPr(); 12318 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12319 } 12320 12321 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12322 } 12323 12324 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12325 try { 12326 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12327 installPackageLI(args, res); 12328 } finally { 12329 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12330 } 12331 } 12332 12333 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12334 final int installFlags = args.installFlags; 12335 final String installerPackageName = args.installerPackageName; 12336 final String volumeUuid = args.volumeUuid; 12337 final File tmpPackageFile = new File(args.getCodePath()); 12338 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12339 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12340 || (args.volumeUuid != null)); 12341 boolean replace = false; 12342 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12343 if (args.move != null) { 12344 // moving a complete application; perfom an initial scan on the new install location 12345 scanFlags |= SCAN_INITIAL; 12346 } 12347 // Result object to be returned 12348 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12349 12350 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12351 12352 // Retrieve PackageSettings and parse package 12353 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12354 | PackageParser.PARSE_ENFORCE_CODE 12355 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12356 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12357 PackageParser pp = new PackageParser(); 12358 pp.setSeparateProcesses(mSeparateProcesses); 12359 pp.setDisplayMetrics(mMetrics); 12360 12361 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12362 final PackageParser.Package pkg; 12363 try { 12364 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12365 } catch (PackageParserException e) { 12366 res.setError("Failed parse during installPackageLI", e); 12367 return; 12368 } finally { 12369 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12370 } 12371 12372 // Mark that we have an install time CPU ABI override. 12373 pkg.cpuAbiOverride = args.abiOverride; 12374 12375 String pkgName = res.name = pkg.packageName; 12376 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12377 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12378 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12379 return; 12380 } 12381 } 12382 12383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12384 try { 12385 pp.collectCertificates(pkg, parseFlags); 12386 pp.collectManifestDigest(pkg); 12387 } catch (PackageParserException e) { 12388 res.setError("Failed collect during installPackageLI", e); 12389 return; 12390 } finally { 12391 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12392 } 12393 12394 /* If the installer passed in a manifest digest, compare it now. */ 12395 if (args.manifestDigest != null) { 12396 if (DEBUG_INSTALL) { 12397 final String parsedManifest = pkg.manifestDigest == null ? "null" 12398 : pkg.manifestDigest.toString(); 12399 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12400 + parsedManifest); 12401 } 12402 12403 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12404 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12405 return; 12406 } 12407 } else if (DEBUG_INSTALL) { 12408 final String parsedManifest = pkg.manifestDigest == null 12409 ? "null" : pkg.manifestDigest.toString(); 12410 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12411 } 12412 12413 // Get rid of all references to package scan path via parser. 12414 pp = null; 12415 String oldCodePath = null; 12416 boolean systemApp = false; 12417 synchronized (mPackages) { 12418 // Check if installing already existing package 12419 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12420 String oldName = mSettings.mRenamedPackages.get(pkgName); 12421 if (pkg.mOriginalPackages != null 12422 && pkg.mOriginalPackages.contains(oldName) 12423 && mPackages.containsKey(oldName)) { 12424 // This package is derived from an original package, 12425 // and this device has been updating from that original 12426 // name. We must continue using the original name, so 12427 // rename the new package here. 12428 pkg.setPackageName(oldName); 12429 pkgName = pkg.packageName; 12430 replace = true; 12431 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12432 + oldName + " pkgName=" + pkgName); 12433 } else if (mPackages.containsKey(pkgName)) { 12434 // This package, under its official name, already exists 12435 // on the device; we should replace it. 12436 replace = true; 12437 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12438 } 12439 12440 // Prevent apps opting out from runtime permissions 12441 if (replace) { 12442 PackageParser.Package oldPackage = mPackages.get(pkgName); 12443 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12444 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12445 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12446 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12447 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12448 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12449 + " doesn't support runtime permissions but the old" 12450 + " target SDK " + oldTargetSdk + " does."); 12451 return; 12452 } 12453 } 12454 } 12455 12456 PackageSetting ps = mSettings.mPackages.get(pkgName); 12457 if (ps != null) { 12458 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12459 12460 // Quick sanity check that we're signed correctly if updating; 12461 // we'll check this again later when scanning, but we want to 12462 // bail early here before tripping over redefined permissions. 12463 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12464 if (!checkUpgradeKeySetLP(ps, pkg)) { 12465 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12466 + pkg.packageName + " upgrade keys do not match the " 12467 + "previously installed version"); 12468 return; 12469 } 12470 } else { 12471 try { 12472 verifySignaturesLP(ps, pkg); 12473 } catch (PackageManagerException e) { 12474 res.setError(e.error, e.getMessage()); 12475 return; 12476 } 12477 } 12478 12479 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12480 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12481 systemApp = (ps.pkg.applicationInfo.flags & 12482 ApplicationInfo.FLAG_SYSTEM) != 0; 12483 } 12484 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12485 } 12486 12487 // Check whether the newly-scanned package wants to define an already-defined perm 12488 int N = pkg.permissions.size(); 12489 for (int i = N-1; i >= 0; i--) { 12490 PackageParser.Permission perm = pkg.permissions.get(i); 12491 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12492 if (bp != null) { 12493 // If the defining package is signed with our cert, it's okay. This 12494 // also includes the "updating the same package" case, of course. 12495 // "updating same package" could also involve key-rotation. 12496 final boolean sigsOk; 12497 if (bp.sourcePackage.equals(pkg.packageName) 12498 && (bp.packageSetting instanceof PackageSetting) 12499 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12500 scanFlags))) { 12501 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12502 } else { 12503 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12504 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12505 } 12506 if (!sigsOk) { 12507 // If the owning package is the system itself, we log but allow 12508 // install to proceed; we fail the install on all other permission 12509 // redefinitions. 12510 if (!bp.sourcePackage.equals("android")) { 12511 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12512 + pkg.packageName + " attempting to redeclare permission " 12513 + perm.info.name + " already owned by " + bp.sourcePackage); 12514 res.origPermission = perm.info.name; 12515 res.origPackage = bp.sourcePackage; 12516 return; 12517 } else { 12518 Slog.w(TAG, "Package " + pkg.packageName 12519 + " attempting to redeclare system permission " 12520 + perm.info.name + "; ignoring new declaration"); 12521 pkg.permissions.remove(i); 12522 } 12523 } 12524 } 12525 } 12526 12527 } 12528 12529 if (systemApp && onExternal) { 12530 // Disable updates to system apps on sdcard 12531 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12532 "Cannot install updates to system apps on sdcard"); 12533 return; 12534 } 12535 12536 if (args.move != null) { 12537 // We did an in-place move, so dex is ready to roll 12538 scanFlags |= SCAN_NO_DEX; 12539 scanFlags |= SCAN_MOVE; 12540 12541 synchronized (mPackages) { 12542 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12543 if (ps == null) { 12544 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12545 "Missing settings for moved package " + pkgName); 12546 } 12547 12548 // We moved the entire application as-is, so bring over the 12549 // previously derived ABI information. 12550 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12551 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12552 } 12553 12554 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12555 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12556 scanFlags |= SCAN_NO_DEX; 12557 12558 try { 12559 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12560 true /* extract libs */); 12561 } catch (PackageManagerException pme) { 12562 Slog.e(TAG, "Error deriving application ABI", pme); 12563 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12564 return; 12565 } 12566 12567 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12569 12570 int result = mPackageDexOptimizer 12571 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12572 false /* defer */, false /* inclDependencies */, 12573 true /*bootComplete*/, false /*useJit*/); 12574 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12575 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12576 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12577 return; 12578 } 12579 } 12580 12581 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12582 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12583 return; 12584 } 12585 12586 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12587 12588 if (replace) { 12589 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12590 installerPackageName, volumeUuid, res); 12591 } else { 12592 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12593 args.user, installerPackageName, volumeUuid, res); 12594 } 12595 synchronized (mPackages) { 12596 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12597 if (ps != null) { 12598 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12599 } 12600 } 12601 } 12602 12603 private void startIntentFilterVerifications(int userId, boolean replacing, 12604 PackageParser.Package pkg) { 12605 if (mIntentFilterVerifierComponent == null) { 12606 Slog.w(TAG, "No IntentFilter verification will not be done as " 12607 + "there is no IntentFilterVerifier available!"); 12608 return; 12609 } 12610 12611 final int verifierUid = getPackageUid( 12612 mIntentFilterVerifierComponent.getPackageName(), 12613 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12614 12615 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12616 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12617 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12618 mHandler.sendMessage(msg); 12619 } 12620 12621 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12622 PackageParser.Package pkg) { 12623 int size = pkg.activities.size(); 12624 if (size == 0) { 12625 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12626 "No activity, so no need to verify any IntentFilter!"); 12627 return; 12628 } 12629 12630 final boolean hasDomainURLs = hasDomainURLs(pkg); 12631 if (!hasDomainURLs) { 12632 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12633 "No domain URLs, so no need to verify any IntentFilter!"); 12634 return; 12635 } 12636 12637 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12638 + " if any IntentFilter from the " + size 12639 + " Activities needs verification ..."); 12640 12641 int count = 0; 12642 final String packageName = pkg.packageName; 12643 12644 synchronized (mPackages) { 12645 // If this is a new install and we see that we've already run verification for this 12646 // package, we have nothing to do: it means the state was restored from backup. 12647 if (!replacing) { 12648 IntentFilterVerificationInfo ivi = 12649 mSettings.getIntentFilterVerificationLPr(packageName); 12650 if (ivi != null) { 12651 if (DEBUG_DOMAIN_VERIFICATION) { 12652 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12653 + ivi.getStatusString()); 12654 } 12655 return; 12656 } 12657 } 12658 12659 // If any filters need to be verified, then all need to be. 12660 boolean needToVerify = false; 12661 for (PackageParser.Activity a : pkg.activities) { 12662 for (ActivityIntentInfo filter : a.intents) { 12663 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12664 if (DEBUG_DOMAIN_VERIFICATION) { 12665 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12666 } 12667 needToVerify = true; 12668 break; 12669 } 12670 } 12671 } 12672 12673 if (needToVerify) { 12674 final int verificationId = mIntentFilterVerificationToken++; 12675 for (PackageParser.Activity a : pkg.activities) { 12676 for (ActivityIntentInfo filter : a.intents) { 12677 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12678 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12679 "Verification needed for IntentFilter:" + filter.toString()); 12680 mIntentFilterVerifier.addOneIntentFilterVerification( 12681 verifierUid, userId, verificationId, filter, packageName); 12682 count++; 12683 } 12684 } 12685 } 12686 } 12687 } 12688 12689 if (count > 0) { 12690 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12691 + " IntentFilter verification" + (count > 1 ? "s" : "") 12692 + " for userId:" + userId); 12693 mIntentFilterVerifier.startVerifications(userId); 12694 } else { 12695 if (DEBUG_DOMAIN_VERIFICATION) { 12696 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12697 } 12698 } 12699 } 12700 12701 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12702 final ComponentName cn = filter.activity.getComponentName(); 12703 final String packageName = cn.getPackageName(); 12704 12705 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12706 packageName); 12707 if (ivi == null) { 12708 return true; 12709 } 12710 int status = ivi.getStatus(); 12711 switch (status) { 12712 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12713 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12714 return true; 12715 12716 default: 12717 // Nothing to do 12718 return false; 12719 } 12720 } 12721 12722 private static boolean isMultiArch(PackageSetting ps) { 12723 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12724 } 12725 12726 private static boolean isMultiArch(ApplicationInfo info) { 12727 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12728 } 12729 12730 private static boolean isExternal(PackageParser.Package pkg) { 12731 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12732 } 12733 12734 private static boolean isExternal(PackageSetting ps) { 12735 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12736 } 12737 12738 private static boolean isExternal(ApplicationInfo info) { 12739 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12740 } 12741 12742 private static boolean isSystemApp(PackageParser.Package pkg) { 12743 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12744 } 12745 12746 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12747 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12748 } 12749 12750 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12751 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12752 } 12753 12754 private static boolean isSystemApp(PackageSetting ps) { 12755 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12756 } 12757 12758 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12759 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12760 } 12761 12762 private int packageFlagsToInstallFlags(PackageSetting ps) { 12763 int installFlags = 0; 12764 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12765 // This existing package was an external ASEC install when we have 12766 // the external flag without a UUID 12767 installFlags |= PackageManager.INSTALL_EXTERNAL; 12768 } 12769 if (ps.isForwardLocked()) { 12770 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12771 } 12772 return installFlags; 12773 } 12774 12775 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12776 if (isExternal(pkg)) { 12777 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12778 return mSettings.getExternalVersion(); 12779 } else { 12780 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12781 } 12782 } else { 12783 return mSettings.getInternalVersion(); 12784 } 12785 } 12786 12787 private void deleteTempPackageFiles() { 12788 final FilenameFilter filter = new FilenameFilter() { 12789 public boolean accept(File dir, String name) { 12790 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12791 } 12792 }; 12793 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12794 file.delete(); 12795 } 12796 } 12797 12798 @Override 12799 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12800 int flags) { 12801 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12802 flags); 12803 } 12804 12805 @Override 12806 public void deletePackage(final String packageName, 12807 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12808 mContext.enforceCallingOrSelfPermission( 12809 android.Manifest.permission.DELETE_PACKAGES, null); 12810 Preconditions.checkNotNull(packageName); 12811 Preconditions.checkNotNull(observer); 12812 final int uid = Binder.getCallingUid(); 12813 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 12814 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 12815 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 12816 mContext.enforceCallingPermission( 12817 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12818 "deletePackage for user " + userId); 12819 } 12820 12821 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12822 try { 12823 observer.onPackageDeleted(packageName, 12824 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12825 } catch (RemoteException re) { 12826 } 12827 return; 12828 } 12829 12830 for (int currentUserId : users) { 12831 if (getBlockUninstallForUser(packageName, currentUserId)) { 12832 try { 12833 observer.onPackageDeleted(packageName, 12834 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 12835 } catch (RemoteException re) { 12836 } 12837 return; 12838 } 12839 } 12840 12841 if (DEBUG_REMOVE) { 12842 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12843 } 12844 // Queue up an async operation since the package deletion may take a little while. 12845 mHandler.post(new Runnable() { 12846 public void run() { 12847 mHandler.removeCallbacks(this); 12848 final int returnCode = deletePackageX(packageName, userId, flags); 12849 try { 12850 observer.onPackageDeleted(packageName, returnCode, null); 12851 } catch (RemoteException e) { 12852 Log.i(TAG, "Observer no longer exists."); 12853 } //end catch 12854 } //end run 12855 }); 12856 } 12857 12858 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12859 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12860 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12861 try { 12862 if (dpm != null) { 12863 if (dpm.isDeviceOwner(packageName)) { 12864 return true; 12865 } 12866 int[] users; 12867 if (userId == UserHandle.USER_ALL) { 12868 users = sUserManager.getUserIds(); 12869 } else { 12870 users = new int[]{userId}; 12871 } 12872 for (int i = 0; i < users.length; ++i) { 12873 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12874 return true; 12875 } 12876 } 12877 } 12878 } catch (RemoteException e) { 12879 } 12880 return false; 12881 } 12882 12883 /** 12884 * This method is an internal method that could be get invoked either 12885 * to delete an installed package or to clean up a failed installation. 12886 * After deleting an installed package, a broadcast is sent to notify any 12887 * listeners that the package has been installed. For cleaning up a failed 12888 * installation, the broadcast is not necessary since the package's 12889 * installation wouldn't have sent the initial broadcast either 12890 * The key steps in deleting a package are 12891 * deleting the package information in internal structures like mPackages, 12892 * deleting the packages base directories through installd 12893 * updating mSettings to reflect current status 12894 * persisting settings for later use 12895 * sending a broadcast if necessary 12896 */ 12897 private int deletePackageX(String packageName, int userId, int flags) { 12898 final PackageRemovedInfo info = new PackageRemovedInfo(); 12899 final boolean res; 12900 12901 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12902 ? UserHandle.ALL : new UserHandle(userId); 12903 12904 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12905 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12906 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12907 } 12908 12909 boolean removedForAllUsers = false; 12910 boolean systemUpdate = false; 12911 12912 // for the uninstall-updates case and restricted profiles, remember the per- 12913 // userhandle installed state 12914 int[] allUsers; 12915 boolean[] perUserInstalled; 12916 synchronized (mPackages) { 12917 PackageSetting ps = mSettings.mPackages.get(packageName); 12918 allUsers = sUserManager.getUserIds(); 12919 perUserInstalled = new boolean[allUsers.length]; 12920 for (int i = 0; i < allUsers.length; i++) { 12921 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12922 } 12923 } 12924 12925 synchronized (mInstallLock) { 12926 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12927 res = deletePackageLI(packageName, removeForUser, 12928 true, allUsers, perUserInstalled, 12929 flags | REMOVE_CHATTY, info, true); 12930 systemUpdate = info.isRemovedPackageSystemUpdate; 12931 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12932 removedForAllUsers = true; 12933 } 12934 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12935 + " removedForAllUsers=" + removedForAllUsers); 12936 } 12937 12938 if (res) { 12939 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12940 12941 // If the removed package was a system update, the old system package 12942 // was re-enabled; we need to broadcast this information 12943 if (systemUpdate) { 12944 Bundle extras = new Bundle(1); 12945 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12946 ? info.removedAppId : info.uid); 12947 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12948 12949 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12950 extras, null, null, null); 12951 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12952 extras, null, null, null); 12953 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12954 null, packageName, null, null); 12955 } 12956 } 12957 // Force a gc here. 12958 Runtime.getRuntime().gc(); 12959 // Delete the resources here after sending the broadcast to let 12960 // other processes clean up before deleting resources. 12961 if (info.args != null) { 12962 synchronized (mInstallLock) { 12963 info.args.doPostDeleteLI(true); 12964 } 12965 } 12966 12967 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12968 } 12969 12970 class PackageRemovedInfo { 12971 String removedPackage; 12972 int uid = -1; 12973 int removedAppId = -1; 12974 int[] removedUsers = null; 12975 boolean isRemovedPackageSystemUpdate = false; 12976 // Clean up resources deleted packages. 12977 InstallArgs args = null; 12978 12979 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12980 Bundle extras = new Bundle(1); 12981 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12982 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12983 if (replacing) { 12984 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12985 } 12986 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12987 if (removedPackage != null) { 12988 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12989 extras, null, null, removedUsers); 12990 if (fullRemove && !replacing) { 12991 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12992 extras, null, null, removedUsers); 12993 } 12994 } 12995 if (removedAppId >= 0) { 12996 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12997 removedUsers); 12998 } 12999 } 13000 } 13001 13002 /* 13003 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13004 * flag is not set, the data directory is removed as well. 13005 * make sure this flag is set for partially installed apps. If not its meaningless to 13006 * delete a partially installed application. 13007 */ 13008 private void removePackageDataLI(PackageSetting ps, 13009 int[] allUserHandles, boolean[] perUserInstalled, 13010 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13011 String packageName = ps.name; 13012 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13013 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13014 // Retrieve object to delete permissions for shared user later on 13015 final PackageSetting deletedPs; 13016 // reader 13017 synchronized (mPackages) { 13018 deletedPs = mSettings.mPackages.get(packageName); 13019 if (outInfo != null) { 13020 outInfo.removedPackage = packageName; 13021 outInfo.removedUsers = deletedPs != null 13022 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13023 : null; 13024 } 13025 } 13026 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13027 removeDataDirsLI(ps.volumeUuid, packageName); 13028 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13029 } 13030 // writer 13031 synchronized (mPackages) { 13032 if (deletedPs != null) { 13033 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13034 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13035 clearDefaultBrowserIfNeeded(packageName); 13036 if (outInfo != null) { 13037 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13038 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13039 } 13040 updatePermissionsLPw(deletedPs.name, null, 0); 13041 if (deletedPs.sharedUser != null) { 13042 // Remove permissions associated with package. Since runtime 13043 // permissions are per user we have to kill the removed package 13044 // or packages running under the shared user of the removed 13045 // package if revoking the permissions requested only by the removed 13046 // package is successful and this causes a change in gids. 13047 for (int userId : UserManagerService.getInstance().getUserIds()) { 13048 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13049 userId); 13050 if (userIdToKill == UserHandle.USER_ALL 13051 || userIdToKill >= UserHandle.USER_SYSTEM) { 13052 // If gids changed for this user, kill all affected packages. 13053 mHandler.post(new Runnable() { 13054 @Override 13055 public void run() { 13056 // This has to happen with no lock held. 13057 killApplication(deletedPs.name, deletedPs.appId, 13058 KILL_APP_REASON_GIDS_CHANGED); 13059 } 13060 }); 13061 break; 13062 } 13063 } 13064 } 13065 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13066 } 13067 // make sure to preserve per-user disabled state if this removal was just 13068 // a downgrade of a system app to the factory package 13069 if (allUserHandles != null && perUserInstalled != null) { 13070 if (DEBUG_REMOVE) { 13071 Slog.d(TAG, "Propagating install state across downgrade"); 13072 } 13073 for (int i = 0; i < allUserHandles.length; i++) { 13074 if (DEBUG_REMOVE) { 13075 Slog.d(TAG, " user " + allUserHandles[i] 13076 + " => " + perUserInstalled[i]); 13077 } 13078 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13079 } 13080 } 13081 } 13082 // can downgrade to reader 13083 if (writeSettings) { 13084 // Save settings now 13085 mSettings.writeLPr(); 13086 } 13087 } 13088 if (outInfo != null) { 13089 // A user ID was deleted here. Go through all users and remove it 13090 // from KeyStore. 13091 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13092 } 13093 } 13094 13095 static boolean locationIsPrivileged(File path) { 13096 try { 13097 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13098 .getCanonicalPath(); 13099 return path.getCanonicalPath().startsWith(privilegedAppDir); 13100 } catch (IOException e) { 13101 Slog.e(TAG, "Unable to access code path " + path); 13102 } 13103 return false; 13104 } 13105 13106 /* 13107 * Tries to delete system package. 13108 */ 13109 private boolean deleteSystemPackageLI(PackageSetting newPs, 13110 int[] allUserHandles, boolean[] perUserInstalled, 13111 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13112 final boolean applyUserRestrictions 13113 = (allUserHandles != null) && (perUserInstalled != null); 13114 PackageSetting disabledPs = null; 13115 // Confirm if the system package has been updated 13116 // An updated system app can be deleted. This will also have to restore 13117 // the system pkg from system partition 13118 // reader 13119 synchronized (mPackages) { 13120 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13121 } 13122 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13123 + " disabledPs=" + disabledPs); 13124 if (disabledPs == null) { 13125 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13126 return false; 13127 } else if (DEBUG_REMOVE) { 13128 Slog.d(TAG, "Deleting system pkg from data partition"); 13129 } 13130 if (DEBUG_REMOVE) { 13131 if (applyUserRestrictions) { 13132 Slog.d(TAG, "Remembering install states:"); 13133 for (int i = 0; i < allUserHandles.length; i++) { 13134 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13135 } 13136 } 13137 } 13138 // Delete the updated package 13139 outInfo.isRemovedPackageSystemUpdate = true; 13140 if (disabledPs.versionCode < newPs.versionCode) { 13141 // Delete data for downgrades 13142 flags &= ~PackageManager.DELETE_KEEP_DATA; 13143 } else { 13144 // Preserve data by setting flag 13145 flags |= PackageManager.DELETE_KEEP_DATA; 13146 } 13147 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13148 allUserHandles, perUserInstalled, outInfo, writeSettings); 13149 if (!ret) { 13150 return false; 13151 } 13152 // writer 13153 synchronized (mPackages) { 13154 // Reinstate the old system package 13155 mSettings.enableSystemPackageLPw(newPs.name); 13156 // Remove any native libraries from the upgraded package. 13157 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13158 } 13159 // Install the system package 13160 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13161 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13162 if (locationIsPrivileged(disabledPs.codePath)) { 13163 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13164 } 13165 13166 final PackageParser.Package newPkg; 13167 try { 13168 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, 13169 UserHandle.SYSTEM); 13170 } catch (PackageManagerException e) { 13171 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13172 return false; 13173 } 13174 13175 // writer 13176 synchronized (mPackages) { 13177 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13178 13179 // Propagate the permissions state as we do not want to drop on the floor 13180 // runtime permissions. The update permissions method below will take 13181 // care of removing obsolete permissions and grant install permissions. 13182 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13183 updatePermissionsLPw(newPkg.packageName, newPkg, 13184 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13185 13186 if (applyUserRestrictions) { 13187 if (DEBUG_REMOVE) { 13188 Slog.d(TAG, "Propagating install state across reinstall"); 13189 } 13190 for (int i = 0; i < allUserHandles.length; i++) { 13191 if (DEBUG_REMOVE) { 13192 Slog.d(TAG, " user " + allUserHandles[i] 13193 + " => " + perUserInstalled[i]); 13194 } 13195 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13196 13197 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13198 } 13199 // Regardless of writeSettings we need to ensure that this restriction 13200 // state propagation is persisted 13201 mSettings.writeAllUsersPackageRestrictionsLPr(); 13202 } 13203 // can downgrade to reader here 13204 if (writeSettings) { 13205 mSettings.writeLPr(); 13206 } 13207 } 13208 return true; 13209 } 13210 13211 private boolean deleteInstalledPackageLI(PackageSetting ps, 13212 boolean deleteCodeAndResources, int flags, 13213 int[] allUserHandles, boolean[] perUserInstalled, 13214 PackageRemovedInfo outInfo, boolean writeSettings) { 13215 if (outInfo != null) { 13216 outInfo.uid = ps.appId; 13217 } 13218 13219 // Delete package data from internal structures and also remove data if flag is set 13220 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13221 13222 // Delete application code and resources 13223 if (deleteCodeAndResources && (outInfo != null)) { 13224 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13225 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13226 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13227 } 13228 return true; 13229 } 13230 13231 @Override 13232 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13233 int userId) { 13234 mContext.enforceCallingOrSelfPermission( 13235 android.Manifest.permission.DELETE_PACKAGES, null); 13236 synchronized (mPackages) { 13237 PackageSetting ps = mSettings.mPackages.get(packageName); 13238 if (ps == null) { 13239 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13240 return false; 13241 } 13242 if (!ps.getInstalled(userId)) { 13243 // Can't block uninstall for an app that is not installed or enabled. 13244 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13245 return false; 13246 } 13247 ps.setBlockUninstall(blockUninstall, userId); 13248 mSettings.writePackageRestrictionsLPr(userId); 13249 } 13250 return true; 13251 } 13252 13253 @Override 13254 public boolean getBlockUninstallForUser(String packageName, int userId) { 13255 synchronized (mPackages) { 13256 PackageSetting ps = mSettings.mPackages.get(packageName); 13257 if (ps == null) { 13258 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13259 return false; 13260 } 13261 return ps.getBlockUninstall(userId); 13262 } 13263 } 13264 13265 /* 13266 * This method handles package deletion in general 13267 */ 13268 private boolean deletePackageLI(String packageName, UserHandle user, 13269 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13270 int flags, PackageRemovedInfo outInfo, 13271 boolean writeSettings) { 13272 if (packageName == null) { 13273 Slog.w(TAG, "Attempt to delete null packageName."); 13274 return false; 13275 } 13276 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13277 PackageSetting ps; 13278 boolean dataOnly = false; 13279 int removeUser = -1; 13280 int appId = -1; 13281 synchronized (mPackages) { 13282 ps = mSettings.mPackages.get(packageName); 13283 if (ps == null) { 13284 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13285 return false; 13286 } 13287 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13288 && user.getIdentifier() != UserHandle.USER_ALL) { 13289 // The caller is asking that the package only be deleted for a single 13290 // user. To do this, we just mark its uninstalled state and delete 13291 // its data. If this is a system app, we only allow this to happen if 13292 // they have set the special DELETE_SYSTEM_APP which requests different 13293 // semantics than normal for uninstalling system apps. 13294 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13295 final int userId = user.getIdentifier(); 13296 ps.setUserState(userId, 13297 COMPONENT_ENABLED_STATE_DEFAULT, 13298 false, //installed 13299 true, //stopped 13300 true, //notLaunched 13301 false, //hidden 13302 null, null, null, 13303 false, // blockUninstall 13304 ps.readUserState(userId).domainVerificationStatus, 0); 13305 if (!isSystemApp(ps)) { 13306 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13307 // Other user still have this package installed, so all 13308 // we need to do is clear this user's data and save that 13309 // it is uninstalled. 13310 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13311 removeUser = user.getIdentifier(); 13312 appId = ps.appId; 13313 scheduleWritePackageRestrictionsLocked(removeUser); 13314 } else { 13315 // We need to set it back to 'installed' so the uninstall 13316 // broadcasts will be sent correctly. 13317 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13318 ps.setInstalled(true, user.getIdentifier()); 13319 } 13320 } else { 13321 // This is a system app, so we assume that the 13322 // other users still have this package installed, so all 13323 // we need to do is clear this user's data and save that 13324 // it is uninstalled. 13325 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13326 removeUser = user.getIdentifier(); 13327 appId = ps.appId; 13328 scheduleWritePackageRestrictionsLocked(removeUser); 13329 } 13330 } 13331 } 13332 13333 if (removeUser >= 0) { 13334 // From above, we determined that we are deleting this only 13335 // for a single user. Continue the work here. 13336 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13337 if (outInfo != null) { 13338 outInfo.removedPackage = packageName; 13339 outInfo.removedAppId = appId; 13340 outInfo.removedUsers = new int[] {removeUser}; 13341 } 13342 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13343 removeKeystoreDataIfNeeded(removeUser, appId); 13344 schedulePackageCleaning(packageName, removeUser, false); 13345 synchronized (mPackages) { 13346 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13347 scheduleWritePackageRestrictionsLocked(removeUser); 13348 } 13349 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13350 } 13351 return true; 13352 } 13353 13354 if (dataOnly) { 13355 // Delete application data first 13356 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13357 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13358 return true; 13359 } 13360 13361 boolean ret = false; 13362 if (isSystemApp(ps)) { 13363 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13364 // When an updated system application is deleted we delete the existing resources as well and 13365 // fall back to existing code in system partition 13366 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13367 flags, outInfo, writeSettings); 13368 } else { 13369 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13370 // Kill application pre-emptively especially for apps on sd. 13371 killApplication(packageName, ps.appId, "uninstall pkg"); 13372 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13373 allUserHandles, perUserInstalled, 13374 outInfo, writeSettings); 13375 } 13376 13377 return ret; 13378 } 13379 13380 private final class ClearStorageConnection implements ServiceConnection { 13381 IMediaContainerService mContainerService; 13382 13383 @Override 13384 public void onServiceConnected(ComponentName name, IBinder service) { 13385 synchronized (this) { 13386 mContainerService = IMediaContainerService.Stub.asInterface(service); 13387 notifyAll(); 13388 } 13389 } 13390 13391 @Override 13392 public void onServiceDisconnected(ComponentName name) { 13393 } 13394 } 13395 13396 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13397 final boolean mounted; 13398 if (Environment.isExternalStorageEmulated()) { 13399 mounted = true; 13400 } else { 13401 final String status = Environment.getExternalStorageState(); 13402 13403 mounted = status.equals(Environment.MEDIA_MOUNTED) 13404 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13405 } 13406 13407 if (!mounted) { 13408 return; 13409 } 13410 13411 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13412 int[] users; 13413 if (userId == UserHandle.USER_ALL) { 13414 users = sUserManager.getUserIds(); 13415 } else { 13416 users = new int[] { userId }; 13417 } 13418 final ClearStorageConnection conn = new ClearStorageConnection(); 13419 if (mContext.bindServiceAsUser( 13420 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13421 try { 13422 for (int curUser : users) { 13423 long timeout = SystemClock.uptimeMillis() + 5000; 13424 synchronized (conn) { 13425 long now = SystemClock.uptimeMillis(); 13426 while (conn.mContainerService == null && now < timeout) { 13427 try { 13428 conn.wait(timeout - now); 13429 } catch (InterruptedException e) { 13430 } 13431 } 13432 } 13433 if (conn.mContainerService == null) { 13434 return; 13435 } 13436 13437 final UserEnvironment userEnv = new UserEnvironment(curUser); 13438 clearDirectory(conn.mContainerService, 13439 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13440 if (allData) { 13441 clearDirectory(conn.mContainerService, 13442 userEnv.buildExternalStorageAppDataDirs(packageName)); 13443 clearDirectory(conn.mContainerService, 13444 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13445 } 13446 } 13447 } finally { 13448 mContext.unbindService(conn); 13449 } 13450 } 13451 } 13452 13453 @Override 13454 public void clearApplicationUserData(final String packageName, 13455 final IPackageDataObserver observer, final int userId) { 13456 mContext.enforceCallingOrSelfPermission( 13457 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13458 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13459 // Queue up an async operation since the package deletion may take a little while. 13460 mHandler.post(new Runnable() { 13461 public void run() { 13462 mHandler.removeCallbacks(this); 13463 final boolean succeeded; 13464 synchronized (mInstallLock) { 13465 succeeded = clearApplicationUserDataLI(packageName, userId); 13466 } 13467 clearExternalStorageDataSync(packageName, userId, true); 13468 if (succeeded) { 13469 // invoke DeviceStorageMonitor's update method to clear any notifications 13470 DeviceStorageMonitorInternal 13471 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13472 if (dsm != null) { 13473 dsm.checkMemory(); 13474 } 13475 } 13476 if(observer != null) { 13477 try { 13478 observer.onRemoveCompleted(packageName, succeeded); 13479 } catch (RemoteException e) { 13480 Log.i(TAG, "Observer no longer exists."); 13481 } 13482 } //end if observer 13483 } //end run 13484 }); 13485 } 13486 13487 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13488 if (packageName == null) { 13489 Slog.w(TAG, "Attempt to delete null packageName."); 13490 return false; 13491 } 13492 13493 // Try finding details about the requested package 13494 PackageParser.Package pkg; 13495 synchronized (mPackages) { 13496 pkg = mPackages.get(packageName); 13497 if (pkg == null) { 13498 final PackageSetting ps = mSettings.mPackages.get(packageName); 13499 if (ps != null) { 13500 pkg = ps.pkg; 13501 } 13502 } 13503 13504 if (pkg == null) { 13505 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13506 return false; 13507 } 13508 13509 PackageSetting ps = (PackageSetting) pkg.mExtras; 13510 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13511 } 13512 13513 // Always delete data directories for package, even if we found no other 13514 // record of app. This helps users recover from UID mismatches without 13515 // resorting to a full data wipe. 13516 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13517 if (retCode < 0) { 13518 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13519 return false; 13520 } 13521 13522 final int appId = pkg.applicationInfo.uid; 13523 removeKeystoreDataIfNeeded(userId, appId); 13524 13525 // Create a native library symlink only if we have native libraries 13526 // and if the native libraries are 32 bit libraries. We do not provide 13527 // this symlink for 64 bit libraries. 13528 if (pkg.applicationInfo.primaryCpuAbi != null && 13529 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13530 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13531 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13532 nativeLibPath, userId) < 0) { 13533 Slog.w(TAG, "Failed linking native library dir"); 13534 return false; 13535 } 13536 } 13537 13538 return true; 13539 } 13540 13541 /** 13542 * Reverts user permission state changes (permissions and flags) in 13543 * all packages for a given user. 13544 * 13545 * @param userId The device user for which to do a reset. 13546 */ 13547 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13548 final int packageCount = mPackages.size(); 13549 for (int i = 0; i < packageCount; i++) { 13550 PackageParser.Package pkg = mPackages.valueAt(i); 13551 PackageSetting ps = (PackageSetting) pkg.mExtras; 13552 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13553 } 13554 } 13555 13556 /** 13557 * Reverts user permission state changes (permissions and flags). 13558 * 13559 * @param ps The package for which to reset. 13560 * @param userId The device user for which to do a reset. 13561 */ 13562 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13563 final PackageSetting ps, final int userId) { 13564 if (ps.pkg == null) { 13565 return; 13566 } 13567 13568 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13569 | FLAG_PERMISSION_USER_FIXED 13570 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13571 13572 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13573 | FLAG_PERMISSION_POLICY_FIXED; 13574 13575 boolean writeInstallPermissions = false; 13576 boolean writeRuntimePermissions = false; 13577 13578 final int permissionCount = ps.pkg.requestedPermissions.size(); 13579 for (int i = 0; i < permissionCount; i++) { 13580 String permission = ps.pkg.requestedPermissions.get(i); 13581 13582 BasePermission bp = mSettings.mPermissions.get(permission); 13583 if (bp == null) { 13584 continue; 13585 } 13586 13587 // If shared user we just reset the state to which only this app contributed. 13588 if (ps.sharedUser != null) { 13589 boolean used = false; 13590 final int packageCount = ps.sharedUser.packages.size(); 13591 for (int j = 0; j < packageCount; j++) { 13592 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13593 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13594 && pkg.pkg.requestedPermissions.contains(permission)) { 13595 used = true; 13596 break; 13597 } 13598 } 13599 if (used) { 13600 continue; 13601 } 13602 } 13603 13604 PermissionsState permissionsState = ps.getPermissionsState(); 13605 13606 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13607 13608 // Always clear the user settable flags. 13609 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13610 bp.name) != null; 13611 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13612 if (hasInstallState) { 13613 writeInstallPermissions = true; 13614 } else { 13615 writeRuntimePermissions = true; 13616 } 13617 } 13618 13619 // Below is only runtime permission handling. 13620 if (!bp.isRuntime()) { 13621 continue; 13622 } 13623 13624 // Never clobber system or policy. 13625 if ((oldFlags & policyOrSystemFlags) != 0) { 13626 continue; 13627 } 13628 13629 // If this permission was granted by default, make sure it is. 13630 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13631 if (permissionsState.grantRuntimePermission(bp, userId) 13632 != PERMISSION_OPERATION_FAILURE) { 13633 writeRuntimePermissions = true; 13634 } 13635 } else { 13636 // Otherwise, reset the permission. 13637 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13638 switch (revokeResult) { 13639 case PERMISSION_OPERATION_SUCCESS: { 13640 writeRuntimePermissions = true; 13641 } break; 13642 13643 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13644 writeRuntimePermissions = true; 13645 final int appId = ps.appId; 13646 mHandler.post(new Runnable() { 13647 @Override 13648 public void run() { 13649 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13650 } 13651 }); 13652 } break; 13653 } 13654 } 13655 } 13656 13657 // Synchronously write as we are taking permissions away. 13658 if (writeRuntimePermissions) { 13659 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13660 } 13661 13662 // Synchronously write as we are taking permissions away. 13663 if (writeInstallPermissions) { 13664 mSettings.writeLPr(); 13665 } 13666 } 13667 13668 /** 13669 * Remove entries from the keystore daemon. Will only remove it if the 13670 * {@code appId} is valid. 13671 */ 13672 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13673 if (appId < 0) { 13674 return; 13675 } 13676 13677 final KeyStore keyStore = KeyStore.getInstance(); 13678 if (keyStore != null) { 13679 if (userId == UserHandle.USER_ALL) { 13680 for (final int individual : sUserManager.getUserIds()) { 13681 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13682 } 13683 } else { 13684 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13685 } 13686 } else { 13687 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13688 } 13689 } 13690 13691 @Override 13692 public void deleteApplicationCacheFiles(final String packageName, 13693 final IPackageDataObserver observer) { 13694 mContext.enforceCallingOrSelfPermission( 13695 android.Manifest.permission.DELETE_CACHE_FILES, null); 13696 // Queue up an async operation since the package deletion may take a little while. 13697 final int userId = UserHandle.getCallingUserId(); 13698 mHandler.post(new Runnable() { 13699 public void run() { 13700 mHandler.removeCallbacks(this); 13701 final boolean succeded; 13702 synchronized (mInstallLock) { 13703 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13704 } 13705 clearExternalStorageDataSync(packageName, userId, false); 13706 if (observer != null) { 13707 try { 13708 observer.onRemoveCompleted(packageName, succeded); 13709 } catch (RemoteException e) { 13710 Log.i(TAG, "Observer no longer exists."); 13711 } 13712 } //end if observer 13713 } //end run 13714 }); 13715 } 13716 13717 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13718 if (packageName == null) { 13719 Slog.w(TAG, "Attempt to delete null packageName."); 13720 return false; 13721 } 13722 PackageParser.Package p; 13723 synchronized (mPackages) { 13724 p = mPackages.get(packageName); 13725 } 13726 if (p == null) { 13727 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13728 return false; 13729 } 13730 final ApplicationInfo applicationInfo = p.applicationInfo; 13731 if (applicationInfo == null) { 13732 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13733 return false; 13734 } 13735 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13736 if (retCode < 0) { 13737 Slog.w(TAG, "Couldn't remove cache files for package: " 13738 + packageName + " u" + userId); 13739 return false; 13740 } 13741 return true; 13742 } 13743 13744 @Override 13745 public void getPackageSizeInfo(final String packageName, int userHandle, 13746 final IPackageStatsObserver observer) { 13747 mContext.enforceCallingOrSelfPermission( 13748 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13749 if (packageName == null) { 13750 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13751 } 13752 13753 PackageStats stats = new PackageStats(packageName, userHandle); 13754 13755 /* 13756 * Queue up an async operation since the package measurement may take a 13757 * little while. 13758 */ 13759 Message msg = mHandler.obtainMessage(INIT_COPY); 13760 msg.obj = new MeasureParams(stats, observer); 13761 mHandler.sendMessage(msg); 13762 } 13763 13764 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13765 PackageStats pStats) { 13766 if (packageName == null) { 13767 Slog.w(TAG, "Attempt to get size of null packageName."); 13768 return false; 13769 } 13770 PackageParser.Package p; 13771 boolean dataOnly = false; 13772 String libDirRoot = null; 13773 String asecPath = null; 13774 PackageSetting ps = null; 13775 synchronized (mPackages) { 13776 p = mPackages.get(packageName); 13777 ps = mSettings.mPackages.get(packageName); 13778 if(p == null) { 13779 dataOnly = true; 13780 if((ps == null) || (ps.pkg == null)) { 13781 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13782 return false; 13783 } 13784 p = ps.pkg; 13785 } 13786 if (ps != null) { 13787 libDirRoot = ps.legacyNativeLibraryPathString; 13788 } 13789 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13790 final long token = Binder.clearCallingIdentity(); 13791 try { 13792 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13793 if (secureContainerId != null) { 13794 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13795 } 13796 } finally { 13797 Binder.restoreCallingIdentity(token); 13798 } 13799 } 13800 } 13801 String publicSrcDir = null; 13802 if(!dataOnly) { 13803 final ApplicationInfo applicationInfo = p.applicationInfo; 13804 if (applicationInfo == null) { 13805 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13806 return false; 13807 } 13808 if (p.isForwardLocked()) { 13809 publicSrcDir = applicationInfo.getBaseResourcePath(); 13810 } 13811 } 13812 // TODO: extend to measure size of split APKs 13813 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13814 // not just the first level. 13815 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13816 // just the primary. 13817 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13818 13819 String apkPath; 13820 File packageDir = new File(p.codePath); 13821 13822 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13823 apkPath = packageDir.getAbsolutePath(); 13824 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13825 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13826 libDirRoot = null; 13827 } 13828 } else { 13829 apkPath = p.baseCodePath; 13830 } 13831 13832 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13833 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13834 if (res < 0) { 13835 return false; 13836 } 13837 13838 // Fix-up for forward-locked applications in ASEC containers. 13839 if (!isExternal(p)) { 13840 pStats.codeSize += pStats.externalCodeSize; 13841 pStats.externalCodeSize = 0L; 13842 } 13843 13844 return true; 13845 } 13846 13847 13848 @Override 13849 public void addPackageToPreferred(String packageName) { 13850 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13851 } 13852 13853 @Override 13854 public void removePackageFromPreferred(String packageName) { 13855 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13856 } 13857 13858 @Override 13859 public List<PackageInfo> getPreferredPackages(int flags) { 13860 return new ArrayList<PackageInfo>(); 13861 } 13862 13863 private int getUidTargetSdkVersionLockedLPr(int uid) { 13864 Object obj = mSettings.getUserIdLPr(uid); 13865 if (obj instanceof SharedUserSetting) { 13866 final SharedUserSetting sus = (SharedUserSetting) obj; 13867 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13868 final Iterator<PackageSetting> it = sus.packages.iterator(); 13869 while (it.hasNext()) { 13870 final PackageSetting ps = it.next(); 13871 if (ps.pkg != null) { 13872 int v = ps.pkg.applicationInfo.targetSdkVersion; 13873 if (v < vers) vers = v; 13874 } 13875 } 13876 return vers; 13877 } else if (obj instanceof PackageSetting) { 13878 final PackageSetting ps = (PackageSetting) obj; 13879 if (ps.pkg != null) { 13880 return ps.pkg.applicationInfo.targetSdkVersion; 13881 } 13882 } 13883 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13884 } 13885 13886 @Override 13887 public void addPreferredActivity(IntentFilter filter, int match, 13888 ComponentName[] set, ComponentName activity, int userId) { 13889 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13890 "Adding preferred"); 13891 } 13892 13893 private void addPreferredActivityInternal(IntentFilter filter, int match, 13894 ComponentName[] set, ComponentName activity, boolean always, int userId, 13895 String opname) { 13896 // writer 13897 int callingUid = Binder.getCallingUid(); 13898 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13899 if (filter.countActions() == 0) { 13900 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13901 return; 13902 } 13903 synchronized (mPackages) { 13904 if (mContext.checkCallingOrSelfPermission( 13905 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13906 != PackageManager.PERMISSION_GRANTED) { 13907 if (getUidTargetSdkVersionLockedLPr(callingUid) 13908 < Build.VERSION_CODES.FROYO) { 13909 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13910 + callingUid); 13911 return; 13912 } 13913 mContext.enforceCallingOrSelfPermission( 13914 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13915 } 13916 13917 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13918 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13919 + userId + ":"); 13920 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13921 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13922 scheduleWritePackageRestrictionsLocked(userId); 13923 } 13924 } 13925 13926 @Override 13927 public void replacePreferredActivity(IntentFilter filter, int match, 13928 ComponentName[] set, ComponentName activity, int userId) { 13929 if (filter.countActions() != 1) { 13930 throw new IllegalArgumentException( 13931 "replacePreferredActivity expects filter to have only 1 action."); 13932 } 13933 if (filter.countDataAuthorities() != 0 13934 || filter.countDataPaths() != 0 13935 || filter.countDataSchemes() > 1 13936 || filter.countDataTypes() != 0) { 13937 throw new IllegalArgumentException( 13938 "replacePreferredActivity expects filter to have no data authorities, " + 13939 "paths, or types; and at most one scheme."); 13940 } 13941 13942 final int callingUid = Binder.getCallingUid(); 13943 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13944 synchronized (mPackages) { 13945 if (mContext.checkCallingOrSelfPermission( 13946 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13947 != PackageManager.PERMISSION_GRANTED) { 13948 if (getUidTargetSdkVersionLockedLPr(callingUid) 13949 < Build.VERSION_CODES.FROYO) { 13950 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13951 + Binder.getCallingUid()); 13952 return; 13953 } 13954 mContext.enforceCallingOrSelfPermission( 13955 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13956 } 13957 13958 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13959 if (pir != null) { 13960 // Get all of the existing entries that exactly match this filter. 13961 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13962 if (existing != null && existing.size() == 1) { 13963 PreferredActivity cur = existing.get(0); 13964 if (DEBUG_PREFERRED) { 13965 Slog.i(TAG, "Checking replace of preferred:"); 13966 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13967 if (!cur.mPref.mAlways) { 13968 Slog.i(TAG, " -- CUR; not mAlways!"); 13969 } else { 13970 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13971 Slog.i(TAG, " -- CUR: mSet=" 13972 + Arrays.toString(cur.mPref.mSetComponents)); 13973 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13974 Slog.i(TAG, " -- NEW: mMatch=" 13975 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13976 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13977 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13978 } 13979 } 13980 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13981 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13982 && cur.mPref.sameSet(set)) { 13983 // Setting the preferred activity to what it happens to be already 13984 if (DEBUG_PREFERRED) { 13985 Slog.i(TAG, "Replacing with same preferred activity " 13986 + cur.mPref.mShortComponent + " for user " 13987 + userId + ":"); 13988 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13989 } 13990 return; 13991 } 13992 } 13993 13994 if (existing != null) { 13995 if (DEBUG_PREFERRED) { 13996 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13997 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13998 } 13999 for (int i = 0; i < existing.size(); i++) { 14000 PreferredActivity pa = existing.get(i); 14001 if (DEBUG_PREFERRED) { 14002 Slog.i(TAG, "Removing existing preferred activity " 14003 + pa.mPref.mComponent + ":"); 14004 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14005 } 14006 pir.removeFilter(pa); 14007 } 14008 } 14009 } 14010 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14011 "Replacing preferred"); 14012 } 14013 } 14014 14015 @Override 14016 public void clearPackagePreferredActivities(String packageName) { 14017 final int uid = Binder.getCallingUid(); 14018 // writer 14019 synchronized (mPackages) { 14020 PackageParser.Package pkg = mPackages.get(packageName); 14021 if (pkg == null || pkg.applicationInfo.uid != uid) { 14022 if (mContext.checkCallingOrSelfPermission( 14023 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14024 != PackageManager.PERMISSION_GRANTED) { 14025 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14026 < Build.VERSION_CODES.FROYO) { 14027 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14028 + Binder.getCallingUid()); 14029 return; 14030 } 14031 mContext.enforceCallingOrSelfPermission( 14032 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14033 } 14034 } 14035 14036 int user = UserHandle.getCallingUserId(); 14037 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14038 scheduleWritePackageRestrictionsLocked(user); 14039 } 14040 } 14041 } 14042 14043 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14044 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14045 ArrayList<PreferredActivity> removed = null; 14046 boolean changed = false; 14047 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14048 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14049 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14050 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14051 continue; 14052 } 14053 Iterator<PreferredActivity> it = pir.filterIterator(); 14054 while (it.hasNext()) { 14055 PreferredActivity pa = it.next(); 14056 // Mark entry for removal only if it matches the package name 14057 // and the entry is of type "always". 14058 if (packageName == null || 14059 (pa.mPref.mComponent.getPackageName().equals(packageName) 14060 && pa.mPref.mAlways)) { 14061 if (removed == null) { 14062 removed = new ArrayList<PreferredActivity>(); 14063 } 14064 removed.add(pa); 14065 } 14066 } 14067 if (removed != null) { 14068 for (int j=0; j<removed.size(); j++) { 14069 PreferredActivity pa = removed.get(j); 14070 pir.removeFilter(pa); 14071 } 14072 changed = true; 14073 } 14074 } 14075 return changed; 14076 } 14077 14078 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14079 private void clearIntentFilterVerificationsLPw(int userId) { 14080 final int packageCount = mPackages.size(); 14081 for (int i = 0; i < packageCount; i++) { 14082 PackageParser.Package pkg = mPackages.valueAt(i); 14083 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14084 } 14085 } 14086 14087 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14088 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14089 if (userId == UserHandle.USER_ALL) { 14090 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14091 sUserManager.getUserIds())) { 14092 for (int oneUserId : sUserManager.getUserIds()) { 14093 scheduleWritePackageRestrictionsLocked(oneUserId); 14094 } 14095 } 14096 } else { 14097 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14098 scheduleWritePackageRestrictionsLocked(userId); 14099 } 14100 } 14101 } 14102 14103 void clearDefaultBrowserIfNeeded(String packageName) { 14104 for (int oneUserId : sUserManager.getUserIds()) { 14105 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14106 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14107 if (packageName.equals(defaultBrowserPackageName)) { 14108 setDefaultBrowserPackageName(null, oneUserId); 14109 } 14110 } 14111 } 14112 14113 @Override 14114 public void resetApplicationPreferences(int userId) { 14115 mContext.enforceCallingOrSelfPermission( 14116 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14117 // writer 14118 synchronized (mPackages) { 14119 final long identity = Binder.clearCallingIdentity(); 14120 try { 14121 clearPackagePreferredActivitiesLPw(null, userId); 14122 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14123 // TODO: We have to reset the default SMS and Phone. This requires 14124 // significant refactoring to keep all default apps in the package 14125 // manager (cleaner but more work) or have the services provide 14126 // callbacks to the package manager to request a default app reset. 14127 applyFactoryDefaultBrowserLPw(userId); 14128 clearIntentFilterVerificationsLPw(userId); 14129 primeDomainVerificationsLPw(userId); 14130 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14131 scheduleWritePackageRestrictionsLocked(userId); 14132 } finally { 14133 Binder.restoreCallingIdentity(identity); 14134 } 14135 } 14136 } 14137 14138 @Override 14139 public int getPreferredActivities(List<IntentFilter> outFilters, 14140 List<ComponentName> outActivities, String packageName) { 14141 14142 int num = 0; 14143 final int userId = UserHandle.getCallingUserId(); 14144 // reader 14145 synchronized (mPackages) { 14146 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14147 if (pir != null) { 14148 final Iterator<PreferredActivity> it = pir.filterIterator(); 14149 while (it.hasNext()) { 14150 final PreferredActivity pa = it.next(); 14151 if (packageName == null 14152 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14153 && pa.mPref.mAlways)) { 14154 if (outFilters != null) { 14155 outFilters.add(new IntentFilter(pa)); 14156 } 14157 if (outActivities != null) { 14158 outActivities.add(pa.mPref.mComponent); 14159 } 14160 } 14161 } 14162 } 14163 } 14164 14165 return num; 14166 } 14167 14168 @Override 14169 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14170 int userId) { 14171 int callingUid = Binder.getCallingUid(); 14172 if (callingUid != Process.SYSTEM_UID) { 14173 throw new SecurityException( 14174 "addPersistentPreferredActivity can only be run by the system"); 14175 } 14176 if (filter.countActions() == 0) { 14177 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14178 return; 14179 } 14180 synchronized (mPackages) { 14181 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14182 " :"); 14183 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14184 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14185 new PersistentPreferredActivity(filter, activity)); 14186 scheduleWritePackageRestrictionsLocked(userId); 14187 } 14188 } 14189 14190 @Override 14191 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14192 int callingUid = Binder.getCallingUid(); 14193 if (callingUid != Process.SYSTEM_UID) { 14194 throw new SecurityException( 14195 "clearPackagePersistentPreferredActivities can only be run by the system"); 14196 } 14197 ArrayList<PersistentPreferredActivity> removed = null; 14198 boolean changed = false; 14199 synchronized (mPackages) { 14200 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14201 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14202 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14203 .valueAt(i); 14204 if (userId != thisUserId) { 14205 continue; 14206 } 14207 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14208 while (it.hasNext()) { 14209 PersistentPreferredActivity ppa = it.next(); 14210 // Mark entry for removal only if it matches the package name. 14211 if (ppa.mComponent.getPackageName().equals(packageName)) { 14212 if (removed == null) { 14213 removed = new ArrayList<PersistentPreferredActivity>(); 14214 } 14215 removed.add(ppa); 14216 } 14217 } 14218 if (removed != null) { 14219 for (int j=0; j<removed.size(); j++) { 14220 PersistentPreferredActivity ppa = removed.get(j); 14221 ppir.removeFilter(ppa); 14222 } 14223 changed = true; 14224 } 14225 } 14226 14227 if (changed) { 14228 scheduleWritePackageRestrictionsLocked(userId); 14229 } 14230 } 14231 } 14232 14233 /** 14234 * Common machinery for picking apart a restored XML blob and passing 14235 * it to a caller-supplied functor to be applied to the running system. 14236 */ 14237 private void restoreFromXml(XmlPullParser parser, int userId, 14238 String expectedStartTag, BlobXmlRestorer functor) 14239 throws IOException, XmlPullParserException { 14240 int type; 14241 while ((type = parser.next()) != XmlPullParser.START_TAG 14242 && type != XmlPullParser.END_DOCUMENT) { 14243 } 14244 if (type != XmlPullParser.START_TAG) { 14245 // oops didn't find a start tag?! 14246 if (DEBUG_BACKUP) { 14247 Slog.e(TAG, "Didn't find start tag during restore"); 14248 } 14249 return; 14250 } 14251 14252 // this is supposed to be TAG_PREFERRED_BACKUP 14253 if (!expectedStartTag.equals(parser.getName())) { 14254 if (DEBUG_BACKUP) { 14255 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14256 } 14257 return; 14258 } 14259 14260 // skip interfering stuff, then we're aligned with the backing implementation 14261 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14262 functor.apply(parser, userId); 14263 } 14264 14265 private interface BlobXmlRestorer { 14266 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14267 } 14268 14269 /** 14270 * Non-Binder method, support for the backup/restore mechanism: write the 14271 * full set of preferred activities in its canonical XML format. Returns the 14272 * XML output as a byte array, or null if there is none. 14273 */ 14274 @Override 14275 public byte[] getPreferredActivityBackup(int userId) { 14276 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14277 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14278 } 14279 14280 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14281 try { 14282 final XmlSerializer serializer = new FastXmlSerializer(); 14283 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14284 serializer.startDocument(null, true); 14285 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14286 14287 synchronized (mPackages) { 14288 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14289 } 14290 14291 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14292 serializer.endDocument(); 14293 serializer.flush(); 14294 } catch (Exception e) { 14295 if (DEBUG_BACKUP) { 14296 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14297 } 14298 return null; 14299 } 14300 14301 return dataStream.toByteArray(); 14302 } 14303 14304 @Override 14305 public void restorePreferredActivities(byte[] backup, int userId) { 14306 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14307 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14308 } 14309 14310 try { 14311 final XmlPullParser parser = Xml.newPullParser(); 14312 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14313 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14314 new BlobXmlRestorer() { 14315 @Override 14316 public void apply(XmlPullParser parser, int userId) 14317 throws XmlPullParserException, IOException { 14318 synchronized (mPackages) { 14319 mSettings.readPreferredActivitiesLPw(parser, userId); 14320 } 14321 } 14322 } ); 14323 } catch (Exception e) { 14324 if (DEBUG_BACKUP) { 14325 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14326 } 14327 } 14328 } 14329 14330 /** 14331 * Non-Binder method, support for the backup/restore mechanism: write the 14332 * default browser (etc) settings in its canonical XML format. Returns the default 14333 * browser XML representation as a byte array, or null if there is none. 14334 */ 14335 @Override 14336 public byte[] getDefaultAppsBackup(int userId) { 14337 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14338 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14339 } 14340 14341 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14342 try { 14343 final XmlSerializer serializer = new FastXmlSerializer(); 14344 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14345 serializer.startDocument(null, true); 14346 serializer.startTag(null, TAG_DEFAULT_APPS); 14347 14348 synchronized (mPackages) { 14349 mSettings.writeDefaultAppsLPr(serializer, userId); 14350 } 14351 14352 serializer.endTag(null, TAG_DEFAULT_APPS); 14353 serializer.endDocument(); 14354 serializer.flush(); 14355 } catch (Exception e) { 14356 if (DEBUG_BACKUP) { 14357 Slog.e(TAG, "Unable to write default apps for backup", e); 14358 } 14359 return null; 14360 } 14361 14362 return dataStream.toByteArray(); 14363 } 14364 14365 @Override 14366 public void restoreDefaultApps(byte[] backup, int userId) { 14367 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14368 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14369 } 14370 14371 try { 14372 final XmlPullParser parser = Xml.newPullParser(); 14373 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14374 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14375 new BlobXmlRestorer() { 14376 @Override 14377 public void apply(XmlPullParser parser, int userId) 14378 throws XmlPullParserException, IOException { 14379 synchronized (mPackages) { 14380 mSettings.readDefaultAppsLPw(parser, userId); 14381 } 14382 } 14383 } ); 14384 } catch (Exception e) { 14385 if (DEBUG_BACKUP) { 14386 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14387 } 14388 } 14389 } 14390 14391 @Override 14392 public byte[] getIntentFilterVerificationBackup(int userId) { 14393 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14394 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14395 } 14396 14397 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14398 try { 14399 final XmlSerializer serializer = new FastXmlSerializer(); 14400 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14401 serializer.startDocument(null, true); 14402 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14403 14404 synchronized (mPackages) { 14405 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14406 } 14407 14408 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14409 serializer.endDocument(); 14410 serializer.flush(); 14411 } catch (Exception e) { 14412 if (DEBUG_BACKUP) { 14413 Slog.e(TAG, "Unable to write default apps for backup", e); 14414 } 14415 return null; 14416 } 14417 14418 return dataStream.toByteArray(); 14419 } 14420 14421 @Override 14422 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14423 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14424 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14425 } 14426 14427 try { 14428 final XmlPullParser parser = Xml.newPullParser(); 14429 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14430 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14431 new BlobXmlRestorer() { 14432 @Override 14433 public void apply(XmlPullParser parser, int userId) 14434 throws XmlPullParserException, IOException { 14435 synchronized (mPackages) { 14436 mSettings.readAllDomainVerificationsLPr(parser, userId); 14437 mSettings.writeLPr(); 14438 } 14439 } 14440 } ); 14441 } catch (Exception e) { 14442 if (DEBUG_BACKUP) { 14443 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14444 } 14445 } 14446 } 14447 14448 @Override 14449 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14450 int sourceUserId, int targetUserId, int flags) { 14451 mContext.enforceCallingOrSelfPermission( 14452 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14453 int callingUid = Binder.getCallingUid(); 14454 enforceOwnerRights(ownerPackage, callingUid); 14455 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14456 if (intentFilter.countActions() == 0) { 14457 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14458 return; 14459 } 14460 synchronized (mPackages) { 14461 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14462 ownerPackage, targetUserId, flags); 14463 CrossProfileIntentResolver resolver = 14464 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14465 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14466 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14467 if (existing != null) { 14468 int size = existing.size(); 14469 for (int i = 0; i < size; i++) { 14470 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14471 return; 14472 } 14473 } 14474 } 14475 resolver.addFilter(newFilter); 14476 scheduleWritePackageRestrictionsLocked(sourceUserId); 14477 } 14478 } 14479 14480 @Override 14481 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14482 mContext.enforceCallingOrSelfPermission( 14483 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14484 int callingUid = Binder.getCallingUid(); 14485 enforceOwnerRights(ownerPackage, callingUid); 14486 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14487 synchronized (mPackages) { 14488 CrossProfileIntentResolver resolver = 14489 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14490 ArraySet<CrossProfileIntentFilter> set = 14491 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14492 for (CrossProfileIntentFilter filter : set) { 14493 if (filter.getOwnerPackage().equals(ownerPackage)) { 14494 resolver.removeFilter(filter); 14495 } 14496 } 14497 scheduleWritePackageRestrictionsLocked(sourceUserId); 14498 } 14499 } 14500 14501 // Enforcing that callingUid is owning pkg on userId 14502 private void enforceOwnerRights(String pkg, int callingUid) { 14503 // The system owns everything. 14504 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14505 return; 14506 } 14507 int callingUserId = UserHandle.getUserId(callingUid); 14508 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14509 if (pi == null) { 14510 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14511 + callingUserId); 14512 } 14513 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14514 throw new SecurityException("Calling uid " + callingUid 14515 + " does not own package " + pkg); 14516 } 14517 } 14518 14519 @Override 14520 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14521 Intent intent = new Intent(Intent.ACTION_MAIN); 14522 intent.addCategory(Intent.CATEGORY_HOME); 14523 14524 final int callingUserId = UserHandle.getCallingUserId(); 14525 List<ResolveInfo> list = queryIntentActivities(intent, null, 14526 PackageManager.GET_META_DATA, callingUserId); 14527 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14528 true, false, false, callingUserId); 14529 14530 allHomeCandidates.clear(); 14531 if (list != null) { 14532 for (ResolveInfo ri : list) { 14533 allHomeCandidates.add(ri); 14534 } 14535 } 14536 return (preferred == null || preferred.activityInfo == null) 14537 ? null 14538 : new ComponentName(preferred.activityInfo.packageName, 14539 preferred.activityInfo.name); 14540 } 14541 14542 @Override 14543 public void setApplicationEnabledSetting(String appPackageName, 14544 int newState, int flags, int userId, String callingPackage) { 14545 if (!sUserManager.exists(userId)) return; 14546 if (callingPackage == null) { 14547 callingPackage = Integer.toString(Binder.getCallingUid()); 14548 } 14549 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14550 } 14551 14552 @Override 14553 public void setComponentEnabledSetting(ComponentName componentName, 14554 int newState, int flags, int userId) { 14555 if (!sUserManager.exists(userId)) return; 14556 setEnabledSetting(componentName.getPackageName(), 14557 componentName.getClassName(), newState, flags, userId, null); 14558 } 14559 14560 private void setEnabledSetting(final String packageName, String className, int newState, 14561 final int flags, int userId, String callingPackage) { 14562 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14563 || newState == COMPONENT_ENABLED_STATE_ENABLED 14564 || newState == COMPONENT_ENABLED_STATE_DISABLED 14565 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14566 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14567 throw new IllegalArgumentException("Invalid new component state: " 14568 + newState); 14569 } 14570 PackageSetting pkgSetting; 14571 final int uid = Binder.getCallingUid(); 14572 final int permission = mContext.checkCallingOrSelfPermission( 14573 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14574 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14575 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14576 boolean sendNow = false; 14577 boolean isApp = (className == null); 14578 String componentName = isApp ? packageName : className; 14579 int packageUid = -1; 14580 ArrayList<String> components; 14581 14582 // writer 14583 synchronized (mPackages) { 14584 pkgSetting = mSettings.mPackages.get(packageName); 14585 if (pkgSetting == null) { 14586 if (className == null) { 14587 throw new IllegalArgumentException( 14588 "Unknown package: " + packageName); 14589 } 14590 throw new IllegalArgumentException( 14591 "Unknown component: " + packageName 14592 + "/" + className); 14593 } 14594 // Allow root and verify that userId is not being specified by a different user 14595 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14596 throw new SecurityException( 14597 "Permission Denial: attempt to change component state from pid=" 14598 + Binder.getCallingPid() 14599 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14600 } 14601 if (className == null) { 14602 // We're dealing with an application/package level state change 14603 if (pkgSetting.getEnabled(userId) == newState) { 14604 // Nothing to do 14605 return; 14606 } 14607 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14608 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14609 // Don't care about who enables an app. 14610 callingPackage = null; 14611 } 14612 pkgSetting.setEnabled(newState, userId, callingPackage); 14613 // pkgSetting.pkg.mSetEnabled = newState; 14614 } else { 14615 // We're dealing with a component level state change 14616 // First, verify that this is a valid class name. 14617 PackageParser.Package pkg = pkgSetting.pkg; 14618 if (pkg == null || !pkg.hasComponentClassName(className)) { 14619 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14620 throw new IllegalArgumentException("Component class " + className 14621 + " does not exist in " + packageName); 14622 } else { 14623 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14624 + className + " does not exist in " + packageName); 14625 } 14626 } 14627 switch (newState) { 14628 case COMPONENT_ENABLED_STATE_ENABLED: 14629 if (!pkgSetting.enableComponentLPw(className, userId)) { 14630 return; 14631 } 14632 break; 14633 case COMPONENT_ENABLED_STATE_DISABLED: 14634 if (!pkgSetting.disableComponentLPw(className, userId)) { 14635 return; 14636 } 14637 break; 14638 case COMPONENT_ENABLED_STATE_DEFAULT: 14639 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14640 return; 14641 } 14642 break; 14643 default: 14644 Slog.e(TAG, "Invalid new component state: " + newState); 14645 return; 14646 } 14647 } 14648 scheduleWritePackageRestrictionsLocked(userId); 14649 components = mPendingBroadcasts.get(userId, packageName); 14650 final boolean newPackage = components == null; 14651 if (newPackage) { 14652 components = new ArrayList<String>(); 14653 } 14654 if (!components.contains(componentName)) { 14655 components.add(componentName); 14656 } 14657 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14658 sendNow = true; 14659 // Purge entry from pending broadcast list if another one exists already 14660 // since we are sending one right away. 14661 mPendingBroadcasts.remove(userId, packageName); 14662 } else { 14663 if (newPackage) { 14664 mPendingBroadcasts.put(userId, packageName, components); 14665 } 14666 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14667 // Schedule a message 14668 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14669 } 14670 } 14671 } 14672 14673 long callingId = Binder.clearCallingIdentity(); 14674 try { 14675 if (sendNow) { 14676 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14677 sendPackageChangedBroadcast(packageName, 14678 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14679 } 14680 } finally { 14681 Binder.restoreCallingIdentity(callingId); 14682 } 14683 } 14684 14685 private void sendPackageChangedBroadcast(String packageName, 14686 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14687 if (DEBUG_INSTALL) 14688 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14689 + componentNames); 14690 Bundle extras = new Bundle(4); 14691 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14692 String nameList[] = new String[componentNames.size()]; 14693 componentNames.toArray(nameList); 14694 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14695 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14696 extras.putInt(Intent.EXTRA_UID, packageUid); 14697 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14698 new int[] {UserHandle.getUserId(packageUid)}); 14699 } 14700 14701 @Override 14702 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14703 if (!sUserManager.exists(userId)) return; 14704 final int uid = Binder.getCallingUid(); 14705 final int permission = mContext.checkCallingOrSelfPermission( 14706 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14707 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14708 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14709 // writer 14710 synchronized (mPackages) { 14711 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14712 allowedByPermission, uid, userId)) { 14713 scheduleWritePackageRestrictionsLocked(userId); 14714 } 14715 } 14716 } 14717 14718 @Override 14719 public String getInstallerPackageName(String packageName) { 14720 // reader 14721 synchronized (mPackages) { 14722 return mSettings.getInstallerPackageNameLPr(packageName); 14723 } 14724 } 14725 14726 @Override 14727 public int getApplicationEnabledSetting(String packageName, int userId) { 14728 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14729 int uid = Binder.getCallingUid(); 14730 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14731 // reader 14732 synchronized (mPackages) { 14733 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14734 } 14735 } 14736 14737 @Override 14738 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14739 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14740 int uid = Binder.getCallingUid(); 14741 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14742 // reader 14743 synchronized (mPackages) { 14744 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14745 } 14746 } 14747 14748 @Override 14749 public void enterSafeMode() { 14750 enforceSystemOrRoot("Only the system can request entering safe mode"); 14751 14752 if (!mSystemReady) { 14753 mSafeMode = true; 14754 } 14755 } 14756 14757 @Override 14758 public void systemReady() { 14759 mSystemReady = true; 14760 14761 // Read the compatibilty setting when the system is ready. 14762 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14763 mContext.getContentResolver(), 14764 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14765 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14766 if (DEBUG_SETTINGS) { 14767 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14768 } 14769 14770 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14771 14772 synchronized (mPackages) { 14773 // Verify that all of the preferred activity components actually 14774 // exist. It is possible for applications to be updated and at 14775 // that point remove a previously declared activity component that 14776 // had been set as a preferred activity. We try to clean this up 14777 // the next time we encounter that preferred activity, but it is 14778 // possible for the user flow to never be able to return to that 14779 // situation so here we do a sanity check to make sure we haven't 14780 // left any junk around. 14781 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14782 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14783 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14784 removed.clear(); 14785 for (PreferredActivity pa : pir.filterSet()) { 14786 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14787 removed.add(pa); 14788 } 14789 } 14790 if (removed.size() > 0) { 14791 for (int r=0; r<removed.size(); r++) { 14792 PreferredActivity pa = removed.get(r); 14793 Slog.w(TAG, "Removing dangling preferred activity: " 14794 + pa.mPref.mComponent); 14795 pir.removeFilter(pa); 14796 } 14797 mSettings.writePackageRestrictionsLPr( 14798 mSettings.mPreferredActivities.keyAt(i)); 14799 } 14800 } 14801 14802 for (int userId : UserManagerService.getInstance().getUserIds()) { 14803 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14804 grantPermissionsUserIds = ArrayUtils.appendInt( 14805 grantPermissionsUserIds, userId); 14806 } 14807 } 14808 } 14809 sUserManager.systemReady(); 14810 14811 // If we upgraded grant all default permissions before kicking off. 14812 for (int userId : grantPermissionsUserIds) { 14813 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14814 } 14815 14816 // Kick off any messages waiting for system ready 14817 if (mPostSystemReadyMessages != null) { 14818 for (Message msg : mPostSystemReadyMessages) { 14819 msg.sendToTarget(); 14820 } 14821 mPostSystemReadyMessages = null; 14822 } 14823 14824 // Watch for external volumes that come and go over time 14825 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14826 storage.registerListener(mStorageListener); 14827 14828 mInstallerService.systemReady(); 14829 mPackageDexOptimizer.systemReady(); 14830 14831 MountServiceInternal mountServiceInternal = LocalServices.getService( 14832 MountServiceInternal.class); 14833 mountServiceInternal.addExternalStoragePolicy( 14834 new MountServiceInternal.ExternalStorageMountPolicy() { 14835 @Override 14836 public int getMountMode(int uid, String packageName) { 14837 if (Process.isIsolated(uid)) { 14838 return Zygote.MOUNT_EXTERNAL_NONE; 14839 } 14840 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14841 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14842 } 14843 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14844 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14845 } 14846 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14847 return Zygote.MOUNT_EXTERNAL_READ; 14848 } 14849 return Zygote.MOUNT_EXTERNAL_WRITE; 14850 } 14851 14852 @Override 14853 public boolean hasExternalStorage(int uid, String packageName) { 14854 return true; 14855 } 14856 }); 14857 } 14858 14859 @Override 14860 public boolean isSafeMode() { 14861 return mSafeMode; 14862 } 14863 14864 @Override 14865 public boolean hasSystemUidErrors() { 14866 return mHasSystemUidErrors; 14867 } 14868 14869 static String arrayToString(int[] array) { 14870 StringBuffer buf = new StringBuffer(128); 14871 buf.append('['); 14872 if (array != null) { 14873 for (int i=0; i<array.length; i++) { 14874 if (i > 0) buf.append(", "); 14875 buf.append(array[i]); 14876 } 14877 } 14878 buf.append(']'); 14879 return buf.toString(); 14880 } 14881 14882 static class DumpState { 14883 public static final int DUMP_LIBS = 1 << 0; 14884 public static final int DUMP_FEATURES = 1 << 1; 14885 public static final int DUMP_RESOLVERS = 1 << 2; 14886 public static final int DUMP_PERMISSIONS = 1 << 3; 14887 public static final int DUMP_PACKAGES = 1 << 4; 14888 public static final int DUMP_SHARED_USERS = 1 << 5; 14889 public static final int DUMP_MESSAGES = 1 << 6; 14890 public static final int DUMP_PROVIDERS = 1 << 7; 14891 public static final int DUMP_VERIFIERS = 1 << 8; 14892 public static final int DUMP_PREFERRED = 1 << 9; 14893 public static final int DUMP_PREFERRED_XML = 1 << 10; 14894 public static final int DUMP_KEYSETS = 1 << 11; 14895 public static final int DUMP_VERSION = 1 << 12; 14896 public static final int DUMP_INSTALLS = 1 << 13; 14897 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14898 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14899 14900 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14901 14902 private int mTypes; 14903 14904 private int mOptions; 14905 14906 private boolean mTitlePrinted; 14907 14908 private SharedUserSetting mSharedUser; 14909 14910 public boolean isDumping(int type) { 14911 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14912 return true; 14913 } 14914 14915 return (mTypes & type) != 0; 14916 } 14917 14918 public void setDump(int type) { 14919 mTypes |= type; 14920 } 14921 14922 public boolean isOptionEnabled(int option) { 14923 return (mOptions & option) != 0; 14924 } 14925 14926 public void setOptionEnabled(int option) { 14927 mOptions |= option; 14928 } 14929 14930 public boolean onTitlePrinted() { 14931 final boolean printed = mTitlePrinted; 14932 mTitlePrinted = true; 14933 return printed; 14934 } 14935 14936 public boolean getTitlePrinted() { 14937 return mTitlePrinted; 14938 } 14939 14940 public void setTitlePrinted(boolean enabled) { 14941 mTitlePrinted = enabled; 14942 } 14943 14944 public SharedUserSetting getSharedUser() { 14945 return mSharedUser; 14946 } 14947 14948 public void setSharedUser(SharedUserSetting user) { 14949 mSharedUser = user; 14950 } 14951 } 14952 14953 @Override 14954 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14955 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14956 != PackageManager.PERMISSION_GRANTED) { 14957 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14958 + Binder.getCallingPid() 14959 + ", uid=" + Binder.getCallingUid() 14960 + " without permission " 14961 + android.Manifest.permission.DUMP); 14962 return; 14963 } 14964 14965 DumpState dumpState = new DumpState(); 14966 boolean fullPreferred = false; 14967 boolean checkin = false; 14968 14969 String packageName = null; 14970 ArraySet<String> permissionNames = null; 14971 14972 int opti = 0; 14973 while (opti < args.length) { 14974 String opt = args[opti]; 14975 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14976 break; 14977 } 14978 opti++; 14979 14980 if ("-a".equals(opt)) { 14981 // Right now we only know how to print all. 14982 } else if ("-h".equals(opt)) { 14983 pw.println("Package manager dump options:"); 14984 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14985 pw.println(" --checkin: dump for a checkin"); 14986 pw.println(" -f: print details of intent filters"); 14987 pw.println(" -h: print this help"); 14988 pw.println(" cmd may be one of:"); 14989 pw.println(" l[ibraries]: list known shared libraries"); 14990 pw.println(" f[ibraries]: list device features"); 14991 pw.println(" k[eysets]: print known keysets"); 14992 pw.println(" r[esolvers]: dump intent resolvers"); 14993 pw.println(" perm[issions]: dump permissions"); 14994 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14995 pw.println(" pref[erred]: print preferred package settings"); 14996 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14997 pw.println(" prov[iders]: dump content providers"); 14998 pw.println(" p[ackages]: dump installed packages"); 14999 pw.println(" s[hared-users]: dump shared user IDs"); 15000 pw.println(" m[essages]: print collected runtime messages"); 15001 pw.println(" v[erifiers]: print package verifier info"); 15002 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15003 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15004 pw.println(" version: print database version info"); 15005 pw.println(" write: write current settings now"); 15006 pw.println(" installs: details about install sessions"); 15007 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15008 pw.println(" <package.name>: info about given package"); 15009 return; 15010 } else if ("--checkin".equals(opt)) { 15011 checkin = true; 15012 } else if ("-f".equals(opt)) { 15013 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15014 } else { 15015 pw.println("Unknown argument: " + opt + "; use -h for help"); 15016 } 15017 } 15018 15019 // Is the caller requesting to dump a particular piece of data? 15020 if (opti < args.length) { 15021 String cmd = args[opti]; 15022 opti++; 15023 // Is this a package name? 15024 if ("android".equals(cmd) || cmd.contains(".")) { 15025 packageName = cmd; 15026 // When dumping a single package, we always dump all of its 15027 // filter information since the amount of data will be reasonable. 15028 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15029 } else if ("check-permission".equals(cmd)) { 15030 if (opti >= args.length) { 15031 pw.println("Error: check-permission missing permission argument"); 15032 return; 15033 } 15034 String perm = args[opti]; 15035 opti++; 15036 if (opti >= args.length) { 15037 pw.println("Error: check-permission missing package argument"); 15038 return; 15039 } 15040 String pkg = args[opti]; 15041 opti++; 15042 int user = UserHandle.getUserId(Binder.getCallingUid()); 15043 if (opti < args.length) { 15044 try { 15045 user = Integer.parseInt(args[opti]); 15046 } catch (NumberFormatException e) { 15047 pw.println("Error: check-permission user argument is not a number: " 15048 + args[opti]); 15049 return; 15050 } 15051 } 15052 pw.println(checkPermission(perm, pkg, user)); 15053 return; 15054 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15055 dumpState.setDump(DumpState.DUMP_LIBS); 15056 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15057 dumpState.setDump(DumpState.DUMP_FEATURES); 15058 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15059 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15060 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15061 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15062 } else if ("permission".equals(cmd)) { 15063 if (opti >= args.length) { 15064 pw.println("Error: permission requires permission name"); 15065 return; 15066 } 15067 permissionNames = new ArraySet<>(); 15068 while (opti < args.length) { 15069 permissionNames.add(args[opti]); 15070 opti++; 15071 } 15072 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15073 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15074 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15075 dumpState.setDump(DumpState.DUMP_PREFERRED); 15076 } else if ("preferred-xml".equals(cmd)) { 15077 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15078 if (opti < args.length && "--full".equals(args[opti])) { 15079 fullPreferred = true; 15080 opti++; 15081 } 15082 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15083 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15084 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15085 dumpState.setDump(DumpState.DUMP_PACKAGES); 15086 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15087 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15088 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15089 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15090 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15091 dumpState.setDump(DumpState.DUMP_MESSAGES); 15092 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15093 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15094 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15095 || "intent-filter-verifiers".equals(cmd)) { 15096 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15097 } else if ("version".equals(cmd)) { 15098 dumpState.setDump(DumpState.DUMP_VERSION); 15099 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15100 dumpState.setDump(DumpState.DUMP_KEYSETS); 15101 } else if ("installs".equals(cmd)) { 15102 dumpState.setDump(DumpState.DUMP_INSTALLS); 15103 } else if ("write".equals(cmd)) { 15104 synchronized (mPackages) { 15105 mSettings.writeLPr(); 15106 pw.println("Settings written."); 15107 return; 15108 } 15109 } 15110 } 15111 15112 if (checkin) { 15113 pw.println("vers,1"); 15114 } 15115 15116 // reader 15117 synchronized (mPackages) { 15118 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15119 if (!checkin) { 15120 if (dumpState.onTitlePrinted()) 15121 pw.println(); 15122 pw.println("Database versions:"); 15123 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15124 } 15125 } 15126 15127 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15128 if (!checkin) { 15129 if (dumpState.onTitlePrinted()) 15130 pw.println(); 15131 pw.println("Verifiers:"); 15132 pw.print(" Required: "); 15133 pw.print(mRequiredVerifierPackage); 15134 pw.print(" (uid="); 15135 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15136 pw.println(")"); 15137 } else if (mRequiredVerifierPackage != null) { 15138 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15139 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15140 } 15141 } 15142 15143 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15144 packageName == null) { 15145 if (mIntentFilterVerifierComponent != null) { 15146 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15147 if (!checkin) { 15148 if (dumpState.onTitlePrinted()) 15149 pw.println(); 15150 pw.println("Intent Filter Verifier:"); 15151 pw.print(" Using: "); 15152 pw.print(verifierPackageName); 15153 pw.print(" (uid="); 15154 pw.print(getPackageUid(verifierPackageName, 0)); 15155 pw.println(")"); 15156 } else if (verifierPackageName != null) { 15157 pw.print("ifv,"); pw.print(verifierPackageName); 15158 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15159 } 15160 } else { 15161 pw.println(); 15162 pw.println("No Intent Filter Verifier available!"); 15163 } 15164 } 15165 15166 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15167 boolean printedHeader = false; 15168 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15169 while (it.hasNext()) { 15170 String name = it.next(); 15171 SharedLibraryEntry ent = mSharedLibraries.get(name); 15172 if (!checkin) { 15173 if (!printedHeader) { 15174 if (dumpState.onTitlePrinted()) 15175 pw.println(); 15176 pw.println("Libraries:"); 15177 printedHeader = true; 15178 } 15179 pw.print(" "); 15180 } else { 15181 pw.print("lib,"); 15182 } 15183 pw.print(name); 15184 if (!checkin) { 15185 pw.print(" -> "); 15186 } 15187 if (ent.path != null) { 15188 if (!checkin) { 15189 pw.print("(jar) "); 15190 pw.print(ent.path); 15191 } else { 15192 pw.print(",jar,"); 15193 pw.print(ent.path); 15194 } 15195 } else { 15196 if (!checkin) { 15197 pw.print("(apk) "); 15198 pw.print(ent.apk); 15199 } else { 15200 pw.print(",apk,"); 15201 pw.print(ent.apk); 15202 } 15203 } 15204 pw.println(); 15205 } 15206 } 15207 15208 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15209 if (dumpState.onTitlePrinted()) 15210 pw.println(); 15211 if (!checkin) { 15212 pw.println("Features:"); 15213 } 15214 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15215 while (it.hasNext()) { 15216 String name = it.next(); 15217 if (!checkin) { 15218 pw.print(" "); 15219 } else { 15220 pw.print("feat,"); 15221 } 15222 pw.println(name); 15223 } 15224 } 15225 15226 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15227 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15228 : "Activity Resolver Table:", " ", packageName, 15229 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15230 dumpState.setTitlePrinted(true); 15231 } 15232 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15233 : "Receiver Resolver Table:", " ", packageName, 15234 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15235 dumpState.setTitlePrinted(true); 15236 } 15237 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15238 : "Service Resolver Table:", " ", packageName, 15239 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15240 dumpState.setTitlePrinted(true); 15241 } 15242 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15243 : "Provider Resolver Table:", " ", packageName, 15244 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15245 dumpState.setTitlePrinted(true); 15246 } 15247 } 15248 15249 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15250 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15251 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15252 int user = mSettings.mPreferredActivities.keyAt(i); 15253 if (pir.dump(pw, 15254 dumpState.getTitlePrinted() 15255 ? "\nPreferred Activities User " + user + ":" 15256 : "Preferred Activities User " + user + ":", " ", 15257 packageName, true, false)) { 15258 dumpState.setTitlePrinted(true); 15259 } 15260 } 15261 } 15262 15263 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15264 pw.flush(); 15265 FileOutputStream fout = new FileOutputStream(fd); 15266 BufferedOutputStream str = new BufferedOutputStream(fout); 15267 XmlSerializer serializer = new FastXmlSerializer(); 15268 try { 15269 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15270 serializer.startDocument(null, true); 15271 serializer.setFeature( 15272 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15273 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15274 serializer.endDocument(); 15275 serializer.flush(); 15276 } catch (IllegalArgumentException e) { 15277 pw.println("Failed writing: " + e); 15278 } catch (IllegalStateException e) { 15279 pw.println("Failed writing: " + e); 15280 } catch (IOException e) { 15281 pw.println("Failed writing: " + e); 15282 } 15283 } 15284 15285 if (!checkin 15286 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15287 && packageName == null) { 15288 pw.println(); 15289 int count = mSettings.mPackages.size(); 15290 if (count == 0) { 15291 pw.println("No applications!"); 15292 pw.println(); 15293 } else { 15294 final String prefix = " "; 15295 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15296 if (allPackageSettings.size() == 0) { 15297 pw.println("No domain preferred apps!"); 15298 pw.println(); 15299 } else { 15300 pw.println("App verification status:"); 15301 pw.println(); 15302 count = 0; 15303 for (PackageSetting ps : allPackageSettings) { 15304 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15305 if (ivi == null || ivi.getPackageName() == null) continue; 15306 pw.println(prefix + "Package: " + ivi.getPackageName()); 15307 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15308 pw.println(prefix + "Status: " + ivi.getStatusString()); 15309 pw.println(); 15310 count++; 15311 } 15312 if (count == 0) { 15313 pw.println(prefix + "No app verification established."); 15314 pw.println(); 15315 } 15316 for (int userId : sUserManager.getUserIds()) { 15317 pw.println("App linkages for user " + userId + ":"); 15318 pw.println(); 15319 count = 0; 15320 for (PackageSetting ps : allPackageSettings) { 15321 final long status = ps.getDomainVerificationStatusForUser(userId); 15322 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15323 continue; 15324 } 15325 pw.println(prefix + "Package: " + ps.name); 15326 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15327 String statusStr = IntentFilterVerificationInfo. 15328 getStatusStringFromValue(status); 15329 pw.println(prefix + "Status: " + statusStr); 15330 pw.println(); 15331 count++; 15332 } 15333 if (count == 0) { 15334 pw.println(prefix + "No configured app linkages."); 15335 pw.println(); 15336 } 15337 } 15338 } 15339 } 15340 } 15341 15342 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15343 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15344 if (packageName == null && permissionNames == null) { 15345 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15346 if (iperm == 0) { 15347 if (dumpState.onTitlePrinted()) 15348 pw.println(); 15349 pw.println("AppOp Permissions:"); 15350 } 15351 pw.print(" AppOp Permission "); 15352 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15353 pw.println(":"); 15354 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15355 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15356 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15357 } 15358 } 15359 } 15360 } 15361 15362 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15363 boolean printedSomething = false; 15364 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15365 if (packageName != null && !packageName.equals(p.info.packageName)) { 15366 continue; 15367 } 15368 if (!printedSomething) { 15369 if (dumpState.onTitlePrinted()) 15370 pw.println(); 15371 pw.println("Registered ContentProviders:"); 15372 printedSomething = true; 15373 } 15374 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15375 pw.print(" "); pw.println(p.toString()); 15376 } 15377 printedSomething = false; 15378 for (Map.Entry<String, PackageParser.Provider> entry : 15379 mProvidersByAuthority.entrySet()) { 15380 PackageParser.Provider p = entry.getValue(); 15381 if (packageName != null && !packageName.equals(p.info.packageName)) { 15382 continue; 15383 } 15384 if (!printedSomething) { 15385 if (dumpState.onTitlePrinted()) 15386 pw.println(); 15387 pw.println("ContentProvider Authorities:"); 15388 printedSomething = true; 15389 } 15390 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15391 pw.print(" "); pw.println(p.toString()); 15392 if (p.info != null && p.info.applicationInfo != null) { 15393 final String appInfo = p.info.applicationInfo.toString(); 15394 pw.print(" applicationInfo="); pw.println(appInfo); 15395 } 15396 } 15397 } 15398 15399 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15400 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15401 } 15402 15403 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15404 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15405 } 15406 15407 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15408 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15409 } 15410 15411 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15412 // XXX should handle packageName != null by dumping only install data that 15413 // the given package is involved with. 15414 if (dumpState.onTitlePrinted()) pw.println(); 15415 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15416 } 15417 15418 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15419 if (dumpState.onTitlePrinted()) pw.println(); 15420 mSettings.dumpReadMessagesLPr(pw, dumpState); 15421 15422 pw.println(); 15423 pw.println("Package warning messages:"); 15424 BufferedReader in = null; 15425 String line = null; 15426 try { 15427 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15428 while ((line = in.readLine()) != null) { 15429 if (line.contains("ignored: updated version")) continue; 15430 pw.println(line); 15431 } 15432 } catch (IOException ignored) { 15433 } finally { 15434 IoUtils.closeQuietly(in); 15435 } 15436 } 15437 15438 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15439 BufferedReader in = null; 15440 String line = null; 15441 try { 15442 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15443 while ((line = in.readLine()) != null) { 15444 if (line.contains("ignored: updated version")) continue; 15445 pw.print("msg,"); 15446 pw.println(line); 15447 } 15448 } catch (IOException ignored) { 15449 } finally { 15450 IoUtils.closeQuietly(in); 15451 } 15452 } 15453 } 15454 } 15455 15456 private String dumpDomainString(String packageName) { 15457 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15458 List<IntentFilter> filters = getAllIntentFilters(packageName); 15459 15460 ArraySet<String> result = new ArraySet<>(); 15461 if (iviList.size() > 0) { 15462 for (IntentFilterVerificationInfo ivi : iviList) { 15463 for (String host : ivi.getDomains()) { 15464 result.add(host); 15465 } 15466 } 15467 } 15468 if (filters != null && filters.size() > 0) { 15469 for (IntentFilter filter : filters) { 15470 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15471 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15472 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15473 result.addAll(filter.getHostsList()); 15474 } 15475 } 15476 } 15477 15478 StringBuilder sb = new StringBuilder(result.size() * 16); 15479 for (String domain : result) { 15480 if (sb.length() > 0) sb.append(" "); 15481 sb.append(domain); 15482 } 15483 return sb.toString(); 15484 } 15485 15486 // ------- apps on sdcard specific code ------- 15487 static final boolean DEBUG_SD_INSTALL = false; 15488 15489 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15490 15491 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15492 15493 private boolean mMediaMounted = false; 15494 15495 static String getEncryptKey() { 15496 try { 15497 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15498 SD_ENCRYPTION_KEYSTORE_NAME); 15499 if (sdEncKey == null) { 15500 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15501 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15502 if (sdEncKey == null) { 15503 Slog.e(TAG, "Failed to create encryption keys"); 15504 return null; 15505 } 15506 } 15507 return sdEncKey; 15508 } catch (NoSuchAlgorithmException nsae) { 15509 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15510 return null; 15511 } catch (IOException ioe) { 15512 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15513 return null; 15514 } 15515 } 15516 15517 /* 15518 * Update media status on PackageManager. 15519 */ 15520 @Override 15521 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15522 int callingUid = Binder.getCallingUid(); 15523 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15524 throw new SecurityException("Media status can only be updated by the system"); 15525 } 15526 // reader; this apparently protects mMediaMounted, but should probably 15527 // be a different lock in that case. 15528 synchronized (mPackages) { 15529 Log.i(TAG, "Updating external media status from " 15530 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15531 + (mediaStatus ? "mounted" : "unmounted")); 15532 if (DEBUG_SD_INSTALL) 15533 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15534 + ", mMediaMounted=" + mMediaMounted); 15535 if (mediaStatus == mMediaMounted) { 15536 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15537 : 0, -1); 15538 mHandler.sendMessage(msg); 15539 return; 15540 } 15541 mMediaMounted = mediaStatus; 15542 } 15543 // Queue up an async operation since the package installation may take a 15544 // little while. 15545 mHandler.post(new Runnable() { 15546 public void run() { 15547 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15548 } 15549 }); 15550 } 15551 15552 /** 15553 * Called by MountService when the initial ASECs to scan are available. 15554 * Should block until all the ASEC containers are finished being scanned. 15555 */ 15556 public void scanAvailableAsecs() { 15557 updateExternalMediaStatusInner(true, false, false); 15558 if (mShouldRestoreconData) { 15559 SELinuxMMAC.setRestoreconDone(); 15560 mShouldRestoreconData = false; 15561 } 15562 } 15563 15564 /* 15565 * Collect information of applications on external media, map them against 15566 * existing containers and update information based on current mount status. 15567 * Please note that we always have to report status if reportStatus has been 15568 * set to true especially when unloading packages. 15569 */ 15570 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15571 boolean externalStorage) { 15572 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15573 int[] uidArr = EmptyArray.INT; 15574 15575 final String[] list = PackageHelper.getSecureContainerList(); 15576 if (ArrayUtils.isEmpty(list)) { 15577 Log.i(TAG, "No secure containers found"); 15578 } else { 15579 // Process list of secure containers and categorize them 15580 // as active or stale based on their package internal state. 15581 15582 // reader 15583 synchronized (mPackages) { 15584 for (String cid : list) { 15585 // Leave stages untouched for now; installer service owns them 15586 if (PackageInstallerService.isStageName(cid)) continue; 15587 15588 if (DEBUG_SD_INSTALL) 15589 Log.i(TAG, "Processing container " + cid); 15590 String pkgName = getAsecPackageName(cid); 15591 if (pkgName == null) { 15592 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15593 continue; 15594 } 15595 if (DEBUG_SD_INSTALL) 15596 Log.i(TAG, "Looking for pkg : " + pkgName); 15597 15598 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15599 if (ps == null) { 15600 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15601 continue; 15602 } 15603 15604 /* 15605 * Skip packages that are not external if we're unmounting 15606 * external storage. 15607 */ 15608 if (externalStorage && !isMounted && !isExternal(ps)) { 15609 continue; 15610 } 15611 15612 final AsecInstallArgs args = new AsecInstallArgs(cid, 15613 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15614 // The package status is changed only if the code path 15615 // matches between settings and the container id. 15616 if (ps.codePathString != null 15617 && ps.codePathString.startsWith(args.getCodePath())) { 15618 if (DEBUG_SD_INSTALL) { 15619 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15620 + " at code path: " + ps.codePathString); 15621 } 15622 15623 // We do have a valid package installed on sdcard 15624 processCids.put(args, ps.codePathString); 15625 final int uid = ps.appId; 15626 if (uid != -1) { 15627 uidArr = ArrayUtils.appendInt(uidArr, uid); 15628 } 15629 } else { 15630 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15631 + ps.codePathString); 15632 } 15633 } 15634 } 15635 15636 Arrays.sort(uidArr); 15637 } 15638 15639 // Process packages with valid entries. 15640 if (isMounted) { 15641 if (DEBUG_SD_INSTALL) 15642 Log.i(TAG, "Loading packages"); 15643 loadMediaPackages(processCids, uidArr); 15644 startCleaningPackages(); 15645 mInstallerService.onSecureContainersAvailable(); 15646 } else { 15647 if (DEBUG_SD_INSTALL) 15648 Log.i(TAG, "Unloading packages"); 15649 unloadMediaPackages(processCids, uidArr, reportStatus); 15650 } 15651 } 15652 15653 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15654 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15655 final int size = infos.size(); 15656 final String[] packageNames = new String[size]; 15657 final int[] packageUids = new int[size]; 15658 for (int i = 0; i < size; i++) { 15659 final ApplicationInfo info = infos.get(i); 15660 packageNames[i] = info.packageName; 15661 packageUids[i] = info.uid; 15662 } 15663 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15664 finishedReceiver); 15665 } 15666 15667 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15668 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15669 sendResourcesChangedBroadcast(mediaStatus, replacing, 15670 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15671 } 15672 15673 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15674 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15675 int size = pkgList.length; 15676 if (size > 0) { 15677 // Send broadcasts here 15678 Bundle extras = new Bundle(); 15679 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15680 if (uidArr != null) { 15681 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15682 } 15683 if (replacing) { 15684 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15685 } 15686 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15687 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15688 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15689 } 15690 } 15691 15692 /* 15693 * Look at potentially valid container ids from processCids If package 15694 * information doesn't match the one on record or package scanning fails, 15695 * the cid is added to list of removeCids. We currently don't delete stale 15696 * containers. 15697 */ 15698 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15699 ArrayList<String> pkgList = new ArrayList<String>(); 15700 Set<AsecInstallArgs> keys = processCids.keySet(); 15701 15702 for (AsecInstallArgs args : keys) { 15703 String codePath = processCids.get(args); 15704 if (DEBUG_SD_INSTALL) 15705 Log.i(TAG, "Loading container : " + args.cid); 15706 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15707 try { 15708 // Make sure there are no container errors first. 15709 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15710 Slog.e(TAG, "Failed to mount cid : " + args.cid 15711 + " when installing from sdcard"); 15712 continue; 15713 } 15714 // Check code path here. 15715 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15716 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15717 + " does not match one in settings " + codePath); 15718 continue; 15719 } 15720 // Parse package 15721 int parseFlags = mDefParseFlags; 15722 if (args.isExternalAsec()) { 15723 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15724 } 15725 if (args.isFwdLocked()) { 15726 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15727 } 15728 15729 synchronized (mInstallLock) { 15730 PackageParser.Package pkg = null; 15731 try { 15732 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, 15733 UserHandle.SYSTEM); 15734 } catch (PackageManagerException e) { 15735 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15736 } 15737 // Scan the package 15738 if (pkg != null) { 15739 /* 15740 * TODO why is the lock being held? doPostInstall is 15741 * called in other places without the lock. This needs 15742 * to be straightened out. 15743 */ 15744 // writer 15745 synchronized (mPackages) { 15746 retCode = PackageManager.INSTALL_SUCCEEDED; 15747 pkgList.add(pkg.packageName); 15748 // Post process args 15749 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15750 pkg.applicationInfo.uid); 15751 } 15752 } else { 15753 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15754 } 15755 } 15756 15757 } finally { 15758 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15759 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15760 } 15761 } 15762 } 15763 // writer 15764 synchronized (mPackages) { 15765 // If the platform SDK has changed since the last time we booted, 15766 // we need to re-grant app permission to catch any new ones that 15767 // appear. This is really a hack, and means that apps can in some 15768 // cases get permissions that the user didn't initially explicitly 15769 // allow... it would be nice to have some better way to handle 15770 // this situation. 15771 final VersionInfo ver = mSettings.getExternalVersion(); 15772 15773 int updateFlags = UPDATE_PERMISSIONS_ALL; 15774 if (ver.sdkVersion != mSdkVersion) { 15775 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15776 + mSdkVersion + "; regranting permissions for external"); 15777 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15778 } 15779 updatePermissionsLPw(null, null, updateFlags); 15780 15781 // Yay, everything is now upgraded 15782 ver.forceCurrent(); 15783 15784 // can downgrade to reader 15785 // Persist settings 15786 mSettings.writeLPr(); 15787 } 15788 // Send a broadcast to let everyone know we are done processing 15789 if (pkgList.size() > 0) { 15790 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15791 } 15792 } 15793 15794 /* 15795 * Utility method to unload a list of specified containers 15796 */ 15797 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15798 // Just unmount all valid containers. 15799 for (AsecInstallArgs arg : cidArgs) { 15800 synchronized (mInstallLock) { 15801 arg.doPostDeleteLI(false); 15802 } 15803 } 15804 } 15805 15806 /* 15807 * Unload packages mounted on external media. This involves deleting package 15808 * data from internal structures, sending broadcasts about diabled packages, 15809 * gc'ing to free up references, unmounting all secure containers 15810 * corresponding to packages on external media, and posting a 15811 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15812 * that we always have to post this message if status has been requested no 15813 * matter what. 15814 */ 15815 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15816 final boolean reportStatus) { 15817 if (DEBUG_SD_INSTALL) 15818 Log.i(TAG, "unloading media packages"); 15819 ArrayList<String> pkgList = new ArrayList<String>(); 15820 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15821 final Set<AsecInstallArgs> keys = processCids.keySet(); 15822 for (AsecInstallArgs args : keys) { 15823 String pkgName = args.getPackageName(); 15824 if (DEBUG_SD_INSTALL) 15825 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15826 // Delete package internally 15827 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15828 synchronized (mInstallLock) { 15829 boolean res = deletePackageLI(pkgName, null, false, null, null, 15830 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15831 if (res) { 15832 pkgList.add(pkgName); 15833 } else { 15834 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15835 failedList.add(args); 15836 } 15837 } 15838 } 15839 15840 // reader 15841 synchronized (mPackages) { 15842 // We didn't update the settings after removing each package; 15843 // write them now for all packages. 15844 mSettings.writeLPr(); 15845 } 15846 15847 // We have to absolutely send UPDATED_MEDIA_STATUS only 15848 // after confirming that all the receivers processed the ordered 15849 // broadcast when packages get disabled, force a gc to clean things up. 15850 // and unload all the containers. 15851 if (pkgList.size() > 0) { 15852 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15853 new IIntentReceiver.Stub() { 15854 public void performReceive(Intent intent, int resultCode, String data, 15855 Bundle extras, boolean ordered, boolean sticky, 15856 int sendingUser) throws RemoteException { 15857 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15858 reportStatus ? 1 : 0, 1, keys); 15859 mHandler.sendMessage(msg); 15860 } 15861 }); 15862 } else { 15863 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15864 keys); 15865 mHandler.sendMessage(msg); 15866 } 15867 } 15868 15869 private void loadPrivatePackages(final VolumeInfo vol) { 15870 mHandler.post(new Runnable() { 15871 @Override 15872 public void run() { 15873 loadPrivatePackagesInner(vol); 15874 } 15875 }); 15876 } 15877 15878 private void loadPrivatePackagesInner(VolumeInfo vol) { 15879 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15880 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15881 15882 final VersionInfo ver; 15883 final List<PackageSetting> packages; 15884 synchronized (mPackages) { 15885 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15886 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15887 } 15888 15889 for (PackageSetting ps : packages) { 15890 synchronized (mInstallLock) { 15891 final PackageParser.Package pkg; 15892 try { 15893 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, 15894 UserHandle.SYSTEM); 15895 loaded.add(pkg.applicationInfo); 15896 } catch (PackageManagerException e) { 15897 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15898 } 15899 15900 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15901 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15902 } 15903 } 15904 } 15905 15906 synchronized (mPackages) { 15907 int updateFlags = UPDATE_PERMISSIONS_ALL; 15908 if (ver.sdkVersion != mSdkVersion) { 15909 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15910 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15911 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15912 } 15913 updatePermissionsLPw(null, null, updateFlags); 15914 15915 // Yay, everything is now upgraded 15916 ver.forceCurrent(); 15917 15918 mSettings.writeLPr(); 15919 } 15920 15921 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15922 sendResourcesChangedBroadcast(true, false, loaded, null); 15923 } 15924 15925 private void unloadPrivatePackages(final VolumeInfo vol) { 15926 mHandler.post(new Runnable() { 15927 @Override 15928 public void run() { 15929 unloadPrivatePackagesInner(vol); 15930 } 15931 }); 15932 } 15933 15934 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15935 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15936 synchronized (mInstallLock) { 15937 synchronized (mPackages) { 15938 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15939 for (PackageSetting ps : packages) { 15940 if (ps.pkg == null) continue; 15941 15942 final ApplicationInfo info = ps.pkg.applicationInfo; 15943 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15944 if (deletePackageLI(ps.name, null, false, null, null, 15945 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15946 unloaded.add(info); 15947 } else { 15948 Slog.w(TAG, "Failed to unload " + ps.codePath); 15949 } 15950 } 15951 15952 mSettings.writeLPr(); 15953 } 15954 } 15955 15956 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15957 sendResourcesChangedBroadcast(false, false, unloaded, null); 15958 } 15959 15960 /** 15961 * Examine all users present on given mounted volume, and destroy data 15962 * belonging to users that are no longer valid, or whose user ID has been 15963 * recycled. 15964 */ 15965 private void reconcileUsers(String volumeUuid) { 15966 final File[] files = FileUtils 15967 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15968 for (File file : files) { 15969 if (!file.isDirectory()) continue; 15970 15971 final int userId; 15972 final UserInfo info; 15973 try { 15974 userId = Integer.parseInt(file.getName()); 15975 info = sUserManager.getUserInfo(userId); 15976 } catch (NumberFormatException e) { 15977 Slog.w(TAG, "Invalid user directory " + file); 15978 continue; 15979 } 15980 15981 boolean destroyUser = false; 15982 if (info == null) { 15983 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15984 + " because no matching user was found"); 15985 destroyUser = true; 15986 } else { 15987 try { 15988 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15989 } catch (IOException e) { 15990 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15991 + " because we failed to enforce serial number: " + e); 15992 destroyUser = true; 15993 } 15994 } 15995 15996 if (destroyUser) { 15997 synchronized (mInstallLock) { 15998 mInstaller.removeUserDataDirs(volumeUuid, userId); 15999 } 16000 } 16001 } 16002 16003 final UserManager um = mContext.getSystemService(UserManager.class); 16004 for (UserInfo user : um.getUsers()) { 16005 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16006 if (userDir.exists()) continue; 16007 16008 try { 16009 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 16010 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16011 } catch (IOException e) { 16012 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16013 } 16014 } 16015 } 16016 16017 /** 16018 * Examine all apps present on given mounted volume, and destroy apps that 16019 * aren't expected, either due to uninstallation or reinstallation on 16020 * another volume. 16021 */ 16022 private void reconcileApps(String volumeUuid) { 16023 final File[] files = FileUtils 16024 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16025 for (File file : files) { 16026 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16027 && !PackageInstallerService.isStageName(file.getName()); 16028 if (!isPackage) { 16029 // Ignore entries which are not packages 16030 continue; 16031 } 16032 16033 boolean destroyApp = false; 16034 String packageName = null; 16035 try { 16036 final PackageLite pkg = PackageParser.parsePackageLite(file, 16037 PackageParser.PARSE_MUST_BE_APK); 16038 packageName = pkg.packageName; 16039 16040 synchronized (mPackages) { 16041 final PackageSetting ps = mSettings.mPackages.get(packageName); 16042 if (ps == null) { 16043 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16044 + volumeUuid + " because we found no install record"); 16045 destroyApp = true; 16046 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16047 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16048 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16049 destroyApp = true; 16050 } 16051 } 16052 16053 } catch (PackageParserException e) { 16054 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16055 destroyApp = true; 16056 } 16057 16058 if (destroyApp) { 16059 synchronized (mInstallLock) { 16060 if (packageName != null) { 16061 removeDataDirsLI(volumeUuid, packageName); 16062 } 16063 if (file.isDirectory()) { 16064 mInstaller.rmPackageDir(file.getAbsolutePath()); 16065 } else { 16066 file.delete(); 16067 } 16068 } 16069 } 16070 } 16071 } 16072 16073 private void unfreezePackage(String packageName) { 16074 synchronized (mPackages) { 16075 final PackageSetting ps = mSettings.mPackages.get(packageName); 16076 if (ps != null) { 16077 ps.frozen = false; 16078 } 16079 } 16080 } 16081 16082 @Override 16083 public int movePackage(final String packageName, final String volumeUuid) { 16084 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16085 16086 final int moveId = mNextMoveId.getAndIncrement(); 16087 try { 16088 movePackageInternal(packageName, volumeUuid, moveId); 16089 } catch (PackageManagerException e) { 16090 Slog.w(TAG, "Failed to move " + packageName, e); 16091 mMoveCallbacks.notifyStatusChanged(moveId, 16092 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16093 } 16094 return moveId; 16095 } 16096 16097 private void movePackageInternal(final String packageName, final String volumeUuid, 16098 final int moveId) throws PackageManagerException { 16099 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16100 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16101 final PackageManager pm = mContext.getPackageManager(); 16102 16103 final boolean currentAsec; 16104 final String currentVolumeUuid; 16105 final File codeFile; 16106 final String installerPackageName; 16107 final String packageAbiOverride; 16108 final int appId; 16109 final String seinfo; 16110 final String label; 16111 16112 // reader 16113 synchronized (mPackages) { 16114 final PackageParser.Package pkg = mPackages.get(packageName); 16115 final PackageSetting ps = mSettings.mPackages.get(packageName); 16116 if (pkg == null || ps == null) { 16117 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16118 } 16119 16120 if (pkg.applicationInfo.isSystemApp()) { 16121 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16122 "Cannot move system application"); 16123 } 16124 16125 if (pkg.applicationInfo.isExternalAsec()) { 16126 currentAsec = true; 16127 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16128 } else if (pkg.applicationInfo.isForwardLocked()) { 16129 currentAsec = true; 16130 currentVolumeUuid = "forward_locked"; 16131 } else { 16132 currentAsec = false; 16133 currentVolumeUuid = ps.volumeUuid; 16134 16135 final File probe = new File(pkg.codePath); 16136 final File probeOat = new File(probe, "oat"); 16137 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16138 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16139 "Move only supported for modern cluster style installs"); 16140 } 16141 } 16142 16143 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16144 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16145 "Package already moved to " + volumeUuid); 16146 } 16147 16148 if (ps.frozen) { 16149 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16150 "Failed to move already frozen package"); 16151 } 16152 ps.frozen = true; 16153 16154 codeFile = new File(pkg.codePath); 16155 installerPackageName = ps.installerPackageName; 16156 packageAbiOverride = ps.cpuAbiOverrideString; 16157 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16158 seinfo = pkg.applicationInfo.seinfo; 16159 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16160 } 16161 16162 // Now that we're guarded by frozen state, kill app during move 16163 final long token = Binder.clearCallingIdentity(); 16164 try { 16165 killApplication(packageName, appId, "move pkg"); 16166 } finally { 16167 Binder.restoreCallingIdentity(token); 16168 } 16169 16170 final Bundle extras = new Bundle(); 16171 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16172 extras.putString(Intent.EXTRA_TITLE, label); 16173 mMoveCallbacks.notifyCreated(moveId, extras); 16174 16175 int installFlags; 16176 final boolean moveCompleteApp; 16177 final File measurePath; 16178 16179 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16180 installFlags = INSTALL_INTERNAL; 16181 moveCompleteApp = !currentAsec; 16182 measurePath = Environment.getDataAppDirectory(volumeUuid); 16183 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16184 installFlags = INSTALL_EXTERNAL; 16185 moveCompleteApp = false; 16186 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16187 } else { 16188 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16189 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16190 || !volume.isMountedWritable()) { 16191 unfreezePackage(packageName); 16192 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16193 "Move location not mounted private volume"); 16194 } 16195 16196 Preconditions.checkState(!currentAsec); 16197 16198 installFlags = INSTALL_INTERNAL; 16199 moveCompleteApp = true; 16200 measurePath = Environment.getDataAppDirectory(volumeUuid); 16201 } 16202 16203 final PackageStats stats = new PackageStats(null, -1); 16204 synchronized (mInstaller) { 16205 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16206 unfreezePackage(packageName); 16207 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16208 "Failed to measure package size"); 16209 } 16210 } 16211 16212 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16213 + stats.dataSize); 16214 16215 final long startFreeBytes = measurePath.getFreeSpace(); 16216 final long sizeBytes; 16217 if (moveCompleteApp) { 16218 sizeBytes = stats.codeSize + stats.dataSize; 16219 } else { 16220 sizeBytes = stats.codeSize; 16221 } 16222 16223 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16224 unfreezePackage(packageName); 16225 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16226 "Not enough free space to move"); 16227 } 16228 16229 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16230 16231 final CountDownLatch installedLatch = new CountDownLatch(1); 16232 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16233 @Override 16234 public void onUserActionRequired(Intent intent) throws RemoteException { 16235 throw new IllegalStateException(); 16236 } 16237 16238 @Override 16239 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16240 Bundle extras) throws RemoteException { 16241 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16242 + PackageManager.installStatusToString(returnCode, msg)); 16243 16244 installedLatch.countDown(); 16245 16246 // Regardless of success or failure of the move operation, 16247 // always unfreeze the package 16248 unfreezePackage(packageName); 16249 16250 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16251 switch (status) { 16252 case PackageInstaller.STATUS_SUCCESS: 16253 mMoveCallbacks.notifyStatusChanged(moveId, 16254 PackageManager.MOVE_SUCCEEDED); 16255 break; 16256 case PackageInstaller.STATUS_FAILURE_STORAGE: 16257 mMoveCallbacks.notifyStatusChanged(moveId, 16258 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16259 break; 16260 default: 16261 mMoveCallbacks.notifyStatusChanged(moveId, 16262 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16263 break; 16264 } 16265 } 16266 }; 16267 16268 final MoveInfo move; 16269 if (moveCompleteApp) { 16270 // Kick off a thread to report progress estimates 16271 new Thread() { 16272 @Override 16273 public void run() { 16274 while (true) { 16275 try { 16276 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16277 break; 16278 } 16279 } catch (InterruptedException ignored) { 16280 } 16281 16282 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16283 final int progress = 10 + (int) MathUtils.constrain( 16284 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16285 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16286 } 16287 } 16288 }.start(); 16289 16290 final String dataAppName = codeFile.getName(); 16291 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16292 dataAppName, appId, seinfo); 16293 } else { 16294 move = null; 16295 } 16296 16297 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16298 16299 final Message msg = mHandler.obtainMessage(INIT_COPY); 16300 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16301 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16302 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16303 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16304 msg.obj = params; 16305 16306 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16307 System.identityHashCode(msg.obj)); 16308 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16309 System.identityHashCode(msg.obj)); 16310 16311 mHandler.sendMessage(msg); 16312 } 16313 16314 @Override 16315 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16316 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16317 16318 final int realMoveId = mNextMoveId.getAndIncrement(); 16319 final Bundle extras = new Bundle(); 16320 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16321 mMoveCallbacks.notifyCreated(realMoveId, extras); 16322 16323 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16324 @Override 16325 public void onCreated(int moveId, Bundle extras) { 16326 // Ignored 16327 } 16328 16329 @Override 16330 public void onStatusChanged(int moveId, int status, long estMillis) { 16331 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16332 } 16333 }; 16334 16335 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16336 storage.setPrimaryStorageUuid(volumeUuid, callback); 16337 return realMoveId; 16338 } 16339 16340 @Override 16341 public int getMoveStatus(int moveId) { 16342 mContext.enforceCallingOrSelfPermission( 16343 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16344 return mMoveCallbacks.mLastStatus.get(moveId); 16345 } 16346 16347 @Override 16348 public void registerMoveCallback(IPackageMoveObserver callback) { 16349 mContext.enforceCallingOrSelfPermission( 16350 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16351 mMoveCallbacks.register(callback); 16352 } 16353 16354 @Override 16355 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16356 mContext.enforceCallingOrSelfPermission( 16357 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16358 mMoveCallbacks.unregister(callback); 16359 } 16360 16361 @Override 16362 public boolean setInstallLocation(int loc) { 16363 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16364 null); 16365 if (getInstallLocation() == loc) { 16366 return true; 16367 } 16368 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16369 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16370 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16371 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16372 return true; 16373 } 16374 return false; 16375 } 16376 16377 @Override 16378 public int getInstallLocation() { 16379 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16380 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16381 PackageHelper.APP_INSTALL_AUTO); 16382 } 16383 16384 /** Called by UserManagerService */ 16385 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16386 mDirtyUsers.remove(userHandle); 16387 mSettings.removeUserLPw(userHandle); 16388 mPendingBroadcasts.remove(userHandle); 16389 if (mInstaller != null) { 16390 // Technically, we shouldn't be doing this with the package lock 16391 // held. However, this is very rare, and there is already so much 16392 // other disk I/O going on, that we'll let it slide for now. 16393 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16394 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16395 final String volumeUuid = vol.getFsUuid(); 16396 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16397 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16398 } 16399 } 16400 mUserNeedsBadging.delete(userHandle); 16401 removeUnusedPackagesLILPw(userManager, userHandle); 16402 } 16403 16404 /** 16405 * We're removing userHandle and would like to remove any downloaded packages 16406 * that are no longer in use by any other user. 16407 * @param userHandle the user being removed 16408 */ 16409 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16410 final boolean DEBUG_CLEAN_APKS = false; 16411 int [] users = userManager.getUserIdsLPr(); 16412 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16413 while (psit.hasNext()) { 16414 PackageSetting ps = psit.next(); 16415 if (ps.pkg == null) { 16416 continue; 16417 } 16418 final String packageName = ps.pkg.packageName; 16419 // Skip over if system app 16420 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16421 continue; 16422 } 16423 if (DEBUG_CLEAN_APKS) { 16424 Slog.i(TAG, "Checking package " + packageName); 16425 } 16426 boolean keep = false; 16427 for (int i = 0; i < users.length; i++) { 16428 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16429 keep = true; 16430 if (DEBUG_CLEAN_APKS) { 16431 Slog.i(TAG, " Keeping package " + packageName + " for user " 16432 + users[i]); 16433 } 16434 break; 16435 } 16436 } 16437 if (!keep) { 16438 if (DEBUG_CLEAN_APKS) { 16439 Slog.i(TAG, " Removing package " + packageName); 16440 } 16441 mHandler.post(new Runnable() { 16442 public void run() { 16443 deletePackageX(packageName, userHandle, 0); 16444 } //end run 16445 }); 16446 } 16447 } 16448 } 16449 16450 /** Called by UserManagerService */ 16451 void createNewUserLILPw(int userHandle) { 16452 if (mInstaller != null) { 16453 mInstaller.createUserConfig(userHandle); 16454 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16455 applyFactoryDefaultBrowserLPw(userHandle); 16456 primeDomainVerificationsLPw(userHandle); 16457 } 16458 } 16459 16460 void newUserCreated(final int userHandle) { 16461 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16462 } 16463 16464 @Override 16465 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16466 mContext.enforceCallingOrSelfPermission( 16467 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16468 "Only package verification agents can read the verifier device identity"); 16469 16470 synchronized (mPackages) { 16471 return mSettings.getVerifierDeviceIdentityLPw(); 16472 } 16473 } 16474 16475 @Override 16476 public void setPermissionEnforced(String permission, boolean enforced) { 16477 // TODO: Now that we no longer change GID for storage, this should to away. 16478 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16479 "setPermissionEnforced"); 16480 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16481 synchronized (mPackages) { 16482 if (mSettings.mReadExternalStorageEnforced == null 16483 || mSettings.mReadExternalStorageEnforced != enforced) { 16484 mSettings.mReadExternalStorageEnforced = enforced; 16485 mSettings.writeLPr(); 16486 } 16487 } 16488 // kill any non-foreground processes so we restart them and 16489 // grant/revoke the GID. 16490 final IActivityManager am = ActivityManagerNative.getDefault(); 16491 if (am != null) { 16492 final long token = Binder.clearCallingIdentity(); 16493 try { 16494 am.killProcessesBelowForeground("setPermissionEnforcement"); 16495 } catch (RemoteException e) { 16496 } finally { 16497 Binder.restoreCallingIdentity(token); 16498 } 16499 } 16500 } else { 16501 throw new IllegalArgumentException("No selective enforcement for " + permission); 16502 } 16503 } 16504 16505 @Override 16506 @Deprecated 16507 public boolean isPermissionEnforced(String permission) { 16508 return true; 16509 } 16510 16511 @Override 16512 public boolean isStorageLow() { 16513 final long token = Binder.clearCallingIdentity(); 16514 try { 16515 final DeviceStorageMonitorInternal 16516 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16517 if (dsm != null) { 16518 return dsm.isMemoryLow(); 16519 } else { 16520 return false; 16521 } 16522 } finally { 16523 Binder.restoreCallingIdentity(token); 16524 } 16525 } 16526 16527 @Override 16528 public IPackageInstaller getPackageInstaller() { 16529 return mInstallerService; 16530 } 16531 16532 private boolean userNeedsBadging(int userId) { 16533 int index = mUserNeedsBadging.indexOfKey(userId); 16534 if (index < 0) { 16535 final UserInfo userInfo; 16536 final long token = Binder.clearCallingIdentity(); 16537 try { 16538 userInfo = sUserManager.getUserInfo(userId); 16539 } finally { 16540 Binder.restoreCallingIdentity(token); 16541 } 16542 final boolean b; 16543 if (userInfo != null && userInfo.isManagedProfile()) { 16544 b = true; 16545 } else { 16546 b = false; 16547 } 16548 mUserNeedsBadging.put(userId, b); 16549 return b; 16550 } 16551 return mUserNeedsBadging.valueAt(index); 16552 } 16553 16554 @Override 16555 public KeySet getKeySetByAlias(String packageName, String alias) { 16556 if (packageName == null || alias == null) { 16557 return null; 16558 } 16559 synchronized(mPackages) { 16560 final PackageParser.Package pkg = mPackages.get(packageName); 16561 if (pkg == null) { 16562 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16563 throw new IllegalArgumentException("Unknown package: " + packageName); 16564 } 16565 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16566 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16567 } 16568 } 16569 16570 @Override 16571 public KeySet getSigningKeySet(String packageName) { 16572 if (packageName == null) { 16573 return null; 16574 } 16575 synchronized(mPackages) { 16576 final PackageParser.Package pkg = mPackages.get(packageName); 16577 if (pkg == null) { 16578 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16579 throw new IllegalArgumentException("Unknown package: " + packageName); 16580 } 16581 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16582 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16583 throw new SecurityException("May not access signing KeySet of other apps."); 16584 } 16585 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16586 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16587 } 16588 } 16589 16590 @Override 16591 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16592 if (packageName == null || ks == null) { 16593 return false; 16594 } 16595 synchronized(mPackages) { 16596 final PackageParser.Package pkg = mPackages.get(packageName); 16597 if (pkg == null) { 16598 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16599 throw new IllegalArgumentException("Unknown package: " + packageName); 16600 } 16601 IBinder ksh = ks.getToken(); 16602 if (ksh instanceof KeySetHandle) { 16603 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16604 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16605 } 16606 return false; 16607 } 16608 } 16609 16610 @Override 16611 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16612 if (packageName == null || ks == null) { 16613 return false; 16614 } 16615 synchronized(mPackages) { 16616 final PackageParser.Package pkg = mPackages.get(packageName); 16617 if (pkg == null) { 16618 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16619 throw new IllegalArgumentException("Unknown package: " + packageName); 16620 } 16621 IBinder ksh = ks.getToken(); 16622 if (ksh instanceof KeySetHandle) { 16623 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16624 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16625 } 16626 return false; 16627 } 16628 } 16629 16630 public void getUsageStatsIfNoPackageUsageInfo() { 16631 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16632 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16633 if (usm == null) { 16634 throw new IllegalStateException("UsageStatsManager must be initialized"); 16635 } 16636 long now = System.currentTimeMillis(); 16637 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16638 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16639 String packageName = entry.getKey(); 16640 PackageParser.Package pkg = mPackages.get(packageName); 16641 if (pkg == null) { 16642 continue; 16643 } 16644 UsageStats usage = entry.getValue(); 16645 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16646 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16647 } 16648 } 16649 } 16650 16651 /** 16652 * Check and throw if the given before/after packages would be considered a 16653 * downgrade. 16654 */ 16655 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16656 throws PackageManagerException { 16657 if (after.versionCode < before.mVersionCode) { 16658 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16659 "Update version code " + after.versionCode + " is older than current " 16660 + before.mVersionCode); 16661 } else if (after.versionCode == before.mVersionCode) { 16662 if (after.baseRevisionCode < before.baseRevisionCode) { 16663 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16664 "Update base revision code " + after.baseRevisionCode 16665 + " is older than current " + before.baseRevisionCode); 16666 } 16667 16668 if (!ArrayUtils.isEmpty(after.splitNames)) { 16669 for (int i = 0; i < after.splitNames.length; i++) { 16670 final String splitName = after.splitNames[i]; 16671 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16672 if (j != -1) { 16673 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16674 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16675 "Update split " + splitName + " revision code " 16676 + after.splitRevisionCodes[i] + " is older than current " 16677 + before.splitRevisionCodes[j]); 16678 } 16679 } 16680 } 16681 } 16682 } 16683 } 16684 16685 private static class MoveCallbacks extends Handler { 16686 private static final int MSG_CREATED = 1; 16687 private static final int MSG_STATUS_CHANGED = 2; 16688 16689 private final RemoteCallbackList<IPackageMoveObserver> 16690 mCallbacks = new RemoteCallbackList<>(); 16691 16692 private final SparseIntArray mLastStatus = new SparseIntArray(); 16693 16694 public MoveCallbacks(Looper looper) { 16695 super(looper); 16696 } 16697 16698 public void register(IPackageMoveObserver callback) { 16699 mCallbacks.register(callback); 16700 } 16701 16702 public void unregister(IPackageMoveObserver callback) { 16703 mCallbacks.unregister(callback); 16704 } 16705 16706 @Override 16707 public void handleMessage(Message msg) { 16708 final SomeArgs args = (SomeArgs) msg.obj; 16709 final int n = mCallbacks.beginBroadcast(); 16710 for (int i = 0; i < n; i++) { 16711 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16712 try { 16713 invokeCallback(callback, msg.what, args); 16714 } catch (RemoteException ignored) { 16715 } 16716 } 16717 mCallbacks.finishBroadcast(); 16718 args.recycle(); 16719 } 16720 16721 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16722 throws RemoteException { 16723 switch (what) { 16724 case MSG_CREATED: { 16725 callback.onCreated(args.argi1, (Bundle) args.arg2); 16726 break; 16727 } 16728 case MSG_STATUS_CHANGED: { 16729 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16730 break; 16731 } 16732 } 16733 } 16734 16735 private void notifyCreated(int moveId, Bundle extras) { 16736 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16737 16738 final SomeArgs args = SomeArgs.obtain(); 16739 args.argi1 = moveId; 16740 args.arg2 = extras; 16741 obtainMessage(MSG_CREATED, args).sendToTarget(); 16742 } 16743 16744 private void notifyStatusChanged(int moveId, int status) { 16745 notifyStatusChanged(moveId, status, -1); 16746 } 16747 16748 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16749 Slog.v(TAG, "Move " + moveId + " status " + status); 16750 16751 final SomeArgs args = SomeArgs.obtain(); 16752 args.argi1 = moveId; 16753 args.argi2 = status; 16754 args.arg3 = estMillis; 16755 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16756 16757 synchronized (mLastStatus) { 16758 mLastStatus.put(moveId, status); 16759 } 16760 } 16761 } 16762 16763 private final class OnPermissionChangeListeners extends Handler { 16764 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16765 16766 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16767 new RemoteCallbackList<>(); 16768 16769 public OnPermissionChangeListeners(Looper looper) { 16770 super(looper); 16771 } 16772 16773 @Override 16774 public void handleMessage(Message msg) { 16775 switch (msg.what) { 16776 case MSG_ON_PERMISSIONS_CHANGED: { 16777 final int uid = msg.arg1; 16778 handleOnPermissionsChanged(uid); 16779 } break; 16780 } 16781 } 16782 16783 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16784 mPermissionListeners.register(listener); 16785 16786 } 16787 16788 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16789 mPermissionListeners.unregister(listener); 16790 } 16791 16792 public void onPermissionsChanged(int uid) { 16793 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16794 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16795 } 16796 } 16797 16798 private void handleOnPermissionsChanged(int uid) { 16799 final int count = mPermissionListeners.beginBroadcast(); 16800 try { 16801 for (int i = 0; i < count; i++) { 16802 IOnPermissionsChangeListener callback = mPermissionListeners 16803 .getBroadcastItem(i); 16804 try { 16805 callback.onPermissionsChanged(uid); 16806 } catch (RemoteException e) { 16807 Log.e(TAG, "Permission listener is dead", e); 16808 } 16809 } 16810 } finally { 16811 mPermissionListeners.finishBroadcast(); 16812 } 16813 } 16814 } 16815 16816 private class PackageManagerInternalImpl extends PackageManagerInternal { 16817 @Override 16818 public void setLocationPackagesProvider(PackagesProvider provider) { 16819 synchronized (mPackages) { 16820 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16821 } 16822 } 16823 16824 @Override 16825 public void setImePackagesProvider(PackagesProvider provider) { 16826 synchronized (mPackages) { 16827 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16828 } 16829 } 16830 16831 @Override 16832 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16833 synchronized (mPackages) { 16834 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16835 } 16836 } 16837 16838 @Override 16839 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16840 synchronized (mPackages) { 16841 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16842 } 16843 } 16844 16845 @Override 16846 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16847 synchronized (mPackages) { 16848 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16849 } 16850 } 16851 16852 @Override 16853 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16854 synchronized (mPackages) { 16855 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16856 } 16857 } 16858 16859 @Override 16860 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16861 synchronized (mPackages) { 16862 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16863 } 16864 } 16865 16866 @Override 16867 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16868 synchronized (mPackages) { 16869 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16870 packageName, userId); 16871 } 16872 } 16873 16874 @Override 16875 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16876 synchronized (mPackages) { 16877 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16878 packageName, userId); 16879 } 16880 } 16881 @Override 16882 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16883 synchronized (mPackages) { 16884 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16885 packageName, userId); 16886 } 16887 } 16888 } 16889 16890 @Override 16891 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16892 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16893 synchronized (mPackages) { 16894 final long identity = Binder.clearCallingIdentity(); 16895 try { 16896 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16897 packageNames, userId); 16898 } finally { 16899 Binder.restoreCallingIdentity(identity); 16900 } 16901 } 16902 } 16903 16904 private static void enforceSystemOrPhoneCaller(String tag) { 16905 int callingUid = Binder.getCallingUid(); 16906 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16907 throw new SecurityException( 16908 "Cannot call " + tag + " from UID " + callingUid); 16909 } 16910 } 16911} 16912