PackageManagerService.java revision c84161847aea15a258ca97c7e7fb90caff421d2e
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.InstructionSets.getAppDexInstructionSets; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 81import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 82import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 86 87import android.Manifest; 88import android.app.ActivityManager; 89import android.app.ActivityManagerNative; 90import android.app.AppGlobals; 91import android.app.IActivityManager; 92import android.app.admin.IDevicePolicyManager; 93import android.app.backup.IBackupManager; 94import android.app.usage.UsageStats; 95import android.app.usage.UsageStatsManager; 96import android.content.BroadcastReceiver; 97import android.content.ComponentName; 98import android.content.Context; 99import android.content.IIntentReceiver; 100import android.content.Intent; 101import android.content.IntentFilter; 102import android.content.IntentSender; 103import android.content.IntentSender.SendIntentException; 104import android.content.ServiceConnection; 105import android.content.pm.ActivityInfo; 106import android.content.pm.ApplicationInfo; 107import android.content.pm.FeatureInfo; 108import android.content.pm.IOnPermissionsChangeListener; 109import android.content.pm.IPackageDataObserver; 110import android.content.pm.IPackageDeleteObserver; 111import android.content.pm.IPackageDeleteObserver2; 112import android.content.pm.IPackageInstallObserver2; 113import android.content.pm.IPackageInstaller; 114import android.content.pm.IPackageManager; 115import android.content.pm.IPackageMoveObserver; 116import android.content.pm.IPackageStatsObserver; 117import android.content.pm.InstrumentationInfo; 118import android.content.pm.IntentFilterVerificationInfo; 119import android.content.pm.KeySet; 120import android.content.pm.ManifestDigest; 121import android.content.pm.PackageCleanItem; 122import android.content.pm.PackageInfo; 123import android.content.pm.PackageInfoLite; 124import android.content.pm.PackageInstaller; 125import android.content.pm.PackageManager; 126import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 127import android.content.pm.PackageManagerInternal; 128import android.content.pm.PackageParser; 129import android.content.pm.PackageParser.ActivityIntentInfo; 130import android.content.pm.PackageParser.PackageLite; 131import android.content.pm.PackageParser.PackageParserException; 132import android.content.pm.PackageStats; 133import android.content.pm.PackageUserState; 134import android.content.pm.ParceledListSlice; 135import android.content.pm.PermissionGroupInfo; 136import android.content.pm.PermissionInfo; 137import android.content.pm.ProviderInfo; 138import android.content.pm.ResolveInfo; 139import android.content.pm.ServiceInfo; 140import android.content.pm.Signature; 141import android.content.pm.UserInfo; 142import android.content.pm.VerificationParams; 143import android.content.pm.VerifierDeviceIdentity; 144import android.content.pm.VerifierInfo; 145import android.content.res.Resources; 146import android.hardware.display.DisplayManager; 147import android.net.Uri; 148import android.os.Debug; 149import android.os.Binder; 150import android.os.Build; 151import android.os.Bundle; 152import android.os.Environment; 153import android.os.Environment.UserEnvironment; 154import android.os.FileUtils; 155import android.os.Handler; 156import android.os.IBinder; 157import android.os.Looper; 158import android.os.Message; 159import android.os.Parcel; 160import android.os.ParcelFileDescriptor; 161import android.os.Process; 162import android.os.RemoteCallbackList; 163import android.os.RemoteException; 164import android.os.SELinux; 165import android.os.ServiceManager; 166import android.os.SystemClock; 167import android.os.SystemProperties; 168import android.os.Trace; 169import android.os.UserHandle; 170import android.os.UserManager; 171import android.os.storage.IMountService; 172import android.os.storage.MountServiceInternal; 173import android.os.storage.StorageEventListener; 174import android.os.storage.StorageManager; 175import android.os.storage.VolumeInfo; 176import android.os.storage.VolumeRecord; 177import android.security.KeyStore; 178import android.security.SystemKeyStore; 179import android.system.ErrnoException; 180import android.system.Os; 181import android.system.StructStat; 182import android.text.TextUtils; 183import android.text.format.DateUtils; 184import android.util.ArrayMap; 185import android.util.ArraySet; 186import android.util.AtomicFile; 187import android.util.DisplayMetrics; 188import android.util.EventLog; 189import android.util.ExceptionUtils; 190import android.util.Log; 191import android.util.LogPrinter; 192import android.util.MathUtils; 193import android.util.PrintStreamPrinter; 194import android.util.Slog; 195import android.util.SparseArray; 196import android.util.SparseBooleanArray; 197import android.util.SparseIntArray; 198import android.util.Xml; 199import android.view.Display; 200 201import dalvik.system.DexFile; 202import dalvik.system.VMRuntime; 203 204import libcore.io.IoUtils; 205import libcore.util.EmptyArray; 206 207import com.android.internal.R; 208import com.android.internal.annotations.GuardedBy; 209import com.android.internal.app.IMediaContainerService; 210import com.android.internal.app.ResolverActivity; 211import com.android.internal.content.NativeLibraryHelper; 212import com.android.internal.content.PackageHelper; 213import com.android.internal.os.IParcelFileDescriptorFactory; 214import com.android.internal.os.SomeArgs; 215import com.android.internal.os.Zygote; 216import com.android.internal.util.ArrayUtils; 217import com.android.internal.util.FastPrintWriter; 218import com.android.internal.util.FastXmlSerializer; 219import com.android.internal.util.IndentingPrintWriter; 220import com.android.internal.util.Preconditions; 221import com.android.server.EventLogTags; 222import com.android.server.FgThread; 223import com.android.server.IntentResolver; 224import com.android.server.LocalServices; 225import com.android.server.ServiceThread; 226import com.android.server.SystemConfig; 227import com.android.server.Watchdog; 228import com.android.server.pm.PermissionsState.PermissionState; 229import com.android.server.pm.Settings.DatabaseVersion; 230import com.android.server.pm.Settings.VersionInfo; 231import com.android.server.storage.DeviceStorageMonitorInternal; 232 233import org.xmlpull.v1.XmlPullParser; 234import org.xmlpull.v1.XmlPullParserException; 235import org.xmlpull.v1.XmlSerializer; 236 237import java.io.BufferedInputStream; 238import java.io.BufferedOutputStream; 239import java.io.BufferedReader; 240import java.io.ByteArrayInputStream; 241import java.io.ByteArrayOutputStream; 242import java.io.File; 243import java.io.FileDescriptor; 244import java.io.FileNotFoundException; 245import java.io.FileOutputStream; 246import java.io.FileReader; 247import java.io.FilenameFilter; 248import java.io.IOException; 249import java.io.InputStream; 250import java.io.PrintWriter; 251import java.nio.charset.StandardCharsets; 252import java.security.NoSuchAlgorithmException; 253import java.security.PublicKey; 254import java.security.cert.CertificateEncodingException; 255import java.security.cert.CertificateException; 256import java.text.SimpleDateFormat; 257import java.util.ArrayList; 258import java.util.Arrays; 259import java.util.Collection; 260import java.util.Collections; 261import java.util.Comparator; 262import java.util.Date; 263import java.util.Iterator; 264import java.util.List; 265import java.util.Map; 266import java.util.Objects; 267import java.util.Set; 268import java.util.concurrent.CountDownLatch; 269import java.util.concurrent.TimeUnit; 270import java.util.concurrent.atomic.AtomicBoolean; 271import java.util.concurrent.atomic.AtomicInteger; 272import java.util.concurrent.atomic.AtomicLong; 273 274/** 275 * Keep track of all those .apks everywhere. 276 * 277 * This is very central to the platform's security; please run the unit 278 * tests whenever making modifications here: 279 * 280runtest -c android.content.pm.PackageManagerTests frameworks-core 281 * 282 * {@hide} 283 */ 284public class PackageManagerService extends IPackageManager.Stub { 285 static final String TAG = "PackageManager"; 286 static final boolean DEBUG_SETTINGS = false; 287 static final boolean DEBUG_PREFERRED = false; 288 static final boolean DEBUG_UPGRADE = false; 289 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 290 private static final boolean DEBUG_BACKUP = false; 291 private static final boolean DEBUG_INSTALL = false; 292 private static final boolean DEBUG_REMOVE = false; 293 private static final boolean DEBUG_BROADCASTS = false; 294 private static final boolean DEBUG_SHOW_INFO = false; 295 private static final boolean DEBUG_PACKAGE_INFO = false; 296 private static final boolean DEBUG_INTENT_MATCHING = false; 297 private static final boolean DEBUG_PACKAGE_SCANNING = false; 298 private static final boolean DEBUG_VERIFY = false; 299 private static final boolean DEBUG_DEXOPT = false; 300 private static final boolean DEBUG_ABI_SELECTION = false; 301 302 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 303 304 private static final int RADIO_UID = Process.PHONE_UID; 305 private static final int LOG_UID = Process.LOG_UID; 306 private static final int NFC_UID = Process.NFC_UID; 307 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 308 private static final int SHELL_UID = Process.SHELL_UID; 309 310 // Cap the size of permission trees that 3rd party apps can define 311 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 312 313 // Suffix used during package installation when copying/moving 314 // package apks to install directory. 315 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 316 317 static final int SCAN_NO_DEX = 1<<1; 318 static final int SCAN_FORCE_DEX = 1<<2; 319 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 320 static final int SCAN_NEW_INSTALL = 1<<4; 321 static final int SCAN_NO_PATHS = 1<<5; 322 static final int SCAN_UPDATE_TIME = 1<<6; 323 static final int SCAN_DEFER_DEX = 1<<7; 324 static final int SCAN_BOOTING = 1<<8; 325 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 326 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 327 static final int SCAN_REPLACING = 1<<11; 328 static final int SCAN_REQUIRE_KNOWN = 1<<12; 329 static final int SCAN_MOVE = 1<<13; 330 static final int SCAN_INITIAL = 1<<14; 331 332 static final int REMOVE_CHATTY = 1<<16; 333 334 private static final int[] EMPTY_INT_ARRAY = new int[0]; 335 336 /** 337 * Timeout (in milliseconds) after which the watchdog should declare that 338 * our handler thread is wedged. The usual default for such things is one 339 * minute but we sometimes do very lengthy I/O operations on this thread, 340 * such as installing multi-gigabyte applications, so ours needs to be longer. 341 */ 342 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 343 344 /** 345 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 346 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 347 * settings entry if available, otherwise we use the hardcoded default. If it's been 348 * more than this long since the last fstrim, we force one during the boot sequence. 349 * 350 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 351 * one gets run at the next available charging+idle time. This final mandatory 352 * no-fstrim check kicks in only of the other scheduling criteria is never met. 353 */ 354 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 355 356 /** 357 * Whether verification is enabled by default. 358 */ 359 private static final boolean DEFAULT_VERIFY_ENABLE = true; 360 361 /** 362 * The default maximum time to wait for the verification agent to return in 363 * milliseconds. 364 */ 365 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 366 367 /** 368 * The default response for package verification timeout. 369 * 370 * This can be either PackageManager.VERIFICATION_ALLOW or 371 * PackageManager.VERIFICATION_REJECT. 372 */ 373 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 374 375 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 376 377 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 378 DEFAULT_CONTAINER_PACKAGE, 379 "com.android.defcontainer.DefaultContainerService"); 380 381 private static final String KILL_APP_REASON_GIDS_CHANGED = 382 "permission grant or revoke changed gids"; 383 384 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 385 "permissions revoked"; 386 387 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 388 389 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 390 391 /** Permission grant: not grant the permission. */ 392 private static final int GRANT_DENIED = 1; 393 394 /** Permission grant: grant the permission as an install permission. */ 395 private static final int GRANT_INSTALL = 2; 396 397 /** Permission grant: grant the permission as an install permission for a legacy app. */ 398 private static final int GRANT_INSTALL_LEGACY = 3; 399 400 /** Permission grant: grant the permission as a runtime one. */ 401 private static final int GRANT_RUNTIME = 4; 402 403 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 404 private static final int GRANT_UPGRADE = 5; 405 406 /** Canonical intent used to identify what counts as a "web browser" app */ 407 private static final Intent sBrowserIntent; 408 static { 409 sBrowserIntent = new Intent(); 410 sBrowserIntent.setAction(Intent.ACTION_VIEW); 411 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 412 sBrowserIntent.setData(Uri.parse("http:")); 413 } 414 415 final ServiceThread mHandlerThread; 416 417 final PackageHandler mHandler; 418 419 /** 420 * Messages for {@link #mHandler} that need to wait for system ready before 421 * being dispatched. 422 */ 423 private ArrayList<Message> mPostSystemReadyMessages; 424 425 final int mSdkVersion = Build.VERSION.SDK_INT; 426 427 final Context mContext; 428 final boolean mFactoryTest; 429 final boolean mOnlyCore; 430 final boolean mLazyDexOpt; 431 final long mDexOptLRUThresholdInMills; 432 final DisplayMetrics mMetrics; 433 final int mDefParseFlags; 434 final String[] mSeparateProcesses; 435 final boolean mIsUpgrade; 436 437 // This is where all application persistent data goes. 438 final File mAppDataDir; 439 440 // This is where all application persistent data goes for secondary users. 441 final File mUserAppDataDir; 442 443 /** The location for ASEC container files on internal storage. */ 444 final String mAsecInternalPath; 445 446 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 447 // LOCK HELD. Can be called with mInstallLock held. 448 @GuardedBy("mInstallLock") 449 final Installer mInstaller; 450 451 /** Directory where installed third-party apps stored */ 452 final File mAppInstallDir; 453 454 /** 455 * Directory to which applications installed internally have their 456 * 32 bit native libraries copied. 457 */ 458 private File mAppLib32InstallDir; 459 460 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 461 // apps. 462 final File mDrmAppPrivateInstallDir; 463 464 // ---------------------------------------------------------------- 465 466 // Lock for state used when installing and doing other long running 467 // operations. Methods that must be called with this lock held have 468 // the suffix "LI". 469 final Object mInstallLock = new Object(); 470 471 // ---------------------------------------------------------------- 472 473 // Keys are String (package name), values are Package. This also serves 474 // as the lock for the global state. Methods that must be called with 475 // this lock held have the prefix "LP". 476 @GuardedBy("mPackages") 477 final ArrayMap<String, PackageParser.Package> mPackages = 478 new ArrayMap<String, PackageParser.Package>(); 479 480 // Tracks available target package names -> overlay package paths. 481 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 482 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 483 484 /** 485 * Tracks new system packages [received in an OTA] that we expect to 486 * find updated user-installed versions. Keys are package name, values 487 * are package location. 488 */ 489 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 490 491 /** 492 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 493 */ 494 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 495 /** 496 * Whether or not system app permissions should be promoted from install to runtime. 497 */ 498 boolean mPromoteSystemApps; 499 500 final Settings mSettings; 501 boolean mRestoredSettings; 502 503 // System configuration read by SystemConfig. 504 final int[] mGlobalGids; 505 final SparseArray<ArraySet<String>> mSystemPermissions; 506 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 507 508 // If mac_permissions.xml was found for seinfo labeling. 509 boolean mFoundPolicyFile; 510 511 // If a recursive restorecon of /data/data/<pkg> is needed. 512 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 513 514 public static final class SharedLibraryEntry { 515 public final String path; 516 public final String apk; 517 518 SharedLibraryEntry(String _path, String _apk) { 519 path = _path; 520 apk = _apk; 521 } 522 } 523 524 // Currently known shared libraries. 525 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 526 new ArrayMap<String, SharedLibraryEntry>(); 527 528 // All available activities, for your resolving pleasure. 529 final ActivityIntentResolver mActivities = 530 new ActivityIntentResolver(); 531 532 // All available receivers, for your resolving pleasure. 533 final ActivityIntentResolver mReceivers = 534 new ActivityIntentResolver(); 535 536 // All available services, for your resolving pleasure. 537 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 538 539 // All available providers, for your resolving pleasure. 540 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 541 542 // Mapping from provider base names (first directory in content URI codePath) 543 // to the provider information. 544 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 545 new ArrayMap<String, PackageParser.Provider>(); 546 547 // Mapping from instrumentation class names to info about them. 548 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 549 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 550 551 // Mapping from permission names to info about them. 552 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 553 new ArrayMap<String, PackageParser.PermissionGroup>(); 554 555 // Packages whose data we have transfered into another package, thus 556 // should no longer exist. 557 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 558 559 // Broadcast actions that are only available to the system. 560 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 561 562 /** List of packages waiting for verification. */ 563 final SparseArray<PackageVerificationState> mPendingVerification 564 = new SparseArray<PackageVerificationState>(); 565 566 /** Set of packages associated with each app op permission. */ 567 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 568 569 final PackageInstallerService mInstallerService; 570 571 private final PackageDexOptimizer mPackageDexOptimizer; 572 573 private AtomicInteger mNextMoveId = new AtomicInteger(); 574 private final MoveCallbacks mMoveCallbacks; 575 576 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 577 578 // Cache of users who need badging. 579 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 580 581 /** Token for keys in mPendingVerification. */ 582 private int mPendingVerificationToken = 0; 583 584 volatile boolean mSystemReady; 585 volatile boolean mSafeMode; 586 volatile boolean mHasSystemUidErrors; 587 588 ApplicationInfo mAndroidApplication; 589 final ActivityInfo mResolveActivity = new ActivityInfo(); 590 final ResolveInfo mResolveInfo = new ResolveInfo(); 591 ComponentName mResolveComponentName; 592 PackageParser.Package mPlatformPackage; 593 ComponentName mCustomResolverComponentName; 594 595 boolean mResolverReplaced = false; 596 597 private final ComponentName mIntentFilterVerifierComponent; 598 private int mIntentFilterVerificationToken = 0; 599 600 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 601 = new SparseArray<IntentFilterVerificationState>(); 602 603 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 604 new DefaultPermissionGrantPolicy(this); 605 606 private static class IFVerificationParams { 607 PackageParser.Package pkg; 608 boolean replacing; 609 int userId; 610 int verifierUid; 611 612 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 613 int _userId, int _verifierUid) { 614 pkg = _pkg; 615 replacing = _replacing; 616 userId = _userId; 617 replacing = _replacing; 618 verifierUid = _verifierUid; 619 } 620 } 621 622 private interface IntentFilterVerifier<T extends IntentFilter> { 623 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 624 T filter, String packageName); 625 void startVerifications(int userId); 626 void receiveVerificationResponse(int verificationId); 627 } 628 629 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 630 private Context mContext; 631 private ComponentName mIntentFilterVerifierComponent; 632 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 633 634 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 635 mContext = context; 636 mIntentFilterVerifierComponent = verifierComponent; 637 } 638 639 private String getDefaultScheme() { 640 return IntentFilter.SCHEME_HTTPS; 641 } 642 643 @Override 644 public void startVerifications(int userId) { 645 // Launch verifications requests 646 int count = mCurrentIntentFilterVerifications.size(); 647 for (int n=0; n<count; n++) { 648 int verificationId = mCurrentIntentFilterVerifications.get(n); 649 final IntentFilterVerificationState ivs = 650 mIntentFilterVerificationStates.get(verificationId); 651 652 String packageName = ivs.getPackageName(); 653 654 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 655 final int filterCount = filters.size(); 656 ArraySet<String> domainsSet = new ArraySet<>(); 657 for (int m=0; m<filterCount; m++) { 658 PackageParser.ActivityIntentInfo filter = filters.get(m); 659 domainsSet.addAll(filter.getHostsList()); 660 } 661 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 662 synchronized (mPackages) { 663 if (mSettings.createIntentFilterVerificationIfNeededLPw( 664 packageName, domainsList) != null) { 665 scheduleWriteSettingsLocked(); 666 } 667 } 668 sendVerificationRequest(userId, verificationId, ivs); 669 } 670 mCurrentIntentFilterVerifications.clear(); 671 } 672 673 private void sendVerificationRequest(int userId, int verificationId, 674 IntentFilterVerificationState ivs) { 675 676 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 677 verificationIntent.putExtra( 678 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 679 verificationId); 680 verificationIntent.putExtra( 681 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 682 getDefaultScheme()); 683 verificationIntent.putExtra( 684 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 685 ivs.getHostsString()); 686 verificationIntent.putExtra( 687 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 688 ivs.getPackageName()); 689 verificationIntent.setComponent(mIntentFilterVerifierComponent); 690 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 691 692 UserHandle user = new UserHandle(userId); 693 mContext.sendBroadcastAsUser(verificationIntent, user); 694 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 695 "Sending IntentFilter verification broadcast"); 696 } 697 698 public void receiveVerificationResponse(int verificationId) { 699 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 700 701 final boolean verified = ivs.isVerified(); 702 703 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 704 final int count = filters.size(); 705 if (DEBUG_DOMAIN_VERIFICATION) { 706 Slog.i(TAG, "Received verification response " + verificationId 707 + " for " + count + " filters, verified=" + verified); 708 } 709 for (int n=0; n<count; n++) { 710 PackageParser.ActivityIntentInfo filter = filters.get(n); 711 filter.setVerified(verified); 712 713 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 714 + " verified with result:" + verified + " and hosts:" 715 + ivs.getHostsString()); 716 } 717 718 mIntentFilterVerificationStates.remove(verificationId); 719 720 final String packageName = ivs.getPackageName(); 721 IntentFilterVerificationInfo ivi = null; 722 723 synchronized (mPackages) { 724 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 725 } 726 if (ivi == null) { 727 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 728 + verificationId + " packageName:" + packageName); 729 return; 730 } 731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 732 "Updating IntentFilterVerificationInfo for package " + packageName 733 +" verificationId:" + verificationId); 734 735 synchronized (mPackages) { 736 if (verified) { 737 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 738 } else { 739 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 740 } 741 scheduleWriteSettingsLocked(); 742 743 final int userId = ivs.getUserId(); 744 if (userId != UserHandle.USER_ALL) { 745 final int userStatus = 746 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 747 748 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 749 boolean needUpdate = false; 750 751 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 752 // already been set by the User thru the Disambiguation dialog 753 switch (userStatus) { 754 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 755 if (verified) { 756 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 757 } else { 758 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 759 } 760 needUpdate = true; 761 break; 762 763 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 764 if (verified) { 765 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 766 needUpdate = true; 767 } 768 break; 769 770 default: 771 // Nothing to do 772 } 773 774 if (needUpdate) { 775 mSettings.updateIntentFilterVerificationStatusLPw( 776 packageName, updatedStatus, userId); 777 scheduleWritePackageRestrictionsLocked(userId); 778 } 779 } 780 } 781 } 782 783 @Override 784 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 785 ActivityIntentInfo filter, String packageName) { 786 if (!hasValidDomains(filter)) { 787 return false; 788 } 789 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 790 if (ivs == null) { 791 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 792 packageName); 793 } 794 if (DEBUG_DOMAIN_VERIFICATION) { 795 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 796 } 797 ivs.addFilter(filter); 798 return true; 799 } 800 801 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 802 int userId, int verificationId, String packageName) { 803 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 804 verifierUid, userId, packageName); 805 ivs.setPendingState(); 806 synchronized (mPackages) { 807 mIntentFilterVerificationStates.append(verificationId, ivs); 808 mCurrentIntentFilterVerifications.add(verificationId); 809 } 810 return ivs; 811 } 812 } 813 814 private static boolean hasValidDomains(ActivityIntentInfo filter) { 815 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 816 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 817 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 818 } 819 820 private IntentFilterVerifier mIntentFilterVerifier; 821 822 // Set of pending broadcasts for aggregating enable/disable of components. 823 static class PendingPackageBroadcasts { 824 // for each user id, a map of <package name -> components within that package> 825 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 826 827 public PendingPackageBroadcasts() { 828 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 829 } 830 831 public ArrayList<String> get(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 833 return packages.get(packageName); 834 } 835 836 public void put(int userId, String packageName, ArrayList<String> components) { 837 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 838 packages.put(packageName, components); 839 } 840 841 public void remove(int userId, String packageName) { 842 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 843 if (packages != null) { 844 packages.remove(packageName); 845 } 846 } 847 848 public void remove(int userId) { 849 mUidMap.remove(userId); 850 } 851 852 public int userIdCount() { 853 return mUidMap.size(); 854 } 855 856 public int userIdAt(int n) { 857 return mUidMap.keyAt(n); 858 } 859 860 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 861 return mUidMap.get(userId); 862 } 863 864 public int size() { 865 // total number of pending broadcast entries across all userIds 866 int num = 0; 867 for (int i = 0; i< mUidMap.size(); i++) { 868 num += mUidMap.valueAt(i).size(); 869 } 870 return num; 871 } 872 873 public void clear() { 874 mUidMap.clear(); 875 } 876 877 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 878 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 879 if (map == null) { 880 map = new ArrayMap<String, ArrayList<String>>(); 881 mUidMap.put(userId, map); 882 } 883 return map; 884 } 885 } 886 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 887 888 // Service Connection to remote media container service to copy 889 // package uri's from external media onto secure containers 890 // or internal storage. 891 private IMediaContainerService mContainerService = null; 892 893 static final int SEND_PENDING_BROADCAST = 1; 894 static final int MCS_BOUND = 3; 895 static final int END_COPY = 4; 896 static final int INIT_COPY = 5; 897 static final int MCS_UNBIND = 6; 898 static final int START_CLEANING_PACKAGE = 7; 899 static final int FIND_INSTALL_LOC = 8; 900 static final int POST_INSTALL = 9; 901 static final int MCS_RECONNECT = 10; 902 static final int MCS_GIVE_UP = 11; 903 static final int UPDATED_MEDIA_STATUS = 12; 904 static final int WRITE_SETTINGS = 13; 905 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 906 static final int PACKAGE_VERIFIED = 15; 907 static final int CHECK_PENDING_VERIFICATION = 16; 908 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 909 static final int INTENT_FILTER_VERIFIED = 18; 910 911 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 912 913 // Delay time in millisecs 914 static final int BROADCAST_DELAY = 10 * 1000; 915 916 static UserManagerService sUserManager; 917 918 // Stores a list of users whose package restrictions file needs to be updated 919 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 920 921 final private DefaultContainerConnection mDefContainerConn = 922 new DefaultContainerConnection(); 923 class DefaultContainerConnection implements ServiceConnection { 924 public void onServiceConnected(ComponentName name, IBinder service) { 925 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 926 IMediaContainerService imcs = 927 IMediaContainerService.Stub.asInterface(service); 928 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 929 } 930 931 public void onServiceDisconnected(ComponentName name) { 932 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 933 } 934 } 935 936 // Recordkeeping of restore-after-install operations that are currently in flight 937 // between the Package Manager and the Backup Manager 938 class PostInstallData { 939 public InstallArgs args; 940 public PackageInstalledInfo res; 941 942 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 943 args = _a; 944 res = _r; 945 } 946 } 947 948 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 949 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 950 951 // XML tags for backup/restore of various bits of state 952 private static final String TAG_PREFERRED_BACKUP = "pa"; 953 private static final String TAG_DEFAULT_APPS = "da"; 954 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 955 956 final String mRequiredVerifierPackage; 957 final String mRequiredInstallerPackage; 958 959 private final PackageUsage mPackageUsage = new PackageUsage(); 960 961 private class PackageUsage { 962 private static final int WRITE_INTERVAL 963 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 964 965 private final Object mFileLock = new Object(); 966 private final AtomicLong mLastWritten = new AtomicLong(0); 967 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 968 969 private boolean mIsHistoricalPackageUsageAvailable = true; 970 971 boolean isHistoricalPackageUsageAvailable() { 972 return mIsHistoricalPackageUsageAvailable; 973 } 974 975 void write(boolean force) { 976 if (force) { 977 writeInternal(); 978 return; 979 } 980 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 981 && !DEBUG_DEXOPT) { 982 return; 983 } 984 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 985 new Thread("PackageUsage_DiskWriter") { 986 @Override 987 public void run() { 988 try { 989 writeInternal(); 990 } finally { 991 mBackgroundWriteRunning.set(false); 992 } 993 } 994 }.start(); 995 } 996 } 997 998 private void writeInternal() { 999 synchronized (mPackages) { 1000 synchronized (mFileLock) { 1001 AtomicFile file = getFile(); 1002 FileOutputStream f = null; 1003 try { 1004 f = file.startWrite(); 1005 BufferedOutputStream out = new BufferedOutputStream(f); 1006 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1007 StringBuilder sb = new StringBuilder(); 1008 for (PackageParser.Package pkg : mPackages.values()) { 1009 if (pkg.mLastPackageUsageTimeInMills == 0) { 1010 continue; 1011 } 1012 sb.setLength(0); 1013 sb.append(pkg.packageName); 1014 sb.append(' '); 1015 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1016 sb.append('\n'); 1017 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1018 } 1019 out.flush(); 1020 file.finishWrite(f); 1021 } catch (IOException e) { 1022 if (f != null) { 1023 file.failWrite(f); 1024 } 1025 Log.e(TAG, "Failed to write package usage times", e); 1026 } 1027 } 1028 } 1029 mLastWritten.set(SystemClock.elapsedRealtime()); 1030 } 1031 1032 void readLP() { 1033 synchronized (mFileLock) { 1034 AtomicFile file = getFile(); 1035 BufferedInputStream in = null; 1036 try { 1037 in = new BufferedInputStream(file.openRead()); 1038 StringBuffer sb = new StringBuffer(); 1039 while (true) { 1040 String packageName = readToken(in, sb, ' '); 1041 if (packageName == null) { 1042 break; 1043 } 1044 String timeInMillisString = readToken(in, sb, '\n'); 1045 if (timeInMillisString == null) { 1046 throw new IOException("Failed to find last usage time for package " 1047 + packageName); 1048 } 1049 PackageParser.Package pkg = mPackages.get(packageName); 1050 if (pkg == null) { 1051 continue; 1052 } 1053 long timeInMillis; 1054 try { 1055 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1056 } catch (NumberFormatException e) { 1057 throw new IOException("Failed to parse " + timeInMillisString 1058 + " as a long.", e); 1059 } 1060 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1061 } 1062 } catch (FileNotFoundException expected) { 1063 mIsHistoricalPackageUsageAvailable = false; 1064 } catch (IOException e) { 1065 Log.w(TAG, "Failed to read package usage times", e); 1066 } finally { 1067 IoUtils.closeQuietly(in); 1068 } 1069 } 1070 mLastWritten.set(SystemClock.elapsedRealtime()); 1071 } 1072 1073 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1074 throws IOException { 1075 sb.setLength(0); 1076 while (true) { 1077 int ch = in.read(); 1078 if (ch == -1) { 1079 if (sb.length() == 0) { 1080 return null; 1081 } 1082 throw new IOException("Unexpected EOF"); 1083 } 1084 if (ch == endOfToken) { 1085 return sb.toString(); 1086 } 1087 sb.append((char)ch); 1088 } 1089 } 1090 1091 private AtomicFile getFile() { 1092 File dataDir = Environment.getDataDirectory(); 1093 File systemDir = new File(dataDir, "system"); 1094 File fname = new File(systemDir, "package-usage.list"); 1095 return new AtomicFile(fname); 1096 } 1097 } 1098 1099 class PackageHandler extends Handler { 1100 private boolean mBound = false; 1101 final ArrayList<HandlerParams> mPendingInstalls = 1102 new ArrayList<HandlerParams>(); 1103 1104 private boolean connectToService() { 1105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1106 " DefaultContainerService"); 1107 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1109 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1110 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 mBound = true; 1113 return true; 1114 } 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1116 return false; 1117 } 1118 1119 private void disconnectService() { 1120 mContainerService = null; 1121 mBound = false; 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1123 mContext.unbindService(mDefContainerConn); 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } 1126 1127 PackageHandler(Looper looper) { 1128 super(looper); 1129 } 1130 1131 public void handleMessage(Message msg) { 1132 try { 1133 doHandleMessage(msg); 1134 } finally { 1135 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1136 } 1137 } 1138 1139 void doHandleMessage(Message msg) { 1140 switch (msg.what) { 1141 case INIT_COPY: { 1142 HandlerParams params = (HandlerParams) msg.obj; 1143 int idx = mPendingInstalls.size(); 1144 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1145 // If a bind was already initiated we dont really 1146 // need to do anything. The pending install 1147 // will be processed later on. 1148 if (!mBound) { 1149 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1150 System.identityHashCode(mHandler)); 1151 // If this is the only one pending we might 1152 // have to bind to the service again. 1153 if (!connectToService()) { 1154 Slog.e(TAG, "Failed to bind to media container service"); 1155 params.serviceError(); 1156 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1157 System.identityHashCode(mHandler)); 1158 if (params.traceMethod != null) { 1159 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1160 params.traceCookie); 1161 } 1162 return; 1163 } else { 1164 // Once we bind to the service, the first 1165 // pending request will be processed. 1166 mPendingInstalls.add(idx, params); 1167 } 1168 } else { 1169 mPendingInstalls.add(idx, params); 1170 // Already bound to the service. Just make 1171 // sure we trigger off processing the first request. 1172 if (idx == 0) { 1173 mHandler.sendEmptyMessage(MCS_BOUND); 1174 } 1175 } 1176 break; 1177 } 1178 case MCS_BOUND: { 1179 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1180 if (msg.obj != null) { 1181 mContainerService = (IMediaContainerService) msg.obj; 1182 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1183 System.identityHashCode(mHandler)); 1184 } 1185 if (mContainerService == null) { 1186 if (!mBound) { 1187 // Something seriously wrong since we are not bound and we are not 1188 // waiting for connection. Bail out. 1189 Slog.e(TAG, "Cannot bind to media container service"); 1190 for (HandlerParams params : mPendingInstalls) { 1191 // Indicate service bind error 1192 params.serviceError(); 1193 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1194 System.identityHashCode(params)); 1195 if (params.traceMethod != null) { 1196 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1197 params.traceMethod, params.traceCookie); 1198 } 1199 return; 1200 } 1201 mPendingInstalls.clear(); 1202 } else { 1203 Slog.w(TAG, "Waiting to connect to media container service"); 1204 } 1205 } else if (mPendingInstalls.size() > 0) { 1206 HandlerParams params = mPendingInstalls.get(0); 1207 if (params != null) { 1208 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1209 System.identityHashCode(params)); 1210 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1211 if (params.startCopy()) { 1212 // We are done... look for more work or to 1213 // go idle. 1214 if (DEBUG_SD_INSTALL) Log.i(TAG, 1215 "Checking for more work or unbind..."); 1216 // Delete pending install 1217 if (mPendingInstalls.size() > 0) { 1218 mPendingInstalls.remove(0); 1219 } 1220 if (mPendingInstalls.size() == 0) { 1221 if (mBound) { 1222 if (DEBUG_SD_INSTALL) Log.i(TAG, 1223 "Posting delayed MCS_UNBIND"); 1224 removeMessages(MCS_UNBIND); 1225 Message ubmsg = obtainMessage(MCS_UNBIND); 1226 // Unbind after a little delay, to avoid 1227 // continual thrashing. 1228 sendMessageDelayed(ubmsg, 10000); 1229 } 1230 } else { 1231 // There are more pending requests in queue. 1232 // Just post MCS_BOUND message to trigger processing 1233 // of next pending install. 1234 if (DEBUG_SD_INSTALL) Log.i(TAG, 1235 "Posting MCS_BOUND for next work"); 1236 mHandler.sendEmptyMessage(MCS_BOUND); 1237 } 1238 } 1239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1240 } 1241 } else { 1242 // Should never happen ideally. 1243 Slog.w(TAG, "Empty queue"); 1244 } 1245 break; 1246 } 1247 case MCS_RECONNECT: { 1248 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1249 if (mPendingInstalls.size() > 0) { 1250 if (mBound) { 1251 disconnectService(); 1252 } 1253 if (!connectToService()) { 1254 Slog.e(TAG, "Failed to bind to media container service"); 1255 for (HandlerParams params : mPendingInstalls) { 1256 // Indicate service bind error 1257 params.serviceError(); 1258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1259 System.identityHashCode(params)); 1260 } 1261 mPendingInstalls.clear(); 1262 } 1263 } 1264 break; 1265 } 1266 case MCS_UNBIND: { 1267 // If there is no actual work left, then time to unbind. 1268 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1269 1270 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1271 if (mBound) { 1272 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1273 1274 disconnectService(); 1275 } 1276 } else if (mPendingInstalls.size() > 0) { 1277 // There are more pending requests in queue. 1278 // Just post MCS_BOUND message to trigger processing 1279 // of next pending install. 1280 mHandler.sendEmptyMessage(MCS_BOUND); 1281 } 1282 1283 break; 1284 } 1285 case MCS_GIVE_UP: { 1286 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1287 HandlerParams params = mPendingInstalls.remove(0); 1288 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1289 System.identityHashCode(params)); 1290 break; 1291 } 1292 case SEND_PENDING_BROADCAST: { 1293 String packages[]; 1294 ArrayList<String> components[]; 1295 int size = 0; 1296 int uids[]; 1297 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1298 synchronized (mPackages) { 1299 if (mPendingBroadcasts == null) { 1300 return; 1301 } 1302 size = mPendingBroadcasts.size(); 1303 if (size <= 0) { 1304 // Nothing to be done. Just return 1305 return; 1306 } 1307 packages = new String[size]; 1308 components = new ArrayList[size]; 1309 uids = new int[size]; 1310 int i = 0; // filling out the above arrays 1311 1312 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1313 int packageUserId = mPendingBroadcasts.userIdAt(n); 1314 Iterator<Map.Entry<String, ArrayList<String>>> it 1315 = mPendingBroadcasts.packagesForUserId(packageUserId) 1316 .entrySet().iterator(); 1317 while (it.hasNext() && i < size) { 1318 Map.Entry<String, ArrayList<String>> ent = it.next(); 1319 packages[i] = ent.getKey(); 1320 components[i] = ent.getValue(); 1321 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1322 uids[i] = (ps != null) 1323 ? UserHandle.getUid(packageUserId, ps.appId) 1324 : -1; 1325 i++; 1326 } 1327 } 1328 size = i; 1329 mPendingBroadcasts.clear(); 1330 } 1331 // Send broadcasts 1332 for (int i = 0; i < size; i++) { 1333 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1334 } 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1336 break; 1337 } 1338 case START_CLEANING_PACKAGE: { 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1340 final String packageName = (String)msg.obj; 1341 final int userId = msg.arg1; 1342 final boolean andCode = msg.arg2 != 0; 1343 synchronized (mPackages) { 1344 if (userId == UserHandle.USER_ALL) { 1345 int[] users = sUserManager.getUserIds(); 1346 for (int user : users) { 1347 mSettings.addPackageToCleanLPw( 1348 new PackageCleanItem(user, packageName, andCode)); 1349 } 1350 } else { 1351 mSettings.addPackageToCleanLPw( 1352 new PackageCleanItem(userId, packageName, andCode)); 1353 } 1354 } 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1356 startCleaningPackages(); 1357 } break; 1358 case POST_INSTALL: { 1359 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1360 PostInstallData data = mRunningInstalls.get(msg.arg1); 1361 mRunningInstalls.delete(msg.arg1); 1362 boolean deleteOld = false; 1363 1364 if (data != null) { 1365 InstallArgs args = data.args; 1366 PackageInstalledInfo res = data.res; 1367 1368 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1369 final String packageName = res.pkg.applicationInfo.packageName; 1370 res.removedInfo.sendBroadcast(false, true, false); 1371 Bundle extras = new Bundle(1); 1372 extras.putInt(Intent.EXTRA_UID, res.uid); 1373 1374 // Now that we successfully installed the package, grant runtime 1375 // permissions if requested before broadcasting the install. 1376 if ((args.installFlags 1377 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1378 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1379 args.installGrantPermissions); 1380 } 1381 1382 // Determine the set of users who are adding this 1383 // package for the first time vs. those who are seeing 1384 // an update. 1385 int[] firstUsers; 1386 int[] updateUsers = new int[0]; 1387 if (res.origUsers == null || res.origUsers.length == 0) { 1388 firstUsers = res.newUsers; 1389 } else { 1390 firstUsers = new int[0]; 1391 for (int i=0; i<res.newUsers.length; i++) { 1392 int user = res.newUsers[i]; 1393 boolean isNew = true; 1394 for (int j=0; j<res.origUsers.length; j++) { 1395 if (res.origUsers[j] == user) { 1396 isNew = false; 1397 break; 1398 } 1399 } 1400 if (isNew) { 1401 int[] newFirst = new int[firstUsers.length+1]; 1402 System.arraycopy(firstUsers, 0, newFirst, 0, 1403 firstUsers.length); 1404 newFirst[firstUsers.length] = user; 1405 firstUsers = newFirst; 1406 } else { 1407 int[] newUpdate = new int[updateUsers.length+1]; 1408 System.arraycopy(updateUsers, 0, newUpdate, 0, 1409 updateUsers.length); 1410 newUpdate[updateUsers.length] = user; 1411 updateUsers = newUpdate; 1412 } 1413 } 1414 } 1415 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1416 packageName, extras, null, null, firstUsers); 1417 final boolean update = res.removedInfo.removedPackage != null; 1418 if (update) { 1419 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1420 } 1421 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1422 packageName, extras, null, null, updateUsers); 1423 if (update) { 1424 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1425 packageName, extras, null, null, updateUsers); 1426 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1427 null, null, packageName, null, updateUsers); 1428 1429 // treat asec-hosted packages like removable media on upgrade 1430 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1431 if (DEBUG_INSTALL) { 1432 Slog.i(TAG, "upgrading pkg " + res.pkg 1433 + " is ASEC-hosted -> AVAILABLE"); 1434 } 1435 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1436 ArrayList<String> pkgList = new ArrayList<String>(1); 1437 pkgList.add(packageName); 1438 sendResourcesChangedBroadcast(true, true, 1439 pkgList,uidArray, null); 1440 } 1441 } 1442 if (res.removedInfo.args != null) { 1443 // Remove the replaced package's older resources safely now 1444 deleteOld = true; 1445 } 1446 1447 // If this app is a browser and it's newly-installed for some 1448 // users, clear any default-browser state in those users 1449 if (firstUsers.length > 0) { 1450 // the app's nature doesn't depend on the user, so we can just 1451 // check its browser nature in any user and generalize. 1452 if (packageIsBrowser(packageName, firstUsers[0])) { 1453 synchronized (mPackages) { 1454 for (int userId : firstUsers) { 1455 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1456 } 1457 } 1458 } 1459 } 1460 // Log current value of "unknown sources" setting 1461 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1462 getUnknownSourcesSettings()); 1463 } 1464 // Force a gc to clear up things 1465 Runtime.getRuntime().gc(); 1466 // We delete after a gc for applications on sdcard. 1467 if (deleteOld) { 1468 synchronized (mInstallLock) { 1469 res.removedInfo.args.doPostDeleteLI(true); 1470 } 1471 } 1472 if (args.observer != null) { 1473 try { 1474 Bundle extras = extrasForInstallResult(res); 1475 args.observer.onPackageInstalled(res.name, res.returnCode, 1476 res.returnMsg, extras); 1477 } catch (RemoteException e) { 1478 Slog.i(TAG, "Observer no longer exists."); 1479 } 1480 } 1481 if (args.traceMethod != null) { 1482 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1483 args.traceCookie); 1484 } 1485 return; 1486 } else { 1487 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1488 } 1489 1490 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1491 } break; 1492 case UPDATED_MEDIA_STATUS: { 1493 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1494 boolean reportStatus = msg.arg1 == 1; 1495 boolean doGc = msg.arg2 == 1; 1496 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1497 if (doGc) { 1498 // Force a gc to clear up stale containers. 1499 Runtime.getRuntime().gc(); 1500 } 1501 if (msg.obj != null) { 1502 @SuppressWarnings("unchecked") 1503 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1504 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1505 // Unload containers 1506 unloadAllContainers(args); 1507 } 1508 if (reportStatus) { 1509 try { 1510 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1511 PackageHelper.getMountService().finishMediaUpdate(); 1512 } catch (RemoteException e) { 1513 Log.e(TAG, "MountService not running?"); 1514 } 1515 } 1516 } break; 1517 case WRITE_SETTINGS: { 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 removeMessages(WRITE_SETTINGS); 1521 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1522 mSettings.writeLPr(); 1523 mDirtyUsers.clear(); 1524 } 1525 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1526 } break; 1527 case WRITE_PACKAGE_RESTRICTIONS: { 1528 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1529 synchronized (mPackages) { 1530 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1531 for (int userId : mDirtyUsers) { 1532 mSettings.writePackageRestrictionsLPr(userId); 1533 } 1534 mDirtyUsers.clear(); 1535 } 1536 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1537 } break; 1538 case CHECK_PENDING_VERIFICATION: { 1539 final int verificationId = msg.arg1; 1540 final PackageVerificationState state = mPendingVerification.get(verificationId); 1541 1542 if ((state != null) && !state.timeoutExtended()) { 1543 final InstallArgs args = state.getInstallArgs(); 1544 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1545 1546 Slog.i(TAG, "Verification timed out for " + originUri); 1547 mPendingVerification.remove(verificationId); 1548 1549 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1550 1551 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1552 Slog.i(TAG, "Continuing with installation of " + originUri); 1553 state.setVerifierResponse(Binder.getCallingUid(), 1554 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1555 broadcastPackageVerified(verificationId, originUri, 1556 PackageManager.VERIFICATION_ALLOW, 1557 state.getInstallArgs().getUser()); 1558 try { 1559 ret = args.copyApk(mContainerService, true); 1560 } catch (RemoteException e) { 1561 Slog.e(TAG, "Could not contact the ContainerService"); 1562 } 1563 } else { 1564 broadcastPackageVerified(verificationId, originUri, 1565 PackageManager.VERIFICATION_REJECT, 1566 state.getInstallArgs().getUser()); 1567 } 1568 1569 Trace.asyncTraceEnd( 1570 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1571 1572 processPendingInstall(args, ret); 1573 mHandler.sendEmptyMessage(MCS_UNBIND); 1574 } 1575 break; 1576 } 1577 case PACKAGE_VERIFIED: { 1578 final int verificationId = msg.arg1; 1579 1580 final PackageVerificationState state = mPendingVerification.get(verificationId); 1581 if (state == null) { 1582 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1583 break; 1584 } 1585 1586 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1587 1588 state.setVerifierResponse(response.callerUid, response.code); 1589 1590 if (state.isVerificationComplete()) { 1591 mPendingVerification.remove(verificationId); 1592 1593 final InstallArgs args = state.getInstallArgs(); 1594 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1595 1596 int ret; 1597 if (state.isInstallAllowed()) { 1598 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1599 broadcastPackageVerified(verificationId, originUri, 1600 response.code, state.getInstallArgs().getUser()); 1601 try { 1602 ret = args.copyApk(mContainerService, true); 1603 } catch (RemoteException e) { 1604 Slog.e(TAG, "Could not contact the ContainerService"); 1605 } 1606 } else { 1607 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1608 } 1609 1610 Trace.asyncTraceEnd( 1611 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1612 1613 processPendingInstall(args, ret); 1614 mHandler.sendEmptyMessage(MCS_UNBIND); 1615 } 1616 1617 break; 1618 } 1619 case START_INTENT_FILTER_VERIFICATIONS: { 1620 IFVerificationParams params = (IFVerificationParams) msg.obj; 1621 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1622 params.replacing, params.pkg); 1623 break; 1624 } 1625 case INTENT_FILTER_VERIFIED: { 1626 final int verificationId = msg.arg1; 1627 1628 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1629 verificationId); 1630 if (state == null) { 1631 Slog.w(TAG, "Invalid IntentFilter verification token " 1632 + verificationId + " received"); 1633 break; 1634 } 1635 1636 final int userId = state.getUserId(); 1637 1638 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1639 "Processing IntentFilter verification with token:" 1640 + verificationId + " and userId:" + userId); 1641 1642 final IntentFilterVerificationResponse response = 1643 (IntentFilterVerificationResponse) msg.obj; 1644 1645 state.setVerifierResponse(response.callerUid, response.code); 1646 1647 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1648 "IntentFilter verification with token:" + verificationId 1649 + " and userId:" + userId 1650 + " is settings verifier response with response code:" 1651 + response.code); 1652 1653 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1654 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1655 + response.getFailedDomainsString()); 1656 } 1657 1658 if (state.isVerificationComplete()) { 1659 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1660 } else { 1661 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1662 "IntentFilter verification with token:" + verificationId 1663 + " was not said to be complete"); 1664 } 1665 1666 break; 1667 } 1668 } 1669 } 1670 } 1671 1672 private StorageEventListener mStorageListener = new StorageEventListener() { 1673 @Override 1674 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1675 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1676 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1677 final String volumeUuid = vol.getFsUuid(); 1678 1679 // Clean up any users or apps that were removed or recreated 1680 // while this volume was missing 1681 reconcileUsers(volumeUuid); 1682 reconcileApps(volumeUuid); 1683 1684 // Clean up any install sessions that expired or were 1685 // cancelled while this volume was missing 1686 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1687 1688 loadPrivatePackages(vol); 1689 1690 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1691 unloadPrivatePackages(vol); 1692 } 1693 } 1694 1695 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1696 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1697 updateExternalMediaStatus(true, false); 1698 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1699 updateExternalMediaStatus(false, false); 1700 } 1701 } 1702 } 1703 1704 @Override 1705 public void onVolumeForgotten(String fsUuid) { 1706 if (TextUtils.isEmpty(fsUuid)) { 1707 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1708 return; 1709 } 1710 1711 // Remove any apps installed on the forgotten volume 1712 synchronized (mPackages) { 1713 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1714 for (PackageSetting ps : packages) { 1715 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1716 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1717 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1718 } 1719 1720 mSettings.onVolumeForgotten(fsUuid); 1721 mSettings.writeLPr(); 1722 } 1723 } 1724 }; 1725 1726 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1727 String[] grantedPermissions) { 1728 if (userId >= UserHandle.USER_OWNER) { 1729 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1730 } else if (userId == UserHandle.USER_ALL) { 1731 final int[] userIds; 1732 synchronized (mPackages) { 1733 userIds = UserManagerService.getInstance().getUserIds(); 1734 } 1735 for (int someUserId : userIds) { 1736 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1737 } 1738 } 1739 1740 // We could have touched GID membership, so flush out packages.list 1741 synchronized (mPackages) { 1742 mSettings.writePackageListLPr(); 1743 } 1744 } 1745 1746 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1747 String[] grantedPermissions) { 1748 SettingBase sb = (SettingBase) pkg.mExtras; 1749 if (sb == null) { 1750 return; 1751 } 1752 1753 PermissionsState permissionsState = sb.getPermissionsState(); 1754 1755 for (String permission : pkg.requestedPermissions) { 1756 BasePermission bp = mSettings.mPermissions.get(permission); 1757 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1758 || ArrayUtils.contains(grantedPermissions, permission))) { 1759 permissionsState.grantRuntimePermission(bp, userId); 1760 } 1761 } 1762 } 1763 1764 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1765 Bundle extras = null; 1766 switch (res.returnCode) { 1767 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1768 extras = new Bundle(); 1769 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1770 res.origPermission); 1771 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1772 res.origPackage); 1773 break; 1774 } 1775 case PackageManager.INSTALL_SUCCEEDED: { 1776 extras = new Bundle(); 1777 extras.putBoolean(Intent.EXTRA_REPLACING, 1778 res.removedInfo != null && res.removedInfo.removedPackage != null); 1779 break; 1780 } 1781 } 1782 return extras; 1783 } 1784 1785 void scheduleWriteSettingsLocked() { 1786 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1787 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1788 } 1789 } 1790 1791 void scheduleWritePackageRestrictionsLocked(int userId) { 1792 if (!sUserManager.exists(userId)) return; 1793 mDirtyUsers.add(userId); 1794 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1795 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1796 } 1797 } 1798 1799 public static PackageManagerService main(Context context, Installer installer, 1800 boolean factoryTest, boolean onlyCore) { 1801 PackageManagerService m = new PackageManagerService(context, installer, 1802 factoryTest, onlyCore); 1803 ServiceManager.addService("package", m); 1804 return m; 1805 } 1806 1807 static String[] splitString(String str, char sep) { 1808 int count = 1; 1809 int i = 0; 1810 while ((i=str.indexOf(sep, i)) >= 0) { 1811 count++; 1812 i++; 1813 } 1814 1815 String[] res = new String[count]; 1816 i=0; 1817 count = 0; 1818 int lastI=0; 1819 while ((i=str.indexOf(sep, i)) >= 0) { 1820 res[count] = str.substring(lastI, i); 1821 count++; 1822 i++; 1823 lastI = i; 1824 } 1825 res[count] = str.substring(lastI, str.length()); 1826 return res; 1827 } 1828 1829 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1830 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1831 Context.DISPLAY_SERVICE); 1832 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1833 } 1834 1835 public PackageManagerService(Context context, Installer installer, 1836 boolean factoryTest, boolean onlyCore) { 1837 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1838 SystemClock.uptimeMillis()); 1839 1840 if (mSdkVersion <= 0) { 1841 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1842 } 1843 1844 mContext = context; 1845 mFactoryTest = factoryTest; 1846 mOnlyCore = onlyCore; 1847 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1848 mMetrics = new DisplayMetrics(); 1849 mSettings = new Settings(mPackages); 1850 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1851 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1852 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1853 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1854 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1855 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1856 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1857 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1858 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1859 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1860 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1861 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1862 1863 // TODO: add a property to control this? 1864 long dexOptLRUThresholdInMinutes; 1865 if (mLazyDexOpt) { 1866 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1867 } else { 1868 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1869 } 1870 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1871 1872 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1873 if (separateProcesses != null && separateProcesses.length() > 0) { 1874 if ("*".equals(separateProcesses)) { 1875 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1876 mSeparateProcesses = null; 1877 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1878 } else { 1879 mDefParseFlags = 0; 1880 mSeparateProcesses = separateProcesses.split(","); 1881 Slog.w(TAG, "Running with debug.separate_processes: " 1882 + separateProcesses); 1883 } 1884 } else { 1885 mDefParseFlags = 0; 1886 mSeparateProcesses = null; 1887 } 1888 1889 mInstaller = installer; 1890 mPackageDexOptimizer = new PackageDexOptimizer(this); 1891 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1892 1893 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1894 FgThread.get().getLooper()); 1895 1896 getDefaultDisplayMetrics(context, mMetrics); 1897 1898 SystemConfig systemConfig = SystemConfig.getInstance(); 1899 mGlobalGids = systemConfig.getGlobalGids(); 1900 mSystemPermissions = systemConfig.getSystemPermissions(); 1901 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1902 1903 synchronized (mInstallLock) { 1904 // writer 1905 synchronized (mPackages) { 1906 mHandlerThread = new ServiceThread(TAG, 1907 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1908 mHandlerThread.start(); 1909 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1910 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1911 1912 File dataDir = Environment.getDataDirectory(); 1913 mAppDataDir = new File(dataDir, "data"); 1914 mAppInstallDir = new File(dataDir, "app"); 1915 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1916 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1917 mUserAppDataDir = new File(dataDir, "user"); 1918 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1919 1920 sUserManager = new UserManagerService(context, this, 1921 mInstallLock, mPackages); 1922 1923 // Propagate permission configuration in to package manager. 1924 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1925 = systemConfig.getPermissions(); 1926 for (int i=0; i<permConfig.size(); i++) { 1927 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1928 BasePermission bp = mSettings.mPermissions.get(perm.name); 1929 if (bp == null) { 1930 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1931 mSettings.mPermissions.put(perm.name, bp); 1932 } 1933 if (perm.gids != null) { 1934 bp.setGids(perm.gids, perm.perUser); 1935 } 1936 } 1937 1938 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1939 for (int i=0; i<libConfig.size(); i++) { 1940 mSharedLibraries.put(libConfig.keyAt(i), 1941 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1942 } 1943 1944 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1945 1946 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1947 1948 String customResolverActivity = Resources.getSystem().getString( 1949 R.string.config_customResolverActivity); 1950 if (TextUtils.isEmpty(customResolverActivity)) { 1951 customResolverActivity = null; 1952 } else { 1953 mCustomResolverComponentName = ComponentName.unflattenFromString( 1954 customResolverActivity); 1955 } 1956 1957 long startTime = SystemClock.uptimeMillis(); 1958 1959 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1960 startTime); 1961 1962 // Set flag to monitor and not change apk file paths when 1963 // scanning install directories. 1964 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1965 1966 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1967 1968 /** 1969 * Add everything in the in the boot class path to the 1970 * list of process files because dexopt will have been run 1971 * if necessary during zygote startup. 1972 */ 1973 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1974 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1975 1976 if (bootClassPath != null) { 1977 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1978 for (String element : bootClassPathElements) { 1979 alreadyDexOpted.add(element); 1980 } 1981 } else { 1982 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1983 } 1984 1985 if (systemServerClassPath != null) { 1986 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1987 for (String element : systemServerClassPathElements) { 1988 alreadyDexOpted.add(element); 1989 } 1990 } else { 1991 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1992 } 1993 1994 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1995 final String[] dexCodeInstructionSets = 1996 getDexCodeInstructionSets( 1997 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1998 1999 /** 2000 * Ensure all external libraries have had dexopt run on them. 2001 */ 2002 if (mSharedLibraries.size() > 0) { 2003 // NOTE: For now, we're compiling these system "shared libraries" 2004 // (and framework jars) into all available architectures. It's possible 2005 // to compile them only when we come across an app that uses them (there's 2006 // already logic for that in scanPackageLI) but that adds some complexity. 2007 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2008 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2009 final String lib = libEntry.path; 2010 if (lib == null) { 2011 continue; 2012 } 2013 2014 try { 2015 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2016 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2017 alreadyDexOpted.add(lib); 2018 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2019 } 2020 } catch (FileNotFoundException e) { 2021 Slog.w(TAG, "Library not found: " + lib); 2022 } catch (IOException e) { 2023 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2024 + e.getMessage()); 2025 } 2026 } 2027 } 2028 } 2029 2030 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2031 2032 // Gross hack for now: we know this file doesn't contain any 2033 // code, so don't dexopt it to avoid the resulting log spew. 2034 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2035 2036 // Gross hack for now: we know this file is only part of 2037 // the boot class path for art, so don't dexopt it to 2038 // avoid the resulting log spew. 2039 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2040 2041 /** 2042 * There are a number of commands implemented in Java, which 2043 * we currently need to do the dexopt on so that they can be 2044 * run from a non-root shell. 2045 */ 2046 String[] frameworkFiles = frameworkDir.list(); 2047 if (frameworkFiles != null) { 2048 // TODO: We could compile these only for the most preferred ABI. We should 2049 // first double check that the dex files for these commands are not referenced 2050 // by other system apps. 2051 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2052 for (int i=0; i<frameworkFiles.length; i++) { 2053 File libPath = new File(frameworkDir, frameworkFiles[i]); 2054 String path = libPath.getPath(); 2055 // Skip the file if we already did it. 2056 if (alreadyDexOpted.contains(path)) { 2057 continue; 2058 } 2059 // Skip the file if it is not a type we want to dexopt. 2060 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2061 continue; 2062 } 2063 try { 2064 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2065 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2066 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2067 } 2068 } catch (FileNotFoundException e) { 2069 Slog.w(TAG, "Jar not found: " + path); 2070 } catch (IOException e) { 2071 Slog.w(TAG, "Exception reading jar: " + path, e); 2072 } 2073 } 2074 } 2075 } 2076 2077 final VersionInfo ver = mSettings.getInternalVersion(); 2078 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2079 // when upgrading from pre-M, promote system app permissions from install to runtime 2080 mPromoteSystemApps = 2081 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2082 2083 // save off the names of pre-existing system packages prior to scanning; we don't 2084 // want to automatically grant runtime permissions for new system apps 2085 if (mPromoteSystemApps) { 2086 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2087 while (pkgSettingIter.hasNext()) { 2088 PackageSetting ps = pkgSettingIter.next(); 2089 if (isSystemApp(ps)) { 2090 mExistingSystemPackages.add(ps.name); 2091 } 2092 } 2093 } 2094 2095 // Collect vendor overlay packages. 2096 // (Do this before scanning any apps.) 2097 // For security and version matching reason, only consider 2098 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2099 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2100 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2101 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2102 2103 // Find base frameworks (resource packages without code). 2104 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2105 | PackageParser.PARSE_IS_SYSTEM_DIR 2106 | PackageParser.PARSE_IS_PRIVILEGED, 2107 scanFlags | SCAN_NO_DEX, 0); 2108 2109 // Collected privileged system packages. 2110 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2111 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2112 | PackageParser.PARSE_IS_SYSTEM_DIR 2113 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2114 2115 // Collect ordinary system packages. 2116 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2117 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2118 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2119 2120 // Collect all vendor packages. 2121 File vendorAppDir = new File("/vendor/app"); 2122 try { 2123 vendorAppDir = vendorAppDir.getCanonicalFile(); 2124 } catch (IOException e) { 2125 // failed to look up canonical path, continue with original one 2126 } 2127 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2128 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2129 2130 // Collect all OEM packages. 2131 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2132 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2133 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2134 2135 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2136 mInstaller.moveFiles(); 2137 2138 // Prune any system packages that no longer exist. 2139 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2140 if (!mOnlyCore) { 2141 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2142 while (psit.hasNext()) { 2143 PackageSetting ps = psit.next(); 2144 2145 /* 2146 * If this is not a system app, it can't be a 2147 * disable system app. 2148 */ 2149 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2150 continue; 2151 } 2152 2153 /* 2154 * If the package is scanned, it's not erased. 2155 */ 2156 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2157 if (scannedPkg != null) { 2158 /* 2159 * If the system app is both scanned and in the 2160 * disabled packages list, then it must have been 2161 * added via OTA. Remove it from the currently 2162 * scanned package so the previously user-installed 2163 * application can be scanned. 2164 */ 2165 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2166 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2167 + ps.name + "; removing system app. Last known codePath=" 2168 + ps.codePathString + ", installStatus=" + ps.installStatus 2169 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2170 + scannedPkg.mVersionCode); 2171 removePackageLI(ps, true); 2172 mExpectingBetter.put(ps.name, ps.codePath); 2173 } 2174 2175 continue; 2176 } 2177 2178 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2179 psit.remove(); 2180 logCriticalInfo(Log.WARN, "System package " + ps.name 2181 + " no longer exists; wiping its data"); 2182 removeDataDirsLI(null, ps.name); 2183 } else { 2184 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2185 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2186 possiblyDeletedUpdatedSystemApps.add(ps.name); 2187 } 2188 } 2189 } 2190 } 2191 2192 //look for any incomplete package installations 2193 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2194 //clean up list 2195 for(int i = 0; i < deletePkgsList.size(); i++) { 2196 //clean up here 2197 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2198 } 2199 //delete tmp files 2200 deleteTempPackageFiles(); 2201 2202 // Remove any shared userIDs that have no associated packages 2203 mSettings.pruneSharedUsersLPw(); 2204 2205 if (!mOnlyCore) { 2206 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2207 SystemClock.uptimeMillis()); 2208 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2209 2210 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2211 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2212 2213 /** 2214 * Remove disable package settings for any updated system 2215 * apps that were removed via an OTA. If they're not a 2216 * previously-updated app, remove them completely. 2217 * Otherwise, just revoke their system-level permissions. 2218 */ 2219 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2220 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2221 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2222 2223 String msg; 2224 if (deletedPkg == null) { 2225 msg = "Updated system package " + deletedAppName 2226 + " no longer exists; wiping its data"; 2227 removeDataDirsLI(null, deletedAppName); 2228 } else { 2229 msg = "Updated system app + " + deletedAppName 2230 + " no longer present; removing system privileges for " 2231 + deletedAppName; 2232 2233 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2234 2235 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2236 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2237 } 2238 logCriticalInfo(Log.WARN, msg); 2239 } 2240 2241 /** 2242 * Make sure all system apps that we expected to appear on 2243 * the userdata partition actually showed up. If they never 2244 * appeared, crawl back and revive the system version. 2245 */ 2246 for (int i = 0; i < mExpectingBetter.size(); i++) { 2247 final String packageName = mExpectingBetter.keyAt(i); 2248 if (!mPackages.containsKey(packageName)) { 2249 final File scanFile = mExpectingBetter.valueAt(i); 2250 2251 logCriticalInfo(Log.WARN, "Expected better " + packageName 2252 + " but never showed up; reverting to system"); 2253 2254 final int reparseFlags; 2255 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2256 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2257 | PackageParser.PARSE_IS_SYSTEM_DIR 2258 | PackageParser.PARSE_IS_PRIVILEGED; 2259 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2260 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2261 | PackageParser.PARSE_IS_SYSTEM_DIR; 2262 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2263 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2264 | PackageParser.PARSE_IS_SYSTEM_DIR; 2265 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2266 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2267 | PackageParser.PARSE_IS_SYSTEM_DIR; 2268 } else { 2269 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2270 continue; 2271 } 2272 2273 mSettings.enableSystemPackageLPw(packageName); 2274 2275 try { 2276 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2277 } catch (PackageManagerException e) { 2278 Slog.e(TAG, "Failed to parse original system package: " 2279 + e.getMessage()); 2280 } 2281 } 2282 } 2283 } 2284 mExpectingBetter.clear(); 2285 2286 // Now that we know all of the shared libraries, update all clients to have 2287 // the correct library paths. 2288 updateAllSharedLibrariesLPw(); 2289 2290 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2291 // NOTE: We ignore potential failures here during a system scan (like 2292 // the rest of the commands above) because there's precious little we 2293 // can do about it. A settings error is reported, though. 2294 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2295 false /* force dexopt */, false /* defer dexopt */); 2296 } 2297 2298 // Now that we know all the packages we are keeping, 2299 // read and update their last usage times. 2300 mPackageUsage.readLP(); 2301 2302 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2303 SystemClock.uptimeMillis()); 2304 Slog.i(TAG, "Time to scan packages: " 2305 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2306 + " seconds"); 2307 2308 // If the platform SDK has changed since the last time we booted, 2309 // we need to re-grant app permission to catch any new ones that 2310 // appear. This is really a hack, and means that apps can in some 2311 // cases get permissions that the user didn't initially explicitly 2312 // allow... it would be nice to have some better way to handle 2313 // this situation. 2314 int updateFlags = UPDATE_PERMISSIONS_ALL; 2315 if (ver.sdkVersion != mSdkVersion) { 2316 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2317 + mSdkVersion + "; regranting permissions for internal storage"); 2318 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2319 } 2320 updatePermissionsLPw(null, null, updateFlags); 2321 ver.sdkVersion = mSdkVersion; 2322 2323 // If this is the first boot or an update from pre-M, and it is a normal 2324 // boot, then we need to initialize the default preferred apps across 2325 // all defined users. 2326 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2327 for (UserInfo user : sUserManager.getUsers(true)) { 2328 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2329 applyFactoryDefaultBrowserLPw(user.id); 2330 primeDomainVerificationsLPw(user.id); 2331 } 2332 } 2333 2334 // If this is first boot after an OTA, and a normal boot, then 2335 // we need to clear code cache directories. 2336 if (mIsUpgrade && !onlyCore) { 2337 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2338 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2339 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2340 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2341 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2342 } 2343 } 2344 ver.fingerprint = Build.FINGERPRINT; 2345 } 2346 2347 checkDefaultBrowser(); 2348 2349 // clear only after permissions and other defaults have been updated 2350 mExistingSystemPackages.clear(); 2351 mPromoteSystemApps = false; 2352 2353 // All the changes are done during package scanning. 2354 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2355 2356 // can downgrade to reader 2357 mSettings.writeLPr(); 2358 2359 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2360 SystemClock.uptimeMillis()); 2361 2362 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2363 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2364 2365 mInstallerService = new PackageInstallerService(context, this); 2366 2367 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2368 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2369 mIntentFilterVerifierComponent); 2370 2371 } // synchronized (mPackages) 2372 } // synchronized (mInstallLock) 2373 2374 // Now after opening every single application zip, make sure they 2375 // are all flushed. Not really needed, but keeps things nice and 2376 // tidy. 2377 Runtime.getRuntime().gc(); 2378 2379 // Expose private service for system components to use. 2380 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2381 } 2382 2383 @Override 2384 public boolean isFirstBoot() { 2385 return !mRestoredSettings; 2386 } 2387 2388 @Override 2389 public boolean isOnlyCoreApps() { 2390 return mOnlyCore; 2391 } 2392 2393 @Override 2394 public boolean isUpgrade() { 2395 return mIsUpgrade; 2396 } 2397 2398 private String getRequiredVerifierLPr() { 2399 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2400 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2401 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2402 2403 String requiredVerifier = null; 2404 2405 final int N = receivers.size(); 2406 for (int i = 0; i < N; i++) { 2407 final ResolveInfo info = receivers.get(i); 2408 2409 if (info.activityInfo == null) { 2410 continue; 2411 } 2412 2413 final String packageName = info.activityInfo.packageName; 2414 2415 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2416 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2417 continue; 2418 } 2419 2420 if (requiredVerifier != null) { 2421 throw new RuntimeException("There can be only one required verifier"); 2422 } 2423 2424 requiredVerifier = packageName; 2425 } 2426 2427 return requiredVerifier; 2428 } 2429 2430 private String getRequiredInstallerLPr() { 2431 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2432 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2433 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2434 2435 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2436 PACKAGE_MIME_TYPE, 0, 0); 2437 2438 String requiredInstaller = null; 2439 2440 final int N = installers.size(); 2441 for (int i = 0; i < N; i++) { 2442 final ResolveInfo info = installers.get(i); 2443 final String packageName = info.activityInfo.packageName; 2444 2445 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2446 continue; 2447 } 2448 2449 if (requiredInstaller != null) { 2450 throw new RuntimeException("There must be one required installer"); 2451 } 2452 2453 requiredInstaller = packageName; 2454 } 2455 2456 if (requiredInstaller == null) { 2457 throw new RuntimeException("There must be one required installer"); 2458 } 2459 2460 return requiredInstaller; 2461 } 2462 2463 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2464 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2465 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2466 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2467 2468 ComponentName verifierComponentName = null; 2469 2470 int priority = -1000; 2471 final int N = receivers.size(); 2472 for (int i = 0; i < N; i++) { 2473 final ResolveInfo info = receivers.get(i); 2474 2475 if (info.activityInfo == null) { 2476 continue; 2477 } 2478 2479 final String packageName = info.activityInfo.packageName; 2480 2481 final PackageSetting ps = mSettings.mPackages.get(packageName); 2482 if (ps == null) { 2483 continue; 2484 } 2485 2486 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2487 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2488 continue; 2489 } 2490 2491 // Select the IntentFilterVerifier with the highest priority 2492 if (priority < info.priority) { 2493 priority = info.priority; 2494 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2495 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2496 + verifierComponentName + " with priority: " + info.priority); 2497 } 2498 } 2499 2500 return verifierComponentName; 2501 } 2502 2503 private void primeDomainVerificationsLPw(int userId) { 2504 if (DEBUG_DOMAIN_VERIFICATION) { 2505 Slog.d(TAG, "Priming domain verifications in user " + userId); 2506 } 2507 2508 SystemConfig systemConfig = SystemConfig.getInstance(); 2509 ArraySet<String> packages = systemConfig.getLinkedApps(); 2510 ArraySet<String> domains = new ArraySet<String>(); 2511 2512 for (String packageName : packages) { 2513 PackageParser.Package pkg = mPackages.get(packageName); 2514 if (pkg != null) { 2515 if (!pkg.isSystemApp()) { 2516 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2517 continue; 2518 } 2519 2520 domains.clear(); 2521 for (PackageParser.Activity a : pkg.activities) { 2522 for (ActivityIntentInfo filter : a.intents) { 2523 if (hasValidDomains(filter)) { 2524 domains.addAll(filter.getHostsList()); 2525 } 2526 } 2527 } 2528 2529 if (domains.size() > 0) { 2530 if (DEBUG_DOMAIN_VERIFICATION) { 2531 Slog.v(TAG, " + " + packageName); 2532 } 2533 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2534 // state w.r.t. the formal app-linkage "no verification attempted" state; 2535 // and then 'always' in the per-user state actually used for intent resolution. 2536 final IntentFilterVerificationInfo ivi; 2537 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2538 new ArrayList<String>(domains)); 2539 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2540 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2541 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2542 } else { 2543 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2544 + "' does not handle web links"); 2545 } 2546 } else { 2547 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2548 } 2549 } 2550 2551 scheduleWritePackageRestrictionsLocked(userId); 2552 scheduleWriteSettingsLocked(); 2553 } 2554 2555 private void applyFactoryDefaultBrowserLPw(int userId) { 2556 // The default browser app's package name is stored in a string resource, 2557 // with a product-specific overlay used for vendor customization. 2558 String browserPkg = mContext.getResources().getString( 2559 com.android.internal.R.string.default_browser); 2560 if (!TextUtils.isEmpty(browserPkg)) { 2561 // non-empty string => required to be a known package 2562 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2563 if (ps == null) { 2564 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2565 browserPkg = null; 2566 } else { 2567 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2568 } 2569 } 2570 2571 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2572 // default. If there's more than one, just leave everything alone. 2573 if (browserPkg == null) { 2574 calculateDefaultBrowserLPw(userId); 2575 } 2576 } 2577 2578 private void calculateDefaultBrowserLPw(int userId) { 2579 List<String> allBrowsers = resolveAllBrowserApps(userId); 2580 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2581 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2582 } 2583 2584 private List<String> resolveAllBrowserApps(int userId) { 2585 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2586 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2587 PackageManager.MATCH_ALL, userId); 2588 2589 final int count = list.size(); 2590 List<String> result = new ArrayList<String>(count); 2591 for (int i=0; i<count; i++) { 2592 ResolveInfo info = list.get(i); 2593 if (info.activityInfo == null 2594 || !info.handleAllWebDataURI 2595 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2596 || result.contains(info.activityInfo.packageName)) { 2597 continue; 2598 } 2599 result.add(info.activityInfo.packageName); 2600 } 2601 2602 return result; 2603 } 2604 2605 private boolean packageIsBrowser(String packageName, int userId) { 2606 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2607 PackageManager.MATCH_ALL, userId); 2608 final int N = list.size(); 2609 for (int i = 0; i < N; i++) { 2610 ResolveInfo info = list.get(i); 2611 if (packageName.equals(info.activityInfo.packageName)) { 2612 return true; 2613 } 2614 } 2615 return false; 2616 } 2617 2618 private void checkDefaultBrowser() { 2619 final int myUserId = UserHandle.myUserId(); 2620 final String packageName = getDefaultBrowserPackageName(myUserId); 2621 if (packageName != null) { 2622 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2623 if (info == null) { 2624 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2625 synchronized (mPackages) { 2626 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2627 } 2628 } 2629 } 2630 } 2631 2632 @Override 2633 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2634 throws RemoteException { 2635 try { 2636 return super.onTransact(code, data, reply, flags); 2637 } catch (RuntimeException e) { 2638 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2639 Slog.wtf(TAG, "Package Manager Crash", e); 2640 } 2641 throw e; 2642 } 2643 } 2644 2645 void cleanupInstallFailedPackage(PackageSetting ps) { 2646 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2647 2648 removeDataDirsLI(ps.volumeUuid, ps.name); 2649 if (ps.codePath != null) { 2650 if (ps.codePath.isDirectory()) { 2651 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2652 } else { 2653 ps.codePath.delete(); 2654 } 2655 } 2656 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2657 if (ps.resourcePath.isDirectory()) { 2658 FileUtils.deleteContents(ps.resourcePath); 2659 } 2660 ps.resourcePath.delete(); 2661 } 2662 mSettings.removePackageLPw(ps.name); 2663 } 2664 2665 static int[] appendInts(int[] cur, int[] add) { 2666 if (add == null) return cur; 2667 if (cur == null) return add; 2668 final int N = add.length; 2669 for (int i=0; i<N; i++) { 2670 cur = appendInt(cur, add[i]); 2671 } 2672 return cur; 2673 } 2674 2675 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2676 if (!sUserManager.exists(userId)) return null; 2677 final PackageSetting ps = (PackageSetting) p.mExtras; 2678 if (ps == null) { 2679 return null; 2680 } 2681 2682 final PermissionsState permissionsState = ps.getPermissionsState(); 2683 2684 final int[] gids = permissionsState.computeGids(userId); 2685 final Set<String> permissions = permissionsState.getPermissions(userId); 2686 final PackageUserState state = ps.readUserState(userId); 2687 2688 return PackageParser.generatePackageInfo(p, gids, flags, 2689 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2690 } 2691 2692 @Override 2693 public boolean isPackageFrozen(String packageName) { 2694 synchronized (mPackages) { 2695 final PackageSetting ps = mSettings.mPackages.get(packageName); 2696 if (ps != null) { 2697 return ps.frozen; 2698 } 2699 } 2700 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2701 return true; 2702 } 2703 2704 @Override 2705 public boolean isPackageAvailable(String packageName, int userId) { 2706 if (!sUserManager.exists(userId)) return false; 2707 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2708 synchronized (mPackages) { 2709 PackageParser.Package p = mPackages.get(packageName); 2710 if (p != null) { 2711 final PackageSetting ps = (PackageSetting) p.mExtras; 2712 if (ps != null) { 2713 final PackageUserState state = ps.readUserState(userId); 2714 if (state != null) { 2715 return PackageParser.isAvailable(state); 2716 } 2717 } 2718 } 2719 } 2720 return false; 2721 } 2722 2723 @Override 2724 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2725 if (!sUserManager.exists(userId)) return null; 2726 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2727 // reader 2728 synchronized (mPackages) { 2729 PackageParser.Package p = mPackages.get(packageName); 2730 if (DEBUG_PACKAGE_INFO) 2731 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2732 if (p != null) { 2733 return generatePackageInfo(p, flags, userId); 2734 } 2735 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2736 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2737 } 2738 } 2739 return null; 2740 } 2741 2742 @Override 2743 public String[] currentToCanonicalPackageNames(String[] names) { 2744 String[] out = new String[names.length]; 2745 // reader 2746 synchronized (mPackages) { 2747 for (int i=names.length-1; i>=0; i--) { 2748 PackageSetting ps = mSettings.mPackages.get(names[i]); 2749 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2750 } 2751 } 2752 return out; 2753 } 2754 2755 @Override 2756 public String[] canonicalToCurrentPackageNames(String[] names) { 2757 String[] out = new String[names.length]; 2758 // reader 2759 synchronized (mPackages) { 2760 for (int i=names.length-1; i>=0; i--) { 2761 String cur = mSettings.mRenamedPackages.get(names[i]); 2762 out[i] = cur != null ? cur : names[i]; 2763 } 2764 } 2765 return out; 2766 } 2767 2768 @Override 2769 public int getPackageUid(String packageName, int userId) { 2770 if (!sUserManager.exists(userId)) return -1; 2771 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2772 2773 // reader 2774 synchronized (mPackages) { 2775 PackageParser.Package p = mPackages.get(packageName); 2776 if(p != null) { 2777 return UserHandle.getUid(userId, p.applicationInfo.uid); 2778 } 2779 PackageSetting ps = mSettings.mPackages.get(packageName); 2780 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2781 return -1; 2782 } 2783 p = ps.pkg; 2784 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2785 } 2786 } 2787 2788 @Override 2789 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2790 if (!sUserManager.exists(userId)) { 2791 return null; 2792 } 2793 2794 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2795 "getPackageGids"); 2796 2797 // reader 2798 synchronized (mPackages) { 2799 PackageParser.Package p = mPackages.get(packageName); 2800 if (DEBUG_PACKAGE_INFO) { 2801 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2802 } 2803 if (p != null) { 2804 PackageSetting ps = (PackageSetting) p.mExtras; 2805 return ps.getPermissionsState().computeGids(userId); 2806 } 2807 } 2808 2809 return null; 2810 } 2811 2812 static PermissionInfo generatePermissionInfo( 2813 BasePermission bp, int flags) { 2814 if (bp.perm != null) { 2815 return PackageParser.generatePermissionInfo(bp.perm, flags); 2816 } 2817 PermissionInfo pi = new PermissionInfo(); 2818 pi.name = bp.name; 2819 pi.packageName = bp.sourcePackage; 2820 pi.nonLocalizedLabel = bp.name; 2821 pi.protectionLevel = bp.protectionLevel; 2822 return pi; 2823 } 2824 2825 @Override 2826 public PermissionInfo getPermissionInfo(String name, int flags) { 2827 // reader 2828 synchronized (mPackages) { 2829 final BasePermission p = mSettings.mPermissions.get(name); 2830 if (p != null) { 2831 return generatePermissionInfo(p, flags); 2832 } 2833 return null; 2834 } 2835 } 2836 2837 @Override 2838 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2839 // reader 2840 synchronized (mPackages) { 2841 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2842 for (BasePermission p : mSettings.mPermissions.values()) { 2843 if (group == null) { 2844 if (p.perm == null || p.perm.info.group == null) { 2845 out.add(generatePermissionInfo(p, flags)); 2846 } 2847 } else { 2848 if (p.perm != null && group.equals(p.perm.info.group)) { 2849 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2850 } 2851 } 2852 } 2853 2854 if (out.size() > 0) { 2855 return out; 2856 } 2857 return mPermissionGroups.containsKey(group) ? out : null; 2858 } 2859 } 2860 2861 @Override 2862 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2863 // reader 2864 synchronized (mPackages) { 2865 return PackageParser.generatePermissionGroupInfo( 2866 mPermissionGroups.get(name), flags); 2867 } 2868 } 2869 2870 @Override 2871 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2872 // reader 2873 synchronized (mPackages) { 2874 final int N = mPermissionGroups.size(); 2875 ArrayList<PermissionGroupInfo> out 2876 = new ArrayList<PermissionGroupInfo>(N); 2877 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2878 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2879 } 2880 return out; 2881 } 2882 } 2883 2884 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2885 int userId) { 2886 if (!sUserManager.exists(userId)) return null; 2887 PackageSetting ps = mSettings.mPackages.get(packageName); 2888 if (ps != null) { 2889 if (ps.pkg == null) { 2890 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2891 flags, userId); 2892 if (pInfo != null) { 2893 return pInfo.applicationInfo; 2894 } 2895 return null; 2896 } 2897 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2898 ps.readUserState(userId), userId); 2899 } 2900 return null; 2901 } 2902 2903 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2904 int userId) { 2905 if (!sUserManager.exists(userId)) return null; 2906 PackageSetting ps = mSettings.mPackages.get(packageName); 2907 if (ps != null) { 2908 PackageParser.Package pkg = ps.pkg; 2909 if (pkg == null) { 2910 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2911 return null; 2912 } 2913 // Only data remains, so we aren't worried about code paths 2914 pkg = new PackageParser.Package(packageName); 2915 pkg.applicationInfo.packageName = packageName; 2916 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2917 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2918 pkg.applicationInfo.dataDir = Environment 2919 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2920 .getAbsolutePath(); 2921 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2922 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2923 } 2924 return generatePackageInfo(pkg, flags, userId); 2925 } 2926 return null; 2927 } 2928 2929 @Override 2930 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2931 if (!sUserManager.exists(userId)) return null; 2932 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2933 // writer 2934 synchronized (mPackages) { 2935 PackageParser.Package p = mPackages.get(packageName); 2936 if (DEBUG_PACKAGE_INFO) Log.v( 2937 TAG, "getApplicationInfo " + packageName 2938 + ": " + p); 2939 if (p != null) { 2940 PackageSetting ps = mSettings.mPackages.get(packageName); 2941 if (ps == null) return null; 2942 // Note: isEnabledLP() does not apply here - always return info 2943 return PackageParser.generateApplicationInfo( 2944 p, flags, ps.readUserState(userId), userId); 2945 } 2946 if ("android".equals(packageName)||"system".equals(packageName)) { 2947 return mAndroidApplication; 2948 } 2949 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2950 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2951 } 2952 } 2953 return null; 2954 } 2955 2956 @Override 2957 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2958 final IPackageDataObserver observer) { 2959 mContext.enforceCallingOrSelfPermission( 2960 android.Manifest.permission.CLEAR_APP_CACHE, null); 2961 // Queue up an async operation since clearing cache may take a little while. 2962 mHandler.post(new Runnable() { 2963 public void run() { 2964 mHandler.removeCallbacks(this); 2965 int retCode = -1; 2966 synchronized (mInstallLock) { 2967 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2968 if (retCode < 0) { 2969 Slog.w(TAG, "Couldn't clear application caches"); 2970 } 2971 } 2972 if (observer != null) { 2973 try { 2974 observer.onRemoveCompleted(null, (retCode >= 0)); 2975 } catch (RemoteException e) { 2976 Slog.w(TAG, "RemoveException when invoking call back"); 2977 } 2978 } 2979 } 2980 }); 2981 } 2982 2983 @Override 2984 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2985 final IntentSender pi) { 2986 mContext.enforceCallingOrSelfPermission( 2987 android.Manifest.permission.CLEAR_APP_CACHE, null); 2988 // Queue up an async operation since clearing cache may take a little while. 2989 mHandler.post(new Runnable() { 2990 public void run() { 2991 mHandler.removeCallbacks(this); 2992 int retCode = -1; 2993 synchronized (mInstallLock) { 2994 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2995 if (retCode < 0) { 2996 Slog.w(TAG, "Couldn't clear application caches"); 2997 } 2998 } 2999 if(pi != null) { 3000 try { 3001 // Callback via pending intent 3002 int code = (retCode >= 0) ? 1 : 0; 3003 pi.sendIntent(null, code, null, 3004 null, null); 3005 } catch (SendIntentException e1) { 3006 Slog.i(TAG, "Failed to send pending intent"); 3007 } 3008 } 3009 } 3010 }); 3011 } 3012 3013 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3014 synchronized (mInstallLock) { 3015 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3016 throw new IOException("Failed to free enough space"); 3017 } 3018 } 3019 } 3020 3021 @Override 3022 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3023 if (!sUserManager.exists(userId)) return null; 3024 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3025 synchronized (mPackages) { 3026 PackageParser.Activity a = mActivities.mActivities.get(component); 3027 3028 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3029 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3030 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3031 if (ps == null) return null; 3032 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3033 userId); 3034 } 3035 if (mResolveComponentName.equals(component)) { 3036 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3037 new PackageUserState(), userId); 3038 } 3039 } 3040 return null; 3041 } 3042 3043 @Override 3044 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3045 String resolvedType) { 3046 synchronized (mPackages) { 3047 if (component.equals(mResolveComponentName)) { 3048 // The resolver supports EVERYTHING! 3049 return true; 3050 } 3051 PackageParser.Activity a = mActivities.mActivities.get(component); 3052 if (a == null) { 3053 return false; 3054 } 3055 for (int i=0; i<a.intents.size(); i++) { 3056 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3057 intent.getData(), intent.getCategories(), TAG) >= 0) { 3058 return true; 3059 } 3060 } 3061 return false; 3062 } 3063 } 3064 3065 @Override 3066 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3067 if (!sUserManager.exists(userId)) return null; 3068 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3069 synchronized (mPackages) { 3070 PackageParser.Activity a = mReceivers.mActivities.get(component); 3071 if (DEBUG_PACKAGE_INFO) Log.v( 3072 TAG, "getReceiverInfo " + component + ": " + a); 3073 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3074 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3075 if (ps == null) return null; 3076 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3077 userId); 3078 } 3079 } 3080 return null; 3081 } 3082 3083 @Override 3084 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3085 if (!sUserManager.exists(userId)) return null; 3086 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3087 synchronized (mPackages) { 3088 PackageParser.Service s = mServices.mServices.get(component); 3089 if (DEBUG_PACKAGE_INFO) Log.v( 3090 TAG, "getServiceInfo " + component + ": " + s); 3091 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3092 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3093 if (ps == null) return null; 3094 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3095 userId); 3096 } 3097 } 3098 return null; 3099 } 3100 3101 @Override 3102 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3103 if (!sUserManager.exists(userId)) return null; 3104 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3105 synchronized (mPackages) { 3106 PackageParser.Provider p = mProviders.mProviders.get(component); 3107 if (DEBUG_PACKAGE_INFO) Log.v( 3108 TAG, "getProviderInfo " + component + ": " + p); 3109 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3110 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3111 if (ps == null) return null; 3112 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3113 userId); 3114 } 3115 } 3116 return null; 3117 } 3118 3119 @Override 3120 public String[] getSystemSharedLibraryNames() { 3121 Set<String> libSet; 3122 synchronized (mPackages) { 3123 libSet = mSharedLibraries.keySet(); 3124 int size = libSet.size(); 3125 if (size > 0) { 3126 String[] libs = new String[size]; 3127 libSet.toArray(libs); 3128 return libs; 3129 } 3130 } 3131 return null; 3132 } 3133 3134 /** 3135 * @hide 3136 */ 3137 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3138 synchronized (mPackages) { 3139 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3140 if (lib != null && lib.apk != null) { 3141 return mPackages.get(lib.apk); 3142 } 3143 } 3144 return null; 3145 } 3146 3147 @Override 3148 public FeatureInfo[] getSystemAvailableFeatures() { 3149 Collection<FeatureInfo> featSet; 3150 synchronized (mPackages) { 3151 featSet = mAvailableFeatures.values(); 3152 int size = featSet.size(); 3153 if (size > 0) { 3154 FeatureInfo[] features = new FeatureInfo[size+1]; 3155 featSet.toArray(features); 3156 FeatureInfo fi = new FeatureInfo(); 3157 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3158 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3159 features[size] = fi; 3160 return features; 3161 } 3162 } 3163 return null; 3164 } 3165 3166 @Override 3167 public boolean hasSystemFeature(String name) { 3168 synchronized (mPackages) { 3169 return mAvailableFeatures.containsKey(name); 3170 } 3171 } 3172 3173 private void checkValidCaller(int uid, int userId) { 3174 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3175 return; 3176 3177 throw new SecurityException("Caller uid=" + uid 3178 + " is not privileged to communicate with user=" + userId); 3179 } 3180 3181 @Override 3182 public int checkPermission(String permName, String pkgName, int userId) { 3183 if (!sUserManager.exists(userId)) { 3184 return PackageManager.PERMISSION_DENIED; 3185 } 3186 3187 synchronized (mPackages) { 3188 final PackageParser.Package p = mPackages.get(pkgName); 3189 if (p != null && p.mExtras != null) { 3190 final PackageSetting ps = (PackageSetting) p.mExtras; 3191 final PermissionsState permissionsState = ps.getPermissionsState(); 3192 if (permissionsState.hasPermission(permName, userId)) { 3193 return PackageManager.PERMISSION_GRANTED; 3194 } 3195 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3196 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3197 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3198 return PackageManager.PERMISSION_GRANTED; 3199 } 3200 } 3201 } 3202 3203 return PackageManager.PERMISSION_DENIED; 3204 } 3205 3206 @Override 3207 public int checkUidPermission(String permName, int uid) { 3208 final int userId = UserHandle.getUserId(uid); 3209 3210 if (!sUserManager.exists(userId)) { 3211 return PackageManager.PERMISSION_DENIED; 3212 } 3213 3214 synchronized (mPackages) { 3215 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3216 if (obj != null) { 3217 final SettingBase ps = (SettingBase) obj; 3218 final PermissionsState permissionsState = ps.getPermissionsState(); 3219 if (permissionsState.hasPermission(permName, userId)) { 3220 return PackageManager.PERMISSION_GRANTED; 3221 } 3222 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3223 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3224 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3225 return PackageManager.PERMISSION_GRANTED; 3226 } 3227 } else { 3228 ArraySet<String> perms = mSystemPermissions.get(uid); 3229 if (perms != null) { 3230 if (perms.contains(permName)) { 3231 return PackageManager.PERMISSION_GRANTED; 3232 } 3233 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3234 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3235 return PackageManager.PERMISSION_GRANTED; 3236 } 3237 } 3238 } 3239 } 3240 3241 return PackageManager.PERMISSION_DENIED; 3242 } 3243 3244 @Override 3245 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3246 if (UserHandle.getCallingUserId() != userId) { 3247 mContext.enforceCallingPermission( 3248 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3249 "isPermissionRevokedByPolicy for user " + userId); 3250 } 3251 3252 if (checkPermission(permission, packageName, userId) 3253 == PackageManager.PERMISSION_GRANTED) { 3254 return false; 3255 } 3256 3257 final long identity = Binder.clearCallingIdentity(); 3258 try { 3259 final int flags = getPermissionFlags(permission, packageName, userId); 3260 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3261 } finally { 3262 Binder.restoreCallingIdentity(identity); 3263 } 3264 } 3265 3266 @Override 3267 public String getPermissionControllerPackageName() { 3268 synchronized (mPackages) { 3269 return mRequiredInstallerPackage; 3270 } 3271 } 3272 3273 /** 3274 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3275 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3276 * @param checkShell TODO(yamasani): 3277 * @param message the message to log on security exception 3278 */ 3279 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3280 boolean checkShell, String message) { 3281 if (userId < 0) { 3282 throw new IllegalArgumentException("Invalid userId " + userId); 3283 } 3284 if (checkShell) { 3285 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3286 } 3287 if (userId == UserHandle.getUserId(callingUid)) return; 3288 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3289 if (requireFullPermission) { 3290 mContext.enforceCallingOrSelfPermission( 3291 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3292 } else { 3293 try { 3294 mContext.enforceCallingOrSelfPermission( 3295 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3296 } catch (SecurityException se) { 3297 mContext.enforceCallingOrSelfPermission( 3298 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3299 } 3300 } 3301 } 3302 } 3303 3304 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3305 if (callingUid == Process.SHELL_UID) { 3306 if (userHandle >= 0 3307 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3308 throw new SecurityException("Shell does not have permission to access user " 3309 + userHandle); 3310 } else if (userHandle < 0) { 3311 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3312 + Debug.getCallers(3)); 3313 } 3314 } 3315 } 3316 3317 private BasePermission findPermissionTreeLP(String permName) { 3318 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3319 if (permName.startsWith(bp.name) && 3320 permName.length() > bp.name.length() && 3321 permName.charAt(bp.name.length()) == '.') { 3322 return bp; 3323 } 3324 } 3325 return null; 3326 } 3327 3328 private BasePermission checkPermissionTreeLP(String permName) { 3329 if (permName != null) { 3330 BasePermission bp = findPermissionTreeLP(permName); 3331 if (bp != null) { 3332 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3333 return bp; 3334 } 3335 throw new SecurityException("Calling uid " 3336 + Binder.getCallingUid() 3337 + " is not allowed to add to permission tree " 3338 + bp.name + " owned by uid " + bp.uid); 3339 } 3340 } 3341 throw new SecurityException("No permission tree found for " + permName); 3342 } 3343 3344 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3345 if (s1 == null) { 3346 return s2 == null; 3347 } 3348 if (s2 == null) { 3349 return false; 3350 } 3351 if (s1.getClass() != s2.getClass()) { 3352 return false; 3353 } 3354 return s1.equals(s2); 3355 } 3356 3357 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3358 if (pi1.icon != pi2.icon) return false; 3359 if (pi1.logo != pi2.logo) return false; 3360 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3361 if (!compareStrings(pi1.name, pi2.name)) return false; 3362 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3363 // We'll take care of setting this one. 3364 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3365 // These are not currently stored in settings. 3366 //if (!compareStrings(pi1.group, pi2.group)) return false; 3367 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3368 //if (pi1.labelRes != pi2.labelRes) return false; 3369 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3370 return true; 3371 } 3372 3373 int permissionInfoFootprint(PermissionInfo info) { 3374 int size = info.name.length(); 3375 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3376 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3377 return size; 3378 } 3379 3380 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3381 int size = 0; 3382 for (BasePermission perm : mSettings.mPermissions.values()) { 3383 if (perm.uid == tree.uid) { 3384 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3385 } 3386 } 3387 return size; 3388 } 3389 3390 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3391 // We calculate the max size of permissions defined by this uid and throw 3392 // if that plus the size of 'info' would exceed our stated maximum. 3393 if (tree.uid != Process.SYSTEM_UID) { 3394 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3395 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3396 throw new SecurityException("Permission tree size cap exceeded"); 3397 } 3398 } 3399 } 3400 3401 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3402 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3403 throw new SecurityException("Label must be specified in permission"); 3404 } 3405 BasePermission tree = checkPermissionTreeLP(info.name); 3406 BasePermission bp = mSettings.mPermissions.get(info.name); 3407 boolean added = bp == null; 3408 boolean changed = true; 3409 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3410 if (added) { 3411 enforcePermissionCapLocked(info, tree); 3412 bp = new BasePermission(info.name, tree.sourcePackage, 3413 BasePermission.TYPE_DYNAMIC); 3414 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3415 throw new SecurityException( 3416 "Not allowed to modify non-dynamic permission " 3417 + info.name); 3418 } else { 3419 if (bp.protectionLevel == fixedLevel 3420 && bp.perm.owner.equals(tree.perm.owner) 3421 && bp.uid == tree.uid 3422 && comparePermissionInfos(bp.perm.info, info)) { 3423 changed = false; 3424 } 3425 } 3426 bp.protectionLevel = fixedLevel; 3427 info = new PermissionInfo(info); 3428 info.protectionLevel = fixedLevel; 3429 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3430 bp.perm.info.packageName = tree.perm.info.packageName; 3431 bp.uid = tree.uid; 3432 if (added) { 3433 mSettings.mPermissions.put(info.name, bp); 3434 } 3435 if (changed) { 3436 if (!async) { 3437 mSettings.writeLPr(); 3438 } else { 3439 scheduleWriteSettingsLocked(); 3440 } 3441 } 3442 return added; 3443 } 3444 3445 @Override 3446 public boolean addPermission(PermissionInfo info) { 3447 synchronized (mPackages) { 3448 return addPermissionLocked(info, false); 3449 } 3450 } 3451 3452 @Override 3453 public boolean addPermissionAsync(PermissionInfo info) { 3454 synchronized (mPackages) { 3455 return addPermissionLocked(info, true); 3456 } 3457 } 3458 3459 @Override 3460 public void removePermission(String name) { 3461 synchronized (mPackages) { 3462 checkPermissionTreeLP(name); 3463 BasePermission bp = mSettings.mPermissions.get(name); 3464 if (bp != null) { 3465 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3466 throw new SecurityException( 3467 "Not allowed to modify non-dynamic permission " 3468 + name); 3469 } 3470 mSettings.mPermissions.remove(name); 3471 mSettings.writeLPr(); 3472 } 3473 } 3474 } 3475 3476 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3477 BasePermission bp) { 3478 int index = pkg.requestedPermissions.indexOf(bp.name); 3479 if (index == -1) { 3480 throw new SecurityException("Package " + pkg.packageName 3481 + " has not requested permission " + bp.name); 3482 } 3483 if (!bp.isRuntime() && !bp.isDevelopment()) { 3484 throw new SecurityException("Permission " + bp.name 3485 + " is not a changeable permission type"); 3486 } 3487 } 3488 3489 @Override 3490 public void grantRuntimePermission(String packageName, String name, final int userId) { 3491 if (!sUserManager.exists(userId)) { 3492 Log.e(TAG, "No such user:" + userId); 3493 return; 3494 } 3495 3496 mContext.enforceCallingOrSelfPermission( 3497 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3498 "grantRuntimePermission"); 3499 3500 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3501 "grantRuntimePermission"); 3502 3503 final int uid; 3504 final SettingBase sb; 3505 3506 synchronized (mPackages) { 3507 final PackageParser.Package pkg = mPackages.get(packageName); 3508 if (pkg == null) { 3509 throw new IllegalArgumentException("Unknown package: " + packageName); 3510 } 3511 3512 final BasePermission bp = mSettings.mPermissions.get(name); 3513 if (bp == null) { 3514 throw new IllegalArgumentException("Unknown permission: " + name); 3515 } 3516 3517 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3518 3519 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3520 sb = (SettingBase) pkg.mExtras; 3521 if (sb == null) { 3522 throw new IllegalArgumentException("Unknown package: " + packageName); 3523 } 3524 3525 final PermissionsState permissionsState = sb.getPermissionsState(); 3526 3527 final int flags = permissionsState.getPermissionFlags(name, userId); 3528 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3529 throw new SecurityException("Cannot grant system fixed permission: " 3530 + name + " for package: " + packageName); 3531 } 3532 3533 if (bp.isDevelopment()) { 3534 // Development permissions must be handled specially, since they are not 3535 // normal runtime permissions. For now they apply to all users. 3536 if (permissionsState.grantInstallPermission(bp) != 3537 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3538 scheduleWriteSettingsLocked(); 3539 } 3540 return; 3541 } 3542 3543 final int result = permissionsState.grantRuntimePermission(bp, userId); 3544 switch (result) { 3545 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3546 return; 3547 } 3548 3549 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3550 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3551 mHandler.post(new Runnable() { 3552 @Override 3553 public void run() { 3554 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3555 } 3556 }); 3557 } break; 3558 } 3559 3560 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3561 3562 // Not critical if that is lost - app has to request again. 3563 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3564 } 3565 3566 // Only need to do this if user is initialized. Otherwise it's a new user 3567 // and there are no processes running as the user yet and there's no need 3568 // to make an expensive call to remount processes for the changed permissions. 3569 if (READ_EXTERNAL_STORAGE.equals(name) 3570 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3571 final long token = Binder.clearCallingIdentity(); 3572 try { 3573 if (sUserManager.isInitialized(userId)) { 3574 MountServiceInternal mountServiceInternal = LocalServices.getService( 3575 MountServiceInternal.class); 3576 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3577 } 3578 } finally { 3579 Binder.restoreCallingIdentity(token); 3580 } 3581 } 3582 } 3583 3584 @Override 3585 public void revokeRuntimePermission(String packageName, String name, int userId) { 3586 if (!sUserManager.exists(userId)) { 3587 Log.e(TAG, "No such user:" + userId); 3588 return; 3589 } 3590 3591 mContext.enforceCallingOrSelfPermission( 3592 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3593 "revokeRuntimePermission"); 3594 3595 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3596 "revokeRuntimePermission"); 3597 3598 final int appId; 3599 3600 synchronized (mPackages) { 3601 final PackageParser.Package pkg = mPackages.get(packageName); 3602 if (pkg == null) { 3603 throw new IllegalArgumentException("Unknown package: " + packageName); 3604 } 3605 3606 final BasePermission bp = mSettings.mPermissions.get(name); 3607 if (bp == null) { 3608 throw new IllegalArgumentException("Unknown permission: " + name); 3609 } 3610 3611 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3612 3613 SettingBase sb = (SettingBase) pkg.mExtras; 3614 if (sb == null) { 3615 throw new IllegalArgumentException("Unknown package: " + packageName); 3616 } 3617 3618 final PermissionsState permissionsState = sb.getPermissionsState(); 3619 3620 final int flags = permissionsState.getPermissionFlags(name, userId); 3621 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3622 throw new SecurityException("Cannot revoke system fixed permission: " 3623 + name + " for package: " + packageName); 3624 } 3625 3626 if (bp.isDevelopment()) { 3627 // Development permissions must be handled specially, since they are not 3628 // normal runtime permissions. For now they apply to all users. 3629 if (permissionsState.revokeInstallPermission(bp) != 3630 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3631 scheduleWriteSettingsLocked(); 3632 } 3633 return; 3634 } 3635 3636 if (permissionsState.revokeRuntimePermission(bp, userId) == 3637 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3638 return; 3639 } 3640 3641 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3642 3643 // Critical, after this call app should never have the permission. 3644 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3645 3646 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3647 } 3648 3649 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3650 } 3651 3652 @Override 3653 public void resetRuntimePermissions() { 3654 mContext.enforceCallingOrSelfPermission( 3655 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3656 "revokeRuntimePermission"); 3657 3658 int callingUid = Binder.getCallingUid(); 3659 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3660 mContext.enforceCallingOrSelfPermission( 3661 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3662 "resetRuntimePermissions"); 3663 } 3664 3665 synchronized (mPackages) { 3666 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3667 for (int userId : UserManagerService.getInstance().getUserIds()) { 3668 final int packageCount = mPackages.size(); 3669 for (int i = 0; i < packageCount; i++) { 3670 PackageParser.Package pkg = mPackages.valueAt(i); 3671 if (!(pkg.mExtras instanceof PackageSetting)) { 3672 continue; 3673 } 3674 PackageSetting ps = (PackageSetting) pkg.mExtras; 3675 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3676 } 3677 } 3678 } 3679 } 3680 3681 @Override 3682 public int getPermissionFlags(String name, String packageName, int userId) { 3683 if (!sUserManager.exists(userId)) { 3684 return 0; 3685 } 3686 3687 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3688 3689 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3690 "getPermissionFlags"); 3691 3692 synchronized (mPackages) { 3693 final PackageParser.Package pkg = mPackages.get(packageName); 3694 if (pkg == null) { 3695 throw new IllegalArgumentException("Unknown package: " + packageName); 3696 } 3697 3698 final BasePermission bp = mSettings.mPermissions.get(name); 3699 if (bp == null) { 3700 throw new IllegalArgumentException("Unknown permission: " + name); 3701 } 3702 3703 SettingBase sb = (SettingBase) pkg.mExtras; 3704 if (sb == null) { 3705 throw new IllegalArgumentException("Unknown package: " + packageName); 3706 } 3707 3708 PermissionsState permissionsState = sb.getPermissionsState(); 3709 return permissionsState.getPermissionFlags(name, userId); 3710 } 3711 } 3712 3713 @Override 3714 public void updatePermissionFlags(String name, String packageName, int flagMask, 3715 int flagValues, int userId) { 3716 if (!sUserManager.exists(userId)) { 3717 return; 3718 } 3719 3720 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3721 3722 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3723 "updatePermissionFlags"); 3724 3725 // Only the system can change these flags and nothing else. 3726 if (getCallingUid() != Process.SYSTEM_UID) { 3727 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3728 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3729 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3730 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3731 } 3732 3733 synchronized (mPackages) { 3734 final PackageParser.Package pkg = mPackages.get(packageName); 3735 if (pkg == null) { 3736 throw new IllegalArgumentException("Unknown package: " + packageName); 3737 } 3738 3739 final BasePermission bp = mSettings.mPermissions.get(name); 3740 if (bp == null) { 3741 throw new IllegalArgumentException("Unknown permission: " + name); 3742 } 3743 3744 SettingBase sb = (SettingBase) pkg.mExtras; 3745 if (sb == null) { 3746 throw new IllegalArgumentException("Unknown package: " + packageName); 3747 } 3748 3749 PermissionsState permissionsState = sb.getPermissionsState(); 3750 3751 // Only the package manager can change flags for system component permissions. 3752 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3753 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3754 return; 3755 } 3756 3757 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3758 3759 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3760 // Install and runtime permissions are stored in different places, 3761 // so figure out what permission changed and persist the change. 3762 if (permissionsState.getInstallPermissionState(name) != null) { 3763 scheduleWriteSettingsLocked(); 3764 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3765 || hadState) { 3766 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3767 } 3768 } 3769 } 3770 } 3771 3772 /** 3773 * Update the permission flags for all packages and runtime permissions of a user in order 3774 * to allow device or profile owner to remove POLICY_FIXED. 3775 */ 3776 @Override 3777 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3778 if (!sUserManager.exists(userId)) { 3779 return; 3780 } 3781 3782 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3783 3784 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3785 "updatePermissionFlagsForAllApps"); 3786 3787 // Only the system can change system fixed flags. 3788 if (getCallingUid() != Process.SYSTEM_UID) { 3789 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3790 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3791 } 3792 3793 synchronized (mPackages) { 3794 boolean changed = false; 3795 final int packageCount = mPackages.size(); 3796 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3797 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3798 SettingBase sb = (SettingBase) pkg.mExtras; 3799 if (sb == null) { 3800 continue; 3801 } 3802 PermissionsState permissionsState = sb.getPermissionsState(); 3803 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3804 userId, flagMask, flagValues); 3805 } 3806 if (changed) { 3807 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3808 } 3809 } 3810 } 3811 3812 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3813 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3814 != PackageManager.PERMISSION_GRANTED 3815 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3816 != PackageManager.PERMISSION_GRANTED) { 3817 throw new SecurityException(message + " requires " 3818 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3819 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3820 } 3821 } 3822 3823 @Override 3824 public boolean shouldShowRequestPermissionRationale(String permissionName, 3825 String packageName, int userId) { 3826 if (UserHandle.getCallingUserId() != userId) { 3827 mContext.enforceCallingPermission( 3828 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3829 "canShowRequestPermissionRationale for user " + userId); 3830 } 3831 3832 final int uid = getPackageUid(packageName, userId); 3833 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3834 return false; 3835 } 3836 3837 if (checkPermission(permissionName, packageName, userId) 3838 == PackageManager.PERMISSION_GRANTED) { 3839 return false; 3840 } 3841 3842 final int flags; 3843 3844 final long identity = Binder.clearCallingIdentity(); 3845 try { 3846 flags = getPermissionFlags(permissionName, 3847 packageName, userId); 3848 } finally { 3849 Binder.restoreCallingIdentity(identity); 3850 } 3851 3852 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3853 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3854 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3855 3856 if ((flags & fixedFlags) != 0) { 3857 return false; 3858 } 3859 3860 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3861 } 3862 3863 @Override 3864 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3865 mContext.enforceCallingOrSelfPermission( 3866 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3867 "addOnPermissionsChangeListener"); 3868 3869 synchronized (mPackages) { 3870 mOnPermissionChangeListeners.addListenerLocked(listener); 3871 } 3872 } 3873 3874 @Override 3875 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3876 synchronized (mPackages) { 3877 mOnPermissionChangeListeners.removeListenerLocked(listener); 3878 } 3879 } 3880 3881 @Override 3882 public boolean isProtectedBroadcast(String actionName) { 3883 synchronized (mPackages) { 3884 return mProtectedBroadcasts.contains(actionName); 3885 } 3886 } 3887 3888 @Override 3889 public int checkSignatures(String pkg1, String pkg2) { 3890 synchronized (mPackages) { 3891 final PackageParser.Package p1 = mPackages.get(pkg1); 3892 final PackageParser.Package p2 = mPackages.get(pkg2); 3893 if (p1 == null || p1.mExtras == null 3894 || p2 == null || p2.mExtras == null) { 3895 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3896 } 3897 return compareSignatures(p1.mSignatures, p2.mSignatures); 3898 } 3899 } 3900 3901 @Override 3902 public int checkUidSignatures(int uid1, int uid2) { 3903 // Map to base uids. 3904 uid1 = UserHandle.getAppId(uid1); 3905 uid2 = UserHandle.getAppId(uid2); 3906 // reader 3907 synchronized (mPackages) { 3908 Signature[] s1; 3909 Signature[] s2; 3910 Object obj = mSettings.getUserIdLPr(uid1); 3911 if (obj != null) { 3912 if (obj instanceof SharedUserSetting) { 3913 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3914 } else if (obj instanceof PackageSetting) { 3915 s1 = ((PackageSetting)obj).signatures.mSignatures; 3916 } else { 3917 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3918 } 3919 } else { 3920 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3921 } 3922 obj = mSettings.getUserIdLPr(uid2); 3923 if (obj != null) { 3924 if (obj instanceof SharedUserSetting) { 3925 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3926 } else if (obj instanceof PackageSetting) { 3927 s2 = ((PackageSetting)obj).signatures.mSignatures; 3928 } else { 3929 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3930 } 3931 } else { 3932 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3933 } 3934 return compareSignatures(s1, s2); 3935 } 3936 } 3937 3938 private void killUid(int appId, int userId, String reason) { 3939 final long identity = Binder.clearCallingIdentity(); 3940 try { 3941 IActivityManager am = ActivityManagerNative.getDefault(); 3942 if (am != null) { 3943 try { 3944 am.killUid(appId, userId, reason); 3945 } catch (RemoteException e) { 3946 /* ignore - same process */ 3947 } 3948 } 3949 } finally { 3950 Binder.restoreCallingIdentity(identity); 3951 } 3952 } 3953 3954 /** 3955 * Compares two sets of signatures. Returns: 3956 * <br /> 3957 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3958 * <br /> 3959 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3960 * <br /> 3961 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3962 * <br /> 3963 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3964 * <br /> 3965 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3966 */ 3967 static int compareSignatures(Signature[] s1, Signature[] s2) { 3968 if (s1 == null) { 3969 return s2 == null 3970 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3971 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3972 } 3973 3974 if (s2 == null) { 3975 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3976 } 3977 3978 if (s1.length != s2.length) { 3979 return PackageManager.SIGNATURE_NO_MATCH; 3980 } 3981 3982 // Since both signature sets are of size 1, we can compare without HashSets. 3983 if (s1.length == 1) { 3984 return s1[0].equals(s2[0]) ? 3985 PackageManager.SIGNATURE_MATCH : 3986 PackageManager.SIGNATURE_NO_MATCH; 3987 } 3988 3989 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3990 for (Signature sig : s1) { 3991 set1.add(sig); 3992 } 3993 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3994 for (Signature sig : s2) { 3995 set2.add(sig); 3996 } 3997 // Make sure s2 contains all signatures in s1. 3998 if (set1.equals(set2)) { 3999 return PackageManager.SIGNATURE_MATCH; 4000 } 4001 return PackageManager.SIGNATURE_NO_MATCH; 4002 } 4003 4004 /** 4005 * If the database version for this type of package (internal storage or 4006 * external storage) is less than the version where package signatures 4007 * were updated, return true. 4008 */ 4009 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4010 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4011 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4012 } 4013 4014 /** 4015 * Used for backward compatibility to make sure any packages with 4016 * certificate chains get upgraded to the new style. {@code existingSigs} 4017 * will be in the old format (since they were stored on disk from before the 4018 * system upgrade) and {@code scannedSigs} will be in the newer format. 4019 */ 4020 private int compareSignaturesCompat(PackageSignatures existingSigs, 4021 PackageParser.Package scannedPkg) { 4022 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4023 return PackageManager.SIGNATURE_NO_MATCH; 4024 } 4025 4026 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4027 for (Signature sig : existingSigs.mSignatures) { 4028 existingSet.add(sig); 4029 } 4030 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4031 for (Signature sig : scannedPkg.mSignatures) { 4032 try { 4033 Signature[] chainSignatures = sig.getChainSignatures(); 4034 for (Signature chainSig : chainSignatures) { 4035 scannedCompatSet.add(chainSig); 4036 } 4037 } catch (CertificateEncodingException e) { 4038 scannedCompatSet.add(sig); 4039 } 4040 } 4041 /* 4042 * Make sure the expanded scanned set contains all signatures in the 4043 * existing one. 4044 */ 4045 if (scannedCompatSet.equals(existingSet)) { 4046 // Migrate the old signatures to the new scheme. 4047 existingSigs.assignSignatures(scannedPkg.mSignatures); 4048 // The new KeySets will be re-added later in the scanning process. 4049 synchronized (mPackages) { 4050 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4051 } 4052 return PackageManager.SIGNATURE_MATCH; 4053 } 4054 return PackageManager.SIGNATURE_NO_MATCH; 4055 } 4056 4057 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4058 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4059 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4060 } 4061 4062 private int compareSignaturesRecover(PackageSignatures existingSigs, 4063 PackageParser.Package scannedPkg) { 4064 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4065 return PackageManager.SIGNATURE_NO_MATCH; 4066 } 4067 4068 String msg = null; 4069 try { 4070 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4071 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4072 + scannedPkg.packageName); 4073 return PackageManager.SIGNATURE_MATCH; 4074 } 4075 } catch (CertificateException e) { 4076 msg = e.getMessage(); 4077 } 4078 4079 logCriticalInfo(Log.INFO, 4080 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4081 return PackageManager.SIGNATURE_NO_MATCH; 4082 } 4083 4084 @Override 4085 public String[] getPackagesForUid(int uid) { 4086 uid = UserHandle.getAppId(uid); 4087 // reader 4088 synchronized (mPackages) { 4089 Object obj = mSettings.getUserIdLPr(uid); 4090 if (obj instanceof SharedUserSetting) { 4091 final SharedUserSetting sus = (SharedUserSetting) obj; 4092 final int N = sus.packages.size(); 4093 final String[] res = new String[N]; 4094 final Iterator<PackageSetting> it = sus.packages.iterator(); 4095 int i = 0; 4096 while (it.hasNext()) { 4097 res[i++] = it.next().name; 4098 } 4099 return res; 4100 } else if (obj instanceof PackageSetting) { 4101 final PackageSetting ps = (PackageSetting) obj; 4102 return new String[] { ps.name }; 4103 } 4104 } 4105 return null; 4106 } 4107 4108 @Override 4109 public String getNameForUid(int uid) { 4110 // reader 4111 synchronized (mPackages) { 4112 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4113 if (obj instanceof SharedUserSetting) { 4114 final SharedUserSetting sus = (SharedUserSetting) obj; 4115 return sus.name + ":" + sus.userId; 4116 } else if (obj instanceof PackageSetting) { 4117 final PackageSetting ps = (PackageSetting) obj; 4118 return ps.name; 4119 } 4120 } 4121 return null; 4122 } 4123 4124 @Override 4125 public int getUidForSharedUser(String sharedUserName) { 4126 if(sharedUserName == null) { 4127 return -1; 4128 } 4129 // reader 4130 synchronized (mPackages) { 4131 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4132 if (suid == null) { 4133 return -1; 4134 } 4135 return suid.userId; 4136 } 4137 } 4138 4139 @Override 4140 public int getFlagsForUid(int uid) { 4141 synchronized (mPackages) { 4142 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4143 if (obj instanceof SharedUserSetting) { 4144 final SharedUserSetting sus = (SharedUserSetting) obj; 4145 return sus.pkgFlags; 4146 } else if (obj instanceof PackageSetting) { 4147 final PackageSetting ps = (PackageSetting) obj; 4148 return ps.pkgFlags; 4149 } 4150 } 4151 return 0; 4152 } 4153 4154 @Override 4155 public int getPrivateFlagsForUid(int uid) { 4156 synchronized (mPackages) { 4157 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4158 if (obj instanceof SharedUserSetting) { 4159 final SharedUserSetting sus = (SharedUserSetting) obj; 4160 return sus.pkgPrivateFlags; 4161 } else if (obj instanceof PackageSetting) { 4162 final PackageSetting ps = (PackageSetting) obj; 4163 return ps.pkgPrivateFlags; 4164 } 4165 } 4166 return 0; 4167 } 4168 4169 @Override 4170 public boolean isUidPrivileged(int uid) { 4171 uid = UserHandle.getAppId(uid); 4172 // reader 4173 synchronized (mPackages) { 4174 Object obj = mSettings.getUserIdLPr(uid); 4175 if (obj instanceof SharedUserSetting) { 4176 final SharedUserSetting sus = (SharedUserSetting) obj; 4177 final Iterator<PackageSetting> it = sus.packages.iterator(); 4178 while (it.hasNext()) { 4179 if (it.next().isPrivileged()) { 4180 return true; 4181 } 4182 } 4183 } else if (obj instanceof PackageSetting) { 4184 final PackageSetting ps = (PackageSetting) obj; 4185 return ps.isPrivileged(); 4186 } 4187 } 4188 return false; 4189 } 4190 4191 @Override 4192 public String[] getAppOpPermissionPackages(String permissionName) { 4193 synchronized (mPackages) { 4194 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4195 if (pkgs == null) { 4196 return null; 4197 } 4198 return pkgs.toArray(new String[pkgs.size()]); 4199 } 4200 } 4201 4202 @Override 4203 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4204 int flags, int userId) { 4205 if (!sUserManager.exists(userId)) return null; 4206 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4207 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4208 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4209 } 4210 4211 @Override 4212 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4213 IntentFilter filter, int match, ComponentName activity) { 4214 final int userId = UserHandle.getCallingUserId(); 4215 if (DEBUG_PREFERRED) { 4216 Log.v(TAG, "setLastChosenActivity intent=" + intent 4217 + " resolvedType=" + resolvedType 4218 + " flags=" + flags 4219 + " filter=" + filter 4220 + " match=" + match 4221 + " activity=" + activity); 4222 filter.dump(new PrintStreamPrinter(System.out), " "); 4223 } 4224 intent.setComponent(null); 4225 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4226 // Find any earlier preferred or last chosen entries and nuke them 4227 findPreferredActivity(intent, resolvedType, 4228 flags, query, 0, false, true, false, userId); 4229 // Add the new activity as the last chosen for this filter 4230 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4231 "Setting last chosen"); 4232 } 4233 4234 @Override 4235 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4236 final int userId = UserHandle.getCallingUserId(); 4237 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4238 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4239 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4240 false, false, false, userId); 4241 } 4242 4243 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4244 int flags, List<ResolveInfo> query, int userId) { 4245 if (query != null) { 4246 final int N = query.size(); 4247 if (N == 1) { 4248 return query.get(0); 4249 } else if (N > 1) { 4250 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4251 // If there is more than one activity with the same priority, 4252 // then let the user decide between them. 4253 ResolveInfo r0 = query.get(0); 4254 ResolveInfo r1 = query.get(1); 4255 if (DEBUG_INTENT_MATCHING || debug) { 4256 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4257 + r1.activityInfo.name + "=" + r1.priority); 4258 } 4259 // If the first activity has a higher priority, or a different 4260 // default, then it is always desireable to pick it. 4261 if (r0.priority != r1.priority 4262 || r0.preferredOrder != r1.preferredOrder 4263 || r0.isDefault != r1.isDefault) { 4264 return query.get(0); 4265 } 4266 // If we have saved a preference for a preferred activity for 4267 // this Intent, use that. 4268 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4269 flags, query, r0.priority, true, false, debug, userId); 4270 if (ri != null) { 4271 return ri; 4272 } 4273 ri = new ResolveInfo(mResolveInfo); 4274 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4275 ri.activityInfo.applicationInfo = new ApplicationInfo( 4276 ri.activityInfo.applicationInfo); 4277 if (userId != 0) { 4278 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4279 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4280 } 4281 // Make sure that the resolver is displayable in car mode 4282 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4283 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4284 return ri; 4285 } 4286 } 4287 return null; 4288 } 4289 4290 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4291 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4292 final int N = query.size(); 4293 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4294 .get(userId); 4295 // Get the list of persistent preferred activities that handle the intent 4296 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4297 List<PersistentPreferredActivity> pprefs = ppir != null 4298 ? ppir.queryIntent(intent, resolvedType, 4299 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4300 : null; 4301 if (pprefs != null && pprefs.size() > 0) { 4302 final int M = pprefs.size(); 4303 for (int i=0; i<M; i++) { 4304 final PersistentPreferredActivity ppa = pprefs.get(i); 4305 if (DEBUG_PREFERRED || debug) { 4306 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4307 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4308 + "\n component=" + ppa.mComponent); 4309 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4310 } 4311 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4312 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4313 if (DEBUG_PREFERRED || debug) { 4314 Slog.v(TAG, "Found persistent preferred activity:"); 4315 if (ai != null) { 4316 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4317 } else { 4318 Slog.v(TAG, " null"); 4319 } 4320 } 4321 if (ai == null) { 4322 // This previously registered persistent preferred activity 4323 // component is no longer known. Ignore it and do NOT remove it. 4324 continue; 4325 } 4326 for (int j=0; j<N; j++) { 4327 final ResolveInfo ri = query.get(j); 4328 if (!ri.activityInfo.applicationInfo.packageName 4329 .equals(ai.applicationInfo.packageName)) { 4330 continue; 4331 } 4332 if (!ri.activityInfo.name.equals(ai.name)) { 4333 continue; 4334 } 4335 // Found a persistent preference that can handle the intent. 4336 if (DEBUG_PREFERRED || debug) { 4337 Slog.v(TAG, "Returning persistent preferred activity: " + 4338 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4339 } 4340 return ri; 4341 } 4342 } 4343 } 4344 return null; 4345 } 4346 4347 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4348 List<ResolveInfo> query, int priority, boolean always, 4349 boolean removeMatches, boolean debug, int userId) { 4350 if (!sUserManager.exists(userId)) return null; 4351 // writer 4352 synchronized (mPackages) { 4353 if (intent.getSelector() != null) { 4354 intent = intent.getSelector(); 4355 } 4356 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4357 4358 // Try to find a matching persistent preferred activity. 4359 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4360 debug, userId); 4361 4362 // If a persistent preferred activity matched, use it. 4363 if (pri != null) { 4364 return pri; 4365 } 4366 4367 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4368 // Get the list of preferred activities that handle the intent 4369 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4370 List<PreferredActivity> prefs = pir != null 4371 ? pir.queryIntent(intent, resolvedType, 4372 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4373 : null; 4374 if (prefs != null && prefs.size() > 0) { 4375 boolean changed = false; 4376 try { 4377 // First figure out how good the original match set is. 4378 // We will only allow preferred activities that came 4379 // from the same match quality. 4380 int match = 0; 4381 4382 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4383 4384 final int N = query.size(); 4385 for (int j=0; j<N; j++) { 4386 final ResolveInfo ri = query.get(j); 4387 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4388 + ": 0x" + Integer.toHexString(match)); 4389 if (ri.match > match) { 4390 match = ri.match; 4391 } 4392 } 4393 4394 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4395 + Integer.toHexString(match)); 4396 4397 match &= IntentFilter.MATCH_CATEGORY_MASK; 4398 final int M = prefs.size(); 4399 for (int i=0; i<M; i++) { 4400 final PreferredActivity pa = prefs.get(i); 4401 if (DEBUG_PREFERRED || debug) { 4402 Slog.v(TAG, "Checking PreferredActivity ds=" 4403 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4404 + "\n component=" + pa.mPref.mComponent); 4405 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4406 } 4407 if (pa.mPref.mMatch != match) { 4408 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4409 + Integer.toHexString(pa.mPref.mMatch)); 4410 continue; 4411 } 4412 // If it's not an "always" type preferred activity and that's what we're 4413 // looking for, skip it. 4414 if (always && !pa.mPref.mAlways) { 4415 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4416 continue; 4417 } 4418 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4419 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4420 if (DEBUG_PREFERRED || debug) { 4421 Slog.v(TAG, "Found preferred activity:"); 4422 if (ai != null) { 4423 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4424 } else { 4425 Slog.v(TAG, " null"); 4426 } 4427 } 4428 if (ai == null) { 4429 // This previously registered preferred activity 4430 // component is no longer known. Most likely an update 4431 // to the app was installed and in the new version this 4432 // component no longer exists. Clean it up by removing 4433 // it from the preferred activities list, and skip it. 4434 Slog.w(TAG, "Removing dangling preferred activity: " 4435 + pa.mPref.mComponent); 4436 pir.removeFilter(pa); 4437 changed = true; 4438 continue; 4439 } 4440 for (int j=0; j<N; j++) { 4441 final ResolveInfo ri = query.get(j); 4442 if (!ri.activityInfo.applicationInfo.packageName 4443 .equals(ai.applicationInfo.packageName)) { 4444 continue; 4445 } 4446 if (!ri.activityInfo.name.equals(ai.name)) { 4447 continue; 4448 } 4449 4450 if (removeMatches) { 4451 pir.removeFilter(pa); 4452 changed = true; 4453 if (DEBUG_PREFERRED) { 4454 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4455 } 4456 break; 4457 } 4458 4459 // Okay we found a previously set preferred or last chosen app. 4460 // If the result set is different from when this 4461 // was created, we need to clear it and re-ask the 4462 // user their preference, if we're looking for an "always" type entry. 4463 if (always && !pa.mPref.sameSet(query)) { 4464 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4465 + intent + " type " + resolvedType); 4466 if (DEBUG_PREFERRED) { 4467 Slog.v(TAG, "Removing preferred activity since set changed " 4468 + pa.mPref.mComponent); 4469 } 4470 pir.removeFilter(pa); 4471 // Re-add the filter as a "last chosen" entry (!always) 4472 PreferredActivity lastChosen = new PreferredActivity( 4473 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4474 pir.addFilter(lastChosen); 4475 changed = true; 4476 return null; 4477 } 4478 4479 // Yay! Either the set matched or we're looking for the last chosen 4480 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4481 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4482 return ri; 4483 } 4484 } 4485 } finally { 4486 if (changed) { 4487 if (DEBUG_PREFERRED) { 4488 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4489 } 4490 scheduleWritePackageRestrictionsLocked(userId); 4491 } 4492 } 4493 } 4494 } 4495 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4496 return null; 4497 } 4498 4499 /* 4500 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4501 */ 4502 @Override 4503 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4504 int targetUserId) { 4505 mContext.enforceCallingOrSelfPermission( 4506 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4507 List<CrossProfileIntentFilter> matches = 4508 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4509 if (matches != null) { 4510 int size = matches.size(); 4511 for (int i = 0; i < size; i++) { 4512 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4513 } 4514 } 4515 if (hasWebURI(intent)) { 4516 // cross-profile app linking works only towards the parent. 4517 final UserInfo parent = getProfileParent(sourceUserId); 4518 synchronized(mPackages) { 4519 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4520 intent, resolvedType, 0, sourceUserId, parent.id); 4521 return xpDomainInfo != null; 4522 } 4523 } 4524 return false; 4525 } 4526 4527 private UserInfo getProfileParent(int userId) { 4528 final long identity = Binder.clearCallingIdentity(); 4529 try { 4530 return sUserManager.getProfileParent(userId); 4531 } finally { 4532 Binder.restoreCallingIdentity(identity); 4533 } 4534 } 4535 4536 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4537 String resolvedType, int userId) { 4538 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4539 if (resolver != null) { 4540 return resolver.queryIntent(intent, resolvedType, false, userId); 4541 } 4542 return null; 4543 } 4544 4545 @Override 4546 public List<ResolveInfo> queryIntentActivities(Intent intent, 4547 String resolvedType, int flags, int userId) { 4548 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4549 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4550 ComponentName comp = intent.getComponent(); 4551 if (comp == null) { 4552 if (intent.getSelector() != null) { 4553 intent = intent.getSelector(); 4554 comp = intent.getComponent(); 4555 } 4556 } 4557 4558 if (comp != null) { 4559 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4560 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4561 if (ai != null) { 4562 final ResolveInfo ri = new ResolveInfo(); 4563 ri.activityInfo = ai; 4564 list.add(ri); 4565 } 4566 return list; 4567 } 4568 4569 // reader 4570 synchronized (mPackages) { 4571 final String pkgName = intent.getPackage(); 4572 if (pkgName == null) { 4573 List<CrossProfileIntentFilter> matchingFilters = 4574 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4575 // Check for results that need to skip the current profile. 4576 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4577 resolvedType, flags, userId); 4578 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4579 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4580 result.add(xpResolveInfo); 4581 return filterIfNotSystemUser(result, userId); 4582 } 4583 4584 // Check for results in the current profile. 4585 List<ResolveInfo> result = mActivities.queryIntent( 4586 intent, resolvedType, flags, userId); 4587 4588 // Check for cross profile results. 4589 xpResolveInfo = queryCrossProfileIntents( 4590 matchingFilters, intent, resolvedType, flags, userId); 4591 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4592 result.add(xpResolveInfo); 4593 Collections.sort(result, mResolvePrioritySorter); 4594 } 4595 result = filterIfNotSystemUser(result, userId); 4596 if (hasWebURI(intent)) { 4597 CrossProfileDomainInfo xpDomainInfo = null; 4598 final UserInfo parent = getProfileParent(userId); 4599 if (parent != null) { 4600 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4601 flags, userId, parent.id); 4602 } 4603 if (xpDomainInfo != null) { 4604 if (xpResolveInfo != null) { 4605 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4606 // in the result. 4607 result.remove(xpResolveInfo); 4608 } 4609 if (result.size() == 0) { 4610 result.add(xpDomainInfo.resolveInfo); 4611 return result; 4612 } 4613 } else if (result.size() <= 1) { 4614 return result; 4615 } 4616 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4617 xpDomainInfo, userId); 4618 Collections.sort(result, mResolvePrioritySorter); 4619 } 4620 return result; 4621 } 4622 final PackageParser.Package pkg = mPackages.get(pkgName); 4623 if (pkg != null) { 4624 return filterIfNotSystemUser( 4625 mActivities.queryIntentForPackage( 4626 intent, resolvedType, flags, pkg.activities, userId), 4627 userId); 4628 } 4629 return new ArrayList<ResolveInfo>(); 4630 } 4631 } 4632 4633 private static class CrossProfileDomainInfo { 4634 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4635 ResolveInfo resolveInfo; 4636 /* Best domain verification status of the activities found in the other profile */ 4637 int bestDomainVerificationStatus; 4638 } 4639 4640 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4641 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4642 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4643 sourceUserId)) { 4644 return null; 4645 } 4646 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4647 resolvedType, flags, parentUserId); 4648 4649 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4650 return null; 4651 } 4652 CrossProfileDomainInfo result = null; 4653 int size = resultTargetUser.size(); 4654 for (int i = 0; i < size; i++) { 4655 ResolveInfo riTargetUser = resultTargetUser.get(i); 4656 // Intent filter verification is only for filters that specify a host. So don't return 4657 // those that handle all web uris. 4658 if (riTargetUser.handleAllWebDataURI) { 4659 continue; 4660 } 4661 String packageName = riTargetUser.activityInfo.packageName; 4662 PackageSetting ps = mSettings.mPackages.get(packageName); 4663 if (ps == null) { 4664 continue; 4665 } 4666 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4667 int status = (int)(verificationState >> 32); 4668 if (result == null) { 4669 result = new CrossProfileDomainInfo(); 4670 result.resolveInfo = 4671 createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId); 4672 result.bestDomainVerificationStatus = status; 4673 } else { 4674 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4675 result.bestDomainVerificationStatus); 4676 } 4677 } 4678 // Don't consider matches with status NEVER across profiles. 4679 if (result != null && result.bestDomainVerificationStatus 4680 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4681 return null; 4682 } 4683 return result; 4684 } 4685 4686 /** 4687 * Verification statuses are ordered from the worse to the best, except for 4688 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4689 */ 4690 private int bestDomainVerificationStatus(int status1, int status2) { 4691 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4692 return status2; 4693 } 4694 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4695 return status1; 4696 } 4697 return (int) MathUtils.max(status1, status2); 4698 } 4699 4700 private boolean isUserEnabled(int userId) { 4701 long callingId = Binder.clearCallingIdentity(); 4702 try { 4703 UserInfo userInfo = sUserManager.getUserInfo(userId); 4704 return userInfo != null && userInfo.isEnabled(); 4705 } finally { 4706 Binder.restoreCallingIdentity(callingId); 4707 } 4708 } 4709 4710 /** 4711 * Filter out activities with systemUserOnly flag set, when current user is not System. 4712 * 4713 * @return filtered list 4714 */ 4715 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4716 if (userId == UserHandle.USER_SYSTEM) { 4717 return resolveInfos; 4718 } 4719 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4720 ResolveInfo info = resolveInfos.get(i); 4721 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4722 resolveInfos.remove(i); 4723 } 4724 } 4725 return resolveInfos; 4726 } 4727 4728 private static boolean hasWebURI(Intent intent) { 4729 if (intent.getData() == null) { 4730 return false; 4731 } 4732 final String scheme = intent.getScheme(); 4733 if (TextUtils.isEmpty(scheme)) { 4734 return false; 4735 } 4736 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4737 } 4738 4739 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4740 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4741 int userId) { 4742 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4743 4744 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4745 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4746 candidates.size()); 4747 } 4748 4749 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4750 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4751 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4752 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4753 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4754 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4755 4756 synchronized (mPackages) { 4757 final int count = candidates.size(); 4758 // First, try to use linked apps. Partition the candidates into four lists: 4759 // one for the final results, one for the "do not use ever", one for "undefined status" 4760 // and finally one for "browser app type". 4761 for (int n=0; n<count; n++) { 4762 ResolveInfo info = candidates.get(n); 4763 String packageName = info.activityInfo.packageName; 4764 PackageSetting ps = mSettings.mPackages.get(packageName); 4765 if (ps != null) { 4766 // Add to the special match all list (Browser use case) 4767 if (info.handleAllWebDataURI) { 4768 matchAllList.add(info); 4769 continue; 4770 } 4771 // Try to get the status from User settings first 4772 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4773 int status = (int)(packedStatus >> 32); 4774 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4775 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4776 if (DEBUG_DOMAIN_VERIFICATION) { 4777 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4778 + " : linkgen=" + linkGeneration); 4779 } 4780 // Use link-enabled generation as preferredOrder, i.e. 4781 // prefer newly-enabled over earlier-enabled. 4782 info.preferredOrder = linkGeneration; 4783 alwaysList.add(info); 4784 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4785 if (DEBUG_DOMAIN_VERIFICATION) { 4786 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4787 } 4788 neverList.add(info); 4789 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4790 if (DEBUG_DOMAIN_VERIFICATION) { 4791 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4792 } 4793 alwaysAskList.add(info); 4794 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4795 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4796 if (DEBUG_DOMAIN_VERIFICATION) { 4797 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4798 } 4799 undefinedList.add(info); 4800 } 4801 } 4802 } 4803 4804 // We'll want to include browser possibilities in a few cases 4805 boolean includeBrowser = false; 4806 4807 // First try to add the "always" resolution(s) for the current user, if any 4808 if (alwaysList.size() > 0) { 4809 result.addAll(alwaysList); 4810 // if there is an "always" for the parent user, add it. 4811 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4812 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4813 result.add(xpDomainInfo.resolveInfo); 4814 } else { 4815 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4816 result.addAll(undefinedList); 4817 if (xpDomainInfo != null && ( 4818 xpDomainInfo.bestDomainVerificationStatus 4819 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4820 || xpDomainInfo.bestDomainVerificationStatus 4821 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4822 result.add(xpDomainInfo.resolveInfo); 4823 } 4824 includeBrowser = true; 4825 } 4826 4827 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4828 // If there were 'always' entries their preferred order has been set, so we also 4829 // back that off to make the alternatives equivalent 4830 if (alwaysAskList.size() > 0) { 4831 for (ResolveInfo i : result) { 4832 i.preferredOrder = 0; 4833 } 4834 result.addAll(alwaysAskList); 4835 includeBrowser = true; 4836 } 4837 4838 if (includeBrowser) { 4839 // Also add browsers (all of them or only the default one) 4840 if (DEBUG_DOMAIN_VERIFICATION) { 4841 Slog.v(TAG, " ...including browsers in candidate set"); 4842 } 4843 if ((matchFlags & MATCH_ALL) != 0) { 4844 result.addAll(matchAllList); 4845 } else { 4846 // Browser/generic handling case. If there's a default browser, go straight 4847 // to that (but only if there is no other higher-priority match). 4848 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4849 int maxMatchPrio = 0; 4850 ResolveInfo defaultBrowserMatch = null; 4851 final int numCandidates = matchAllList.size(); 4852 for (int n = 0; n < numCandidates; n++) { 4853 ResolveInfo info = matchAllList.get(n); 4854 // track the highest overall match priority... 4855 if (info.priority > maxMatchPrio) { 4856 maxMatchPrio = info.priority; 4857 } 4858 // ...and the highest-priority default browser match 4859 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4860 if (defaultBrowserMatch == null 4861 || (defaultBrowserMatch.priority < info.priority)) { 4862 if (debug) { 4863 Slog.v(TAG, "Considering default browser match " + info); 4864 } 4865 defaultBrowserMatch = info; 4866 } 4867 } 4868 } 4869 if (defaultBrowserMatch != null 4870 && defaultBrowserMatch.priority >= maxMatchPrio 4871 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4872 { 4873 if (debug) { 4874 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4875 } 4876 result.add(defaultBrowserMatch); 4877 } else { 4878 result.addAll(matchAllList); 4879 } 4880 } 4881 4882 // If there is nothing selected, add all candidates and remove the ones that the user 4883 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4884 if (result.size() == 0) { 4885 result.addAll(candidates); 4886 result.removeAll(neverList); 4887 } 4888 } 4889 } 4890 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4891 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4892 result.size()); 4893 for (ResolveInfo info : result) { 4894 Slog.v(TAG, " + " + info.activityInfo); 4895 } 4896 } 4897 return result; 4898 } 4899 4900 // Returns a packed value as a long: 4901 // 4902 // high 'int'-sized word: link status: undefined/ask/never/always. 4903 // low 'int'-sized word: relative priority among 'always' results. 4904 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4905 long result = ps.getDomainVerificationStatusForUser(userId); 4906 // if none available, get the master status 4907 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4908 if (ps.getIntentFilterVerificationInfo() != null) { 4909 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4910 } 4911 } 4912 return result; 4913 } 4914 4915 private ResolveInfo querySkipCurrentProfileIntents( 4916 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4917 int flags, int sourceUserId) { 4918 if (matchingFilters != null) { 4919 int size = matchingFilters.size(); 4920 for (int i = 0; i < size; i ++) { 4921 CrossProfileIntentFilter filter = matchingFilters.get(i); 4922 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4923 // Checking if there are activities in the target user that can handle the 4924 // intent. 4925 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4926 flags, sourceUserId); 4927 if (resolveInfo != null) { 4928 return resolveInfo; 4929 } 4930 } 4931 } 4932 } 4933 return null; 4934 } 4935 4936 // Return matching ResolveInfo if any for skip current profile intent filters. 4937 private ResolveInfo queryCrossProfileIntents( 4938 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4939 int flags, int sourceUserId) { 4940 if (matchingFilters != null) { 4941 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4942 // match the same intent. For performance reasons, it is better not to 4943 // run queryIntent twice for the same userId 4944 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4945 int size = matchingFilters.size(); 4946 for (int i = 0; i < size; i++) { 4947 CrossProfileIntentFilter filter = matchingFilters.get(i); 4948 int targetUserId = filter.getTargetUserId(); 4949 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4950 && !alreadyTriedUserIds.get(targetUserId)) { 4951 // Checking if there are activities in the target user that can handle the 4952 // intent. 4953 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4954 flags, sourceUserId); 4955 if (resolveInfo != null) return resolveInfo; 4956 alreadyTriedUserIds.put(targetUserId, true); 4957 } 4958 } 4959 } 4960 return null; 4961 } 4962 4963 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4964 String resolvedType, int flags, int sourceUserId) { 4965 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4966 resolvedType, flags, filter.getTargetUserId()); 4967 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4968 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4969 } 4970 return null; 4971 } 4972 4973 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4974 int sourceUserId, int targetUserId) { 4975 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4976 long ident = Binder.clearCallingIdentity(); 4977 boolean targetIsProfile; 4978 try { 4979 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4980 } finally { 4981 Binder.restoreCallingIdentity(ident); 4982 } 4983 String className; 4984 if (targetIsProfile) { 4985 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4986 } else { 4987 className = FORWARD_INTENT_TO_PARENT; 4988 } 4989 ComponentName forwardingActivityComponentName = new ComponentName( 4990 mAndroidApplication.packageName, className); 4991 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4992 sourceUserId); 4993 if (!targetIsProfile) { 4994 forwardingActivityInfo.showUserIcon = targetUserId; 4995 forwardingResolveInfo.noResourceId = true; 4996 } 4997 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4998 forwardingResolveInfo.priority = 0; 4999 forwardingResolveInfo.preferredOrder = 0; 5000 forwardingResolveInfo.match = 0; 5001 forwardingResolveInfo.isDefault = true; 5002 forwardingResolveInfo.filter = filter; 5003 forwardingResolveInfo.targetUserId = targetUserId; 5004 return forwardingResolveInfo; 5005 } 5006 5007 @Override 5008 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5009 Intent[] specifics, String[] specificTypes, Intent intent, 5010 String resolvedType, int flags, int userId) { 5011 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5012 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5013 false, "query intent activity options"); 5014 final String resultsAction = intent.getAction(); 5015 5016 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5017 | PackageManager.GET_RESOLVED_FILTER, userId); 5018 5019 if (DEBUG_INTENT_MATCHING) { 5020 Log.v(TAG, "Query " + intent + ": " + results); 5021 } 5022 5023 int specificsPos = 0; 5024 int N; 5025 5026 // todo: note that the algorithm used here is O(N^2). This 5027 // isn't a problem in our current environment, but if we start running 5028 // into situations where we have more than 5 or 10 matches then this 5029 // should probably be changed to something smarter... 5030 5031 // First we go through and resolve each of the specific items 5032 // that were supplied, taking care of removing any corresponding 5033 // duplicate items in the generic resolve list. 5034 if (specifics != null) { 5035 for (int i=0; i<specifics.length; i++) { 5036 final Intent sintent = specifics[i]; 5037 if (sintent == null) { 5038 continue; 5039 } 5040 5041 if (DEBUG_INTENT_MATCHING) { 5042 Log.v(TAG, "Specific #" + i + ": " + sintent); 5043 } 5044 5045 String action = sintent.getAction(); 5046 if (resultsAction != null && resultsAction.equals(action)) { 5047 // If this action was explicitly requested, then don't 5048 // remove things that have it. 5049 action = null; 5050 } 5051 5052 ResolveInfo ri = null; 5053 ActivityInfo ai = null; 5054 5055 ComponentName comp = sintent.getComponent(); 5056 if (comp == null) { 5057 ri = resolveIntent( 5058 sintent, 5059 specificTypes != null ? specificTypes[i] : null, 5060 flags, userId); 5061 if (ri == null) { 5062 continue; 5063 } 5064 if (ri == mResolveInfo) { 5065 // ACK! Must do something better with this. 5066 } 5067 ai = ri.activityInfo; 5068 comp = new ComponentName(ai.applicationInfo.packageName, 5069 ai.name); 5070 } else { 5071 ai = getActivityInfo(comp, flags, userId); 5072 if (ai == null) { 5073 continue; 5074 } 5075 } 5076 5077 // Look for any generic query activities that are duplicates 5078 // of this specific one, and remove them from the results. 5079 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5080 N = results.size(); 5081 int j; 5082 for (j=specificsPos; j<N; j++) { 5083 ResolveInfo sri = results.get(j); 5084 if ((sri.activityInfo.name.equals(comp.getClassName()) 5085 && sri.activityInfo.applicationInfo.packageName.equals( 5086 comp.getPackageName())) 5087 || (action != null && sri.filter.matchAction(action))) { 5088 results.remove(j); 5089 if (DEBUG_INTENT_MATCHING) Log.v( 5090 TAG, "Removing duplicate item from " + j 5091 + " due to specific " + specificsPos); 5092 if (ri == null) { 5093 ri = sri; 5094 } 5095 j--; 5096 N--; 5097 } 5098 } 5099 5100 // Add this specific item to its proper place. 5101 if (ri == null) { 5102 ri = new ResolveInfo(); 5103 ri.activityInfo = ai; 5104 } 5105 results.add(specificsPos, ri); 5106 ri.specificIndex = i; 5107 specificsPos++; 5108 } 5109 } 5110 5111 // Now we go through the remaining generic results and remove any 5112 // duplicate actions that are found here. 5113 N = results.size(); 5114 for (int i=specificsPos; i<N-1; i++) { 5115 final ResolveInfo rii = results.get(i); 5116 if (rii.filter == null) { 5117 continue; 5118 } 5119 5120 // Iterate over all of the actions of this result's intent 5121 // filter... typically this should be just one. 5122 final Iterator<String> it = rii.filter.actionsIterator(); 5123 if (it == null) { 5124 continue; 5125 } 5126 while (it.hasNext()) { 5127 final String action = it.next(); 5128 if (resultsAction != null && resultsAction.equals(action)) { 5129 // If this action was explicitly requested, then don't 5130 // remove things that have it. 5131 continue; 5132 } 5133 for (int j=i+1; j<N; j++) { 5134 final ResolveInfo rij = results.get(j); 5135 if (rij.filter != null && rij.filter.hasAction(action)) { 5136 results.remove(j); 5137 if (DEBUG_INTENT_MATCHING) Log.v( 5138 TAG, "Removing duplicate item from " + j 5139 + " due to action " + action + " at " + i); 5140 j--; 5141 N--; 5142 } 5143 } 5144 } 5145 5146 // If the caller didn't request filter information, drop it now 5147 // so we don't have to marshall/unmarshall it. 5148 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5149 rii.filter = null; 5150 } 5151 } 5152 5153 // Filter out the caller activity if so requested. 5154 if (caller != null) { 5155 N = results.size(); 5156 for (int i=0; i<N; i++) { 5157 ActivityInfo ainfo = results.get(i).activityInfo; 5158 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5159 && caller.getClassName().equals(ainfo.name)) { 5160 results.remove(i); 5161 break; 5162 } 5163 } 5164 } 5165 5166 // If the caller didn't request filter information, 5167 // drop them now so we don't have to 5168 // marshall/unmarshall it. 5169 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5170 N = results.size(); 5171 for (int i=0; i<N; i++) { 5172 results.get(i).filter = null; 5173 } 5174 } 5175 5176 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5177 return results; 5178 } 5179 5180 @Override 5181 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5182 int userId) { 5183 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5184 ComponentName comp = intent.getComponent(); 5185 if (comp == null) { 5186 if (intent.getSelector() != null) { 5187 intent = intent.getSelector(); 5188 comp = intent.getComponent(); 5189 } 5190 } 5191 if (comp != null) { 5192 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5193 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5194 if (ai != null) { 5195 ResolveInfo ri = new ResolveInfo(); 5196 ri.activityInfo = ai; 5197 list.add(ri); 5198 } 5199 return list; 5200 } 5201 5202 // reader 5203 synchronized (mPackages) { 5204 String pkgName = intent.getPackage(); 5205 if (pkgName == null) { 5206 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5207 } 5208 final PackageParser.Package pkg = mPackages.get(pkgName); 5209 if (pkg != null) { 5210 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5211 userId); 5212 } 5213 return null; 5214 } 5215 } 5216 5217 @Override 5218 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5219 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5220 if (!sUserManager.exists(userId)) return null; 5221 if (query != null) { 5222 if (query.size() >= 1) { 5223 // If there is more than one service with the same priority, 5224 // just arbitrarily pick the first one. 5225 return query.get(0); 5226 } 5227 } 5228 return null; 5229 } 5230 5231 @Override 5232 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5233 int userId) { 5234 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5235 ComponentName comp = intent.getComponent(); 5236 if (comp == null) { 5237 if (intent.getSelector() != null) { 5238 intent = intent.getSelector(); 5239 comp = intent.getComponent(); 5240 } 5241 } 5242 if (comp != null) { 5243 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5244 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5245 if (si != null) { 5246 final ResolveInfo ri = new ResolveInfo(); 5247 ri.serviceInfo = si; 5248 list.add(ri); 5249 } 5250 return list; 5251 } 5252 5253 // reader 5254 synchronized (mPackages) { 5255 String pkgName = intent.getPackage(); 5256 if (pkgName == null) { 5257 return mServices.queryIntent(intent, resolvedType, flags, userId); 5258 } 5259 final PackageParser.Package pkg = mPackages.get(pkgName); 5260 if (pkg != null) { 5261 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5262 userId); 5263 } 5264 return null; 5265 } 5266 } 5267 5268 @Override 5269 public List<ResolveInfo> queryIntentContentProviders( 5270 Intent intent, String resolvedType, int flags, int userId) { 5271 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5272 ComponentName comp = intent.getComponent(); 5273 if (comp == null) { 5274 if (intent.getSelector() != null) { 5275 intent = intent.getSelector(); 5276 comp = intent.getComponent(); 5277 } 5278 } 5279 if (comp != null) { 5280 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5281 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5282 if (pi != null) { 5283 final ResolveInfo ri = new ResolveInfo(); 5284 ri.providerInfo = pi; 5285 list.add(ri); 5286 } 5287 return list; 5288 } 5289 5290 // reader 5291 synchronized (mPackages) { 5292 String pkgName = intent.getPackage(); 5293 if (pkgName == null) { 5294 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5295 } 5296 final PackageParser.Package pkg = mPackages.get(pkgName); 5297 if (pkg != null) { 5298 return mProviders.queryIntentForPackage( 5299 intent, resolvedType, flags, pkg.providers, userId); 5300 } 5301 return null; 5302 } 5303 } 5304 5305 @Override 5306 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5307 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5308 5309 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5310 5311 // writer 5312 synchronized (mPackages) { 5313 ArrayList<PackageInfo> list; 5314 if (listUninstalled) { 5315 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5316 for (PackageSetting ps : mSettings.mPackages.values()) { 5317 PackageInfo pi; 5318 if (ps.pkg != null) { 5319 pi = generatePackageInfo(ps.pkg, flags, userId); 5320 } else { 5321 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5322 } 5323 if (pi != null) { 5324 list.add(pi); 5325 } 5326 } 5327 } else { 5328 list = new ArrayList<PackageInfo>(mPackages.size()); 5329 for (PackageParser.Package p : mPackages.values()) { 5330 PackageInfo pi = generatePackageInfo(p, flags, userId); 5331 if (pi != null) { 5332 list.add(pi); 5333 } 5334 } 5335 } 5336 5337 return new ParceledListSlice<PackageInfo>(list); 5338 } 5339 } 5340 5341 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5342 String[] permissions, boolean[] tmp, int flags, int userId) { 5343 int numMatch = 0; 5344 final PermissionsState permissionsState = ps.getPermissionsState(); 5345 for (int i=0; i<permissions.length; i++) { 5346 final String permission = permissions[i]; 5347 if (permissionsState.hasPermission(permission, userId)) { 5348 tmp[i] = true; 5349 numMatch++; 5350 } else { 5351 tmp[i] = false; 5352 } 5353 } 5354 if (numMatch == 0) { 5355 return; 5356 } 5357 PackageInfo pi; 5358 if (ps.pkg != null) { 5359 pi = generatePackageInfo(ps.pkg, flags, userId); 5360 } else { 5361 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5362 } 5363 // The above might return null in cases of uninstalled apps or install-state 5364 // skew across users/profiles. 5365 if (pi != null) { 5366 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5367 if (numMatch == permissions.length) { 5368 pi.requestedPermissions = permissions; 5369 } else { 5370 pi.requestedPermissions = new String[numMatch]; 5371 numMatch = 0; 5372 for (int i=0; i<permissions.length; i++) { 5373 if (tmp[i]) { 5374 pi.requestedPermissions[numMatch] = permissions[i]; 5375 numMatch++; 5376 } 5377 } 5378 } 5379 } 5380 list.add(pi); 5381 } 5382 } 5383 5384 @Override 5385 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5386 String[] permissions, int flags, int userId) { 5387 if (!sUserManager.exists(userId)) return null; 5388 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5389 5390 // writer 5391 synchronized (mPackages) { 5392 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5393 boolean[] tmpBools = new boolean[permissions.length]; 5394 if (listUninstalled) { 5395 for (PackageSetting ps : mSettings.mPackages.values()) { 5396 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5397 } 5398 } else { 5399 for (PackageParser.Package pkg : mPackages.values()) { 5400 PackageSetting ps = (PackageSetting)pkg.mExtras; 5401 if (ps != null) { 5402 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5403 userId); 5404 } 5405 } 5406 } 5407 5408 return new ParceledListSlice<PackageInfo>(list); 5409 } 5410 } 5411 5412 @Override 5413 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5414 if (!sUserManager.exists(userId)) return null; 5415 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5416 5417 // writer 5418 synchronized (mPackages) { 5419 ArrayList<ApplicationInfo> list; 5420 if (listUninstalled) { 5421 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5422 for (PackageSetting ps : mSettings.mPackages.values()) { 5423 ApplicationInfo ai; 5424 if (ps.pkg != null) { 5425 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5426 ps.readUserState(userId), userId); 5427 } else { 5428 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5429 } 5430 if (ai != null) { 5431 list.add(ai); 5432 } 5433 } 5434 } else { 5435 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5436 for (PackageParser.Package p : mPackages.values()) { 5437 if (p.mExtras != null) { 5438 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5439 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5440 if (ai != null) { 5441 list.add(ai); 5442 } 5443 } 5444 } 5445 } 5446 5447 return new ParceledListSlice<ApplicationInfo>(list); 5448 } 5449 } 5450 5451 public List<ApplicationInfo> getPersistentApplications(int flags) { 5452 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5453 5454 // reader 5455 synchronized (mPackages) { 5456 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5457 final int userId = UserHandle.getCallingUserId(); 5458 while (i.hasNext()) { 5459 final PackageParser.Package p = i.next(); 5460 if (p.applicationInfo != null 5461 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5462 && (!mSafeMode || isSystemApp(p))) { 5463 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5464 if (ps != null) { 5465 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5466 ps.readUserState(userId), userId); 5467 if (ai != null) { 5468 finalList.add(ai); 5469 } 5470 } 5471 } 5472 } 5473 } 5474 5475 return finalList; 5476 } 5477 5478 @Override 5479 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5480 if (!sUserManager.exists(userId)) return null; 5481 // reader 5482 synchronized (mPackages) { 5483 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5484 PackageSetting ps = provider != null 5485 ? mSettings.mPackages.get(provider.owner.packageName) 5486 : null; 5487 return ps != null 5488 && mSettings.isEnabledLPr(provider.info, flags, userId) 5489 && (!mSafeMode || (provider.info.applicationInfo.flags 5490 &ApplicationInfo.FLAG_SYSTEM) != 0) 5491 ? PackageParser.generateProviderInfo(provider, flags, 5492 ps.readUserState(userId), userId) 5493 : null; 5494 } 5495 } 5496 5497 /** 5498 * @deprecated 5499 */ 5500 @Deprecated 5501 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5502 // reader 5503 synchronized (mPackages) { 5504 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5505 .entrySet().iterator(); 5506 final int userId = UserHandle.getCallingUserId(); 5507 while (i.hasNext()) { 5508 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5509 PackageParser.Provider p = entry.getValue(); 5510 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5511 5512 if (ps != null && p.syncable 5513 && (!mSafeMode || (p.info.applicationInfo.flags 5514 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5515 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5516 ps.readUserState(userId), userId); 5517 if (info != null) { 5518 outNames.add(entry.getKey()); 5519 outInfo.add(info); 5520 } 5521 } 5522 } 5523 } 5524 } 5525 5526 @Override 5527 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5528 int uid, int flags) { 5529 ArrayList<ProviderInfo> finalList = null; 5530 // reader 5531 synchronized (mPackages) { 5532 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5533 final int userId = processName != null ? 5534 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5535 while (i.hasNext()) { 5536 final PackageParser.Provider p = i.next(); 5537 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5538 if (ps != null && p.info.authority != null 5539 && (processName == null 5540 || (p.info.processName.equals(processName) 5541 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5542 && mSettings.isEnabledLPr(p.info, flags, userId) 5543 && (!mSafeMode 5544 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5545 if (finalList == null) { 5546 finalList = new ArrayList<ProviderInfo>(3); 5547 } 5548 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5549 ps.readUserState(userId), userId); 5550 if (info != null) { 5551 finalList.add(info); 5552 } 5553 } 5554 } 5555 } 5556 5557 if (finalList != null) { 5558 Collections.sort(finalList, mProviderInitOrderSorter); 5559 return new ParceledListSlice<ProviderInfo>(finalList); 5560 } 5561 5562 return null; 5563 } 5564 5565 @Override 5566 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5567 int flags) { 5568 // reader 5569 synchronized (mPackages) { 5570 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5571 return PackageParser.generateInstrumentationInfo(i, flags); 5572 } 5573 } 5574 5575 @Override 5576 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5577 int flags) { 5578 ArrayList<InstrumentationInfo> finalList = 5579 new ArrayList<InstrumentationInfo>(); 5580 5581 // reader 5582 synchronized (mPackages) { 5583 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5584 while (i.hasNext()) { 5585 final PackageParser.Instrumentation p = i.next(); 5586 if (targetPackage == null 5587 || targetPackage.equals(p.info.targetPackage)) { 5588 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5589 flags); 5590 if (ii != null) { 5591 finalList.add(ii); 5592 } 5593 } 5594 } 5595 } 5596 5597 return finalList; 5598 } 5599 5600 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5601 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5602 if (overlays == null) { 5603 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5604 return; 5605 } 5606 for (PackageParser.Package opkg : overlays.values()) { 5607 // Not much to do if idmap fails: we already logged the error 5608 // and we certainly don't want to abort installation of pkg simply 5609 // because an overlay didn't fit properly. For these reasons, 5610 // ignore the return value of createIdmapForPackagePairLI. 5611 createIdmapForPackagePairLI(pkg, opkg); 5612 } 5613 } 5614 5615 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5616 PackageParser.Package opkg) { 5617 if (!opkg.mTrustedOverlay) { 5618 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5619 opkg.baseCodePath + ": overlay not trusted"); 5620 return false; 5621 } 5622 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5623 if (overlaySet == null) { 5624 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5625 opkg.baseCodePath + " but target package has no known overlays"); 5626 return false; 5627 } 5628 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5629 // TODO: generate idmap for split APKs 5630 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5631 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5632 + opkg.baseCodePath); 5633 return false; 5634 } 5635 PackageParser.Package[] overlayArray = 5636 overlaySet.values().toArray(new PackageParser.Package[0]); 5637 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5638 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5639 return p1.mOverlayPriority - p2.mOverlayPriority; 5640 } 5641 }; 5642 Arrays.sort(overlayArray, cmp); 5643 5644 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5645 int i = 0; 5646 for (PackageParser.Package p : overlayArray) { 5647 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5648 } 5649 return true; 5650 } 5651 5652 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5653 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5654 try { 5655 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5656 } finally { 5657 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5658 } 5659 } 5660 5661 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5662 final File[] files = dir.listFiles(); 5663 if (ArrayUtils.isEmpty(files)) { 5664 Log.d(TAG, "No files in app dir " + dir); 5665 return; 5666 } 5667 5668 if (DEBUG_PACKAGE_SCANNING) { 5669 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5670 + " flags=0x" + Integer.toHexString(parseFlags)); 5671 } 5672 5673 for (File file : files) { 5674 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5675 && !PackageInstallerService.isStageName(file.getName()); 5676 if (!isPackage) { 5677 // Ignore entries which are not packages 5678 continue; 5679 } 5680 try { 5681 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5682 scanFlags, currentTime, null); 5683 } catch (PackageManagerException e) { 5684 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5685 5686 // Delete invalid userdata apps 5687 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5688 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5689 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5690 if (file.isDirectory()) { 5691 mInstaller.rmPackageDir(file.getAbsolutePath()); 5692 } else { 5693 file.delete(); 5694 } 5695 } 5696 } 5697 } 5698 } 5699 5700 private static File getSettingsProblemFile() { 5701 File dataDir = Environment.getDataDirectory(); 5702 File systemDir = new File(dataDir, "system"); 5703 File fname = new File(systemDir, "uiderrors.txt"); 5704 return fname; 5705 } 5706 5707 static void reportSettingsProblem(int priority, String msg) { 5708 logCriticalInfo(priority, msg); 5709 } 5710 5711 static void logCriticalInfo(int priority, String msg) { 5712 Slog.println(priority, TAG, msg); 5713 EventLogTags.writePmCriticalInfo(msg); 5714 try { 5715 File fname = getSettingsProblemFile(); 5716 FileOutputStream out = new FileOutputStream(fname, true); 5717 PrintWriter pw = new FastPrintWriter(out); 5718 SimpleDateFormat formatter = new SimpleDateFormat(); 5719 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5720 pw.println(dateString + ": " + msg); 5721 pw.close(); 5722 FileUtils.setPermissions( 5723 fname.toString(), 5724 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5725 -1, -1); 5726 } catch (java.io.IOException e) { 5727 } 5728 } 5729 5730 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5731 PackageParser.Package pkg, File srcFile, int parseFlags) 5732 throws PackageManagerException { 5733 if (ps != null 5734 && ps.codePath.equals(srcFile) 5735 && ps.timeStamp == srcFile.lastModified() 5736 && !isCompatSignatureUpdateNeeded(pkg) 5737 && !isRecoverSignatureUpdateNeeded(pkg)) { 5738 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5739 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5740 ArraySet<PublicKey> signingKs; 5741 synchronized (mPackages) { 5742 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5743 } 5744 if (ps.signatures.mSignatures != null 5745 && ps.signatures.mSignatures.length != 0 5746 && signingKs != null) { 5747 // Optimization: reuse the existing cached certificates 5748 // if the package appears to be unchanged. 5749 pkg.mSignatures = ps.signatures.mSignatures; 5750 pkg.mSigningKeys = signingKs; 5751 return; 5752 } 5753 5754 Slog.w(TAG, "PackageSetting for " + ps.name 5755 + " is missing signatures. Collecting certs again to recover them."); 5756 } else { 5757 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5758 } 5759 5760 try { 5761 pp.collectCertificates(pkg, parseFlags); 5762 pp.collectManifestDigest(pkg); 5763 } catch (PackageParserException e) { 5764 throw PackageManagerException.from(e); 5765 } 5766 } 5767 5768 /** 5769 * Traces a package scan. 5770 * @see #scanPackageLI(File, int, int, long, UserHandle) 5771 */ 5772 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5773 long currentTime, UserHandle user) throws PackageManagerException { 5774 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5775 try { 5776 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5777 } finally { 5778 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5779 } 5780 } 5781 5782 /** 5783 * Scans a package and returns the newly parsed package. 5784 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5785 */ 5786 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5787 long currentTime, UserHandle user) throws PackageManagerException { 5788 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5789 parseFlags |= mDefParseFlags; 5790 PackageParser pp = new PackageParser(); 5791 pp.setSeparateProcesses(mSeparateProcesses); 5792 pp.setOnlyCoreApps(mOnlyCore); 5793 pp.setDisplayMetrics(mMetrics); 5794 5795 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5796 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5797 } 5798 5799 final PackageParser.Package pkg; 5800 try { 5801 pkg = pp.parsePackage(scanFile, parseFlags); 5802 } catch (PackageParserException e) { 5803 throw PackageManagerException.from(e); 5804 } 5805 5806 PackageSetting ps = null; 5807 PackageSetting updatedPkg; 5808 // reader 5809 synchronized (mPackages) { 5810 // Look to see if we already know about this package. 5811 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5812 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5813 // This package has been renamed to its original name. Let's 5814 // use that. 5815 ps = mSettings.peekPackageLPr(oldName); 5816 } 5817 // If there was no original package, see one for the real package name. 5818 if (ps == null) { 5819 ps = mSettings.peekPackageLPr(pkg.packageName); 5820 } 5821 // Check to see if this package could be hiding/updating a system 5822 // package. Must look for it either under the original or real 5823 // package name depending on our state. 5824 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5825 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5826 } 5827 boolean updatedPkgBetter = false; 5828 // First check if this is a system package that may involve an update 5829 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5830 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5831 // it needs to drop FLAG_PRIVILEGED. 5832 if (locationIsPrivileged(scanFile)) { 5833 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5834 } else { 5835 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5836 } 5837 5838 if (ps != null && !ps.codePath.equals(scanFile)) { 5839 // The path has changed from what was last scanned... check the 5840 // version of the new path against what we have stored to determine 5841 // what to do. 5842 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5843 if (pkg.mVersionCode <= ps.versionCode) { 5844 // The system package has been updated and the code path does not match 5845 // Ignore entry. Skip it. 5846 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5847 + " ignored: updated version " + ps.versionCode 5848 + " better than this " + pkg.mVersionCode); 5849 if (!updatedPkg.codePath.equals(scanFile)) { 5850 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5851 + ps.name + " changing from " + updatedPkg.codePathString 5852 + " to " + scanFile); 5853 updatedPkg.codePath = scanFile; 5854 updatedPkg.codePathString = scanFile.toString(); 5855 updatedPkg.resourcePath = scanFile; 5856 updatedPkg.resourcePathString = scanFile.toString(); 5857 } 5858 updatedPkg.pkg = pkg; 5859 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5860 "Package " + ps.name + " at " + scanFile 5861 + " ignored: updated version " + ps.versionCode 5862 + " better than this " + pkg.mVersionCode); 5863 } else { 5864 // The current app on the system partition is better than 5865 // what we have updated to on the data partition; switch 5866 // back to the system partition version. 5867 // At this point, its safely assumed that package installation for 5868 // apps in system partition will go through. If not there won't be a working 5869 // version of the app 5870 // writer 5871 synchronized (mPackages) { 5872 // Just remove the loaded entries from package lists. 5873 mPackages.remove(ps.name); 5874 } 5875 5876 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5877 + " reverting from " + ps.codePathString 5878 + ": new version " + pkg.mVersionCode 5879 + " better than installed " + ps.versionCode); 5880 5881 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5882 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5883 synchronized (mInstallLock) { 5884 args.cleanUpResourcesLI(); 5885 } 5886 synchronized (mPackages) { 5887 mSettings.enableSystemPackageLPw(ps.name); 5888 } 5889 updatedPkgBetter = true; 5890 } 5891 } 5892 } 5893 5894 if (updatedPkg != null) { 5895 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5896 // initially 5897 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5898 5899 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5900 // flag set initially 5901 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5902 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5903 } 5904 } 5905 5906 // Verify certificates against what was last scanned 5907 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5908 5909 /* 5910 * A new system app appeared, but we already had a non-system one of the 5911 * same name installed earlier. 5912 */ 5913 boolean shouldHideSystemApp = false; 5914 if (updatedPkg == null && ps != null 5915 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5916 /* 5917 * Check to make sure the signatures match first. If they don't, 5918 * wipe the installed application and its data. 5919 */ 5920 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5921 != PackageManager.SIGNATURE_MATCH) { 5922 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5923 + " signatures don't match existing userdata copy; removing"); 5924 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5925 ps = null; 5926 } else { 5927 /* 5928 * If the newly-added system app is an older version than the 5929 * already installed version, hide it. It will be scanned later 5930 * and re-added like an update. 5931 */ 5932 if (pkg.mVersionCode <= ps.versionCode) { 5933 shouldHideSystemApp = true; 5934 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5935 + " but new version " + pkg.mVersionCode + " better than installed " 5936 + ps.versionCode + "; hiding system"); 5937 } else { 5938 /* 5939 * The newly found system app is a newer version that the 5940 * one previously installed. Simply remove the 5941 * already-installed application and replace it with our own 5942 * while keeping the application data. 5943 */ 5944 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5945 + " reverting from " + ps.codePathString + ": new version " 5946 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5947 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5948 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5949 synchronized (mInstallLock) { 5950 args.cleanUpResourcesLI(); 5951 } 5952 } 5953 } 5954 } 5955 5956 // The apk is forward locked (not public) if its code and resources 5957 // are kept in different files. (except for app in either system or 5958 // vendor path). 5959 // TODO grab this value from PackageSettings 5960 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5961 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5962 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5963 } 5964 } 5965 5966 // TODO: extend to support forward-locked splits 5967 String resourcePath = null; 5968 String baseResourcePath = null; 5969 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5970 if (ps != null && ps.resourcePathString != null) { 5971 resourcePath = ps.resourcePathString; 5972 baseResourcePath = ps.resourcePathString; 5973 } else { 5974 // Should not happen at all. Just log an error. 5975 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5976 } 5977 } else { 5978 resourcePath = pkg.codePath; 5979 baseResourcePath = pkg.baseCodePath; 5980 } 5981 5982 // Set application objects path explicitly. 5983 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5984 pkg.applicationInfo.setCodePath(pkg.codePath); 5985 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5986 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5987 pkg.applicationInfo.setResourcePath(resourcePath); 5988 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5989 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5990 5991 // Note that we invoke the following method only if we are about to unpack an application 5992 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5993 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5994 5995 /* 5996 * If the system app should be overridden by a previously installed 5997 * data, hide the system app now and let the /data/app scan pick it up 5998 * again. 5999 */ 6000 if (shouldHideSystemApp) { 6001 synchronized (mPackages) { 6002 /* 6003 * We have to grant systems permissions before we hide, because 6004 * grantPermissions will assume the package update is trying to 6005 * expand its permissions. 6006 */ 6007 grantPermissionsLPw(pkg, true, pkg.packageName); 6008 mSettings.disableSystemPackageLPw(pkg.packageName); 6009 } 6010 } 6011 6012 return scannedPkg; 6013 } 6014 6015 private static String fixProcessName(String defProcessName, 6016 String processName, int uid) { 6017 if (processName == null) { 6018 return defProcessName; 6019 } 6020 return processName; 6021 } 6022 6023 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6024 throws PackageManagerException { 6025 if (pkgSetting.signatures.mSignatures != null) { 6026 // Already existing package. Make sure signatures match 6027 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6028 == PackageManager.SIGNATURE_MATCH; 6029 if (!match) { 6030 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6031 == PackageManager.SIGNATURE_MATCH; 6032 } 6033 if (!match) { 6034 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6035 == PackageManager.SIGNATURE_MATCH; 6036 } 6037 if (!match) { 6038 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6039 + pkg.packageName + " signatures do not match the " 6040 + "previously installed version; ignoring!"); 6041 } 6042 } 6043 6044 // Check for shared user signatures 6045 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6046 // Already existing package. Make sure signatures match 6047 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6048 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6049 if (!match) { 6050 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6051 == PackageManager.SIGNATURE_MATCH; 6052 } 6053 if (!match) { 6054 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6055 == PackageManager.SIGNATURE_MATCH; 6056 } 6057 if (!match) { 6058 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6059 "Package " + pkg.packageName 6060 + " has no signatures that match those in shared user " 6061 + pkgSetting.sharedUser.name + "; ignoring!"); 6062 } 6063 } 6064 } 6065 6066 /** 6067 * Enforces that only the system UID or root's UID can call a method exposed 6068 * via Binder. 6069 * 6070 * @param message used as message if SecurityException is thrown 6071 * @throws SecurityException if the caller is not system or root 6072 */ 6073 private static final void enforceSystemOrRoot(String message) { 6074 final int uid = Binder.getCallingUid(); 6075 if (uid != Process.SYSTEM_UID && uid != 0) { 6076 throw new SecurityException(message); 6077 } 6078 } 6079 6080 @Override 6081 public void performBootDexOpt() { 6082 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6083 6084 // Before everything else, see whether we need to fstrim. 6085 try { 6086 IMountService ms = PackageHelper.getMountService(); 6087 if (ms != null) { 6088 final boolean isUpgrade = isUpgrade(); 6089 boolean doTrim = isUpgrade; 6090 if (doTrim) { 6091 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6092 } else { 6093 final long interval = android.provider.Settings.Global.getLong( 6094 mContext.getContentResolver(), 6095 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6096 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6097 if (interval > 0) { 6098 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6099 if (timeSinceLast > interval) { 6100 doTrim = true; 6101 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6102 + "; running immediately"); 6103 } 6104 } 6105 } 6106 if (doTrim) { 6107 if (!isFirstBoot()) { 6108 try { 6109 ActivityManagerNative.getDefault().showBootMessage( 6110 mContext.getResources().getString( 6111 R.string.android_upgrading_fstrim), true); 6112 } catch (RemoteException e) { 6113 } 6114 } 6115 ms.runMaintenance(); 6116 } 6117 } else { 6118 Slog.e(TAG, "Mount service unavailable!"); 6119 } 6120 } catch (RemoteException e) { 6121 // Can't happen; MountService is local 6122 } 6123 6124 final ArraySet<PackageParser.Package> pkgs; 6125 synchronized (mPackages) { 6126 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6127 } 6128 6129 if (pkgs != null) { 6130 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6131 // in case the device runs out of space. 6132 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6133 // Give priority to core apps. 6134 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6135 PackageParser.Package pkg = it.next(); 6136 if (pkg.coreApp) { 6137 if (DEBUG_DEXOPT) { 6138 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6139 } 6140 sortedPkgs.add(pkg); 6141 it.remove(); 6142 } 6143 } 6144 // Give priority to system apps that listen for pre boot complete. 6145 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6146 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6147 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6148 PackageParser.Package pkg = it.next(); 6149 if (pkgNames.contains(pkg.packageName)) { 6150 if (DEBUG_DEXOPT) { 6151 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6152 } 6153 sortedPkgs.add(pkg); 6154 it.remove(); 6155 } 6156 } 6157 // Give priority to system apps. 6158 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6159 PackageParser.Package pkg = it.next(); 6160 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6161 if (DEBUG_DEXOPT) { 6162 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6163 } 6164 sortedPkgs.add(pkg); 6165 it.remove(); 6166 } 6167 } 6168 // Give priority to updated system apps. 6169 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6170 PackageParser.Package pkg = it.next(); 6171 if (pkg.isUpdatedSystemApp()) { 6172 if (DEBUG_DEXOPT) { 6173 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6174 } 6175 sortedPkgs.add(pkg); 6176 it.remove(); 6177 } 6178 } 6179 // Give priority to apps that listen for boot complete. 6180 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6181 pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6182 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6183 PackageParser.Package pkg = it.next(); 6184 if (pkgNames.contains(pkg.packageName)) { 6185 if (DEBUG_DEXOPT) { 6186 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6187 } 6188 sortedPkgs.add(pkg); 6189 it.remove(); 6190 } 6191 } 6192 // Filter out packages that aren't recently used. 6193 filterRecentlyUsedApps(pkgs); 6194 // Add all remaining apps. 6195 for (PackageParser.Package pkg : pkgs) { 6196 if (DEBUG_DEXOPT) { 6197 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6198 } 6199 sortedPkgs.add(pkg); 6200 } 6201 6202 // If we want to be lazy, filter everything that wasn't recently used. 6203 if (mLazyDexOpt) { 6204 filterRecentlyUsedApps(sortedPkgs); 6205 } 6206 6207 int i = 0; 6208 int total = sortedPkgs.size(); 6209 File dataDir = Environment.getDataDirectory(); 6210 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6211 if (lowThreshold == 0) { 6212 throw new IllegalStateException("Invalid low memory threshold"); 6213 } 6214 for (PackageParser.Package pkg : sortedPkgs) { 6215 long usableSpace = dataDir.getUsableSpace(); 6216 if (usableSpace < lowThreshold) { 6217 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6218 break; 6219 } 6220 performBootDexOpt(pkg, ++i, total); 6221 } 6222 } 6223 } 6224 6225 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6226 // Filter out packages that aren't recently used. 6227 // 6228 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6229 // should do a full dexopt. 6230 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6231 int total = pkgs.size(); 6232 int skipped = 0; 6233 long now = System.currentTimeMillis(); 6234 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6235 PackageParser.Package pkg = i.next(); 6236 long then = pkg.mLastPackageUsageTimeInMills; 6237 if (then + mDexOptLRUThresholdInMills < now) { 6238 if (DEBUG_DEXOPT) { 6239 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6240 ((then == 0) ? "never" : new Date(then))); 6241 } 6242 i.remove(); 6243 skipped++; 6244 } 6245 } 6246 if (DEBUG_DEXOPT) { 6247 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6248 } 6249 } 6250 } 6251 6252 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6253 List<ResolveInfo> ris = null; 6254 try { 6255 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6256 intent, null, 0, userId); 6257 } catch (RemoteException e) { 6258 } 6259 ArraySet<String> pkgNames = new ArraySet<String>(); 6260 if (ris != null) { 6261 for (ResolveInfo ri : ris) { 6262 pkgNames.add(ri.activityInfo.packageName); 6263 } 6264 } 6265 return pkgNames; 6266 } 6267 6268 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6269 if (DEBUG_DEXOPT) { 6270 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6271 } 6272 if (!isFirstBoot()) { 6273 try { 6274 ActivityManagerNative.getDefault().showBootMessage( 6275 mContext.getResources().getString(R.string.android_upgrading_apk, 6276 curr, total), true); 6277 } catch (RemoteException e) { 6278 } 6279 } 6280 PackageParser.Package p = pkg; 6281 synchronized (mInstallLock) { 6282 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6283 false /* force dex */, false /* defer */, true /* include dependencies */); 6284 } 6285 } 6286 6287 @Override 6288 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6289 return performDexOptTraced(packageName, instructionSet, false); 6290 } 6291 6292 public boolean performDexOpt( 6293 String packageName, String instructionSet, boolean backgroundDexopt) { 6294 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6295 } 6296 6297 private boolean performDexOptTraced( 6298 String packageName, String instructionSet, boolean backgroundDexopt) { 6299 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6300 try { 6301 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6302 } finally { 6303 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6304 } 6305 } 6306 6307 private boolean performDexOptInternal( 6308 String packageName, String instructionSet, boolean backgroundDexopt) { 6309 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6310 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6311 if (!dexopt && !updateUsage) { 6312 // We aren't going to dexopt or update usage, so bail early. 6313 return false; 6314 } 6315 PackageParser.Package p; 6316 final String targetInstructionSet; 6317 synchronized (mPackages) { 6318 p = mPackages.get(packageName); 6319 if (p == null) { 6320 return false; 6321 } 6322 if (updateUsage) { 6323 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6324 } 6325 mPackageUsage.write(false); 6326 if (!dexopt) { 6327 // We aren't going to dexopt, so bail early. 6328 return false; 6329 } 6330 6331 targetInstructionSet = instructionSet != null ? instructionSet : 6332 getPrimaryInstructionSet(p.applicationInfo); 6333 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6334 return false; 6335 } 6336 } 6337 long callingId = Binder.clearCallingIdentity(); 6338 try { 6339 synchronized (mInstallLock) { 6340 final String[] instructionSets = new String[] { targetInstructionSet }; 6341 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6342 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6343 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6344 } 6345 } finally { 6346 Binder.restoreCallingIdentity(callingId); 6347 } 6348 } 6349 6350 public ArraySet<String> getPackagesThatNeedDexOpt() { 6351 ArraySet<String> pkgs = null; 6352 synchronized (mPackages) { 6353 for (PackageParser.Package p : mPackages.values()) { 6354 if (DEBUG_DEXOPT) { 6355 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6356 } 6357 if (!p.mDexOptPerformed.isEmpty()) { 6358 continue; 6359 } 6360 if (pkgs == null) { 6361 pkgs = new ArraySet<String>(); 6362 } 6363 pkgs.add(p.packageName); 6364 } 6365 } 6366 return pkgs; 6367 } 6368 6369 public void shutdown() { 6370 mPackageUsage.write(true); 6371 } 6372 6373 @Override 6374 public void forceDexOpt(String packageName) { 6375 enforceSystemOrRoot("forceDexOpt"); 6376 6377 PackageParser.Package pkg; 6378 synchronized (mPackages) { 6379 pkg = mPackages.get(packageName); 6380 if (pkg == null) { 6381 throw new IllegalArgumentException("Missing package: " + packageName); 6382 } 6383 } 6384 6385 synchronized (mInstallLock) { 6386 final String[] instructionSets = new String[] { 6387 getPrimaryInstructionSet(pkg.applicationInfo) }; 6388 6389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6390 6391 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6392 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6393 6394 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6395 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6396 throw new IllegalStateException("Failed to dexopt: " + res); 6397 } 6398 } 6399 } 6400 6401 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6402 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6403 Slog.w(TAG, "Unable to update from " + oldPkg.name 6404 + " to " + newPkg.packageName 6405 + ": old package not in system partition"); 6406 return false; 6407 } else if (mPackages.get(oldPkg.name) != null) { 6408 Slog.w(TAG, "Unable to update from " + oldPkg.name 6409 + " to " + newPkg.packageName 6410 + ": old package still exists"); 6411 return false; 6412 } 6413 return true; 6414 } 6415 6416 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6417 int[] users = sUserManager.getUserIds(); 6418 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6419 if (res < 0) { 6420 return res; 6421 } 6422 for (int user : users) { 6423 if (user != 0) { 6424 res = mInstaller.createUserData(volumeUuid, packageName, 6425 UserHandle.getUid(user, uid), user, seinfo); 6426 if (res < 0) { 6427 return res; 6428 } 6429 } 6430 } 6431 return res; 6432 } 6433 6434 private int removeDataDirsLI(String volumeUuid, String packageName) { 6435 int[] users = sUserManager.getUserIds(); 6436 int res = 0; 6437 for (int user : users) { 6438 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6439 if (resInner < 0) { 6440 res = resInner; 6441 } 6442 } 6443 6444 return res; 6445 } 6446 6447 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6448 int[] users = sUserManager.getUserIds(); 6449 int res = 0; 6450 for (int user : users) { 6451 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6452 if (resInner < 0) { 6453 res = resInner; 6454 } 6455 } 6456 return res; 6457 } 6458 6459 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6460 PackageParser.Package changingLib) { 6461 if (file.path != null) { 6462 usesLibraryFiles.add(file.path); 6463 return; 6464 } 6465 PackageParser.Package p = mPackages.get(file.apk); 6466 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6467 // If we are doing this while in the middle of updating a library apk, 6468 // then we need to make sure to use that new apk for determining the 6469 // dependencies here. (We haven't yet finished committing the new apk 6470 // to the package manager state.) 6471 if (p == null || p.packageName.equals(changingLib.packageName)) { 6472 p = changingLib; 6473 } 6474 } 6475 if (p != null) { 6476 usesLibraryFiles.addAll(p.getAllCodePaths()); 6477 } 6478 } 6479 6480 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6481 PackageParser.Package changingLib) throws PackageManagerException { 6482 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6483 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6484 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6485 for (int i=0; i<N; i++) { 6486 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6487 if (file == null) { 6488 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6489 "Package " + pkg.packageName + " requires unavailable shared library " 6490 + pkg.usesLibraries.get(i) + "; failing!"); 6491 } 6492 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6493 } 6494 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6495 for (int i=0; i<N; i++) { 6496 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6497 if (file == null) { 6498 Slog.w(TAG, "Package " + pkg.packageName 6499 + " desires unavailable shared library " 6500 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6501 } else { 6502 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6503 } 6504 } 6505 N = usesLibraryFiles.size(); 6506 if (N > 0) { 6507 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6508 } else { 6509 pkg.usesLibraryFiles = null; 6510 } 6511 } 6512 } 6513 6514 private static boolean hasString(List<String> list, List<String> which) { 6515 if (list == null) { 6516 return false; 6517 } 6518 for (int i=list.size()-1; i>=0; i--) { 6519 for (int j=which.size()-1; j>=0; j--) { 6520 if (which.get(j).equals(list.get(i))) { 6521 return true; 6522 } 6523 } 6524 } 6525 return false; 6526 } 6527 6528 private void updateAllSharedLibrariesLPw() { 6529 for (PackageParser.Package pkg : mPackages.values()) { 6530 try { 6531 updateSharedLibrariesLPw(pkg, null); 6532 } catch (PackageManagerException e) { 6533 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6534 } 6535 } 6536 } 6537 6538 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6539 PackageParser.Package changingPkg) { 6540 ArrayList<PackageParser.Package> res = null; 6541 for (PackageParser.Package pkg : mPackages.values()) { 6542 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6543 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6544 if (res == null) { 6545 res = new ArrayList<PackageParser.Package>(); 6546 } 6547 res.add(pkg); 6548 try { 6549 updateSharedLibrariesLPw(pkg, changingPkg); 6550 } catch (PackageManagerException e) { 6551 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6552 } 6553 } 6554 } 6555 return res; 6556 } 6557 6558 /** 6559 * Derive the value of the {@code cpuAbiOverride} based on the provided 6560 * value and an optional stored value from the package settings. 6561 */ 6562 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6563 String cpuAbiOverride = null; 6564 6565 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6566 cpuAbiOverride = null; 6567 } else if (abiOverride != null) { 6568 cpuAbiOverride = abiOverride; 6569 } else if (settings != null) { 6570 cpuAbiOverride = settings.cpuAbiOverrideString; 6571 } 6572 6573 return cpuAbiOverride; 6574 } 6575 6576 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6577 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6578 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6579 try { 6580 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6581 } finally { 6582 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6583 } 6584 } 6585 6586 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6587 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6588 boolean success = false; 6589 try { 6590 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6591 currentTime, user); 6592 success = true; 6593 return res; 6594 } finally { 6595 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6596 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6597 } 6598 } 6599 } 6600 6601 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6602 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6603 final File scanFile = new File(pkg.codePath); 6604 if (pkg.applicationInfo.getCodePath() == null || 6605 pkg.applicationInfo.getResourcePath() == null) { 6606 // Bail out. The resource and code paths haven't been set. 6607 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6608 "Code and resource paths haven't been set correctly"); 6609 } 6610 6611 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6612 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6613 } else { 6614 // Only allow system apps to be flagged as core apps. 6615 pkg.coreApp = false; 6616 } 6617 6618 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6619 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6620 } 6621 6622 if (mCustomResolverComponentName != null && 6623 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6624 setUpCustomResolverActivity(pkg); 6625 } 6626 6627 if (pkg.packageName.equals("android")) { 6628 synchronized (mPackages) { 6629 if (mAndroidApplication != null) { 6630 Slog.w(TAG, "*************************************************"); 6631 Slog.w(TAG, "Core android package being redefined. Skipping."); 6632 Slog.w(TAG, " file=" + scanFile); 6633 Slog.w(TAG, "*************************************************"); 6634 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6635 "Core android package being redefined. Skipping."); 6636 } 6637 6638 // Set up information for our fall-back user intent resolution activity. 6639 mPlatformPackage = pkg; 6640 pkg.mVersionCode = mSdkVersion; 6641 mAndroidApplication = pkg.applicationInfo; 6642 6643 if (!mResolverReplaced) { 6644 mResolveActivity.applicationInfo = mAndroidApplication; 6645 mResolveActivity.name = ResolverActivity.class.getName(); 6646 mResolveActivity.packageName = mAndroidApplication.packageName; 6647 mResolveActivity.processName = "system:ui"; 6648 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6649 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6650 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6651 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6652 mResolveActivity.exported = true; 6653 mResolveActivity.enabled = true; 6654 mResolveInfo.activityInfo = mResolveActivity; 6655 mResolveInfo.priority = 0; 6656 mResolveInfo.preferredOrder = 0; 6657 mResolveInfo.match = 0; 6658 mResolveComponentName = new ComponentName( 6659 mAndroidApplication.packageName, mResolveActivity.name); 6660 } 6661 } 6662 } 6663 6664 if (DEBUG_PACKAGE_SCANNING) { 6665 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6666 Log.d(TAG, "Scanning package " + pkg.packageName); 6667 } 6668 6669 if (mPackages.containsKey(pkg.packageName) 6670 || mSharedLibraries.containsKey(pkg.packageName)) { 6671 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6672 "Application package " + pkg.packageName 6673 + " already installed. Skipping duplicate."); 6674 } 6675 6676 // If we're only installing presumed-existing packages, require that the 6677 // scanned APK is both already known and at the path previously established 6678 // for it. Previously unknown packages we pick up normally, but if we have an 6679 // a priori expectation about this package's install presence, enforce it. 6680 // With a singular exception for new system packages. When an OTA contains 6681 // a new system package, we allow the codepath to change from a system location 6682 // to the user-installed location. If we don't allow this change, any newer, 6683 // user-installed version of the application will be ignored. 6684 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6685 if (mExpectingBetter.containsKey(pkg.packageName)) { 6686 logCriticalInfo(Log.WARN, 6687 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6688 } else { 6689 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6690 if (known != null) { 6691 if (DEBUG_PACKAGE_SCANNING) { 6692 Log.d(TAG, "Examining " + pkg.codePath 6693 + " and requiring known paths " + known.codePathString 6694 + " & " + known.resourcePathString); 6695 } 6696 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6697 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6698 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6699 "Application package " + pkg.packageName 6700 + " found at " + pkg.applicationInfo.getCodePath() 6701 + " but expected at " + known.codePathString + "; ignoring."); 6702 } 6703 } 6704 } 6705 } 6706 6707 // Initialize package source and resource directories 6708 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6709 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6710 6711 SharedUserSetting suid = null; 6712 PackageSetting pkgSetting = null; 6713 6714 if (!isSystemApp(pkg)) { 6715 // Only system apps can use these features. 6716 pkg.mOriginalPackages = null; 6717 pkg.mRealPackage = null; 6718 pkg.mAdoptPermissions = null; 6719 } 6720 6721 // writer 6722 synchronized (mPackages) { 6723 if (pkg.mSharedUserId != null) { 6724 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6725 if (suid == null) { 6726 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6727 "Creating application package " + pkg.packageName 6728 + " for shared user failed"); 6729 } 6730 if (DEBUG_PACKAGE_SCANNING) { 6731 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6732 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6733 + "): packages=" + suid.packages); 6734 } 6735 } 6736 6737 // Check if we are renaming from an original package name. 6738 PackageSetting origPackage = null; 6739 String realName = null; 6740 if (pkg.mOriginalPackages != null) { 6741 // This package may need to be renamed to a previously 6742 // installed name. Let's check on that... 6743 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6744 if (pkg.mOriginalPackages.contains(renamed)) { 6745 // This package had originally been installed as the 6746 // original name, and we have already taken care of 6747 // transitioning to the new one. Just update the new 6748 // one to continue using the old name. 6749 realName = pkg.mRealPackage; 6750 if (!pkg.packageName.equals(renamed)) { 6751 // Callers into this function may have already taken 6752 // care of renaming the package; only do it here if 6753 // it is not already done. 6754 pkg.setPackageName(renamed); 6755 } 6756 6757 } else { 6758 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6759 if ((origPackage = mSettings.peekPackageLPr( 6760 pkg.mOriginalPackages.get(i))) != null) { 6761 // We do have the package already installed under its 6762 // original name... should we use it? 6763 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6764 // New package is not compatible with original. 6765 origPackage = null; 6766 continue; 6767 } else if (origPackage.sharedUser != null) { 6768 // Make sure uid is compatible between packages. 6769 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6770 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6771 + " to " + pkg.packageName + ": old uid " 6772 + origPackage.sharedUser.name 6773 + " differs from " + pkg.mSharedUserId); 6774 origPackage = null; 6775 continue; 6776 } 6777 } else { 6778 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6779 + pkg.packageName + " to old name " + origPackage.name); 6780 } 6781 break; 6782 } 6783 } 6784 } 6785 } 6786 6787 if (mTransferedPackages.contains(pkg.packageName)) { 6788 Slog.w(TAG, "Package " + pkg.packageName 6789 + " was transferred to another, but its .apk remains"); 6790 } 6791 6792 // Just create the setting, don't add it yet. For already existing packages 6793 // the PkgSetting exists already and doesn't have to be created. 6794 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6795 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6796 pkg.applicationInfo.primaryCpuAbi, 6797 pkg.applicationInfo.secondaryCpuAbi, 6798 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6799 user, false); 6800 if (pkgSetting == null) { 6801 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6802 "Creating application package " + pkg.packageName + " failed"); 6803 } 6804 6805 if (pkgSetting.origPackage != null) { 6806 // If we are first transitioning from an original package, 6807 // fix up the new package's name now. We need to do this after 6808 // looking up the package under its new name, so getPackageLP 6809 // can take care of fiddling things correctly. 6810 pkg.setPackageName(origPackage.name); 6811 6812 // File a report about this. 6813 String msg = "New package " + pkgSetting.realName 6814 + " renamed to replace old package " + pkgSetting.name; 6815 reportSettingsProblem(Log.WARN, msg); 6816 6817 // Make a note of it. 6818 mTransferedPackages.add(origPackage.name); 6819 6820 // No longer need to retain this. 6821 pkgSetting.origPackage = null; 6822 } 6823 6824 if (realName != null) { 6825 // Make a note of it. 6826 mTransferedPackages.add(pkg.packageName); 6827 } 6828 6829 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6830 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6831 } 6832 6833 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6834 // Check all shared libraries and map to their actual file path. 6835 // We only do this here for apps not on a system dir, because those 6836 // are the only ones that can fail an install due to this. We 6837 // will take care of the system apps by updating all of their 6838 // library paths after the scan is done. 6839 updateSharedLibrariesLPw(pkg, null); 6840 } 6841 6842 if (mFoundPolicyFile) { 6843 SELinuxMMAC.assignSeinfoValue(pkg); 6844 } 6845 6846 pkg.applicationInfo.uid = pkgSetting.appId; 6847 pkg.mExtras = pkgSetting; 6848 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6849 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6850 // We just determined the app is signed correctly, so bring 6851 // over the latest parsed certs. 6852 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6853 } else { 6854 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6855 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6856 "Package " + pkg.packageName + " upgrade keys do not match the " 6857 + "previously installed version"); 6858 } else { 6859 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6860 String msg = "System package " + pkg.packageName 6861 + " signature changed; retaining data."; 6862 reportSettingsProblem(Log.WARN, msg); 6863 } 6864 } 6865 } else { 6866 try { 6867 verifySignaturesLP(pkgSetting, pkg); 6868 // We just determined the app is signed correctly, so bring 6869 // over the latest parsed certs. 6870 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6871 } catch (PackageManagerException e) { 6872 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6873 throw e; 6874 } 6875 // The signature has changed, but this package is in the system 6876 // image... let's recover! 6877 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6878 // However... if this package is part of a shared user, but it 6879 // doesn't match the signature of the shared user, let's fail. 6880 // What this means is that you can't change the signatures 6881 // associated with an overall shared user, which doesn't seem all 6882 // that unreasonable. 6883 if (pkgSetting.sharedUser != null) { 6884 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6885 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6886 throw new PackageManagerException( 6887 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6888 "Signature mismatch for shared user : " 6889 + pkgSetting.sharedUser); 6890 } 6891 } 6892 // File a report about this. 6893 String msg = "System package " + pkg.packageName 6894 + " signature changed; retaining data."; 6895 reportSettingsProblem(Log.WARN, msg); 6896 } 6897 } 6898 // Verify that this new package doesn't have any content providers 6899 // that conflict with existing packages. Only do this if the 6900 // package isn't already installed, since we don't want to break 6901 // things that are installed. 6902 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6903 final int N = pkg.providers.size(); 6904 int i; 6905 for (i=0; i<N; i++) { 6906 PackageParser.Provider p = pkg.providers.get(i); 6907 if (p.info.authority != null) { 6908 String names[] = p.info.authority.split(";"); 6909 for (int j = 0; j < names.length; j++) { 6910 if (mProvidersByAuthority.containsKey(names[j])) { 6911 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6912 final String otherPackageName = 6913 ((other != null && other.getComponentName() != null) ? 6914 other.getComponentName().getPackageName() : "?"); 6915 throw new PackageManagerException( 6916 INSTALL_FAILED_CONFLICTING_PROVIDER, 6917 "Can't install because provider name " + names[j] 6918 + " (in package " + pkg.applicationInfo.packageName 6919 + ") is already used by " + otherPackageName); 6920 } 6921 } 6922 } 6923 } 6924 } 6925 6926 if (pkg.mAdoptPermissions != null) { 6927 // This package wants to adopt ownership of permissions from 6928 // another package. 6929 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6930 final String origName = pkg.mAdoptPermissions.get(i); 6931 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6932 if (orig != null) { 6933 if (verifyPackageUpdateLPr(orig, pkg)) { 6934 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6935 + pkg.packageName); 6936 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6937 } 6938 } 6939 } 6940 } 6941 } 6942 6943 final String pkgName = pkg.packageName; 6944 6945 final long scanFileTime = scanFile.lastModified(); 6946 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6947 pkg.applicationInfo.processName = fixProcessName( 6948 pkg.applicationInfo.packageName, 6949 pkg.applicationInfo.processName, 6950 pkg.applicationInfo.uid); 6951 6952 File dataPath; 6953 if (mPlatformPackage == pkg) { 6954 // The system package is special. 6955 dataPath = new File(Environment.getDataDirectory(), "system"); 6956 6957 pkg.applicationInfo.dataDir = dataPath.getPath(); 6958 6959 } else { 6960 // This is a normal package, need to make its data directory. 6961 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6962 UserHandle.USER_OWNER, pkg.packageName); 6963 6964 boolean uidError = false; 6965 if (dataPath.exists()) { 6966 int currentUid = 0; 6967 try { 6968 StructStat stat = Os.stat(dataPath.getPath()); 6969 currentUid = stat.st_uid; 6970 } catch (ErrnoException e) { 6971 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6972 } 6973 6974 // If we have mismatched owners for the data path, we have a problem. 6975 if (currentUid != pkg.applicationInfo.uid) { 6976 boolean recovered = false; 6977 if (currentUid == 0) { 6978 // The directory somehow became owned by root. Wow. 6979 // This is probably because the system was stopped while 6980 // installd was in the middle of messing with its libs 6981 // directory. Ask installd to fix that. 6982 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6983 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6984 if (ret >= 0) { 6985 recovered = true; 6986 String msg = "Package " + pkg.packageName 6987 + " unexpectedly changed to uid 0; recovered to " + 6988 + pkg.applicationInfo.uid; 6989 reportSettingsProblem(Log.WARN, msg); 6990 } 6991 } 6992 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6993 || (scanFlags&SCAN_BOOTING) != 0)) { 6994 // If this is a system app, we can at least delete its 6995 // current data so the application will still work. 6996 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6997 if (ret >= 0) { 6998 // TODO: Kill the processes first 6999 // Old data gone! 7000 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7001 ? "System package " : "Third party package "; 7002 String msg = prefix + pkg.packageName 7003 + " has changed from uid: " 7004 + currentUid + " to " 7005 + pkg.applicationInfo.uid + "; old data erased"; 7006 reportSettingsProblem(Log.WARN, msg); 7007 recovered = true; 7008 7009 // And now re-install the app. 7010 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7011 pkg.applicationInfo.seinfo); 7012 if (ret == -1) { 7013 // Ack should not happen! 7014 msg = prefix + pkg.packageName 7015 + " could not have data directory re-created after delete."; 7016 reportSettingsProblem(Log.WARN, msg); 7017 throw new PackageManagerException( 7018 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 7019 } 7020 } 7021 if (!recovered) { 7022 mHasSystemUidErrors = true; 7023 } 7024 } else if (!recovered) { 7025 // If we allow this install to proceed, we will be broken. 7026 // Abort, abort! 7027 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7028 "scanPackageLI"); 7029 } 7030 if (!recovered) { 7031 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7032 + pkg.applicationInfo.uid + "/fs_" 7033 + currentUid; 7034 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7035 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7036 String msg = "Package " + pkg.packageName 7037 + " has mismatched uid: " 7038 + currentUid + " on disk, " 7039 + pkg.applicationInfo.uid + " in settings"; 7040 // writer 7041 synchronized (mPackages) { 7042 mSettings.mReadMessages.append(msg); 7043 mSettings.mReadMessages.append('\n'); 7044 uidError = true; 7045 if (!pkgSetting.uidError) { 7046 reportSettingsProblem(Log.ERROR, msg); 7047 } 7048 } 7049 } 7050 } 7051 pkg.applicationInfo.dataDir = dataPath.getPath(); 7052 if (mShouldRestoreconData) { 7053 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7054 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7055 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7056 } 7057 } else { 7058 if (DEBUG_PACKAGE_SCANNING) { 7059 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7060 Log.v(TAG, "Want this data dir: " + dataPath); 7061 } 7062 //invoke installer to do the actual installation 7063 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7064 pkg.applicationInfo.seinfo); 7065 if (ret < 0) { 7066 // Error from installer 7067 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7068 "Unable to create data dirs [errorCode=" + ret + "]"); 7069 } 7070 7071 if (dataPath.exists()) { 7072 pkg.applicationInfo.dataDir = dataPath.getPath(); 7073 } else { 7074 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7075 pkg.applicationInfo.dataDir = null; 7076 } 7077 } 7078 7079 pkgSetting.uidError = uidError; 7080 } 7081 7082 final String path = scanFile.getPath(); 7083 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7084 7085 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7086 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7087 7088 // Some system apps still use directory structure for native libraries 7089 // in which case we might end up not detecting abi solely based on apk 7090 // structure. Try to detect abi based on directory structure. 7091 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7092 pkg.applicationInfo.primaryCpuAbi == null) { 7093 setBundledAppAbisAndRoots(pkg, pkgSetting); 7094 setNativeLibraryPaths(pkg); 7095 } 7096 7097 } else { 7098 if ((scanFlags & SCAN_MOVE) != 0) { 7099 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7100 // but we already have this packages package info in the PackageSetting. We just 7101 // use that and derive the native library path based on the new codepath. 7102 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7103 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7104 } 7105 7106 // Set native library paths again. For moves, the path will be updated based on the 7107 // ABIs we've determined above. For non-moves, the path will be updated based on the 7108 // ABIs we determined during compilation, but the path will depend on the final 7109 // package path (after the rename away from the stage path). 7110 setNativeLibraryPaths(pkg); 7111 } 7112 7113 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7114 final int[] userIds = sUserManager.getUserIds(); 7115 synchronized (mInstallLock) { 7116 // Make sure all user data directories are ready to roll; we're okay 7117 // if they already exist 7118 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7119 for (int userId : userIds) { 7120 if (userId != 0) { 7121 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7122 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7123 pkg.applicationInfo.seinfo); 7124 } 7125 } 7126 } 7127 7128 // Create a native library symlink only if we have native libraries 7129 // and if the native libraries are 32 bit libraries. We do not provide 7130 // this symlink for 64 bit libraries. 7131 if (pkg.applicationInfo.primaryCpuAbi != null && 7132 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7133 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7134 try { 7135 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7136 for (int userId : userIds) { 7137 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7138 nativeLibPath, userId) < 0) { 7139 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7140 "Failed linking native library dir (user=" + userId + ")"); 7141 } 7142 } 7143 } finally { 7144 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7145 } 7146 } 7147 } 7148 7149 // This is a special case for the "system" package, where the ABI is 7150 // dictated by the zygote configuration (and init.rc). We should keep track 7151 // of this ABI so that we can deal with "normal" applications that run under 7152 // the same UID correctly. 7153 if (mPlatformPackage == pkg) { 7154 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7155 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7156 } 7157 7158 // If there's a mismatch between the abi-override in the package setting 7159 // and the abiOverride specified for the install. Warn about this because we 7160 // would've already compiled the app without taking the package setting into 7161 // account. 7162 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7163 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7164 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7165 " for package: " + pkg.packageName); 7166 } 7167 } 7168 7169 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7170 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7171 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7172 7173 // Copy the derived override back to the parsed package, so that we can 7174 // update the package settings accordingly. 7175 pkg.cpuAbiOverride = cpuAbiOverride; 7176 7177 if (DEBUG_ABI_SELECTION) { 7178 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7179 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7180 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7181 } 7182 7183 // Push the derived path down into PackageSettings so we know what to 7184 // clean up at uninstall time. 7185 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7186 7187 if (DEBUG_ABI_SELECTION) { 7188 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7189 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7190 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7191 } 7192 7193 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7194 // We don't do this here during boot because we can do it all 7195 // at once after scanning all existing packages. 7196 // 7197 // We also do this *before* we perform dexopt on this package, so that 7198 // we can avoid redundant dexopts, and also to make sure we've got the 7199 // code and package path correct. 7200 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7201 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7202 } 7203 7204 if ((scanFlags & SCAN_NO_DEX) == 0) { 7205 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7206 7207 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7208 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7209 7210 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7211 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7212 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7213 } 7214 } 7215 if (mFactoryTest && pkg.requestedPermissions.contains( 7216 android.Manifest.permission.FACTORY_TEST)) { 7217 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7218 } 7219 7220 ArrayList<PackageParser.Package> clientLibPkgs = null; 7221 7222 // writer 7223 synchronized (mPackages) { 7224 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7225 // Only system apps can add new shared libraries. 7226 if (pkg.libraryNames != null) { 7227 for (int i=0; i<pkg.libraryNames.size(); i++) { 7228 String name = pkg.libraryNames.get(i); 7229 boolean allowed = false; 7230 if (pkg.isUpdatedSystemApp()) { 7231 // New library entries can only be added through the 7232 // system image. This is important to get rid of a lot 7233 // of nasty edge cases: for example if we allowed a non- 7234 // system update of the app to add a library, then uninstalling 7235 // the update would make the library go away, and assumptions 7236 // we made such as through app install filtering would now 7237 // have allowed apps on the device which aren't compatible 7238 // with it. Better to just have the restriction here, be 7239 // conservative, and create many fewer cases that can negatively 7240 // impact the user experience. 7241 final PackageSetting sysPs = mSettings 7242 .getDisabledSystemPkgLPr(pkg.packageName); 7243 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7244 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7245 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7246 allowed = true; 7247 allowed = true; 7248 break; 7249 } 7250 } 7251 } 7252 } else { 7253 allowed = true; 7254 } 7255 if (allowed) { 7256 if (!mSharedLibraries.containsKey(name)) { 7257 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7258 } else if (!name.equals(pkg.packageName)) { 7259 Slog.w(TAG, "Package " + pkg.packageName + " library " 7260 + name + " already exists; skipping"); 7261 } 7262 } else { 7263 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7264 + name + " that is not declared on system image; skipping"); 7265 } 7266 } 7267 if ((scanFlags&SCAN_BOOTING) == 0) { 7268 // If we are not booting, we need to update any applications 7269 // that are clients of our shared library. If we are booting, 7270 // this will all be done once the scan is complete. 7271 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7272 } 7273 } 7274 } 7275 } 7276 7277 // We also need to dexopt any apps that are dependent on this library. Note that 7278 // if these fail, we should abort the install since installing the library will 7279 // result in some apps being broken. 7280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7281 try { 7282 if (clientLibPkgs != null) { 7283 if ((scanFlags & SCAN_NO_DEX) == 0) { 7284 for (int i = 0; i < clientLibPkgs.size(); i++) { 7285 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7286 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7287 null /* instruction sets */, forceDex, 7288 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7289 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7290 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7291 "scanPackageLI failed to dexopt clientLibPkgs"); 7292 } 7293 } 7294 } 7295 } 7296 } finally { 7297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7298 } 7299 7300 // Request the ActivityManager to kill the process(only for existing packages) 7301 // so that we do not end up in a confused state while the user is still using the older 7302 // version of the application while the new one gets installed. 7303 if ((scanFlags & SCAN_REPLACING) != 0) { 7304 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7305 7306 killApplication(pkg.applicationInfo.packageName, 7307 pkg.applicationInfo.uid, "replace pkg"); 7308 7309 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7310 } 7311 7312 // Also need to kill any apps that are dependent on the library. 7313 if (clientLibPkgs != null) { 7314 for (int i=0; i<clientLibPkgs.size(); i++) { 7315 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7316 killApplication(clientPkg.applicationInfo.packageName, 7317 clientPkg.applicationInfo.uid, "update lib"); 7318 } 7319 } 7320 7321 // Make sure we're not adding any bogus keyset info 7322 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7323 ksms.assertScannedPackageValid(pkg); 7324 7325 // writer 7326 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7327 7328 boolean createIdmapFailed = false; 7329 synchronized (mPackages) { 7330 // We don't expect installation to fail beyond this point 7331 7332 // Add the new setting to mSettings 7333 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7334 // Add the new setting to mPackages 7335 mPackages.put(pkg.applicationInfo.packageName, pkg); 7336 // Make sure we don't accidentally delete its data. 7337 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7338 while (iter.hasNext()) { 7339 PackageCleanItem item = iter.next(); 7340 if (pkgName.equals(item.packageName)) { 7341 iter.remove(); 7342 } 7343 } 7344 7345 // Take care of first install / last update times. 7346 if (currentTime != 0) { 7347 if (pkgSetting.firstInstallTime == 0) { 7348 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7349 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7350 pkgSetting.lastUpdateTime = currentTime; 7351 } 7352 } else if (pkgSetting.firstInstallTime == 0) { 7353 // We need *something*. Take time time stamp of the file. 7354 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7355 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7356 if (scanFileTime != pkgSetting.timeStamp) { 7357 // A package on the system image has changed; consider this 7358 // to be an update. 7359 pkgSetting.lastUpdateTime = scanFileTime; 7360 } 7361 } 7362 7363 // Add the package's KeySets to the global KeySetManagerService 7364 ksms.addScannedPackageLPw(pkg); 7365 7366 int N = pkg.providers.size(); 7367 StringBuilder r = null; 7368 int i; 7369 for (i=0; i<N; i++) { 7370 PackageParser.Provider p = pkg.providers.get(i); 7371 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7372 p.info.processName, pkg.applicationInfo.uid); 7373 mProviders.addProvider(p); 7374 p.syncable = p.info.isSyncable; 7375 if (p.info.authority != null) { 7376 String names[] = p.info.authority.split(";"); 7377 p.info.authority = null; 7378 for (int j = 0; j < names.length; j++) { 7379 if (j == 1 && p.syncable) { 7380 // We only want the first authority for a provider to possibly be 7381 // syncable, so if we already added this provider using a different 7382 // authority clear the syncable flag. We copy the provider before 7383 // changing it because the mProviders object contains a reference 7384 // to a provider that we don't want to change. 7385 // Only do this for the second authority since the resulting provider 7386 // object can be the same for all future authorities for this provider. 7387 p = new PackageParser.Provider(p); 7388 p.syncable = false; 7389 } 7390 if (!mProvidersByAuthority.containsKey(names[j])) { 7391 mProvidersByAuthority.put(names[j], p); 7392 if (p.info.authority == null) { 7393 p.info.authority = names[j]; 7394 } else { 7395 p.info.authority = p.info.authority + ";" + names[j]; 7396 } 7397 if (DEBUG_PACKAGE_SCANNING) { 7398 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7399 Log.d(TAG, "Registered content provider: " + names[j] 7400 + ", className = " + p.info.name + ", isSyncable = " 7401 + p.info.isSyncable); 7402 } 7403 } else { 7404 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7405 Slog.w(TAG, "Skipping provider name " + names[j] + 7406 " (in package " + pkg.applicationInfo.packageName + 7407 "): name already used by " 7408 + ((other != null && other.getComponentName() != null) 7409 ? other.getComponentName().getPackageName() : "?")); 7410 } 7411 } 7412 } 7413 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7414 if (r == null) { 7415 r = new StringBuilder(256); 7416 } else { 7417 r.append(' '); 7418 } 7419 r.append(p.info.name); 7420 } 7421 } 7422 if (r != null) { 7423 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7424 } 7425 7426 N = pkg.services.size(); 7427 r = null; 7428 for (i=0; i<N; i++) { 7429 PackageParser.Service s = pkg.services.get(i); 7430 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7431 s.info.processName, pkg.applicationInfo.uid); 7432 mServices.addService(s); 7433 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7434 if (r == null) { 7435 r = new StringBuilder(256); 7436 } else { 7437 r.append(' '); 7438 } 7439 r.append(s.info.name); 7440 } 7441 } 7442 if (r != null) { 7443 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7444 } 7445 7446 N = pkg.receivers.size(); 7447 r = null; 7448 for (i=0; i<N; i++) { 7449 PackageParser.Activity a = pkg.receivers.get(i); 7450 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7451 a.info.processName, pkg.applicationInfo.uid); 7452 mReceivers.addActivity(a, "receiver"); 7453 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7454 if (r == null) { 7455 r = new StringBuilder(256); 7456 } else { 7457 r.append(' '); 7458 } 7459 r.append(a.info.name); 7460 } 7461 } 7462 if (r != null) { 7463 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7464 } 7465 7466 N = pkg.activities.size(); 7467 r = null; 7468 for (i=0; i<N; i++) { 7469 PackageParser.Activity a = pkg.activities.get(i); 7470 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7471 a.info.processName, pkg.applicationInfo.uid); 7472 mActivities.addActivity(a, "activity"); 7473 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7474 if (r == null) { 7475 r = new StringBuilder(256); 7476 } else { 7477 r.append(' '); 7478 } 7479 r.append(a.info.name); 7480 } 7481 } 7482 if (r != null) { 7483 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7484 } 7485 7486 N = pkg.permissionGroups.size(); 7487 r = null; 7488 for (i=0; i<N; i++) { 7489 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7490 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7491 if (cur == null) { 7492 mPermissionGroups.put(pg.info.name, pg); 7493 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7494 if (r == null) { 7495 r = new StringBuilder(256); 7496 } else { 7497 r.append(' '); 7498 } 7499 r.append(pg.info.name); 7500 } 7501 } else { 7502 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7503 + pg.info.packageName + " ignored: original from " 7504 + cur.info.packageName); 7505 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7506 if (r == null) { 7507 r = new StringBuilder(256); 7508 } else { 7509 r.append(' '); 7510 } 7511 r.append("DUP:"); 7512 r.append(pg.info.name); 7513 } 7514 } 7515 } 7516 if (r != null) { 7517 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7518 } 7519 7520 N = pkg.permissions.size(); 7521 r = null; 7522 for (i=0; i<N; i++) { 7523 PackageParser.Permission p = pkg.permissions.get(i); 7524 7525 // Assume by default that we did not install this permission into the system. 7526 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7527 7528 // Now that permission groups have a special meaning, we ignore permission 7529 // groups for legacy apps to prevent unexpected behavior. In particular, 7530 // permissions for one app being granted to someone just becuase they happen 7531 // to be in a group defined by another app (before this had no implications). 7532 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7533 p.group = mPermissionGroups.get(p.info.group); 7534 // Warn for a permission in an unknown group. 7535 if (p.info.group != null && p.group == null) { 7536 Slog.w(TAG, "Permission " + p.info.name + " from package " 7537 + p.info.packageName + " in an unknown group " + p.info.group); 7538 } 7539 } 7540 7541 ArrayMap<String, BasePermission> permissionMap = 7542 p.tree ? mSettings.mPermissionTrees 7543 : mSettings.mPermissions; 7544 BasePermission bp = permissionMap.get(p.info.name); 7545 7546 // Allow system apps to redefine non-system permissions 7547 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7548 final boolean currentOwnerIsSystem = (bp.perm != null 7549 && isSystemApp(bp.perm.owner)); 7550 if (isSystemApp(p.owner)) { 7551 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7552 // It's a built-in permission and no owner, take ownership now 7553 bp.packageSetting = pkgSetting; 7554 bp.perm = p; 7555 bp.uid = pkg.applicationInfo.uid; 7556 bp.sourcePackage = p.info.packageName; 7557 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7558 } else if (!currentOwnerIsSystem) { 7559 String msg = "New decl " + p.owner + " of permission " 7560 + p.info.name + " is system; overriding " + bp.sourcePackage; 7561 reportSettingsProblem(Log.WARN, msg); 7562 bp = null; 7563 } 7564 } 7565 } 7566 7567 if (bp == null) { 7568 bp = new BasePermission(p.info.name, p.info.packageName, 7569 BasePermission.TYPE_NORMAL); 7570 permissionMap.put(p.info.name, bp); 7571 } 7572 7573 if (bp.perm == null) { 7574 if (bp.sourcePackage == null 7575 || bp.sourcePackage.equals(p.info.packageName)) { 7576 BasePermission tree = findPermissionTreeLP(p.info.name); 7577 if (tree == null 7578 || tree.sourcePackage.equals(p.info.packageName)) { 7579 bp.packageSetting = pkgSetting; 7580 bp.perm = p; 7581 bp.uid = pkg.applicationInfo.uid; 7582 bp.sourcePackage = p.info.packageName; 7583 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7584 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7585 if (r == null) { 7586 r = new StringBuilder(256); 7587 } else { 7588 r.append(' '); 7589 } 7590 r.append(p.info.name); 7591 } 7592 } else { 7593 Slog.w(TAG, "Permission " + p.info.name + " from package " 7594 + p.info.packageName + " ignored: base tree " 7595 + tree.name + " is from package " 7596 + tree.sourcePackage); 7597 } 7598 } else { 7599 Slog.w(TAG, "Permission " + p.info.name + " from package " 7600 + p.info.packageName + " ignored: original from " 7601 + bp.sourcePackage); 7602 } 7603 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7604 if (r == null) { 7605 r = new StringBuilder(256); 7606 } else { 7607 r.append(' '); 7608 } 7609 r.append("DUP:"); 7610 r.append(p.info.name); 7611 } 7612 if (bp.perm == p) { 7613 bp.protectionLevel = p.info.protectionLevel; 7614 } 7615 } 7616 7617 if (r != null) { 7618 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7619 } 7620 7621 N = pkg.instrumentation.size(); 7622 r = null; 7623 for (i=0; i<N; i++) { 7624 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7625 a.info.packageName = pkg.applicationInfo.packageName; 7626 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7627 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7628 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7629 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7630 a.info.dataDir = pkg.applicationInfo.dataDir; 7631 7632 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7633 // need other information about the application, like the ABI and what not ? 7634 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7635 mInstrumentation.put(a.getComponentName(), a); 7636 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7637 if (r == null) { 7638 r = new StringBuilder(256); 7639 } else { 7640 r.append(' '); 7641 } 7642 r.append(a.info.name); 7643 } 7644 } 7645 if (r != null) { 7646 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7647 } 7648 7649 if (pkg.protectedBroadcasts != null) { 7650 N = pkg.protectedBroadcasts.size(); 7651 for (i=0; i<N; i++) { 7652 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7653 } 7654 } 7655 7656 pkgSetting.setTimeStamp(scanFileTime); 7657 7658 // Create idmap files for pairs of (packages, overlay packages). 7659 // Note: "android", ie framework-res.apk, is handled by native layers. 7660 if (pkg.mOverlayTarget != null) { 7661 // This is an overlay package. 7662 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7663 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7664 mOverlays.put(pkg.mOverlayTarget, 7665 new ArrayMap<String, PackageParser.Package>()); 7666 } 7667 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7668 map.put(pkg.packageName, pkg); 7669 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7670 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7671 createIdmapFailed = true; 7672 } 7673 } 7674 } else if (mOverlays.containsKey(pkg.packageName) && 7675 !pkg.packageName.equals("android")) { 7676 // This is a regular package, with one or more known overlay packages. 7677 createIdmapsForPackageLI(pkg); 7678 } 7679 } 7680 7681 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7682 7683 if (createIdmapFailed) { 7684 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7685 "scanPackageLI failed to createIdmap"); 7686 } 7687 return pkg; 7688 } 7689 7690 /** 7691 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7692 * is derived purely on the basis of the contents of {@code scanFile} and 7693 * {@code cpuAbiOverride}. 7694 * 7695 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7696 */ 7697 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7698 String cpuAbiOverride, boolean extractLibs) 7699 throws PackageManagerException { 7700 // TODO: We can probably be smarter about this stuff. For installed apps, 7701 // we can calculate this information at install time once and for all. For 7702 // system apps, we can probably assume that this information doesn't change 7703 // after the first boot scan. As things stand, we do lots of unnecessary work. 7704 7705 // Give ourselves some initial paths; we'll come back for another 7706 // pass once we've determined ABI below. 7707 setNativeLibraryPaths(pkg); 7708 7709 // We would never need to extract libs for forward-locked and external packages, 7710 // since the container service will do it for us. We shouldn't attempt to 7711 // extract libs from system app when it was not updated. 7712 if (pkg.isForwardLocked() || isExternal(pkg) || 7713 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7714 extractLibs = false; 7715 } 7716 7717 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7718 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7719 7720 NativeLibraryHelper.Handle handle = null; 7721 try { 7722 handle = NativeLibraryHelper.Handle.create(pkg); 7723 // TODO(multiArch): This can be null for apps that didn't go through the 7724 // usual installation process. We can calculate it again, like we 7725 // do during install time. 7726 // 7727 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7728 // unnecessary. 7729 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7730 7731 // Null out the abis so that they can be recalculated. 7732 pkg.applicationInfo.primaryCpuAbi = null; 7733 pkg.applicationInfo.secondaryCpuAbi = null; 7734 if (isMultiArch(pkg.applicationInfo)) { 7735 // Warn if we've set an abiOverride for multi-lib packages.. 7736 // By definition, we need to copy both 32 and 64 bit libraries for 7737 // such packages. 7738 if (pkg.cpuAbiOverride != null 7739 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7740 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7741 } 7742 7743 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7744 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7745 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7746 if (extractLibs) { 7747 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7748 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7749 useIsaSpecificSubdirs); 7750 } else { 7751 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7752 } 7753 } 7754 7755 maybeThrowExceptionForMultiArchCopy( 7756 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7757 7758 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7759 if (extractLibs) { 7760 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7761 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7762 useIsaSpecificSubdirs); 7763 } else { 7764 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7765 } 7766 } 7767 7768 maybeThrowExceptionForMultiArchCopy( 7769 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7770 7771 if (abi64 >= 0) { 7772 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7773 } 7774 7775 if (abi32 >= 0) { 7776 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7777 if (abi64 >= 0) { 7778 pkg.applicationInfo.secondaryCpuAbi = abi; 7779 } else { 7780 pkg.applicationInfo.primaryCpuAbi = abi; 7781 } 7782 } 7783 } else { 7784 String[] abiList = (cpuAbiOverride != null) ? 7785 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7786 7787 // Enable gross and lame hacks for apps that are built with old 7788 // SDK tools. We must scan their APKs for renderscript bitcode and 7789 // not launch them if it's present. Don't bother checking on devices 7790 // that don't have 64 bit support. 7791 boolean needsRenderScriptOverride = false; 7792 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7793 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7794 abiList = Build.SUPPORTED_32_BIT_ABIS; 7795 needsRenderScriptOverride = true; 7796 } 7797 7798 final int copyRet; 7799 if (extractLibs) { 7800 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7801 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7802 } else { 7803 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7804 } 7805 7806 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7807 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7808 "Error unpackaging native libs for app, errorCode=" + copyRet); 7809 } 7810 7811 if (copyRet >= 0) { 7812 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7813 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7814 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7815 } else if (needsRenderScriptOverride) { 7816 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7817 } 7818 } 7819 } catch (IOException ioe) { 7820 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7821 } finally { 7822 IoUtils.closeQuietly(handle); 7823 } 7824 7825 // Now that we've calculated the ABIs and determined if it's an internal app, 7826 // we will go ahead and populate the nativeLibraryPath. 7827 setNativeLibraryPaths(pkg); 7828 } 7829 7830 /** 7831 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7832 * i.e, so that all packages can be run inside a single process if required. 7833 * 7834 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7835 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7836 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7837 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7838 * updating a package that belongs to a shared user. 7839 * 7840 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7841 * adds unnecessary complexity. 7842 */ 7843 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7844 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7845 String requiredInstructionSet = null; 7846 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7847 requiredInstructionSet = VMRuntime.getInstructionSet( 7848 scannedPackage.applicationInfo.primaryCpuAbi); 7849 } 7850 7851 PackageSetting requirer = null; 7852 for (PackageSetting ps : packagesForUser) { 7853 // If packagesForUser contains scannedPackage, we skip it. This will happen 7854 // when scannedPackage is an update of an existing package. Without this check, 7855 // we will never be able to change the ABI of any package belonging to a shared 7856 // user, even if it's compatible with other packages. 7857 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7858 if (ps.primaryCpuAbiString == null) { 7859 continue; 7860 } 7861 7862 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7863 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7864 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7865 // this but there's not much we can do. 7866 String errorMessage = "Instruction set mismatch, " 7867 + ((requirer == null) ? "[caller]" : requirer) 7868 + " requires " + requiredInstructionSet + " whereas " + ps 7869 + " requires " + instructionSet; 7870 Slog.w(TAG, errorMessage); 7871 } 7872 7873 if (requiredInstructionSet == null) { 7874 requiredInstructionSet = instructionSet; 7875 requirer = ps; 7876 } 7877 } 7878 } 7879 7880 if (requiredInstructionSet != null) { 7881 String adjustedAbi; 7882 if (requirer != null) { 7883 // requirer != null implies that either scannedPackage was null or that scannedPackage 7884 // did not require an ABI, in which case we have to adjust scannedPackage to match 7885 // the ABI of the set (which is the same as requirer's ABI) 7886 adjustedAbi = requirer.primaryCpuAbiString; 7887 if (scannedPackage != null) { 7888 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7889 } 7890 } else { 7891 // requirer == null implies that we're updating all ABIs in the set to 7892 // match scannedPackage. 7893 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7894 } 7895 7896 for (PackageSetting ps : packagesForUser) { 7897 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7898 if (ps.primaryCpuAbiString != null) { 7899 continue; 7900 } 7901 7902 ps.primaryCpuAbiString = adjustedAbi; 7903 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7904 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7905 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7906 7907 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7908 7909 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7910 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7911 7912 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7913 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7914 ps.primaryCpuAbiString = null; 7915 ps.pkg.applicationInfo.primaryCpuAbi = null; 7916 return; 7917 } else { 7918 mInstaller.rmdex(ps.codePathString, 7919 getDexCodeInstructionSet(getPreferredInstructionSet())); 7920 } 7921 } 7922 } 7923 } 7924 } 7925 } 7926 7927 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7928 synchronized (mPackages) { 7929 mResolverReplaced = true; 7930 // Set up information for custom user intent resolution activity. 7931 mResolveActivity.applicationInfo = pkg.applicationInfo; 7932 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7933 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7934 mResolveActivity.processName = pkg.applicationInfo.packageName; 7935 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7936 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7937 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7938 mResolveActivity.theme = 0; 7939 mResolveActivity.exported = true; 7940 mResolveActivity.enabled = true; 7941 mResolveInfo.activityInfo = mResolveActivity; 7942 mResolveInfo.priority = 0; 7943 mResolveInfo.preferredOrder = 0; 7944 mResolveInfo.match = 0; 7945 mResolveComponentName = mCustomResolverComponentName; 7946 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7947 mResolveComponentName); 7948 } 7949 } 7950 7951 private static String calculateBundledApkRoot(final String codePathString) { 7952 final File codePath = new File(codePathString); 7953 final File codeRoot; 7954 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7955 codeRoot = Environment.getRootDirectory(); 7956 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7957 codeRoot = Environment.getOemDirectory(); 7958 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7959 codeRoot = Environment.getVendorDirectory(); 7960 } else { 7961 // Unrecognized code path; take its top real segment as the apk root: 7962 // e.g. /something/app/blah.apk => /something 7963 try { 7964 File f = codePath.getCanonicalFile(); 7965 File parent = f.getParentFile(); // non-null because codePath is a file 7966 File tmp; 7967 while ((tmp = parent.getParentFile()) != null) { 7968 f = parent; 7969 parent = tmp; 7970 } 7971 codeRoot = f; 7972 Slog.w(TAG, "Unrecognized code path " 7973 + codePath + " - using " + codeRoot); 7974 } catch (IOException e) { 7975 // Can't canonicalize the code path -- shenanigans? 7976 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7977 return Environment.getRootDirectory().getPath(); 7978 } 7979 } 7980 return codeRoot.getPath(); 7981 } 7982 7983 /** 7984 * Derive and set the location of native libraries for the given package, 7985 * which varies depending on where and how the package was installed. 7986 */ 7987 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7988 final ApplicationInfo info = pkg.applicationInfo; 7989 final String codePath = pkg.codePath; 7990 final File codeFile = new File(codePath); 7991 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7992 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7993 7994 info.nativeLibraryRootDir = null; 7995 info.nativeLibraryRootRequiresIsa = false; 7996 info.nativeLibraryDir = null; 7997 info.secondaryNativeLibraryDir = null; 7998 7999 if (isApkFile(codeFile)) { 8000 // Monolithic install 8001 if (bundledApp) { 8002 // If "/system/lib64/apkname" exists, assume that is the per-package 8003 // native library directory to use; otherwise use "/system/lib/apkname". 8004 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8005 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8006 getPrimaryInstructionSet(info)); 8007 8008 // This is a bundled system app so choose the path based on the ABI. 8009 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8010 // is just the default path. 8011 final String apkName = deriveCodePathName(codePath); 8012 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8013 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8014 apkName).getAbsolutePath(); 8015 8016 if (info.secondaryCpuAbi != null) { 8017 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8018 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8019 secondaryLibDir, apkName).getAbsolutePath(); 8020 } 8021 } else if (asecApp) { 8022 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8023 .getAbsolutePath(); 8024 } else { 8025 final String apkName = deriveCodePathName(codePath); 8026 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8027 .getAbsolutePath(); 8028 } 8029 8030 info.nativeLibraryRootRequiresIsa = false; 8031 info.nativeLibraryDir = info.nativeLibraryRootDir; 8032 } else { 8033 // Cluster install 8034 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8035 info.nativeLibraryRootRequiresIsa = true; 8036 8037 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8038 getPrimaryInstructionSet(info)).getAbsolutePath(); 8039 8040 if (info.secondaryCpuAbi != null) { 8041 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8042 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8043 } 8044 } 8045 } 8046 8047 /** 8048 * Calculate the abis and roots for a bundled app. These can uniquely 8049 * be determined from the contents of the system partition, i.e whether 8050 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8051 * of this information, and instead assume that the system was built 8052 * sensibly. 8053 */ 8054 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8055 PackageSetting pkgSetting) { 8056 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8057 8058 // If "/system/lib64/apkname" exists, assume that is the per-package 8059 // native library directory to use; otherwise use "/system/lib/apkname". 8060 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8061 setBundledAppAbi(pkg, apkRoot, apkName); 8062 // pkgSetting might be null during rescan following uninstall of updates 8063 // to a bundled app, so accommodate that possibility. The settings in 8064 // that case will be established later from the parsed package. 8065 // 8066 // If the settings aren't null, sync them up with what we've just derived. 8067 // note that apkRoot isn't stored in the package settings. 8068 if (pkgSetting != null) { 8069 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8070 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8071 } 8072 } 8073 8074 /** 8075 * Deduces the ABI of a bundled app and sets the relevant fields on the 8076 * parsed pkg object. 8077 * 8078 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8079 * under which system libraries are installed. 8080 * @param apkName the name of the installed package. 8081 */ 8082 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8083 final File codeFile = new File(pkg.codePath); 8084 8085 final boolean has64BitLibs; 8086 final boolean has32BitLibs; 8087 if (isApkFile(codeFile)) { 8088 // Monolithic install 8089 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8090 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8091 } else { 8092 // Cluster install 8093 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8094 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8095 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8096 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8097 has64BitLibs = (new File(rootDir, isa)).exists(); 8098 } else { 8099 has64BitLibs = false; 8100 } 8101 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8102 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8103 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8104 has32BitLibs = (new File(rootDir, isa)).exists(); 8105 } else { 8106 has32BitLibs = false; 8107 } 8108 } 8109 8110 if (has64BitLibs && !has32BitLibs) { 8111 // The package has 64 bit libs, but not 32 bit libs. Its primary 8112 // ABI should be 64 bit. We can safely assume here that the bundled 8113 // native libraries correspond to the most preferred ABI in the list. 8114 8115 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8116 pkg.applicationInfo.secondaryCpuAbi = null; 8117 } else if (has32BitLibs && !has64BitLibs) { 8118 // The package has 32 bit libs but not 64 bit libs. Its primary 8119 // ABI should be 32 bit. 8120 8121 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8122 pkg.applicationInfo.secondaryCpuAbi = null; 8123 } else if (has32BitLibs && has64BitLibs) { 8124 // The application has both 64 and 32 bit bundled libraries. We check 8125 // here that the app declares multiArch support, and warn if it doesn't. 8126 // 8127 // We will be lenient here and record both ABIs. The primary will be the 8128 // ABI that's higher on the list, i.e, a device that's configured to prefer 8129 // 64 bit apps will see a 64 bit primary ABI, 8130 8131 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8132 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8133 } 8134 8135 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8136 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8137 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8138 } else { 8139 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8140 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8141 } 8142 } else { 8143 pkg.applicationInfo.primaryCpuAbi = null; 8144 pkg.applicationInfo.secondaryCpuAbi = null; 8145 } 8146 } 8147 8148 private void killApplication(String pkgName, int appId, String reason) { 8149 // Request the ActivityManager to kill the process(only for existing packages) 8150 // so that we do not end up in a confused state while the user is still using the older 8151 // version of the application while the new one gets installed. 8152 IActivityManager am = ActivityManagerNative.getDefault(); 8153 if (am != null) { 8154 try { 8155 am.killApplicationWithAppId(pkgName, appId, reason); 8156 } catch (RemoteException e) { 8157 } 8158 } 8159 } 8160 8161 void removePackageLI(PackageSetting ps, boolean chatty) { 8162 if (DEBUG_INSTALL) { 8163 if (chatty) 8164 Log.d(TAG, "Removing package " + ps.name); 8165 } 8166 8167 // writer 8168 synchronized (mPackages) { 8169 mPackages.remove(ps.name); 8170 final PackageParser.Package pkg = ps.pkg; 8171 if (pkg != null) { 8172 cleanPackageDataStructuresLILPw(pkg, chatty); 8173 } 8174 } 8175 } 8176 8177 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8178 if (DEBUG_INSTALL) { 8179 if (chatty) 8180 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8181 } 8182 8183 // writer 8184 synchronized (mPackages) { 8185 mPackages.remove(pkg.applicationInfo.packageName); 8186 cleanPackageDataStructuresLILPw(pkg, chatty); 8187 } 8188 } 8189 8190 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8191 int N = pkg.providers.size(); 8192 StringBuilder r = null; 8193 int i; 8194 for (i=0; i<N; i++) { 8195 PackageParser.Provider p = pkg.providers.get(i); 8196 mProviders.removeProvider(p); 8197 if (p.info.authority == null) { 8198 8199 /* There was another ContentProvider with this authority when 8200 * this app was installed so this authority is null, 8201 * Ignore it as we don't have to unregister the provider. 8202 */ 8203 continue; 8204 } 8205 String names[] = p.info.authority.split(";"); 8206 for (int j = 0; j < names.length; j++) { 8207 if (mProvidersByAuthority.get(names[j]) == p) { 8208 mProvidersByAuthority.remove(names[j]); 8209 if (DEBUG_REMOVE) { 8210 if (chatty) 8211 Log.d(TAG, "Unregistered content provider: " + names[j] 8212 + ", className = " + p.info.name + ", isSyncable = " 8213 + p.info.isSyncable); 8214 } 8215 } 8216 } 8217 if (DEBUG_REMOVE && chatty) { 8218 if (r == null) { 8219 r = new StringBuilder(256); 8220 } else { 8221 r.append(' '); 8222 } 8223 r.append(p.info.name); 8224 } 8225 } 8226 if (r != null) { 8227 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8228 } 8229 8230 N = pkg.services.size(); 8231 r = null; 8232 for (i=0; i<N; i++) { 8233 PackageParser.Service s = pkg.services.get(i); 8234 mServices.removeService(s); 8235 if (chatty) { 8236 if (r == null) { 8237 r = new StringBuilder(256); 8238 } else { 8239 r.append(' '); 8240 } 8241 r.append(s.info.name); 8242 } 8243 } 8244 if (r != null) { 8245 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8246 } 8247 8248 N = pkg.receivers.size(); 8249 r = null; 8250 for (i=0; i<N; i++) { 8251 PackageParser.Activity a = pkg.receivers.get(i); 8252 mReceivers.removeActivity(a, "receiver"); 8253 if (DEBUG_REMOVE && chatty) { 8254 if (r == null) { 8255 r = new StringBuilder(256); 8256 } else { 8257 r.append(' '); 8258 } 8259 r.append(a.info.name); 8260 } 8261 } 8262 if (r != null) { 8263 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8264 } 8265 8266 N = pkg.activities.size(); 8267 r = null; 8268 for (i=0; i<N; i++) { 8269 PackageParser.Activity a = pkg.activities.get(i); 8270 mActivities.removeActivity(a, "activity"); 8271 if (DEBUG_REMOVE && chatty) { 8272 if (r == null) { 8273 r = new StringBuilder(256); 8274 } else { 8275 r.append(' '); 8276 } 8277 r.append(a.info.name); 8278 } 8279 } 8280 if (r != null) { 8281 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8282 } 8283 8284 N = pkg.permissions.size(); 8285 r = null; 8286 for (i=0; i<N; i++) { 8287 PackageParser.Permission p = pkg.permissions.get(i); 8288 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8289 if (bp == null) { 8290 bp = mSettings.mPermissionTrees.get(p.info.name); 8291 } 8292 if (bp != null && bp.perm == p) { 8293 bp.perm = null; 8294 if (DEBUG_REMOVE && chatty) { 8295 if (r == null) { 8296 r = new StringBuilder(256); 8297 } else { 8298 r.append(' '); 8299 } 8300 r.append(p.info.name); 8301 } 8302 } 8303 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8304 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8305 if (appOpPerms != null) { 8306 appOpPerms.remove(pkg.packageName); 8307 } 8308 } 8309 } 8310 if (r != null) { 8311 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8312 } 8313 8314 N = pkg.requestedPermissions.size(); 8315 r = null; 8316 for (i=0; i<N; i++) { 8317 String perm = pkg.requestedPermissions.get(i); 8318 BasePermission bp = mSettings.mPermissions.get(perm); 8319 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8320 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8321 if (appOpPerms != null) { 8322 appOpPerms.remove(pkg.packageName); 8323 if (appOpPerms.isEmpty()) { 8324 mAppOpPermissionPackages.remove(perm); 8325 } 8326 } 8327 } 8328 } 8329 if (r != null) { 8330 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8331 } 8332 8333 N = pkg.instrumentation.size(); 8334 r = null; 8335 for (i=0; i<N; i++) { 8336 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8337 mInstrumentation.remove(a.getComponentName()); 8338 if (DEBUG_REMOVE && chatty) { 8339 if (r == null) { 8340 r = new StringBuilder(256); 8341 } else { 8342 r.append(' '); 8343 } 8344 r.append(a.info.name); 8345 } 8346 } 8347 if (r != null) { 8348 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8349 } 8350 8351 r = null; 8352 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8353 // Only system apps can hold shared libraries. 8354 if (pkg.libraryNames != null) { 8355 for (i=0; i<pkg.libraryNames.size(); i++) { 8356 String name = pkg.libraryNames.get(i); 8357 SharedLibraryEntry cur = mSharedLibraries.get(name); 8358 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8359 mSharedLibraries.remove(name); 8360 if (DEBUG_REMOVE && chatty) { 8361 if (r == null) { 8362 r = new StringBuilder(256); 8363 } else { 8364 r.append(' '); 8365 } 8366 r.append(name); 8367 } 8368 } 8369 } 8370 } 8371 } 8372 if (r != null) { 8373 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8374 } 8375 } 8376 8377 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8378 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8379 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8380 return true; 8381 } 8382 } 8383 return false; 8384 } 8385 8386 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8387 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8388 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8389 8390 private void updatePermissionsLPw(String changingPkg, 8391 PackageParser.Package pkgInfo, int flags) { 8392 // Make sure there are no dangling permission trees. 8393 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8394 while (it.hasNext()) { 8395 final BasePermission bp = it.next(); 8396 if (bp.packageSetting == null) { 8397 // We may not yet have parsed the package, so just see if 8398 // we still know about its settings. 8399 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8400 } 8401 if (bp.packageSetting == null) { 8402 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8403 + " from package " + bp.sourcePackage); 8404 it.remove(); 8405 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8406 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8407 Slog.i(TAG, "Removing old permission tree: " + bp.name 8408 + " from package " + bp.sourcePackage); 8409 flags |= UPDATE_PERMISSIONS_ALL; 8410 it.remove(); 8411 } 8412 } 8413 } 8414 8415 // Make sure all dynamic permissions have been assigned to a package, 8416 // and make sure there are no dangling permissions. 8417 it = mSettings.mPermissions.values().iterator(); 8418 while (it.hasNext()) { 8419 final BasePermission bp = it.next(); 8420 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8421 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8422 + bp.name + " pkg=" + bp.sourcePackage 8423 + " info=" + bp.pendingInfo); 8424 if (bp.packageSetting == null && bp.pendingInfo != null) { 8425 final BasePermission tree = findPermissionTreeLP(bp.name); 8426 if (tree != null && tree.perm != null) { 8427 bp.packageSetting = tree.packageSetting; 8428 bp.perm = new PackageParser.Permission(tree.perm.owner, 8429 new PermissionInfo(bp.pendingInfo)); 8430 bp.perm.info.packageName = tree.perm.info.packageName; 8431 bp.perm.info.name = bp.name; 8432 bp.uid = tree.uid; 8433 } 8434 } 8435 } 8436 if (bp.packageSetting == null) { 8437 // We may not yet have parsed the package, so just see if 8438 // we still know about its settings. 8439 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8440 } 8441 if (bp.packageSetting == null) { 8442 Slog.w(TAG, "Removing dangling permission: " + bp.name 8443 + " from package " + bp.sourcePackage); 8444 it.remove(); 8445 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8446 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8447 Slog.i(TAG, "Removing old permission: " + bp.name 8448 + " from package " + bp.sourcePackage); 8449 flags |= UPDATE_PERMISSIONS_ALL; 8450 it.remove(); 8451 } 8452 } 8453 } 8454 8455 // Now update the permissions for all packages, in particular 8456 // replace the granted permissions of the system packages. 8457 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8458 for (PackageParser.Package pkg : mPackages.values()) { 8459 if (pkg != pkgInfo) { 8460 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8461 changingPkg); 8462 } 8463 } 8464 } 8465 8466 if (pkgInfo != null) { 8467 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8468 } 8469 } 8470 8471 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8472 String packageOfInterest) { 8473 // IMPORTANT: There are two types of permissions: install and runtime. 8474 // Install time permissions are granted when the app is installed to 8475 // all device users and users added in the future. Runtime permissions 8476 // are granted at runtime explicitly to specific users. Normal and signature 8477 // protected permissions are install time permissions. Dangerous permissions 8478 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8479 // otherwise they are runtime permissions. This function does not manage 8480 // runtime permissions except for the case an app targeting Lollipop MR1 8481 // being upgraded to target a newer SDK, in which case dangerous permissions 8482 // are transformed from install time to runtime ones. 8483 8484 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8485 if (ps == null) { 8486 return; 8487 } 8488 8489 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8490 8491 PermissionsState permissionsState = ps.getPermissionsState(); 8492 PermissionsState origPermissions = permissionsState; 8493 8494 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8495 8496 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8497 8498 boolean changedInstallPermission = false; 8499 8500 if (replace) { 8501 ps.installPermissionsFixed = false; 8502 if (!ps.isSharedUser()) { 8503 origPermissions = new PermissionsState(permissionsState); 8504 permissionsState.reset(); 8505 } 8506 } 8507 8508 permissionsState.setGlobalGids(mGlobalGids); 8509 8510 final int N = pkg.requestedPermissions.size(); 8511 for (int i=0; i<N; i++) { 8512 final String name = pkg.requestedPermissions.get(i); 8513 final BasePermission bp = mSettings.mPermissions.get(name); 8514 8515 if (DEBUG_INSTALL) { 8516 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8517 } 8518 8519 if (bp == null || bp.packageSetting == null) { 8520 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8521 Slog.w(TAG, "Unknown permission " + name 8522 + " in package " + pkg.packageName); 8523 } 8524 continue; 8525 } 8526 8527 final String perm = bp.name; 8528 boolean allowedSig = false; 8529 int grant = GRANT_DENIED; 8530 8531 // Keep track of app op permissions. 8532 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8533 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8534 if (pkgs == null) { 8535 pkgs = new ArraySet<>(); 8536 mAppOpPermissionPackages.put(bp.name, pkgs); 8537 } 8538 pkgs.add(pkg.packageName); 8539 } 8540 8541 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8542 switch (level) { 8543 case PermissionInfo.PROTECTION_NORMAL: { 8544 // For all apps normal permissions are install time ones. 8545 grant = GRANT_INSTALL; 8546 } break; 8547 8548 case PermissionInfo.PROTECTION_DANGEROUS: { 8549 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8550 // For legacy apps dangerous permissions are install time ones. 8551 grant = GRANT_INSTALL_LEGACY; 8552 } else if (origPermissions.hasInstallPermission(bp.name)) { 8553 // For legacy apps that became modern, install becomes runtime. 8554 grant = GRANT_UPGRADE; 8555 } else if (mPromoteSystemApps 8556 && isSystemApp(ps) 8557 && mExistingSystemPackages.contains(ps.name)) { 8558 // For legacy system apps, install becomes runtime. 8559 // We cannot check hasInstallPermission() for system apps since those 8560 // permissions were granted implicitly and not persisted pre-M. 8561 grant = GRANT_UPGRADE; 8562 } else { 8563 // For modern apps keep runtime permissions unchanged. 8564 grant = GRANT_RUNTIME; 8565 } 8566 } break; 8567 8568 case PermissionInfo.PROTECTION_SIGNATURE: { 8569 // For all apps signature permissions are install time ones. 8570 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8571 if (allowedSig) { 8572 grant = GRANT_INSTALL; 8573 } 8574 } break; 8575 } 8576 8577 if (DEBUG_INSTALL) { 8578 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8579 } 8580 8581 if (grant != GRANT_DENIED) { 8582 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8583 // If this is an existing, non-system package, then 8584 // we can't add any new permissions to it. 8585 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8586 // Except... if this is a permission that was added 8587 // to the platform (note: need to only do this when 8588 // updating the platform). 8589 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8590 grant = GRANT_DENIED; 8591 } 8592 } 8593 } 8594 8595 switch (grant) { 8596 case GRANT_INSTALL: { 8597 // Revoke this as runtime permission to handle the case of 8598 // a runtime permission being downgraded to an install one. 8599 for (int userId : UserManagerService.getInstance().getUserIds()) { 8600 if (origPermissions.getRuntimePermissionState( 8601 bp.name, userId) != null) { 8602 // Revoke the runtime permission and clear the flags. 8603 origPermissions.revokeRuntimePermission(bp, userId); 8604 origPermissions.updatePermissionFlags(bp, userId, 8605 PackageManager.MASK_PERMISSION_FLAGS, 0); 8606 // If we revoked a permission permission, we have to write. 8607 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8608 changedRuntimePermissionUserIds, userId); 8609 } 8610 } 8611 // Grant an install permission. 8612 if (permissionsState.grantInstallPermission(bp) != 8613 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8614 changedInstallPermission = true; 8615 } 8616 } break; 8617 8618 case GRANT_INSTALL_LEGACY: { 8619 // Grant an install permission. 8620 if (permissionsState.grantInstallPermission(bp) != 8621 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8622 changedInstallPermission = true; 8623 } 8624 } break; 8625 8626 case GRANT_RUNTIME: { 8627 // Grant previously granted runtime permissions. 8628 for (int userId : UserManagerService.getInstance().getUserIds()) { 8629 PermissionState permissionState = origPermissions 8630 .getRuntimePermissionState(bp.name, userId); 8631 final int flags = permissionState != null 8632 ? permissionState.getFlags() : 0; 8633 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8634 if (permissionsState.grantRuntimePermission(bp, userId) == 8635 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8636 // If we cannot put the permission as it was, we have to write. 8637 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8638 changedRuntimePermissionUserIds, userId); 8639 } 8640 } 8641 // Propagate the permission flags. 8642 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8643 } 8644 } break; 8645 8646 case GRANT_UPGRADE: { 8647 // Grant runtime permissions for a previously held install permission. 8648 PermissionState permissionState = origPermissions 8649 .getInstallPermissionState(bp.name); 8650 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8651 8652 if (origPermissions.revokeInstallPermission(bp) 8653 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8654 // We will be transferring the permission flags, so clear them. 8655 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8656 PackageManager.MASK_PERMISSION_FLAGS, 0); 8657 changedInstallPermission = true; 8658 } 8659 8660 // If the permission is not to be promoted to runtime we ignore it and 8661 // also its other flags as they are not applicable to install permissions. 8662 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8663 for (int userId : currentUserIds) { 8664 if (permissionsState.grantRuntimePermission(bp, userId) != 8665 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8666 // Transfer the permission flags. 8667 permissionsState.updatePermissionFlags(bp, userId, 8668 flags, flags); 8669 // If we granted the permission, we have to write. 8670 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8671 changedRuntimePermissionUserIds, userId); 8672 } 8673 } 8674 } 8675 } break; 8676 8677 default: { 8678 if (packageOfInterest == null 8679 || packageOfInterest.equals(pkg.packageName)) { 8680 Slog.w(TAG, "Not granting permission " + perm 8681 + " to package " + pkg.packageName 8682 + " because it was previously installed without"); 8683 } 8684 } break; 8685 } 8686 } else { 8687 if (permissionsState.revokeInstallPermission(bp) != 8688 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8689 // Also drop the permission flags. 8690 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8691 PackageManager.MASK_PERMISSION_FLAGS, 0); 8692 changedInstallPermission = true; 8693 Slog.i(TAG, "Un-granting permission " + perm 8694 + " from package " + pkg.packageName 8695 + " (protectionLevel=" + bp.protectionLevel 8696 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8697 + ")"); 8698 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8699 // Don't print warning for app op permissions, since it is fine for them 8700 // not to be granted, there is a UI for the user to decide. 8701 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8702 Slog.w(TAG, "Not granting permission " + perm 8703 + " to package " + pkg.packageName 8704 + " (protectionLevel=" + bp.protectionLevel 8705 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8706 + ")"); 8707 } 8708 } 8709 } 8710 } 8711 8712 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8713 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8714 // This is the first that we have heard about this package, so the 8715 // permissions we have now selected are fixed until explicitly 8716 // changed. 8717 ps.installPermissionsFixed = true; 8718 } 8719 8720 // Persist the runtime permissions state for users with changes. 8721 for (int userId : changedRuntimePermissionUserIds) { 8722 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8723 } 8724 8725 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8726 } 8727 8728 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8729 boolean allowed = false; 8730 final int NP = PackageParser.NEW_PERMISSIONS.length; 8731 for (int ip=0; ip<NP; ip++) { 8732 final PackageParser.NewPermissionInfo npi 8733 = PackageParser.NEW_PERMISSIONS[ip]; 8734 if (npi.name.equals(perm) 8735 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8736 allowed = true; 8737 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8738 + pkg.packageName); 8739 break; 8740 } 8741 } 8742 return allowed; 8743 } 8744 8745 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8746 BasePermission bp, PermissionsState origPermissions) { 8747 boolean allowed; 8748 allowed = (compareSignatures( 8749 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8750 == PackageManager.SIGNATURE_MATCH) 8751 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8752 == PackageManager.SIGNATURE_MATCH); 8753 if (!allowed && (bp.protectionLevel 8754 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8755 if (isSystemApp(pkg)) { 8756 // For updated system applications, a system permission 8757 // is granted only if it had been defined by the original application. 8758 if (pkg.isUpdatedSystemApp()) { 8759 final PackageSetting sysPs = mSettings 8760 .getDisabledSystemPkgLPr(pkg.packageName); 8761 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8762 // If the original was granted this permission, we take 8763 // that grant decision as read and propagate it to the 8764 // update. 8765 if (sysPs.isPrivileged()) { 8766 allowed = true; 8767 } 8768 } else { 8769 // The system apk may have been updated with an older 8770 // version of the one on the data partition, but which 8771 // granted a new system permission that it didn't have 8772 // before. In this case we do want to allow the app to 8773 // now get the new permission if the ancestral apk is 8774 // privileged to get it. 8775 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8776 for (int j=0; 8777 j<sysPs.pkg.requestedPermissions.size(); j++) { 8778 if (perm.equals( 8779 sysPs.pkg.requestedPermissions.get(j))) { 8780 allowed = true; 8781 break; 8782 } 8783 } 8784 } 8785 } 8786 } else { 8787 allowed = isPrivilegedApp(pkg); 8788 } 8789 } 8790 } 8791 if (!allowed) { 8792 if (!allowed && (bp.protectionLevel 8793 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8794 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8795 // If this was a previously normal/dangerous permission that got moved 8796 // to a system permission as part of the runtime permission redesign, then 8797 // we still want to blindly grant it to old apps. 8798 allowed = true; 8799 } 8800 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8801 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8802 // If this permission is to be granted to the system installer and 8803 // this app is an installer, then it gets the permission. 8804 allowed = true; 8805 } 8806 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8807 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8808 // If this permission is to be granted to the system verifier and 8809 // this app is a verifier, then it gets the permission. 8810 allowed = true; 8811 } 8812 if (!allowed && (bp.protectionLevel 8813 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8814 && isSystemApp(pkg)) { 8815 // Any pre-installed system app is allowed to get this permission. 8816 allowed = true; 8817 } 8818 if (!allowed && (bp.protectionLevel 8819 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8820 // For development permissions, a development permission 8821 // is granted only if it was already granted. 8822 allowed = origPermissions.hasInstallPermission(perm); 8823 } 8824 } 8825 return allowed; 8826 } 8827 8828 final class ActivityIntentResolver 8829 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8830 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8831 boolean defaultOnly, int userId) { 8832 if (!sUserManager.exists(userId)) return null; 8833 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8834 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8835 } 8836 8837 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8838 int userId) { 8839 if (!sUserManager.exists(userId)) return null; 8840 mFlags = flags; 8841 return super.queryIntent(intent, resolvedType, 8842 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8843 } 8844 8845 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8846 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8847 if (!sUserManager.exists(userId)) return null; 8848 if (packageActivities == null) { 8849 return null; 8850 } 8851 mFlags = flags; 8852 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8853 final int N = packageActivities.size(); 8854 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8855 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8856 8857 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8858 for (int i = 0; i < N; ++i) { 8859 intentFilters = packageActivities.get(i).intents; 8860 if (intentFilters != null && intentFilters.size() > 0) { 8861 PackageParser.ActivityIntentInfo[] array = 8862 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8863 intentFilters.toArray(array); 8864 listCut.add(array); 8865 } 8866 } 8867 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8868 } 8869 8870 public final void addActivity(PackageParser.Activity a, String type) { 8871 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8872 mActivities.put(a.getComponentName(), a); 8873 if (DEBUG_SHOW_INFO) 8874 Log.v( 8875 TAG, " " + type + " " + 8876 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8877 if (DEBUG_SHOW_INFO) 8878 Log.v(TAG, " Class=" + a.info.name); 8879 final int NI = a.intents.size(); 8880 for (int j=0; j<NI; j++) { 8881 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8882 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8883 intent.setPriority(0); 8884 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8885 + a.className + " with priority > 0, forcing to 0"); 8886 } 8887 if (DEBUG_SHOW_INFO) { 8888 Log.v(TAG, " IntentFilter:"); 8889 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8890 } 8891 if (!intent.debugCheck()) { 8892 Log.w(TAG, "==> For Activity " + a.info.name); 8893 } 8894 addFilter(intent); 8895 } 8896 } 8897 8898 public final void removeActivity(PackageParser.Activity a, String type) { 8899 mActivities.remove(a.getComponentName()); 8900 if (DEBUG_SHOW_INFO) { 8901 Log.v(TAG, " " + type + " " 8902 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8903 : a.info.name) + ":"); 8904 Log.v(TAG, " Class=" + a.info.name); 8905 } 8906 final int NI = a.intents.size(); 8907 for (int j=0; j<NI; j++) { 8908 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8909 if (DEBUG_SHOW_INFO) { 8910 Log.v(TAG, " IntentFilter:"); 8911 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8912 } 8913 removeFilter(intent); 8914 } 8915 } 8916 8917 @Override 8918 protected boolean allowFilterResult( 8919 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8920 ActivityInfo filterAi = filter.activity.info; 8921 for (int i=dest.size()-1; i>=0; i--) { 8922 ActivityInfo destAi = dest.get(i).activityInfo; 8923 if (destAi.name == filterAi.name 8924 && destAi.packageName == filterAi.packageName) { 8925 return false; 8926 } 8927 } 8928 return true; 8929 } 8930 8931 @Override 8932 protected ActivityIntentInfo[] newArray(int size) { 8933 return new ActivityIntentInfo[size]; 8934 } 8935 8936 @Override 8937 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8938 if (!sUserManager.exists(userId)) return true; 8939 PackageParser.Package p = filter.activity.owner; 8940 if (p != null) { 8941 PackageSetting ps = (PackageSetting)p.mExtras; 8942 if (ps != null) { 8943 // System apps are never considered stopped for purposes of 8944 // filtering, because there may be no way for the user to 8945 // actually re-launch them. 8946 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8947 && ps.getStopped(userId); 8948 } 8949 } 8950 return false; 8951 } 8952 8953 @Override 8954 protected boolean isPackageForFilter(String packageName, 8955 PackageParser.ActivityIntentInfo info) { 8956 return packageName.equals(info.activity.owner.packageName); 8957 } 8958 8959 @Override 8960 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8961 int match, int userId) { 8962 if (!sUserManager.exists(userId)) return null; 8963 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8964 return null; 8965 } 8966 final PackageParser.Activity activity = info.activity; 8967 if (mSafeMode && (activity.info.applicationInfo.flags 8968 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8969 return null; 8970 } 8971 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8972 if (ps == null) { 8973 return null; 8974 } 8975 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8976 ps.readUserState(userId), userId); 8977 if (ai == null) { 8978 return null; 8979 } 8980 final ResolveInfo res = new ResolveInfo(); 8981 res.activityInfo = ai; 8982 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8983 res.filter = info; 8984 } 8985 if (info != null) { 8986 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8987 } 8988 res.priority = info.getPriority(); 8989 res.preferredOrder = activity.owner.mPreferredOrder; 8990 //System.out.println("Result: " + res.activityInfo.className + 8991 // " = " + res.priority); 8992 res.match = match; 8993 res.isDefault = info.hasDefault; 8994 res.labelRes = info.labelRes; 8995 res.nonLocalizedLabel = info.nonLocalizedLabel; 8996 if (userNeedsBadging(userId)) { 8997 res.noResourceId = true; 8998 } else { 8999 res.icon = info.icon; 9000 } 9001 res.iconResourceId = info.icon; 9002 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9003 return res; 9004 } 9005 9006 @Override 9007 protected void sortResults(List<ResolveInfo> results) { 9008 Collections.sort(results, mResolvePrioritySorter); 9009 } 9010 9011 @Override 9012 protected void dumpFilter(PrintWriter out, String prefix, 9013 PackageParser.ActivityIntentInfo filter) { 9014 out.print(prefix); out.print( 9015 Integer.toHexString(System.identityHashCode(filter.activity))); 9016 out.print(' '); 9017 filter.activity.printComponentShortName(out); 9018 out.print(" filter "); 9019 out.println(Integer.toHexString(System.identityHashCode(filter))); 9020 } 9021 9022 @Override 9023 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9024 return filter.activity; 9025 } 9026 9027 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9028 PackageParser.Activity activity = (PackageParser.Activity)label; 9029 out.print(prefix); out.print( 9030 Integer.toHexString(System.identityHashCode(activity))); 9031 out.print(' '); 9032 activity.printComponentShortName(out); 9033 if (count > 1) { 9034 out.print(" ("); out.print(count); out.print(" filters)"); 9035 } 9036 out.println(); 9037 } 9038 9039// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9040// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9041// final List<ResolveInfo> retList = Lists.newArrayList(); 9042// while (i.hasNext()) { 9043// final ResolveInfo resolveInfo = i.next(); 9044// if (isEnabledLP(resolveInfo.activityInfo)) { 9045// retList.add(resolveInfo); 9046// } 9047// } 9048// return retList; 9049// } 9050 9051 // Keys are String (activity class name), values are Activity. 9052 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9053 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9054 private int mFlags; 9055 } 9056 9057 private final class ServiceIntentResolver 9058 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9059 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9060 boolean defaultOnly, int userId) { 9061 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9062 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9063 } 9064 9065 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9066 int userId) { 9067 if (!sUserManager.exists(userId)) return null; 9068 mFlags = flags; 9069 return super.queryIntent(intent, resolvedType, 9070 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9071 } 9072 9073 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9074 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9075 if (!sUserManager.exists(userId)) return null; 9076 if (packageServices == null) { 9077 return null; 9078 } 9079 mFlags = flags; 9080 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9081 final int N = packageServices.size(); 9082 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9083 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9084 9085 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9086 for (int i = 0; i < N; ++i) { 9087 intentFilters = packageServices.get(i).intents; 9088 if (intentFilters != null && intentFilters.size() > 0) { 9089 PackageParser.ServiceIntentInfo[] array = 9090 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9091 intentFilters.toArray(array); 9092 listCut.add(array); 9093 } 9094 } 9095 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9096 } 9097 9098 public final void addService(PackageParser.Service s) { 9099 mServices.put(s.getComponentName(), s); 9100 if (DEBUG_SHOW_INFO) { 9101 Log.v(TAG, " " 9102 + (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 if (!intent.debugCheck()) { 9115 Log.w(TAG, "==> For Service " + s.info.name); 9116 } 9117 addFilter(intent); 9118 } 9119 } 9120 9121 public final void removeService(PackageParser.Service s) { 9122 mServices.remove(s.getComponentName()); 9123 if (DEBUG_SHOW_INFO) { 9124 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9125 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9126 Log.v(TAG, " Class=" + s.info.name); 9127 } 9128 final int NI = s.intents.size(); 9129 int j; 9130 for (j=0; j<NI; j++) { 9131 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9132 if (DEBUG_SHOW_INFO) { 9133 Log.v(TAG, " IntentFilter:"); 9134 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9135 } 9136 removeFilter(intent); 9137 } 9138 } 9139 9140 @Override 9141 protected boolean allowFilterResult( 9142 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9143 ServiceInfo filterSi = filter.service.info; 9144 for (int i=dest.size()-1; i>=0; i--) { 9145 ServiceInfo destAi = dest.get(i).serviceInfo; 9146 if (destAi.name == filterSi.name 9147 && destAi.packageName == filterSi.packageName) { 9148 return false; 9149 } 9150 } 9151 return true; 9152 } 9153 9154 @Override 9155 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9156 return new PackageParser.ServiceIntentInfo[size]; 9157 } 9158 9159 @Override 9160 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9161 if (!sUserManager.exists(userId)) return true; 9162 PackageParser.Package p = filter.service.owner; 9163 if (p != null) { 9164 PackageSetting ps = (PackageSetting)p.mExtras; 9165 if (ps != null) { 9166 // System apps are never considered stopped for purposes of 9167 // filtering, because there may be no way for the user to 9168 // actually re-launch them. 9169 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9170 && ps.getStopped(userId); 9171 } 9172 } 9173 return false; 9174 } 9175 9176 @Override 9177 protected boolean isPackageForFilter(String packageName, 9178 PackageParser.ServiceIntentInfo info) { 9179 return packageName.equals(info.service.owner.packageName); 9180 } 9181 9182 @Override 9183 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9184 int match, int userId) { 9185 if (!sUserManager.exists(userId)) return null; 9186 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9187 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9188 return null; 9189 } 9190 final PackageParser.Service service = info.service; 9191 if (mSafeMode && (service.info.applicationInfo.flags 9192 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9193 return null; 9194 } 9195 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9196 if (ps == null) { 9197 return null; 9198 } 9199 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9200 ps.readUserState(userId), userId); 9201 if (si == null) { 9202 return null; 9203 } 9204 final ResolveInfo res = new ResolveInfo(); 9205 res.serviceInfo = si; 9206 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9207 res.filter = filter; 9208 } 9209 res.priority = info.getPriority(); 9210 res.preferredOrder = service.owner.mPreferredOrder; 9211 res.match = match; 9212 res.isDefault = info.hasDefault; 9213 res.labelRes = info.labelRes; 9214 res.nonLocalizedLabel = info.nonLocalizedLabel; 9215 res.icon = info.icon; 9216 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9217 return res; 9218 } 9219 9220 @Override 9221 protected void sortResults(List<ResolveInfo> results) { 9222 Collections.sort(results, mResolvePrioritySorter); 9223 } 9224 9225 @Override 9226 protected void dumpFilter(PrintWriter out, String prefix, 9227 PackageParser.ServiceIntentInfo filter) { 9228 out.print(prefix); out.print( 9229 Integer.toHexString(System.identityHashCode(filter.service))); 9230 out.print(' '); 9231 filter.service.printComponentShortName(out); 9232 out.print(" filter "); 9233 out.println(Integer.toHexString(System.identityHashCode(filter))); 9234 } 9235 9236 @Override 9237 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9238 return filter.service; 9239 } 9240 9241 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9242 PackageParser.Service service = (PackageParser.Service)label; 9243 out.print(prefix); out.print( 9244 Integer.toHexString(System.identityHashCode(service))); 9245 out.print(' '); 9246 service.printComponentShortName(out); 9247 if (count > 1) { 9248 out.print(" ("); out.print(count); out.print(" filters)"); 9249 } 9250 out.println(); 9251 } 9252 9253// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9254// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9255// final List<ResolveInfo> retList = Lists.newArrayList(); 9256// while (i.hasNext()) { 9257// final ResolveInfo resolveInfo = (ResolveInfo) i; 9258// if (isEnabledLP(resolveInfo.serviceInfo)) { 9259// retList.add(resolveInfo); 9260// } 9261// } 9262// return retList; 9263// } 9264 9265 // Keys are String (activity class name), values are Activity. 9266 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9267 = new ArrayMap<ComponentName, PackageParser.Service>(); 9268 private int mFlags; 9269 }; 9270 9271 private final class ProviderIntentResolver 9272 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9273 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9274 boolean defaultOnly, int userId) { 9275 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9276 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9277 } 9278 9279 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9280 int userId) { 9281 if (!sUserManager.exists(userId)) 9282 return null; 9283 mFlags = flags; 9284 return super.queryIntent(intent, resolvedType, 9285 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9286 } 9287 9288 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9289 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9290 if (!sUserManager.exists(userId)) 9291 return null; 9292 if (packageProviders == null) { 9293 return null; 9294 } 9295 mFlags = flags; 9296 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9297 final int N = packageProviders.size(); 9298 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9299 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9300 9301 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9302 for (int i = 0; i < N; ++i) { 9303 intentFilters = packageProviders.get(i).intents; 9304 if (intentFilters != null && intentFilters.size() > 0) { 9305 PackageParser.ProviderIntentInfo[] array = 9306 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9307 intentFilters.toArray(array); 9308 listCut.add(array); 9309 } 9310 } 9311 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9312 } 9313 9314 public final void addProvider(PackageParser.Provider p) { 9315 if (mProviders.containsKey(p.getComponentName())) { 9316 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9317 return; 9318 } 9319 9320 mProviders.put(p.getComponentName(), p); 9321 if (DEBUG_SHOW_INFO) { 9322 Log.v(TAG, " " 9323 + (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 if (!intent.debugCheck()) { 9336 Log.w(TAG, "==> For Provider " + p.info.name); 9337 } 9338 addFilter(intent); 9339 } 9340 } 9341 9342 public final void removeProvider(PackageParser.Provider p) { 9343 mProviders.remove(p.getComponentName()); 9344 if (DEBUG_SHOW_INFO) { 9345 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9346 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9347 Log.v(TAG, " Class=" + p.info.name); 9348 } 9349 final int NI = p.intents.size(); 9350 int j; 9351 for (j = 0; j < NI; j++) { 9352 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9353 if (DEBUG_SHOW_INFO) { 9354 Log.v(TAG, " IntentFilter:"); 9355 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9356 } 9357 removeFilter(intent); 9358 } 9359 } 9360 9361 @Override 9362 protected boolean allowFilterResult( 9363 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9364 ProviderInfo filterPi = filter.provider.info; 9365 for (int i = dest.size() - 1; i >= 0; i--) { 9366 ProviderInfo destPi = dest.get(i).providerInfo; 9367 if (destPi.name == filterPi.name 9368 && destPi.packageName == filterPi.packageName) { 9369 return false; 9370 } 9371 } 9372 return true; 9373 } 9374 9375 @Override 9376 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9377 return new PackageParser.ProviderIntentInfo[size]; 9378 } 9379 9380 @Override 9381 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9382 if (!sUserManager.exists(userId)) 9383 return true; 9384 PackageParser.Package p = filter.provider.owner; 9385 if (p != null) { 9386 PackageSetting ps = (PackageSetting) p.mExtras; 9387 if (ps != null) { 9388 // System apps are never considered stopped for purposes of 9389 // filtering, because there may be no way for the user to 9390 // actually re-launch them. 9391 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9392 && ps.getStopped(userId); 9393 } 9394 } 9395 return false; 9396 } 9397 9398 @Override 9399 protected boolean isPackageForFilter(String packageName, 9400 PackageParser.ProviderIntentInfo info) { 9401 return packageName.equals(info.provider.owner.packageName); 9402 } 9403 9404 @Override 9405 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9406 int match, int userId) { 9407 if (!sUserManager.exists(userId)) 9408 return null; 9409 final PackageParser.ProviderIntentInfo info = filter; 9410 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9411 return null; 9412 } 9413 final PackageParser.Provider provider = info.provider; 9414 if (mSafeMode && (provider.info.applicationInfo.flags 9415 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9416 return null; 9417 } 9418 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9419 if (ps == null) { 9420 return null; 9421 } 9422 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9423 ps.readUserState(userId), userId); 9424 if (pi == null) { 9425 return null; 9426 } 9427 final ResolveInfo res = new ResolveInfo(); 9428 res.providerInfo = pi; 9429 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9430 res.filter = filter; 9431 } 9432 res.priority = info.getPriority(); 9433 res.preferredOrder = provider.owner.mPreferredOrder; 9434 res.match = match; 9435 res.isDefault = info.hasDefault; 9436 res.labelRes = info.labelRes; 9437 res.nonLocalizedLabel = info.nonLocalizedLabel; 9438 res.icon = info.icon; 9439 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9440 return res; 9441 } 9442 9443 @Override 9444 protected void sortResults(List<ResolveInfo> results) { 9445 Collections.sort(results, mResolvePrioritySorter); 9446 } 9447 9448 @Override 9449 protected void dumpFilter(PrintWriter out, String prefix, 9450 PackageParser.ProviderIntentInfo filter) { 9451 out.print(prefix); 9452 out.print( 9453 Integer.toHexString(System.identityHashCode(filter.provider))); 9454 out.print(' '); 9455 filter.provider.printComponentShortName(out); 9456 out.print(" filter "); 9457 out.println(Integer.toHexString(System.identityHashCode(filter))); 9458 } 9459 9460 @Override 9461 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9462 return filter.provider; 9463 } 9464 9465 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9466 PackageParser.Provider provider = (PackageParser.Provider)label; 9467 out.print(prefix); out.print( 9468 Integer.toHexString(System.identityHashCode(provider))); 9469 out.print(' '); 9470 provider.printComponentShortName(out); 9471 if (count > 1) { 9472 out.print(" ("); out.print(count); out.print(" filters)"); 9473 } 9474 out.println(); 9475 } 9476 9477 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9478 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9479 private int mFlags; 9480 }; 9481 9482 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9483 new Comparator<ResolveInfo>() { 9484 public int compare(ResolveInfo r1, ResolveInfo r2) { 9485 int v1 = r1.priority; 9486 int v2 = r2.priority; 9487 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9488 if (v1 != v2) { 9489 return (v1 > v2) ? -1 : 1; 9490 } 9491 v1 = r1.preferredOrder; 9492 v2 = r2.preferredOrder; 9493 if (v1 != v2) { 9494 return (v1 > v2) ? -1 : 1; 9495 } 9496 if (r1.isDefault != r2.isDefault) { 9497 return r1.isDefault ? -1 : 1; 9498 } 9499 v1 = r1.match; 9500 v2 = r2.match; 9501 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9502 if (v1 != v2) { 9503 return (v1 > v2) ? -1 : 1; 9504 } 9505 if (r1.system != r2.system) { 9506 return r1.system ? -1 : 1; 9507 } 9508 return 0; 9509 } 9510 }; 9511 9512 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9513 new Comparator<ProviderInfo>() { 9514 public int compare(ProviderInfo p1, ProviderInfo p2) { 9515 final int v1 = p1.initOrder; 9516 final int v2 = p2.initOrder; 9517 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9518 } 9519 }; 9520 9521 final void sendPackageBroadcast(final String action, final String pkg, 9522 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9523 final int[] userIds) { 9524 mHandler.post(new Runnable() { 9525 @Override 9526 public void run() { 9527 try { 9528 final IActivityManager am = ActivityManagerNative.getDefault(); 9529 if (am == null) return; 9530 final int[] resolvedUserIds; 9531 if (userIds == null) { 9532 resolvedUserIds = am.getRunningUserIds(); 9533 } else { 9534 resolvedUserIds = userIds; 9535 } 9536 for (int id : resolvedUserIds) { 9537 final Intent intent = new Intent(action, 9538 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9539 if (extras != null) { 9540 intent.putExtras(extras); 9541 } 9542 if (targetPkg != null) { 9543 intent.setPackage(targetPkg); 9544 } 9545 // Modify the UID when posting to other users 9546 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9547 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9548 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9549 intent.putExtra(Intent.EXTRA_UID, uid); 9550 } 9551 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9552 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9553 if (DEBUG_BROADCASTS) { 9554 RuntimeException here = new RuntimeException("here"); 9555 here.fillInStackTrace(); 9556 Slog.d(TAG, "Sending to user " + id + ": " 9557 + intent.toShortString(false, true, false, false) 9558 + " " + intent.getExtras(), here); 9559 } 9560 am.broadcastIntent(null, intent, null, finishedReceiver, 9561 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9562 null, finishedReceiver != null, false, id); 9563 } 9564 } catch (RemoteException ex) { 9565 } 9566 } 9567 }); 9568 } 9569 9570 /** 9571 * Check if the external storage media is available. This is true if there 9572 * is a mounted external storage medium or if the external storage is 9573 * emulated. 9574 */ 9575 private boolean isExternalMediaAvailable() { 9576 return mMediaMounted || Environment.isExternalStorageEmulated(); 9577 } 9578 9579 @Override 9580 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9581 // writer 9582 synchronized (mPackages) { 9583 if (!isExternalMediaAvailable()) { 9584 // If the external storage is no longer mounted at this point, 9585 // the caller may not have been able to delete all of this 9586 // packages files and can not delete any more. Bail. 9587 return null; 9588 } 9589 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9590 if (lastPackage != null) { 9591 pkgs.remove(lastPackage); 9592 } 9593 if (pkgs.size() > 0) { 9594 return pkgs.get(0); 9595 } 9596 } 9597 return null; 9598 } 9599 9600 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9601 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9602 userId, andCode ? 1 : 0, packageName); 9603 if (mSystemReady) { 9604 msg.sendToTarget(); 9605 } else { 9606 if (mPostSystemReadyMessages == null) { 9607 mPostSystemReadyMessages = new ArrayList<>(); 9608 } 9609 mPostSystemReadyMessages.add(msg); 9610 } 9611 } 9612 9613 void startCleaningPackages() { 9614 // reader 9615 synchronized (mPackages) { 9616 if (!isExternalMediaAvailable()) { 9617 return; 9618 } 9619 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9620 return; 9621 } 9622 } 9623 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9624 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9625 IActivityManager am = ActivityManagerNative.getDefault(); 9626 if (am != null) { 9627 try { 9628 am.startService(null, intent, null, mContext.getOpPackageName(), 9629 UserHandle.USER_OWNER); 9630 } catch (RemoteException e) { 9631 } 9632 } 9633 } 9634 9635 @Override 9636 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9637 int installFlags, String installerPackageName, VerificationParams verificationParams, 9638 String packageAbiOverride) { 9639 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9640 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9641 } 9642 9643 @Override 9644 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9645 int installFlags, String installerPackageName, VerificationParams verificationParams, 9646 String packageAbiOverride, int userId) { 9647 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9648 9649 final int callingUid = Binder.getCallingUid(); 9650 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9651 9652 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9653 try { 9654 if (observer != null) { 9655 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9656 } 9657 } catch (RemoteException re) { 9658 } 9659 return; 9660 } 9661 9662 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9663 installFlags |= PackageManager.INSTALL_FROM_ADB; 9664 9665 } else { 9666 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9667 // about installerPackageName. 9668 9669 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9670 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9671 } 9672 9673 UserHandle user; 9674 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9675 user = UserHandle.ALL; 9676 } else { 9677 user = new UserHandle(userId); 9678 } 9679 9680 // Only system components can circumvent runtime permissions when installing. 9681 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9682 && mContext.checkCallingOrSelfPermission(Manifest.permission 9683 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9684 throw new SecurityException("You need the " 9685 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9686 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9687 } 9688 9689 verificationParams.setInstallerUid(callingUid); 9690 9691 final File originFile = new File(originPath); 9692 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9693 9694 final Message msg = mHandler.obtainMessage(INIT_COPY); 9695 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9696 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9697 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9698 msg.obj = params; 9699 9700 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9701 System.identityHashCode(msg.obj)); 9702 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9703 System.identityHashCode(msg.obj)); 9704 9705 mHandler.sendMessage(msg); 9706 } 9707 9708 void installStage(String packageName, File stagedDir, String stagedCid, 9709 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9710 String installerPackageName, int installerUid, UserHandle user) { 9711 final VerificationParams verifParams = new VerificationParams( 9712 null, sessionParams.originatingUri, sessionParams.referrerUri, installerUid, null); 9713 verifParams.setInstallerUid(installerUid); 9714 9715 final OriginInfo origin; 9716 if (stagedDir != null) { 9717 origin = OriginInfo.fromStagedFile(stagedDir); 9718 } else { 9719 origin = OriginInfo.fromStagedContainer(stagedCid); 9720 } 9721 9722 final Message msg = mHandler.obtainMessage(INIT_COPY); 9723 final InstallParams params = new InstallParams(origin, null, observer, 9724 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9725 verifParams, user, sessionParams.abiOverride, 9726 sessionParams.grantedRuntimePermissions); 9727 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9728 msg.obj = params; 9729 9730 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9731 System.identityHashCode(msg.obj)); 9732 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9733 System.identityHashCode(msg.obj)); 9734 9735 mHandler.sendMessage(msg); 9736 } 9737 9738 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9739 Bundle extras = new Bundle(1); 9740 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9741 9742 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9743 packageName, extras, null, null, new int[] {userId}); 9744 try { 9745 IActivityManager am = ActivityManagerNative.getDefault(); 9746 final boolean isSystem = 9747 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9748 if (isSystem && am.isUserRunning(userId, false)) { 9749 // The just-installed/enabled app is bundled on the system, so presumed 9750 // to be able to run automatically without needing an explicit launch. 9751 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9752 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9753 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9754 .setPackage(packageName); 9755 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9756 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9757 } 9758 } catch (RemoteException e) { 9759 // shouldn't happen 9760 Slog.w(TAG, "Unable to bootstrap installed package", e); 9761 } 9762 } 9763 9764 @Override 9765 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9766 int userId) { 9767 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9768 PackageSetting pkgSetting; 9769 final int uid = Binder.getCallingUid(); 9770 enforceCrossUserPermission(uid, userId, true, true, 9771 "setApplicationHiddenSetting for user " + userId); 9772 9773 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9774 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9775 return false; 9776 } 9777 9778 long callingId = Binder.clearCallingIdentity(); 9779 try { 9780 boolean sendAdded = false; 9781 boolean sendRemoved = false; 9782 // writer 9783 synchronized (mPackages) { 9784 pkgSetting = mSettings.mPackages.get(packageName); 9785 if (pkgSetting == null) { 9786 return false; 9787 } 9788 if (pkgSetting.getHidden(userId) != hidden) { 9789 pkgSetting.setHidden(hidden, userId); 9790 mSettings.writePackageRestrictionsLPr(userId); 9791 if (hidden) { 9792 sendRemoved = true; 9793 } else { 9794 sendAdded = true; 9795 } 9796 } 9797 } 9798 if (sendAdded) { 9799 sendPackageAddedForUser(packageName, pkgSetting, userId); 9800 return true; 9801 } 9802 if (sendRemoved) { 9803 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9804 "hiding pkg"); 9805 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9806 return true; 9807 } 9808 } finally { 9809 Binder.restoreCallingIdentity(callingId); 9810 } 9811 return false; 9812 } 9813 9814 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9815 int userId) { 9816 final PackageRemovedInfo info = new PackageRemovedInfo(); 9817 info.removedPackage = packageName; 9818 info.removedUsers = new int[] {userId}; 9819 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9820 info.sendBroadcast(false, false, false); 9821 } 9822 9823 /** 9824 * Returns true if application is not found or there was an error. Otherwise it returns 9825 * the hidden state of the package for the given user. 9826 */ 9827 @Override 9828 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9829 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9830 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9831 false, "getApplicationHidden for user " + userId); 9832 PackageSetting pkgSetting; 9833 long callingId = Binder.clearCallingIdentity(); 9834 try { 9835 // writer 9836 synchronized (mPackages) { 9837 pkgSetting = mSettings.mPackages.get(packageName); 9838 if (pkgSetting == null) { 9839 return true; 9840 } 9841 return pkgSetting.getHidden(userId); 9842 } 9843 } finally { 9844 Binder.restoreCallingIdentity(callingId); 9845 } 9846 } 9847 9848 /** 9849 * @hide 9850 */ 9851 @Override 9852 public int installExistingPackageAsUser(String packageName, int userId) { 9853 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9854 null); 9855 PackageSetting pkgSetting; 9856 final int uid = Binder.getCallingUid(); 9857 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9858 + userId); 9859 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9860 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9861 } 9862 9863 long callingId = Binder.clearCallingIdentity(); 9864 try { 9865 boolean sendAdded = false; 9866 9867 // writer 9868 synchronized (mPackages) { 9869 pkgSetting = mSettings.mPackages.get(packageName); 9870 if (pkgSetting == null) { 9871 return PackageManager.INSTALL_FAILED_INVALID_URI; 9872 } 9873 if (!pkgSetting.getInstalled(userId)) { 9874 pkgSetting.setInstalled(true, userId); 9875 pkgSetting.setHidden(false, userId); 9876 mSettings.writePackageRestrictionsLPr(userId); 9877 sendAdded = true; 9878 } 9879 } 9880 9881 if (sendAdded) { 9882 sendPackageAddedForUser(packageName, pkgSetting, userId); 9883 } 9884 } finally { 9885 Binder.restoreCallingIdentity(callingId); 9886 } 9887 9888 return PackageManager.INSTALL_SUCCEEDED; 9889 } 9890 9891 boolean isUserRestricted(int userId, String restrictionKey) { 9892 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9893 if (restrictions.getBoolean(restrictionKey, false)) { 9894 Log.w(TAG, "User is restricted: " + restrictionKey); 9895 return true; 9896 } 9897 return false; 9898 } 9899 9900 @Override 9901 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9902 mContext.enforceCallingOrSelfPermission( 9903 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9904 "Only package verification agents can verify applications"); 9905 9906 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9907 final PackageVerificationResponse response = new PackageVerificationResponse( 9908 verificationCode, Binder.getCallingUid()); 9909 msg.arg1 = id; 9910 msg.obj = response; 9911 mHandler.sendMessage(msg); 9912 } 9913 9914 @Override 9915 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9916 long millisecondsToDelay) { 9917 mContext.enforceCallingOrSelfPermission( 9918 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9919 "Only package verification agents can extend verification timeouts"); 9920 9921 final PackageVerificationState state = mPendingVerification.get(id); 9922 final PackageVerificationResponse response = new PackageVerificationResponse( 9923 verificationCodeAtTimeout, Binder.getCallingUid()); 9924 9925 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9926 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9927 } 9928 if (millisecondsToDelay < 0) { 9929 millisecondsToDelay = 0; 9930 } 9931 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9932 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9933 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9934 } 9935 9936 if ((state != null) && !state.timeoutExtended()) { 9937 state.extendTimeout(); 9938 9939 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9940 msg.arg1 = id; 9941 msg.obj = response; 9942 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9943 } 9944 } 9945 9946 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9947 int verificationCode, UserHandle user) { 9948 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9949 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9950 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9951 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9952 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9953 9954 mContext.sendBroadcastAsUser(intent, user, 9955 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9956 } 9957 9958 private ComponentName matchComponentForVerifier(String packageName, 9959 List<ResolveInfo> receivers) { 9960 ActivityInfo targetReceiver = null; 9961 9962 final int NR = receivers.size(); 9963 for (int i = 0; i < NR; i++) { 9964 final ResolveInfo info = receivers.get(i); 9965 if (info.activityInfo == null) { 9966 continue; 9967 } 9968 9969 if (packageName.equals(info.activityInfo.packageName)) { 9970 targetReceiver = info.activityInfo; 9971 break; 9972 } 9973 } 9974 9975 if (targetReceiver == null) { 9976 return null; 9977 } 9978 9979 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9980 } 9981 9982 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9983 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9984 if (pkgInfo.verifiers.length == 0) { 9985 return null; 9986 } 9987 9988 final int N = pkgInfo.verifiers.length; 9989 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9990 for (int i = 0; i < N; i++) { 9991 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9992 9993 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9994 receivers); 9995 if (comp == null) { 9996 continue; 9997 } 9998 9999 final int verifierUid = getUidForVerifier(verifierInfo); 10000 if (verifierUid == -1) { 10001 continue; 10002 } 10003 10004 if (DEBUG_VERIFY) { 10005 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10006 + " with the correct signature"); 10007 } 10008 sufficientVerifiers.add(comp); 10009 verificationState.addSufficientVerifier(verifierUid); 10010 } 10011 10012 return sufficientVerifiers; 10013 } 10014 10015 private int getUidForVerifier(VerifierInfo verifierInfo) { 10016 synchronized (mPackages) { 10017 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10018 if (pkg == null) { 10019 return -1; 10020 } else if (pkg.mSignatures.length != 1) { 10021 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10022 + " has more than one signature; ignoring"); 10023 return -1; 10024 } 10025 10026 /* 10027 * If the public key of the package's signature does not match 10028 * our expected public key, then this is a different package and 10029 * we should skip. 10030 */ 10031 10032 final byte[] expectedPublicKey; 10033 try { 10034 final Signature verifierSig = pkg.mSignatures[0]; 10035 final PublicKey publicKey = verifierSig.getPublicKey(); 10036 expectedPublicKey = publicKey.getEncoded(); 10037 } catch (CertificateException e) { 10038 return -1; 10039 } 10040 10041 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10042 10043 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10044 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10045 + " does not have the expected public key; ignoring"); 10046 return -1; 10047 } 10048 10049 return pkg.applicationInfo.uid; 10050 } 10051 } 10052 10053 @Override 10054 public void finishPackageInstall(int token) { 10055 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10056 10057 if (DEBUG_INSTALL) { 10058 Slog.v(TAG, "BM finishing package install for " + token); 10059 } 10060 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10061 10062 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10063 mHandler.sendMessage(msg); 10064 } 10065 10066 /** 10067 * Get the verification agent timeout. 10068 * 10069 * @return verification timeout in milliseconds 10070 */ 10071 private long getVerificationTimeout() { 10072 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10073 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10074 DEFAULT_VERIFICATION_TIMEOUT); 10075 } 10076 10077 /** 10078 * Get the default verification agent response code. 10079 * 10080 * @return default verification response code 10081 */ 10082 private int getDefaultVerificationResponse() { 10083 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10084 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10085 DEFAULT_VERIFICATION_RESPONSE); 10086 } 10087 10088 /** 10089 * Check whether or not package verification has been enabled. 10090 * 10091 * @return true if verification should be performed 10092 */ 10093 private boolean isVerificationEnabled(int userId, int installFlags) { 10094 if (!DEFAULT_VERIFY_ENABLE) { 10095 return false; 10096 } 10097 10098 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10099 10100 // Check if installing from ADB 10101 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10102 // Do not run verification in a test harness environment 10103 if (ActivityManager.isRunningInTestHarness()) { 10104 return false; 10105 } 10106 if (ensureVerifyAppsEnabled) { 10107 return true; 10108 } 10109 // Check if the developer does not want package verification for ADB installs 10110 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10111 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10112 return false; 10113 } 10114 } 10115 10116 if (ensureVerifyAppsEnabled) { 10117 return true; 10118 } 10119 10120 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10121 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10122 } 10123 10124 @Override 10125 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10126 throws RemoteException { 10127 mContext.enforceCallingOrSelfPermission( 10128 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10129 "Only intentfilter verification agents can verify applications"); 10130 10131 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10132 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10133 Binder.getCallingUid(), verificationCode, failedDomains); 10134 msg.arg1 = id; 10135 msg.obj = response; 10136 mHandler.sendMessage(msg); 10137 } 10138 10139 @Override 10140 public int getIntentVerificationStatus(String packageName, int userId) { 10141 synchronized (mPackages) { 10142 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10143 } 10144 } 10145 10146 @Override 10147 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10148 mContext.enforceCallingOrSelfPermission( 10149 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10150 10151 boolean result = false; 10152 synchronized (mPackages) { 10153 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10154 } 10155 if (result) { 10156 scheduleWritePackageRestrictionsLocked(userId); 10157 } 10158 return result; 10159 } 10160 10161 @Override 10162 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10163 synchronized (mPackages) { 10164 return mSettings.getIntentFilterVerificationsLPr(packageName); 10165 } 10166 } 10167 10168 @Override 10169 public List<IntentFilter> getAllIntentFilters(String packageName) { 10170 if (TextUtils.isEmpty(packageName)) { 10171 return Collections.<IntentFilter>emptyList(); 10172 } 10173 synchronized (mPackages) { 10174 PackageParser.Package pkg = mPackages.get(packageName); 10175 if (pkg == null || pkg.activities == null) { 10176 return Collections.<IntentFilter>emptyList(); 10177 } 10178 final int count = pkg.activities.size(); 10179 ArrayList<IntentFilter> result = new ArrayList<>(); 10180 for (int n=0; n<count; n++) { 10181 PackageParser.Activity activity = pkg.activities.get(n); 10182 if (activity.intents != null || activity.intents.size() > 0) { 10183 result.addAll(activity.intents); 10184 } 10185 } 10186 return result; 10187 } 10188 } 10189 10190 @Override 10191 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10192 mContext.enforceCallingOrSelfPermission( 10193 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10194 10195 synchronized (mPackages) { 10196 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10197 if (packageName != null) { 10198 result |= updateIntentVerificationStatus(packageName, 10199 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10200 userId); 10201 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10202 packageName, userId); 10203 } 10204 return result; 10205 } 10206 } 10207 10208 @Override 10209 public String getDefaultBrowserPackageName(int userId) { 10210 synchronized (mPackages) { 10211 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10212 } 10213 } 10214 10215 /** 10216 * Get the "allow unknown sources" setting. 10217 * 10218 * @return the current "allow unknown sources" setting 10219 */ 10220 private int getUnknownSourcesSettings() { 10221 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10222 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10223 -1); 10224 } 10225 10226 @Override 10227 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10228 final int uid = Binder.getCallingUid(); 10229 // writer 10230 synchronized (mPackages) { 10231 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10232 if (targetPackageSetting == null) { 10233 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10234 } 10235 10236 PackageSetting installerPackageSetting; 10237 if (installerPackageName != null) { 10238 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10239 if (installerPackageSetting == null) { 10240 throw new IllegalArgumentException("Unknown installer package: " 10241 + installerPackageName); 10242 } 10243 } else { 10244 installerPackageSetting = null; 10245 } 10246 10247 Signature[] callerSignature; 10248 Object obj = mSettings.getUserIdLPr(uid); 10249 if (obj != null) { 10250 if (obj instanceof SharedUserSetting) { 10251 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10252 } else if (obj instanceof PackageSetting) { 10253 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10254 } else { 10255 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10256 } 10257 } else { 10258 throw new SecurityException("Unknown calling uid " + uid); 10259 } 10260 10261 // Verify: can't set installerPackageName to a package that is 10262 // not signed with the same cert as the caller. 10263 if (installerPackageSetting != null) { 10264 if (compareSignatures(callerSignature, 10265 installerPackageSetting.signatures.mSignatures) 10266 != PackageManager.SIGNATURE_MATCH) { 10267 throw new SecurityException( 10268 "Caller does not have same cert as new installer package " 10269 + installerPackageName); 10270 } 10271 } 10272 10273 // Verify: if target already has an installer package, it must 10274 // be signed with the same cert as the caller. 10275 if (targetPackageSetting.installerPackageName != null) { 10276 PackageSetting setting = mSettings.mPackages.get( 10277 targetPackageSetting.installerPackageName); 10278 // If the currently set package isn't valid, then it's always 10279 // okay to change it. 10280 if (setting != null) { 10281 if (compareSignatures(callerSignature, 10282 setting.signatures.mSignatures) 10283 != PackageManager.SIGNATURE_MATCH) { 10284 throw new SecurityException( 10285 "Caller does not have same cert as old installer package " 10286 + targetPackageSetting.installerPackageName); 10287 } 10288 } 10289 } 10290 10291 // Okay! 10292 targetPackageSetting.installerPackageName = installerPackageName; 10293 scheduleWriteSettingsLocked(); 10294 } 10295 } 10296 10297 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10298 // Queue up an async operation since the package installation may take a little while. 10299 mHandler.post(new Runnable() { 10300 public void run() { 10301 mHandler.removeCallbacks(this); 10302 // Result object to be returned 10303 PackageInstalledInfo res = new PackageInstalledInfo(); 10304 res.returnCode = currentStatus; 10305 res.uid = -1; 10306 res.pkg = null; 10307 res.removedInfo = new PackageRemovedInfo(); 10308 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10309 args.doPreInstall(res.returnCode); 10310 synchronized (mInstallLock) { 10311 installPackageTracedLI(args, res); 10312 } 10313 args.doPostInstall(res.returnCode, res.uid); 10314 } 10315 10316 // A restore should be performed at this point if (a) the install 10317 // succeeded, (b) the operation is not an update, and (c) the new 10318 // package has not opted out of backup participation. 10319 final boolean update = res.removedInfo.removedPackage != null; 10320 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10321 boolean doRestore = !update 10322 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10323 10324 // Set up the post-install work request bookkeeping. This will be used 10325 // and cleaned up by the post-install event handling regardless of whether 10326 // there's a restore pass performed. Token values are >= 1. 10327 int token; 10328 if (mNextInstallToken < 0) mNextInstallToken = 1; 10329 token = mNextInstallToken++; 10330 10331 PostInstallData data = new PostInstallData(args, res); 10332 mRunningInstalls.put(token, data); 10333 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10334 10335 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10336 // Pass responsibility to the Backup Manager. It will perform a 10337 // restore if appropriate, then pass responsibility back to the 10338 // Package Manager to run the post-install observer callbacks 10339 // and broadcasts. 10340 IBackupManager bm = IBackupManager.Stub.asInterface( 10341 ServiceManager.getService(Context.BACKUP_SERVICE)); 10342 if (bm != null) { 10343 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10344 + " to BM for possible restore"); 10345 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10346 try { 10347 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10348 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10349 } else { 10350 doRestore = false; 10351 } 10352 } catch (RemoteException e) { 10353 // can't happen; the backup manager is local 10354 } catch (Exception e) { 10355 Slog.e(TAG, "Exception trying to enqueue restore", e); 10356 doRestore = false; 10357 } 10358 } else { 10359 Slog.e(TAG, "Backup Manager not found!"); 10360 doRestore = false; 10361 } 10362 } 10363 10364 if (!doRestore) { 10365 // No restore possible, or the Backup Manager was mysteriously not 10366 // available -- just fire the post-install work request directly. 10367 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10368 10369 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10370 10371 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10372 mHandler.sendMessage(msg); 10373 } 10374 } 10375 }); 10376 } 10377 10378 private abstract class HandlerParams { 10379 private static final int MAX_RETRIES = 4; 10380 10381 /** 10382 * Number of times startCopy() has been attempted and had a non-fatal 10383 * error. 10384 */ 10385 private int mRetries = 0; 10386 10387 /** User handle for the user requesting the information or installation. */ 10388 private final UserHandle mUser; 10389 String traceMethod; 10390 int traceCookie; 10391 10392 HandlerParams(UserHandle user) { 10393 mUser = user; 10394 } 10395 10396 UserHandle getUser() { 10397 return mUser; 10398 } 10399 10400 HandlerParams setTraceMethod(String traceMethod) { 10401 this.traceMethod = traceMethod; 10402 return this; 10403 } 10404 10405 HandlerParams setTraceCookie(int traceCookie) { 10406 this.traceCookie = traceCookie; 10407 return this; 10408 } 10409 10410 final boolean startCopy() { 10411 boolean res; 10412 try { 10413 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10414 10415 if (++mRetries > MAX_RETRIES) { 10416 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10417 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10418 handleServiceError(); 10419 return false; 10420 } else { 10421 handleStartCopy(); 10422 res = true; 10423 } 10424 } catch (RemoteException e) { 10425 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10426 mHandler.sendEmptyMessage(MCS_RECONNECT); 10427 res = false; 10428 } 10429 handleReturnCode(); 10430 return res; 10431 } 10432 10433 final void serviceError() { 10434 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10435 handleServiceError(); 10436 handleReturnCode(); 10437 } 10438 10439 abstract void handleStartCopy() throws RemoteException; 10440 abstract void handleServiceError(); 10441 abstract void handleReturnCode(); 10442 } 10443 10444 class MeasureParams extends HandlerParams { 10445 private final PackageStats mStats; 10446 private boolean mSuccess; 10447 10448 private final IPackageStatsObserver mObserver; 10449 10450 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10451 super(new UserHandle(stats.userHandle)); 10452 mObserver = observer; 10453 mStats = stats; 10454 } 10455 10456 @Override 10457 public String toString() { 10458 return "MeasureParams{" 10459 + Integer.toHexString(System.identityHashCode(this)) 10460 + " " + mStats.packageName + "}"; 10461 } 10462 10463 @Override 10464 void handleStartCopy() throws RemoteException { 10465 synchronized (mInstallLock) { 10466 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10467 } 10468 10469 if (mSuccess) { 10470 final boolean mounted; 10471 if (Environment.isExternalStorageEmulated()) { 10472 mounted = true; 10473 } else { 10474 final String status = Environment.getExternalStorageState(); 10475 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10476 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10477 } 10478 10479 if (mounted) { 10480 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10481 10482 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10483 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10484 10485 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10486 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10487 10488 // Always subtract cache size, since it's a subdirectory 10489 mStats.externalDataSize -= mStats.externalCacheSize; 10490 10491 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10492 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10493 10494 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10495 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10496 } 10497 } 10498 } 10499 10500 @Override 10501 void handleReturnCode() { 10502 if (mObserver != null) { 10503 try { 10504 mObserver.onGetStatsCompleted(mStats, mSuccess); 10505 } catch (RemoteException e) { 10506 Slog.i(TAG, "Observer no longer exists."); 10507 } 10508 } 10509 } 10510 10511 @Override 10512 void handleServiceError() { 10513 Slog.e(TAG, "Could not measure application " + mStats.packageName 10514 + " external storage"); 10515 } 10516 } 10517 10518 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10519 throws RemoteException { 10520 long result = 0; 10521 for (File path : paths) { 10522 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10523 } 10524 return result; 10525 } 10526 10527 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10528 for (File path : paths) { 10529 try { 10530 mcs.clearDirectory(path.getAbsolutePath()); 10531 } catch (RemoteException e) { 10532 } 10533 } 10534 } 10535 10536 static class OriginInfo { 10537 /** 10538 * Location where install is coming from, before it has been 10539 * copied/renamed into place. This could be a single monolithic APK 10540 * file, or a cluster directory. This location may be untrusted. 10541 */ 10542 final File file; 10543 final String cid; 10544 10545 /** 10546 * Flag indicating that {@link #file} or {@link #cid} has already been 10547 * staged, meaning downstream users don't need to defensively copy the 10548 * contents. 10549 */ 10550 final boolean staged; 10551 10552 /** 10553 * Flag indicating that {@link #file} or {@link #cid} is an already 10554 * installed app that is being moved. 10555 */ 10556 final boolean existing; 10557 10558 final String resolvedPath; 10559 final File resolvedFile; 10560 10561 static OriginInfo fromNothing() { 10562 return new OriginInfo(null, null, false, false); 10563 } 10564 10565 static OriginInfo fromUntrustedFile(File file) { 10566 return new OriginInfo(file, null, false, false); 10567 } 10568 10569 static OriginInfo fromExistingFile(File file) { 10570 return new OriginInfo(file, null, false, true); 10571 } 10572 10573 static OriginInfo fromStagedFile(File file) { 10574 return new OriginInfo(file, null, true, false); 10575 } 10576 10577 static OriginInfo fromStagedContainer(String cid) { 10578 return new OriginInfo(null, cid, true, false); 10579 } 10580 10581 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10582 this.file = file; 10583 this.cid = cid; 10584 this.staged = staged; 10585 this.existing = existing; 10586 10587 if (cid != null) { 10588 resolvedPath = PackageHelper.getSdDir(cid); 10589 resolvedFile = new File(resolvedPath); 10590 } else if (file != null) { 10591 resolvedPath = file.getAbsolutePath(); 10592 resolvedFile = file; 10593 } else { 10594 resolvedPath = null; 10595 resolvedFile = null; 10596 } 10597 } 10598 } 10599 10600 class MoveInfo { 10601 final int moveId; 10602 final String fromUuid; 10603 final String toUuid; 10604 final String packageName; 10605 final String dataAppName; 10606 final int appId; 10607 final String seinfo; 10608 10609 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10610 String dataAppName, int appId, String seinfo) { 10611 this.moveId = moveId; 10612 this.fromUuid = fromUuid; 10613 this.toUuid = toUuid; 10614 this.packageName = packageName; 10615 this.dataAppName = dataAppName; 10616 this.appId = appId; 10617 this.seinfo = seinfo; 10618 } 10619 } 10620 10621 class InstallParams extends HandlerParams { 10622 final OriginInfo origin; 10623 final MoveInfo move; 10624 final IPackageInstallObserver2 observer; 10625 int installFlags; 10626 final String installerPackageName; 10627 final String volumeUuid; 10628 final VerificationParams verificationParams; 10629 private InstallArgs mArgs; 10630 private int mRet; 10631 final String packageAbiOverride; 10632 final String[] grantedRuntimePermissions; 10633 10634 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10635 int installFlags, String installerPackageName, String volumeUuid, 10636 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10637 String[] grantedPermissions) { 10638 super(user); 10639 this.origin = origin; 10640 this.move = move; 10641 this.observer = observer; 10642 this.installFlags = installFlags; 10643 this.installerPackageName = installerPackageName; 10644 this.volumeUuid = volumeUuid; 10645 this.verificationParams = verificationParams; 10646 this.packageAbiOverride = packageAbiOverride; 10647 this.grantedRuntimePermissions = grantedPermissions; 10648 } 10649 10650 @Override 10651 public String toString() { 10652 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10653 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10654 } 10655 10656 public ManifestDigest getManifestDigest() { 10657 if (verificationParams == null) { 10658 return null; 10659 } 10660 return verificationParams.getManifestDigest(); 10661 } 10662 10663 private int installLocationPolicy(PackageInfoLite pkgLite) { 10664 String packageName = pkgLite.packageName; 10665 int installLocation = pkgLite.installLocation; 10666 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10667 // reader 10668 synchronized (mPackages) { 10669 PackageParser.Package pkg = mPackages.get(packageName); 10670 if (pkg != null) { 10671 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10672 // Check for downgrading. 10673 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10674 try { 10675 checkDowngrade(pkg, pkgLite); 10676 } catch (PackageManagerException e) { 10677 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10678 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10679 } 10680 } 10681 // Check for updated system application. 10682 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10683 if (onSd) { 10684 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10685 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10686 } 10687 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10688 } else { 10689 if (onSd) { 10690 // Install flag overrides everything. 10691 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10692 } 10693 // If current upgrade specifies particular preference 10694 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10695 // Application explicitly specified internal. 10696 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10697 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10698 // App explictly prefers external. Let policy decide 10699 } else { 10700 // Prefer previous location 10701 if (isExternal(pkg)) { 10702 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10703 } 10704 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10705 } 10706 } 10707 } else { 10708 // Invalid install. Return error code 10709 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10710 } 10711 } 10712 } 10713 // All the special cases have been taken care of. 10714 // Return result based on recommended install location. 10715 if (onSd) { 10716 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10717 } 10718 return pkgLite.recommendedInstallLocation; 10719 } 10720 10721 /* 10722 * Invoke remote method to get package information and install 10723 * location values. Override install location based on default 10724 * policy if needed and then create install arguments based 10725 * on the install location. 10726 */ 10727 public void handleStartCopy() throws RemoteException { 10728 int ret = PackageManager.INSTALL_SUCCEEDED; 10729 10730 // If we're already staged, we've firmly committed to an install location 10731 if (origin.staged) { 10732 if (origin.file != null) { 10733 installFlags |= PackageManager.INSTALL_INTERNAL; 10734 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10735 } else if (origin.cid != null) { 10736 installFlags |= PackageManager.INSTALL_EXTERNAL; 10737 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10738 } else { 10739 throw new IllegalStateException("Invalid stage location"); 10740 } 10741 } 10742 10743 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10744 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10745 PackageInfoLite pkgLite = null; 10746 10747 if (onInt && onSd) { 10748 // Check if both bits are set. 10749 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10750 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10751 } else { 10752 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10753 packageAbiOverride); 10754 10755 /* 10756 * If we have too little free space, try to free cache 10757 * before giving up. 10758 */ 10759 if (!origin.staged && pkgLite.recommendedInstallLocation 10760 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10761 // TODO: focus freeing disk space on the target device 10762 final StorageManager storage = StorageManager.from(mContext); 10763 final long lowThreshold = storage.getStorageLowBytes( 10764 Environment.getDataDirectory()); 10765 10766 final long sizeBytes = mContainerService.calculateInstalledSize( 10767 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10768 10769 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10770 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10771 installFlags, packageAbiOverride); 10772 } 10773 10774 /* 10775 * The cache free must have deleted the file we 10776 * downloaded to install. 10777 * 10778 * TODO: fix the "freeCache" call to not delete 10779 * the file we care about. 10780 */ 10781 if (pkgLite.recommendedInstallLocation 10782 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10783 pkgLite.recommendedInstallLocation 10784 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10785 } 10786 } 10787 } 10788 10789 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10790 int loc = pkgLite.recommendedInstallLocation; 10791 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10792 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10793 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10794 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10795 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10796 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10797 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10798 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10799 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10800 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10801 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10802 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10803 } else { 10804 // Override with defaults if needed. 10805 loc = installLocationPolicy(pkgLite); 10806 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10807 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10808 } else if (!onSd && !onInt) { 10809 // Override install location with flags 10810 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10811 // Set the flag to install on external media. 10812 installFlags |= PackageManager.INSTALL_EXTERNAL; 10813 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10814 } else { 10815 // Make sure the flag for installing on external 10816 // media is unset 10817 installFlags |= PackageManager.INSTALL_INTERNAL; 10818 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10819 } 10820 } 10821 } 10822 } 10823 10824 final InstallArgs args = createInstallArgs(this); 10825 mArgs = args; 10826 10827 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10828 /* 10829 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10830 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10831 */ 10832 int userIdentifier = getUser().getIdentifier(); 10833 if (userIdentifier == UserHandle.USER_ALL 10834 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10835 userIdentifier = UserHandle.USER_OWNER; 10836 } 10837 10838 /* 10839 * Determine if we have any installed package verifiers. If we 10840 * do, then we'll defer to them to verify the packages. 10841 */ 10842 final int requiredUid = mRequiredVerifierPackage == null ? -1 10843 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10844 if (!origin.existing && requiredUid != -1 10845 && isVerificationEnabled(userIdentifier, installFlags)) { 10846 final Intent verification = new Intent( 10847 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10848 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10849 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10850 PACKAGE_MIME_TYPE); 10851 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10852 10853 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10854 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10855 0 /* TODO: Which userId? */); 10856 10857 if (DEBUG_VERIFY) { 10858 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10859 + verification.toString() + " with " + pkgLite.verifiers.length 10860 + " optional verifiers"); 10861 } 10862 10863 final int verificationId = mPendingVerificationToken++; 10864 10865 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10866 10867 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10868 installerPackageName); 10869 10870 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10871 installFlags); 10872 10873 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10874 pkgLite.packageName); 10875 10876 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10877 pkgLite.versionCode); 10878 10879 if (verificationParams != null) { 10880 if (verificationParams.getVerificationURI() != null) { 10881 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10882 verificationParams.getVerificationURI()); 10883 } 10884 if (verificationParams.getOriginatingURI() != null) { 10885 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10886 verificationParams.getOriginatingURI()); 10887 } 10888 if (verificationParams.getReferrer() != null) { 10889 verification.putExtra(Intent.EXTRA_REFERRER, 10890 verificationParams.getReferrer()); 10891 } 10892 if (verificationParams.getOriginatingUid() >= 0) { 10893 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10894 verificationParams.getOriginatingUid()); 10895 } 10896 if (verificationParams.getInstallerUid() >= 0) { 10897 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10898 verificationParams.getInstallerUid()); 10899 } 10900 } 10901 10902 final PackageVerificationState verificationState = new PackageVerificationState( 10903 requiredUid, args); 10904 10905 mPendingVerification.append(verificationId, verificationState); 10906 10907 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10908 receivers, verificationState); 10909 10910 // Apps installed for "all" users use the device owner to verify the app 10911 UserHandle verifierUser = getUser(); 10912 if (verifierUser == UserHandle.ALL) { 10913 verifierUser = UserHandle.OWNER; 10914 } 10915 10916 /* 10917 * If any sufficient verifiers were listed in the package 10918 * manifest, attempt to ask them. 10919 */ 10920 if (sufficientVerifiers != null) { 10921 final int N = sufficientVerifiers.size(); 10922 if (N == 0) { 10923 Slog.i(TAG, "Additional verifiers required, but none installed."); 10924 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10925 } else { 10926 for (int i = 0; i < N; i++) { 10927 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10928 10929 final Intent sufficientIntent = new Intent(verification); 10930 sufficientIntent.setComponent(verifierComponent); 10931 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10932 } 10933 } 10934 } 10935 10936 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10937 mRequiredVerifierPackage, receivers); 10938 if (ret == PackageManager.INSTALL_SUCCEEDED 10939 && mRequiredVerifierPackage != null) { 10940 Trace.asyncTraceBegin( 10941 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10942 /* 10943 * Send the intent to the required verification agent, 10944 * but only start the verification timeout after the 10945 * target BroadcastReceivers have run. 10946 */ 10947 verification.setComponent(requiredVerifierComponent); 10948 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10949 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10950 new BroadcastReceiver() { 10951 @Override 10952 public void onReceive(Context context, Intent intent) { 10953 final Message msg = mHandler 10954 .obtainMessage(CHECK_PENDING_VERIFICATION); 10955 msg.arg1 = verificationId; 10956 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10957 } 10958 }, null, 0, null, null); 10959 10960 /* 10961 * We don't want the copy to proceed until verification 10962 * succeeds, so null out this field. 10963 */ 10964 mArgs = null; 10965 } 10966 } else { 10967 /* 10968 * No package verification is enabled, so immediately start 10969 * the remote call to initiate copy using temporary file. 10970 */ 10971 ret = args.copyApk(mContainerService, true); 10972 } 10973 } 10974 10975 mRet = ret; 10976 } 10977 10978 @Override 10979 void handleReturnCode() { 10980 // If mArgs is null, then MCS couldn't be reached. When it 10981 // reconnects, it will try again to install. At that point, this 10982 // will succeed. 10983 if (mArgs != null) { 10984 processPendingInstall(mArgs, mRet); 10985 } 10986 } 10987 10988 @Override 10989 void handleServiceError() { 10990 mArgs = createInstallArgs(this); 10991 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10992 } 10993 10994 public boolean isForwardLocked() { 10995 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10996 } 10997 } 10998 10999 /** 11000 * Used during creation of InstallArgs 11001 * 11002 * @param installFlags package installation flags 11003 * @return true if should be installed on external storage 11004 */ 11005 private static boolean installOnExternalAsec(int installFlags) { 11006 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11007 return false; 11008 } 11009 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11010 return true; 11011 } 11012 return false; 11013 } 11014 11015 /** 11016 * Used during creation of InstallArgs 11017 * 11018 * @param installFlags package installation flags 11019 * @return true if should be installed as forward locked 11020 */ 11021 private static boolean installForwardLocked(int installFlags) { 11022 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11023 } 11024 11025 private InstallArgs createInstallArgs(InstallParams params) { 11026 if (params.move != null) { 11027 return new MoveInstallArgs(params); 11028 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11029 return new AsecInstallArgs(params); 11030 } else { 11031 return new FileInstallArgs(params); 11032 } 11033 } 11034 11035 /** 11036 * Create args that describe an existing installed package. Typically used 11037 * when cleaning up old installs, or used as a move source. 11038 */ 11039 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11040 String resourcePath, String[] instructionSets) { 11041 final boolean isInAsec; 11042 if (installOnExternalAsec(installFlags)) { 11043 /* Apps on SD card are always in ASEC containers. */ 11044 isInAsec = true; 11045 } else if (installForwardLocked(installFlags) 11046 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11047 /* 11048 * Forward-locked apps are only in ASEC containers if they're the 11049 * new style 11050 */ 11051 isInAsec = true; 11052 } else { 11053 isInAsec = false; 11054 } 11055 11056 if (isInAsec) { 11057 return new AsecInstallArgs(codePath, instructionSets, 11058 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11059 } else { 11060 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11061 } 11062 } 11063 11064 static abstract class InstallArgs { 11065 /** @see InstallParams#origin */ 11066 final OriginInfo origin; 11067 /** @see InstallParams#move */ 11068 final MoveInfo move; 11069 11070 final IPackageInstallObserver2 observer; 11071 // Always refers to PackageManager flags only 11072 final int installFlags; 11073 final String installerPackageName; 11074 final String volumeUuid; 11075 final ManifestDigest manifestDigest; 11076 final UserHandle user; 11077 final String abiOverride; 11078 final String[] installGrantPermissions; 11079 /** If non-null, drop an async trace when the install completes */ 11080 final String traceMethod; 11081 final int traceCookie; 11082 11083 // The list of instruction sets supported by this app. This is currently 11084 // only used during the rmdex() phase to clean up resources. We can get rid of this 11085 // if we move dex files under the common app path. 11086 /* nullable */ String[] instructionSets; 11087 11088 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11089 int installFlags, String installerPackageName, String volumeUuid, 11090 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11091 String abiOverride, String[] installGrantPermissions, 11092 String traceMethod, int traceCookie) { 11093 this.origin = origin; 11094 this.move = move; 11095 this.installFlags = installFlags; 11096 this.observer = observer; 11097 this.installerPackageName = installerPackageName; 11098 this.volumeUuid = volumeUuid; 11099 this.manifestDigest = manifestDigest; 11100 this.user = user; 11101 this.instructionSets = instructionSets; 11102 this.abiOverride = abiOverride; 11103 this.installGrantPermissions = installGrantPermissions; 11104 this.traceMethod = traceMethod; 11105 this.traceCookie = traceCookie; 11106 } 11107 11108 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11109 abstract int doPreInstall(int status); 11110 11111 /** 11112 * Rename package into final resting place. All paths on the given 11113 * scanned package should be updated to reflect the rename. 11114 */ 11115 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11116 abstract int doPostInstall(int status, int uid); 11117 11118 /** @see PackageSettingBase#codePathString */ 11119 abstract String getCodePath(); 11120 /** @see PackageSettingBase#resourcePathString */ 11121 abstract String getResourcePath(); 11122 11123 // Need installer lock especially for dex file removal. 11124 abstract void cleanUpResourcesLI(); 11125 abstract boolean doPostDeleteLI(boolean delete); 11126 11127 /** 11128 * Called before the source arguments are copied. This is used mostly 11129 * for MoveParams when it needs to read the source file to put it in the 11130 * destination. 11131 */ 11132 int doPreCopy() { 11133 return PackageManager.INSTALL_SUCCEEDED; 11134 } 11135 11136 /** 11137 * Called after the source arguments are copied. This is used mostly for 11138 * MoveParams when it needs to read the source file to put it in the 11139 * destination. 11140 * 11141 * @return 11142 */ 11143 int doPostCopy(int uid) { 11144 return PackageManager.INSTALL_SUCCEEDED; 11145 } 11146 11147 protected boolean isFwdLocked() { 11148 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11149 } 11150 11151 protected boolean isExternalAsec() { 11152 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11153 } 11154 11155 UserHandle getUser() { 11156 return user; 11157 } 11158 } 11159 11160 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11161 if (!allCodePaths.isEmpty()) { 11162 if (instructionSets == null) { 11163 throw new IllegalStateException("instructionSet == null"); 11164 } 11165 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11166 for (String codePath : allCodePaths) { 11167 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11168 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11169 if (retCode < 0) { 11170 Slog.w(TAG, "Couldn't remove dex file for package: " 11171 + " at location " + codePath + ", retcode=" + retCode); 11172 // we don't consider this to be a failure of the core package deletion 11173 } 11174 } 11175 } 11176 } 11177 } 11178 11179 /** 11180 * Logic to handle installation of non-ASEC applications, including copying 11181 * and renaming logic. 11182 */ 11183 class FileInstallArgs extends InstallArgs { 11184 private File codeFile; 11185 private File resourceFile; 11186 11187 // Example topology: 11188 // /data/app/com.example/base.apk 11189 // /data/app/com.example/split_foo.apk 11190 // /data/app/com.example/lib/arm/libfoo.so 11191 // /data/app/com.example/lib/arm64/libfoo.so 11192 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11193 11194 /** New install */ 11195 FileInstallArgs(InstallParams params) { 11196 super(params.origin, params.move, params.observer, params.installFlags, 11197 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11198 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11199 params.grantedRuntimePermissions, 11200 params.traceMethod, params.traceCookie); 11201 if (isFwdLocked()) { 11202 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11203 } 11204 } 11205 11206 /** Existing install */ 11207 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11208 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11209 null, null, null, 0); 11210 this.codeFile = (codePath != null) ? new File(codePath) : null; 11211 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11212 } 11213 11214 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11215 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11216 try { 11217 return doCopyApk(imcs, temp); 11218 } finally { 11219 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11220 } 11221 } 11222 11223 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11224 if (origin.staged) { 11225 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11226 codeFile = origin.file; 11227 resourceFile = origin.file; 11228 return PackageManager.INSTALL_SUCCEEDED; 11229 } 11230 11231 try { 11232 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11233 codeFile = tempDir; 11234 resourceFile = tempDir; 11235 } catch (IOException e) { 11236 Slog.w(TAG, "Failed to create copy file: " + e); 11237 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11238 } 11239 11240 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11241 @Override 11242 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11243 if (!FileUtils.isValidExtFilename(name)) { 11244 throw new IllegalArgumentException("Invalid filename: " + name); 11245 } 11246 try { 11247 final File file = new File(codeFile, name); 11248 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11249 O_RDWR | O_CREAT, 0644); 11250 Os.chmod(file.getAbsolutePath(), 0644); 11251 return new ParcelFileDescriptor(fd); 11252 } catch (ErrnoException e) { 11253 throw new RemoteException("Failed to open: " + e.getMessage()); 11254 } 11255 } 11256 }; 11257 11258 int ret = PackageManager.INSTALL_SUCCEEDED; 11259 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11260 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11261 Slog.e(TAG, "Failed to copy package"); 11262 return ret; 11263 } 11264 11265 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11266 NativeLibraryHelper.Handle handle = null; 11267 try { 11268 handle = NativeLibraryHelper.Handle.create(codeFile); 11269 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11270 abiOverride); 11271 } catch (IOException e) { 11272 Slog.e(TAG, "Copying native libraries failed", e); 11273 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11274 } finally { 11275 IoUtils.closeQuietly(handle); 11276 } 11277 11278 return ret; 11279 } 11280 11281 int doPreInstall(int status) { 11282 if (status != PackageManager.INSTALL_SUCCEEDED) { 11283 cleanUp(); 11284 } 11285 return status; 11286 } 11287 11288 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11289 if (status != PackageManager.INSTALL_SUCCEEDED) { 11290 cleanUp(); 11291 return false; 11292 } 11293 11294 final File targetDir = codeFile.getParentFile(); 11295 final File beforeCodeFile = codeFile; 11296 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11297 11298 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11299 try { 11300 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11301 } catch (ErrnoException e) { 11302 Slog.w(TAG, "Failed to rename", e); 11303 return false; 11304 } 11305 11306 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11307 Slog.w(TAG, "Failed to restorecon"); 11308 return false; 11309 } 11310 11311 // Reflect the rename internally 11312 codeFile = afterCodeFile; 11313 resourceFile = afterCodeFile; 11314 11315 // Reflect the rename in scanned details 11316 pkg.codePath = afterCodeFile.getAbsolutePath(); 11317 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11318 pkg.baseCodePath); 11319 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11320 pkg.splitCodePaths); 11321 11322 // Reflect the rename in app info 11323 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11324 pkg.applicationInfo.setCodePath(pkg.codePath); 11325 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11326 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11327 pkg.applicationInfo.setResourcePath(pkg.codePath); 11328 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11329 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11330 11331 return true; 11332 } 11333 11334 int doPostInstall(int status, int uid) { 11335 if (status != PackageManager.INSTALL_SUCCEEDED) { 11336 cleanUp(); 11337 } 11338 return status; 11339 } 11340 11341 @Override 11342 String getCodePath() { 11343 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11344 } 11345 11346 @Override 11347 String getResourcePath() { 11348 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11349 } 11350 11351 private boolean cleanUp() { 11352 if (codeFile == null || !codeFile.exists()) { 11353 return false; 11354 } 11355 11356 if (codeFile.isDirectory()) { 11357 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11358 } else { 11359 codeFile.delete(); 11360 } 11361 11362 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11363 resourceFile.delete(); 11364 } 11365 11366 return true; 11367 } 11368 11369 void cleanUpResourcesLI() { 11370 // Try enumerating all code paths before deleting 11371 List<String> allCodePaths = Collections.EMPTY_LIST; 11372 if (codeFile != null && codeFile.exists()) { 11373 try { 11374 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11375 allCodePaths = pkg.getAllCodePaths(); 11376 } catch (PackageParserException e) { 11377 // Ignored; we tried our best 11378 } 11379 } 11380 11381 cleanUp(); 11382 removeDexFiles(allCodePaths, instructionSets); 11383 } 11384 11385 boolean doPostDeleteLI(boolean delete) { 11386 // XXX err, shouldn't we respect the delete flag? 11387 cleanUpResourcesLI(); 11388 return true; 11389 } 11390 } 11391 11392 private boolean isAsecExternal(String cid) { 11393 final String asecPath = PackageHelper.getSdFilesystem(cid); 11394 return !asecPath.startsWith(mAsecInternalPath); 11395 } 11396 11397 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11398 PackageManagerException { 11399 if (copyRet < 0) { 11400 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11401 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11402 throw new PackageManagerException(copyRet, message); 11403 } 11404 } 11405 } 11406 11407 /** 11408 * Extract the MountService "container ID" from the full code path of an 11409 * .apk. 11410 */ 11411 static String cidFromCodePath(String fullCodePath) { 11412 int eidx = fullCodePath.lastIndexOf("/"); 11413 String subStr1 = fullCodePath.substring(0, eidx); 11414 int sidx = subStr1.lastIndexOf("/"); 11415 return subStr1.substring(sidx+1, eidx); 11416 } 11417 11418 /** 11419 * Logic to handle installation of ASEC applications, including copying and 11420 * renaming logic. 11421 */ 11422 class AsecInstallArgs extends InstallArgs { 11423 static final String RES_FILE_NAME = "pkg.apk"; 11424 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11425 11426 String cid; 11427 String packagePath; 11428 String resourcePath; 11429 11430 /** New install */ 11431 AsecInstallArgs(InstallParams params) { 11432 super(params.origin, params.move, params.observer, params.installFlags, 11433 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11434 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11435 params.grantedRuntimePermissions, 11436 params.traceMethod, params.traceCookie); 11437 } 11438 11439 /** Existing install */ 11440 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11441 boolean isExternal, boolean isForwardLocked) { 11442 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11443 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11444 instructionSets, null, null, null, 0); 11445 // Hackily pretend we're still looking at a full code path 11446 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11447 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11448 } 11449 11450 // Extract cid from fullCodePath 11451 int eidx = fullCodePath.lastIndexOf("/"); 11452 String subStr1 = fullCodePath.substring(0, eidx); 11453 int sidx = subStr1.lastIndexOf("/"); 11454 cid = subStr1.substring(sidx+1, eidx); 11455 setMountPath(subStr1); 11456 } 11457 11458 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11459 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11460 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11461 instructionSets, null, null, null, 0); 11462 this.cid = cid; 11463 setMountPath(PackageHelper.getSdDir(cid)); 11464 } 11465 11466 void createCopyFile() { 11467 cid = mInstallerService.allocateExternalStageCidLegacy(); 11468 } 11469 11470 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11471 if (origin.staged) { 11472 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11473 cid = origin.cid; 11474 setMountPath(PackageHelper.getSdDir(cid)); 11475 return PackageManager.INSTALL_SUCCEEDED; 11476 } 11477 11478 if (temp) { 11479 createCopyFile(); 11480 } else { 11481 /* 11482 * Pre-emptively destroy the container since it's destroyed if 11483 * copying fails due to it existing anyway. 11484 */ 11485 PackageHelper.destroySdDir(cid); 11486 } 11487 11488 final String newMountPath = imcs.copyPackageToContainer( 11489 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11490 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11491 11492 if (newMountPath != null) { 11493 setMountPath(newMountPath); 11494 return PackageManager.INSTALL_SUCCEEDED; 11495 } else { 11496 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11497 } 11498 } 11499 11500 @Override 11501 String getCodePath() { 11502 return packagePath; 11503 } 11504 11505 @Override 11506 String getResourcePath() { 11507 return resourcePath; 11508 } 11509 11510 int doPreInstall(int status) { 11511 if (status != PackageManager.INSTALL_SUCCEEDED) { 11512 // Destroy container 11513 PackageHelper.destroySdDir(cid); 11514 } else { 11515 boolean mounted = PackageHelper.isContainerMounted(cid); 11516 if (!mounted) { 11517 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11518 Process.SYSTEM_UID); 11519 if (newMountPath != null) { 11520 setMountPath(newMountPath); 11521 } else { 11522 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11523 } 11524 } 11525 } 11526 return status; 11527 } 11528 11529 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11530 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11531 String newMountPath = null; 11532 if (PackageHelper.isContainerMounted(cid)) { 11533 // Unmount the container 11534 if (!PackageHelper.unMountSdDir(cid)) { 11535 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11536 return false; 11537 } 11538 } 11539 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11540 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11541 " which might be stale. Will try to clean up."); 11542 // Clean up the stale container and proceed to recreate. 11543 if (!PackageHelper.destroySdDir(newCacheId)) { 11544 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11545 return false; 11546 } 11547 // Successfully cleaned up stale container. Try to rename again. 11548 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11549 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11550 + " inspite of cleaning it up."); 11551 return false; 11552 } 11553 } 11554 if (!PackageHelper.isContainerMounted(newCacheId)) { 11555 Slog.w(TAG, "Mounting container " + newCacheId); 11556 newMountPath = PackageHelper.mountSdDir(newCacheId, 11557 getEncryptKey(), Process.SYSTEM_UID); 11558 } else { 11559 newMountPath = PackageHelper.getSdDir(newCacheId); 11560 } 11561 if (newMountPath == null) { 11562 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11563 return false; 11564 } 11565 Log.i(TAG, "Succesfully renamed " + cid + 11566 " to " + newCacheId + 11567 " at new path: " + newMountPath); 11568 cid = newCacheId; 11569 11570 final File beforeCodeFile = new File(packagePath); 11571 setMountPath(newMountPath); 11572 final File afterCodeFile = new File(packagePath); 11573 11574 // Reflect the rename in scanned details 11575 pkg.codePath = afterCodeFile.getAbsolutePath(); 11576 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11577 pkg.baseCodePath); 11578 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11579 pkg.splitCodePaths); 11580 11581 // Reflect the rename in app info 11582 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11583 pkg.applicationInfo.setCodePath(pkg.codePath); 11584 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11585 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11586 pkg.applicationInfo.setResourcePath(pkg.codePath); 11587 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11588 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11589 11590 return true; 11591 } 11592 11593 private void setMountPath(String mountPath) { 11594 final File mountFile = new File(mountPath); 11595 11596 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11597 if (monolithicFile.exists()) { 11598 packagePath = monolithicFile.getAbsolutePath(); 11599 if (isFwdLocked()) { 11600 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11601 } else { 11602 resourcePath = packagePath; 11603 } 11604 } else { 11605 packagePath = mountFile.getAbsolutePath(); 11606 resourcePath = packagePath; 11607 } 11608 } 11609 11610 int doPostInstall(int status, int uid) { 11611 if (status != PackageManager.INSTALL_SUCCEEDED) { 11612 cleanUp(); 11613 } else { 11614 final int groupOwner; 11615 final String protectedFile; 11616 if (isFwdLocked()) { 11617 groupOwner = UserHandle.getSharedAppGid(uid); 11618 protectedFile = RES_FILE_NAME; 11619 } else { 11620 groupOwner = -1; 11621 protectedFile = null; 11622 } 11623 11624 if (uid < Process.FIRST_APPLICATION_UID 11625 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11626 Slog.e(TAG, "Failed to finalize " + cid); 11627 PackageHelper.destroySdDir(cid); 11628 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11629 } 11630 11631 boolean mounted = PackageHelper.isContainerMounted(cid); 11632 if (!mounted) { 11633 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11634 } 11635 } 11636 return status; 11637 } 11638 11639 private void cleanUp() { 11640 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11641 11642 // Destroy secure container 11643 PackageHelper.destroySdDir(cid); 11644 } 11645 11646 private List<String> getAllCodePaths() { 11647 final File codeFile = new File(getCodePath()); 11648 if (codeFile != null && codeFile.exists()) { 11649 try { 11650 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11651 return pkg.getAllCodePaths(); 11652 } catch (PackageParserException e) { 11653 // Ignored; we tried our best 11654 } 11655 } 11656 return Collections.EMPTY_LIST; 11657 } 11658 11659 void cleanUpResourcesLI() { 11660 // Enumerate all code paths before deleting 11661 cleanUpResourcesLI(getAllCodePaths()); 11662 } 11663 11664 private void cleanUpResourcesLI(List<String> allCodePaths) { 11665 cleanUp(); 11666 removeDexFiles(allCodePaths, instructionSets); 11667 } 11668 11669 String getPackageName() { 11670 return getAsecPackageName(cid); 11671 } 11672 11673 boolean doPostDeleteLI(boolean delete) { 11674 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11675 final List<String> allCodePaths = getAllCodePaths(); 11676 boolean mounted = PackageHelper.isContainerMounted(cid); 11677 if (mounted) { 11678 // Unmount first 11679 if (PackageHelper.unMountSdDir(cid)) { 11680 mounted = false; 11681 } 11682 } 11683 if (!mounted && delete) { 11684 cleanUpResourcesLI(allCodePaths); 11685 } 11686 return !mounted; 11687 } 11688 11689 @Override 11690 int doPreCopy() { 11691 if (isFwdLocked()) { 11692 if (!PackageHelper.fixSdPermissions(cid, 11693 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11694 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11695 } 11696 } 11697 11698 return PackageManager.INSTALL_SUCCEEDED; 11699 } 11700 11701 @Override 11702 int doPostCopy(int uid) { 11703 if (isFwdLocked()) { 11704 if (uid < Process.FIRST_APPLICATION_UID 11705 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11706 RES_FILE_NAME)) { 11707 Slog.e(TAG, "Failed to finalize " + cid); 11708 PackageHelper.destroySdDir(cid); 11709 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11710 } 11711 } 11712 11713 return PackageManager.INSTALL_SUCCEEDED; 11714 } 11715 } 11716 11717 /** 11718 * Logic to handle movement of existing installed applications. 11719 */ 11720 class MoveInstallArgs extends InstallArgs { 11721 private File codeFile; 11722 private File resourceFile; 11723 11724 /** New install */ 11725 MoveInstallArgs(InstallParams params) { 11726 super(params.origin, params.move, params.observer, params.installFlags, 11727 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11728 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11729 params.grantedRuntimePermissions, 11730 params.traceMethod, params.traceCookie); 11731 } 11732 11733 int copyApk(IMediaContainerService imcs, boolean temp) { 11734 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11735 + move.fromUuid + " to " + move.toUuid); 11736 synchronized (mInstaller) { 11737 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11738 move.dataAppName, move.appId, move.seinfo) != 0) { 11739 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11740 } 11741 } 11742 11743 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11744 resourceFile = codeFile; 11745 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11746 11747 return PackageManager.INSTALL_SUCCEEDED; 11748 } 11749 11750 int doPreInstall(int status) { 11751 if (status != PackageManager.INSTALL_SUCCEEDED) { 11752 cleanUp(move.toUuid); 11753 } 11754 return status; 11755 } 11756 11757 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11758 if (status != PackageManager.INSTALL_SUCCEEDED) { 11759 cleanUp(move.toUuid); 11760 return false; 11761 } 11762 11763 // Reflect the move in app info 11764 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11765 pkg.applicationInfo.setCodePath(pkg.codePath); 11766 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11767 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11768 pkg.applicationInfo.setResourcePath(pkg.codePath); 11769 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11770 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11771 11772 return true; 11773 } 11774 11775 int doPostInstall(int status, int uid) { 11776 if (status == PackageManager.INSTALL_SUCCEEDED) { 11777 cleanUp(move.fromUuid); 11778 } else { 11779 cleanUp(move.toUuid); 11780 } 11781 return status; 11782 } 11783 11784 @Override 11785 String getCodePath() { 11786 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11787 } 11788 11789 @Override 11790 String getResourcePath() { 11791 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11792 } 11793 11794 private boolean cleanUp(String volumeUuid) { 11795 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11796 move.dataAppName); 11797 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11798 synchronized (mInstallLock) { 11799 // Clean up both app data and code 11800 removeDataDirsLI(volumeUuid, move.packageName); 11801 if (codeFile.isDirectory()) { 11802 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11803 } else { 11804 codeFile.delete(); 11805 } 11806 } 11807 return true; 11808 } 11809 11810 void cleanUpResourcesLI() { 11811 throw new UnsupportedOperationException(); 11812 } 11813 11814 boolean doPostDeleteLI(boolean delete) { 11815 throw new UnsupportedOperationException(); 11816 } 11817 } 11818 11819 static String getAsecPackageName(String packageCid) { 11820 int idx = packageCid.lastIndexOf("-"); 11821 if (idx == -1) { 11822 return packageCid; 11823 } 11824 return packageCid.substring(0, idx); 11825 } 11826 11827 // Utility method used to create code paths based on package name and available index. 11828 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11829 String idxStr = ""; 11830 int idx = 1; 11831 // Fall back to default value of idx=1 if prefix is not 11832 // part of oldCodePath 11833 if (oldCodePath != null) { 11834 String subStr = oldCodePath; 11835 // Drop the suffix right away 11836 if (suffix != null && subStr.endsWith(suffix)) { 11837 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11838 } 11839 // If oldCodePath already contains prefix find out the 11840 // ending index to either increment or decrement. 11841 int sidx = subStr.lastIndexOf(prefix); 11842 if (sidx != -1) { 11843 subStr = subStr.substring(sidx + prefix.length()); 11844 if (subStr != null) { 11845 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11846 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11847 } 11848 try { 11849 idx = Integer.parseInt(subStr); 11850 if (idx <= 1) { 11851 idx++; 11852 } else { 11853 idx--; 11854 } 11855 } catch(NumberFormatException e) { 11856 } 11857 } 11858 } 11859 } 11860 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11861 return prefix + idxStr; 11862 } 11863 11864 private File getNextCodePath(File targetDir, String packageName) { 11865 int suffix = 1; 11866 File result; 11867 do { 11868 result = new File(targetDir, packageName + "-" + suffix); 11869 suffix++; 11870 } while (result.exists()); 11871 return result; 11872 } 11873 11874 // Utility method that returns the relative package path with respect 11875 // to the installation directory. Like say for /data/data/com.test-1.apk 11876 // string com.test-1 is returned. 11877 static String deriveCodePathName(String codePath) { 11878 if (codePath == null) { 11879 return null; 11880 } 11881 final File codeFile = new File(codePath); 11882 final String name = codeFile.getName(); 11883 if (codeFile.isDirectory()) { 11884 return name; 11885 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11886 final int lastDot = name.lastIndexOf('.'); 11887 return name.substring(0, lastDot); 11888 } else { 11889 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11890 return null; 11891 } 11892 } 11893 11894 class PackageInstalledInfo { 11895 String name; 11896 int uid; 11897 // The set of users that originally had this package installed. 11898 int[] origUsers; 11899 // The set of users that now have this package installed. 11900 int[] newUsers; 11901 PackageParser.Package pkg; 11902 int returnCode; 11903 String returnMsg; 11904 PackageRemovedInfo removedInfo; 11905 11906 public void setError(int code, String msg) { 11907 returnCode = code; 11908 returnMsg = msg; 11909 Slog.w(TAG, msg); 11910 } 11911 11912 public void setError(String msg, PackageParserException e) { 11913 returnCode = e.error; 11914 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11915 Slog.w(TAG, msg, e); 11916 } 11917 11918 public void setError(String msg, PackageManagerException e) { 11919 returnCode = e.error; 11920 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11921 Slog.w(TAG, msg, e); 11922 } 11923 11924 // In some error cases we want to convey more info back to the observer 11925 String origPackage; 11926 String origPermission; 11927 } 11928 11929 /* 11930 * Install a non-existing package. 11931 */ 11932 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11933 UserHandle user, String installerPackageName, String volumeUuid, 11934 PackageInstalledInfo res) { 11935 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11936 11937 // Remember this for later, in case we need to rollback this install 11938 String pkgName = pkg.packageName; 11939 11940 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11941 // TODO: b/23350563 11942 final boolean dataDirExists = Environment 11943 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11944 11945 synchronized(mPackages) { 11946 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11947 // A package with the same name is already installed, though 11948 // it has been renamed to an older name. The package we 11949 // are trying to install should be installed as an update to 11950 // the existing one, but that has not been requested, so bail. 11951 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11952 + " without first uninstalling package running as " 11953 + mSettings.mRenamedPackages.get(pkgName)); 11954 return; 11955 } 11956 if (mPackages.containsKey(pkgName)) { 11957 // Don't allow installation over an existing package with the same name. 11958 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11959 + " without first uninstalling."); 11960 return; 11961 } 11962 } 11963 11964 try { 11965 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11966 System.currentTimeMillis(), user); 11967 11968 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11969 // delete the partially installed application. the data directory will have to be 11970 // restored if it was already existing 11971 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11972 // remove package from internal structures. Note that we want deletePackageX to 11973 // delete the package data and cache directories that it created in 11974 // scanPackageLocked, unless those directories existed before we even tried to 11975 // install. 11976 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11977 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11978 res.removedInfo, true); 11979 } 11980 11981 } catch (PackageManagerException e) { 11982 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11983 } 11984 11985 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11986 } 11987 11988 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11989 // Can't rotate keys during boot or if sharedUser. 11990 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11991 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11992 return false; 11993 } 11994 // app is using upgradeKeySets; make sure all are valid 11995 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11996 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11997 for (int i = 0; i < upgradeKeySets.length; i++) { 11998 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11999 Slog.wtf(TAG, "Package " 12000 + (oldPs.name != null ? oldPs.name : "<null>") 12001 + " contains upgrade-key-set reference to unknown key-set: " 12002 + upgradeKeySets[i] 12003 + " reverting to signatures check."); 12004 return false; 12005 } 12006 } 12007 return true; 12008 } 12009 12010 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12011 // Upgrade keysets are being used. Determine if new package has a superset of the 12012 // required keys. 12013 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12014 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12015 for (int i = 0; i < upgradeKeySets.length; i++) { 12016 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12017 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12018 return true; 12019 } 12020 } 12021 return false; 12022 } 12023 12024 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12025 UserHandle user, String installerPackageName, String volumeUuid, 12026 PackageInstalledInfo res) { 12027 final PackageParser.Package oldPackage; 12028 final String pkgName = pkg.packageName; 12029 final int[] allUsers; 12030 final boolean[] perUserInstalled; 12031 12032 // First find the old package info and check signatures 12033 synchronized(mPackages) { 12034 oldPackage = mPackages.get(pkgName); 12035 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12036 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12037 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12038 if(!checkUpgradeKeySetLP(ps, pkg)) { 12039 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12040 "New package not signed by keys specified by upgrade-keysets: " 12041 + pkgName); 12042 return; 12043 } 12044 } else { 12045 // default to original signature matching 12046 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12047 != PackageManager.SIGNATURE_MATCH) { 12048 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12049 "New package has a different signature: " + pkgName); 12050 return; 12051 } 12052 } 12053 12054 // In case of rollback, remember per-user/profile install state 12055 allUsers = sUserManager.getUserIds(); 12056 perUserInstalled = new boolean[allUsers.length]; 12057 for (int i = 0; i < allUsers.length; i++) { 12058 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12059 } 12060 } 12061 12062 boolean sysPkg = (isSystemApp(oldPackage)); 12063 if (sysPkg) { 12064 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12065 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12066 } else { 12067 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12068 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12069 } 12070 } 12071 12072 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12073 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12074 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12075 String volumeUuid, PackageInstalledInfo res) { 12076 String pkgName = deletedPackage.packageName; 12077 boolean deletedPkg = true; 12078 boolean updatedSettings = false; 12079 12080 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12081 + deletedPackage); 12082 long origUpdateTime; 12083 if (pkg.mExtras != null) { 12084 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12085 } else { 12086 origUpdateTime = 0; 12087 } 12088 12089 // First delete the existing package while retaining the data directory 12090 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12091 res.removedInfo, true)) { 12092 // If the existing package wasn't successfully deleted 12093 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12094 deletedPkg = false; 12095 } else { 12096 // Successfully deleted the old package; proceed with replace. 12097 12098 // If deleted package lived in a container, give users a chance to 12099 // relinquish resources before killing. 12100 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12101 if (DEBUG_INSTALL) { 12102 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12103 } 12104 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12105 final ArrayList<String> pkgList = new ArrayList<String>(1); 12106 pkgList.add(deletedPackage.applicationInfo.packageName); 12107 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12108 } 12109 12110 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12111 try { 12112 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12113 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12114 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12115 perUserInstalled, res, user); 12116 updatedSettings = true; 12117 } catch (PackageManagerException e) { 12118 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12119 } 12120 } 12121 12122 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12123 // remove package from internal structures. Note that we want deletePackageX to 12124 // delete the package data and cache directories that it created in 12125 // scanPackageLocked, unless those directories existed before we even tried to 12126 // install. 12127 if(updatedSettings) { 12128 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12129 deletePackageLI( 12130 pkgName, null, true, allUsers, perUserInstalled, 12131 PackageManager.DELETE_KEEP_DATA, 12132 res.removedInfo, true); 12133 } 12134 // Since we failed to install the new package we need to restore the old 12135 // package that we deleted. 12136 if (deletedPkg) { 12137 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12138 File restoreFile = new File(deletedPackage.codePath); 12139 // Parse old package 12140 boolean oldExternal = isExternal(deletedPackage); 12141 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12142 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12143 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12144 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12145 try { 12146 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 12147 } catch (PackageManagerException e) { 12148 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12149 + e.getMessage()); 12150 return; 12151 } 12152 // Restore of old package succeeded. Update permissions. 12153 // writer 12154 synchronized (mPackages) { 12155 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12156 UPDATE_PERMISSIONS_ALL); 12157 // can downgrade to reader 12158 mSettings.writeLPr(); 12159 } 12160 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12161 } 12162 } 12163 } 12164 12165 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12166 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12167 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12168 String volumeUuid, PackageInstalledInfo res) { 12169 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12170 + ", old=" + deletedPackage); 12171 boolean disabledSystem = false; 12172 boolean updatedSettings = false; 12173 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12174 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12175 != 0) { 12176 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12177 } 12178 String packageName = deletedPackage.packageName; 12179 if (packageName == null) { 12180 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12181 "Attempt to delete null packageName."); 12182 return; 12183 } 12184 PackageParser.Package oldPkg; 12185 PackageSetting oldPkgSetting; 12186 // reader 12187 synchronized (mPackages) { 12188 oldPkg = mPackages.get(packageName); 12189 oldPkgSetting = mSettings.mPackages.get(packageName); 12190 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12191 (oldPkgSetting == null)) { 12192 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12193 "Couldn't find package:" + packageName + " information"); 12194 return; 12195 } 12196 } 12197 12198 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12199 12200 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12201 res.removedInfo.removedPackage = packageName; 12202 // Remove existing system package 12203 removePackageLI(oldPkgSetting, true); 12204 // writer 12205 synchronized (mPackages) { 12206 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12207 if (!disabledSystem && deletedPackage != null) { 12208 // We didn't need to disable the .apk as a current system package, 12209 // which means we are replacing another update that is already 12210 // installed. We need to make sure to delete the older one's .apk. 12211 res.removedInfo.args = createInstallArgsForExisting(0, 12212 deletedPackage.applicationInfo.getCodePath(), 12213 deletedPackage.applicationInfo.getResourcePath(), 12214 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12215 } else { 12216 res.removedInfo.args = null; 12217 } 12218 } 12219 12220 // Successfully disabled the old package. Now proceed with re-installation 12221 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12222 12223 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12224 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12225 12226 PackageParser.Package newPackage = null; 12227 try { 12228 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12229 if (newPackage.mExtras != null) { 12230 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12231 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12232 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12233 12234 // is the update attempting to change shared user? that isn't going to work... 12235 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12236 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12237 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12238 + " to " + newPkgSetting.sharedUser); 12239 updatedSettings = true; 12240 } 12241 } 12242 12243 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12244 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12245 perUserInstalled, res, user); 12246 updatedSettings = true; 12247 } 12248 12249 } catch (PackageManagerException e) { 12250 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12251 } 12252 12253 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12254 // Re installation failed. Restore old information 12255 // Remove new pkg information 12256 if (newPackage != null) { 12257 removeInstalledPackageLI(newPackage, true); 12258 } 12259 // Add back the old system package 12260 try { 12261 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12262 } catch (PackageManagerException e) { 12263 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12264 } 12265 // Restore the old system information in Settings 12266 synchronized (mPackages) { 12267 if (disabledSystem) { 12268 mSettings.enableSystemPackageLPw(packageName); 12269 } 12270 if (updatedSettings) { 12271 mSettings.setInstallerPackageName(packageName, 12272 oldPkgSetting.installerPackageName); 12273 } 12274 mSettings.writeLPr(); 12275 } 12276 } 12277 } 12278 12279 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12280 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12281 UserHandle user) { 12282 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12283 12284 String pkgName = newPackage.packageName; 12285 synchronized (mPackages) { 12286 //write settings. the installStatus will be incomplete at this stage. 12287 //note that the new package setting would have already been 12288 //added to mPackages. It hasn't been persisted yet. 12289 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12290 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12291 mSettings.writeLPr(); 12292 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12293 } 12294 12295 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12296 synchronized (mPackages) { 12297 updatePermissionsLPw(newPackage.packageName, newPackage, 12298 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12299 ? UPDATE_PERMISSIONS_ALL : 0)); 12300 // For system-bundled packages, we assume that installing an upgraded version 12301 // of the package implies that the user actually wants to run that new code, 12302 // so we enable the package. 12303 PackageSetting ps = mSettings.mPackages.get(pkgName); 12304 if (ps != null) { 12305 if (isSystemApp(newPackage)) { 12306 // NB: implicit assumption that system package upgrades apply to all users 12307 if (DEBUG_INSTALL) { 12308 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12309 } 12310 if (res.origUsers != null) { 12311 for (int userHandle : res.origUsers) { 12312 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12313 userHandle, installerPackageName); 12314 } 12315 } 12316 // Also convey the prior install/uninstall state 12317 if (allUsers != null && perUserInstalled != null) { 12318 for (int i = 0; i < allUsers.length; i++) { 12319 if (DEBUG_INSTALL) { 12320 Slog.d(TAG, " user " + allUsers[i] 12321 + " => " + perUserInstalled[i]); 12322 } 12323 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12324 } 12325 // these install state changes will be persisted in the 12326 // upcoming call to mSettings.writeLPr(). 12327 } 12328 } 12329 // It's implied that when a user requests installation, they want the app to be 12330 // installed and enabled. 12331 int userId = user.getIdentifier(); 12332 if (userId != UserHandle.USER_ALL) { 12333 ps.setInstalled(true, userId); 12334 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12335 } 12336 } 12337 res.name = pkgName; 12338 res.uid = newPackage.applicationInfo.uid; 12339 res.pkg = newPackage; 12340 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12341 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12342 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12343 //to update install status 12344 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12345 mSettings.writeLPr(); 12346 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12347 } 12348 12349 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12350 } 12351 12352 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12353 try { 12354 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12355 installPackageLI(args, res); 12356 } finally { 12357 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12358 } 12359 } 12360 12361 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12362 final int installFlags = args.installFlags; 12363 final String installerPackageName = args.installerPackageName; 12364 final String volumeUuid = args.volumeUuid; 12365 final File tmpPackageFile = new File(args.getCodePath()); 12366 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12367 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12368 || (args.volumeUuid != null)); 12369 boolean replace = false; 12370 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12371 if (args.move != null) { 12372 // moving a complete application; perfom an initial scan on the new install location 12373 scanFlags |= SCAN_INITIAL; 12374 } 12375 // Result object to be returned 12376 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12377 12378 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12379 12380 // Retrieve PackageSettings and parse package 12381 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12382 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12383 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12384 PackageParser pp = new PackageParser(); 12385 pp.setSeparateProcesses(mSeparateProcesses); 12386 pp.setDisplayMetrics(mMetrics); 12387 12388 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12389 final PackageParser.Package pkg; 12390 try { 12391 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12392 } catch (PackageParserException e) { 12393 res.setError("Failed parse during installPackageLI", e); 12394 return; 12395 } finally { 12396 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12397 } 12398 12399 // Mark that we have an install time CPU ABI override. 12400 pkg.cpuAbiOverride = args.abiOverride; 12401 12402 String pkgName = res.name = pkg.packageName; 12403 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12404 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12405 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12406 return; 12407 } 12408 } 12409 12410 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12411 try { 12412 pp.collectCertificates(pkg, parseFlags); 12413 pp.collectManifestDigest(pkg); 12414 } catch (PackageParserException e) { 12415 res.setError("Failed collect during installPackageLI", e); 12416 return; 12417 } finally { 12418 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12419 } 12420 12421 /* If the installer passed in a manifest digest, compare it now. */ 12422 if (args.manifestDigest != null) { 12423 if (DEBUG_INSTALL) { 12424 final String parsedManifest = pkg.manifestDigest == null ? "null" 12425 : pkg.manifestDigest.toString(); 12426 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12427 + parsedManifest); 12428 } 12429 12430 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12431 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12432 return; 12433 } 12434 } else if (DEBUG_INSTALL) { 12435 final String parsedManifest = pkg.manifestDigest == null 12436 ? "null" : pkg.manifestDigest.toString(); 12437 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12438 } 12439 12440 // Get rid of all references to package scan path via parser. 12441 pp = null; 12442 String oldCodePath = null; 12443 boolean systemApp = false; 12444 synchronized (mPackages) { 12445 // Check if installing already existing package 12446 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12447 String oldName = mSettings.mRenamedPackages.get(pkgName); 12448 if (pkg.mOriginalPackages != null 12449 && pkg.mOriginalPackages.contains(oldName) 12450 && mPackages.containsKey(oldName)) { 12451 // This package is derived from an original package, 12452 // and this device has been updating from that original 12453 // name. We must continue using the original name, so 12454 // rename the new package here. 12455 pkg.setPackageName(oldName); 12456 pkgName = pkg.packageName; 12457 replace = true; 12458 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12459 + oldName + " pkgName=" + pkgName); 12460 } else if (mPackages.containsKey(pkgName)) { 12461 // This package, under its official name, already exists 12462 // on the device; we should replace it. 12463 replace = true; 12464 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12465 } 12466 12467 // Prevent apps opting out from runtime permissions 12468 if (replace) { 12469 PackageParser.Package oldPackage = mPackages.get(pkgName); 12470 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12471 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12472 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12473 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12474 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12475 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12476 + " doesn't support runtime permissions but the old" 12477 + " target SDK " + oldTargetSdk + " does."); 12478 return; 12479 } 12480 } 12481 } 12482 12483 PackageSetting ps = mSettings.mPackages.get(pkgName); 12484 if (ps != null) { 12485 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12486 12487 // Quick sanity check that we're signed correctly if updating; 12488 // we'll check this again later when scanning, but we want to 12489 // bail early here before tripping over redefined permissions. 12490 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12491 if (!checkUpgradeKeySetLP(ps, pkg)) { 12492 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12493 + pkg.packageName + " upgrade keys do not match the " 12494 + "previously installed version"); 12495 return; 12496 } 12497 } else { 12498 try { 12499 verifySignaturesLP(ps, pkg); 12500 } catch (PackageManagerException e) { 12501 res.setError(e.error, e.getMessage()); 12502 return; 12503 } 12504 } 12505 12506 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12507 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12508 systemApp = (ps.pkg.applicationInfo.flags & 12509 ApplicationInfo.FLAG_SYSTEM) != 0; 12510 } 12511 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12512 } 12513 12514 // Check whether the newly-scanned package wants to define an already-defined perm 12515 int N = pkg.permissions.size(); 12516 for (int i = N-1; i >= 0; i--) { 12517 PackageParser.Permission perm = pkg.permissions.get(i); 12518 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12519 if (bp != null) { 12520 // If the defining package is signed with our cert, it's okay. This 12521 // also includes the "updating the same package" case, of course. 12522 // "updating same package" could also involve key-rotation. 12523 final boolean sigsOk; 12524 if (bp.sourcePackage.equals(pkg.packageName) 12525 && (bp.packageSetting instanceof PackageSetting) 12526 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12527 scanFlags))) { 12528 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12529 } else { 12530 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12531 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12532 } 12533 if (!sigsOk) { 12534 // If the owning package is the system itself, we log but allow 12535 // install to proceed; we fail the install on all other permission 12536 // redefinitions. 12537 if (!bp.sourcePackage.equals("android")) { 12538 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12539 + pkg.packageName + " attempting to redeclare permission " 12540 + perm.info.name + " already owned by " + bp.sourcePackage); 12541 res.origPermission = perm.info.name; 12542 res.origPackage = bp.sourcePackage; 12543 return; 12544 } else { 12545 Slog.w(TAG, "Package " + pkg.packageName 12546 + " attempting to redeclare system permission " 12547 + perm.info.name + "; ignoring new declaration"); 12548 pkg.permissions.remove(i); 12549 } 12550 } 12551 } 12552 } 12553 12554 } 12555 12556 if (systemApp && onExternal) { 12557 // Disable updates to system apps on sdcard 12558 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12559 "Cannot install updates to system apps on sdcard"); 12560 return; 12561 } 12562 12563 if (args.move != null) { 12564 // We did an in-place move, so dex is ready to roll 12565 scanFlags |= SCAN_NO_DEX; 12566 scanFlags |= SCAN_MOVE; 12567 12568 synchronized (mPackages) { 12569 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12570 if (ps == null) { 12571 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12572 "Missing settings for moved package " + pkgName); 12573 } 12574 12575 // We moved the entire application as-is, so bring over the 12576 // previously derived ABI information. 12577 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12578 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12579 } 12580 12581 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12582 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12583 scanFlags |= SCAN_NO_DEX; 12584 12585 try { 12586 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12587 true /* extract libs */); 12588 } catch (PackageManagerException pme) { 12589 Slog.e(TAG, "Error deriving application ABI", pme); 12590 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12591 return; 12592 } 12593 12594 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12595 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12596 12597 int result = mPackageDexOptimizer 12598 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12599 false /* defer */, false /* inclDependencies */); 12600 12601 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12602 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12603 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12604 return; 12605 } 12606 } 12607 12608 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12609 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12610 return; 12611 } 12612 12613 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12614 12615 if (replace) { 12616 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12617 installerPackageName, volumeUuid, res); 12618 } else { 12619 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12620 args.user, installerPackageName, volumeUuid, res); 12621 } 12622 synchronized (mPackages) { 12623 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12624 if (ps != null) { 12625 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12626 } 12627 } 12628 } 12629 12630 private void startIntentFilterVerifications(int userId, boolean replacing, 12631 PackageParser.Package pkg) { 12632 if (mIntentFilterVerifierComponent == null) { 12633 Slog.w(TAG, "No IntentFilter verification will not be done as " 12634 + "there is no IntentFilterVerifier available!"); 12635 return; 12636 } 12637 12638 final int verifierUid = getPackageUid( 12639 mIntentFilterVerifierComponent.getPackageName(), 12640 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12641 12642 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12643 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12644 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12645 mHandler.sendMessage(msg); 12646 } 12647 12648 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12649 PackageParser.Package pkg) { 12650 int size = pkg.activities.size(); 12651 if (size == 0) { 12652 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12653 "No activity, so no need to verify any IntentFilter!"); 12654 return; 12655 } 12656 12657 final boolean hasDomainURLs = hasDomainURLs(pkg); 12658 if (!hasDomainURLs) { 12659 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12660 "No domain URLs, so no need to verify any IntentFilter!"); 12661 return; 12662 } 12663 12664 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12665 + " if any IntentFilter from the " + size 12666 + " Activities needs verification ..."); 12667 12668 int count = 0; 12669 final String packageName = pkg.packageName; 12670 12671 synchronized (mPackages) { 12672 // If this is a new install and we see that we've already run verification for this 12673 // package, we have nothing to do: it means the state was restored from backup. 12674 if (!replacing) { 12675 IntentFilterVerificationInfo ivi = 12676 mSettings.getIntentFilterVerificationLPr(packageName); 12677 if (ivi != null) { 12678 if (DEBUG_DOMAIN_VERIFICATION) { 12679 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12680 + ivi.getStatusString()); 12681 } 12682 return; 12683 } 12684 } 12685 12686 // If any filters need to be verified, then all need to be. 12687 boolean needToVerify = false; 12688 for (PackageParser.Activity a : pkg.activities) { 12689 for (ActivityIntentInfo filter : a.intents) { 12690 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12691 if (DEBUG_DOMAIN_VERIFICATION) { 12692 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12693 } 12694 needToVerify = true; 12695 break; 12696 } 12697 } 12698 } 12699 12700 if (needToVerify) { 12701 final int verificationId = mIntentFilterVerificationToken++; 12702 for (PackageParser.Activity a : pkg.activities) { 12703 for (ActivityIntentInfo filter : a.intents) { 12704 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12705 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12706 "Verification needed for IntentFilter:" + filter.toString()); 12707 mIntentFilterVerifier.addOneIntentFilterVerification( 12708 verifierUid, userId, verificationId, filter, packageName); 12709 count++; 12710 } 12711 } 12712 } 12713 } 12714 } 12715 12716 if (count > 0) { 12717 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12718 + " IntentFilter verification" + (count > 1 ? "s" : "") 12719 + " for userId:" + userId); 12720 mIntentFilterVerifier.startVerifications(userId); 12721 } else { 12722 if (DEBUG_DOMAIN_VERIFICATION) { 12723 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12724 } 12725 } 12726 } 12727 12728 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12729 final ComponentName cn = filter.activity.getComponentName(); 12730 final String packageName = cn.getPackageName(); 12731 12732 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12733 packageName); 12734 if (ivi == null) { 12735 return true; 12736 } 12737 int status = ivi.getStatus(); 12738 switch (status) { 12739 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12740 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12741 return true; 12742 12743 default: 12744 // Nothing to do 12745 return false; 12746 } 12747 } 12748 12749 private static boolean isMultiArch(PackageSetting ps) { 12750 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12751 } 12752 12753 private static boolean isMultiArch(ApplicationInfo info) { 12754 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12755 } 12756 12757 private static boolean isExternal(PackageParser.Package pkg) { 12758 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12759 } 12760 12761 private static boolean isExternal(PackageSetting ps) { 12762 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12763 } 12764 12765 private static boolean isExternal(ApplicationInfo info) { 12766 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12767 } 12768 12769 private static boolean isSystemApp(PackageParser.Package pkg) { 12770 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12771 } 12772 12773 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12774 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12775 } 12776 12777 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12778 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12779 } 12780 12781 private static boolean isSystemApp(PackageSetting ps) { 12782 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12783 } 12784 12785 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12786 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12787 } 12788 12789 private int packageFlagsToInstallFlags(PackageSetting ps) { 12790 int installFlags = 0; 12791 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12792 // This existing package was an external ASEC install when we have 12793 // the external flag without a UUID 12794 installFlags |= PackageManager.INSTALL_EXTERNAL; 12795 } 12796 if (ps.isForwardLocked()) { 12797 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12798 } 12799 return installFlags; 12800 } 12801 12802 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12803 if (isExternal(pkg)) { 12804 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12805 return mSettings.getExternalVersion(); 12806 } else { 12807 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12808 } 12809 } else { 12810 return mSettings.getInternalVersion(); 12811 } 12812 } 12813 12814 private void deleteTempPackageFiles() { 12815 final FilenameFilter filter = new FilenameFilter() { 12816 public boolean accept(File dir, String name) { 12817 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12818 } 12819 }; 12820 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12821 file.delete(); 12822 } 12823 } 12824 12825 @Override 12826 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12827 int flags) { 12828 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12829 flags); 12830 } 12831 12832 @Override 12833 public void deletePackage(final String packageName, 12834 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12835 mContext.enforceCallingOrSelfPermission( 12836 android.Manifest.permission.DELETE_PACKAGES, null); 12837 Preconditions.checkNotNull(packageName); 12838 Preconditions.checkNotNull(observer); 12839 final int uid = Binder.getCallingUid(); 12840 if (UserHandle.getUserId(uid) != userId) { 12841 mContext.enforceCallingPermission( 12842 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12843 "deletePackage for user " + userId); 12844 } 12845 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12846 try { 12847 observer.onPackageDeleted(packageName, 12848 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12849 } catch (RemoteException re) { 12850 } 12851 return; 12852 } 12853 12854 boolean uninstallBlocked = false; 12855 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12856 int[] users = sUserManager.getUserIds(); 12857 for (int i = 0; i < users.length; ++i) { 12858 if (getBlockUninstallForUser(packageName, users[i])) { 12859 uninstallBlocked = true; 12860 break; 12861 } 12862 } 12863 } else { 12864 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12865 } 12866 if (uninstallBlocked) { 12867 try { 12868 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12869 null); 12870 } catch (RemoteException re) { 12871 } 12872 return; 12873 } 12874 12875 if (DEBUG_REMOVE) { 12876 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12877 } 12878 // Queue up an async operation since the package deletion may take a little while. 12879 mHandler.post(new Runnable() { 12880 public void run() { 12881 mHandler.removeCallbacks(this); 12882 final int returnCode = deletePackageX(packageName, userId, flags); 12883 if (observer != null) { 12884 try { 12885 observer.onPackageDeleted(packageName, returnCode, null); 12886 } catch (RemoteException e) { 12887 Log.i(TAG, "Observer no longer exists."); 12888 } //end catch 12889 } //end if 12890 } //end run 12891 }); 12892 } 12893 12894 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12895 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12896 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12897 try { 12898 if (dpm != null) { 12899 if (dpm.isDeviceOwner(packageName)) { 12900 return true; 12901 } 12902 int[] users; 12903 if (userId == UserHandle.USER_ALL) { 12904 users = sUserManager.getUserIds(); 12905 } else { 12906 users = new int[]{userId}; 12907 } 12908 for (int i = 0; i < users.length; ++i) { 12909 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12910 return true; 12911 } 12912 } 12913 } 12914 } catch (RemoteException e) { 12915 } 12916 return false; 12917 } 12918 12919 /** 12920 * This method is an internal method that could be get invoked either 12921 * to delete an installed package or to clean up a failed installation. 12922 * After deleting an installed package, a broadcast is sent to notify any 12923 * listeners that the package has been installed. For cleaning up a failed 12924 * installation, the broadcast is not necessary since the package's 12925 * installation wouldn't have sent the initial broadcast either 12926 * The key steps in deleting a package are 12927 * deleting the package information in internal structures like mPackages, 12928 * deleting the packages base directories through installd 12929 * updating mSettings to reflect current status 12930 * persisting settings for later use 12931 * sending a broadcast if necessary 12932 */ 12933 private int deletePackageX(String packageName, int userId, int flags) { 12934 final PackageRemovedInfo info = new PackageRemovedInfo(); 12935 final boolean res; 12936 12937 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12938 ? UserHandle.ALL : new UserHandle(userId); 12939 12940 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12941 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12942 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12943 } 12944 12945 boolean removedForAllUsers = false; 12946 boolean systemUpdate = false; 12947 12948 // for the uninstall-updates case and restricted profiles, remember the per- 12949 // userhandle installed state 12950 int[] allUsers; 12951 boolean[] perUserInstalled; 12952 synchronized (mPackages) { 12953 PackageSetting ps = mSettings.mPackages.get(packageName); 12954 allUsers = sUserManager.getUserIds(); 12955 perUserInstalled = new boolean[allUsers.length]; 12956 for (int i = 0; i < allUsers.length; i++) { 12957 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12958 } 12959 } 12960 12961 synchronized (mInstallLock) { 12962 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12963 res = deletePackageLI(packageName, removeForUser, 12964 true, allUsers, perUserInstalled, 12965 flags | REMOVE_CHATTY, info, true); 12966 systemUpdate = info.isRemovedPackageSystemUpdate; 12967 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12968 removedForAllUsers = true; 12969 } 12970 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12971 + " removedForAllUsers=" + removedForAllUsers); 12972 } 12973 12974 if (res) { 12975 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12976 12977 // If the removed package was a system update, the old system package 12978 // was re-enabled; we need to broadcast this information 12979 if (systemUpdate) { 12980 Bundle extras = new Bundle(1); 12981 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12982 ? info.removedAppId : info.uid); 12983 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12984 12985 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12986 extras, null, null, null); 12987 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12988 extras, null, null, null); 12989 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12990 null, packageName, null, null); 12991 } 12992 } 12993 // Force a gc here. 12994 Runtime.getRuntime().gc(); 12995 // Delete the resources here after sending the broadcast to let 12996 // other processes clean up before deleting resources. 12997 if (info.args != null) { 12998 synchronized (mInstallLock) { 12999 info.args.doPostDeleteLI(true); 13000 } 13001 } 13002 13003 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13004 } 13005 13006 class PackageRemovedInfo { 13007 String removedPackage; 13008 int uid = -1; 13009 int removedAppId = -1; 13010 int[] removedUsers = null; 13011 boolean isRemovedPackageSystemUpdate = false; 13012 // Clean up resources deleted packages. 13013 InstallArgs args = null; 13014 13015 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13016 Bundle extras = new Bundle(1); 13017 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13018 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13019 if (replacing) { 13020 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13021 } 13022 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13023 if (removedPackage != null) { 13024 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13025 extras, null, null, removedUsers); 13026 if (fullRemove && !replacing) { 13027 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13028 extras, null, null, removedUsers); 13029 } 13030 } 13031 if (removedAppId >= 0) { 13032 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 13033 removedUsers); 13034 } 13035 } 13036 } 13037 13038 /* 13039 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13040 * flag is not set, the data directory is removed as well. 13041 * make sure this flag is set for partially installed apps. If not its meaningless to 13042 * delete a partially installed application. 13043 */ 13044 private void removePackageDataLI(PackageSetting ps, 13045 int[] allUserHandles, boolean[] perUserInstalled, 13046 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13047 String packageName = ps.name; 13048 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13049 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13050 // Retrieve object to delete permissions for shared user later on 13051 final PackageSetting deletedPs; 13052 // reader 13053 synchronized (mPackages) { 13054 deletedPs = mSettings.mPackages.get(packageName); 13055 if (outInfo != null) { 13056 outInfo.removedPackage = packageName; 13057 outInfo.removedUsers = deletedPs != null 13058 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13059 : null; 13060 } 13061 } 13062 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13063 removeDataDirsLI(ps.volumeUuid, packageName); 13064 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13065 } 13066 // writer 13067 synchronized (mPackages) { 13068 if (deletedPs != null) { 13069 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13070 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13071 clearDefaultBrowserIfNeeded(packageName); 13072 if (outInfo != null) { 13073 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13074 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13075 } 13076 updatePermissionsLPw(deletedPs.name, null, 0); 13077 if (deletedPs.sharedUser != null) { 13078 // Remove permissions associated with package. Since runtime 13079 // permissions are per user we have to kill the removed package 13080 // or packages running under the shared user of the removed 13081 // package if revoking the permissions requested only by the removed 13082 // package is successful and this causes a change in gids. 13083 for (int userId : UserManagerService.getInstance().getUserIds()) { 13084 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13085 userId); 13086 if (userIdToKill == UserHandle.USER_ALL 13087 || userIdToKill >= UserHandle.USER_OWNER) { 13088 // If gids changed for this user, kill all affected packages. 13089 mHandler.post(new Runnable() { 13090 @Override 13091 public void run() { 13092 // This has to happen with no lock held. 13093 killApplication(deletedPs.name, deletedPs.appId, 13094 KILL_APP_REASON_GIDS_CHANGED); 13095 } 13096 }); 13097 break; 13098 } 13099 } 13100 } 13101 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13102 } 13103 // make sure to preserve per-user disabled state if this removal was just 13104 // a downgrade of a system app to the factory package 13105 if (allUserHandles != null && perUserInstalled != null) { 13106 if (DEBUG_REMOVE) { 13107 Slog.d(TAG, "Propagating install state across downgrade"); 13108 } 13109 for (int i = 0; i < allUserHandles.length; i++) { 13110 if (DEBUG_REMOVE) { 13111 Slog.d(TAG, " user " + allUserHandles[i] 13112 + " => " + perUserInstalled[i]); 13113 } 13114 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13115 } 13116 } 13117 } 13118 // can downgrade to reader 13119 if (writeSettings) { 13120 // Save settings now 13121 mSettings.writeLPr(); 13122 } 13123 } 13124 if (outInfo != null) { 13125 // A user ID was deleted here. Go through all users and remove it 13126 // from KeyStore. 13127 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13128 } 13129 } 13130 13131 static boolean locationIsPrivileged(File path) { 13132 try { 13133 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13134 .getCanonicalPath(); 13135 return path.getCanonicalPath().startsWith(privilegedAppDir); 13136 } catch (IOException e) { 13137 Slog.e(TAG, "Unable to access code path " + path); 13138 } 13139 return false; 13140 } 13141 13142 /* 13143 * Tries to delete system package. 13144 */ 13145 private boolean deleteSystemPackageLI(PackageSetting newPs, 13146 int[] allUserHandles, boolean[] perUserInstalled, 13147 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13148 final boolean applyUserRestrictions 13149 = (allUserHandles != null) && (perUserInstalled != null); 13150 PackageSetting disabledPs = null; 13151 // Confirm if the system package has been updated 13152 // An updated system app can be deleted. This will also have to restore 13153 // the system pkg from system partition 13154 // reader 13155 synchronized (mPackages) { 13156 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13157 } 13158 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13159 + " disabledPs=" + disabledPs); 13160 if (disabledPs == null) { 13161 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13162 return false; 13163 } else if (DEBUG_REMOVE) { 13164 Slog.d(TAG, "Deleting system pkg from data partition"); 13165 } 13166 if (DEBUG_REMOVE) { 13167 if (applyUserRestrictions) { 13168 Slog.d(TAG, "Remembering install states:"); 13169 for (int i = 0; i < allUserHandles.length; i++) { 13170 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13171 } 13172 } 13173 } 13174 // Delete the updated package 13175 outInfo.isRemovedPackageSystemUpdate = true; 13176 if (disabledPs.versionCode < newPs.versionCode) { 13177 // Delete data for downgrades 13178 flags &= ~PackageManager.DELETE_KEEP_DATA; 13179 } else { 13180 // Preserve data by setting flag 13181 flags |= PackageManager.DELETE_KEEP_DATA; 13182 } 13183 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13184 allUserHandles, perUserInstalled, outInfo, writeSettings); 13185 if (!ret) { 13186 return false; 13187 } 13188 // writer 13189 synchronized (mPackages) { 13190 // Reinstate the old system package 13191 mSettings.enableSystemPackageLPw(newPs.name); 13192 // Remove any native libraries from the upgraded package. 13193 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13194 } 13195 // Install the system package 13196 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13197 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13198 if (locationIsPrivileged(disabledPs.codePath)) { 13199 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13200 } 13201 13202 final PackageParser.Package newPkg; 13203 try { 13204 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13205 } catch (PackageManagerException e) { 13206 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13207 return false; 13208 } 13209 13210 // writer 13211 synchronized (mPackages) { 13212 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13213 13214 // Propagate the permissions state as we do not want to drop on the floor 13215 // runtime permissions. The update permissions method below will take 13216 // care of removing obsolete permissions and grant install permissions. 13217 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13218 updatePermissionsLPw(newPkg.packageName, newPkg, 13219 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13220 13221 if (applyUserRestrictions) { 13222 if (DEBUG_REMOVE) { 13223 Slog.d(TAG, "Propagating install state across reinstall"); 13224 } 13225 for (int i = 0; i < allUserHandles.length; i++) { 13226 if (DEBUG_REMOVE) { 13227 Slog.d(TAG, " user " + allUserHandles[i] 13228 + " => " + perUserInstalled[i]); 13229 } 13230 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13231 13232 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13233 } 13234 // Regardless of writeSettings we need to ensure that this restriction 13235 // state propagation is persisted 13236 mSettings.writeAllUsersPackageRestrictionsLPr(); 13237 } 13238 // can downgrade to reader here 13239 if (writeSettings) { 13240 mSettings.writeLPr(); 13241 } 13242 } 13243 return true; 13244 } 13245 13246 private boolean deleteInstalledPackageLI(PackageSetting ps, 13247 boolean deleteCodeAndResources, int flags, 13248 int[] allUserHandles, boolean[] perUserInstalled, 13249 PackageRemovedInfo outInfo, boolean writeSettings) { 13250 if (outInfo != null) { 13251 outInfo.uid = ps.appId; 13252 } 13253 13254 // Delete package data from internal structures and also remove data if flag is set 13255 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13256 13257 // Delete application code and resources 13258 if (deleteCodeAndResources && (outInfo != null)) { 13259 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13260 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13261 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13262 } 13263 return true; 13264 } 13265 13266 @Override 13267 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13268 int userId) { 13269 mContext.enforceCallingOrSelfPermission( 13270 android.Manifest.permission.DELETE_PACKAGES, null); 13271 synchronized (mPackages) { 13272 PackageSetting ps = mSettings.mPackages.get(packageName); 13273 if (ps == null) { 13274 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13275 return false; 13276 } 13277 if (!ps.getInstalled(userId)) { 13278 // Can't block uninstall for an app that is not installed or enabled. 13279 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13280 return false; 13281 } 13282 ps.setBlockUninstall(blockUninstall, userId); 13283 mSettings.writePackageRestrictionsLPr(userId); 13284 } 13285 return true; 13286 } 13287 13288 @Override 13289 public boolean getBlockUninstallForUser(String packageName, int userId) { 13290 synchronized (mPackages) { 13291 PackageSetting ps = mSettings.mPackages.get(packageName); 13292 if (ps == null) { 13293 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13294 return false; 13295 } 13296 return ps.getBlockUninstall(userId); 13297 } 13298 } 13299 13300 /* 13301 * This method handles package deletion in general 13302 */ 13303 private boolean deletePackageLI(String packageName, UserHandle user, 13304 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13305 int flags, PackageRemovedInfo outInfo, 13306 boolean writeSettings) { 13307 if (packageName == null) { 13308 Slog.w(TAG, "Attempt to delete null packageName."); 13309 return false; 13310 } 13311 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13312 PackageSetting ps; 13313 boolean dataOnly = false; 13314 int removeUser = -1; 13315 int appId = -1; 13316 synchronized (mPackages) { 13317 ps = mSettings.mPackages.get(packageName); 13318 if (ps == null) { 13319 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13320 return false; 13321 } 13322 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13323 && user.getIdentifier() != UserHandle.USER_ALL) { 13324 // The caller is asking that the package only be deleted for a single 13325 // user. To do this, we just mark its uninstalled state and delete 13326 // its data. If this is a system app, we only allow this to happen if 13327 // they have set the special DELETE_SYSTEM_APP which requests different 13328 // semantics than normal for uninstalling system apps. 13329 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13330 final int userId = user.getIdentifier(); 13331 ps.setUserState(userId, 13332 COMPONENT_ENABLED_STATE_DEFAULT, 13333 false, //installed 13334 true, //stopped 13335 true, //notLaunched 13336 false, //hidden 13337 null, null, null, 13338 false, // blockUninstall 13339 ps.readUserState(userId).domainVerificationStatus, 0); 13340 if (!isSystemApp(ps)) { 13341 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13342 // Other user still have this package installed, so all 13343 // we need to do is clear this user's data and save that 13344 // it is uninstalled. 13345 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13346 removeUser = user.getIdentifier(); 13347 appId = ps.appId; 13348 scheduleWritePackageRestrictionsLocked(removeUser); 13349 } else { 13350 // We need to set it back to 'installed' so the uninstall 13351 // broadcasts will be sent correctly. 13352 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13353 ps.setInstalled(true, user.getIdentifier()); 13354 } 13355 } else { 13356 // This is a system app, so we assume that the 13357 // other users still have this package installed, so all 13358 // we need to do is clear this user's data and save that 13359 // it is uninstalled. 13360 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13361 removeUser = user.getIdentifier(); 13362 appId = ps.appId; 13363 scheduleWritePackageRestrictionsLocked(removeUser); 13364 } 13365 } 13366 } 13367 13368 if (removeUser >= 0) { 13369 // From above, we determined that we are deleting this only 13370 // for a single user. Continue the work here. 13371 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13372 if (outInfo != null) { 13373 outInfo.removedPackage = packageName; 13374 outInfo.removedAppId = appId; 13375 outInfo.removedUsers = new int[] {removeUser}; 13376 } 13377 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13378 removeKeystoreDataIfNeeded(removeUser, appId); 13379 schedulePackageCleaning(packageName, removeUser, false); 13380 synchronized (mPackages) { 13381 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13382 scheduleWritePackageRestrictionsLocked(removeUser); 13383 } 13384 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13385 } 13386 return true; 13387 } 13388 13389 if (dataOnly) { 13390 // Delete application data first 13391 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13392 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13393 return true; 13394 } 13395 13396 boolean ret = false; 13397 if (isSystemApp(ps)) { 13398 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13399 // When an updated system application is deleted we delete the existing resources as well and 13400 // fall back to existing code in system partition 13401 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13402 flags, outInfo, writeSettings); 13403 } else { 13404 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13405 // Kill application pre-emptively especially for apps on sd. 13406 killApplication(packageName, ps.appId, "uninstall pkg"); 13407 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13408 allUserHandles, perUserInstalled, 13409 outInfo, writeSettings); 13410 } 13411 13412 return ret; 13413 } 13414 13415 private final class ClearStorageConnection implements ServiceConnection { 13416 IMediaContainerService mContainerService; 13417 13418 @Override 13419 public void onServiceConnected(ComponentName name, IBinder service) { 13420 synchronized (this) { 13421 mContainerService = IMediaContainerService.Stub.asInterface(service); 13422 notifyAll(); 13423 } 13424 } 13425 13426 @Override 13427 public void onServiceDisconnected(ComponentName name) { 13428 } 13429 } 13430 13431 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13432 final boolean mounted; 13433 if (Environment.isExternalStorageEmulated()) { 13434 mounted = true; 13435 } else { 13436 final String status = Environment.getExternalStorageState(); 13437 13438 mounted = status.equals(Environment.MEDIA_MOUNTED) 13439 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13440 } 13441 13442 if (!mounted) { 13443 return; 13444 } 13445 13446 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13447 int[] users; 13448 if (userId == UserHandle.USER_ALL) { 13449 users = sUserManager.getUserIds(); 13450 } else { 13451 users = new int[] { userId }; 13452 } 13453 final ClearStorageConnection conn = new ClearStorageConnection(); 13454 if (mContext.bindServiceAsUser( 13455 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13456 try { 13457 for (int curUser : users) { 13458 long timeout = SystemClock.uptimeMillis() + 5000; 13459 synchronized (conn) { 13460 long now = SystemClock.uptimeMillis(); 13461 while (conn.mContainerService == null && now < timeout) { 13462 try { 13463 conn.wait(timeout - now); 13464 } catch (InterruptedException e) { 13465 } 13466 } 13467 } 13468 if (conn.mContainerService == null) { 13469 return; 13470 } 13471 13472 final UserEnvironment userEnv = new UserEnvironment(curUser); 13473 clearDirectory(conn.mContainerService, 13474 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13475 if (allData) { 13476 clearDirectory(conn.mContainerService, 13477 userEnv.buildExternalStorageAppDataDirs(packageName)); 13478 clearDirectory(conn.mContainerService, 13479 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13480 } 13481 } 13482 } finally { 13483 mContext.unbindService(conn); 13484 } 13485 } 13486 } 13487 13488 @Override 13489 public void clearApplicationUserData(final String packageName, 13490 final IPackageDataObserver observer, final int userId) { 13491 mContext.enforceCallingOrSelfPermission( 13492 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13493 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13494 // Queue up an async operation since the package deletion may take a little while. 13495 mHandler.post(new Runnable() { 13496 public void run() { 13497 mHandler.removeCallbacks(this); 13498 final boolean succeeded; 13499 synchronized (mInstallLock) { 13500 succeeded = clearApplicationUserDataLI(packageName, userId); 13501 } 13502 clearExternalStorageDataSync(packageName, userId, true); 13503 if (succeeded) { 13504 // invoke DeviceStorageMonitor's update method to clear any notifications 13505 DeviceStorageMonitorInternal 13506 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13507 if (dsm != null) { 13508 dsm.checkMemory(); 13509 } 13510 } 13511 if(observer != null) { 13512 try { 13513 observer.onRemoveCompleted(packageName, succeeded); 13514 } catch (RemoteException e) { 13515 Log.i(TAG, "Observer no longer exists."); 13516 } 13517 } //end if observer 13518 } //end run 13519 }); 13520 } 13521 13522 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13523 if (packageName == null) { 13524 Slog.w(TAG, "Attempt to delete null packageName."); 13525 return false; 13526 } 13527 13528 // Try finding details about the requested package 13529 PackageParser.Package pkg; 13530 synchronized (mPackages) { 13531 pkg = mPackages.get(packageName); 13532 if (pkg == null) { 13533 final PackageSetting ps = mSettings.mPackages.get(packageName); 13534 if (ps != null) { 13535 pkg = ps.pkg; 13536 } 13537 } 13538 13539 if (pkg == null) { 13540 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13541 return false; 13542 } 13543 13544 PackageSetting ps = (PackageSetting) pkg.mExtras; 13545 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13546 } 13547 13548 // Always delete data directories for package, even if we found no other 13549 // record of app. This helps users recover from UID mismatches without 13550 // resorting to a full data wipe. 13551 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13552 if (retCode < 0) { 13553 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13554 return false; 13555 } 13556 13557 final int appId = pkg.applicationInfo.uid; 13558 removeKeystoreDataIfNeeded(userId, appId); 13559 13560 // Create a native library symlink only if we have native libraries 13561 // and if the native libraries are 32 bit libraries. We do not provide 13562 // this symlink for 64 bit libraries. 13563 if (pkg.applicationInfo.primaryCpuAbi != null && 13564 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13565 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13566 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13567 nativeLibPath, userId) < 0) { 13568 Slog.w(TAG, "Failed linking native library dir"); 13569 return false; 13570 } 13571 } 13572 13573 return true; 13574 } 13575 13576 /** 13577 * Reverts user permission state changes (permissions and flags) in 13578 * all packages for a given user. 13579 * 13580 * @param userId The device user for which to do a reset. 13581 */ 13582 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13583 final int packageCount = mPackages.size(); 13584 for (int i = 0; i < packageCount; i++) { 13585 PackageParser.Package pkg = mPackages.valueAt(i); 13586 PackageSetting ps = (PackageSetting) pkg.mExtras; 13587 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13588 } 13589 } 13590 13591 /** 13592 * Reverts user permission state changes (permissions and flags). 13593 * 13594 * @param ps The package for which to reset. 13595 * @param userId The device user for which to do a reset. 13596 */ 13597 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13598 final PackageSetting ps, final int userId) { 13599 if (ps.pkg == null) { 13600 return; 13601 } 13602 13603 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13604 | FLAG_PERMISSION_USER_FIXED 13605 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13606 13607 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13608 | FLAG_PERMISSION_POLICY_FIXED; 13609 13610 boolean writeInstallPermissions = false; 13611 boolean writeRuntimePermissions = false; 13612 13613 final int permissionCount = ps.pkg.requestedPermissions.size(); 13614 for (int i = 0; i < permissionCount; i++) { 13615 String permission = ps.pkg.requestedPermissions.get(i); 13616 13617 BasePermission bp = mSettings.mPermissions.get(permission); 13618 if (bp == null) { 13619 continue; 13620 } 13621 13622 // If shared user we just reset the state to which only this app contributed. 13623 if (ps.sharedUser != null) { 13624 boolean used = false; 13625 final int packageCount = ps.sharedUser.packages.size(); 13626 for (int j = 0; j < packageCount; j++) { 13627 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13628 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13629 && pkg.pkg.requestedPermissions.contains(permission)) { 13630 used = true; 13631 break; 13632 } 13633 } 13634 if (used) { 13635 continue; 13636 } 13637 } 13638 13639 PermissionsState permissionsState = ps.getPermissionsState(); 13640 13641 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13642 13643 // Always clear the user settable flags. 13644 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13645 bp.name) != null; 13646 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13647 if (hasInstallState) { 13648 writeInstallPermissions = true; 13649 } else { 13650 writeRuntimePermissions = true; 13651 } 13652 } 13653 13654 // Below is only runtime permission handling. 13655 if (!bp.isRuntime()) { 13656 continue; 13657 } 13658 13659 // Never clobber system or policy. 13660 if ((oldFlags & policyOrSystemFlags) != 0) { 13661 continue; 13662 } 13663 13664 // If this permission was granted by default, make sure it is. 13665 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13666 if (permissionsState.grantRuntimePermission(bp, userId) 13667 != PERMISSION_OPERATION_FAILURE) { 13668 writeRuntimePermissions = true; 13669 } 13670 } else { 13671 // Otherwise, reset the permission. 13672 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13673 switch (revokeResult) { 13674 case PERMISSION_OPERATION_SUCCESS: { 13675 writeRuntimePermissions = true; 13676 } break; 13677 13678 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13679 writeRuntimePermissions = true; 13680 final int appId = ps.appId; 13681 mHandler.post(new Runnable() { 13682 @Override 13683 public void run() { 13684 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13685 } 13686 }); 13687 } break; 13688 } 13689 } 13690 } 13691 13692 // Synchronously write as we are taking permissions away. 13693 if (writeRuntimePermissions) { 13694 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13695 } 13696 13697 // Synchronously write as we are taking permissions away. 13698 if (writeInstallPermissions) { 13699 mSettings.writeLPr(); 13700 } 13701 } 13702 13703 /** 13704 * Remove entries from the keystore daemon. Will only remove it if the 13705 * {@code appId} is valid. 13706 */ 13707 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13708 if (appId < 0) { 13709 return; 13710 } 13711 13712 final KeyStore keyStore = KeyStore.getInstance(); 13713 if (keyStore != null) { 13714 if (userId == UserHandle.USER_ALL) { 13715 for (final int individual : sUserManager.getUserIds()) { 13716 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13717 } 13718 } else { 13719 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13720 } 13721 } else { 13722 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13723 } 13724 } 13725 13726 @Override 13727 public void deleteApplicationCacheFiles(final String packageName, 13728 final IPackageDataObserver observer) { 13729 mContext.enforceCallingOrSelfPermission( 13730 android.Manifest.permission.DELETE_CACHE_FILES, null); 13731 // Queue up an async operation since the package deletion may take a little while. 13732 final int userId = UserHandle.getCallingUserId(); 13733 mHandler.post(new Runnable() { 13734 public void run() { 13735 mHandler.removeCallbacks(this); 13736 final boolean succeded; 13737 synchronized (mInstallLock) { 13738 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13739 } 13740 clearExternalStorageDataSync(packageName, userId, false); 13741 if (observer != null) { 13742 try { 13743 observer.onRemoveCompleted(packageName, succeded); 13744 } catch (RemoteException e) { 13745 Log.i(TAG, "Observer no longer exists."); 13746 } 13747 } //end if observer 13748 } //end run 13749 }); 13750 } 13751 13752 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13753 if (packageName == null) { 13754 Slog.w(TAG, "Attempt to delete null packageName."); 13755 return false; 13756 } 13757 PackageParser.Package p; 13758 synchronized (mPackages) { 13759 p = mPackages.get(packageName); 13760 } 13761 if (p == null) { 13762 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13763 return false; 13764 } 13765 final ApplicationInfo applicationInfo = p.applicationInfo; 13766 if (applicationInfo == null) { 13767 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13768 return false; 13769 } 13770 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13771 if (retCode < 0) { 13772 Slog.w(TAG, "Couldn't remove cache files for package: " 13773 + packageName + " u" + userId); 13774 return false; 13775 } 13776 return true; 13777 } 13778 13779 @Override 13780 public void getPackageSizeInfo(final String packageName, int userHandle, 13781 final IPackageStatsObserver observer) { 13782 mContext.enforceCallingOrSelfPermission( 13783 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13784 if (packageName == null) { 13785 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13786 } 13787 13788 PackageStats stats = new PackageStats(packageName, userHandle); 13789 13790 /* 13791 * Queue up an async operation since the package measurement may take a 13792 * little while. 13793 */ 13794 Message msg = mHandler.obtainMessage(INIT_COPY); 13795 msg.obj = new MeasureParams(stats, observer); 13796 mHandler.sendMessage(msg); 13797 } 13798 13799 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13800 PackageStats pStats) { 13801 if (packageName == null) { 13802 Slog.w(TAG, "Attempt to get size of null packageName."); 13803 return false; 13804 } 13805 PackageParser.Package p; 13806 boolean dataOnly = false; 13807 String libDirRoot = null; 13808 String asecPath = null; 13809 PackageSetting ps = null; 13810 synchronized (mPackages) { 13811 p = mPackages.get(packageName); 13812 ps = mSettings.mPackages.get(packageName); 13813 if(p == null) { 13814 dataOnly = true; 13815 if((ps == null) || (ps.pkg == null)) { 13816 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13817 return false; 13818 } 13819 p = ps.pkg; 13820 } 13821 if (ps != null) { 13822 libDirRoot = ps.legacyNativeLibraryPathString; 13823 } 13824 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13825 final long token = Binder.clearCallingIdentity(); 13826 try { 13827 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13828 if (secureContainerId != null) { 13829 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13830 } 13831 } finally { 13832 Binder.restoreCallingIdentity(token); 13833 } 13834 } 13835 } 13836 String publicSrcDir = null; 13837 if(!dataOnly) { 13838 final ApplicationInfo applicationInfo = p.applicationInfo; 13839 if (applicationInfo == null) { 13840 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13841 return false; 13842 } 13843 if (p.isForwardLocked()) { 13844 publicSrcDir = applicationInfo.getBaseResourcePath(); 13845 } 13846 } 13847 // TODO: extend to measure size of split APKs 13848 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13849 // not just the first level. 13850 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13851 // just the primary. 13852 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13853 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13854 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13855 if (res < 0) { 13856 return false; 13857 } 13858 13859 // Fix-up for forward-locked applications in ASEC containers. 13860 if (!isExternal(p)) { 13861 pStats.codeSize += pStats.externalCodeSize; 13862 pStats.externalCodeSize = 0L; 13863 } 13864 13865 return true; 13866 } 13867 13868 13869 @Override 13870 public void addPackageToPreferred(String packageName) { 13871 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13872 } 13873 13874 @Override 13875 public void removePackageFromPreferred(String packageName) { 13876 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13877 } 13878 13879 @Override 13880 public List<PackageInfo> getPreferredPackages(int flags) { 13881 return new ArrayList<PackageInfo>(); 13882 } 13883 13884 private int getUidTargetSdkVersionLockedLPr(int uid) { 13885 Object obj = mSettings.getUserIdLPr(uid); 13886 if (obj instanceof SharedUserSetting) { 13887 final SharedUserSetting sus = (SharedUserSetting) obj; 13888 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13889 final Iterator<PackageSetting> it = sus.packages.iterator(); 13890 while (it.hasNext()) { 13891 final PackageSetting ps = it.next(); 13892 if (ps.pkg != null) { 13893 int v = ps.pkg.applicationInfo.targetSdkVersion; 13894 if (v < vers) vers = v; 13895 } 13896 } 13897 return vers; 13898 } else if (obj instanceof PackageSetting) { 13899 final PackageSetting ps = (PackageSetting) obj; 13900 if (ps.pkg != null) { 13901 return ps.pkg.applicationInfo.targetSdkVersion; 13902 } 13903 } 13904 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13905 } 13906 13907 @Override 13908 public void addPreferredActivity(IntentFilter filter, int match, 13909 ComponentName[] set, ComponentName activity, int userId) { 13910 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13911 "Adding preferred"); 13912 } 13913 13914 private void addPreferredActivityInternal(IntentFilter filter, int match, 13915 ComponentName[] set, ComponentName activity, boolean always, int userId, 13916 String opname) { 13917 // writer 13918 int callingUid = Binder.getCallingUid(); 13919 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13920 if (filter.countActions() == 0) { 13921 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13922 return; 13923 } 13924 synchronized (mPackages) { 13925 if (mContext.checkCallingOrSelfPermission( 13926 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13927 != PackageManager.PERMISSION_GRANTED) { 13928 if (getUidTargetSdkVersionLockedLPr(callingUid) 13929 < Build.VERSION_CODES.FROYO) { 13930 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13931 + callingUid); 13932 return; 13933 } 13934 mContext.enforceCallingOrSelfPermission( 13935 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13936 } 13937 13938 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13939 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13940 + userId + ":"); 13941 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13942 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13943 scheduleWritePackageRestrictionsLocked(userId); 13944 } 13945 } 13946 13947 @Override 13948 public void replacePreferredActivity(IntentFilter filter, int match, 13949 ComponentName[] set, ComponentName activity, int userId) { 13950 if (filter.countActions() != 1) { 13951 throw new IllegalArgumentException( 13952 "replacePreferredActivity expects filter to have only 1 action."); 13953 } 13954 if (filter.countDataAuthorities() != 0 13955 || filter.countDataPaths() != 0 13956 || filter.countDataSchemes() > 1 13957 || filter.countDataTypes() != 0) { 13958 throw new IllegalArgumentException( 13959 "replacePreferredActivity expects filter to have no data authorities, " + 13960 "paths, or types; and at most one scheme."); 13961 } 13962 13963 final int callingUid = Binder.getCallingUid(); 13964 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13965 synchronized (mPackages) { 13966 if (mContext.checkCallingOrSelfPermission( 13967 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13968 != PackageManager.PERMISSION_GRANTED) { 13969 if (getUidTargetSdkVersionLockedLPr(callingUid) 13970 < Build.VERSION_CODES.FROYO) { 13971 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13972 + Binder.getCallingUid()); 13973 return; 13974 } 13975 mContext.enforceCallingOrSelfPermission( 13976 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13977 } 13978 13979 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13980 if (pir != null) { 13981 // Get all of the existing entries that exactly match this filter. 13982 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13983 if (existing != null && existing.size() == 1) { 13984 PreferredActivity cur = existing.get(0); 13985 if (DEBUG_PREFERRED) { 13986 Slog.i(TAG, "Checking replace of preferred:"); 13987 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13988 if (!cur.mPref.mAlways) { 13989 Slog.i(TAG, " -- CUR; not mAlways!"); 13990 } else { 13991 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13992 Slog.i(TAG, " -- CUR: mSet=" 13993 + Arrays.toString(cur.mPref.mSetComponents)); 13994 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13995 Slog.i(TAG, " -- NEW: mMatch=" 13996 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13997 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13998 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13999 } 14000 } 14001 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14002 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14003 && cur.mPref.sameSet(set)) { 14004 // Setting the preferred activity to what it happens to be already 14005 if (DEBUG_PREFERRED) { 14006 Slog.i(TAG, "Replacing with same preferred activity " 14007 + cur.mPref.mShortComponent + " for user " 14008 + userId + ":"); 14009 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14010 } 14011 return; 14012 } 14013 } 14014 14015 if (existing != null) { 14016 if (DEBUG_PREFERRED) { 14017 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14018 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14019 } 14020 for (int i = 0; i < existing.size(); i++) { 14021 PreferredActivity pa = existing.get(i); 14022 if (DEBUG_PREFERRED) { 14023 Slog.i(TAG, "Removing existing preferred activity " 14024 + pa.mPref.mComponent + ":"); 14025 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14026 } 14027 pir.removeFilter(pa); 14028 } 14029 } 14030 } 14031 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14032 "Replacing preferred"); 14033 } 14034 } 14035 14036 @Override 14037 public void clearPackagePreferredActivities(String packageName) { 14038 final int uid = Binder.getCallingUid(); 14039 // writer 14040 synchronized (mPackages) { 14041 PackageParser.Package pkg = mPackages.get(packageName); 14042 if (pkg == null || pkg.applicationInfo.uid != uid) { 14043 if (mContext.checkCallingOrSelfPermission( 14044 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14045 != PackageManager.PERMISSION_GRANTED) { 14046 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14047 < Build.VERSION_CODES.FROYO) { 14048 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14049 + Binder.getCallingUid()); 14050 return; 14051 } 14052 mContext.enforceCallingOrSelfPermission( 14053 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14054 } 14055 } 14056 14057 int user = UserHandle.getCallingUserId(); 14058 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14059 scheduleWritePackageRestrictionsLocked(user); 14060 } 14061 } 14062 } 14063 14064 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14065 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14066 ArrayList<PreferredActivity> removed = null; 14067 boolean changed = false; 14068 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14069 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14070 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14071 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14072 continue; 14073 } 14074 Iterator<PreferredActivity> it = pir.filterIterator(); 14075 while (it.hasNext()) { 14076 PreferredActivity pa = it.next(); 14077 // Mark entry for removal only if it matches the package name 14078 // and the entry is of type "always". 14079 if (packageName == null || 14080 (pa.mPref.mComponent.getPackageName().equals(packageName) 14081 && pa.mPref.mAlways)) { 14082 if (removed == null) { 14083 removed = new ArrayList<PreferredActivity>(); 14084 } 14085 removed.add(pa); 14086 } 14087 } 14088 if (removed != null) { 14089 for (int j=0; j<removed.size(); j++) { 14090 PreferredActivity pa = removed.get(j); 14091 pir.removeFilter(pa); 14092 } 14093 changed = true; 14094 } 14095 } 14096 return changed; 14097 } 14098 14099 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14100 private void clearIntentFilterVerificationsLPw(int userId) { 14101 final int packageCount = mPackages.size(); 14102 for (int i = 0; i < packageCount; i++) { 14103 PackageParser.Package pkg = mPackages.valueAt(i); 14104 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14105 } 14106 } 14107 14108 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14109 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14110 if (userId == UserHandle.USER_ALL) { 14111 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14112 sUserManager.getUserIds())) { 14113 for (int oneUserId : sUserManager.getUserIds()) { 14114 scheduleWritePackageRestrictionsLocked(oneUserId); 14115 } 14116 } 14117 } else { 14118 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14119 scheduleWritePackageRestrictionsLocked(userId); 14120 } 14121 } 14122 } 14123 14124 void clearDefaultBrowserIfNeeded(String packageName) { 14125 for (int oneUserId : sUserManager.getUserIds()) { 14126 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14127 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14128 if (packageName.equals(defaultBrowserPackageName)) { 14129 setDefaultBrowserPackageName(null, oneUserId); 14130 } 14131 } 14132 } 14133 14134 @Override 14135 public void resetApplicationPreferences(int userId) { 14136 mContext.enforceCallingOrSelfPermission( 14137 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14138 // writer 14139 synchronized (mPackages) { 14140 final long identity = Binder.clearCallingIdentity(); 14141 try { 14142 clearPackagePreferredActivitiesLPw(null, userId); 14143 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14144 // TODO: We have to reset the default SMS and Phone. This requires 14145 // significant refactoring to keep all default apps in the package 14146 // manager (cleaner but more work) or have the services provide 14147 // callbacks to the package manager to request a default app reset. 14148 applyFactoryDefaultBrowserLPw(userId); 14149 clearIntentFilterVerificationsLPw(userId); 14150 primeDomainVerificationsLPw(userId); 14151 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14152 scheduleWritePackageRestrictionsLocked(userId); 14153 } finally { 14154 Binder.restoreCallingIdentity(identity); 14155 } 14156 } 14157 } 14158 14159 @Override 14160 public int getPreferredActivities(List<IntentFilter> outFilters, 14161 List<ComponentName> outActivities, String packageName) { 14162 14163 int num = 0; 14164 final int userId = UserHandle.getCallingUserId(); 14165 // reader 14166 synchronized (mPackages) { 14167 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14168 if (pir != null) { 14169 final Iterator<PreferredActivity> it = pir.filterIterator(); 14170 while (it.hasNext()) { 14171 final PreferredActivity pa = it.next(); 14172 if (packageName == null 14173 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14174 && pa.mPref.mAlways)) { 14175 if (outFilters != null) { 14176 outFilters.add(new IntentFilter(pa)); 14177 } 14178 if (outActivities != null) { 14179 outActivities.add(pa.mPref.mComponent); 14180 } 14181 } 14182 } 14183 } 14184 } 14185 14186 return num; 14187 } 14188 14189 @Override 14190 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14191 int userId) { 14192 int callingUid = Binder.getCallingUid(); 14193 if (callingUid != Process.SYSTEM_UID) { 14194 throw new SecurityException( 14195 "addPersistentPreferredActivity can only be run by the system"); 14196 } 14197 if (filter.countActions() == 0) { 14198 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14199 return; 14200 } 14201 synchronized (mPackages) { 14202 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14203 " :"); 14204 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14205 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14206 new PersistentPreferredActivity(filter, activity)); 14207 scheduleWritePackageRestrictionsLocked(userId); 14208 } 14209 } 14210 14211 @Override 14212 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14213 int callingUid = Binder.getCallingUid(); 14214 if (callingUid != Process.SYSTEM_UID) { 14215 throw new SecurityException( 14216 "clearPackagePersistentPreferredActivities can only be run by the system"); 14217 } 14218 ArrayList<PersistentPreferredActivity> removed = null; 14219 boolean changed = false; 14220 synchronized (mPackages) { 14221 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14222 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14223 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14224 .valueAt(i); 14225 if (userId != thisUserId) { 14226 continue; 14227 } 14228 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14229 while (it.hasNext()) { 14230 PersistentPreferredActivity ppa = it.next(); 14231 // Mark entry for removal only if it matches the package name. 14232 if (ppa.mComponent.getPackageName().equals(packageName)) { 14233 if (removed == null) { 14234 removed = new ArrayList<PersistentPreferredActivity>(); 14235 } 14236 removed.add(ppa); 14237 } 14238 } 14239 if (removed != null) { 14240 for (int j=0; j<removed.size(); j++) { 14241 PersistentPreferredActivity ppa = removed.get(j); 14242 ppir.removeFilter(ppa); 14243 } 14244 changed = true; 14245 } 14246 } 14247 14248 if (changed) { 14249 scheduleWritePackageRestrictionsLocked(userId); 14250 } 14251 } 14252 } 14253 14254 /** 14255 * Common machinery for picking apart a restored XML blob and passing 14256 * it to a caller-supplied functor to be applied to the running system. 14257 */ 14258 private void restoreFromXml(XmlPullParser parser, int userId, 14259 String expectedStartTag, BlobXmlRestorer functor) 14260 throws IOException, XmlPullParserException { 14261 int type; 14262 while ((type = parser.next()) != XmlPullParser.START_TAG 14263 && type != XmlPullParser.END_DOCUMENT) { 14264 } 14265 if (type != XmlPullParser.START_TAG) { 14266 // oops didn't find a start tag?! 14267 if (DEBUG_BACKUP) { 14268 Slog.e(TAG, "Didn't find start tag during restore"); 14269 } 14270 return; 14271 } 14272 14273 // this is supposed to be TAG_PREFERRED_BACKUP 14274 if (!expectedStartTag.equals(parser.getName())) { 14275 if (DEBUG_BACKUP) { 14276 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14277 } 14278 return; 14279 } 14280 14281 // skip interfering stuff, then we're aligned with the backing implementation 14282 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14283 functor.apply(parser, userId); 14284 } 14285 14286 private interface BlobXmlRestorer { 14287 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14288 } 14289 14290 /** 14291 * Non-Binder method, support for the backup/restore mechanism: write the 14292 * full set of preferred activities in its canonical XML format. Returns the 14293 * XML output as a byte array, or null if there is none. 14294 */ 14295 @Override 14296 public byte[] getPreferredActivityBackup(int userId) { 14297 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14298 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14299 } 14300 14301 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14302 try { 14303 final XmlSerializer serializer = new FastXmlSerializer(); 14304 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14305 serializer.startDocument(null, true); 14306 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14307 14308 synchronized (mPackages) { 14309 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14310 } 14311 14312 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14313 serializer.endDocument(); 14314 serializer.flush(); 14315 } catch (Exception e) { 14316 if (DEBUG_BACKUP) { 14317 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14318 } 14319 return null; 14320 } 14321 14322 return dataStream.toByteArray(); 14323 } 14324 14325 @Override 14326 public void restorePreferredActivities(byte[] backup, int userId) { 14327 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14328 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14329 } 14330 14331 try { 14332 final XmlPullParser parser = Xml.newPullParser(); 14333 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14334 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14335 new BlobXmlRestorer() { 14336 @Override 14337 public void apply(XmlPullParser parser, int userId) 14338 throws XmlPullParserException, IOException { 14339 synchronized (mPackages) { 14340 mSettings.readPreferredActivitiesLPw(parser, userId); 14341 } 14342 } 14343 } ); 14344 } catch (Exception e) { 14345 if (DEBUG_BACKUP) { 14346 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14347 } 14348 } 14349 } 14350 14351 /** 14352 * Non-Binder method, support for the backup/restore mechanism: write the 14353 * default browser (etc) settings in its canonical XML format. Returns the default 14354 * browser XML representation as a byte array, or null if there is none. 14355 */ 14356 @Override 14357 public byte[] getDefaultAppsBackup(int userId) { 14358 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14359 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14360 } 14361 14362 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14363 try { 14364 final XmlSerializer serializer = new FastXmlSerializer(); 14365 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14366 serializer.startDocument(null, true); 14367 serializer.startTag(null, TAG_DEFAULT_APPS); 14368 14369 synchronized (mPackages) { 14370 mSettings.writeDefaultAppsLPr(serializer, userId); 14371 } 14372 14373 serializer.endTag(null, TAG_DEFAULT_APPS); 14374 serializer.endDocument(); 14375 serializer.flush(); 14376 } catch (Exception e) { 14377 if (DEBUG_BACKUP) { 14378 Slog.e(TAG, "Unable to write default apps for backup", e); 14379 } 14380 return null; 14381 } 14382 14383 return dataStream.toByteArray(); 14384 } 14385 14386 @Override 14387 public void restoreDefaultApps(byte[] backup, int userId) { 14388 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14389 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14390 } 14391 14392 try { 14393 final XmlPullParser parser = Xml.newPullParser(); 14394 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14395 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14396 new BlobXmlRestorer() { 14397 @Override 14398 public void apply(XmlPullParser parser, int userId) 14399 throws XmlPullParserException, IOException { 14400 synchronized (mPackages) { 14401 mSettings.readDefaultAppsLPw(parser, userId); 14402 } 14403 } 14404 } ); 14405 } catch (Exception e) { 14406 if (DEBUG_BACKUP) { 14407 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14408 } 14409 } 14410 } 14411 14412 @Override 14413 public byte[] getIntentFilterVerificationBackup(int userId) { 14414 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14415 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14416 } 14417 14418 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14419 try { 14420 final XmlSerializer serializer = new FastXmlSerializer(); 14421 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14422 serializer.startDocument(null, true); 14423 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14424 14425 synchronized (mPackages) { 14426 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14427 } 14428 14429 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14430 serializer.endDocument(); 14431 serializer.flush(); 14432 } catch (Exception e) { 14433 if (DEBUG_BACKUP) { 14434 Slog.e(TAG, "Unable to write default apps for backup", e); 14435 } 14436 return null; 14437 } 14438 14439 return dataStream.toByteArray(); 14440 } 14441 14442 @Override 14443 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14444 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14445 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14446 } 14447 14448 try { 14449 final XmlPullParser parser = Xml.newPullParser(); 14450 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14451 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14452 new BlobXmlRestorer() { 14453 @Override 14454 public void apply(XmlPullParser parser, int userId) 14455 throws XmlPullParserException, IOException { 14456 synchronized (mPackages) { 14457 mSettings.readAllDomainVerificationsLPr(parser, userId); 14458 mSettings.writeLPr(); 14459 } 14460 } 14461 } ); 14462 } catch (Exception e) { 14463 if (DEBUG_BACKUP) { 14464 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14465 } 14466 } 14467 } 14468 14469 @Override 14470 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14471 int sourceUserId, int targetUserId, int flags) { 14472 mContext.enforceCallingOrSelfPermission( 14473 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14474 int callingUid = Binder.getCallingUid(); 14475 enforceOwnerRights(ownerPackage, callingUid); 14476 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14477 if (intentFilter.countActions() == 0) { 14478 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14479 return; 14480 } 14481 synchronized (mPackages) { 14482 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14483 ownerPackage, targetUserId, flags); 14484 CrossProfileIntentResolver resolver = 14485 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14486 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14487 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14488 if (existing != null) { 14489 int size = existing.size(); 14490 for (int i = 0; i < size; i++) { 14491 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14492 return; 14493 } 14494 } 14495 } 14496 resolver.addFilter(newFilter); 14497 scheduleWritePackageRestrictionsLocked(sourceUserId); 14498 } 14499 } 14500 14501 @Override 14502 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14503 mContext.enforceCallingOrSelfPermission( 14504 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14505 int callingUid = Binder.getCallingUid(); 14506 enforceOwnerRights(ownerPackage, callingUid); 14507 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14508 synchronized (mPackages) { 14509 CrossProfileIntentResolver resolver = 14510 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14511 ArraySet<CrossProfileIntentFilter> set = 14512 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14513 for (CrossProfileIntentFilter filter : set) { 14514 if (filter.getOwnerPackage().equals(ownerPackage)) { 14515 resolver.removeFilter(filter); 14516 } 14517 } 14518 scheduleWritePackageRestrictionsLocked(sourceUserId); 14519 } 14520 } 14521 14522 // Enforcing that callingUid is owning pkg on userId 14523 private void enforceOwnerRights(String pkg, int callingUid) { 14524 // The system owns everything. 14525 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14526 return; 14527 } 14528 int callingUserId = UserHandle.getUserId(callingUid); 14529 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14530 if (pi == null) { 14531 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14532 + callingUserId); 14533 } 14534 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14535 throw new SecurityException("Calling uid " + callingUid 14536 + " does not own package " + pkg); 14537 } 14538 } 14539 14540 @Override 14541 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14542 Intent intent = new Intent(Intent.ACTION_MAIN); 14543 intent.addCategory(Intent.CATEGORY_HOME); 14544 14545 final int callingUserId = UserHandle.getCallingUserId(); 14546 List<ResolveInfo> list = queryIntentActivities(intent, null, 14547 PackageManager.GET_META_DATA, callingUserId); 14548 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14549 true, false, false, callingUserId); 14550 14551 allHomeCandidates.clear(); 14552 if (list != null) { 14553 for (ResolveInfo ri : list) { 14554 allHomeCandidates.add(ri); 14555 } 14556 } 14557 return (preferred == null || preferred.activityInfo == null) 14558 ? null 14559 : new ComponentName(preferred.activityInfo.packageName, 14560 preferred.activityInfo.name); 14561 } 14562 14563 @Override 14564 public void setApplicationEnabledSetting(String appPackageName, 14565 int newState, int flags, int userId, String callingPackage) { 14566 if (!sUserManager.exists(userId)) return; 14567 if (callingPackage == null) { 14568 callingPackage = Integer.toString(Binder.getCallingUid()); 14569 } 14570 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14571 } 14572 14573 @Override 14574 public void setComponentEnabledSetting(ComponentName componentName, 14575 int newState, int flags, int userId) { 14576 if (!sUserManager.exists(userId)) return; 14577 setEnabledSetting(componentName.getPackageName(), 14578 componentName.getClassName(), newState, flags, userId, null); 14579 } 14580 14581 private void setEnabledSetting(final String packageName, String className, int newState, 14582 final int flags, int userId, String callingPackage) { 14583 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14584 || newState == COMPONENT_ENABLED_STATE_ENABLED 14585 || newState == COMPONENT_ENABLED_STATE_DISABLED 14586 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14587 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14588 throw new IllegalArgumentException("Invalid new component state: " 14589 + newState); 14590 } 14591 PackageSetting pkgSetting; 14592 final int uid = Binder.getCallingUid(); 14593 final int permission = mContext.checkCallingOrSelfPermission( 14594 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14595 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14596 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14597 boolean sendNow = false; 14598 boolean isApp = (className == null); 14599 String componentName = isApp ? packageName : className; 14600 int packageUid = -1; 14601 ArrayList<String> components; 14602 14603 // writer 14604 synchronized (mPackages) { 14605 pkgSetting = mSettings.mPackages.get(packageName); 14606 if (pkgSetting == null) { 14607 if (className == null) { 14608 throw new IllegalArgumentException( 14609 "Unknown package: " + packageName); 14610 } 14611 throw new IllegalArgumentException( 14612 "Unknown component: " + packageName 14613 + "/" + className); 14614 } 14615 // Allow root and verify that userId is not being specified by a different user 14616 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14617 throw new SecurityException( 14618 "Permission Denial: attempt to change component state from pid=" 14619 + Binder.getCallingPid() 14620 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14621 } 14622 if (className == null) { 14623 // We're dealing with an application/package level state change 14624 if (pkgSetting.getEnabled(userId) == newState) { 14625 // Nothing to do 14626 return; 14627 } 14628 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14629 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14630 // Don't care about who enables an app. 14631 callingPackage = null; 14632 } 14633 pkgSetting.setEnabled(newState, userId, callingPackage); 14634 // pkgSetting.pkg.mSetEnabled = newState; 14635 } else { 14636 // We're dealing with a component level state change 14637 // First, verify that this is a valid class name. 14638 PackageParser.Package pkg = pkgSetting.pkg; 14639 if (pkg == null || !pkg.hasComponentClassName(className)) { 14640 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14641 throw new IllegalArgumentException("Component class " + className 14642 + " does not exist in " + packageName); 14643 } else { 14644 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14645 + className + " does not exist in " + packageName); 14646 } 14647 } 14648 switch (newState) { 14649 case COMPONENT_ENABLED_STATE_ENABLED: 14650 if (!pkgSetting.enableComponentLPw(className, userId)) { 14651 return; 14652 } 14653 break; 14654 case COMPONENT_ENABLED_STATE_DISABLED: 14655 if (!pkgSetting.disableComponentLPw(className, userId)) { 14656 return; 14657 } 14658 break; 14659 case COMPONENT_ENABLED_STATE_DEFAULT: 14660 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14661 return; 14662 } 14663 break; 14664 default: 14665 Slog.e(TAG, "Invalid new component state: " + newState); 14666 return; 14667 } 14668 } 14669 scheduleWritePackageRestrictionsLocked(userId); 14670 components = mPendingBroadcasts.get(userId, packageName); 14671 final boolean newPackage = components == null; 14672 if (newPackage) { 14673 components = new ArrayList<String>(); 14674 } 14675 if (!components.contains(componentName)) { 14676 components.add(componentName); 14677 } 14678 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14679 sendNow = true; 14680 // Purge entry from pending broadcast list if another one exists already 14681 // since we are sending one right away. 14682 mPendingBroadcasts.remove(userId, packageName); 14683 } else { 14684 if (newPackage) { 14685 mPendingBroadcasts.put(userId, packageName, components); 14686 } 14687 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14688 // Schedule a message 14689 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14690 } 14691 } 14692 } 14693 14694 long callingId = Binder.clearCallingIdentity(); 14695 try { 14696 if (sendNow) { 14697 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14698 sendPackageChangedBroadcast(packageName, 14699 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14700 } 14701 } finally { 14702 Binder.restoreCallingIdentity(callingId); 14703 } 14704 } 14705 14706 private void sendPackageChangedBroadcast(String packageName, 14707 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14708 if (DEBUG_INSTALL) 14709 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14710 + componentNames); 14711 Bundle extras = new Bundle(4); 14712 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14713 String nameList[] = new String[componentNames.size()]; 14714 componentNames.toArray(nameList); 14715 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14716 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14717 extras.putInt(Intent.EXTRA_UID, packageUid); 14718 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14719 new int[] {UserHandle.getUserId(packageUid)}); 14720 } 14721 14722 @Override 14723 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14724 if (!sUserManager.exists(userId)) return; 14725 final int uid = Binder.getCallingUid(); 14726 final int permission = mContext.checkCallingOrSelfPermission( 14727 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14728 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14729 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14730 // writer 14731 synchronized (mPackages) { 14732 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14733 allowedByPermission, uid, userId)) { 14734 scheduleWritePackageRestrictionsLocked(userId); 14735 } 14736 } 14737 } 14738 14739 @Override 14740 public String getInstallerPackageName(String packageName) { 14741 // reader 14742 synchronized (mPackages) { 14743 return mSettings.getInstallerPackageNameLPr(packageName); 14744 } 14745 } 14746 14747 @Override 14748 public int getApplicationEnabledSetting(String packageName, int userId) { 14749 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14750 int uid = Binder.getCallingUid(); 14751 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14752 // reader 14753 synchronized (mPackages) { 14754 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14755 } 14756 } 14757 14758 @Override 14759 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14760 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14761 int uid = Binder.getCallingUid(); 14762 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14763 // reader 14764 synchronized (mPackages) { 14765 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14766 } 14767 } 14768 14769 @Override 14770 public void enterSafeMode() { 14771 enforceSystemOrRoot("Only the system can request entering safe mode"); 14772 14773 if (!mSystemReady) { 14774 mSafeMode = true; 14775 } 14776 } 14777 14778 @Override 14779 public void systemReady() { 14780 mSystemReady = true; 14781 14782 // Read the compatibilty setting when the system is ready. 14783 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14784 mContext.getContentResolver(), 14785 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14786 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14787 if (DEBUG_SETTINGS) { 14788 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14789 } 14790 14791 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14792 14793 synchronized (mPackages) { 14794 // Verify that all of the preferred activity components actually 14795 // exist. It is possible for applications to be updated and at 14796 // that point remove a previously declared activity component that 14797 // had been set as a preferred activity. We try to clean this up 14798 // the next time we encounter that preferred activity, but it is 14799 // possible for the user flow to never be able to return to that 14800 // situation so here we do a sanity check to make sure we haven't 14801 // left any junk around. 14802 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14803 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14804 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14805 removed.clear(); 14806 for (PreferredActivity pa : pir.filterSet()) { 14807 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14808 removed.add(pa); 14809 } 14810 } 14811 if (removed.size() > 0) { 14812 for (int r=0; r<removed.size(); r++) { 14813 PreferredActivity pa = removed.get(r); 14814 Slog.w(TAG, "Removing dangling preferred activity: " 14815 + pa.mPref.mComponent); 14816 pir.removeFilter(pa); 14817 } 14818 mSettings.writePackageRestrictionsLPr( 14819 mSettings.mPreferredActivities.keyAt(i)); 14820 } 14821 } 14822 14823 for (int userId : UserManagerService.getInstance().getUserIds()) { 14824 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14825 grantPermissionsUserIds = ArrayUtils.appendInt( 14826 grantPermissionsUserIds, userId); 14827 } 14828 } 14829 } 14830 sUserManager.systemReady(); 14831 14832 // If we upgraded grant all default permissions before kicking off. 14833 for (int userId : grantPermissionsUserIds) { 14834 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14835 } 14836 14837 // Kick off any messages waiting for system ready 14838 if (mPostSystemReadyMessages != null) { 14839 for (Message msg : mPostSystemReadyMessages) { 14840 msg.sendToTarget(); 14841 } 14842 mPostSystemReadyMessages = null; 14843 } 14844 14845 // Watch for external volumes that come and go over time 14846 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14847 storage.registerListener(mStorageListener); 14848 14849 mInstallerService.systemReady(); 14850 mPackageDexOptimizer.systemReady(); 14851 14852 MountServiceInternal mountServiceInternal = LocalServices.getService( 14853 MountServiceInternal.class); 14854 mountServiceInternal.addExternalStoragePolicy( 14855 new MountServiceInternal.ExternalStorageMountPolicy() { 14856 @Override 14857 public int getMountMode(int uid, String packageName) { 14858 if (Process.isIsolated(uid)) { 14859 return Zygote.MOUNT_EXTERNAL_NONE; 14860 } 14861 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14862 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14863 } 14864 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14865 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14866 } 14867 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14868 return Zygote.MOUNT_EXTERNAL_READ; 14869 } 14870 return Zygote.MOUNT_EXTERNAL_WRITE; 14871 } 14872 14873 @Override 14874 public boolean hasExternalStorage(int uid, String packageName) { 14875 return true; 14876 } 14877 }); 14878 } 14879 14880 @Override 14881 public boolean isSafeMode() { 14882 return mSafeMode; 14883 } 14884 14885 @Override 14886 public boolean hasSystemUidErrors() { 14887 return mHasSystemUidErrors; 14888 } 14889 14890 static String arrayToString(int[] array) { 14891 StringBuffer buf = new StringBuffer(128); 14892 buf.append('['); 14893 if (array != null) { 14894 for (int i=0; i<array.length; i++) { 14895 if (i > 0) buf.append(", "); 14896 buf.append(array[i]); 14897 } 14898 } 14899 buf.append(']'); 14900 return buf.toString(); 14901 } 14902 14903 static class DumpState { 14904 public static final int DUMP_LIBS = 1 << 0; 14905 public static final int DUMP_FEATURES = 1 << 1; 14906 public static final int DUMP_RESOLVERS = 1 << 2; 14907 public static final int DUMP_PERMISSIONS = 1 << 3; 14908 public static final int DUMP_PACKAGES = 1 << 4; 14909 public static final int DUMP_SHARED_USERS = 1 << 5; 14910 public static final int DUMP_MESSAGES = 1 << 6; 14911 public static final int DUMP_PROVIDERS = 1 << 7; 14912 public static final int DUMP_VERIFIERS = 1 << 8; 14913 public static final int DUMP_PREFERRED = 1 << 9; 14914 public static final int DUMP_PREFERRED_XML = 1 << 10; 14915 public static final int DUMP_KEYSETS = 1 << 11; 14916 public static final int DUMP_VERSION = 1 << 12; 14917 public static final int DUMP_INSTALLS = 1 << 13; 14918 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14919 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14920 14921 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14922 14923 private int mTypes; 14924 14925 private int mOptions; 14926 14927 private boolean mTitlePrinted; 14928 14929 private SharedUserSetting mSharedUser; 14930 14931 public boolean isDumping(int type) { 14932 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14933 return true; 14934 } 14935 14936 return (mTypes & type) != 0; 14937 } 14938 14939 public void setDump(int type) { 14940 mTypes |= type; 14941 } 14942 14943 public boolean isOptionEnabled(int option) { 14944 return (mOptions & option) != 0; 14945 } 14946 14947 public void setOptionEnabled(int option) { 14948 mOptions |= option; 14949 } 14950 14951 public boolean onTitlePrinted() { 14952 final boolean printed = mTitlePrinted; 14953 mTitlePrinted = true; 14954 return printed; 14955 } 14956 14957 public boolean getTitlePrinted() { 14958 return mTitlePrinted; 14959 } 14960 14961 public void setTitlePrinted(boolean enabled) { 14962 mTitlePrinted = enabled; 14963 } 14964 14965 public SharedUserSetting getSharedUser() { 14966 return mSharedUser; 14967 } 14968 14969 public void setSharedUser(SharedUserSetting user) { 14970 mSharedUser = user; 14971 } 14972 } 14973 14974 @Override 14975 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14976 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14977 != PackageManager.PERMISSION_GRANTED) { 14978 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14979 + Binder.getCallingPid() 14980 + ", uid=" + Binder.getCallingUid() 14981 + " without permission " 14982 + android.Manifest.permission.DUMP); 14983 return; 14984 } 14985 14986 DumpState dumpState = new DumpState(); 14987 boolean fullPreferred = false; 14988 boolean checkin = false; 14989 14990 String packageName = null; 14991 ArraySet<String> permissionNames = null; 14992 14993 int opti = 0; 14994 while (opti < args.length) { 14995 String opt = args[opti]; 14996 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14997 break; 14998 } 14999 opti++; 15000 15001 if ("-a".equals(opt)) { 15002 // Right now we only know how to print all. 15003 } else if ("-h".equals(opt)) { 15004 pw.println("Package manager dump options:"); 15005 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15006 pw.println(" --checkin: dump for a checkin"); 15007 pw.println(" -f: print details of intent filters"); 15008 pw.println(" -h: print this help"); 15009 pw.println(" cmd may be one of:"); 15010 pw.println(" l[ibraries]: list known shared libraries"); 15011 pw.println(" f[ibraries]: list device features"); 15012 pw.println(" k[eysets]: print known keysets"); 15013 pw.println(" r[esolvers]: dump intent resolvers"); 15014 pw.println(" perm[issions]: dump permissions"); 15015 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15016 pw.println(" pref[erred]: print preferred package settings"); 15017 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15018 pw.println(" prov[iders]: dump content providers"); 15019 pw.println(" p[ackages]: dump installed packages"); 15020 pw.println(" s[hared-users]: dump shared user IDs"); 15021 pw.println(" m[essages]: print collected runtime messages"); 15022 pw.println(" v[erifiers]: print package verifier info"); 15023 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15024 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15025 pw.println(" version: print database version info"); 15026 pw.println(" write: write current settings now"); 15027 pw.println(" installs: details about install sessions"); 15028 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15029 pw.println(" <package.name>: info about given package"); 15030 return; 15031 } else if ("--checkin".equals(opt)) { 15032 checkin = true; 15033 } else if ("-f".equals(opt)) { 15034 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15035 } else { 15036 pw.println("Unknown argument: " + opt + "; use -h for help"); 15037 } 15038 } 15039 15040 // Is the caller requesting to dump a particular piece of data? 15041 if (opti < args.length) { 15042 String cmd = args[opti]; 15043 opti++; 15044 // Is this a package name? 15045 if ("android".equals(cmd) || cmd.contains(".")) { 15046 packageName = cmd; 15047 // When dumping a single package, we always dump all of its 15048 // filter information since the amount of data will be reasonable. 15049 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15050 } else if ("check-permission".equals(cmd)) { 15051 if (opti >= args.length) { 15052 pw.println("Error: check-permission missing permission argument"); 15053 return; 15054 } 15055 String perm = args[opti]; 15056 opti++; 15057 if (opti >= args.length) { 15058 pw.println("Error: check-permission missing package argument"); 15059 return; 15060 } 15061 String pkg = args[opti]; 15062 opti++; 15063 int user = UserHandle.getUserId(Binder.getCallingUid()); 15064 if (opti < args.length) { 15065 try { 15066 user = Integer.parseInt(args[opti]); 15067 } catch (NumberFormatException e) { 15068 pw.println("Error: check-permission user argument is not a number: " 15069 + args[opti]); 15070 return; 15071 } 15072 } 15073 pw.println(checkPermission(perm, pkg, user)); 15074 return; 15075 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15076 dumpState.setDump(DumpState.DUMP_LIBS); 15077 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15078 dumpState.setDump(DumpState.DUMP_FEATURES); 15079 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15080 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15081 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15082 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15083 } else if ("permission".equals(cmd)) { 15084 if (opti >= args.length) { 15085 pw.println("Error: permission requires permission name"); 15086 return; 15087 } 15088 permissionNames = new ArraySet<>(); 15089 while (opti < args.length) { 15090 permissionNames.add(args[opti]); 15091 opti++; 15092 } 15093 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15094 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15095 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15096 dumpState.setDump(DumpState.DUMP_PREFERRED); 15097 } else if ("preferred-xml".equals(cmd)) { 15098 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15099 if (opti < args.length && "--full".equals(args[opti])) { 15100 fullPreferred = true; 15101 opti++; 15102 } 15103 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15104 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15105 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15106 dumpState.setDump(DumpState.DUMP_PACKAGES); 15107 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15108 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15109 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15110 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15111 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15112 dumpState.setDump(DumpState.DUMP_MESSAGES); 15113 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15114 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15115 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15116 || "intent-filter-verifiers".equals(cmd)) { 15117 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15118 } else if ("version".equals(cmd)) { 15119 dumpState.setDump(DumpState.DUMP_VERSION); 15120 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15121 dumpState.setDump(DumpState.DUMP_KEYSETS); 15122 } else if ("installs".equals(cmd)) { 15123 dumpState.setDump(DumpState.DUMP_INSTALLS); 15124 } else if ("write".equals(cmd)) { 15125 synchronized (mPackages) { 15126 mSettings.writeLPr(); 15127 pw.println("Settings written."); 15128 return; 15129 } 15130 } 15131 } 15132 15133 if (checkin) { 15134 pw.println("vers,1"); 15135 } 15136 15137 // reader 15138 synchronized (mPackages) { 15139 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15140 if (!checkin) { 15141 if (dumpState.onTitlePrinted()) 15142 pw.println(); 15143 pw.println("Database versions:"); 15144 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15145 } 15146 } 15147 15148 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15149 if (!checkin) { 15150 if (dumpState.onTitlePrinted()) 15151 pw.println(); 15152 pw.println("Verifiers:"); 15153 pw.print(" Required: "); 15154 pw.print(mRequiredVerifierPackage); 15155 pw.print(" (uid="); 15156 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15157 pw.println(")"); 15158 } else if (mRequiredVerifierPackage != null) { 15159 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15160 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15161 } 15162 } 15163 15164 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15165 packageName == null) { 15166 if (mIntentFilterVerifierComponent != null) { 15167 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15168 if (!checkin) { 15169 if (dumpState.onTitlePrinted()) 15170 pw.println(); 15171 pw.println("Intent Filter Verifier:"); 15172 pw.print(" Using: "); 15173 pw.print(verifierPackageName); 15174 pw.print(" (uid="); 15175 pw.print(getPackageUid(verifierPackageName, 0)); 15176 pw.println(")"); 15177 } else if (verifierPackageName != null) { 15178 pw.print("ifv,"); pw.print(verifierPackageName); 15179 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15180 } 15181 } else { 15182 pw.println(); 15183 pw.println("No Intent Filter Verifier available!"); 15184 } 15185 } 15186 15187 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15188 boolean printedHeader = false; 15189 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15190 while (it.hasNext()) { 15191 String name = it.next(); 15192 SharedLibraryEntry ent = mSharedLibraries.get(name); 15193 if (!checkin) { 15194 if (!printedHeader) { 15195 if (dumpState.onTitlePrinted()) 15196 pw.println(); 15197 pw.println("Libraries:"); 15198 printedHeader = true; 15199 } 15200 pw.print(" "); 15201 } else { 15202 pw.print("lib,"); 15203 } 15204 pw.print(name); 15205 if (!checkin) { 15206 pw.print(" -> "); 15207 } 15208 if (ent.path != null) { 15209 if (!checkin) { 15210 pw.print("(jar) "); 15211 pw.print(ent.path); 15212 } else { 15213 pw.print(",jar,"); 15214 pw.print(ent.path); 15215 } 15216 } else { 15217 if (!checkin) { 15218 pw.print("(apk) "); 15219 pw.print(ent.apk); 15220 } else { 15221 pw.print(",apk,"); 15222 pw.print(ent.apk); 15223 } 15224 } 15225 pw.println(); 15226 } 15227 } 15228 15229 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15230 if (dumpState.onTitlePrinted()) 15231 pw.println(); 15232 if (!checkin) { 15233 pw.println("Features:"); 15234 } 15235 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15236 while (it.hasNext()) { 15237 String name = it.next(); 15238 if (!checkin) { 15239 pw.print(" "); 15240 } else { 15241 pw.print("feat,"); 15242 } 15243 pw.println(name); 15244 } 15245 } 15246 15247 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15248 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15249 : "Activity Resolver Table:", " ", packageName, 15250 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15251 dumpState.setTitlePrinted(true); 15252 } 15253 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15254 : "Receiver Resolver Table:", " ", packageName, 15255 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15256 dumpState.setTitlePrinted(true); 15257 } 15258 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15259 : "Service Resolver Table:", " ", packageName, 15260 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15261 dumpState.setTitlePrinted(true); 15262 } 15263 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15264 : "Provider Resolver Table:", " ", packageName, 15265 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15266 dumpState.setTitlePrinted(true); 15267 } 15268 } 15269 15270 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15271 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15272 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15273 int user = mSettings.mPreferredActivities.keyAt(i); 15274 if (pir.dump(pw, 15275 dumpState.getTitlePrinted() 15276 ? "\nPreferred Activities User " + user + ":" 15277 : "Preferred Activities User " + user + ":", " ", 15278 packageName, true, false)) { 15279 dumpState.setTitlePrinted(true); 15280 } 15281 } 15282 } 15283 15284 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15285 pw.flush(); 15286 FileOutputStream fout = new FileOutputStream(fd); 15287 BufferedOutputStream str = new BufferedOutputStream(fout); 15288 XmlSerializer serializer = new FastXmlSerializer(); 15289 try { 15290 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15291 serializer.startDocument(null, true); 15292 serializer.setFeature( 15293 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15294 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15295 serializer.endDocument(); 15296 serializer.flush(); 15297 } catch (IllegalArgumentException e) { 15298 pw.println("Failed writing: " + e); 15299 } catch (IllegalStateException e) { 15300 pw.println("Failed writing: " + e); 15301 } catch (IOException e) { 15302 pw.println("Failed writing: " + e); 15303 } 15304 } 15305 15306 if (!checkin 15307 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15308 && packageName == null) { 15309 pw.println(); 15310 int count = mSettings.mPackages.size(); 15311 if (count == 0) { 15312 pw.println("No applications!"); 15313 pw.println(); 15314 } else { 15315 final String prefix = " "; 15316 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15317 if (allPackageSettings.size() == 0) { 15318 pw.println("No domain preferred apps!"); 15319 pw.println(); 15320 } else { 15321 pw.println("App verification status:"); 15322 pw.println(); 15323 count = 0; 15324 for (PackageSetting ps : allPackageSettings) { 15325 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15326 if (ivi == null || ivi.getPackageName() == null) continue; 15327 pw.println(prefix + "Package: " + ivi.getPackageName()); 15328 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15329 pw.println(prefix + "Status: " + ivi.getStatusString()); 15330 pw.println(); 15331 count++; 15332 } 15333 if (count == 0) { 15334 pw.println(prefix + "No app verification established."); 15335 pw.println(); 15336 } 15337 for (int userId : sUserManager.getUserIds()) { 15338 pw.println("App linkages for user " + userId + ":"); 15339 pw.println(); 15340 count = 0; 15341 for (PackageSetting ps : allPackageSettings) { 15342 final long status = ps.getDomainVerificationStatusForUser(userId); 15343 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15344 continue; 15345 } 15346 pw.println(prefix + "Package: " + ps.name); 15347 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15348 String statusStr = IntentFilterVerificationInfo. 15349 getStatusStringFromValue(status); 15350 pw.println(prefix + "Status: " + statusStr); 15351 pw.println(); 15352 count++; 15353 } 15354 if (count == 0) { 15355 pw.println(prefix + "No configured app linkages."); 15356 pw.println(); 15357 } 15358 } 15359 } 15360 } 15361 } 15362 15363 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15364 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15365 if (packageName == null && permissionNames == null) { 15366 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15367 if (iperm == 0) { 15368 if (dumpState.onTitlePrinted()) 15369 pw.println(); 15370 pw.println("AppOp Permissions:"); 15371 } 15372 pw.print(" AppOp Permission "); 15373 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15374 pw.println(":"); 15375 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15376 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15377 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15378 } 15379 } 15380 } 15381 } 15382 15383 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15384 boolean printedSomething = false; 15385 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15386 if (packageName != null && !packageName.equals(p.info.packageName)) { 15387 continue; 15388 } 15389 if (!printedSomething) { 15390 if (dumpState.onTitlePrinted()) 15391 pw.println(); 15392 pw.println("Registered ContentProviders:"); 15393 printedSomething = true; 15394 } 15395 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15396 pw.print(" "); pw.println(p.toString()); 15397 } 15398 printedSomething = false; 15399 for (Map.Entry<String, PackageParser.Provider> entry : 15400 mProvidersByAuthority.entrySet()) { 15401 PackageParser.Provider p = entry.getValue(); 15402 if (packageName != null && !packageName.equals(p.info.packageName)) { 15403 continue; 15404 } 15405 if (!printedSomething) { 15406 if (dumpState.onTitlePrinted()) 15407 pw.println(); 15408 pw.println("ContentProvider Authorities:"); 15409 printedSomething = true; 15410 } 15411 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15412 pw.print(" "); pw.println(p.toString()); 15413 if (p.info != null && p.info.applicationInfo != null) { 15414 final String appInfo = p.info.applicationInfo.toString(); 15415 pw.print(" applicationInfo="); pw.println(appInfo); 15416 } 15417 } 15418 } 15419 15420 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15421 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15422 } 15423 15424 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15425 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15426 } 15427 15428 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15429 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15430 } 15431 15432 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15433 // XXX should handle packageName != null by dumping only install data that 15434 // the given package is involved with. 15435 if (dumpState.onTitlePrinted()) pw.println(); 15436 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15437 } 15438 15439 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15440 if (dumpState.onTitlePrinted()) pw.println(); 15441 mSettings.dumpReadMessagesLPr(pw, dumpState); 15442 15443 pw.println(); 15444 pw.println("Package warning messages:"); 15445 BufferedReader in = null; 15446 String line = null; 15447 try { 15448 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15449 while ((line = in.readLine()) != null) { 15450 if (line.contains("ignored: updated version")) continue; 15451 pw.println(line); 15452 } 15453 } catch (IOException ignored) { 15454 } finally { 15455 IoUtils.closeQuietly(in); 15456 } 15457 } 15458 15459 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15460 BufferedReader in = null; 15461 String line = null; 15462 try { 15463 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15464 while ((line = in.readLine()) != null) { 15465 if (line.contains("ignored: updated version")) continue; 15466 pw.print("msg,"); 15467 pw.println(line); 15468 } 15469 } catch (IOException ignored) { 15470 } finally { 15471 IoUtils.closeQuietly(in); 15472 } 15473 } 15474 } 15475 } 15476 15477 private String dumpDomainString(String packageName) { 15478 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15479 List<IntentFilter> filters = getAllIntentFilters(packageName); 15480 15481 ArraySet<String> result = new ArraySet<>(); 15482 if (iviList.size() > 0) { 15483 for (IntentFilterVerificationInfo ivi : iviList) { 15484 for (String host : ivi.getDomains()) { 15485 result.add(host); 15486 } 15487 } 15488 } 15489 if (filters != null && filters.size() > 0) { 15490 for (IntentFilter filter : filters) { 15491 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15492 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15493 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15494 result.addAll(filter.getHostsList()); 15495 } 15496 } 15497 } 15498 15499 StringBuilder sb = new StringBuilder(result.size() * 16); 15500 for (String domain : result) { 15501 if (sb.length() > 0) sb.append(" "); 15502 sb.append(domain); 15503 } 15504 return sb.toString(); 15505 } 15506 15507 // ------- apps on sdcard specific code ------- 15508 static final boolean DEBUG_SD_INSTALL = false; 15509 15510 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15511 15512 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15513 15514 private boolean mMediaMounted = false; 15515 15516 static String getEncryptKey() { 15517 try { 15518 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15519 SD_ENCRYPTION_KEYSTORE_NAME); 15520 if (sdEncKey == null) { 15521 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15522 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15523 if (sdEncKey == null) { 15524 Slog.e(TAG, "Failed to create encryption keys"); 15525 return null; 15526 } 15527 } 15528 return sdEncKey; 15529 } catch (NoSuchAlgorithmException nsae) { 15530 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15531 return null; 15532 } catch (IOException ioe) { 15533 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15534 return null; 15535 } 15536 } 15537 15538 /* 15539 * Update media status on PackageManager. 15540 */ 15541 @Override 15542 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15543 int callingUid = Binder.getCallingUid(); 15544 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15545 throw new SecurityException("Media status can only be updated by the system"); 15546 } 15547 // reader; this apparently protects mMediaMounted, but should probably 15548 // be a different lock in that case. 15549 synchronized (mPackages) { 15550 Log.i(TAG, "Updating external media status from " 15551 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15552 + (mediaStatus ? "mounted" : "unmounted")); 15553 if (DEBUG_SD_INSTALL) 15554 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15555 + ", mMediaMounted=" + mMediaMounted); 15556 if (mediaStatus == mMediaMounted) { 15557 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15558 : 0, -1); 15559 mHandler.sendMessage(msg); 15560 return; 15561 } 15562 mMediaMounted = mediaStatus; 15563 } 15564 // Queue up an async operation since the package installation may take a 15565 // little while. 15566 mHandler.post(new Runnable() { 15567 public void run() { 15568 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15569 } 15570 }); 15571 } 15572 15573 /** 15574 * Called by MountService when the initial ASECs to scan are available. 15575 * Should block until all the ASEC containers are finished being scanned. 15576 */ 15577 public void scanAvailableAsecs() { 15578 updateExternalMediaStatusInner(true, false, false); 15579 if (mShouldRestoreconData) { 15580 SELinuxMMAC.setRestoreconDone(); 15581 mShouldRestoreconData = false; 15582 } 15583 } 15584 15585 /* 15586 * Collect information of applications on external media, map them against 15587 * existing containers and update information based on current mount status. 15588 * Please note that we always have to report status if reportStatus has been 15589 * set to true especially when unloading packages. 15590 */ 15591 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15592 boolean externalStorage) { 15593 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15594 int[] uidArr = EmptyArray.INT; 15595 15596 final String[] list = PackageHelper.getSecureContainerList(); 15597 if (ArrayUtils.isEmpty(list)) { 15598 Log.i(TAG, "No secure containers found"); 15599 } else { 15600 // Process list of secure containers and categorize them 15601 // as active or stale based on their package internal state. 15602 15603 // reader 15604 synchronized (mPackages) { 15605 for (String cid : list) { 15606 // Leave stages untouched for now; installer service owns them 15607 if (PackageInstallerService.isStageName(cid)) continue; 15608 15609 if (DEBUG_SD_INSTALL) 15610 Log.i(TAG, "Processing container " + cid); 15611 String pkgName = getAsecPackageName(cid); 15612 if (pkgName == null) { 15613 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15614 continue; 15615 } 15616 if (DEBUG_SD_INSTALL) 15617 Log.i(TAG, "Looking for pkg : " + pkgName); 15618 15619 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15620 if (ps == null) { 15621 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15622 continue; 15623 } 15624 15625 /* 15626 * Skip packages that are not external if we're unmounting 15627 * external storage. 15628 */ 15629 if (externalStorage && !isMounted && !isExternal(ps)) { 15630 continue; 15631 } 15632 15633 final AsecInstallArgs args = new AsecInstallArgs(cid, 15634 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15635 // The package status is changed only if the code path 15636 // matches between settings and the container id. 15637 if (ps.codePathString != null 15638 && ps.codePathString.startsWith(args.getCodePath())) { 15639 if (DEBUG_SD_INSTALL) { 15640 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15641 + " at code path: " + ps.codePathString); 15642 } 15643 15644 // We do have a valid package installed on sdcard 15645 processCids.put(args, ps.codePathString); 15646 final int uid = ps.appId; 15647 if (uid != -1) { 15648 uidArr = ArrayUtils.appendInt(uidArr, uid); 15649 } 15650 } else { 15651 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15652 + ps.codePathString); 15653 } 15654 } 15655 } 15656 15657 Arrays.sort(uidArr); 15658 } 15659 15660 // Process packages with valid entries. 15661 if (isMounted) { 15662 if (DEBUG_SD_INSTALL) 15663 Log.i(TAG, "Loading packages"); 15664 loadMediaPackages(processCids, uidArr); 15665 startCleaningPackages(); 15666 mInstallerService.onSecureContainersAvailable(); 15667 } else { 15668 if (DEBUG_SD_INSTALL) 15669 Log.i(TAG, "Unloading packages"); 15670 unloadMediaPackages(processCids, uidArr, reportStatus); 15671 } 15672 } 15673 15674 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15675 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15676 final int size = infos.size(); 15677 final String[] packageNames = new String[size]; 15678 final int[] packageUids = new int[size]; 15679 for (int i = 0; i < size; i++) { 15680 final ApplicationInfo info = infos.get(i); 15681 packageNames[i] = info.packageName; 15682 packageUids[i] = info.uid; 15683 } 15684 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15685 finishedReceiver); 15686 } 15687 15688 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15689 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15690 sendResourcesChangedBroadcast(mediaStatus, replacing, 15691 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15692 } 15693 15694 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15695 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15696 int size = pkgList.length; 15697 if (size > 0) { 15698 // Send broadcasts here 15699 Bundle extras = new Bundle(); 15700 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15701 if (uidArr != null) { 15702 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15703 } 15704 if (replacing) { 15705 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15706 } 15707 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15708 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15709 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15710 } 15711 } 15712 15713 /* 15714 * Look at potentially valid container ids from processCids If package 15715 * information doesn't match the one on record or package scanning fails, 15716 * the cid is added to list of removeCids. We currently don't delete stale 15717 * containers. 15718 */ 15719 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15720 ArrayList<String> pkgList = new ArrayList<String>(); 15721 Set<AsecInstallArgs> keys = processCids.keySet(); 15722 15723 for (AsecInstallArgs args : keys) { 15724 String codePath = processCids.get(args); 15725 if (DEBUG_SD_INSTALL) 15726 Log.i(TAG, "Loading container : " + args.cid); 15727 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15728 try { 15729 // Make sure there are no container errors first. 15730 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15731 Slog.e(TAG, "Failed to mount cid : " + args.cid 15732 + " when installing from sdcard"); 15733 continue; 15734 } 15735 // Check code path here. 15736 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15737 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15738 + " does not match one in settings " + codePath); 15739 continue; 15740 } 15741 // Parse package 15742 int parseFlags = mDefParseFlags; 15743 if (args.isExternalAsec()) { 15744 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15745 } 15746 if (args.isFwdLocked()) { 15747 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15748 } 15749 15750 synchronized (mInstallLock) { 15751 PackageParser.Package pkg = null; 15752 try { 15753 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15754 } catch (PackageManagerException e) { 15755 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15756 } 15757 // Scan the package 15758 if (pkg != null) { 15759 /* 15760 * TODO why is the lock being held? doPostInstall is 15761 * called in other places without the lock. This needs 15762 * to be straightened out. 15763 */ 15764 // writer 15765 synchronized (mPackages) { 15766 retCode = PackageManager.INSTALL_SUCCEEDED; 15767 pkgList.add(pkg.packageName); 15768 // Post process args 15769 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15770 pkg.applicationInfo.uid); 15771 } 15772 } else { 15773 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15774 } 15775 } 15776 15777 } finally { 15778 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15779 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15780 } 15781 } 15782 } 15783 // writer 15784 synchronized (mPackages) { 15785 // If the platform SDK has changed since the last time we booted, 15786 // we need to re-grant app permission to catch any new ones that 15787 // appear. This is really a hack, and means that apps can in some 15788 // cases get permissions that the user didn't initially explicitly 15789 // allow... it would be nice to have some better way to handle 15790 // this situation. 15791 final VersionInfo ver = mSettings.getExternalVersion(); 15792 15793 int updateFlags = UPDATE_PERMISSIONS_ALL; 15794 if (ver.sdkVersion != mSdkVersion) { 15795 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15796 + mSdkVersion + "; regranting permissions for external"); 15797 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15798 } 15799 updatePermissionsLPw(null, null, updateFlags); 15800 15801 // Yay, everything is now upgraded 15802 ver.forceCurrent(); 15803 15804 // can downgrade to reader 15805 // Persist settings 15806 mSettings.writeLPr(); 15807 } 15808 // Send a broadcast to let everyone know we are done processing 15809 if (pkgList.size() > 0) { 15810 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15811 } 15812 } 15813 15814 /* 15815 * Utility method to unload a list of specified containers 15816 */ 15817 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15818 // Just unmount all valid containers. 15819 for (AsecInstallArgs arg : cidArgs) { 15820 synchronized (mInstallLock) { 15821 arg.doPostDeleteLI(false); 15822 } 15823 } 15824 } 15825 15826 /* 15827 * Unload packages mounted on external media. This involves deleting package 15828 * data from internal structures, sending broadcasts about diabled packages, 15829 * gc'ing to free up references, unmounting all secure containers 15830 * corresponding to packages on external media, and posting a 15831 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15832 * that we always have to post this message if status has been requested no 15833 * matter what. 15834 */ 15835 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15836 final boolean reportStatus) { 15837 if (DEBUG_SD_INSTALL) 15838 Log.i(TAG, "unloading media packages"); 15839 ArrayList<String> pkgList = new ArrayList<String>(); 15840 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15841 final Set<AsecInstallArgs> keys = processCids.keySet(); 15842 for (AsecInstallArgs args : keys) { 15843 String pkgName = args.getPackageName(); 15844 if (DEBUG_SD_INSTALL) 15845 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15846 // Delete package internally 15847 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15848 synchronized (mInstallLock) { 15849 boolean res = deletePackageLI(pkgName, null, false, null, null, 15850 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15851 if (res) { 15852 pkgList.add(pkgName); 15853 } else { 15854 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15855 failedList.add(args); 15856 } 15857 } 15858 } 15859 15860 // reader 15861 synchronized (mPackages) { 15862 // We didn't update the settings after removing each package; 15863 // write them now for all packages. 15864 mSettings.writeLPr(); 15865 } 15866 15867 // We have to absolutely send UPDATED_MEDIA_STATUS only 15868 // after confirming that all the receivers processed the ordered 15869 // broadcast when packages get disabled, force a gc to clean things up. 15870 // and unload all the containers. 15871 if (pkgList.size() > 0) { 15872 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15873 new IIntentReceiver.Stub() { 15874 public void performReceive(Intent intent, int resultCode, String data, 15875 Bundle extras, boolean ordered, boolean sticky, 15876 int sendingUser) throws RemoteException { 15877 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15878 reportStatus ? 1 : 0, 1, keys); 15879 mHandler.sendMessage(msg); 15880 } 15881 }); 15882 } else { 15883 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15884 keys); 15885 mHandler.sendMessage(msg); 15886 } 15887 } 15888 15889 private void loadPrivatePackages(VolumeInfo vol) { 15890 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15891 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15892 synchronized (mInstallLock) { 15893 synchronized (mPackages) { 15894 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15895 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15896 for (PackageSetting ps : packages) { 15897 final PackageParser.Package pkg; 15898 try { 15899 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15900 loaded.add(pkg.applicationInfo); 15901 } catch (PackageManagerException e) { 15902 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15903 } 15904 15905 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15906 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15907 } 15908 } 15909 15910 int updateFlags = UPDATE_PERMISSIONS_ALL; 15911 if (ver.sdkVersion != mSdkVersion) { 15912 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15913 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15914 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15915 } 15916 updatePermissionsLPw(null, null, updateFlags); 15917 15918 // Yay, everything is now upgraded 15919 ver.forceCurrent(); 15920 15921 mSettings.writeLPr(); 15922 } 15923 } 15924 15925 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15926 sendResourcesChangedBroadcast(true, false, loaded, null); 15927 } 15928 15929 private void unloadPrivatePackages(VolumeInfo vol) { 15930 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15931 synchronized (mInstallLock) { 15932 synchronized (mPackages) { 15933 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15934 for (PackageSetting ps : packages) { 15935 if (ps.pkg == null) continue; 15936 15937 final ApplicationInfo info = ps.pkg.applicationInfo; 15938 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15939 if (deletePackageLI(ps.name, null, false, null, null, 15940 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15941 unloaded.add(info); 15942 } else { 15943 Slog.w(TAG, "Failed to unload " + ps.codePath); 15944 } 15945 } 15946 15947 mSettings.writeLPr(); 15948 } 15949 } 15950 15951 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15952 sendResourcesChangedBroadcast(false, false, unloaded, null); 15953 } 15954 15955 /** 15956 * Examine all users present on given mounted volume, and destroy data 15957 * belonging to users that are no longer valid, or whose user ID has been 15958 * recycled. 15959 */ 15960 private void reconcileUsers(String volumeUuid) { 15961 final File[] files = FileUtils 15962 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15963 for (File file : files) { 15964 if (!file.isDirectory()) continue; 15965 15966 final int userId; 15967 final UserInfo info; 15968 try { 15969 userId = Integer.parseInt(file.getName()); 15970 info = sUserManager.getUserInfo(userId); 15971 } catch (NumberFormatException e) { 15972 Slog.w(TAG, "Invalid user directory " + file); 15973 continue; 15974 } 15975 15976 boolean destroyUser = false; 15977 if (info == null) { 15978 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15979 + " because no matching user was found"); 15980 destroyUser = true; 15981 } else { 15982 try { 15983 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15984 } catch (IOException e) { 15985 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15986 + " because we failed to enforce serial number: " + e); 15987 destroyUser = true; 15988 } 15989 } 15990 15991 if (destroyUser) { 15992 synchronized (mInstallLock) { 15993 mInstaller.removeUserDataDirs(volumeUuid, userId); 15994 } 15995 } 15996 } 15997 15998 final UserManager um = mContext.getSystemService(UserManager.class); 15999 for (UserInfo user : um.getUsers()) { 16000 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16001 if (userDir.exists()) continue; 16002 16003 try { 16004 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 16005 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16006 } catch (IOException e) { 16007 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16008 } 16009 } 16010 } 16011 16012 /** 16013 * Examine all apps present on given mounted volume, and destroy apps that 16014 * aren't expected, either due to uninstallation or reinstallation on 16015 * another volume. 16016 */ 16017 private void reconcileApps(String volumeUuid) { 16018 final File[] files = FileUtils 16019 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16020 for (File file : files) { 16021 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16022 && !PackageInstallerService.isStageName(file.getName()); 16023 if (!isPackage) { 16024 // Ignore entries which are not packages 16025 continue; 16026 } 16027 16028 boolean destroyApp = false; 16029 String packageName = null; 16030 try { 16031 final PackageLite pkg = PackageParser.parsePackageLite(file, 16032 PackageParser.PARSE_MUST_BE_APK); 16033 packageName = pkg.packageName; 16034 16035 synchronized (mPackages) { 16036 final PackageSetting ps = mSettings.mPackages.get(packageName); 16037 if (ps == null) { 16038 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16039 + volumeUuid + " because we found no install record"); 16040 destroyApp = true; 16041 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16042 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16043 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16044 destroyApp = true; 16045 } 16046 } 16047 16048 } catch (PackageParserException e) { 16049 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16050 destroyApp = true; 16051 } 16052 16053 if (destroyApp) { 16054 synchronized (mInstallLock) { 16055 if (packageName != null) { 16056 removeDataDirsLI(volumeUuid, packageName); 16057 } 16058 if (file.isDirectory()) { 16059 mInstaller.rmPackageDir(file.getAbsolutePath()); 16060 } else { 16061 file.delete(); 16062 } 16063 } 16064 } 16065 } 16066 } 16067 16068 private void unfreezePackage(String packageName) { 16069 synchronized (mPackages) { 16070 final PackageSetting ps = mSettings.mPackages.get(packageName); 16071 if (ps != null) { 16072 ps.frozen = false; 16073 } 16074 } 16075 } 16076 16077 @Override 16078 public int movePackage(final String packageName, final String volumeUuid) { 16079 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16080 16081 final int moveId = mNextMoveId.getAndIncrement(); 16082 try { 16083 movePackageInternal(packageName, volumeUuid, moveId); 16084 } catch (PackageManagerException e) { 16085 Slog.w(TAG, "Failed to move " + packageName, e); 16086 mMoveCallbacks.notifyStatusChanged(moveId, 16087 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16088 } 16089 return moveId; 16090 } 16091 16092 private void movePackageInternal(final String packageName, final String volumeUuid, 16093 final int moveId) throws PackageManagerException { 16094 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16095 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16096 final PackageManager pm = mContext.getPackageManager(); 16097 16098 final boolean currentAsec; 16099 final String currentVolumeUuid; 16100 final File codeFile; 16101 final String installerPackageName; 16102 final String packageAbiOverride; 16103 final int appId; 16104 final String seinfo; 16105 final String label; 16106 16107 // reader 16108 synchronized (mPackages) { 16109 final PackageParser.Package pkg = mPackages.get(packageName); 16110 final PackageSetting ps = mSettings.mPackages.get(packageName); 16111 if (pkg == null || ps == null) { 16112 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16113 } 16114 16115 if (pkg.applicationInfo.isSystemApp()) { 16116 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16117 "Cannot move system application"); 16118 } 16119 16120 if (pkg.applicationInfo.isExternalAsec()) { 16121 currentAsec = true; 16122 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16123 } else if (pkg.applicationInfo.isForwardLocked()) { 16124 currentAsec = true; 16125 currentVolumeUuid = "forward_locked"; 16126 } else { 16127 currentAsec = false; 16128 currentVolumeUuid = ps.volumeUuid; 16129 16130 final File probe = new File(pkg.codePath); 16131 final File probeOat = new File(probe, "oat"); 16132 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16133 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16134 "Move only supported for modern cluster style installs"); 16135 } 16136 } 16137 16138 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16139 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16140 "Package already moved to " + volumeUuid); 16141 } 16142 16143 if (ps.frozen) { 16144 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16145 "Failed to move already frozen package"); 16146 } 16147 ps.frozen = true; 16148 16149 codeFile = new File(pkg.codePath); 16150 installerPackageName = ps.installerPackageName; 16151 packageAbiOverride = ps.cpuAbiOverrideString; 16152 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16153 seinfo = pkg.applicationInfo.seinfo; 16154 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16155 } 16156 16157 // Now that we're guarded by frozen state, kill app during move 16158 final long token = Binder.clearCallingIdentity(); 16159 try { 16160 killApplication(packageName, appId, "move pkg"); 16161 } finally { 16162 Binder.restoreCallingIdentity(token); 16163 } 16164 16165 final Bundle extras = new Bundle(); 16166 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16167 extras.putString(Intent.EXTRA_TITLE, label); 16168 mMoveCallbacks.notifyCreated(moveId, extras); 16169 16170 int installFlags; 16171 final boolean moveCompleteApp; 16172 final File measurePath; 16173 16174 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16175 installFlags = INSTALL_INTERNAL; 16176 moveCompleteApp = !currentAsec; 16177 measurePath = Environment.getDataAppDirectory(volumeUuid); 16178 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16179 installFlags = INSTALL_EXTERNAL; 16180 moveCompleteApp = false; 16181 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16182 } else { 16183 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16184 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16185 || !volume.isMountedWritable()) { 16186 unfreezePackage(packageName); 16187 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16188 "Move location not mounted private volume"); 16189 } 16190 16191 Preconditions.checkState(!currentAsec); 16192 16193 installFlags = INSTALL_INTERNAL; 16194 moveCompleteApp = true; 16195 measurePath = Environment.getDataAppDirectory(volumeUuid); 16196 } 16197 16198 final PackageStats stats = new PackageStats(null, -1); 16199 synchronized (mInstaller) { 16200 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16201 unfreezePackage(packageName); 16202 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16203 "Failed to measure package size"); 16204 } 16205 } 16206 16207 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16208 + stats.dataSize); 16209 16210 final long startFreeBytes = measurePath.getFreeSpace(); 16211 final long sizeBytes; 16212 if (moveCompleteApp) { 16213 sizeBytes = stats.codeSize + stats.dataSize; 16214 } else { 16215 sizeBytes = stats.codeSize; 16216 } 16217 16218 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16219 unfreezePackage(packageName); 16220 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16221 "Not enough free space to move"); 16222 } 16223 16224 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16225 16226 final CountDownLatch installedLatch = new CountDownLatch(1); 16227 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16228 @Override 16229 public void onUserActionRequired(Intent intent) throws RemoteException { 16230 throw new IllegalStateException(); 16231 } 16232 16233 @Override 16234 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16235 Bundle extras) throws RemoteException { 16236 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16237 + PackageManager.installStatusToString(returnCode, msg)); 16238 16239 installedLatch.countDown(); 16240 16241 // Regardless of success or failure of the move operation, 16242 // always unfreeze the package 16243 unfreezePackage(packageName); 16244 16245 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16246 switch (status) { 16247 case PackageInstaller.STATUS_SUCCESS: 16248 mMoveCallbacks.notifyStatusChanged(moveId, 16249 PackageManager.MOVE_SUCCEEDED); 16250 break; 16251 case PackageInstaller.STATUS_FAILURE_STORAGE: 16252 mMoveCallbacks.notifyStatusChanged(moveId, 16253 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16254 break; 16255 default: 16256 mMoveCallbacks.notifyStatusChanged(moveId, 16257 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16258 break; 16259 } 16260 } 16261 }; 16262 16263 final MoveInfo move; 16264 if (moveCompleteApp) { 16265 // Kick off a thread to report progress estimates 16266 new Thread() { 16267 @Override 16268 public void run() { 16269 while (true) { 16270 try { 16271 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16272 break; 16273 } 16274 } catch (InterruptedException ignored) { 16275 } 16276 16277 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16278 final int progress = 10 + (int) MathUtils.constrain( 16279 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16280 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16281 } 16282 } 16283 }.start(); 16284 16285 final String dataAppName = codeFile.getName(); 16286 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16287 dataAppName, appId, seinfo); 16288 } else { 16289 move = null; 16290 } 16291 16292 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16293 16294 final Message msg = mHandler.obtainMessage(INIT_COPY); 16295 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16296 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16297 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16298 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16299 msg.obj = params; 16300 16301 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16302 System.identityHashCode(msg.obj)); 16303 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16304 System.identityHashCode(msg.obj)); 16305 16306 mHandler.sendMessage(msg); 16307 } 16308 16309 @Override 16310 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16311 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16312 16313 final int realMoveId = mNextMoveId.getAndIncrement(); 16314 final Bundle extras = new Bundle(); 16315 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16316 mMoveCallbacks.notifyCreated(realMoveId, extras); 16317 16318 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16319 @Override 16320 public void onCreated(int moveId, Bundle extras) { 16321 // Ignored 16322 } 16323 16324 @Override 16325 public void onStatusChanged(int moveId, int status, long estMillis) { 16326 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16327 } 16328 }; 16329 16330 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16331 storage.setPrimaryStorageUuid(volumeUuid, callback); 16332 return realMoveId; 16333 } 16334 16335 @Override 16336 public int getMoveStatus(int moveId) { 16337 mContext.enforceCallingOrSelfPermission( 16338 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16339 return mMoveCallbacks.mLastStatus.get(moveId); 16340 } 16341 16342 @Override 16343 public void registerMoveCallback(IPackageMoveObserver callback) { 16344 mContext.enforceCallingOrSelfPermission( 16345 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16346 mMoveCallbacks.register(callback); 16347 } 16348 16349 @Override 16350 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16351 mContext.enforceCallingOrSelfPermission( 16352 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16353 mMoveCallbacks.unregister(callback); 16354 } 16355 16356 @Override 16357 public boolean setInstallLocation(int loc) { 16358 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16359 null); 16360 if (getInstallLocation() == loc) { 16361 return true; 16362 } 16363 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16364 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16365 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16366 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16367 return true; 16368 } 16369 return false; 16370 } 16371 16372 @Override 16373 public int getInstallLocation() { 16374 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16375 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16376 PackageHelper.APP_INSTALL_AUTO); 16377 } 16378 16379 /** Called by UserManagerService */ 16380 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16381 mDirtyUsers.remove(userHandle); 16382 mSettings.removeUserLPw(userHandle); 16383 mPendingBroadcasts.remove(userHandle); 16384 if (mInstaller != null) { 16385 // Technically, we shouldn't be doing this with the package lock 16386 // held. However, this is very rare, and there is already so much 16387 // other disk I/O going on, that we'll let it slide for now. 16388 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16389 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16390 final String volumeUuid = vol.getFsUuid(); 16391 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16392 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16393 } 16394 } 16395 mUserNeedsBadging.delete(userHandle); 16396 removeUnusedPackagesLILPw(userManager, userHandle); 16397 } 16398 16399 /** 16400 * We're removing userHandle and would like to remove any downloaded packages 16401 * that are no longer in use by any other user. 16402 * @param userHandle the user being removed 16403 */ 16404 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16405 final boolean DEBUG_CLEAN_APKS = false; 16406 int [] users = userManager.getUserIdsLPr(); 16407 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16408 while (psit.hasNext()) { 16409 PackageSetting ps = psit.next(); 16410 if (ps.pkg == null) { 16411 continue; 16412 } 16413 final String packageName = ps.pkg.packageName; 16414 // Skip over if system app 16415 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16416 continue; 16417 } 16418 if (DEBUG_CLEAN_APKS) { 16419 Slog.i(TAG, "Checking package " + packageName); 16420 } 16421 boolean keep = false; 16422 for (int i = 0; i < users.length; i++) { 16423 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16424 keep = true; 16425 if (DEBUG_CLEAN_APKS) { 16426 Slog.i(TAG, " Keeping package " + packageName + " for user " 16427 + users[i]); 16428 } 16429 break; 16430 } 16431 } 16432 if (!keep) { 16433 if (DEBUG_CLEAN_APKS) { 16434 Slog.i(TAG, " Removing package " + packageName); 16435 } 16436 mHandler.post(new Runnable() { 16437 public void run() { 16438 deletePackageX(packageName, userHandle, 0); 16439 } //end run 16440 }); 16441 } 16442 } 16443 } 16444 16445 /** Called by UserManagerService */ 16446 void createNewUserLILPw(int userHandle) { 16447 if (mInstaller != null) { 16448 mInstaller.createUserConfig(userHandle); 16449 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16450 applyFactoryDefaultBrowserLPw(userHandle); 16451 primeDomainVerificationsLPw(userHandle); 16452 } 16453 } 16454 16455 void newUserCreated(final int userHandle) { 16456 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16457 } 16458 16459 @Override 16460 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16461 mContext.enforceCallingOrSelfPermission( 16462 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16463 "Only package verification agents can read the verifier device identity"); 16464 16465 synchronized (mPackages) { 16466 return mSettings.getVerifierDeviceIdentityLPw(); 16467 } 16468 } 16469 16470 @Override 16471 public void setPermissionEnforced(String permission, boolean enforced) { 16472 // TODO: Now that we no longer change GID for storage, this should to away. 16473 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16474 "setPermissionEnforced"); 16475 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16476 synchronized (mPackages) { 16477 if (mSettings.mReadExternalStorageEnforced == null 16478 || mSettings.mReadExternalStorageEnforced != enforced) { 16479 mSettings.mReadExternalStorageEnforced = enforced; 16480 mSettings.writeLPr(); 16481 } 16482 } 16483 // kill any non-foreground processes so we restart them and 16484 // grant/revoke the GID. 16485 final IActivityManager am = ActivityManagerNative.getDefault(); 16486 if (am != null) { 16487 final long token = Binder.clearCallingIdentity(); 16488 try { 16489 am.killProcessesBelowForeground("setPermissionEnforcement"); 16490 } catch (RemoteException e) { 16491 } finally { 16492 Binder.restoreCallingIdentity(token); 16493 } 16494 } 16495 } else { 16496 throw new IllegalArgumentException("No selective enforcement for " + permission); 16497 } 16498 } 16499 16500 @Override 16501 @Deprecated 16502 public boolean isPermissionEnforced(String permission) { 16503 return true; 16504 } 16505 16506 @Override 16507 public boolean isStorageLow() { 16508 final long token = Binder.clearCallingIdentity(); 16509 try { 16510 final DeviceStorageMonitorInternal 16511 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16512 if (dsm != null) { 16513 return dsm.isMemoryLow(); 16514 } else { 16515 return false; 16516 } 16517 } finally { 16518 Binder.restoreCallingIdentity(token); 16519 } 16520 } 16521 16522 @Override 16523 public IPackageInstaller getPackageInstaller() { 16524 return mInstallerService; 16525 } 16526 16527 private boolean userNeedsBadging(int userId) { 16528 int index = mUserNeedsBadging.indexOfKey(userId); 16529 if (index < 0) { 16530 final UserInfo userInfo; 16531 final long token = Binder.clearCallingIdentity(); 16532 try { 16533 userInfo = sUserManager.getUserInfo(userId); 16534 } finally { 16535 Binder.restoreCallingIdentity(token); 16536 } 16537 final boolean b; 16538 if (userInfo != null && userInfo.isManagedProfile()) { 16539 b = true; 16540 } else { 16541 b = false; 16542 } 16543 mUserNeedsBadging.put(userId, b); 16544 return b; 16545 } 16546 return mUserNeedsBadging.valueAt(index); 16547 } 16548 16549 @Override 16550 public KeySet getKeySetByAlias(String packageName, String alias) { 16551 if (packageName == null || alias == null) { 16552 return null; 16553 } 16554 synchronized(mPackages) { 16555 final PackageParser.Package pkg = mPackages.get(packageName); 16556 if (pkg == null) { 16557 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16558 throw new IllegalArgumentException("Unknown package: " + packageName); 16559 } 16560 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16561 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16562 } 16563 } 16564 16565 @Override 16566 public KeySet getSigningKeySet(String packageName) { 16567 if (packageName == null) { 16568 return null; 16569 } 16570 synchronized(mPackages) { 16571 final PackageParser.Package pkg = mPackages.get(packageName); 16572 if (pkg == null) { 16573 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16574 throw new IllegalArgumentException("Unknown package: " + packageName); 16575 } 16576 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16577 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16578 throw new SecurityException("May not access signing KeySet of other apps."); 16579 } 16580 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16581 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16582 } 16583 } 16584 16585 @Override 16586 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16587 if (packageName == null || ks == null) { 16588 return false; 16589 } 16590 synchronized(mPackages) { 16591 final PackageParser.Package pkg = mPackages.get(packageName); 16592 if (pkg == null) { 16593 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16594 throw new IllegalArgumentException("Unknown package: " + packageName); 16595 } 16596 IBinder ksh = ks.getToken(); 16597 if (ksh instanceof KeySetHandle) { 16598 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16599 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16600 } 16601 return false; 16602 } 16603 } 16604 16605 @Override 16606 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16607 if (packageName == null || ks == null) { 16608 return false; 16609 } 16610 synchronized(mPackages) { 16611 final PackageParser.Package pkg = mPackages.get(packageName); 16612 if (pkg == null) { 16613 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16614 throw new IllegalArgumentException("Unknown package: " + packageName); 16615 } 16616 IBinder ksh = ks.getToken(); 16617 if (ksh instanceof KeySetHandle) { 16618 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16619 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16620 } 16621 return false; 16622 } 16623 } 16624 16625 public void getUsageStatsIfNoPackageUsageInfo() { 16626 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16627 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16628 if (usm == null) { 16629 throw new IllegalStateException("UsageStatsManager must be initialized"); 16630 } 16631 long now = System.currentTimeMillis(); 16632 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16633 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16634 String packageName = entry.getKey(); 16635 PackageParser.Package pkg = mPackages.get(packageName); 16636 if (pkg == null) { 16637 continue; 16638 } 16639 UsageStats usage = entry.getValue(); 16640 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16641 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16642 } 16643 } 16644 } 16645 16646 /** 16647 * Check and throw if the given before/after packages would be considered a 16648 * downgrade. 16649 */ 16650 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16651 throws PackageManagerException { 16652 if (after.versionCode < before.mVersionCode) { 16653 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16654 "Update version code " + after.versionCode + " is older than current " 16655 + before.mVersionCode); 16656 } else if (after.versionCode == before.mVersionCode) { 16657 if (after.baseRevisionCode < before.baseRevisionCode) { 16658 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16659 "Update base revision code " + after.baseRevisionCode 16660 + " is older than current " + before.baseRevisionCode); 16661 } 16662 16663 if (!ArrayUtils.isEmpty(after.splitNames)) { 16664 for (int i = 0; i < after.splitNames.length; i++) { 16665 final String splitName = after.splitNames[i]; 16666 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16667 if (j != -1) { 16668 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16669 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16670 "Update split " + splitName + " revision code " 16671 + after.splitRevisionCodes[i] + " is older than current " 16672 + before.splitRevisionCodes[j]); 16673 } 16674 } 16675 } 16676 } 16677 } 16678 } 16679 16680 private static class MoveCallbacks extends Handler { 16681 private static final int MSG_CREATED = 1; 16682 private static final int MSG_STATUS_CHANGED = 2; 16683 16684 private final RemoteCallbackList<IPackageMoveObserver> 16685 mCallbacks = new RemoteCallbackList<>(); 16686 16687 private final SparseIntArray mLastStatus = new SparseIntArray(); 16688 16689 public MoveCallbacks(Looper looper) { 16690 super(looper); 16691 } 16692 16693 public void register(IPackageMoveObserver callback) { 16694 mCallbacks.register(callback); 16695 } 16696 16697 public void unregister(IPackageMoveObserver callback) { 16698 mCallbacks.unregister(callback); 16699 } 16700 16701 @Override 16702 public void handleMessage(Message msg) { 16703 final SomeArgs args = (SomeArgs) msg.obj; 16704 final int n = mCallbacks.beginBroadcast(); 16705 for (int i = 0; i < n; i++) { 16706 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16707 try { 16708 invokeCallback(callback, msg.what, args); 16709 } catch (RemoteException ignored) { 16710 } 16711 } 16712 mCallbacks.finishBroadcast(); 16713 args.recycle(); 16714 } 16715 16716 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16717 throws RemoteException { 16718 switch (what) { 16719 case MSG_CREATED: { 16720 callback.onCreated(args.argi1, (Bundle) args.arg2); 16721 break; 16722 } 16723 case MSG_STATUS_CHANGED: { 16724 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16725 break; 16726 } 16727 } 16728 } 16729 16730 private void notifyCreated(int moveId, Bundle extras) { 16731 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16732 16733 final SomeArgs args = SomeArgs.obtain(); 16734 args.argi1 = moveId; 16735 args.arg2 = extras; 16736 obtainMessage(MSG_CREATED, args).sendToTarget(); 16737 } 16738 16739 private void notifyStatusChanged(int moveId, int status) { 16740 notifyStatusChanged(moveId, status, -1); 16741 } 16742 16743 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16744 Slog.v(TAG, "Move " + moveId + " status " + status); 16745 16746 final SomeArgs args = SomeArgs.obtain(); 16747 args.argi1 = moveId; 16748 args.argi2 = status; 16749 args.arg3 = estMillis; 16750 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16751 16752 synchronized (mLastStatus) { 16753 mLastStatus.put(moveId, status); 16754 } 16755 } 16756 } 16757 16758 private final class OnPermissionChangeListeners extends Handler { 16759 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16760 16761 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16762 new RemoteCallbackList<>(); 16763 16764 public OnPermissionChangeListeners(Looper looper) { 16765 super(looper); 16766 } 16767 16768 @Override 16769 public void handleMessage(Message msg) { 16770 switch (msg.what) { 16771 case MSG_ON_PERMISSIONS_CHANGED: { 16772 final int uid = msg.arg1; 16773 handleOnPermissionsChanged(uid); 16774 } break; 16775 } 16776 } 16777 16778 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16779 mPermissionListeners.register(listener); 16780 16781 } 16782 16783 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16784 mPermissionListeners.unregister(listener); 16785 } 16786 16787 public void onPermissionsChanged(int uid) { 16788 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16789 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16790 } 16791 } 16792 16793 private void handleOnPermissionsChanged(int uid) { 16794 final int count = mPermissionListeners.beginBroadcast(); 16795 try { 16796 for (int i = 0; i < count; i++) { 16797 IOnPermissionsChangeListener callback = mPermissionListeners 16798 .getBroadcastItem(i); 16799 try { 16800 callback.onPermissionsChanged(uid); 16801 } catch (RemoteException e) { 16802 Log.e(TAG, "Permission listener is dead", e); 16803 } 16804 } 16805 } finally { 16806 mPermissionListeners.finishBroadcast(); 16807 } 16808 } 16809 } 16810 16811 private class PackageManagerInternalImpl extends PackageManagerInternal { 16812 @Override 16813 public void setLocationPackagesProvider(PackagesProvider provider) { 16814 synchronized (mPackages) { 16815 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16816 } 16817 } 16818 16819 @Override 16820 public void setImePackagesProvider(PackagesProvider provider) { 16821 synchronized (mPackages) { 16822 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16823 } 16824 } 16825 16826 @Override 16827 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16828 synchronized (mPackages) { 16829 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16830 } 16831 } 16832 16833 @Override 16834 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16835 synchronized (mPackages) { 16836 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16837 } 16838 } 16839 16840 @Override 16841 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16842 synchronized (mPackages) { 16843 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16844 } 16845 } 16846 16847 @Override 16848 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16849 synchronized (mPackages) { 16850 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16851 } 16852 } 16853 16854 @Override 16855 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16856 synchronized (mPackages) { 16857 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16858 } 16859 } 16860 16861 @Override 16862 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16863 synchronized (mPackages) { 16864 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16865 packageName, userId); 16866 } 16867 } 16868 16869 @Override 16870 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16871 synchronized (mPackages) { 16872 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16873 packageName, userId); 16874 } 16875 } 16876 @Override 16877 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16878 synchronized (mPackages) { 16879 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16880 packageName, userId); 16881 } 16882 } 16883 } 16884 16885 @Override 16886 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16887 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16888 synchronized (mPackages) { 16889 final long identity = Binder.clearCallingIdentity(); 16890 try { 16891 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16892 packageNames, userId); 16893 } finally { 16894 Binder.restoreCallingIdentity(identity); 16895 } 16896 } 16897 } 16898 16899 private static void enforceSystemOrPhoneCaller(String tag) { 16900 int callingUid = Binder.getCallingUid(); 16901 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16902 throw new SecurityException( 16903 "Cannot call " + tag + " from UID " + callingUid); 16904 } 16905 } 16906} 16907