PackageManagerService.java revision cf9f751206e027a1654572585d045a325dec4ecc
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) { 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 = createForwardingResolveInfoUnchecked(new IntentFilter(), 4671 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 = createForwardingResolveInfo(filter, intent, 4926 resolvedType, 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 = createForwardingResolveInfo(filter, intent, 4954 resolvedType, flags, sourceUserId); 4955 if (resolveInfo != null) return resolveInfo; 4956 alreadyTriedUserIds.put(targetUserId, true); 4957 } 4958 } 4959 } 4960 return null; 4961 } 4962 4963 /** 4964 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4965 * will forward the intent to the filter's target user. 4966 * Otherwise, returns null. 4967 */ 4968 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4969 String resolvedType, int flags, int sourceUserId) { 4970 int targetUserId = filter.getTargetUserId(); 4971 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4972 resolvedType, flags, targetUserId); 4973 if (resultTargetUser != null && !resultTargetUser.isEmpty() 4974 && isUserEnabled(targetUserId)) { 4975 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 4976 } 4977 return null; 4978 } 4979 4980 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 4981 int sourceUserId, int targetUserId) { 4982 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4983 long ident = Binder.clearCallingIdentity(); 4984 boolean targetIsProfile; 4985 try { 4986 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4987 } finally { 4988 Binder.restoreCallingIdentity(ident); 4989 } 4990 String className; 4991 if (targetIsProfile) { 4992 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4993 } else { 4994 className = FORWARD_INTENT_TO_PARENT; 4995 } 4996 ComponentName forwardingActivityComponentName = new ComponentName( 4997 mAndroidApplication.packageName, className); 4998 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4999 sourceUserId); 5000 if (!targetIsProfile) { 5001 forwardingActivityInfo.showUserIcon = targetUserId; 5002 forwardingResolveInfo.noResourceId = true; 5003 } 5004 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5005 forwardingResolveInfo.priority = 0; 5006 forwardingResolveInfo.preferredOrder = 0; 5007 forwardingResolveInfo.match = 0; 5008 forwardingResolveInfo.isDefault = true; 5009 forwardingResolveInfo.filter = filter; 5010 forwardingResolveInfo.targetUserId = targetUserId; 5011 return forwardingResolveInfo; 5012 } 5013 5014 @Override 5015 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5016 Intent[] specifics, String[] specificTypes, Intent intent, 5017 String resolvedType, int flags, int userId) { 5018 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5019 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5020 false, "query intent activity options"); 5021 final String resultsAction = intent.getAction(); 5022 5023 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5024 | PackageManager.GET_RESOLVED_FILTER, userId); 5025 5026 if (DEBUG_INTENT_MATCHING) { 5027 Log.v(TAG, "Query " + intent + ": " + results); 5028 } 5029 5030 int specificsPos = 0; 5031 int N; 5032 5033 // todo: note that the algorithm used here is O(N^2). This 5034 // isn't a problem in our current environment, but if we start running 5035 // into situations where we have more than 5 or 10 matches then this 5036 // should probably be changed to something smarter... 5037 5038 // First we go through and resolve each of the specific items 5039 // that were supplied, taking care of removing any corresponding 5040 // duplicate items in the generic resolve list. 5041 if (specifics != null) { 5042 for (int i=0; i<specifics.length; i++) { 5043 final Intent sintent = specifics[i]; 5044 if (sintent == null) { 5045 continue; 5046 } 5047 5048 if (DEBUG_INTENT_MATCHING) { 5049 Log.v(TAG, "Specific #" + i + ": " + sintent); 5050 } 5051 5052 String action = sintent.getAction(); 5053 if (resultsAction != null && resultsAction.equals(action)) { 5054 // If this action was explicitly requested, then don't 5055 // remove things that have it. 5056 action = null; 5057 } 5058 5059 ResolveInfo ri = null; 5060 ActivityInfo ai = null; 5061 5062 ComponentName comp = sintent.getComponent(); 5063 if (comp == null) { 5064 ri = resolveIntent( 5065 sintent, 5066 specificTypes != null ? specificTypes[i] : null, 5067 flags, userId); 5068 if (ri == null) { 5069 continue; 5070 } 5071 if (ri == mResolveInfo) { 5072 // ACK! Must do something better with this. 5073 } 5074 ai = ri.activityInfo; 5075 comp = new ComponentName(ai.applicationInfo.packageName, 5076 ai.name); 5077 } else { 5078 ai = getActivityInfo(comp, flags, userId); 5079 if (ai == null) { 5080 continue; 5081 } 5082 } 5083 5084 // Look for any generic query activities that are duplicates 5085 // of this specific one, and remove them from the results. 5086 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5087 N = results.size(); 5088 int j; 5089 for (j=specificsPos; j<N; j++) { 5090 ResolveInfo sri = results.get(j); 5091 if ((sri.activityInfo.name.equals(comp.getClassName()) 5092 && sri.activityInfo.applicationInfo.packageName.equals( 5093 comp.getPackageName())) 5094 || (action != null && sri.filter.matchAction(action))) { 5095 results.remove(j); 5096 if (DEBUG_INTENT_MATCHING) Log.v( 5097 TAG, "Removing duplicate item from " + j 5098 + " due to specific " + specificsPos); 5099 if (ri == null) { 5100 ri = sri; 5101 } 5102 j--; 5103 N--; 5104 } 5105 } 5106 5107 // Add this specific item to its proper place. 5108 if (ri == null) { 5109 ri = new ResolveInfo(); 5110 ri.activityInfo = ai; 5111 } 5112 results.add(specificsPos, ri); 5113 ri.specificIndex = i; 5114 specificsPos++; 5115 } 5116 } 5117 5118 // Now we go through the remaining generic results and remove any 5119 // duplicate actions that are found here. 5120 N = results.size(); 5121 for (int i=specificsPos; i<N-1; i++) { 5122 final ResolveInfo rii = results.get(i); 5123 if (rii.filter == null) { 5124 continue; 5125 } 5126 5127 // Iterate over all of the actions of this result's intent 5128 // filter... typically this should be just one. 5129 final Iterator<String> it = rii.filter.actionsIterator(); 5130 if (it == null) { 5131 continue; 5132 } 5133 while (it.hasNext()) { 5134 final String action = it.next(); 5135 if (resultsAction != null && resultsAction.equals(action)) { 5136 // If this action was explicitly requested, then don't 5137 // remove things that have it. 5138 continue; 5139 } 5140 for (int j=i+1; j<N; j++) { 5141 final ResolveInfo rij = results.get(j); 5142 if (rij.filter != null && rij.filter.hasAction(action)) { 5143 results.remove(j); 5144 if (DEBUG_INTENT_MATCHING) Log.v( 5145 TAG, "Removing duplicate item from " + j 5146 + " due to action " + action + " at " + i); 5147 j--; 5148 N--; 5149 } 5150 } 5151 } 5152 5153 // If the caller didn't request filter information, drop it now 5154 // so we don't have to marshall/unmarshall it. 5155 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5156 rii.filter = null; 5157 } 5158 } 5159 5160 // Filter out the caller activity if so requested. 5161 if (caller != null) { 5162 N = results.size(); 5163 for (int i=0; i<N; i++) { 5164 ActivityInfo ainfo = results.get(i).activityInfo; 5165 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5166 && caller.getClassName().equals(ainfo.name)) { 5167 results.remove(i); 5168 break; 5169 } 5170 } 5171 } 5172 5173 // If the caller didn't request filter information, 5174 // drop them now so we don't have to 5175 // marshall/unmarshall it. 5176 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5177 N = results.size(); 5178 for (int i=0; i<N; i++) { 5179 results.get(i).filter = null; 5180 } 5181 } 5182 5183 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5184 return results; 5185 } 5186 5187 @Override 5188 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5189 int userId) { 5190 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5191 ComponentName comp = intent.getComponent(); 5192 if (comp == null) { 5193 if (intent.getSelector() != null) { 5194 intent = intent.getSelector(); 5195 comp = intent.getComponent(); 5196 } 5197 } 5198 if (comp != null) { 5199 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5200 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5201 if (ai != null) { 5202 ResolveInfo ri = new ResolveInfo(); 5203 ri.activityInfo = ai; 5204 list.add(ri); 5205 } 5206 return list; 5207 } 5208 5209 // reader 5210 synchronized (mPackages) { 5211 String pkgName = intent.getPackage(); 5212 if (pkgName == null) { 5213 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5214 } 5215 final PackageParser.Package pkg = mPackages.get(pkgName); 5216 if (pkg != null) { 5217 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5218 userId); 5219 } 5220 return null; 5221 } 5222 } 5223 5224 @Override 5225 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5226 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5227 if (!sUserManager.exists(userId)) return null; 5228 if (query != null) { 5229 if (query.size() >= 1) { 5230 // If there is more than one service with the same priority, 5231 // just arbitrarily pick the first one. 5232 return query.get(0); 5233 } 5234 } 5235 return null; 5236 } 5237 5238 @Override 5239 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5240 int userId) { 5241 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5242 ComponentName comp = intent.getComponent(); 5243 if (comp == null) { 5244 if (intent.getSelector() != null) { 5245 intent = intent.getSelector(); 5246 comp = intent.getComponent(); 5247 } 5248 } 5249 if (comp != null) { 5250 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5251 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5252 if (si != null) { 5253 final ResolveInfo ri = new ResolveInfo(); 5254 ri.serviceInfo = si; 5255 list.add(ri); 5256 } 5257 return list; 5258 } 5259 5260 // reader 5261 synchronized (mPackages) { 5262 String pkgName = intent.getPackage(); 5263 if (pkgName == null) { 5264 return mServices.queryIntent(intent, resolvedType, flags, userId); 5265 } 5266 final PackageParser.Package pkg = mPackages.get(pkgName); 5267 if (pkg != null) { 5268 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5269 userId); 5270 } 5271 return null; 5272 } 5273 } 5274 5275 @Override 5276 public List<ResolveInfo> queryIntentContentProviders( 5277 Intent intent, String resolvedType, int flags, int userId) { 5278 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5279 ComponentName comp = intent.getComponent(); 5280 if (comp == null) { 5281 if (intent.getSelector() != null) { 5282 intent = intent.getSelector(); 5283 comp = intent.getComponent(); 5284 } 5285 } 5286 if (comp != null) { 5287 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5288 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5289 if (pi != null) { 5290 final ResolveInfo ri = new ResolveInfo(); 5291 ri.providerInfo = pi; 5292 list.add(ri); 5293 } 5294 return list; 5295 } 5296 5297 // reader 5298 synchronized (mPackages) { 5299 String pkgName = intent.getPackage(); 5300 if (pkgName == null) { 5301 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5302 } 5303 final PackageParser.Package pkg = mPackages.get(pkgName); 5304 if (pkg != null) { 5305 return mProviders.queryIntentForPackage( 5306 intent, resolvedType, flags, pkg.providers, userId); 5307 } 5308 return null; 5309 } 5310 } 5311 5312 @Override 5313 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5314 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5315 5316 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5317 5318 // writer 5319 synchronized (mPackages) { 5320 ArrayList<PackageInfo> list; 5321 if (listUninstalled) { 5322 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5323 for (PackageSetting ps : mSettings.mPackages.values()) { 5324 PackageInfo pi; 5325 if (ps.pkg != null) { 5326 pi = generatePackageInfo(ps.pkg, flags, userId); 5327 } else { 5328 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5329 } 5330 if (pi != null) { 5331 list.add(pi); 5332 } 5333 } 5334 } else { 5335 list = new ArrayList<PackageInfo>(mPackages.size()); 5336 for (PackageParser.Package p : mPackages.values()) { 5337 PackageInfo pi = generatePackageInfo(p, flags, userId); 5338 if (pi != null) { 5339 list.add(pi); 5340 } 5341 } 5342 } 5343 5344 return new ParceledListSlice<PackageInfo>(list); 5345 } 5346 } 5347 5348 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5349 String[] permissions, boolean[] tmp, int flags, int userId) { 5350 int numMatch = 0; 5351 final PermissionsState permissionsState = ps.getPermissionsState(); 5352 for (int i=0; i<permissions.length; i++) { 5353 final String permission = permissions[i]; 5354 if (permissionsState.hasPermission(permission, userId)) { 5355 tmp[i] = true; 5356 numMatch++; 5357 } else { 5358 tmp[i] = false; 5359 } 5360 } 5361 if (numMatch == 0) { 5362 return; 5363 } 5364 PackageInfo pi; 5365 if (ps.pkg != null) { 5366 pi = generatePackageInfo(ps.pkg, flags, userId); 5367 } else { 5368 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5369 } 5370 // The above might return null in cases of uninstalled apps or install-state 5371 // skew across users/profiles. 5372 if (pi != null) { 5373 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5374 if (numMatch == permissions.length) { 5375 pi.requestedPermissions = permissions; 5376 } else { 5377 pi.requestedPermissions = new String[numMatch]; 5378 numMatch = 0; 5379 for (int i=0; i<permissions.length; i++) { 5380 if (tmp[i]) { 5381 pi.requestedPermissions[numMatch] = permissions[i]; 5382 numMatch++; 5383 } 5384 } 5385 } 5386 } 5387 list.add(pi); 5388 } 5389 } 5390 5391 @Override 5392 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5393 String[] permissions, int flags, int userId) { 5394 if (!sUserManager.exists(userId)) return null; 5395 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5396 5397 // writer 5398 synchronized (mPackages) { 5399 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5400 boolean[] tmpBools = new boolean[permissions.length]; 5401 if (listUninstalled) { 5402 for (PackageSetting ps : mSettings.mPackages.values()) { 5403 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5404 } 5405 } else { 5406 for (PackageParser.Package pkg : mPackages.values()) { 5407 PackageSetting ps = (PackageSetting)pkg.mExtras; 5408 if (ps != null) { 5409 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5410 userId); 5411 } 5412 } 5413 } 5414 5415 return new ParceledListSlice<PackageInfo>(list); 5416 } 5417 } 5418 5419 @Override 5420 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5421 if (!sUserManager.exists(userId)) return null; 5422 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5423 5424 // writer 5425 synchronized (mPackages) { 5426 ArrayList<ApplicationInfo> list; 5427 if (listUninstalled) { 5428 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5429 for (PackageSetting ps : mSettings.mPackages.values()) { 5430 ApplicationInfo ai; 5431 if (ps.pkg != null) { 5432 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5433 ps.readUserState(userId), userId); 5434 } else { 5435 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5436 } 5437 if (ai != null) { 5438 list.add(ai); 5439 } 5440 } 5441 } else { 5442 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5443 for (PackageParser.Package p : mPackages.values()) { 5444 if (p.mExtras != null) { 5445 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5446 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5447 if (ai != null) { 5448 list.add(ai); 5449 } 5450 } 5451 } 5452 } 5453 5454 return new ParceledListSlice<ApplicationInfo>(list); 5455 } 5456 } 5457 5458 public List<ApplicationInfo> getPersistentApplications(int flags) { 5459 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5460 5461 // reader 5462 synchronized (mPackages) { 5463 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5464 final int userId = UserHandle.getCallingUserId(); 5465 while (i.hasNext()) { 5466 final PackageParser.Package p = i.next(); 5467 if (p.applicationInfo != null 5468 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5469 && (!mSafeMode || isSystemApp(p))) { 5470 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5471 if (ps != null) { 5472 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5473 ps.readUserState(userId), userId); 5474 if (ai != null) { 5475 finalList.add(ai); 5476 } 5477 } 5478 } 5479 } 5480 } 5481 5482 return finalList; 5483 } 5484 5485 @Override 5486 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5487 if (!sUserManager.exists(userId)) return null; 5488 // reader 5489 synchronized (mPackages) { 5490 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5491 PackageSetting ps = provider != null 5492 ? mSettings.mPackages.get(provider.owner.packageName) 5493 : null; 5494 return ps != null 5495 && mSettings.isEnabledLPr(provider.info, flags, userId) 5496 && (!mSafeMode || (provider.info.applicationInfo.flags 5497 &ApplicationInfo.FLAG_SYSTEM) != 0) 5498 ? PackageParser.generateProviderInfo(provider, flags, 5499 ps.readUserState(userId), userId) 5500 : null; 5501 } 5502 } 5503 5504 /** 5505 * @deprecated 5506 */ 5507 @Deprecated 5508 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5509 // reader 5510 synchronized (mPackages) { 5511 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5512 .entrySet().iterator(); 5513 final int userId = UserHandle.getCallingUserId(); 5514 while (i.hasNext()) { 5515 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5516 PackageParser.Provider p = entry.getValue(); 5517 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5518 5519 if (ps != null && p.syncable 5520 && (!mSafeMode || (p.info.applicationInfo.flags 5521 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5522 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5523 ps.readUserState(userId), userId); 5524 if (info != null) { 5525 outNames.add(entry.getKey()); 5526 outInfo.add(info); 5527 } 5528 } 5529 } 5530 } 5531 } 5532 5533 @Override 5534 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5535 int uid, int flags) { 5536 ArrayList<ProviderInfo> finalList = null; 5537 // reader 5538 synchronized (mPackages) { 5539 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5540 final int userId = processName != null ? 5541 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5542 while (i.hasNext()) { 5543 final PackageParser.Provider p = i.next(); 5544 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5545 if (ps != null && p.info.authority != null 5546 && (processName == null 5547 || (p.info.processName.equals(processName) 5548 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5549 && mSettings.isEnabledLPr(p.info, flags, userId) 5550 && (!mSafeMode 5551 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5552 if (finalList == null) { 5553 finalList = new ArrayList<ProviderInfo>(3); 5554 } 5555 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5556 ps.readUserState(userId), userId); 5557 if (info != null) { 5558 finalList.add(info); 5559 } 5560 } 5561 } 5562 } 5563 5564 if (finalList != null) { 5565 Collections.sort(finalList, mProviderInitOrderSorter); 5566 return new ParceledListSlice<ProviderInfo>(finalList); 5567 } 5568 5569 return null; 5570 } 5571 5572 @Override 5573 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5574 int flags) { 5575 // reader 5576 synchronized (mPackages) { 5577 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5578 return PackageParser.generateInstrumentationInfo(i, flags); 5579 } 5580 } 5581 5582 @Override 5583 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5584 int flags) { 5585 ArrayList<InstrumentationInfo> finalList = 5586 new ArrayList<InstrumentationInfo>(); 5587 5588 // reader 5589 synchronized (mPackages) { 5590 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5591 while (i.hasNext()) { 5592 final PackageParser.Instrumentation p = i.next(); 5593 if (targetPackage == null 5594 || targetPackage.equals(p.info.targetPackage)) { 5595 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5596 flags); 5597 if (ii != null) { 5598 finalList.add(ii); 5599 } 5600 } 5601 } 5602 } 5603 5604 return finalList; 5605 } 5606 5607 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5608 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5609 if (overlays == null) { 5610 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5611 return; 5612 } 5613 for (PackageParser.Package opkg : overlays.values()) { 5614 // Not much to do if idmap fails: we already logged the error 5615 // and we certainly don't want to abort installation of pkg simply 5616 // because an overlay didn't fit properly. For these reasons, 5617 // ignore the return value of createIdmapForPackagePairLI. 5618 createIdmapForPackagePairLI(pkg, opkg); 5619 } 5620 } 5621 5622 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5623 PackageParser.Package opkg) { 5624 if (!opkg.mTrustedOverlay) { 5625 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5626 opkg.baseCodePath + ": overlay not trusted"); 5627 return false; 5628 } 5629 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5630 if (overlaySet == null) { 5631 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5632 opkg.baseCodePath + " but target package has no known overlays"); 5633 return false; 5634 } 5635 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5636 // TODO: generate idmap for split APKs 5637 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5638 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5639 + opkg.baseCodePath); 5640 return false; 5641 } 5642 PackageParser.Package[] overlayArray = 5643 overlaySet.values().toArray(new PackageParser.Package[0]); 5644 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5645 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5646 return p1.mOverlayPriority - p2.mOverlayPriority; 5647 } 5648 }; 5649 Arrays.sort(overlayArray, cmp); 5650 5651 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5652 int i = 0; 5653 for (PackageParser.Package p : overlayArray) { 5654 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5655 } 5656 return true; 5657 } 5658 5659 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5660 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5661 try { 5662 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5663 } finally { 5664 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5665 } 5666 } 5667 5668 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5669 final File[] files = dir.listFiles(); 5670 if (ArrayUtils.isEmpty(files)) { 5671 Log.d(TAG, "No files in app dir " + dir); 5672 return; 5673 } 5674 5675 if (DEBUG_PACKAGE_SCANNING) { 5676 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5677 + " flags=0x" + Integer.toHexString(parseFlags)); 5678 } 5679 5680 for (File file : files) { 5681 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5682 && !PackageInstallerService.isStageName(file.getName()); 5683 if (!isPackage) { 5684 // Ignore entries which are not packages 5685 continue; 5686 } 5687 try { 5688 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5689 scanFlags, currentTime, null); 5690 } catch (PackageManagerException e) { 5691 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5692 5693 // Delete invalid userdata apps 5694 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5695 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5696 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5697 if (file.isDirectory()) { 5698 mInstaller.rmPackageDir(file.getAbsolutePath()); 5699 } else { 5700 file.delete(); 5701 } 5702 } 5703 } 5704 } 5705 } 5706 5707 private static File getSettingsProblemFile() { 5708 File dataDir = Environment.getDataDirectory(); 5709 File systemDir = new File(dataDir, "system"); 5710 File fname = new File(systemDir, "uiderrors.txt"); 5711 return fname; 5712 } 5713 5714 static void reportSettingsProblem(int priority, String msg) { 5715 logCriticalInfo(priority, msg); 5716 } 5717 5718 static void logCriticalInfo(int priority, String msg) { 5719 Slog.println(priority, TAG, msg); 5720 EventLogTags.writePmCriticalInfo(msg); 5721 try { 5722 File fname = getSettingsProblemFile(); 5723 FileOutputStream out = new FileOutputStream(fname, true); 5724 PrintWriter pw = new FastPrintWriter(out); 5725 SimpleDateFormat formatter = new SimpleDateFormat(); 5726 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5727 pw.println(dateString + ": " + msg); 5728 pw.close(); 5729 FileUtils.setPermissions( 5730 fname.toString(), 5731 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5732 -1, -1); 5733 } catch (java.io.IOException e) { 5734 } 5735 } 5736 5737 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5738 PackageParser.Package pkg, File srcFile, int parseFlags) 5739 throws PackageManagerException { 5740 if (ps != null 5741 && ps.codePath.equals(srcFile) 5742 && ps.timeStamp == srcFile.lastModified() 5743 && !isCompatSignatureUpdateNeeded(pkg) 5744 && !isRecoverSignatureUpdateNeeded(pkg)) { 5745 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5746 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5747 ArraySet<PublicKey> signingKs; 5748 synchronized (mPackages) { 5749 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5750 } 5751 if (ps.signatures.mSignatures != null 5752 && ps.signatures.mSignatures.length != 0 5753 && signingKs != null) { 5754 // Optimization: reuse the existing cached certificates 5755 // if the package appears to be unchanged. 5756 pkg.mSignatures = ps.signatures.mSignatures; 5757 pkg.mSigningKeys = signingKs; 5758 return; 5759 } 5760 5761 Slog.w(TAG, "PackageSetting for " + ps.name 5762 + " is missing signatures. Collecting certs again to recover them."); 5763 } else { 5764 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5765 } 5766 5767 try { 5768 pp.collectCertificates(pkg, parseFlags); 5769 pp.collectManifestDigest(pkg); 5770 } catch (PackageParserException e) { 5771 throw PackageManagerException.from(e); 5772 } 5773 } 5774 5775 /** 5776 * Traces a package scan. 5777 * @see #scanPackageLI(File, int, int, long, UserHandle) 5778 */ 5779 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5780 long currentTime, UserHandle user) throws PackageManagerException { 5781 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5782 try { 5783 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5784 } finally { 5785 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5786 } 5787 } 5788 5789 /** 5790 * Scans a package and returns the newly parsed package. 5791 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5792 */ 5793 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5794 long currentTime, UserHandle user) throws PackageManagerException { 5795 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5796 parseFlags |= mDefParseFlags; 5797 PackageParser pp = new PackageParser(); 5798 pp.setSeparateProcesses(mSeparateProcesses); 5799 pp.setOnlyCoreApps(mOnlyCore); 5800 pp.setDisplayMetrics(mMetrics); 5801 5802 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5803 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5804 } 5805 5806 final PackageParser.Package pkg; 5807 try { 5808 pkg = pp.parsePackage(scanFile, parseFlags); 5809 } catch (PackageParserException e) { 5810 throw PackageManagerException.from(e); 5811 } 5812 5813 PackageSetting ps = null; 5814 PackageSetting updatedPkg; 5815 // reader 5816 synchronized (mPackages) { 5817 // Look to see if we already know about this package. 5818 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5819 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5820 // This package has been renamed to its original name. Let's 5821 // use that. 5822 ps = mSettings.peekPackageLPr(oldName); 5823 } 5824 // If there was no original package, see one for the real package name. 5825 if (ps == null) { 5826 ps = mSettings.peekPackageLPr(pkg.packageName); 5827 } 5828 // Check to see if this package could be hiding/updating a system 5829 // package. Must look for it either under the original or real 5830 // package name depending on our state. 5831 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5832 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5833 } 5834 boolean updatedPkgBetter = false; 5835 // First check if this is a system package that may involve an update 5836 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5837 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5838 // it needs to drop FLAG_PRIVILEGED. 5839 if (locationIsPrivileged(scanFile)) { 5840 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5841 } else { 5842 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5843 } 5844 5845 if (ps != null && !ps.codePath.equals(scanFile)) { 5846 // The path has changed from what was last scanned... check the 5847 // version of the new path against what we have stored to determine 5848 // what to do. 5849 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5850 if (pkg.mVersionCode <= ps.versionCode) { 5851 // The system package has been updated and the code path does not match 5852 // Ignore entry. Skip it. 5853 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5854 + " ignored: updated version " + ps.versionCode 5855 + " better than this " + pkg.mVersionCode); 5856 if (!updatedPkg.codePath.equals(scanFile)) { 5857 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5858 + ps.name + " changing from " + updatedPkg.codePathString 5859 + " to " + scanFile); 5860 updatedPkg.codePath = scanFile; 5861 updatedPkg.codePathString = scanFile.toString(); 5862 updatedPkg.resourcePath = scanFile; 5863 updatedPkg.resourcePathString = scanFile.toString(); 5864 } 5865 updatedPkg.pkg = pkg; 5866 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5867 "Package " + ps.name + " at " + scanFile 5868 + " ignored: updated version " + ps.versionCode 5869 + " better than this " + pkg.mVersionCode); 5870 } else { 5871 // The current app on the system partition is better than 5872 // what we have updated to on the data partition; switch 5873 // back to the system partition version. 5874 // At this point, its safely assumed that package installation for 5875 // apps in system partition will go through. If not there won't be a working 5876 // version of the app 5877 // writer 5878 synchronized (mPackages) { 5879 // Just remove the loaded entries from package lists. 5880 mPackages.remove(ps.name); 5881 } 5882 5883 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5884 + " reverting from " + ps.codePathString 5885 + ": new version " + pkg.mVersionCode 5886 + " better than installed " + ps.versionCode); 5887 5888 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5889 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5890 synchronized (mInstallLock) { 5891 args.cleanUpResourcesLI(); 5892 } 5893 synchronized (mPackages) { 5894 mSettings.enableSystemPackageLPw(ps.name); 5895 } 5896 updatedPkgBetter = true; 5897 } 5898 } 5899 } 5900 5901 if (updatedPkg != null) { 5902 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5903 // initially 5904 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5905 5906 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5907 // flag set initially 5908 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5909 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5910 } 5911 } 5912 5913 // Verify certificates against what was last scanned 5914 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5915 5916 /* 5917 * A new system app appeared, but we already had a non-system one of the 5918 * same name installed earlier. 5919 */ 5920 boolean shouldHideSystemApp = false; 5921 if (updatedPkg == null && ps != null 5922 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5923 /* 5924 * Check to make sure the signatures match first. If they don't, 5925 * wipe the installed application and its data. 5926 */ 5927 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5928 != PackageManager.SIGNATURE_MATCH) { 5929 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5930 + " signatures don't match existing userdata copy; removing"); 5931 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5932 ps = null; 5933 } else { 5934 /* 5935 * If the newly-added system app is an older version than the 5936 * already installed version, hide it. It will be scanned later 5937 * and re-added like an update. 5938 */ 5939 if (pkg.mVersionCode <= ps.versionCode) { 5940 shouldHideSystemApp = true; 5941 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5942 + " but new version " + pkg.mVersionCode + " better than installed " 5943 + ps.versionCode + "; hiding system"); 5944 } else { 5945 /* 5946 * The newly found system app is a newer version that the 5947 * one previously installed. Simply remove the 5948 * already-installed application and replace it with our own 5949 * while keeping the application data. 5950 */ 5951 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5952 + " reverting from " + ps.codePathString + ": new version " 5953 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5954 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5955 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5956 synchronized (mInstallLock) { 5957 args.cleanUpResourcesLI(); 5958 } 5959 } 5960 } 5961 } 5962 5963 // The apk is forward locked (not public) if its code and resources 5964 // are kept in different files. (except for app in either system or 5965 // vendor path). 5966 // TODO grab this value from PackageSettings 5967 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5968 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5969 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5970 } 5971 } 5972 5973 // TODO: extend to support forward-locked splits 5974 String resourcePath = null; 5975 String baseResourcePath = null; 5976 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5977 if (ps != null && ps.resourcePathString != null) { 5978 resourcePath = ps.resourcePathString; 5979 baseResourcePath = ps.resourcePathString; 5980 } else { 5981 // Should not happen at all. Just log an error. 5982 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5983 } 5984 } else { 5985 resourcePath = pkg.codePath; 5986 baseResourcePath = pkg.baseCodePath; 5987 } 5988 5989 // Set application objects path explicitly. 5990 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5991 pkg.applicationInfo.setCodePath(pkg.codePath); 5992 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5993 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5994 pkg.applicationInfo.setResourcePath(resourcePath); 5995 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5996 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5997 5998 // Note that we invoke the following method only if we are about to unpack an application 5999 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6000 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6001 6002 /* 6003 * If the system app should be overridden by a previously installed 6004 * data, hide the system app now and let the /data/app scan pick it up 6005 * again. 6006 */ 6007 if (shouldHideSystemApp) { 6008 synchronized (mPackages) { 6009 mSettings.disableSystemPackageLPw(pkg.packageName); 6010 } 6011 } 6012 6013 return scannedPkg; 6014 } 6015 6016 private static String fixProcessName(String defProcessName, 6017 String processName, int uid) { 6018 if (processName == null) { 6019 return defProcessName; 6020 } 6021 return processName; 6022 } 6023 6024 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6025 throws PackageManagerException { 6026 if (pkgSetting.signatures.mSignatures != null) { 6027 // Already existing package. Make sure signatures match 6028 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6029 == PackageManager.SIGNATURE_MATCH; 6030 if (!match) { 6031 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6032 == PackageManager.SIGNATURE_MATCH; 6033 } 6034 if (!match) { 6035 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6036 == PackageManager.SIGNATURE_MATCH; 6037 } 6038 if (!match) { 6039 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6040 + pkg.packageName + " signatures do not match the " 6041 + "previously installed version; ignoring!"); 6042 } 6043 } 6044 6045 // Check for shared user signatures 6046 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6047 // Already existing package. Make sure signatures match 6048 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6049 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6050 if (!match) { 6051 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6052 == PackageManager.SIGNATURE_MATCH; 6053 } 6054 if (!match) { 6055 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6056 == PackageManager.SIGNATURE_MATCH; 6057 } 6058 if (!match) { 6059 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6060 "Package " + pkg.packageName 6061 + " has no signatures that match those in shared user " 6062 + pkgSetting.sharedUser.name + "; ignoring!"); 6063 } 6064 } 6065 } 6066 6067 /** 6068 * Enforces that only the system UID or root's UID can call a method exposed 6069 * via Binder. 6070 * 6071 * @param message used as message if SecurityException is thrown 6072 * @throws SecurityException if the caller is not system or root 6073 */ 6074 private static final void enforceSystemOrRoot(String message) { 6075 final int uid = Binder.getCallingUid(); 6076 if (uid != Process.SYSTEM_UID && uid != 0) { 6077 throw new SecurityException(message); 6078 } 6079 } 6080 6081 @Override 6082 public void performBootDexOpt() { 6083 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6084 6085 // Before everything else, see whether we need to fstrim. 6086 try { 6087 IMountService ms = PackageHelper.getMountService(); 6088 if (ms != null) { 6089 final boolean isUpgrade = isUpgrade(); 6090 boolean doTrim = isUpgrade; 6091 if (doTrim) { 6092 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6093 } else { 6094 final long interval = android.provider.Settings.Global.getLong( 6095 mContext.getContentResolver(), 6096 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6097 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6098 if (interval > 0) { 6099 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6100 if (timeSinceLast > interval) { 6101 doTrim = true; 6102 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6103 + "; running immediately"); 6104 } 6105 } 6106 } 6107 if (doTrim) { 6108 if (!isFirstBoot()) { 6109 try { 6110 ActivityManagerNative.getDefault().showBootMessage( 6111 mContext.getResources().getString( 6112 R.string.android_upgrading_fstrim), true); 6113 } catch (RemoteException e) { 6114 } 6115 } 6116 ms.runMaintenance(); 6117 } 6118 } else { 6119 Slog.e(TAG, "Mount service unavailable!"); 6120 } 6121 } catch (RemoteException e) { 6122 // Can't happen; MountService is local 6123 } 6124 6125 final ArraySet<PackageParser.Package> pkgs; 6126 synchronized (mPackages) { 6127 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6128 } 6129 6130 if (pkgs != null) { 6131 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6132 // in case the device runs out of space. 6133 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6134 // Give priority to core apps. 6135 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6136 PackageParser.Package pkg = it.next(); 6137 if (pkg.coreApp) { 6138 if (DEBUG_DEXOPT) { 6139 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6140 } 6141 sortedPkgs.add(pkg); 6142 it.remove(); 6143 } 6144 } 6145 // Give priority to system apps that listen for pre boot complete. 6146 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6147 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6148 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6149 PackageParser.Package pkg = it.next(); 6150 if (pkgNames.contains(pkg.packageName)) { 6151 if (DEBUG_DEXOPT) { 6152 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6153 } 6154 sortedPkgs.add(pkg); 6155 it.remove(); 6156 } 6157 } 6158 // Give priority to system apps. 6159 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6160 PackageParser.Package pkg = it.next(); 6161 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6162 if (DEBUG_DEXOPT) { 6163 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6164 } 6165 sortedPkgs.add(pkg); 6166 it.remove(); 6167 } 6168 } 6169 // Give priority to updated system apps. 6170 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6171 PackageParser.Package pkg = it.next(); 6172 if (pkg.isUpdatedSystemApp()) { 6173 if (DEBUG_DEXOPT) { 6174 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6175 } 6176 sortedPkgs.add(pkg); 6177 it.remove(); 6178 } 6179 } 6180 // Give priority to apps that listen for boot complete. 6181 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6182 pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6183 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6184 PackageParser.Package pkg = it.next(); 6185 if (pkgNames.contains(pkg.packageName)) { 6186 if (DEBUG_DEXOPT) { 6187 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6188 } 6189 sortedPkgs.add(pkg); 6190 it.remove(); 6191 } 6192 } 6193 // Filter out packages that aren't recently used. 6194 filterRecentlyUsedApps(pkgs); 6195 // Add all remaining apps. 6196 for (PackageParser.Package pkg : pkgs) { 6197 if (DEBUG_DEXOPT) { 6198 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6199 } 6200 sortedPkgs.add(pkg); 6201 } 6202 6203 // If we want to be lazy, filter everything that wasn't recently used. 6204 if (mLazyDexOpt) { 6205 filterRecentlyUsedApps(sortedPkgs); 6206 } 6207 6208 int i = 0; 6209 int total = sortedPkgs.size(); 6210 File dataDir = Environment.getDataDirectory(); 6211 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6212 if (lowThreshold == 0) { 6213 throw new IllegalStateException("Invalid low memory threshold"); 6214 } 6215 for (PackageParser.Package pkg : sortedPkgs) { 6216 long usableSpace = dataDir.getUsableSpace(); 6217 if (usableSpace < lowThreshold) { 6218 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6219 break; 6220 } 6221 performBootDexOpt(pkg, ++i, total); 6222 } 6223 } 6224 } 6225 6226 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6227 // Filter out packages that aren't recently used. 6228 // 6229 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6230 // should do a full dexopt. 6231 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6232 int total = pkgs.size(); 6233 int skipped = 0; 6234 long now = System.currentTimeMillis(); 6235 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6236 PackageParser.Package pkg = i.next(); 6237 long then = pkg.mLastPackageUsageTimeInMills; 6238 if (then + mDexOptLRUThresholdInMills < now) { 6239 if (DEBUG_DEXOPT) { 6240 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6241 ((then == 0) ? "never" : new Date(then))); 6242 } 6243 i.remove(); 6244 skipped++; 6245 } 6246 } 6247 if (DEBUG_DEXOPT) { 6248 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6249 } 6250 } 6251 } 6252 6253 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6254 List<ResolveInfo> ris = null; 6255 try { 6256 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6257 intent, null, 0, userId); 6258 } catch (RemoteException e) { 6259 } 6260 ArraySet<String> pkgNames = new ArraySet<String>(); 6261 if (ris != null) { 6262 for (ResolveInfo ri : ris) { 6263 pkgNames.add(ri.activityInfo.packageName); 6264 } 6265 } 6266 return pkgNames; 6267 } 6268 6269 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6270 if (DEBUG_DEXOPT) { 6271 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6272 } 6273 if (!isFirstBoot()) { 6274 try { 6275 ActivityManagerNative.getDefault().showBootMessage( 6276 mContext.getResources().getString(R.string.android_upgrading_apk, 6277 curr, total), true); 6278 } catch (RemoteException e) { 6279 } 6280 } 6281 PackageParser.Package p = pkg; 6282 synchronized (mInstallLock) { 6283 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6284 false /* force dex */, false /* defer */, true /* include dependencies */); 6285 } 6286 } 6287 6288 @Override 6289 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6290 return performDexOptTraced(packageName, instructionSet, false); 6291 } 6292 6293 public boolean performDexOpt( 6294 String packageName, String instructionSet, boolean backgroundDexopt) { 6295 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6296 } 6297 6298 private boolean performDexOptTraced( 6299 String packageName, String instructionSet, boolean backgroundDexopt) { 6300 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6301 try { 6302 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6303 } finally { 6304 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6305 } 6306 } 6307 6308 private boolean performDexOptInternal( 6309 String packageName, String instructionSet, boolean backgroundDexopt) { 6310 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6311 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6312 if (!dexopt && !updateUsage) { 6313 // We aren't going to dexopt or update usage, so bail early. 6314 return false; 6315 } 6316 PackageParser.Package p; 6317 final String targetInstructionSet; 6318 synchronized (mPackages) { 6319 p = mPackages.get(packageName); 6320 if (p == null) { 6321 return false; 6322 } 6323 if (updateUsage) { 6324 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6325 } 6326 mPackageUsage.write(false); 6327 if (!dexopt) { 6328 // We aren't going to dexopt, so bail early. 6329 return false; 6330 } 6331 6332 targetInstructionSet = instructionSet != null ? instructionSet : 6333 getPrimaryInstructionSet(p.applicationInfo); 6334 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6335 return false; 6336 } 6337 } 6338 long callingId = Binder.clearCallingIdentity(); 6339 try { 6340 synchronized (mInstallLock) { 6341 final String[] instructionSets = new String[] { targetInstructionSet }; 6342 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6343 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6344 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6345 } 6346 } finally { 6347 Binder.restoreCallingIdentity(callingId); 6348 } 6349 } 6350 6351 public ArraySet<String> getPackagesThatNeedDexOpt() { 6352 ArraySet<String> pkgs = null; 6353 synchronized (mPackages) { 6354 for (PackageParser.Package p : mPackages.values()) { 6355 if (DEBUG_DEXOPT) { 6356 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6357 } 6358 if (!p.mDexOptPerformed.isEmpty()) { 6359 continue; 6360 } 6361 if (pkgs == null) { 6362 pkgs = new ArraySet<String>(); 6363 } 6364 pkgs.add(p.packageName); 6365 } 6366 } 6367 return pkgs; 6368 } 6369 6370 public void shutdown() { 6371 mPackageUsage.write(true); 6372 } 6373 6374 @Override 6375 public void forceDexOpt(String packageName) { 6376 enforceSystemOrRoot("forceDexOpt"); 6377 6378 PackageParser.Package pkg; 6379 synchronized (mPackages) { 6380 pkg = mPackages.get(packageName); 6381 if (pkg == null) { 6382 throw new IllegalArgumentException("Missing package: " + packageName); 6383 } 6384 } 6385 6386 synchronized (mInstallLock) { 6387 final String[] instructionSets = new String[] { 6388 getPrimaryInstructionSet(pkg.applicationInfo) }; 6389 6390 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6391 6392 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6393 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6394 6395 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6396 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6397 throw new IllegalStateException("Failed to dexopt: " + res); 6398 } 6399 } 6400 } 6401 6402 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6403 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6404 Slog.w(TAG, "Unable to update from " + oldPkg.name 6405 + " to " + newPkg.packageName 6406 + ": old package not in system partition"); 6407 return false; 6408 } else if (mPackages.get(oldPkg.name) != null) { 6409 Slog.w(TAG, "Unable to update from " + oldPkg.name 6410 + " to " + newPkg.packageName 6411 + ": old package still exists"); 6412 return false; 6413 } 6414 return true; 6415 } 6416 6417 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6418 int[] users = sUserManager.getUserIds(); 6419 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6420 if (res < 0) { 6421 return res; 6422 } 6423 for (int user : users) { 6424 if (user != 0) { 6425 res = mInstaller.createUserData(volumeUuid, packageName, 6426 UserHandle.getUid(user, uid), user, seinfo); 6427 if (res < 0) { 6428 return res; 6429 } 6430 } 6431 } 6432 return res; 6433 } 6434 6435 private int removeDataDirsLI(String volumeUuid, String packageName) { 6436 int[] users = sUserManager.getUserIds(); 6437 int res = 0; 6438 for (int user : users) { 6439 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6440 if (resInner < 0) { 6441 res = resInner; 6442 } 6443 } 6444 6445 return res; 6446 } 6447 6448 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6449 int[] users = sUserManager.getUserIds(); 6450 int res = 0; 6451 for (int user : users) { 6452 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6453 if (resInner < 0) { 6454 res = resInner; 6455 } 6456 } 6457 return res; 6458 } 6459 6460 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6461 PackageParser.Package changingLib) { 6462 if (file.path != null) { 6463 usesLibraryFiles.add(file.path); 6464 return; 6465 } 6466 PackageParser.Package p = mPackages.get(file.apk); 6467 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6468 // If we are doing this while in the middle of updating a library apk, 6469 // then we need to make sure to use that new apk for determining the 6470 // dependencies here. (We haven't yet finished committing the new apk 6471 // to the package manager state.) 6472 if (p == null || p.packageName.equals(changingLib.packageName)) { 6473 p = changingLib; 6474 } 6475 } 6476 if (p != null) { 6477 usesLibraryFiles.addAll(p.getAllCodePaths()); 6478 } 6479 } 6480 6481 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6482 PackageParser.Package changingLib) throws PackageManagerException { 6483 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6484 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6485 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6486 for (int i=0; i<N; i++) { 6487 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6488 if (file == null) { 6489 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6490 "Package " + pkg.packageName + " requires unavailable shared library " 6491 + pkg.usesLibraries.get(i) + "; failing!"); 6492 } 6493 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6494 } 6495 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6496 for (int i=0; i<N; i++) { 6497 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6498 if (file == null) { 6499 Slog.w(TAG, "Package " + pkg.packageName 6500 + " desires unavailable shared library " 6501 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6502 } else { 6503 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6504 } 6505 } 6506 N = usesLibraryFiles.size(); 6507 if (N > 0) { 6508 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6509 } else { 6510 pkg.usesLibraryFiles = null; 6511 } 6512 } 6513 } 6514 6515 private static boolean hasString(List<String> list, List<String> which) { 6516 if (list == null) { 6517 return false; 6518 } 6519 for (int i=list.size()-1; i>=0; i--) { 6520 for (int j=which.size()-1; j>=0; j--) { 6521 if (which.get(j).equals(list.get(i))) { 6522 return true; 6523 } 6524 } 6525 } 6526 return false; 6527 } 6528 6529 private void updateAllSharedLibrariesLPw() { 6530 for (PackageParser.Package pkg : mPackages.values()) { 6531 try { 6532 updateSharedLibrariesLPw(pkg, null); 6533 } catch (PackageManagerException e) { 6534 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6535 } 6536 } 6537 } 6538 6539 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6540 PackageParser.Package changingPkg) { 6541 ArrayList<PackageParser.Package> res = null; 6542 for (PackageParser.Package pkg : mPackages.values()) { 6543 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6544 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6545 if (res == null) { 6546 res = new ArrayList<PackageParser.Package>(); 6547 } 6548 res.add(pkg); 6549 try { 6550 updateSharedLibrariesLPw(pkg, changingPkg); 6551 } catch (PackageManagerException e) { 6552 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6553 } 6554 } 6555 } 6556 return res; 6557 } 6558 6559 /** 6560 * Derive the value of the {@code cpuAbiOverride} based on the provided 6561 * value and an optional stored value from the package settings. 6562 */ 6563 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6564 String cpuAbiOverride = null; 6565 6566 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6567 cpuAbiOverride = null; 6568 } else if (abiOverride != null) { 6569 cpuAbiOverride = abiOverride; 6570 } else if (settings != null) { 6571 cpuAbiOverride = settings.cpuAbiOverrideString; 6572 } 6573 6574 return cpuAbiOverride; 6575 } 6576 6577 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6578 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6579 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6580 try { 6581 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6582 } finally { 6583 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6584 } 6585 } 6586 6587 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6588 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6589 boolean success = false; 6590 try { 6591 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6592 currentTime, user); 6593 success = true; 6594 return res; 6595 } finally { 6596 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6597 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6598 } 6599 } 6600 } 6601 6602 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6603 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6604 final File scanFile = new File(pkg.codePath); 6605 if (pkg.applicationInfo.getCodePath() == null || 6606 pkg.applicationInfo.getResourcePath() == null) { 6607 // Bail out. The resource and code paths haven't been set. 6608 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6609 "Code and resource paths haven't been set correctly"); 6610 } 6611 6612 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6613 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6614 } else { 6615 // Only allow system apps to be flagged as core apps. 6616 pkg.coreApp = false; 6617 } 6618 6619 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6620 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6621 } 6622 6623 if (mCustomResolverComponentName != null && 6624 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6625 setUpCustomResolverActivity(pkg); 6626 } 6627 6628 if (pkg.packageName.equals("android")) { 6629 synchronized (mPackages) { 6630 if (mAndroidApplication != null) { 6631 Slog.w(TAG, "*************************************************"); 6632 Slog.w(TAG, "Core android package being redefined. Skipping."); 6633 Slog.w(TAG, " file=" + scanFile); 6634 Slog.w(TAG, "*************************************************"); 6635 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6636 "Core android package being redefined. Skipping."); 6637 } 6638 6639 // Set up information for our fall-back user intent resolution activity. 6640 mPlatformPackage = pkg; 6641 pkg.mVersionCode = mSdkVersion; 6642 mAndroidApplication = pkg.applicationInfo; 6643 6644 if (!mResolverReplaced) { 6645 mResolveActivity.applicationInfo = mAndroidApplication; 6646 mResolveActivity.name = ResolverActivity.class.getName(); 6647 mResolveActivity.packageName = mAndroidApplication.packageName; 6648 mResolveActivity.processName = "system:ui"; 6649 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6650 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6651 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6652 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6653 mResolveActivity.exported = true; 6654 mResolveActivity.enabled = true; 6655 mResolveInfo.activityInfo = mResolveActivity; 6656 mResolveInfo.priority = 0; 6657 mResolveInfo.preferredOrder = 0; 6658 mResolveInfo.match = 0; 6659 mResolveComponentName = new ComponentName( 6660 mAndroidApplication.packageName, mResolveActivity.name); 6661 } 6662 } 6663 } 6664 6665 if (DEBUG_PACKAGE_SCANNING) { 6666 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6667 Log.d(TAG, "Scanning package " + pkg.packageName); 6668 } 6669 6670 if (mPackages.containsKey(pkg.packageName) 6671 || mSharedLibraries.containsKey(pkg.packageName)) { 6672 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6673 "Application package " + pkg.packageName 6674 + " already installed. Skipping duplicate."); 6675 } 6676 6677 // If we're only installing presumed-existing packages, require that the 6678 // scanned APK is both already known and at the path previously established 6679 // for it. Previously unknown packages we pick up normally, but if we have an 6680 // a priori expectation about this package's install presence, enforce it. 6681 // With a singular exception for new system packages. When an OTA contains 6682 // a new system package, we allow the codepath to change from a system location 6683 // to the user-installed location. If we don't allow this change, any newer, 6684 // user-installed version of the application will be ignored. 6685 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6686 if (mExpectingBetter.containsKey(pkg.packageName)) { 6687 logCriticalInfo(Log.WARN, 6688 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6689 } else { 6690 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6691 if (known != null) { 6692 if (DEBUG_PACKAGE_SCANNING) { 6693 Log.d(TAG, "Examining " + pkg.codePath 6694 + " and requiring known paths " + known.codePathString 6695 + " & " + known.resourcePathString); 6696 } 6697 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6698 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6699 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6700 "Application package " + pkg.packageName 6701 + " found at " + pkg.applicationInfo.getCodePath() 6702 + " but expected at " + known.codePathString + "; ignoring."); 6703 } 6704 } 6705 } 6706 } 6707 6708 // Initialize package source and resource directories 6709 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6710 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6711 6712 SharedUserSetting suid = null; 6713 PackageSetting pkgSetting = null; 6714 6715 if (!isSystemApp(pkg)) { 6716 // Only system apps can use these features. 6717 pkg.mOriginalPackages = null; 6718 pkg.mRealPackage = null; 6719 pkg.mAdoptPermissions = null; 6720 } 6721 6722 // writer 6723 synchronized (mPackages) { 6724 if (pkg.mSharedUserId != null) { 6725 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6726 if (suid == null) { 6727 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6728 "Creating application package " + pkg.packageName 6729 + " for shared user failed"); 6730 } 6731 if (DEBUG_PACKAGE_SCANNING) { 6732 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6733 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6734 + "): packages=" + suid.packages); 6735 } 6736 } 6737 6738 // Check if we are renaming from an original package name. 6739 PackageSetting origPackage = null; 6740 String realName = null; 6741 if (pkg.mOriginalPackages != null) { 6742 // This package may need to be renamed to a previously 6743 // installed name. Let's check on that... 6744 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6745 if (pkg.mOriginalPackages.contains(renamed)) { 6746 // This package had originally been installed as the 6747 // original name, and we have already taken care of 6748 // transitioning to the new one. Just update the new 6749 // one to continue using the old name. 6750 realName = pkg.mRealPackage; 6751 if (!pkg.packageName.equals(renamed)) { 6752 // Callers into this function may have already taken 6753 // care of renaming the package; only do it here if 6754 // it is not already done. 6755 pkg.setPackageName(renamed); 6756 } 6757 6758 } else { 6759 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6760 if ((origPackage = mSettings.peekPackageLPr( 6761 pkg.mOriginalPackages.get(i))) != null) { 6762 // We do have the package already installed under its 6763 // original name... should we use it? 6764 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6765 // New package is not compatible with original. 6766 origPackage = null; 6767 continue; 6768 } else if (origPackage.sharedUser != null) { 6769 // Make sure uid is compatible between packages. 6770 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6771 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6772 + " to " + pkg.packageName + ": old uid " 6773 + origPackage.sharedUser.name 6774 + " differs from " + pkg.mSharedUserId); 6775 origPackage = null; 6776 continue; 6777 } 6778 } else { 6779 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6780 + pkg.packageName + " to old name " + origPackage.name); 6781 } 6782 break; 6783 } 6784 } 6785 } 6786 } 6787 6788 if (mTransferedPackages.contains(pkg.packageName)) { 6789 Slog.w(TAG, "Package " + pkg.packageName 6790 + " was transferred to another, but its .apk remains"); 6791 } 6792 6793 // Just create the setting, don't add it yet. For already existing packages 6794 // the PkgSetting exists already and doesn't have to be created. 6795 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6796 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6797 pkg.applicationInfo.primaryCpuAbi, 6798 pkg.applicationInfo.secondaryCpuAbi, 6799 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6800 user, false); 6801 if (pkgSetting == null) { 6802 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6803 "Creating application package " + pkg.packageName + " failed"); 6804 } 6805 6806 if (pkgSetting.origPackage != null) { 6807 // If we are first transitioning from an original package, 6808 // fix up the new package's name now. We need to do this after 6809 // looking up the package under its new name, so getPackageLP 6810 // can take care of fiddling things correctly. 6811 pkg.setPackageName(origPackage.name); 6812 6813 // File a report about this. 6814 String msg = "New package " + pkgSetting.realName 6815 + " renamed to replace old package " + pkgSetting.name; 6816 reportSettingsProblem(Log.WARN, msg); 6817 6818 // Make a note of it. 6819 mTransferedPackages.add(origPackage.name); 6820 6821 // No longer need to retain this. 6822 pkgSetting.origPackage = null; 6823 } 6824 6825 if (realName != null) { 6826 // Make a note of it. 6827 mTransferedPackages.add(pkg.packageName); 6828 } 6829 6830 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6831 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6832 } 6833 6834 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6835 // Check all shared libraries and map to their actual file path. 6836 // We only do this here for apps not on a system dir, because those 6837 // are the only ones that can fail an install due to this. We 6838 // will take care of the system apps by updating all of their 6839 // library paths after the scan is done. 6840 updateSharedLibrariesLPw(pkg, null); 6841 } 6842 6843 if (mFoundPolicyFile) { 6844 SELinuxMMAC.assignSeinfoValue(pkg); 6845 } 6846 6847 pkg.applicationInfo.uid = pkgSetting.appId; 6848 pkg.mExtras = pkgSetting; 6849 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6850 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6851 // We just determined the app is signed correctly, so bring 6852 // over the latest parsed certs. 6853 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6854 } else { 6855 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6856 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6857 "Package " + pkg.packageName + " upgrade keys do not match the " 6858 + "previously installed version"); 6859 } else { 6860 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6861 String msg = "System package " + pkg.packageName 6862 + " signature changed; retaining data."; 6863 reportSettingsProblem(Log.WARN, msg); 6864 } 6865 } 6866 } else { 6867 try { 6868 verifySignaturesLP(pkgSetting, pkg); 6869 // We just determined the app is signed correctly, so bring 6870 // over the latest parsed certs. 6871 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6872 } catch (PackageManagerException e) { 6873 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6874 throw e; 6875 } 6876 // The signature has changed, but this package is in the system 6877 // image... let's recover! 6878 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6879 // However... if this package is part of a shared user, but it 6880 // doesn't match the signature of the shared user, let's fail. 6881 // What this means is that you can't change the signatures 6882 // associated with an overall shared user, which doesn't seem all 6883 // that unreasonable. 6884 if (pkgSetting.sharedUser != null) { 6885 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6886 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6887 throw new PackageManagerException( 6888 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6889 "Signature mismatch for shared user : " 6890 + pkgSetting.sharedUser); 6891 } 6892 } 6893 // File a report about this. 6894 String msg = "System package " + pkg.packageName 6895 + " signature changed; retaining data."; 6896 reportSettingsProblem(Log.WARN, msg); 6897 } 6898 } 6899 // Verify that this new package doesn't have any content providers 6900 // that conflict with existing packages. Only do this if the 6901 // package isn't already installed, since we don't want to break 6902 // things that are installed. 6903 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6904 final int N = pkg.providers.size(); 6905 int i; 6906 for (i=0; i<N; i++) { 6907 PackageParser.Provider p = pkg.providers.get(i); 6908 if (p.info.authority != null) { 6909 String names[] = p.info.authority.split(";"); 6910 for (int j = 0; j < names.length; j++) { 6911 if (mProvidersByAuthority.containsKey(names[j])) { 6912 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6913 final String otherPackageName = 6914 ((other != null && other.getComponentName() != null) ? 6915 other.getComponentName().getPackageName() : "?"); 6916 throw new PackageManagerException( 6917 INSTALL_FAILED_CONFLICTING_PROVIDER, 6918 "Can't install because provider name " + names[j] 6919 + " (in package " + pkg.applicationInfo.packageName 6920 + ") is already used by " + otherPackageName); 6921 } 6922 } 6923 } 6924 } 6925 } 6926 6927 if (pkg.mAdoptPermissions != null) { 6928 // This package wants to adopt ownership of permissions from 6929 // another package. 6930 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6931 final String origName = pkg.mAdoptPermissions.get(i); 6932 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6933 if (orig != null) { 6934 if (verifyPackageUpdateLPr(orig, pkg)) { 6935 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6936 + pkg.packageName); 6937 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6938 } 6939 } 6940 } 6941 } 6942 } 6943 6944 final String pkgName = pkg.packageName; 6945 6946 final long scanFileTime = scanFile.lastModified(); 6947 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6948 pkg.applicationInfo.processName = fixProcessName( 6949 pkg.applicationInfo.packageName, 6950 pkg.applicationInfo.processName, 6951 pkg.applicationInfo.uid); 6952 6953 File dataPath; 6954 if (mPlatformPackage == pkg) { 6955 // The system package is special. 6956 dataPath = new File(Environment.getDataDirectory(), "system"); 6957 6958 pkg.applicationInfo.dataDir = dataPath.getPath(); 6959 6960 } else { 6961 // This is a normal package, need to make its data directory. 6962 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6963 UserHandle.USER_OWNER, pkg.packageName); 6964 6965 boolean uidError = false; 6966 if (dataPath.exists()) { 6967 int currentUid = 0; 6968 try { 6969 StructStat stat = Os.stat(dataPath.getPath()); 6970 currentUid = stat.st_uid; 6971 } catch (ErrnoException e) { 6972 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6973 } 6974 6975 // If we have mismatched owners for the data path, we have a problem. 6976 if (currentUid != pkg.applicationInfo.uid) { 6977 boolean recovered = false; 6978 if (currentUid == 0) { 6979 // The directory somehow became owned by root. Wow. 6980 // This is probably because the system was stopped while 6981 // installd was in the middle of messing with its libs 6982 // directory. Ask installd to fix that. 6983 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6984 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6985 if (ret >= 0) { 6986 recovered = true; 6987 String msg = "Package " + pkg.packageName 6988 + " unexpectedly changed to uid 0; recovered to " + 6989 + pkg.applicationInfo.uid; 6990 reportSettingsProblem(Log.WARN, msg); 6991 } 6992 } 6993 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6994 || (scanFlags&SCAN_BOOTING) != 0)) { 6995 // If this is a system app, we can at least delete its 6996 // current data so the application will still work. 6997 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6998 if (ret >= 0) { 6999 // TODO: Kill the processes first 7000 // Old data gone! 7001 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7002 ? "System package " : "Third party package "; 7003 String msg = prefix + pkg.packageName 7004 + " has changed from uid: " 7005 + currentUid + " to " 7006 + pkg.applicationInfo.uid + "; old data erased"; 7007 reportSettingsProblem(Log.WARN, msg); 7008 recovered = true; 7009 7010 // And now re-install the app. 7011 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7012 pkg.applicationInfo.seinfo); 7013 if (ret == -1) { 7014 // Ack should not happen! 7015 msg = prefix + pkg.packageName 7016 + " could not have data directory re-created after delete."; 7017 reportSettingsProblem(Log.WARN, msg); 7018 throw new PackageManagerException( 7019 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 7020 } 7021 } 7022 if (!recovered) { 7023 mHasSystemUidErrors = true; 7024 } 7025 } else if (!recovered) { 7026 // If we allow this install to proceed, we will be broken. 7027 // Abort, abort! 7028 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7029 "scanPackageLI"); 7030 } 7031 if (!recovered) { 7032 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7033 + pkg.applicationInfo.uid + "/fs_" 7034 + currentUid; 7035 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7036 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7037 String msg = "Package " + pkg.packageName 7038 + " has mismatched uid: " 7039 + currentUid + " on disk, " 7040 + pkg.applicationInfo.uid + " in settings"; 7041 // writer 7042 synchronized (mPackages) { 7043 mSettings.mReadMessages.append(msg); 7044 mSettings.mReadMessages.append('\n'); 7045 uidError = true; 7046 if (!pkgSetting.uidError) { 7047 reportSettingsProblem(Log.ERROR, msg); 7048 } 7049 } 7050 } 7051 } 7052 pkg.applicationInfo.dataDir = dataPath.getPath(); 7053 if (mShouldRestoreconData) { 7054 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7055 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7056 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7057 } 7058 } else { 7059 if (DEBUG_PACKAGE_SCANNING) { 7060 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7061 Log.v(TAG, "Want this data dir: " + dataPath); 7062 } 7063 //invoke installer to do the actual installation 7064 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7065 pkg.applicationInfo.seinfo); 7066 if (ret < 0) { 7067 // Error from installer 7068 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7069 "Unable to create data dirs [errorCode=" + ret + "]"); 7070 } 7071 7072 if (dataPath.exists()) { 7073 pkg.applicationInfo.dataDir = dataPath.getPath(); 7074 } else { 7075 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7076 pkg.applicationInfo.dataDir = null; 7077 } 7078 } 7079 7080 pkgSetting.uidError = uidError; 7081 } 7082 7083 final String path = scanFile.getPath(); 7084 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7085 7086 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7087 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7088 7089 // Some system apps still use directory structure for native libraries 7090 // in which case we might end up not detecting abi solely based on apk 7091 // structure. Try to detect abi based on directory structure. 7092 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7093 pkg.applicationInfo.primaryCpuAbi == null) { 7094 setBundledAppAbisAndRoots(pkg, pkgSetting); 7095 setNativeLibraryPaths(pkg); 7096 } 7097 7098 } else { 7099 if ((scanFlags & SCAN_MOVE) != 0) { 7100 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7101 // but we already have this packages package info in the PackageSetting. We just 7102 // use that and derive the native library path based on the new codepath. 7103 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7104 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7105 } 7106 7107 // Set native library paths again. For moves, the path will be updated based on the 7108 // ABIs we've determined above. For non-moves, the path will be updated based on the 7109 // ABIs we determined during compilation, but the path will depend on the final 7110 // package path (after the rename away from the stage path). 7111 setNativeLibraryPaths(pkg); 7112 } 7113 7114 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7115 final int[] userIds = sUserManager.getUserIds(); 7116 synchronized (mInstallLock) { 7117 // Make sure all user data directories are ready to roll; we're okay 7118 // if they already exist 7119 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7120 for (int userId : userIds) { 7121 if (userId != 0) { 7122 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7123 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7124 pkg.applicationInfo.seinfo); 7125 } 7126 } 7127 } 7128 7129 // Create a native library symlink only if we have native libraries 7130 // and if the native libraries are 32 bit libraries. We do not provide 7131 // this symlink for 64 bit libraries. 7132 if (pkg.applicationInfo.primaryCpuAbi != null && 7133 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7134 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7135 try { 7136 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7137 for (int userId : userIds) { 7138 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7139 nativeLibPath, userId) < 0) { 7140 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7141 "Failed linking native library dir (user=" + userId + ")"); 7142 } 7143 } 7144 } finally { 7145 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7146 } 7147 } 7148 } 7149 7150 // This is a special case for the "system" package, where the ABI is 7151 // dictated by the zygote configuration (and init.rc). We should keep track 7152 // of this ABI so that we can deal with "normal" applications that run under 7153 // the same UID correctly. 7154 if (mPlatformPackage == pkg) { 7155 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7156 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7157 } 7158 7159 // If there's a mismatch between the abi-override in the package setting 7160 // and the abiOverride specified for the install. Warn about this because we 7161 // would've already compiled the app without taking the package setting into 7162 // account. 7163 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7164 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7165 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7166 " for package: " + pkg.packageName); 7167 } 7168 } 7169 7170 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7171 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7172 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7173 7174 // Copy the derived override back to the parsed package, so that we can 7175 // update the package settings accordingly. 7176 pkg.cpuAbiOverride = cpuAbiOverride; 7177 7178 if (DEBUG_ABI_SELECTION) { 7179 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7180 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7181 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7182 } 7183 7184 // Push the derived path down into PackageSettings so we know what to 7185 // clean up at uninstall time. 7186 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7187 7188 if (DEBUG_ABI_SELECTION) { 7189 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7190 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7191 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7192 } 7193 7194 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7195 // We don't do this here during boot because we can do it all 7196 // at once after scanning all existing packages. 7197 // 7198 // We also do this *before* we perform dexopt on this package, so that 7199 // we can avoid redundant dexopts, and also to make sure we've got the 7200 // code and package path correct. 7201 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7202 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7203 } 7204 7205 if ((scanFlags & SCAN_NO_DEX) == 0) { 7206 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7207 7208 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7209 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7210 7211 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7212 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7213 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7214 } 7215 } 7216 if (mFactoryTest && pkg.requestedPermissions.contains( 7217 android.Manifest.permission.FACTORY_TEST)) { 7218 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7219 } 7220 7221 ArrayList<PackageParser.Package> clientLibPkgs = null; 7222 7223 // writer 7224 synchronized (mPackages) { 7225 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7226 // Only system apps can add new shared libraries. 7227 if (pkg.libraryNames != null) { 7228 for (int i=0; i<pkg.libraryNames.size(); i++) { 7229 String name = pkg.libraryNames.get(i); 7230 boolean allowed = false; 7231 if (pkg.isUpdatedSystemApp()) { 7232 // New library entries can only be added through the 7233 // system image. This is important to get rid of a lot 7234 // of nasty edge cases: for example if we allowed a non- 7235 // system update of the app to add a library, then uninstalling 7236 // the update would make the library go away, and assumptions 7237 // we made such as through app install filtering would now 7238 // have allowed apps on the device which aren't compatible 7239 // with it. Better to just have the restriction here, be 7240 // conservative, and create many fewer cases that can negatively 7241 // impact the user experience. 7242 final PackageSetting sysPs = mSettings 7243 .getDisabledSystemPkgLPr(pkg.packageName); 7244 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7245 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7246 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7247 allowed = true; 7248 allowed = true; 7249 break; 7250 } 7251 } 7252 } 7253 } else { 7254 allowed = true; 7255 } 7256 if (allowed) { 7257 if (!mSharedLibraries.containsKey(name)) { 7258 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7259 } else if (!name.equals(pkg.packageName)) { 7260 Slog.w(TAG, "Package " + pkg.packageName + " library " 7261 + name + " already exists; skipping"); 7262 } 7263 } else { 7264 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7265 + name + " that is not declared on system image; skipping"); 7266 } 7267 } 7268 if ((scanFlags&SCAN_BOOTING) == 0) { 7269 // If we are not booting, we need to update any applications 7270 // that are clients of our shared library. If we are booting, 7271 // this will all be done once the scan is complete. 7272 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7273 } 7274 } 7275 } 7276 } 7277 7278 // We also need to dexopt any apps that are dependent on this library. Note that 7279 // if these fail, we should abort the install since installing the library will 7280 // result in some apps being broken. 7281 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7282 try { 7283 if (clientLibPkgs != null) { 7284 if ((scanFlags & SCAN_NO_DEX) == 0) { 7285 for (int i = 0; i < clientLibPkgs.size(); i++) { 7286 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7287 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7288 null /* instruction sets */, forceDex, 7289 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7290 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7291 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7292 "scanPackageLI failed to dexopt clientLibPkgs"); 7293 } 7294 } 7295 } 7296 } 7297 } finally { 7298 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7299 } 7300 7301 // Request the ActivityManager to kill the process(only for existing packages) 7302 // so that we do not end up in a confused state while the user is still using the older 7303 // version of the application while the new one gets installed. 7304 if ((scanFlags & SCAN_REPLACING) != 0) { 7305 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7306 7307 killApplication(pkg.applicationInfo.packageName, 7308 pkg.applicationInfo.uid, "replace pkg"); 7309 7310 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7311 } 7312 7313 // Also need to kill any apps that are dependent on the library. 7314 if (clientLibPkgs != null) { 7315 for (int i=0; i<clientLibPkgs.size(); i++) { 7316 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7317 killApplication(clientPkg.applicationInfo.packageName, 7318 clientPkg.applicationInfo.uid, "update lib"); 7319 } 7320 } 7321 7322 // Make sure we're not adding any bogus keyset info 7323 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7324 ksms.assertScannedPackageValid(pkg); 7325 7326 // writer 7327 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7328 7329 boolean createIdmapFailed = false; 7330 synchronized (mPackages) { 7331 // We don't expect installation to fail beyond this point 7332 7333 // Add the new setting to mSettings 7334 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7335 // Add the new setting to mPackages 7336 mPackages.put(pkg.applicationInfo.packageName, pkg); 7337 // Make sure we don't accidentally delete its data. 7338 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7339 while (iter.hasNext()) { 7340 PackageCleanItem item = iter.next(); 7341 if (pkgName.equals(item.packageName)) { 7342 iter.remove(); 7343 } 7344 } 7345 7346 // Take care of first install / last update times. 7347 if (currentTime != 0) { 7348 if (pkgSetting.firstInstallTime == 0) { 7349 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7350 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7351 pkgSetting.lastUpdateTime = currentTime; 7352 } 7353 } else if (pkgSetting.firstInstallTime == 0) { 7354 // We need *something*. Take time time stamp of the file. 7355 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7356 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7357 if (scanFileTime != pkgSetting.timeStamp) { 7358 // A package on the system image has changed; consider this 7359 // to be an update. 7360 pkgSetting.lastUpdateTime = scanFileTime; 7361 } 7362 } 7363 7364 // Add the package's KeySets to the global KeySetManagerService 7365 ksms.addScannedPackageLPw(pkg); 7366 7367 int N = pkg.providers.size(); 7368 StringBuilder r = null; 7369 int i; 7370 for (i=0; i<N; i++) { 7371 PackageParser.Provider p = pkg.providers.get(i); 7372 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7373 p.info.processName, pkg.applicationInfo.uid); 7374 mProviders.addProvider(p); 7375 p.syncable = p.info.isSyncable; 7376 if (p.info.authority != null) { 7377 String names[] = p.info.authority.split(";"); 7378 p.info.authority = null; 7379 for (int j = 0; j < names.length; j++) { 7380 if (j == 1 && p.syncable) { 7381 // We only want the first authority for a provider to possibly be 7382 // syncable, so if we already added this provider using a different 7383 // authority clear the syncable flag. We copy the provider before 7384 // changing it because the mProviders object contains a reference 7385 // to a provider that we don't want to change. 7386 // Only do this for the second authority since the resulting provider 7387 // object can be the same for all future authorities for this provider. 7388 p = new PackageParser.Provider(p); 7389 p.syncable = false; 7390 } 7391 if (!mProvidersByAuthority.containsKey(names[j])) { 7392 mProvidersByAuthority.put(names[j], p); 7393 if (p.info.authority == null) { 7394 p.info.authority = names[j]; 7395 } else { 7396 p.info.authority = p.info.authority + ";" + names[j]; 7397 } 7398 if (DEBUG_PACKAGE_SCANNING) { 7399 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7400 Log.d(TAG, "Registered content provider: " + names[j] 7401 + ", className = " + p.info.name + ", isSyncable = " 7402 + p.info.isSyncable); 7403 } 7404 } else { 7405 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7406 Slog.w(TAG, "Skipping provider name " + names[j] + 7407 " (in package " + pkg.applicationInfo.packageName + 7408 "): name already used by " 7409 + ((other != null && other.getComponentName() != null) 7410 ? other.getComponentName().getPackageName() : "?")); 7411 } 7412 } 7413 } 7414 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7415 if (r == null) { 7416 r = new StringBuilder(256); 7417 } else { 7418 r.append(' '); 7419 } 7420 r.append(p.info.name); 7421 } 7422 } 7423 if (r != null) { 7424 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7425 } 7426 7427 N = pkg.services.size(); 7428 r = null; 7429 for (i=0; i<N; i++) { 7430 PackageParser.Service s = pkg.services.get(i); 7431 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7432 s.info.processName, pkg.applicationInfo.uid); 7433 mServices.addService(s); 7434 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7435 if (r == null) { 7436 r = new StringBuilder(256); 7437 } else { 7438 r.append(' '); 7439 } 7440 r.append(s.info.name); 7441 } 7442 } 7443 if (r != null) { 7444 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7445 } 7446 7447 N = pkg.receivers.size(); 7448 r = null; 7449 for (i=0; i<N; i++) { 7450 PackageParser.Activity a = pkg.receivers.get(i); 7451 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7452 a.info.processName, pkg.applicationInfo.uid); 7453 mReceivers.addActivity(a, "receiver"); 7454 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7455 if (r == null) { 7456 r = new StringBuilder(256); 7457 } else { 7458 r.append(' '); 7459 } 7460 r.append(a.info.name); 7461 } 7462 } 7463 if (r != null) { 7464 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7465 } 7466 7467 N = pkg.activities.size(); 7468 r = null; 7469 for (i=0; i<N; i++) { 7470 PackageParser.Activity a = pkg.activities.get(i); 7471 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7472 a.info.processName, pkg.applicationInfo.uid); 7473 mActivities.addActivity(a, "activity"); 7474 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7475 if (r == null) { 7476 r = new StringBuilder(256); 7477 } else { 7478 r.append(' '); 7479 } 7480 r.append(a.info.name); 7481 } 7482 } 7483 if (r != null) { 7484 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7485 } 7486 7487 N = pkg.permissionGroups.size(); 7488 r = null; 7489 for (i=0; i<N; i++) { 7490 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7491 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7492 if (cur == null) { 7493 mPermissionGroups.put(pg.info.name, pg); 7494 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7495 if (r == null) { 7496 r = new StringBuilder(256); 7497 } else { 7498 r.append(' '); 7499 } 7500 r.append(pg.info.name); 7501 } 7502 } else { 7503 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7504 + pg.info.packageName + " ignored: original from " 7505 + cur.info.packageName); 7506 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7507 if (r == null) { 7508 r = new StringBuilder(256); 7509 } else { 7510 r.append(' '); 7511 } 7512 r.append("DUP:"); 7513 r.append(pg.info.name); 7514 } 7515 } 7516 } 7517 if (r != null) { 7518 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7519 } 7520 7521 N = pkg.permissions.size(); 7522 r = null; 7523 for (i=0; i<N; i++) { 7524 PackageParser.Permission p = pkg.permissions.get(i); 7525 7526 // Assume by default that we did not install this permission into the system. 7527 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7528 7529 // Now that permission groups have a special meaning, we ignore permission 7530 // groups for legacy apps to prevent unexpected behavior. In particular, 7531 // permissions for one app being granted to someone just becuase they happen 7532 // to be in a group defined by another app (before this had no implications). 7533 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7534 p.group = mPermissionGroups.get(p.info.group); 7535 // Warn for a permission in an unknown group. 7536 if (p.info.group != null && p.group == null) { 7537 Slog.w(TAG, "Permission " + p.info.name + " from package " 7538 + p.info.packageName + " in an unknown group " + p.info.group); 7539 } 7540 } 7541 7542 ArrayMap<String, BasePermission> permissionMap = 7543 p.tree ? mSettings.mPermissionTrees 7544 : mSettings.mPermissions; 7545 BasePermission bp = permissionMap.get(p.info.name); 7546 7547 // Allow system apps to redefine non-system permissions 7548 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7549 final boolean currentOwnerIsSystem = (bp.perm != null 7550 && isSystemApp(bp.perm.owner)); 7551 if (isSystemApp(p.owner)) { 7552 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7553 // It's a built-in permission and no owner, take ownership now 7554 bp.packageSetting = pkgSetting; 7555 bp.perm = p; 7556 bp.uid = pkg.applicationInfo.uid; 7557 bp.sourcePackage = p.info.packageName; 7558 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7559 } else if (!currentOwnerIsSystem) { 7560 String msg = "New decl " + p.owner + " of permission " 7561 + p.info.name + " is system; overriding " + bp.sourcePackage; 7562 reportSettingsProblem(Log.WARN, msg); 7563 bp = null; 7564 } 7565 } 7566 } 7567 7568 if (bp == null) { 7569 bp = new BasePermission(p.info.name, p.info.packageName, 7570 BasePermission.TYPE_NORMAL); 7571 permissionMap.put(p.info.name, bp); 7572 } 7573 7574 if (bp.perm == null) { 7575 if (bp.sourcePackage == null 7576 || bp.sourcePackage.equals(p.info.packageName)) { 7577 BasePermission tree = findPermissionTreeLP(p.info.name); 7578 if (tree == null 7579 || tree.sourcePackage.equals(p.info.packageName)) { 7580 bp.packageSetting = pkgSetting; 7581 bp.perm = p; 7582 bp.uid = pkg.applicationInfo.uid; 7583 bp.sourcePackage = p.info.packageName; 7584 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7585 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7586 if (r == null) { 7587 r = new StringBuilder(256); 7588 } else { 7589 r.append(' '); 7590 } 7591 r.append(p.info.name); 7592 } 7593 } else { 7594 Slog.w(TAG, "Permission " + p.info.name + " from package " 7595 + p.info.packageName + " ignored: base tree " 7596 + tree.name + " is from package " 7597 + tree.sourcePackage); 7598 } 7599 } else { 7600 Slog.w(TAG, "Permission " + p.info.name + " from package " 7601 + p.info.packageName + " ignored: original from " 7602 + bp.sourcePackage); 7603 } 7604 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7605 if (r == null) { 7606 r = new StringBuilder(256); 7607 } else { 7608 r.append(' '); 7609 } 7610 r.append("DUP:"); 7611 r.append(p.info.name); 7612 } 7613 if (bp.perm == p) { 7614 bp.protectionLevel = p.info.protectionLevel; 7615 } 7616 } 7617 7618 if (r != null) { 7619 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7620 } 7621 7622 N = pkg.instrumentation.size(); 7623 r = null; 7624 for (i=0; i<N; i++) { 7625 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7626 a.info.packageName = pkg.applicationInfo.packageName; 7627 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7628 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7629 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7630 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7631 a.info.dataDir = pkg.applicationInfo.dataDir; 7632 7633 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7634 // need other information about the application, like the ABI and what not ? 7635 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7636 mInstrumentation.put(a.getComponentName(), a); 7637 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7638 if (r == null) { 7639 r = new StringBuilder(256); 7640 } else { 7641 r.append(' '); 7642 } 7643 r.append(a.info.name); 7644 } 7645 } 7646 if (r != null) { 7647 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7648 } 7649 7650 if (pkg.protectedBroadcasts != null) { 7651 N = pkg.protectedBroadcasts.size(); 7652 for (i=0; i<N; i++) { 7653 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7654 } 7655 } 7656 7657 pkgSetting.setTimeStamp(scanFileTime); 7658 7659 // Create idmap files for pairs of (packages, overlay packages). 7660 // Note: "android", ie framework-res.apk, is handled by native layers. 7661 if (pkg.mOverlayTarget != null) { 7662 // This is an overlay package. 7663 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7664 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7665 mOverlays.put(pkg.mOverlayTarget, 7666 new ArrayMap<String, PackageParser.Package>()); 7667 } 7668 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7669 map.put(pkg.packageName, pkg); 7670 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7671 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7672 createIdmapFailed = true; 7673 } 7674 } 7675 } else if (mOverlays.containsKey(pkg.packageName) && 7676 !pkg.packageName.equals("android")) { 7677 // This is a regular package, with one or more known overlay packages. 7678 createIdmapsForPackageLI(pkg); 7679 } 7680 } 7681 7682 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7683 7684 if (createIdmapFailed) { 7685 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7686 "scanPackageLI failed to createIdmap"); 7687 } 7688 return pkg; 7689 } 7690 7691 /** 7692 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7693 * is derived purely on the basis of the contents of {@code scanFile} and 7694 * {@code cpuAbiOverride}. 7695 * 7696 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7697 */ 7698 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7699 String cpuAbiOverride, boolean extractLibs) 7700 throws PackageManagerException { 7701 // TODO: We can probably be smarter about this stuff. For installed apps, 7702 // we can calculate this information at install time once and for all. For 7703 // system apps, we can probably assume that this information doesn't change 7704 // after the first boot scan. As things stand, we do lots of unnecessary work. 7705 7706 // Give ourselves some initial paths; we'll come back for another 7707 // pass once we've determined ABI below. 7708 setNativeLibraryPaths(pkg); 7709 7710 // We would never need to extract libs for forward-locked and external packages, 7711 // since the container service will do it for us. We shouldn't attempt to 7712 // extract libs from system app when it was not updated. 7713 if (pkg.isForwardLocked() || isExternal(pkg) || 7714 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7715 extractLibs = false; 7716 } 7717 7718 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7719 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7720 7721 NativeLibraryHelper.Handle handle = null; 7722 try { 7723 handle = NativeLibraryHelper.Handle.create(pkg); 7724 // TODO(multiArch): This can be null for apps that didn't go through the 7725 // usual installation process. We can calculate it again, like we 7726 // do during install time. 7727 // 7728 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7729 // unnecessary. 7730 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7731 7732 // Null out the abis so that they can be recalculated. 7733 pkg.applicationInfo.primaryCpuAbi = null; 7734 pkg.applicationInfo.secondaryCpuAbi = null; 7735 if (isMultiArch(pkg.applicationInfo)) { 7736 // Warn if we've set an abiOverride for multi-lib packages.. 7737 // By definition, we need to copy both 32 and 64 bit libraries for 7738 // such packages. 7739 if (pkg.cpuAbiOverride != null 7740 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7741 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7742 } 7743 7744 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7745 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7746 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7747 if (extractLibs) { 7748 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7749 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7750 useIsaSpecificSubdirs); 7751 } else { 7752 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7753 } 7754 } 7755 7756 maybeThrowExceptionForMultiArchCopy( 7757 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7758 7759 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7760 if (extractLibs) { 7761 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7762 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7763 useIsaSpecificSubdirs); 7764 } else { 7765 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7766 } 7767 } 7768 7769 maybeThrowExceptionForMultiArchCopy( 7770 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7771 7772 if (abi64 >= 0) { 7773 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7774 } 7775 7776 if (abi32 >= 0) { 7777 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7778 if (abi64 >= 0) { 7779 pkg.applicationInfo.secondaryCpuAbi = abi; 7780 } else { 7781 pkg.applicationInfo.primaryCpuAbi = abi; 7782 } 7783 } 7784 } else { 7785 String[] abiList = (cpuAbiOverride != null) ? 7786 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7787 7788 // Enable gross and lame hacks for apps that are built with old 7789 // SDK tools. We must scan their APKs for renderscript bitcode and 7790 // not launch them if it's present. Don't bother checking on devices 7791 // that don't have 64 bit support. 7792 boolean needsRenderScriptOverride = false; 7793 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7794 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7795 abiList = Build.SUPPORTED_32_BIT_ABIS; 7796 needsRenderScriptOverride = true; 7797 } 7798 7799 final int copyRet; 7800 if (extractLibs) { 7801 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7802 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7803 } else { 7804 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7805 } 7806 7807 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7808 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7809 "Error unpackaging native libs for app, errorCode=" + copyRet); 7810 } 7811 7812 if (copyRet >= 0) { 7813 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7814 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7815 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7816 } else if (needsRenderScriptOverride) { 7817 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7818 } 7819 } 7820 } catch (IOException ioe) { 7821 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7822 } finally { 7823 IoUtils.closeQuietly(handle); 7824 } 7825 7826 // Now that we've calculated the ABIs and determined if it's an internal app, 7827 // we will go ahead and populate the nativeLibraryPath. 7828 setNativeLibraryPaths(pkg); 7829 } 7830 7831 /** 7832 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7833 * i.e, so that all packages can be run inside a single process if required. 7834 * 7835 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7836 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7837 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7838 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7839 * updating a package that belongs to a shared user. 7840 * 7841 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7842 * adds unnecessary complexity. 7843 */ 7844 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7845 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7846 String requiredInstructionSet = null; 7847 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7848 requiredInstructionSet = VMRuntime.getInstructionSet( 7849 scannedPackage.applicationInfo.primaryCpuAbi); 7850 } 7851 7852 PackageSetting requirer = null; 7853 for (PackageSetting ps : packagesForUser) { 7854 // If packagesForUser contains scannedPackage, we skip it. This will happen 7855 // when scannedPackage is an update of an existing package. Without this check, 7856 // we will never be able to change the ABI of any package belonging to a shared 7857 // user, even if it's compatible with other packages. 7858 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7859 if (ps.primaryCpuAbiString == null) { 7860 continue; 7861 } 7862 7863 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7864 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7865 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7866 // this but there's not much we can do. 7867 String errorMessage = "Instruction set mismatch, " 7868 + ((requirer == null) ? "[caller]" : requirer) 7869 + " requires " + requiredInstructionSet + " whereas " + ps 7870 + " requires " + instructionSet; 7871 Slog.w(TAG, errorMessage); 7872 } 7873 7874 if (requiredInstructionSet == null) { 7875 requiredInstructionSet = instructionSet; 7876 requirer = ps; 7877 } 7878 } 7879 } 7880 7881 if (requiredInstructionSet != null) { 7882 String adjustedAbi; 7883 if (requirer != null) { 7884 // requirer != null implies that either scannedPackage was null or that scannedPackage 7885 // did not require an ABI, in which case we have to adjust scannedPackage to match 7886 // the ABI of the set (which is the same as requirer's ABI) 7887 adjustedAbi = requirer.primaryCpuAbiString; 7888 if (scannedPackage != null) { 7889 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7890 } 7891 } else { 7892 // requirer == null implies that we're updating all ABIs in the set to 7893 // match scannedPackage. 7894 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7895 } 7896 7897 for (PackageSetting ps : packagesForUser) { 7898 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7899 if (ps.primaryCpuAbiString != null) { 7900 continue; 7901 } 7902 7903 ps.primaryCpuAbiString = adjustedAbi; 7904 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7905 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7906 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7907 7908 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7909 7910 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7911 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7912 7913 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7914 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7915 ps.primaryCpuAbiString = null; 7916 ps.pkg.applicationInfo.primaryCpuAbi = null; 7917 return; 7918 } else { 7919 mInstaller.rmdex(ps.codePathString, 7920 getDexCodeInstructionSet(getPreferredInstructionSet())); 7921 } 7922 } 7923 } 7924 } 7925 } 7926 } 7927 7928 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7929 synchronized (mPackages) { 7930 mResolverReplaced = true; 7931 // Set up information for custom user intent resolution activity. 7932 mResolveActivity.applicationInfo = pkg.applicationInfo; 7933 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7934 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7935 mResolveActivity.processName = pkg.applicationInfo.packageName; 7936 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7937 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7938 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7939 mResolveActivity.theme = 0; 7940 mResolveActivity.exported = true; 7941 mResolveActivity.enabled = true; 7942 mResolveInfo.activityInfo = mResolveActivity; 7943 mResolveInfo.priority = 0; 7944 mResolveInfo.preferredOrder = 0; 7945 mResolveInfo.match = 0; 7946 mResolveComponentName = mCustomResolverComponentName; 7947 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7948 mResolveComponentName); 7949 } 7950 } 7951 7952 private static String calculateBundledApkRoot(final String codePathString) { 7953 final File codePath = new File(codePathString); 7954 final File codeRoot; 7955 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7956 codeRoot = Environment.getRootDirectory(); 7957 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7958 codeRoot = Environment.getOemDirectory(); 7959 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7960 codeRoot = Environment.getVendorDirectory(); 7961 } else { 7962 // Unrecognized code path; take its top real segment as the apk root: 7963 // e.g. /something/app/blah.apk => /something 7964 try { 7965 File f = codePath.getCanonicalFile(); 7966 File parent = f.getParentFile(); // non-null because codePath is a file 7967 File tmp; 7968 while ((tmp = parent.getParentFile()) != null) { 7969 f = parent; 7970 parent = tmp; 7971 } 7972 codeRoot = f; 7973 Slog.w(TAG, "Unrecognized code path " 7974 + codePath + " - using " + codeRoot); 7975 } catch (IOException e) { 7976 // Can't canonicalize the code path -- shenanigans? 7977 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7978 return Environment.getRootDirectory().getPath(); 7979 } 7980 } 7981 return codeRoot.getPath(); 7982 } 7983 7984 /** 7985 * Derive and set the location of native libraries for the given package, 7986 * which varies depending on where and how the package was installed. 7987 */ 7988 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7989 final ApplicationInfo info = pkg.applicationInfo; 7990 final String codePath = pkg.codePath; 7991 final File codeFile = new File(codePath); 7992 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7993 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7994 7995 info.nativeLibraryRootDir = null; 7996 info.nativeLibraryRootRequiresIsa = false; 7997 info.nativeLibraryDir = null; 7998 info.secondaryNativeLibraryDir = null; 7999 8000 if (isApkFile(codeFile)) { 8001 // Monolithic install 8002 if (bundledApp) { 8003 // If "/system/lib64/apkname" exists, assume that is the per-package 8004 // native library directory to use; otherwise use "/system/lib/apkname". 8005 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8006 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8007 getPrimaryInstructionSet(info)); 8008 8009 // This is a bundled system app so choose the path based on the ABI. 8010 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8011 // is just the default path. 8012 final String apkName = deriveCodePathName(codePath); 8013 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8014 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8015 apkName).getAbsolutePath(); 8016 8017 if (info.secondaryCpuAbi != null) { 8018 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8019 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8020 secondaryLibDir, apkName).getAbsolutePath(); 8021 } 8022 } else if (asecApp) { 8023 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8024 .getAbsolutePath(); 8025 } else { 8026 final String apkName = deriveCodePathName(codePath); 8027 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8028 .getAbsolutePath(); 8029 } 8030 8031 info.nativeLibraryRootRequiresIsa = false; 8032 info.nativeLibraryDir = info.nativeLibraryRootDir; 8033 } else { 8034 // Cluster install 8035 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8036 info.nativeLibraryRootRequiresIsa = true; 8037 8038 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8039 getPrimaryInstructionSet(info)).getAbsolutePath(); 8040 8041 if (info.secondaryCpuAbi != null) { 8042 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8043 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8044 } 8045 } 8046 } 8047 8048 /** 8049 * Calculate the abis and roots for a bundled app. These can uniquely 8050 * be determined from the contents of the system partition, i.e whether 8051 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8052 * of this information, and instead assume that the system was built 8053 * sensibly. 8054 */ 8055 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8056 PackageSetting pkgSetting) { 8057 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8058 8059 // If "/system/lib64/apkname" exists, assume that is the per-package 8060 // native library directory to use; otherwise use "/system/lib/apkname". 8061 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8062 setBundledAppAbi(pkg, apkRoot, apkName); 8063 // pkgSetting might be null during rescan following uninstall of updates 8064 // to a bundled app, so accommodate that possibility. The settings in 8065 // that case will be established later from the parsed package. 8066 // 8067 // If the settings aren't null, sync them up with what we've just derived. 8068 // note that apkRoot isn't stored in the package settings. 8069 if (pkgSetting != null) { 8070 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8071 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8072 } 8073 } 8074 8075 /** 8076 * Deduces the ABI of a bundled app and sets the relevant fields on the 8077 * parsed pkg object. 8078 * 8079 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8080 * under which system libraries are installed. 8081 * @param apkName the name of the installed package. 8082 */ 8083 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8084 final File codeFile = new File(pkg.codePath); 8085 8086 final boolean has64BitLibs; 8087 final boolean has32BitLibs; 8088 if (isApkFile(codeFile)) { 8089 // Monolithic install 8090 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8091 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8092 } else { 8093 // Cluster install 8094 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8095 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8096 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8097 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8098 has64BitLibs = (new File(rootDir, isa)).exists(); 8099 } else { 8100 has64BitLibs = false; 8101 } 8102 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8103 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8104 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8105 has32BitLibs = (new File(rootDir, isa)).exists(); 8106 } else { 8107 has32BitLibs = false; 8108 } 8109 } 8110 8111 if (has64BitLibs && !has32BitLibs) { 8112 // The package has 64 bit libs, but not 32 bit libs. Its primary 8113 // ABI should be 64 bit. We can safely assume here that the bundled 8114 // native libraries correspond to the most preferred ABI in the list. 8115 8116 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8117 pkg.applicationInfo.secondaryCpuAbi = null; 8118 } else if (has32BitLibs && !has64BitLibs) { 8119 // The package has 32 bit libs but not 64 bit libs. Its primary 8120 // ABI should be 32 bit. 8121 8122 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8123 pkg.applicationInfo.secondaryCpuAbi = null; 8124 } else if (has32BitLibs && has64BitLibs) { 8125 // The application has both 64 and 32 bit bundled libraries. We check 8126 // here that the app declares multiArch support, and warn if it doesn't. 8127 // 8128 // We will be lenient here and record both ABIs. The primary will be the 8129 // ABI that's higher on the list, i.e, a device that's configured to prefer 8130 // 64 bit apps will see a 64 bit primary ABI, 8131 8132 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8133 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8134 } 8135 8136 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8137 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8138 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8139 } else { 8140 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8141 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8142 } 8143 } else { 8144 pkg.applicationInfo.primaryCpuAbi = null; 8145 pkg.applicationInfo.secondaryCpuAbi = null; 8146 } 8147 } 8148 8149 private void killApplication(String pkgName, int appId, String reason) { 8150 // Request the ActivityManager to kill the process(only for existing packages) 8151 // so that we do not end up in a confused state while the user is still using the older 8152 // version of the application while the new one gets installed. 8153 IActivityManager am = ActivityManagerNative.getDefault(); 8154 if (am != null) { 8155 try { 8156 am.killApplicationWithAppId(pkgName, appId, reason); 8157 } catch (RemoteException e) { 8158 } 8159 } 8160 } 8161 8162 void removePackageLI(PackageSetting ps, boolean chatty) { 8163 if (DEBUG_INSTALL) { 8164 if (chatty) 8165 Log.d(TAG, "Removing package " + ps.name); 8166 } 8167 8168 // writer 8169 synchronized (mPackages) { 8170 mPackages.remove(ps.name); 8171 final PackageParser.Package pkg = ps.pkg; 8172 if (pkg != null) { 8173 cleanPackageDataStructuresLILPw(pkg, chatty); 8174 } 8175 } 8176 } 8177 8178 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8179 if (DEBUG_INSTALL) { 8180 if (chatty) 8181 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8182 } 8183 8184 // writer 8185 synchronized (mPackages) { 8186 mPackages.remove(pkg.applicationInfo.packageName); 8187 cleanPackageDataStructuresLILPw(pkg, chatty); 8188 } 8189 } 8190 8191 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8192 int N = pkg.providers.size(); 8193 StringBuilder r = null; 8194 int i; 8195 for (i=0; i<N; i++) { 8196 PackageParser.Provider p = pkg.providers.get(i); 8197 mProviders.removeProvider(p); 8198 if (p.info.authority == null) { 8199 8200 /* There was another ContentProvider with this authority when 8201 * this app was installed so this authority is null, 8202 * Ignore it as we don't have to unregister the provider. 8203 */ 8204 continue; 8205 } 8206 String names[] = p.info.authority.split(";"); 8207 for (int j = 0; j < names.length; j++) { 8208 if (mProvidersByAuthority.get(names[j]) == p) { 8209 mProvidersByAuthority.remove(names[j]); 8210 if (DEBUG_REMOVE) { 8211 if (chatty) 8212 Log.d(TAG, "Unregistered content provider: " + names[j] 8213 + ", className = " + p.info.name + ", isSyncable = " 8214 + p.info.isSyncable); 8215 } 8216 } 8217 } 8218 if (DEBUG_REMOVE && chatty) { 8219 if (r == null) { 8220 r = new StringBuilder(256); 8221 } else { 8222 r.append(' '); 8223 } 8224 r.append(p.info.name); 8225 } 8226 } 8227 if (r != null) { 8228 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8229 } 8230 8231 N = pkg.services.size(); 8232 r = null; 8233 for (i=0; i<N; i++) { 8234 PackageParser.Service s = pkg.services.get(i); 8235 mServices.removeService(s); 8236 if (chatty) { 8237 if (r == null) { 8238 r = new StringBuilder(256); 8239 } else { 8240 r.append(' '); 8241 } 8242 r.append(s.info.name); 8243 } 8244 } 8245 if (r != null) { 8246 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8247 } 8248 8249 N = pkg.receivers.size(); 8250 r = null; 8251 for (i=0; i<N; i++) { 8252 PackageParser.Activity a = pkg.receivers.get(i); 8253 mReceivers.removeActivity(a, "receiver"); 8254 if (DEBUG_REMOVE && chatty) { 8255 if (r == null) { 8256 r = new StringBuilder(256); 8257 } else { 8258 r.append(' '); 8259 } 8260 r.append(a.info.name); 8261 } 8262 } 8263 if (r != null) { 8264 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8265 } 8266 8267 N = pkg.activities.size(); 8268 r = null; 8269 for (i=0; i<N; i++) { 8270 PackageParser.Activity a = pkg.activities.get(i); 8271 mActivities.removeActivity(a, "activity"); 8272 if (DEBUG_REMOVE && chatty) { 8273 if (r == null) { 8274 r = new StringBuilder(256); 8275 } else { 8276 r.append(' '); 8277 } 8278 r.append(a.info.name); 8279 } 8280 } 8281 if (r != null) { 8282 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8283 } 8284 8285 N = pkg.permissions.size(); 8286 r = null; 8287 for (i=0; i<N; i++) { 8288 PackageParser.Permission p = pkg.permissions.get(i); 8289 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8290 if (bp == null) { 8291 bp = mSettings.mPermissionTrees.get(p.info.name); 8292 } 8293 if (bp != null && bp.perm == p) { 8294 bp.perm = null; 8295 if (DEBUG_REMOVE && chatty) { 8296 if (r == null) { 8297 r = new StringBuilder(256); 8298 } else { 8299 r.append(' '); 8300 } 8301 r.append(p.info.name); 8302 } 8303 } 8304 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8305 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8306 if (appOpPerms != null) { 8307 appOpPerms.remove(pkg.packageName); 8308 } 8309 } 8310 } 8311 if (r != null) { 8312 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8313 } 8314 8315 N = pkg.requestedPermissions.size(); 8316 r = null; 8317 for (i=0; i<N; i++) { 8318 String perm = pkg.requestedPermissions.get(i); 8319 BasePermission bp = mSettings.mPermissions.get(perm); 8320 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8321 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8322 if (appOpPerms != null) { 8323 appOpPerms.remove(pkg.packageName); 8324 if (appOpPerms.isEmpty()) { 8325 mAppOpPermissionPackages.remove(perm); 8326 } 8327 } 8328 } 8329 } 8330 if (r != null) { 8331 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8332 } 8333 8334 N = pkg.instrumentation.size(); 8335 r = null; 8336 for (i=0; i<N; i++) { 8337 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8338 mInstrumentation.remove(a.getComponentName()); 8339 if (DEBUG_REMOVE && chatty) { 8340 if (r == null) { 8341 r = new StringBuilder(256); 8342 } else { 8343 r.append(' '); 8344 } 8345 r.append(a.info.name); 8346 } 8347 } 8348 if (r != null) { 8349 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8350 } 8351 8352 r = null; 8353 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8354 // Only system apps can hold shared libraries. 8355 if (pkg.libraryNames != null) { 8356 for (i=0; i<pkg.libraryNames.size(); i++) { 8357 String name = pkg.libraryNames.get(i); 8358 SharedLibraryEntry cur = mSharedLibraries.get(name); 8359 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8360 mSharedLibraries.remove(name); 8361 if (DEBUG_REMOVE && chatty) { 8362 if (r == null) { 8363 r = new StringBuilder(256); 8364 } else { 8365 r.append(' '); 8366 } 8367 r.append(name); 8368 } 8369 } 8370 } 8371 } 8372 } 8373 if (r != null) { 8374 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8375 } 8376 } 8377 8378 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8379 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8380 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8381 return true; 8382 } 8383 } 8384 return false; 8385 } 8386 8387 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8388 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8389 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8390 8391 private void updatePermissionsLPw(String changingPkg, 8392 PackageParser.Package pkgInfo, int flags) { 8393 // Make sure there are no dangling permission trees. 8394 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8395 while (it.hasNext()) { 8396 final BasePermission bp = it.next(); 8397 if (bp.packageSetting == null) { 8398 // We may not yet have parsed the package, so just see if 8399 // we still know about its settings. 8400 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8401 } 8402 if (bp.packageSetting == null) { 8403 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8404 + " from package " + bp.sourcePackage); 8405 it.remove(); 8406 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8407 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8408 Slog.i(TAG, "Removing old permission tree: " + bp.name 8409 + " from package " + bp.sourcePackage); 8410 flags |= UPDATE_PERMISSIONS_ALL; 8411 it.remove(); 8412 } 8413 } 8414 } 8415 8416 // Make sure all dynamic permissions have been assigned to a package, 8417 // and make sure there are no dangling permissions. 8418 it = mSettings.mPermissions.values().iterator(); 8419 while (it.hasNext()) { 8420 final BasePermission bp = it.next(); 8421 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8422 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8423 + bp.name + " pkg=" + bp.sourcePackage 8424 + " info=" + bp.pendingInfo); 8425 if (bp.packageSetting == null && bp.pendingInfo != null) { 8426 final BasePermission tree = findPermissionTreeLP(bp.name); 8427 if (tree != null && tree.perm != null) { 8428 bp.packageSetting = tree.packageSetting; 8429 bp.perm = new PackageParser.Permission(tree.perm.owner, 8430 new PermissionInfo(bp.pendingInfo)); 8431 bp.perm.info.packageName = tree.perm.info.packageName; 8432 bp.perm.info.name = bp.name; 8433 bp.uid = tree.uid; 8434 } 8435 } 8436 } 8437 if (bp.packageSetting == null) { 8438 // We may not yet have parsed the package, so just see if 8439 // we still know about its settings. 8440 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8441 } 8442 if (bp.packageSetting == null) { 8443 Slog.w(TAG, "Removing dangling permission: " + bp.name 8444 + " from package " + bp.sourcePackage); 8445 it.remove(); 8446 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8447 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8448 Slog.i(TAG, "Removing old permission: " + bp.name 8449 + " from package " + bp.sourcePackage); 8450 flags |= UPDATE_PERMISSIONS_ALL; 8451 it.remove(); 8452 } 8453 } 8454 } 8455 8456 // Now update the permissions for all packages, in particular 8457 // replace the granted permissions of the system packages. 8458 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8459 for (PackageParser.Package pkg : mPackages.values()) { 8460 if (pkg != pkgInfo) { 8461 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8462 changingPkg); 8463 } 8464 } 8465 } 8466 8467 if (pkgInfo != null) { 8468 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8469 } 8470 } 8471 8472 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8473 String packageOfInterest) { 8474 // IMPORTANT: There are two types of permissions: install and runtime. 8475 // Install time permissions are granted when the app is installed to 8476 // all device users and users added in the future. Runtime permissions 8477 // are granted at runtime explicitly to specific users. Normal and signature 8478 // protected permissions are install time permissions. Dangerous permissions 8479 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8480 // otherwise they are runtime permissions. This function does not manage 8481 // runtime permissions except for the case an app targeting Lollipop MR1 8482 // being upgraded to target a newer SDK, in which case dangerous permissions 8483 // are transformed from install time to runtime ones. 8484 8485 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8486 if (ps == null) { 8487 return; 8488 } 8489 8490 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8491 8492 PermissionsState permissionsState = ps.getPermissionsState(); 8493 PermissionsState origPermissions = permissionsState; 8494 8495 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8496 8497 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8498 8499 boolean changedInstallPermission = false; 8500 8501 if (replace) { 8502 ps.installPermissionsFixed = false; 8503 if (!ps.isSharedUser()) { 8504 origPermissions = new PermissionsState(permissionsState); 8505 permissionsState.reset(); 8506 } 8507 } 8508 8509 permissionsState.setGlobalGids(mGlobalGids); 8510 8511 final int N = pkg.requestedPermissions.size(); 8512 for (int i=0; i<N; i++) { 8513 final String name = pkg.requestedPermissions.get(i); 8514 final BasePermission bp = mSettings.mPermissions.get(name); 8515 8516 if (DEBUG_INSTALL) { 8517 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8518 } 8519 8520 if (bp == null || bp.packageSetting == null) { 8521 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8522 Slog.w(TAG, "Unknown permission " + name 8523 + " in package " + pkg.packageName); 8524 } 8525 continue; 8526 } 8527 8528 final String perm = bp.name; 8529 boolean allowedSig = false; 8530 int grant = GRANT_DENIED; 8531 8532 // Keep track of app op permissions. 8533 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8534 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8535 if (pkgs == null) { 8536 pkgs = new ArraySet<>(); 8537 mAppOpPermissionPackages.put(bp.name, pkgs); 8538 } 8539 pkgs.add(pkg.packageName); 8540 } 8541 8542 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8543 switch (level) { 8544 case PermissionInfo.PROTECTION_NORMAL: { 8545 // For all apps normal permissions are install time ones. 8546 grant = GRANT_INSTALL; 8547 } break; 8548 8549 case PermissionInfo.PROTECTION_DANGEROUS: { 8550 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8551 // For legacy apps dangerous permissions are install time ones. 8552 grant = GRANT_INSTALL_LEGACY; 8553 } else if (origPermissions.hasInstallPermission(bp.name)) { 8554 // For legacy apps that became modern, install becomes runtime. 8555 grant = GRANT_UPGRADE; 8556 } else if (mPromoteSystemApps 8557 && isSystemApp(ps) 8558 && mExistingSystemPackages.contains(ps.name)) { 8559 // For legacy system apps, install becomes runtime. 8560 // We cannot check hasInstallPermission() for system apps since those 8561 // permissions were granted implicitly and not persisted pre-M. 8562 grant = GRANT_UPGRADE; 8563 } else { 8564 // For modern apps keep runtime permissions unchanged. 8565 grant = GRANT_RUNTIME; 8566 } 8567 } break; 8568 8569 case PermissionInfo.PROTECTION_SIGNATURE: { 8570 // For all apps signature permissions are install time ones. 8571 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8572 if (allowedSig) { 8573 grant = GRANT_INSTALL; 8574 } 8575 } break; 8576 } 8577 8578 if (DEBUG_INSTALL) { 8579 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8580 } 8581 8582 if (grant != GRANT_DENIED) { 8583 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8584 // If this is an existing, non-system package, then 8585 // we can't add any new permissions to it. 8586 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8587 // Except... if this is a permission that was added 8588 // to the platform (note: need to only do this when 8589 // updating the platform). 8590 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8591 grant = GRANT_DENIED; 8592 } 8593 } 8594 } 8595 8596 switch (grant) { 8597 case GRANT_INSTALL: { 8598 // Revoke this as runtime permission to handle the case of 8599 // a runtime permission being downgraded to an install one. 8600 for (int userId : UserManagerService.getInstance().getUserIds()) { 8601 if (origPermissions.getRuntimePermissionState( 8602 bp.name, userId) != null) { 8603 // Revoke the runtime permission and clear the flags. 8604 origPermissions.revokeRuntimePermission(bp, userId); 8605 origPermissions.updatePermissionFlags(bp, userId, 8606 PackageManager.MASK_PERMISSION_FLAGS, 0); 8607 // If we revoked a permission permission, we have to write. 8608 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8609 changedRuntimePermissionUserIds, userId); 8610 } 8611 } 8612 // Grant an install permission. 8613 if (permissionsState.grantInstallPermission(bp) != 8614 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8615 changedInstallPermission = true; 8616 } 8617 } break; 8618 8619 case GRANT_INSTALL_LEGACY: { 8620 // Grant an install permission. 8621 if (permissionsState.grantInstallPermission(bp) != 8622 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8623 changedInstallPermission = true; 8624 } 8625 } break; 8626 8627 case GRANT_RUNTIME: { 8628 // Grant previously granted runtime permissions. 8629 for (int userId : UserManagerService.getInstance().getUserIds()) { 8630 PermissionState permissionState = origPermissions 8631 .getRuntimePermissionState(bp.name, userId); 8632 final int flags = permissionState != null 8633 ? permissionState.getFlags() : 0; 8634 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8635 if (permissionsState.grantRuntimePermission(bp, userId) == 8636 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8637 // If we cannot put the permission as it was, we have to write. 8638 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8639 changedRuntimePermissionUserIds, userId); 8640 } 8641 } 8642 // Propagate the permission flags. 8643 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8644 } 8645 } break; 8646 8647 case GRANT_UPGRADE: { 8648 // Grant runtime permissions for a previously held install permission. 8649 PermissionState permissionState = origPermissions 8650 .getInstallPermissionState(bp.name); 8651 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8652 8653 if (origPermissions.revokeInstallPermission(bp) 8654 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8655 // We will be transferring the permission flags, so clear them. 8656 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8657 PackageManager.MASK_PERMISSION_FLAGS, 0); 8658 changedInstallPermission = true; 8659 } 8660 8661 // If the permission is not to be promoted to runtime we ignore it and 8662 // also its other flags as they are not applicable to install permissions. 8663 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8664 for (int userId : currentUserIds) { 8665 if (permissionsState.grantRuntimePermission(bp, userId) != 8666 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8667 // Transfer the permission flags. 8668 permissionsState.updatePermissionFlags(bp, userId, 8669 flags, flags); 8670 // If we granted the permission, we have to write. 8671 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8672 changedRuntimePermissionUserIds, userId); 8673 } 8674 } 8675 } 8676 } break; 8677 8678 default: { 8679 if (packageOfInterest == null 8680 || packageOfInterest.equals(pkg.packageName)) { 8681 Slog.w(TAG, "Not granting permission " + perm 8682 + " to package " + pkg.packageName 8683 + " because it was previously installed without"); 8684 } 8685 } break; 8686 } 8687 } else { 8688 if (permissionsState.revokeInstallPermission(bp) != 8689 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8690 // Also drop the permission flags. 8691 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8692 PackageManager.MASK_PERMISSION_FLAGS, 0); 8693 changedInstallPermission = true; 8694 Slog.i(TAG, "Un-granting permission " + perm 8695 + " from package " + pkg.packageName 8696 + " (protectionLevel=" + bp.protectionLevel 8697 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8698 + ")"); 8699 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8700 // Don't print warning for app op permissions, since it is fine for them 8701 // not to be granted, there is a UI for the user to decide. 8702 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8703 Slog.w(TAG, "Not granting permission " + perm 8704 + " to package " + pkg.packageName 8705 + " (protectionLevel=" + bp.protectionLevel 8706 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8707 + ")"); 8708 } 8709 } 8710 } 8711 } 8712 8713 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8714 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8715 // This is the first that we have heard about this package, so the 8716 // permissions we have now selected are fixed until explicitly 8717 // changed. 8718 ps.installPermissionsFixed = true; 8719 } 8720 8721 // Persist the runtime permissions state for users with changes. 8722 for (int userId : changedRuntimePermissionUserIds) { 8723 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8724 } 8725 8726 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8727 } 8728 8729 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8730 boolean allowed = false; 8731 final int NP = PackageParser.NEW_PERMISSIONS.length; 8732 for (int ip=0; ip<NP; ip++) { 8733 final PackageParser.NewPermissionInfo npi 8734 = PackageParser.NEW_PERMISSIONS[ip]; 8735 if (npi.name.equals(perm) 8736 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8737 allowed = true; 8738 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8739 + pkg.packageName); 8740 break; 8741 } 8742 } 8743 return allowed; 8744 } 8745 8746 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8747 BasePermission bp, PermissionsState origPermissions) { 8748 boolean allowed; 8749 allowed = (compareSignatures( 8750 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8751 == PackageManager.SIGNATURE_MATCH) 8752 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8753 == PackageManager.SIGNATURE_MATCH); 8754 if (!allowed && (bp.protectionLevel 8755 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8756 if (isSystemApp(pkg)) { 8757 // For updated system applications, a system permission 8758 // is granted only if it had been defined by the original application. 8759 if (pkg.isUpdatedSystemApp()) { 8760 final PackageSetting sysPs = mSettings 8761 .getDisabledSystemPkgLPr(pkg.packageName); 8762 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8763 // If the original was granted this permission, we take 8764 // that grant decision as read and propagate it to the 8765 // update. 8766 if (sysPs.isPrivileged()) { 8767 allowed = true; 8768 } 8769 } else { 8770 // The system apk may have been updated with an older 8771 // version of the one on the data partition, but which 8772 // granted a new system permission that it didn't have 8773 // before. In this case we do want to allow the app to 8774 // now get the new permission if the ancestral apk is 8775 // privileged to get it. 8776 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8777 for (int j=0; 8778 j<sysPs.pkg.requestedPermissions.size(); j++) { 8779 if (perm.equals( 8780 sysPs.pkg.requestedPermissions.get(j))) { 8781 allowed = true; 8782 break; 8783 } 8784 } 8785 } 8786 } 8787 } else { 8788 allowed = isPrivilegedApp(pkg); 8789 } 8790 } 8791 } 8792 if (!allowed) { 8793 if (!allowed && (bp.protectionLevel 8794 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8795 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8796 // If this was a previously normal/dangerous permission that got moved 8797 // to a system permission as part of the runtime permission redesign, then 8798 // we still want to blindly grant it to old apps. 8799 allowed = true; 8800 } 8801 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8802 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8803 // If this permission is to be granted to the system installer and 8804 // this app is an installer, then it gets the permission. 8805 allowed = true; 8806 } 8807 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8808 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8809 // If this permission is to be granted to the system verifier and 8810 // this app is a verifier, then it gets the permission. 8811 allowed = true; 8812 } 8813 if (!allowed && (bp.protectionLevel 8814 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8815 && isSystemApp(pkg)) { 8816 // Any pre-installed system app is allowed to get this permission. 8817 allowed = true; 8818 } 8819 if (!allowed && (bp.protectionLevel 8820 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8821 // For development permissions, a development permission 8822 // is granted only if it was already granted. 8823 allowed = origPermissions.hasInstallPermission(perm); 8824 } 8825 } 8826 return allowed; 8827 } 8828 8829 final class ActivityIntentResolver 8830 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8831 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8832 boolean defaultOnly, int userId) { 8833 if (!sUserManager.exists(userId)) return null; 8834 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8835 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8836 } 8837 8838 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8839 int userId) { 8840 if (!sUserManager.exists(userId)) return null; 8841 mFlags = flags; 8842 return super.queryIntent(intent, resolvedType, 8843 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8844 } 8845 8846 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8847 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8848 if (!sUserManager.exists(userId)) return null; 8849 if (packageActivities == null) { 8850 return null; 8851 } 8852 mFlags = flags; 8853 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8854 final int N = packageActivities.size(); 8855 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8856 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8857 8858 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8859 for (int i = 0; i < N; ++i) { 8860 intentFilters = packageActivities.get(i).intents; 8861 if (intentFilters != null && intentFilters.size() > 0) { 8862 PackageParser.ActivityIntentInfo[] array = 8863 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8864 intentFilters.toArray(array); 8865 listCut.add(array); 8866 } 8867 } 8868 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8869 } 8870 8871 public final void addActivity(PackageParser.Activity a, String type) { 8872 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8873 mActivities.put(a.getComponentName(), a); 8874 if (DEBUG_SHOW_INFO) 8875 Log.v( 8876 TAG, " " + type + " " + 8877 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8878 if (DEBUG_SHOW_INFO) 8879 Log.v(TAG, " Class=" + a.info.name); 8880 final int NI = a.intents.size(); 8881 for (int j=0; j<NI; j++) { 8882 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8883 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8884 intent.setPriority(0); 8885 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8886 + a.className + " with priority > 0, forcing to 0"); 8887 } 8888 if (DEBUG_SHOW_INFO) { 8889 Log.v(TAG, " IntentFilter:"); 8890 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8891 } 8892 if (!intent.debugCheck()) { 8893 Log.w(TAG, "==> For Activity " + a.info.name); 8894 } 8895 addFilter(intent); 8896 } 8897 } 8898 8899 public final void removeActivity(PackageParser.Activity a, String type) { 8900 mActivities.remove(a.getComponentName()); 8901 if (DEBUG_SHOW_INFO) { 8902 Log.v(TAG, " " + type + " " 8903 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8904 : a.info.name) + ":"); 8905 Log.v(TAG, " Class=" + a.info.name); 8906 } 8907 final int NI = a.intents.size(); 8908 for (int j=0; j<NI; j++) { 8909 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8910 if (DEBUG_SHOW_INFO) { 8911 Log.v(TAG, " IntentFilter:"); 8912 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8913 } 8914 removeFilter(intent); 8915 } 8916 } 8917 8918 @Override 8919 protected boolean allowFilterResult( 8920 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8921 ActivityInfo filterAi = filter.activity.info; 8922 for (int i=dest.size()-1; i>=0; i--) { 8923 ActivityInfo destAi = dest.get(i).activityInfo; 8924 if (destAi.name == filterAi.name 8925 && destAi.packageName == filterAi.packageName) { 8926 return false; 8927 } 8928 } 8929 return true; 8930 } 8931 8932 @Override 8933 protected ActivityIntentInfo[] newArray(int size) { 8934 return new ActivityIntentInfo[size]; 8935 } 8936 8937 @Override 8938 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8939 if (!sUserManager.exists(userId)) return true; 8940 PackageParser.Package p = filter.activity.owner; 8941 if (p != null) { 8942 PackageSetting ps = (PackageSetting)p.mExtras; 8943 if (ps != null) { 8944 // System apps are never considered stopped for purposes of 8945 // filtering, because there may be no way for the user to 8946 // actually re-launch them. 8947 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8948 && ps.getStopped(userId); 8949 } 8950 } 8951 return false; 8952 } 8953 8954 @Override 8955 protected boolean isPackageForFilter(String packageName, 8956 PackageParser.ActivityIntentInfo info) { 8957 return packageName.equals(info.activity.owner.packageName); 8958 } 8959 8960 @Override 8961 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8962 int match, int userId) { 8963 if (!sUserManager.exists(userId)) return null; 8964 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8965 return null; 8966 } 8967 final PackageParser.Activity activity = info.activity; 8968 if (mSafeMode && (activity.info.applicationInfo.flags 8969 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8970 return null; 8971 } 8972 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8973 if (ps == null) { 8974 return null; 8975 } 8976 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8977 ps.readUserState(userId), userId); 8978 if (ai == null) { 8979 return null; 8980 } 8981 final ResolveInfo res = new ResolveInfo(); 8982 res.activityInfo = ai; 8983 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8984 res.filter = info; 8985 } 8986 if (info != null) { 8987 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8988 } 8989 res.priority = info.getPriority(); 8990 res.preferredOrder = activity.owner.mPreferredOrder; 8991 //System.out.println("Result: " + res.activityInfo.className + 8992 // " = " + res.priority); 8993 res.match = match; 8994 res.isDefault = info.hasDefault; 8995 res.labelRes = info.labelRes; 8996 res.nonLocalizedLabel = info.nonLocalizedLabel; 8997 if (userNeedsBadging(userId)) { 8998 res.noResourceId = true; 8999 } else { 9000 res.icon = info.icon; 9001 } 9002 res.iconResourceId = info.icon; 9003 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9004 return res; 9005 } 9006 9007 @Override 9008 protected void sortResults(List<ResolveInfo> results) { 9009 Collections.sort(results, mResolvePrioritySorter); 9010 } 9011 9012 @Override 9013 protected void dumpFilter(PrintWriter out, String prefix, 9014 PackageParser.ActivityIntentInfo filter) { 9015 out.print(prefix); out.print( 9016 Integer.toHexString(System.identityHashCode(filter.activity))); 9017 out.print(' '); 9018 filter.activity.printComponentShortName(out); 9019 out.print(" filter "); 9020 out.println(Integer.toHexString(System.identityHashCode(filter))); 9021 } 9022 9023 @Override 9024 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9025 return filter.activity; 9026 } 9027 9028 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9029 PackageParser.Activity activity = (PackageParser.Activity)label; 9030 out.print(prefix); out.print( 9031 Integer.toHexString(System.identityHashCode(activity))); 9032 out.print(' '); 9033 activity.printComponentShortName(out); 9034 if (count > 1) { 9035 out.print(" ("); out.print(count); out.print(" filters)"); 9036 } 9037 out.println(); 9038 } 9039 9040// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9041// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9042// final List<ResolveInfo> retList = Lists.newArrayList(); 9043// while (i.hasNext()) { 9044// final ResolveInfo resolveInfo = i.next(); 9045// if (isEnabledLP(resolveInfo.activityInfo)) { 9046// retList.add(resolveInfo); 9047// } 9048// } 9049// return retList; 9050// } 9051 9052 // Keys are String (activity class name), values are Activity. 9053 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9054 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9055 private int mFlags; 9056 } 9057 9058 private final class ServiceIntentResolver 9059 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9060 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9061 boolean defaultOnly, int userId) { 9062 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9063 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9064 } 9065 9066 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9067 int userId) { 9068 if (!sUserManager.exists(userId)) return null; 9069 mFlags = flags; 9070 return super.queryIntent(intent, resolvedType, 9071 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9072 } 9073 9074 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9075 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9076 if (!sUserManager.exists(userId)) return null; 9077 if (packageServices == null) { 9078 return null; 9079 } 9080 mFlags = flags; 9081 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9082 final int N = packageServices.size(); 9083 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9084 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9085 9086 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9087 for (int i = 0; i < N; ++i) { 9088 intentFilters = packageServices.get(i).intents; 9089 if (intentFilters != null && intentFilters.size() > 0) { 9090 PackageParser.ServiceIntentInfo[] array = 9091 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9092 intentFilters.toArray(array); 9093 listCut.add(array); 9094 } 9095 } 9096 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9097 } 9098 9099 public final void addService(PackageParser.Service s) { 9100 mServices.put(s.getComponentName(), s); 9101 if (DEBUG_SHOW_INFO) { 9102 Log.v(TAG, " " 9103 + (s.info.nonLocalizedLabel != null 9104 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9105 Log.v(TAG, " Class=" + s.info.name); 9106 } 9107 final int NI = s.intents.size(); 9108 int j; 9109 for (j=0; j<NI; j++) { 9110 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9111 if (DEBUG_SHOW_INFO) { 9112 Log.v(TAG, " IntentFilter:"); 9113 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9114 } 9115 if (!intent.debugCheck()) { 9116 Log.w(TAG, "==> For Service " + s.info.name); 9117 } 9118 addFilter(intent); 9119 } 9120 } 9121 9122 public final void removeService(PackageParser.Service s) { 9123 mServices.remove(s.getComponentName()); 9124 if (DEBUG_SHOW_INFO) { 9125 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9126 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9127 Log.v(TAG, " Class=" + s.info.name); 9128 } 9129 final int NI = s.intents.size(); 9130 int j; 9131 for (j=0; j<NI; j++) { 9132 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9133 if (DEBUG_SHOW_INFO) { 9134 Log.v(TAG, " IntentFilter:"); 9135 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9136 } 9137 removeFilter(intent); 9138 } 9139 } 9140 9141 @Override 9142 protected boolean allowFilterResult( 9143 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9144 ServiceInfo filterSi = filter.service.info; 9145 for (int i=dest.size()-1; i>=0; i--) { 9146 ServiceInfo destAi = dest.get(i).serviceInfo; 9147 if (destAi.name == filterSi.name 9148 && destAi.packageName == filterSi.packageName) { 9149 return false; 9150 } 9151 } 9152 return true; 9153 } 9154 9155 @Override 9156 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9157 return new PackageParser.ServiceIntentInfo[size]; 9158 } 9159 9160 @Override 9161 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9162 if (!sUserManager.exists(userId)) return true; 9163 PackageParser.Package p = filter.service.owner; 9164 if (p != null) { 9165 PackageSetting ps = (PackageSetting)p.mExtras; 9166 if (ps != null) { 9167 // System apps are never considered stopped for purposes of 9168 // filtering, because there may be no way for the user to 9169 // actually re-launch them. 9170 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9171 && ps.getStopped(userId); 9172 } 9173 } 9174 return false; 9175 } 9176 9177 @Override 9178 protected boolean isPackageForFilter(String packageName, 9179 PackageParser.ServiceIntentInfo info) { 9180 return packageName.equals(info.service.owner.packageName); 9181 } 9182 9183 @Override 9184 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9185 int match, int userId) { 9186 if (!sUserManager.exists(userId)) return null; 9187 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9188 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9189 return null; 9190 } 9191 final PackageParser.Service service = info.service; 9192 if (mSafeMode && (service.info.applicationInfo.flags 9193 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9194 return null; 9195 } 9196 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9197 if (ps == null) { 9198 return null; 9199 } 9200 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9201 ps.readUserState(userId), userId); 9202 if (si == null) { 9203 return null; 9204 } 9205 final ResolveInfo res = new ResolveInfo(); 9206 res.serviceInfo = si; 9207 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9208 res.filter = filter; 9209 } 9210 res.priority = info.getPriority(); 9211 res.preferredOrder = service.owner.mPreferredOrder; 9212 res.match = match; 9213 res.isDefault = info.hasDefault; 9214 res.labelRes = info.labelRes; 9215 res.nonLocalizedLabel = info.nonLocalizedLabel; 9216 res.icon = info.icon; 9217 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9218 return res; 9219 } 9220 9221 @Override 9222 protected void sortResults(List<ResolveInfo> results) { 9223 Collections.sort(results, mResolvePrioritySorter); 9224 } 9225 9226 @Override 9227 protected void dumpFilter(PrintWriter out, String prefix, 9228 PackageParser.ServiceIntentInfo filter) { 9229 out.print(prefix); out.print( 9230 Integer.toHexString(System.identityHashCode(filter.service))); 9231 out.print(' '); 9232 filter.service.printComponentShortName(out); 9233 out.print(" filter "); 9234 out.println(Integer.toHexString(System.identityHashCode(filter))); 9235 } 9236 9237 @Override 9238 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9239 return filter.service; 9240 } 9241 9242 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9243 PackageParser.Service service = (PackageParser.Service)label; 9244 out.print(prefix); out.print( 9245 Integer.toHexString(System.identityHashCode(service))); 9246 out.print(' '); 9247 service.printComponentShortName(out); 9248 if (count > 1) { 9249 out.print(" ("); out.print(count); out.print(" filters)"); 9250 } 9251 out.println(); 9252 } 9253 9254// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9255// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9256// final List<ResolveInfo> retList = Lists.newArrayList(); 9257// while (i.hasNext()) { 9258// final ResolveInfo resolveInfo = (ResolveInfo) i; 9259// if (isEnabledLP(resolveInfo.serviceInfo)) { 9260// retList.add(resolveInfo); 9261// } 9262// } 9263// return retList; 9264// } 9265 9266 // Keys are String (activity class name), values are Activity. 9267 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9268 = new ArrayMap<ComponentName, PackageParser.Service>(); 9269 private int mFlags; 9270 }; 9271 9272 private final class ProviderIntentResolver 9273 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9274 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9275 boolean defaultOnly, int userId) { 9276 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9277 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9278 } 9279 9280 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9281 int userId) { 9282 if (!sUserManager.exists(userId)) 9283 return null; 9284 mFlags = flags; 9285 return super.queryIntent(intent, resolvedType, 9286 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9287 } 9288 9289 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9290 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9291 if (!sUserManager.exists(userId)) 9292 return null; 9293 if (packageProviders == null) { 9294 return null; 9295 } 9296 mFlags = flags; 9297 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9298 final int N = packageProviders.size(); 9299 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9300 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9301 9302 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9303 for (int i = 0; i < N; ++i) { 9304 intentFilters = packageProviders.get(i).intents; 9305 if (intentFilters != null && intentFilters.size() > 0) { 9306 PackageParser.ProviderIntentInfo[] array = 9307 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9308 intentFilters.toArray(array); 9309 listCut.add(array); 9310 } 9311 } 9312 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9313 } 9314 9315 public final void addProvider(PackageParser.Provider p) { 9316 if (mProviders.containsKey(p.getComponentName())) { 9317 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9318 return; 9319 } 9320 9321 mProviders.put(p.getComponentName(), p); 9322 if (DEBUG_SHOW_INFO) { 9323 Log.v(TAG, " " 9324 + (p.info.nonLocalizedLabel != null 9325 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9326 Log.v(TAG, " Class=" + p.info.name); 9327 } 9328 final int NI = p.intents.size(); 9329 int j; 9330 for (j = 0; j < NI; j++) { 9331 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9332 if (DEBUG_SHOW_INFO) { 9333 Log.v(TAG, " IntentFilter:"); 9334 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9335 } 9336 if (!intent.debugCheck()) { 9337 Log.w(TAG, "==> For Provider " + p.info.name); 9338 } 9339 addFilter(intent); 9340 } 9341 } 9342 9343 public final void removeProvider(PackageParser.Provider p) { 9344 mProviders.remove(p.getComponentName()); 9345 if (DEBUG_SHOW_INFO) { 9346 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9347 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9348 Log.v(TAG, " Class=" + p.info.name); 9349 } 9350 final int NI = p.intents.size(); 9351 int j; 9352 for (j = 0; j < NI; j++) { 9353 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9354 if (DEBUG_SHOW_INFO) { 9355 Log.v(TAG, " IntentFilter:"); 9356 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9357 } 9358 removeFilter(intent); 9359 } 9360 } 9361 9362 @Override 9363 protected boolean allowFilterResult( 9364 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9365 ProviderInfo filterPi = filter.provider.info; 9366 for (int i = dest.size() - 1; i >= 0; i--) { 9367 ProviderInfo destPi = dest.get(i).providerInfo; 9368 if (destPi.name == filterPi.name 9369 && destPi.packageName == filterPi.packageName) { 9370 return false; 9371 } 9372 } 9373 return true; 9374 } 9375 9376 @Override 9377 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9378 return new PackageParser.ProviderIntentInfo[size]; 9379 } 9380 9381 @Override 9382 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9383 if (!sUserManager.exists(userId)) 9384 return true; 9385 PackageParser.Package p = filter.provider.owner; 9386 if (p != null) { 9387 PackageSetting ps = (PackageSetting) p.mExtras; 9388 if (ps != null) { 9389 // System apps are never considered stopped for purposes of 9390 // filtering, because there may be no way for the user to 9391 // actually re-launch them. 9392 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9393 && ps.getStopped(userId); 9394 } 9395 } 9396 return false; 9397 } 9398 9399 @Override 9400 protected boolean isPackageForFilter(String packageName, 9401 PackageParser.ProviderIntentInfo info) { 9402 return packageName.equals(info.provider.owner.packageName); 9403 } 9404 9405 @Override 9406 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9407 int match, int userId) { 9408 if (!sUserManager.exists(userId)) 9409 return null; 9410 final PackageParser.ProviderIntentInfo info = filter; 9411 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9412 return null; 9413 } 9414 final PackageParser.Provider provider = info.provider; 9415 if (mSafeMode && (provider.info.applicationInfo.flags 9416 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9417 return null; 9418 } 9419 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9420 if (ps == null) { 9421 return null; 9422 } 9423 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9424 ps.readUserState(userId), userId); 9425 if (pi == null) { 9426 return null; 9427 } 9428 final ResolveInfo res = new ResolveInfo(); 9429 res.providerInfo = pi; 9430 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9431 res.filter = filter; 9432 } 9433 res.priority = info.getPriority(); 9434 res.preferredOrder = provider.owner.mPreferredOrder; 9435 res.match = match; 9436 res.isDefault = info.hasDefault; 9437 res.labelRes = info.labelRes; 9438 res.nonLocalizedLabel = info.nonLocalizedLabel; 9439 res.icon = info.icon; 9440 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9441 return res; 9442 } 9443 9444 @Override 9445 protected void sortResults(List<ResolveInfo> results) { 9446 Collections.sort(results, mResolvePrioritySorter); 9447 } 9448 9449 @Override 9450 protected void dumpFilter(PrintWriter out, String prefix, 9451 PackageParser.ProviderIntentInfo filter) { 9452 out.print(prefix); 9453 out.print( 9454 Integer.toHexString(System.identityHashCode(filter.provider))); 9455 out.print(' '); 9456 filter.provider.printComponentShortName(out); 9457 out.print(" filter "); 9458 out.println(Integer.toHexString(System.identityHashCode(filter))); 9459 } 9460 9461 @Override 9462 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9463 return filter.provider; 9464 } 9465 9466 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9467 PackageParser.Provider provider = (PackageParser.Provider)label; 9468 out.print(prefix); out.print( 9469 Integer.toHexString(System.identityHashCode(provider))); 9470 out.print(' '); 9471 provider.printComponentShortName(out); 9472 if (count > 1) { 9473 out.print(" ("); out.print(count); out.print(" filters)"); 9474 } 9475 out.println(); 9476 } 9477 9478 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9479 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9480 private int mFlags; 9481 }; 9482 9483 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9484 new Comparator<ResolveInfo>() { 9485 public int compare(ResolveInfo r1, ResolveInfo r2) { 9486 int v1 = r1.priority; 9487 int v2 = r2.priority; 9488 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9489 if (v1 != v2) { 9490 return (v1 > v2) ? -1 : 1; 9491 } 9492 v1 = r1.preferredOrder; 9493 v2 = r2.preferredOrder; 9494 if (v1 != v2) { 9495 return (v1 > v2) ? -1 : 1; 9496 } 9497 if (r1.isDefault != r2.isDefault) { 9498 return r1.isDefault ? -1 : 1; 9499 } 9500 v1 = r1.match; 9501 v2 = r2.match; 9502 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9503 if (v1 != v2) { 9504 return (v1 > v2) ? -1 : 1; 9505 } 9506 if (r1.system != r2.system) { 9507 return r1.system ? -1 : 1; 9508 } 9509 return 0; 9510 } 9511 }; 9512 9513 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9514 new Comparator<ProviderInfo>() { 9515 public int compare(ProviderInfo p1, ProviderInfo p2) { 9516 final int v1 = p1.initOrder; 9517 final int v2 = p2.initOrder; 9518 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9519 } 9520 }; 9521 9522 final void sendPackageBroadcast(final String action, final String pkg, 9523 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9524 final int[] userIds) { 9525 mHandler.post(new Runnable() { 9526 @Override 9527 public void run() { 9528 try { 9529 final IActivityManager am = ActivityManagerNative.getDefault(); 9530 if (am == null) return; 9531 final int[] resolvedUserIds; 9532 if (userIds == null) { 9533 resolvedUserIds = am.getRunningUserIds(); 9534 } else { 9535 resolvedUserIds = userIds; 9536 } 9537 for (int id : resolvedUserIds) { 9538 final Intent intent = new Intent(action, 9539 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9540 if (extras != null) { 9541 intent.putExtras(extras); 9542 } 9543 if (targetPkg != null) { 9544 intent.setPackage(targetPkg); 9545 } 9546 // Modify the UID when posting to other users 9547 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9548 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9549 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9550 intent.putExtra(Intent.EXTRA_UID, uid); 9551 } 9552 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9553 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9554 if (DEBUG_BROADCASTS) { 9555 RuntimeException here = new RuntimeException("here"); 9556 here.fillInStackTrace(); 9557 Slog.d(TAG, "Sending to user " + id + ": " 9558 + intent.toShortString(false, true, false, false) 9559 + " " + intent.getExtras(), here); 9560 } 9561 am.broadcastIntent(null, intent, null, finishedReceiver, 9562 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9563 null, finishedReceiver != null, false, id); 9564 } 9565 } catch (RemoteException ex) { 9566 } 9567 } 9568 }); 9569 } 9570 9571 /** 9572 * Check if the external storage media is available. This is true if there 9573 * is a mounted external storage medium or if the external storage is 9574 * emulated. 9575 */ 9576 private boolean isExternalMediaAvailable() { 9577 return mMediaMounted || Environment.isExternalStorageEmulated(); 9578 } 9579 9580 @Override 9581 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9582 // writer 9583 synchronized (mPackages) { 9584 if (!isExternalMediaAvailable()) { 9585 // If the external storage is no longer mounted at this point, 9586 // the caller may not have been able to delete all of this 9587 // packages files and can not delete any more. Bail. 9588 return null; 9589 } 9590 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9591 if (lastPackage != null) { 9592 pkgs.remove(lastPackage); 9593 } 9594 if (pkgs.size() > 0) { 9595 return pkgs.get(0); 9596 } 9597 } 9598 return null; 9599 } 9600 9601 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9602 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9603 userId, andCode ? 1 : 0, packageName); 9604 if (mSystemReady) { 9605 msg.sendToTarget(); 9606 } else { 9607 if (mPostSystemReadyMessages == null) { 9608 mPostSystemReadyMessages = new ArrayList<>(); 9609 } 9610 mPostSystemReadyMessages.add(msg); 9611 } 9612 } 9613 9614 void startCleaningPackages() { 9615 // reader 9616 synchronized (mPackages) { 9617 if (!isExternalMediaAvailable()) { 9618 return; 9619 } 9620 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9621 return; 9622 } 9623 } 9624 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9625 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9626 IActivityManager am = ActivityManagerNative.getDefault(); 9627 if (am != null) { 9628 try { 9629 am.startService(null, intent, null, mContext.getOpPackageName(), 9630 UserHandle.USER_OWNER); 9631 } catch (RemoteException e) { 9632 } 9633 } 9634 } 9635 9636 @Override 9637 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9638 int installFlags, String installerPackageName, VerificationParams verificationParams, 9639 String packageAbiOverride) { 9640 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9641 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9642 } 9643 9644 @Override 9645 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9646 int installFlags, String installerPackageName, VerificationParams verificationParams, 9647 String packageAbiOverride, int userId) { 9648 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9649 9650 final int callingUid = Binder.getCallingUid(); 9651 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9652 9653 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9654 try { 9655 if (observer != null) { 9656 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9657 } 9658 } catch (RemoteException re) { 9659 } 9660 return; 9661 } 9662 9663 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9664 installFlags |= PackageManager.INSTALL_FROM_ADB; 9665 9666 } else { 9667 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9668 // about installerPackageName. 9669 9670 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9671 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9672 } 9673 9674 UserHandle user; 9675 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9676 user = UserHandle.ALL; 9677 } else { 9678 user = new UserHandle(userId); 9679 } 9680 9681 // Only system components can circumvent runtime permissions when installing. 9682 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9683 && mContext.checkCallingOrSelfPermission(Manifest.permission 9684 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9685 throw new SecurityException("You need the " 9686 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9687 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9688 } 9689 9690 verificationParams.setInstallerUid(callingUid); 9691 9692 final File originFile = new File(originPath); 9693 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9694 9695 final Message msg = mHandler.obtainMessage(INIT_COPY); 9696 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9697 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9698 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9699 msg.obj = params; 9700 9701 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9702 System.identityHashCode(msg.obj)); 9703 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9704 System.identityHashCode(msg.obj)); 9705 9706 mHandler.sendMessage(msg); 9707 } 9708 9709 void installStage(String packageName, File stagedDir, String stagedCid, 9710 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9711 String installerPackageName, int installerUid, UserHandle user) { 9712 final VerificationParams verifParams = new VerificationParams( 9713 null, sessionParams.originatingUri, sessionParams.referrerUri, installerUid, null); 9714 verifParams.setInstallerUid(installerUid); 9715 9716 final OriginInfo origin; 9717 if (stagedDir != null) { 9718 origin = OriginInfo.fromStagedFile(stagedDir); 9719 } else { 9720 origin = OriginInfo.fromStagedContainer(stagedCid); 9721 } 9722 9723 final Message msg = mHandler.obtainMessage(INIT_COPY); 9724 final InstallParams params = new InstallParams(origin, null, observer, 9725 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9726 verifParams, user, sessionParams.abiOverride, 9727 sessionParams.grantedRuntimePermissions); 9728 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9729 msg.obj = params; 9730 9731 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9732 System.identityHashCode(msg.obj)); 9733 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9734 System.identityHashCode(msg.obj)); 9735 9736 mHandler.sendMessage(msg); 9737 } 9738 9739 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9740 Bundle extras = new Bundle(1); 9741 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9742 9743 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9744 packageName, extras, null, null, new int[] {userId}); 9745 try { 9746 IActivityManager am = ActivityManagerNative.getDefault(); 9747 final boolean isSystem = 9748 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9749 if (isSystem && am.isUserRunning(userId, false)) { 9750 // The just-installed/enabled app is bundled on the system, so presumed 9751 // to be able to run automatically without needing an explicit launch. 9752 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9753 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9754 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9755 .setPackage(packageName); 9756 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9757 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9758 } 9759 } catch (RemoteException e) { 9760 // shouldn't happen 9761 Slog.w(TAG, "Unable to bootstrap installed package", e); 9762 } 9763 } 9764 9765 @Override 9766 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9767 int userId) { 9768 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9769 PackageSetting pkgSetting; 9770 final int uid = Binder.getCallingUid(); 9771 enforceCrossUserPermission(uid, userId, true, true, 9772 "setApplicationHiddenSetting for user " + userId); 9773 9774 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9775 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9776 return false; 9777 } 9778 9779 long callingId = Binder.clearCallingIdentity(); 9780 try { 9781 boolean sendAdded = false; 9782 boolean sendRemoved = false; 9783 // writer 9784 synchronized (mPackages) { 9785 pkgSetting = mSettings.mPackages.get(packageName); 9786 if (pkgSetting == null) { 9787 return false; 9788 } 9789 if (pkgSetting.getHidden(userId) != hidden) { 9790 pkgSetting.setHidden(hidden, userId); 9791 mSettings.writePackageRestrictionsLPr(userId); 9792 if (hidden) { 9793 sendRemoved = true; 9794 } else { 9795 sendAdded = true; 9796 } 9797 } 9798 } 9799 if (sendAdded) { 9800 sendPackageAddedForUser(packageName, pkgSetting, userId); 9801 return true; 9802 } 9803 if (sendRemoved) { 9804 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9805 "hiding pkg"); 9806 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9807 return true; 9808 } 9809 } finally { 9810 Binder.restoreCallingIdentity(callingId); 9811 } 9812 return false; 9813 } 9814 9815 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9816 int userId) { 9817 final PackageRemovedInfo info = new PackageRemovedInfo(); 9818 info.removedPackage = packageName; 9819 info.removedUsers = new int[] {userId}; 9820 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9821 info.sendBroadcast(false, false, false); 9822 } 9823 9824 /** 9825 * Returns true if application is not found or there was an error. Otherwise it returns 9826 * the hidden state of the package for the given user. 9827 */ 9828 @Override 9829 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9830 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9831 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9832 false, "getApplicationHidden for user " + userId); 9833 PackageSetting pkgSetting; 9834 long callingId = Binder.clearCallingIdentity(); 9835 try { 9836 // writer 9837 synchronized (mPackages) { 9838 pkgSetting = mSettings.mPackages.get(packageName); 9839 if (pkgSetting == null) { 9840 return true; 9841 } 9842 return pkgSetting.getHidden(userId); 9843 } 9844 } finally { 9845 Binder.restoreCallingIdentity(callingId); 9846 } 9847 } 9848 9849 /** 9850 * @hide 9851 */ 9852 @Override 9853 public int installExistingPackageAsUser(String packageName, int userId) { 9854 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9855 null); 9856 PackageSetting pkgSetting; 9857 final int uid = Binder.getCallingUid(); 9858 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9859 + userId); 9860 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9861 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9862 } 9863 9864 long callingId = Binder.clearCallingIdentity(); 9865 try { 9866 boolean sendAdded = false; 9867 9868 // writer 9869 synchronized (mPackages) { 9870 pkgSetting = mSettings.mPackages.get(packageName); 9871 if (pkgSetting == null) { 9872 return PackageManager.INSTALL_FAILED_INVALID_URI; 9873 } 9874 if (!pkgSetting.getInstalled(userId)) { 9875 pkgSetting.setInstalled(true, userId); 9876 pkgSetting.setHidden(false, userId); 9877 mSettings.writePackageRestrictionsLPr(userId); 9878 sendAdded = true; 9879 } 9880 } 9881 9882 if (sendAdded) { 9883 sendPackageAddedForUser(packageName, pkgSetting, userId); 9884 } 9885 } finally { 9886 Binder.restoreCallingIdentity(callingId); 9887 } 9888 9889 return PackageManager.INSTALL_SUCCEEDED; 9890 } 9891 9892 boolean isUserRestricted(int userId, String restrictionKey) { 9893 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9894 if (restrictions.getBoolean(restrictionKey, false)) { 9895 Log.w(TAG, "User is restricted: " + restrictionKey); 9896 return true; 9897 } 9898 return false; 9899 } 9900 9901 @Override 9902 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9903 mContext.enforceCallingOrSelfPermission( 9904 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9905 "Only package verification agents can verify applications"); 9906 9907 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9908 final PackageVerificationResponse response = new PackageVerificationResponse( 9909 verificationCode, Binder.getCallingUid()); 9910 msg.arg1 = id; 9911 msg.obj = response; 9912 mHandler.sendMessage(msg); 9913 } 9914 9915 @Override 9916 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9917 long millisecondsToDelay) { 9918 mContext.enforceCallingOrSelfPermission( 9919 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9920 "Only package verification agents can extend verification timeouts"); 9921 9922 final PackageVerificationState state = mPendingVerification.get(id); 9923 final PackageVerificationResponse response = new PackageVerificationResponse( 9924 verificationCodeAtTimeout, Binder.getCallingUid()); 9925 9926 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9927 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9928 } 9929 if (millisecondsToDelay < 0) { 9930 millisecondsToDelay = 0; 9931 } 9932 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9933 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9934 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9935 } 9936 9937 if ((state != null) && !state.timeoutExtended()) { 9938 state.extendTimeout(); 9939 9940 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9941 msg.arg1 = id; 9942 msg.obj = response; 9943 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9944 } 9945 } 9946 9947 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9948 int verificationCode, UserHandle user) { 9949 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9950 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9951 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9952 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9953 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9954 9955 mContext.sendBroadcastAsUser(intent, user, 9956 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9957 } 9958 9959 private ComponentName matchComponentForVerifier(String packageName, 9960 List<ResolveInfo> receivers) { 9961 ActivityInfo targetReceiver = null; 9962 9963 final int NR = receivers.size(); 9964 for (int i = 0; i < NR; i++) { 9965 final ResolveInfo info = receivers.get(i); 9966 if (info.activityInfo == null) { 9967 continue; 9968 } 9969 9970 if (packageName.equals(info.activityInfo.packageName)) { 9971 targetReceiver = info.activityInfo; 9972 break; 9973 } 9974 } 9975 9976 if (targetReceiver == null) { 9977 return null; 9978 } 9979 9980 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9981 } 9982 9983 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9984 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9985 if (pkgInfo.verifiers.length == 0) { 9986 return null; 9987 } 9988 9989 final int N = pkgInfo.verifiers.length; 9990 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9991 for (int i = 0; i < N; i++) { 9992 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9993 9994 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9995 receivers); 9996 if (comp == null) { 9997 continue; 9998 } 9999 10000 final int verifierUid = getUidForVerifier(verifierInfo); 10001 if (verifierUid == -1) { 10002 continue; 10003 } 10004 10005 if (DEBUG_VERIFY) { 10006 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10007 + " with the correct signature"); 10008 } 10009 sufficientVerifiers.add(comp); 10010 verificationState.addSufficientVerifier(verifierUid); 10011 } 10012 10013 return sufficientVerifiers; 10014 } 10015 10016 private int getUidForVerifier(VerifierInfo verifierInfo) { 10017 synchronized (mPackages) { 10018 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10019 if (pkg == null) { 10020 return -1; 10021 } else if (pkg.mSignatures.length != 1) { 10022 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10023 + " has more than one signature; ignoring"); 10024 return -1; 10025 } 10026 10027 /* 10028 * If the public key of the package's signature does not match 10029 * our expected public key, then this is a different package and 10030 * we should skip. 10031 */ 10032 10033 final byte[] expectedPublicKey; 10034 try { 10035 final Signature verifierSig = pkg.mSignatures[0]; 10036 final PublicKey publicKey = verifierSig.getPublicKey(); 10037 expectedPublicKey = publicKey.getEncoded(); 10038 } catch (CertificateException e) { 10039 return -1; 10040 } 10041 10042 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10043 10044 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10045 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10046 + " does not have the expected public key; ignoring"); 10047 return -1; 10048 } 10049 10050 return pkg.applicationInfo.uid; 10051 } 10052 } 10053 10054 @Override 10055 public void finishPackageInstall(int token) { 10056 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10057 10058 if (DEBUG_INSTALL) { 10059 Slog.v(TAG, "BM finishing package install for " + token); 10060 } 10061 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10062 10063 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10064 mHandler.sendMessage(msg); 10065 } 10066 10067 /** 10068 * Get the verification agent timeout. 10069 * 10070 * @return verification timeout in milliseconds 10071 */ 10072 private long getVerificationTimeout() { 10073 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10074 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10075 DEFAULT_VERIFICATION_TIMEOUT); 10076 } 10077 10078 /** 10079 * Get the default verification agent response code. 10080 * 10081 * @return default verification response code 10082 */ 10083 private int getDefaultVerificationResponse() { 10084 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10085 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10086 DEFAULT_VERIFICATION_RESPONSE); 10087 } 10088 10089 /** 10090 * Check whether or not package verification has been enabled. 10091 * 10092 * @return true if verification should be performed 10093 */ 10094 private boolean isVerificationEnabled(int userId, int installFlags) { 10095 if (!DEFAULT_VERIFY_ENABLE) { 10096 return false; 10097 } 10098 10099 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10100 10101 // Check if installing from ADB 10102 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10103 // Do not run verification in a test harness environment 10104 if (ActivityManager.isRunningInTestHarness()) { 10105 return false; 10106 } 10107 if (ensureVerifyAppsEnabled) { 10108 return true; 10109 } 10110 // Check if the developer does not want package verification for ADB installs 10111 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10112 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10113 return false; 10114 } 10115 } 10116 10117 if (ensureVerifyAppsEnabled) { 10118 return true; 10119 } 10120 10121 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10122 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10123 } 10124 10125 @Override 10126 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10127 throws RemoteException { 10128 mContext.enforceCallingOrSelfPermission( 10129 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10130 "Only intentfilter verification agents can verify applications"); 10131 10132 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10133 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10134 Binder.getCallingUid(), verificationCode, failedDomains); 10135 msg.arg1 = id; 10136 msg.obj = response; 10137 mHandler.sendMessage(msg); 10138 } 10139 10140 @Override 10141 public int getIntentVerificationStatus(String packageName, int userId) { 10142 synchronized (mPackages) { 10143 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10144 } 10145 } 10146 10147 @Override 10148 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10149 mContext.enforceCallingOrSelfPermission( 10150 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10151 10152 boolean result = false; 10153 synchronized (mPackages) { 10154 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10155 } 10156 if (result) { 10157 scheduleWritePackageRestrictionsLocked(userId); 10158 } 10159 return result; 10160 } 10161 10162 @Override 10163 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10164 synchronized (mPackages) { 10165 return mSettings.getIntentFilterVerificationsLPr(packageName); 10166 } 10167 } 10168 10169 @Override 10170 public List<IntentFilter> getAllIntentFilters(String packageName) { 10171 if (TextUtils.isEmpty(packageName)) { 10172 return Collections.<IntentFilter>emptyList(); 10173 } 10174 synchronized (mPackages) { 10175 PackageParser.Package pkg = mPackages.get(packageName); 10176 if (pkg == null || pkg.activities == null) { 10177 return Collections.<IntentFilter>emptyList(); 10178 } 10179 final int count = pkg.activities.size(); 10180 ArrayList<IntentFilter> result = new ArrayList<>(); 10181 for (int n=0; n<count; n++) { 10182 PackageParser.Activity activity = pkg.activities.get(n); 10183 if (activity.intents != null || activity.intents.size() > 0) { 10184 result.addAll(activity.intents); 10185 } 10186 } 10187 return result; 10188 } 10189 } 10190 10191 @Override 10192 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10193 mContext.enforceCallingOrSelfPermission( 10194 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10195 10196 synchronized (mPackages) { 10197 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10198 if (packageName != null) { 10199 result |= updateIntentVerificationStatus(packageName, 10200 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10201 userId); 10202 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10203 packageName, userId); 10204 } 10205 return result; 10206 } 10207 } 10208 10209 @Override 10210 public String getDefaultBrowserPackageName(int userId) { 10211 synchronized (mPackages) { 10212 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10213 } 10214 } 10215 10216 /** 10217 * Get the "allow unknown sources" setting. 10218 * 10219 * @return the current "allow unknown sources" setting 10220 */ 10221 private int getUnknownSourcesSettings() { 10222 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10223 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10224 -1); 10225 } 10226 10227 @Override 10228 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10229 final int uid = Binder.getCallingUid(); 10230 // writer 10231 synchronized (mPackages) { 10232 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10233 if (targetPackageSetting == null) { 10234 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10235 } 10236 10237 PackageSetting installerPackageSetting; 10238 if (installerPackageName != null) { 10239 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10240 if (installerPackageSetting == null) { 10241 throw new IllegalArgumentException("Unknown installer package: " 10242 + installerPackageName); 10243 } 10244 } else { 10245 installerPackageSetting = null; 10246 } 10247 10248 Signature[] callerSignature; 10249 Object obj = mSettings.getUserIdLPr(uid); 10250 if (obj != null) { 10251 if (obj instanceof SharedUserSetting) { 10252 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10253 } else if (obj instanceof PackageSetting) { 10254 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10255 } else { 10256 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10257 } 10258 } else { 10259 throw new SecurityException("Unknown calling uid " + uid); 10260 } 10261 10262 // Verify: can't set installerPackageName to a package that is 10263 // not signed with the same cert as the caller. 10264 if (installerPackageSetting != null) { 10265 if (compareSignatures(callerSignature, 10266 installerPackageSetting.signatures.mSignatures) 10267 != PackageManager.SIGNATURE_MATCH) { 10268 throw new SecurityException( 10269 "Caller does not have same cert as new installer package " 10270 + installerPackageName); 10271 } 10272 } 10273 10274 // Verify: if target already has an installer package, it must 10275 // be signed with the same cert as the caller. 10276 if (targetPackageSetting.installerPackageName != null) { 10277 PackageSetting setting = mSettings.mPackages.get( 10278 targetPackageSetting.installerPackageName); 10279 // If the currently set package isn't valid, then it's always 10280 // okay to change it. 10281 if (setting != null) { 10282 if (compareSignatures(callerSignature, 10283 setting.signatures.mSignatures) 10284 != PackageManager.SIGNATURE_MATCH) { 10285 throw new SecurityException( 10286 "Caller does not have same cert as old installer package " 10287 + targetPackageSetting.installerPackageName); 10288 } 10289 } 10290 } 10291 10292 // Okay! 10293 targetPackageSetting.installerPackageName = installerPackageName; 10294 scheduleWriteSettingsLocked(); 10295 } 10296 } 10297 10298 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10299 // Queue up an async operation since the package installation may take a little while. 10300 mHandler.post(new Runnable() { 10301 public void run() { 10302 mHandler.removeCallbacks(this); 10303 // Result object to be returned 10304 PackageInstalledInfo res = new PackageInstalledInfo(); 10305 res.returnCode = currentStatus; 10306 res.uid = -1; 10307 res.pkg = null; 10308 res.removedInfo = new PackageRemovedInfo(); 10309 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10310 args.doPreInstall(res.returnCode); 10311 synchronized (mInstallLock) { 10312 installPackageTracedLI(args, res); 10313 } 10314 args.doPostInstall(res.returnCode, res.uid); 10315 } 10316 10317 // A restore should be performed at this point if (a) the install 10318 // succeeded, (b) the operation is not an update, and (c) the new 10319 // package has not opted out of backup participation. 10320 final boolean update = res.removedInfo.removedPackage != null; 10321 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10322 boolean doRestore = !update 10323 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10324 10325 // Set up the post-install work request bookkeeping. This will be used 10326 // and cleaned up by the post-install event handling regardless of whether 10327 // there's a restore pass performed. Token values are >= 1. 10328 int token; 10329 if (mNextInstallToken < 0) mNextInstallToken = 1; 10330 token = mNextInstallToken++; 10331 10332 PostInstallData data = new PostInstallData(args, res); 10333 mRunningInstalls.put(token, data); 10334 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10335 10336 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10337 // Pass responsibility to the Backup Manager. It will perform a 10338 // restore if appropriate, then pass responsibility back to the 10339 // Package Manager to run the post-install observer callbacks 10340 // and broadcasts. 10341 IBackupManager bm = IBackupManager.Stub.asInterface( 10342 ServiceManager.getService(Context.BACKUP_SERVICE)); 10343 if (bm != null) { 10344 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10345 + " to BM for possible restore"); 10346 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10347 try { 10348 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10349 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10350 } else { 10351 doRestore = false; 10352 } 10353 } catch (RemoteException e) { 10354 // can't happen; the backup manager is local 10355 } catch (Exception e) { 10356 Slog.e(TAG, "Exception trying to enqueue restore", e); 10357 doRestore = false; 10358 } 10359 } else { 10360 Slog.e(TAG, "Backup Manager not found!"); 10361 doRestore = false; 10362 } 10363 } 10364 10365 if (!doRestore) { 10366 // No restore possible, or the Backup Manager was mysteriously not 10367 // available -- just fire the post-install work request directly. 10368 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10369 10370 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10371 10372 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10373 mHandler.sendMessage(msg); 10374 } 10375 } 10376 }); 10377 } 10378 10379 private abstract class HandlerParams { 10380 private static final int MAX_RETRIES = 4; 10381 10382 /** 10383 * Number of times startCopy() has been attempted and had a non-fatal 10384 * error. 10385 */ 10386 private int mRetries = 0; 10387 10388 /** User handle for the user requesting the information or installation. */ 10389 private final UserHandle mUser; 10390 String traceMethod; 10391 int traceCookie; 10392 10393 HandlerParams(UserHandle user) { 10394 mUser = user; 10395 } 10396 10397 UserHandle getUser() { 10398 return mUser; 10399 } 10400 10401 HandlerParams setTraceMethod(String traceMethod) { 10402 this.traceMethod = traceMethod; 10403 return this; 10404 } 10405 10406 HandlerParams setTraceCookie(int traceCookie) { 10407 this.traceCookie = traceCookie; 10408 return this; 10409 } 10410 10411 final boolean startCopy() { 10412 boolean res; 10413 try { 10414 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10415 10416 if (++mRetries > MAX_RETRIES) { 10417 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10418 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10419 handleServiceError(); 10420 return false; 10421 } else { 10422 handleStartCopy(); 10423 res = true; 10424 } 10425 } catch (RemoteException e) { 10426 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10427 mHandler.sendEmptyMessage(MCS_RECONNECT); 10428 res = false; 10429 } 10430 handleReturnCode(); 10431 return res; 10432 } 10433 10434 final void serviceError() { 10435 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10436 handleServiceError(); 10437 handleReturnCode(); 10438 } 10439 10440 abstract void handleStartCopy() throws RemoteException; 10441 abstract void handleServiceError(); 10442 abstract void handleReturnCode(); 10443 } 10444 10445 class MeasureParams extends HandlerParams { 10446 private final PackageStats mStats; 10447 private boolean mSuccess; 10448 10449 private final IPackageStatsObserver mObserver; 10450 10451 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10452 super(new UserHandle(stats.userHandle)); 10453 mObserver = observer; 10454 mStats = stats; 10455 } 10456 10457 @Override 10458 public String toString() { 10459 return "MeasureParams{" 10460 + Integer.toHexString(System.identityHashCode(this)) 10461 + " " + mStats.packageName + "}"; 10462 } 10463 10464 @Override 10465 void handleStartCopy() throws RemoteException { 10466 synchronized (mInstallLock) { 10467 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10468 } 10469 10470 if (mSuccess) { 10471 final boolean mounted; 10472 if (Environment.isExternalStorageEmulated()) { 10473 mounted = true; 10474 } else { 10475 final String status = Environment.getExternalStorageState(); 10476 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10477 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10478 } 10479 10480 if (mounted) { 10481 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10482 10483 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10484 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10485 10486 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10487 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10488 10489 // Always subtract cache size, since it's a subdirectory 10490 mStats.externalDataSize -= mStats.externalCacheSize; 10491 10492 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10493 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10494 10495 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10496 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10497 } 10498 } 10499 } 10500 10501 @Override 10502 void handleReturnCode() { 10503 if (mObserver != null) { 10504 try { 10505 mObserver.onGetStatsCompleted(mStats, mSuccess); 10506 } catch (RemoteException e) { 10507 Slog.i(TAG, "Observer no longer exists."); 10508 } 10509 } 10510 } 10511 10512 @Override 10513 void handleServiceError() { 10514 Slog.e(TAG, "Could not measure application " + mStats.packageName 10515 + " external storage"); 10516 } 10517 } 10518 10519 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10520 throws RemoteException { 10521 long result = 0; 10522 for (File path : paths) { 10523 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10524 } 10525 return result; 10526 } 10527 10528 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10529 for (File path : paths) { 10530 try { 10531 mcs.clearDirectory(path.getAbsolutePath()); 10532 } catch (RemoteException e) { 10533 } 10534 } 10535 } 10536 10537 static class OriginInfo { 10538 /** 10539 * Location where install is coming from, before it has been 10540 * copied/renamed into place. This could be a single monolithic APK 10541 * file, or a cluster directory. This location may be untrusted. 10542 */ 10543 final File file; 10544 final String cid; 10545 10546 /** 10547 * Flag indicating that {@link #file} or {@link #cid} has already been 10548 * staged, meaning downstream users don't need to defensively copy the 10549 * contents. 10550 */ 10551 final boolean staged; 10552 10553 /** 10554 * Flag indicating that {@link #file} or {@link #cid} is an already 10555 * installed app that is being moved. 10556 */ 10557 final boolean existing; 10558 10559 final String resolvedPath; 10560 final File resolvedFile; 10561 10562 static OriginInfo fromNothing() { 10563 return new OriginInfo(null, null, false, false); 10564 } 10565 10566 static OriginInfo fromUntrustedFile(File file) { 10567 return new OriginInfo(file, null, false, false); 10568 } 10569 10570 static OriginInfo fromExistingFile(File file) { 10571 return new OriginInfo(file, null, false, true); 10572 } 10573 10574 static OriginInfo fromStagedFile(File file) { 10575 return new OriginInfo(file, null, true, false); 10576 } 10577 10578 static OriginInfo fromStagedContainer(String cid) { 10579 return new OriginInfo(null, cid, true, false); 10580 } 10581 10582 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10583 this.file = file; 10584 this.cid = cid; 10585 this.staged = staged; 10586 this.existing = existing; 10587 10588 if (cid != null) { 10589 resolvedPath = PackageHelper.getSdDir(cid); 10590 resolvedFile = new File(resolvedPath); 10591 } else if (file != null) { 10592 resolvedPath = file.getAbsolutePath(); 10593 resolvedFile = file; 10594 } else { 10595 resolvedPath = null; 10596 resolvedFile = null; 10597 } 10598 } 10599 } 10600 10601 class MoveInfo { 10602 final int moveId; 10603 final String fromUuid; 10604 final String toUuid; 10605 final String packageName; 10606 final String dataAppName; 10607 final int appId; 10608 final String seinfo; 10609 10610 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10611 String dataAppName, int appId, String seinfo) { 10612 this.moveId = moveId; 10613 this.fromUuid = fromUuid; 10614 this.toUuid = toUuid; 10615 this.packageName = packageName; 10616 this.dataAppName = dataAppName; 10617 this.appId = appId; 10618 this.seinfo = seinfo; 10619 } 10620 } 10621 10622 class InstallParams extends HandlerParams { 10623 final OriginInfo origin; 10624 final MoveInfo move; 10625 final IPackageInstallObserver2 observer; 10626 int installFlags; 10627 final String installerPackageName; 10628 final String volumeUuid; 10629 final VerificationParams verificationParams; 10630 private InstallArgs mArgs; 10631 private int mRet; 10632 final String packageAbiOverride; 10633 final String[] grantedRuntimePermissions; 10634 10635 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10636 int installFlags, String installerPackageName, String volumeUuid, 10637 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10638 String[] grantedPermissions) { 10639 super(user); 10640 this.origin = origin; 10641 this.move = move; 10642 this.observer = observer; 10643 this.installFlags = installFlags; 10644 this.installerPackageName = installerPackageName; 10645 this.volumeUuid = volumeUuid; 10646 this.verificationParams = verificationParams; 10647 this.packageAbiOverride = packageAbiOverride; 10648 this.grantedRuntimePermissions = grantedPermissions; 10649 } 10650 10651 @Override 10652 public String toString() { 10653 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10654 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10655 } 10656 10657 public ManifestDigest getManifestDigest() { 10658 if (verificationParams == null) { 10659 return null; 10660 } 10661 return verificationParams.getManifestDigest(); 10662 } 10663 10664 private int installLocationPolicy(PackageInfoLite pkgLite) { 10665 String packageName = pkgLite.packageName; 10666 int installLocation = pkgLite.installLocation; 10667 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10668 // reader 10669 synchronized (mPackages) { 10670 PackageParser.Package pkg = mPackages.get(packageName); 10671 if (pkg != null) { 10672 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10673 // Check for downgrading. 10674 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10675 try { 10676 checkDowngrade(pkg, pkgLite); 10677 } catch (PackageManagerException e) { 10678 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10679 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10680 } 10681 } 10682 // Check for updated system application. 10683 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10684 if (onSd) { 10685 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10686 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10687 } 10688 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10689 } else { 10690 if (onSd) { 10691 // Install flag overrides everything. 10692 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10693 } 10694 // If current upgrade specifies particular preference 10695 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10696 // Application explicitly specified internal. 10697 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10698 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10699 // App explictly prefers external. Let policy decide 10700 } else { 10701 // Prefer previous location 10702 if (isExternal(pkg)) { 10703 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10704 } 10705 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10706 } 10707 } 10708 } else { 10709 // Invalid install. Return error code 10710 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10711 } 10712 } 10713 } 10714 // All the special cases have been taken care of. 10715 // Return result based on recommended install location. 10716 if (onSd) { 10717 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10718 } 10719 return pkgLite.recommendedInstallLocation; 10720 } 10721 10722 /* 10723 * Invoke remote method to get package information and install 10724 * location values. Override install location based on default 10725 * policy if needed and then create install arguments based 10726 * on the install location. 10727 */ 10728 public void handleStartCopy() throws RemoteException { 10729 int ret = PackageManager.INSTALL_SUCCEEDED; 10730 10731 // If we're already staged, we've firmly committed to an install location 10732 if (origin.staged) { 10733 if (origin.file != null) { 10734 installFlags |= PackageManager.INSTALL_INTERNAL; 10735 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10736 } else if (origin.cid != null) { 10737 installFlags |= PackageManager.INSTALL_EXTERNAL; 10738 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10739 } else { 10740 throw new IllegalStateException("Invalid stage location"); 10741 } 10742 } 10743 10744 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10745 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10746 PackageInfoLite pkgLite = null; 10747 10748 if (onInt && onSd) { 10749 // Check if both bits are set. 10750 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10751 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10752 } else { 10753 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10754 packageAbiOverride); 10755 10756 /* 10757 * If we have too little free space, try to free cache 10758 * before giving up. 10759 */ 10760 if (!origin.staged && pkgLite.recommendedInstallLocation 10761 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10762 // TODO: focus freeing disk space on the target device 10763 final StorageManager storage = StorageManager.from(mContext); 10764 final long lowThreshold = storage.getStorageLowBytes( 10765 Environment.getDataDirectory()); 10766 10767 final long sizeBytes = mContainerService.calculateInstalledSize( 10768 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10769 10770 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10771 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10772 installFlags, packageAbiOverride); 10773 } 10774 10775 /* 10776 * The cache free must have deleted the file we 10777 * downloaded to install. 10778 * 10779 * TODO: fix the "freeCache" call to not delete 10780 * the file we care about. 10781 */ 10782 if (pkgLite.recommendedInstallLocation 10783 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10784 pkgLite.recommendedInstallLocation 10785 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10786 } 10787 } 10788 } 10789 10790 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10791 int loc = pkgLite.recommendedInstallLocation; 10792 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10793 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10794 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10795 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10796 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10797 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10798 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10799 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10800 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10801 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10802 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10803 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10804 } else { 10805 // Override with defaults if needed. 10806 loc = installLocationPolicy(pkgLite); 10807 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10808 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10809 } else if (!onSd && !onInt) { 10810 // Override install location with flags 10811 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10812 // Set the flag to install on external media. 10813 installFlags |= PackageManager.INSTALL_EXTERNAL; 10814 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10815 } else { 10816 // Make sure the flag for installing on external 10817 // media is unset 10818 installFlags |= PackageManager.INSTALL_INTERNAL; 10819 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10820 } 10821 } 10822 } 10823 } 10824 10825 final InstallArgs args = createInstallArgs(this); 10826 mArgs = args; 10827 10828 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10829 /* 10830 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10831 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10832 */ 10833 int userIdentifier = getUser().getIdentifier(); 10834 if (userIdentifier == UserHandle.USER_ALL 10835 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10836 userIdentifier = UserHandle.USER_OWNER; 10837 } 10838 10839 /* 10840 * Determine if we have any installed package verifiers. If we 10841 * do, then we'll defer to them to verify the packages. 10842 */ 10843 final int requiredUid = mRequiredVerifierPackage == null ? -1 10844 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10845 if (!origin.existing && requiredUid != -1 10846 && isVerificationEnabled(userIdentifier, installFlags)) { 10847 final Intent verification = new Intent( 10848 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10849 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10850 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10851 PACKAGE_MIME_TYPE); 10852 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10853 10854 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10855 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10856 0 /* TODO: Which userId? */); 10857 10858 if (DEBUG_VERIFY) { 10859 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10860 + verification.toString() + " with " + pkgLite.verifiers.length 10861 + " optional verifiers"); 10862 } 10863 10864 final int verificationId = mPendingVerificationToken++; 10865 10866 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10867 10868 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10869 installerPackageName); 10870 10871 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10872 installFlags); 10873 10874 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10875 pkgLite.packageName); 10876 10877 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10878 pkgLite.versionCode); 10879 10880 if (verificationParams != null) { 10881 if (verificationParams.getVerificationURI() != null) { 10882 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10883 verificationParams.getVerificationURI()); 10884 } 10885 if (verificationParams.getOriginatingURI() != null) { 10886 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10887 verificationParams.getOriginatingURI()); 10888 } 10889 if (verificationParams.getReferrer() != null) { 10890 verification.putExtra(Intent.EXTRA_REFERRER, 10891 verificationParams.getReferrer()); 10892 } 10893 if (verificationParams.getOriginatingUid() >= 0) { 10894 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10895 verificationParams.getOriginatingUid()); 10896 } 10897 if (verificationParams.getInstallerUid() >= 0) { 10898 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10899 verificationParams.getInstallerUid()); 10900 } 10901 } 10902 10903 final PackageVerificationState verificationState = new PackageVerificationState( 10904 requiredUid, args); 10905 10906 mPendingVerification.append(verificationId, verificationState); 10907 10908 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10909 receivers, verificationState); 10910 10911 // Apps installed for "all" users use the device owner to verify the app 10912 UserHandle verifierUser = getUser(); 10913 if (verifierUser == UserHandle.ALL) { 10914 verifierUser = UserHandle.OWNER; 10915 } 10916 10917 /* 10918 * If any sufficient verifiers were listed in the package 10919 * manifest, attempt to ask them. 10920 */ 10921 if (sufficientVerifiers != null) { 10922 final int N = sufficientVerifiers.size(); 10923 if (N == 0) { 10924 Slog.i(TAG, "Additional verifiers required, but none installed."); 10925 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10926 } else { 10927 for (int i = 0; i < N; i++) { 10928 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10929 10930 final Intent sufficientIntent = new Intent(verification); 10931 sufficientIntent.setComponent(verifierComponent); 10932 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10933 } 10934 } 10935 } 10936 10937 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10938 mRequiredVerifierPackage, receivers); 10939 if (ret == PackageManager.INSTALL_SUCCEEDED 10940 && mRequiredVerifierPackage != null) { 10941 Trace.asyncTraceBegin( 10942 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10943 /* 10944 * Send the intent to the required verification agent, 10945 * but only start the verification timeout after the 10946 * target BroadcastReceivers have run. 10947 */ 10948 verification.setComponent(requiredVerifierComponent); 10949 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10950 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10951 new BroadcastReceiver() { 10952 @Override 10953 public void onReceive(Context context, Intent intent) { 10954 final Message msg = mHandler 10955 .obtainMessage(CHECK_PENDING_VERIFICATION); 10956 msg.arg1 = verificationId; 10957 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10958 } 10959 }, null, 0, null, null); 10960 10961 /* 10962 * We don't want the copy to proceed until verification 10963 * succeeds, so null out this field. 10964 */ 10965 mArgs = null; 10966 } 10967 } else { 10968 /* 10969 * No package verification is enabled, so immediately start 10970 * the remote call to initiate copy using temporary file. 10971 */ 10972 ret = args.copyApk(mContainerService, true); 10973 } 10974 } 10975 10976 mRet = ret; 10977 } 10978 10979 @Override 10980 void handleReturnCode() { 10981 // If mArgs is null, then MCS couldn't be reached. When it 10982 // reconnects, it will try again to install. At that point, this 10983 // will succeed. 10984 if (mArgs != null) { 10985 processPendingInstall(mArgs, mRet); 10986 } 10987 } 10988 10989 @Override 10990 void handleServiceError() { 10991 mArgs = createInstallArgs(this); 10992 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10993 } 10994 10995 public boolean isForwardLocked() { 10996 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10997 } 10998 } 10999 11000 /** 11001 * Used during creation of InstallArgs 11002 * 11003 * @param installFlags package installation flags 11004 * @return true if should be installed on external storage 11005 */ 11006 private static boolean installOnExternalAsec(int installFlags) { 11007 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11008 return false; 11009 } 11010 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11011 return true; 11012 } 11013 return false; 11014 } 11015 11016 /** 11017 * Used during creation of InstallArgs 11018 * 11019 * @param installFlags package installation flags 11020 * @return true if should be installed as forward locked 11021 */ 11022 private static boolean installForwardLocked(int installFlags) { 11023 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11024 } 11025 11026 private InstallArgs createInstallArgs(InstallParams params) { 11027 if (params.move != null) { 11028 return new MoveInstallArgs(params); 11029 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11030 return new AsecInstallArgs(params); 11031 } else { 11032 return new FileInstallArgs(params); 11033 } 11034 } 11035 11036 /** 11037 * Create args that describe an existing installed package. Typically used 11038 * when cleaning up old installs, or used as a move source. 11039 */ 11040 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11041 String resourcePath, String[] instructionSets) { 11042 final boolean isInAsec; 11043 if (installOnExternalAsec(installFlags)) { 11044 /* Apps on SD card are always in ASEC containers. */ 11045 isInAsec = true; 11046 } else if (installForwardLocked(installFlags) 11047 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11048 /* 11049 * Forward-locked apps are only in ASEC containers if they're the 11050 * new style 11051 */ 11052 isInAsec = true; 11053 } else { 11054 isInAsec = false; 11055 } 11056 11057 if (isInAsec) { 11058 return new AsecInstallArgs(codePath, instructionSets, 11059 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11060 } else { 11061 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11062 } 11063 } 11064 11065 static abstract class InstallArgs { 11066 /** @see InstallParams#origin */ 11067 final OriginInfo origin; 11068 /** @see InstallParams#move */ 11069 final MoveInfo move; 11070 11071 final IPackageInstallObserver2 observer; 11072 // Always refers to PackageManager flags only 11073 final int installFlags; 11074 final String installerPackageName; 11075 final String volumeUuid; 11076 final ManifestDigest manifestDigest; 11077 final UserHandle user; 11078 final String abiOverride; 11079 final String[] installGrantPermissions; 11080 /** If non-null, drop an async trace when the install completes */ 11081 final String traceMethod; 11082 final int traceCookie; 11083 11084 // The list of instruction sets supported by this app. This is currently 11085 // only used during the rmdex() phase to clean up resources. We can get rid of this 11086 // if we move dex files under the common app path. 11087 /* nullable */ String[] instructionSets; 11088 11089 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11090 int installFlags, String installerPackageName, String volumeUuid, 11091 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11092 String abiOverride, String[] installGrantPermissions, 11093 String traceMethod, int traceCookie) { 11094 this.origin = origin; 11095 this.move = move; 11096 this.installFlags = installFlags; 11097 this.observer = observer; 11098 this.installerPackageName = installerPackageName; 11099 this.volumeUuid = volumeUuid; 11100 this.manifestDigest = manifestDigest; 11101 this.user = user; 11102 this.instructionSets = instructionSets; 11103 this.abiOverride = abiOverride; 11104 this.installGrantPermissions = installGrantPermissions; 11105 this.traceMethod = traceMethod; 11106 this.traceCookie = traceCookie; 11107 } 11108 11109 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11110 abstract int doPreInstall(int status); 11111 11112 /** 11113 * Rename package into final resting place. All paths on the given 11114 * scanned package should be updated to reflect the rename. 11115 */ 11116 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11117 abstract int doPostInstall(int status, int uid); 11118 11119 /** @see PackageSettingBase#codePathString */ 11120 abstract String getCodePath(); 11121 /** @see PackageSettingBase#resourcePathString */ 11122 abstract String getResourcePath(); 11123 11124 // Need installer lock especially for dex file removal. 11125 abstract void cleanUpResourcesLI(); 11126 abstract boolean doPostDeleteLI(boolean delete); 11127 11128 /** 11129 * Called before the source arguments are copied. This is used mostly 11130 * for MoveParams when it needs to read the source file to put it in the 11131 * destination. 11132 */ 11133 int doPreCopy() { 11134 return PackageManager.INSTALL_SUCCEEDED; 11135 } 11136 11137 /** 11138 * Called after the source arguments are copied. This is used mostly for 11139 * MoveParams when it needs to read the source file to put it in the 11140 * destination. 11141 * 11142 * @return 11143 */ 11144 int doPostCopy(int uid) { 11145 return PackageManager.INSTALL_SUCCEEDED; 11146 } 11147 11148 protected boolean isFwdLocked() { 11149 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11150 } 11151 11152 protected boolean isExternalAsec() { 11153 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11154 } 11155 11156 UserHandle getUser() { 11157 return user; 11158 } 11159 } 11160 11161 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11162 if (!allCodePaths.isEmpty()) { 11163 if (instructionSets == null) { 11164 throw new IllegalStateException("instructionSet == null"); 11165 } 11166 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11167 for (String codePath : allCodePaths) { 11168 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11169 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11170 if (retCode < 0) { 11171 Slog.w(TAG, "Couldn't remove dex file for package: " 11172 + " at location " + codePath + ", retcode=" + retCode); 11173 // we don't consider this to be a failure of the core package deletion 11174 } 11175 } 11176 } 11177 } 11178 } 11179 11180 /** 11181 * Logic to handle installation of non-ASEC applications, including copying 11182 * and renaming logic. 11183 */ 11184 class FileInstallArgs extends InstallArgs { 11185 private File codeFile; 11186 private File resourceFile; 11187 11188 // Example topology: 11189 // /data/app/com.example/base.apk 11190 // /data/app/com.example/split_foo.apk 11191 // /data/app/com.example/lib/arm/libfoo.so 11192 // /data/app/com.example/lib/arm64/libfoo.so 11193 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11194 11195 /** New install */ 11196 FileInstallArgs(InstallParams params) { 11197 super(params.origin, params.move, params.observer, params.installFlags, 11198 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11199 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11200 params.grantedRuntimePermissions, 11201 params.traceMethod, params.traceCookie); 11202 if (isFwdLocked()) { 11203 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11204 } 11205 } 11206 11207 /** Existing install */ 11208 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11209 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11210 null, null, null, 0); 11211 this.codeFile = (codePath != null) ? new File(codePath) : null; 11212 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11213 } 11214 11215 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11216 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11217 try { 11218 return doCopyApk(imcs, temp); 11219 } finally { 11220 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11221 } 11222 } 11223 11224 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11225 if (origin.staged) { 11226 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11227 codeFile = origin.file; 11228 resourceFile = origin.file; 11229 return PackageManager.INSTALL_SUCCEEDED; 11230 } 11231 11232 try { 11233 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11234 codeFile = tempDir; 11235 resourceFile = tempDir; 11236 } catch (IOException e) { 11237 Slog.w(TAG, "Failed to create copy file: " + e); 11238 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11239 } 11240 11241 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11242 @Override 11243 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11244 if (!FileUtils.isValidExtFilename(name)) { 11245 throw new IllegalArgumentException("Invalid filename: " + name); 11246 } 11247 try { 11248 final File file = new File(codeFile, name); 11249 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11250 O_RDWR | O_CREAT, 0644); 11251 Os.chmod(file.getAbsolutePath(), 0644); 11252 return new ParcelFileDescriptor(fd); 11253 } catch (ErrnoException e) { 11254 throw new RemoteException("Failed to open: " + e.getMessage()); 11255 } 11256 } 11257 }; 11258 11259 int ret = PackageManager.INSTALL_SUCCEEDED; 11260 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11261 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11262 Slog.e(TAG, "Failed to copy package"); 11263 return ret; 11264 } 11265 11266 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11267 NativeLibraryHelper.Handle handle = null; 11268 try { 11269 handle = NativeLibraryHelper.Handle.create(codeFile); 11270 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11271 abiOverride); 11272 } catch (IOException e) { 11273 Slog.e(TAG, "Copying native libraries failed", e); 11274 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11275 } finally { 11276 IoUtils.closeQuietly(handle); 11277 } 11278 11279 return ret; 11280 } 11281 11282 int doPreInstall(int status) { 11283 if (status != PackageManager.INSTALL_SUCCEEDED) { 11284 cleanUp(); 11285 } 11286 return status; 11287 } 11288 11289 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11290 if (status != PackageManager.INSTALL_SUCCEEDED) { 11291 cleanUp(); 11292 return false; 11293 } 11294 11295 final File targetDir = codeFile.getParentFile(); 11296 final File beforeCodeFile = codeFile; 11297 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11298 11299 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11300 try { 11301 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11302 } catch (ErrnoException e) { 11303 Slog.w(TAG, "Failed to rename", e); 11304 return false; 11305 } 11306 11307 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11308 Slog.w(TAG, "Failed to restorecon"); 11309 return false; 11310 } 11311 11312 // Reflect the rename internally 11313 codeFile = afterCodeFile; 11314 resourceFile = afterCodeFile; 11315 11316 // Reflect the rename in scanned details 11317 pkg.codePath = afterCodeFile.getAbsolutePath(); 11318 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11319 pkg.baseCodePath); 11320 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11321 pkg.splitCodePaths); 11322 11323 // Reflect the rename in app info 11324 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11325 pkg.applicationInfo.setCodePath(pkg.codePath); 11326 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11327 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11328 pkg.applicationInfo.setResourcePath(pkg.codePath); 11329 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11330 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11331 11332 return true; 11333 } 11334 11335 int doPostInstall(int status, int uid) { 11336 if (status != PackageManager.INSTALL_SUCCEEDED) { 11337 cleanUp(); 11338 } 11339 return status; 11340 } 11341 11342 @Override 11343 String getCodePath() { 11344 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11345 } 11346 11347 @Override 11348 String getResourcePath() { 11349 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11350 } 11351 11352 private boolean cleanUp() { 11353 if (codeFile == null || !codeFile.exists()) { 11354 return false; 11355 } 11356 11357 if (codeFile.isDirectory()) { 11358 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11359 } else { 11360 codeFile.delete(); 11361 } 11362 11363 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11364 resourceFile.delete(); 11365 } 11366 11367 return true; 11368 } 11369 11370 void cleanUpResourcesLI() { 11371 // Try enumerating all code paths before deleting 11372 List<String> allCodePaths = Collections.EMPTY_LIST; 11373 if (codeFile != null && codeFile.exists()) { 11374 try { 11375 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11376 allCodePaths = pkg.getAllCodePaths(); 11377 } catch (PackageParserException e) { 11378 // Ignored; we tried our best 11379 } 11380 } 11381 11382 cleanUp(); 11383 removeDexFiles(allCodePaths, instructionSets); 11384 } 11385 11386 boolean doPostDeleteLI(boolean delete) { 11387 // XXX err, shouldn't we respect the delete flag? 11388 cleanUpResourcesLI(); 11389 return true; 11390 } 11391 } 11392 11393 private boolean isAsecExternal(String cid) { 11394 final String asecPath = PackageHelper.getSdFilesystem(cid); 11395 return !asecPath.startsWith(mAsecInternalPath); 11396 } 11397 11398 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11399 PackageManagerException { 11400 if (copyRet < 0) { 11401 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11402 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11403 throw new PackageManagerException(copyRet, message); 11404 } 11405 } 11406 } 11407 11408 /** 11409 * Extract the MountService "container ID" from the full code path of an 11410 * .apk. 11411 */ 11412 static String cidFromCodePath(String fullCodePath) { 11413 int eidx = fullCodePath.lastIndexOf("/"); 11414 String subStr1 = fullCodePath.substring(0, eidx); 11415 int sidx = subStr1.lastIndexOf("/"); 11416 return subStr1.substring(sidx+1, eidx); 11417 } 11418 11419 /** 11420 * Logic to handle installation of ASEC applications, including copying and 11421 * renaming logic. 11422 */ 11423 class AsecInstallArgs extends InstallArgs { 11424 static final String RES_FILE_NAME = "pkg.apk"; 11425 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11426 11427 String cid; 11428 String packagePath; 11429 String resourcePath; 11430 11431 /** New install */ 11432 AsecInstallArgs(InstallParams params) { 11433 super(params.origin, params.move, params.observer, params.installFlags, 11434 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11435 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11436 params.grantedRuntimePermissions, 11437 params.traceMethod, params.traceCookie); 11438 } 11439 11440 /** Existing install */ 11441 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11442 boolean isExternal, boolean isForwardLocked) { 11443 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11444 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11445 instructionSets, null, null, null, 0); 11446 // Hackily pretend we're still looking at a full code path 11447 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11448 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11449 } 11450 11451 // Extract cid from fullCodePath 11452 int eidx = fullCodePath.lastIndexOf("/"); 11453 String subStr1 = fullCodePath.substring(0, eidx); 11454 int sidx = subStr1.lastIndexOf("/"); 11455 cid = subStr1.substring(sidx+1, eidx); 11456 setMountPath(subStr1); 11457 } 11458 11459 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11460 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11461 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11462 instructionSets, null, null, null, 0); 11463 this.cid = cid; 11464 setMountPath(PackageHelper.getSdDir(cid)); 11465 } 11466 11467 void createCopyFile() { 11468 cid = mInstallerService.allocateExternalStageCidLegacy(); 11469 } 11470 11471 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11472 if (origin.staged) { 11473 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11474 cid = origin.cid; 11475 setMountPath(PackageHelper.getSdDir(cid)); 11476 return PackageManager.INSTALL_SUCCEEDED; 11477 } 11478 11479 if (temp) { 11480 createCopyFile(); 11481 } else { 11482 /* 11483 * Pre-emptively destroy the container since it's destroyed if 11484 * copying fails due to it existing anyway. 11485 */ 11486 PackageHelper.destroySdDir(cid); 11487 } 11488 11489 final String newMountPath = imcs.copyPackageToContainer( 11490 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11491 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11492 11493 if (newMountPath != null) { 11494 setMountPath(newMountPath); 11495 return PackageManager.INSTALL_SUCCEEDED; 11496 } else { 11497 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11498 } 11499 } 11500 11501 @Override 11502 String getCodePath() { 11503 return packagePath; 11504 } 11505 11506 @Override 11507 String getResourcePath() { 11508 return resourcePath; 11509 } 11510 11511 int doPreInstall(int status) { 11512 if (status != PackageManager.INSTALL_SUCCEEDED) { 11513 // Destroy container 11514 PackageHelper.destroySdDir(cid); 11515 } else { 11516 boolean mounted = PackageHelper.isContainerMounted(cid); 11517 if (!mounted) { 11518 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11519 Process.SYSTEM_UID); 11520 if (newMountPath != null) { 11521 setMountPath(newMountPath); 11522 } else { 11523 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11524 } 11525 } 11526 } 11527 return status; 11528 } 11529 11530 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11531 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11532 String newMountPath = null; 11533 if (PackageHelper.isContainerMounted(cid)) { 11534 // Unmount the container 11535 if (!PackageHelper.unMountSdDir(cid)) { 11536 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11537 return false; 11538 } 11539 } 11540 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11541 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11542 " which might be stale. Will try to clean up."); 11543 // Clean up the stale container and proceed to recreate. 11544 if (!PackageHelper.destroySdDir(newCacheId)) { 11545 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11546 return false; 11547 } 11548 // Successfully cleaned up stale container. Try to rename again. 11549 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11550 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11551 + " inspite of cleaning it up."); 11552 return false; 11553 } 11554 } 11555 if (!PackageHelper.isContainerMounted(newCacheId)) { 11556 Slog.w(TAG, "Mounting container " + newCacheId); 11557 newMountPath = PackageHelper.mountSdDir(newCacheId, 11558 getEncryptKey(), Process.SYSTEM_UID); 11559 } else { 11560 newMountPath = PackageHelper.getSdDir(newCacheId); 11561 } 11562 if (newMountPath == null) { 11563 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11564 return false; 11565 } 11566 Log.i(TAG, "Succesfully renamed " + cid + 11567 " to " + newCacheId + 11568 " at new path: " + newMountPath); 11569 cid = newCacheId; 11570 11571 final File beforeCodeFile = new File(packagePath); 11572 setMountPath(newMountPath); 11573 final File afterCodeFile = new File(packagePath); 11574 11575 // Reflect the rename in scanned details 11576 pkg.codePath = afterCodeFile.getAbsolutePath(); 11577 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11578 pkg.baseCodePath); 11579 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11580 pkg.splitCodePaths); 11581 11582 // Reflect the rename in app info 11583 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11584 pkg.applicationInfo.setCodePath(pkg.codePath); 11585 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11586 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11587 pkg.applicationInfo.setResourcePath(pkg.codePath); 11588 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11589 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11590 11591 return true; 11592 } 11593 11594 private void setMountPath(String mountPath) { 11595 final File mountFile = new File(mountPath); 11596 11597 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11598 if (monolithicFile.exists()) { 11599 packagePath = monolithicFile.getAbsolutePath(); 11600 if (isFwdLocked()) { 11601 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11602 } else { 11603 resourcePath = packagePath; 11604 } 11605 } else { 11606 packagePath = mountFile.getAbsolutePath(); 11607 resourcePath = packagePath; 11608 } 11609 } 11610 11611 int doPostInstall(int status, int uid) { 11612 if (status != PackageManager.INSTALL_SUCCEEDED) { 11613 cleanUp(); 11614 } else { 11615 final int groupOwner; 11616 final String protectedFile; 11617 if (isFwdLocked()) { 11618 groupOwner = UserHandle.getSharedAppGid(uid); 11619 protectedFile = RES_FILE_NAME; 11620 } else { 11621 groupOwner = -1; 11622 protectedFile = null; 11623 } 11624 11625 if (uid < Process.FIRST_APPLICATION_UID 11626 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11627 Slog.e(TAG, "Failed to finalize " + cid); 11628 PackageHelper.destroySdDir(cid); 11629 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11630 } 11631 11632 boolean mounted = PackageHelper.isContainerMounted(cid); 11633 if (!mounted) { 11634 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11635 } 11636 } 11637 return status; 11638 } 11639 11640 private void cleanUp() { 11641 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11642 11643 // Destroy secure container 11644 PackageHelper.destroySdDir(cid); 11645 } 11646 11647 private List<String> getAllCodePaths() { 11648 final File codeFile = new File(getCodePath()); 11649 if (codeFile != null && codeFile.exists()) { 11650 try { 11651 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11652 return pkg.getAllCodePaths(); 11653 } catch (PackageParserException e) { 11654 // Ignored; we tried our best 11655 } 11656 } 11657 return Collections.EMPTY_LIST; 11658 } 11659 11660 void cleanUpResourcesLI() { 11661 // Enumerate all code paths before deleting 11662 cleanUpResourcesLI(getAllCodePaths()); 11663 } 11664 11665 private void cleanUpResourcesLI(List<String> allCodePaths) { 11666 cleanUp(); 11667 removeDexFiles(allCodePaths, instructionSets); 11668 } 11669 11670 String getPackageName() { 11671 return getAsecPackageName(cid); 11672 } 11673 11674 boolean doPostDeleteLI(boolean delete) { 11675 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11676 final List<String> allCodePaths = getAllCodePaths(); 11677 boolean mounted = PackageHelper.isContainerMounted(cid); 11678 if (mounted) { 11679 // Unmount first 11680 if (PackageHelper.unMountSdDir(cid)) { 11681 mounted = false; 11682 } 11683 } 11684 if (!mounted && delete) { 11685 cleanUpResourcesLI(allCodePaths); 11686 } 11687 return !mounted; 11688 } 11689 11690 @Override 11691 int doPreCopy() { 11692 if (isFwdLocked()) { 11693 if (!PackageHelper.fixSdPermissions(cid, 11694 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11695 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11696 } 11697 } 11698 11699 return PackageManager.INSTALL_SUCCEEDED; 11700 } 11701 11702 @Override 11703 int doPostCopy(int uid) { 11704 if (isFwdLocked()) { 11705 if (uid < Process.FIRST_APPLICATION_UID 11706 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11707 RES_FILE_NAME)) { 11708 Slog.e(TAG, "Failed to finalize " + cid); 11709 PackageHelper.destroySdDir(cid); 11710 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11711 } 11712 } 11713 11714 return PackageManager.INSTALL_SUCCEEDED; 11715 } 11716 } 11717 11718 /** 11719 * Logic to handle movement of existing installed applications. 11720 */ 11721 class MoveInstallArgs extends InstallArgs { 11722 private File codeFile; 11723 private File resourceFile; 11724 11725 /** New install */ 11726 MoveInstallArgs(InstallParams params) { 11727 super(params.origin, params.move, params.observer, params.installFlags, 11728 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11729 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11730 params.grantedRuntimePermissions, 11731 params.traceMethod, params.traceCookie); 11732 } 11733 11734 int copyApk(IMediaContainerService imcs, boolean temp) { 11735 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11736 + move.fromUuid + " to " + move.toUuid); 11737 synchronized (mInstaller) { 11738 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11739 move.dataAppName, move.appId, move.seinfo) != 0) { 11740 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11741 } 11742 } 11743 11744 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11745 resourceFile = codeFile; 11746 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11747 11748 return PackageManager.INSTALL_SUCCEEDED; 11749 } 11750 11751 int doPreInstall(int status) { 11752 if (status != PackageManager.INSTALL_SUCCEEDED) { 11753 cleanUp(move.toUuid); 11754 } 11755 return status; 11756 } 11757 11758 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11759 if (status != PackageManager.INSTALL_SUCCEEDED) { 11760 cleanUp(move.toUuid); 11761 return false; 11762 } 11763 11764 // Reflect the move in app info 11765 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11766 pkg.applicationInfo.setCodePath(pkg.codePath); 11767 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11768 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11769 pkg.applicationInfo.setResourcePath(pkg.codePath); 11770 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11771 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11772 11773 return true; 11774 } 11775 11776 int doPostInstall(int status, int uid) { 11777 if (status == PackageManager.INSTALL_SUCCEEDED) { 11778 cleanUp(move.fromUuid); 11779 } else { 11780 cleanUp(move.toUuid); 11781 } 11782 return status; 11783 } 11784 11785 @Override 11786 String getCodePath() { 11787 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11788 } 11789 11790 @Override 11791 String getResourcePath() { 11792 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11793 } 11794 11795 private boolean cleanUp(String volumeUuid) { 11796 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11797 move.dataAppName); 11798 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11799 synchronized (mInstallLock) { 11800 // Clean up both app data and code 11801 removeDataDirsLI(volumeUuid, move.packageName); 11802 if (codeFile.isDirectory()) { 11803 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11804 } else { 11805 codeFile.delete(); 11806 } 11807 } 11808 return true; 11809 } 11810 11811 void cleanUpResourcesLI() { 11812 throw new UnsupportedOperationException(); 11813 } 11814 11815 boolean doPostDeleteLI(boolean delete) { 11816 throw new UnsupportedOperationException(); 11817 } 11818 } 11819 11820 static String getAsecPackageName(String packageCid) { 11821 int idx = packageCid.lastIndexOf("-"); 11822 if (idx == -1) { 11823 return packageCid; 11824 } 11825 return packageCid.substring(0, idx); 11826 } 11827 11828 // Utility method used to create code paths based on package name and available index. 11829 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11830 String idxStr = ""; 11831 int idx = 1; 11832 // Fall back to default value of idx=1 if prefix is not 11833 // part of oldCodePath 11834 if (oldCodePath != null) { 11835 String subStr = oldCodePath; 11836 // Drop the suffix right away 11837 if (suffix != null && subStr.endsWith(suffix)) { 11838 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11839 } 11840 // If oldCodePath already contains prefix find out the 11841 // ending index to either increment or decrement. 11842 int sidx = subStr.lastIndexOf(prefix); 11843 if (sidx != -1) { 11844 subStr = subStr.substring(sidx + prefix.length()); 11845 if (subStr != null) { 11846 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11847 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11848 } 11849 try { 11850 idx = Integer.parseInt(subStr); 11851 if (idx <= 1) { 11852 idx++; 11853 } else { 11854 idx--; 11855 } 11856 } catch(NumberFormatException e) { 11857 } 11858 } 11859 } 11860 } 11861 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11862 return prefix + idxStr; 11863 } 11864 11865 private File getNextCodePath(File targetDir, String packageName) { 11866 int suffix = 1; 11867 File result; 11868 do { 11869 result = new File(targetDir, packageName + "-" + suffix); 11870 suffix++; 11871 } while (result.exists()); 11872 return result; 11873 } 11874 11875 // Utility method that returns the relative package path with respect 11876 // to the installation directory. Like say for /data/data/com.test-1.apk 11877 // string com.test-1 is returned. 11878 static String deriveCodePathName(String codePath) { 11879 if (codePath == null) { 11880 return null; 11881 } 11882 final File codeFile = new File(codePath); 11883 final String name = codeFile.getName(); 11884 if (codeFile.isDirectory()) { 11885 return name; 11886 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11887 final int lastDot = name.lastIndexOf('.'); 11888 return name.substring(0, lastDot); 11889 } else { 11890 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11891 return null; 11892 } 11893 } 11894 11895 class PackageInstalledInfo { 11896 String name; 11897 int uid; 11898 // The set of users that originally had this package installed. 11899 int[] origUsers; 11900 // The set of users that now have this package installed. 11901 int[] newUsers; 11902 PackageParser.Package pkg; 11903 int returnCode; 11904 String returnMsg; 11905 PackageRemovedInfo removedInfo; 11906 11907 public void setError(int code, String msg) { 11908 returnCode = code; 11909 returnMsg = msg; 11910 Slog.w(TAG, msg); 11911 } 11912 11913 public void setError(String msg, PackageParserException e) { 11914 returnCode = e.error; 11915 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11916 Slog.w(TAG, msg, e); 11917 } 11918 11919 public void setError(String msg, PackageManagerException e) { 11920 returnCode = e.error; 11921 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11922 Slog.w(TAG, msg, e); 11923 } 11924 11925 // In some error cases we want to convey more info back to the observer 11926 String origPackage; 11927 String origPermission; 11928 } 11929 11930 /* 11931 * Install a non-existing package. 11932 */ 11933 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11934 UserHandle user, String installerPackageName, String volumeUuid, 11935 PackageInstalledInfo res) { 11936 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11937 11938 // Remember this for later, in case we need to rollback this install 11939 String pkgName = pkg.packageName; 11940 11941 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11942 // TODO: b/23350563 11943 final boolean dataDirExists = Environment 11944 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11945 11946 synchronized(mPackages) { 11947 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11948 // A package with the same name is already installed, though 11949 // it has been renamed to an older name. The package we 11950 // are trying to install should be installed as an update to 11951 // the existing one, but that has not been requested, so bail. 11952 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11953 + " without first uninstalling package running as " 11954 + mSettings.mRenamedPackages.get(pkgName)); 11955 return; 11956 } 11957 if (mPackages.containsKey(pkgName)) { 11958 // Don't allow installation over an existing package with the same name. 11959 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11960 + " without first uninstalling."); 11961 return; 11962 } 11963 } 11964 11965 try { 11966 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11967 System.currentTimeMillis(), user); 11968 11969 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11970 // delete the partially installed application. the data directory will have to be 11971 // restored if it was already existing 11972 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11973 // remove package from internal structures. Note that we want deletePackageX to 11974 // delete the package data and cache directories that it created in 11975 // scanPackageLocked, unless those directories existed before we even tried to 11976 // install. 11977 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11978 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11979 res.removedInfo, true); 11980 } 11981 11982 } catch (PackageManagerException e) { 11983 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11984 } 11985 11986 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11987 } 11988 11989 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11990 // Can't rotate keys during boot or if sharedUser. 11991 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11992 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11993 return false; 11994 } 11995 // app is using upgradeKeySets; make sure all are valid 11996 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11997 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11998 for (int i = 0; i < upgradeKeySets.length; i++) { 11999 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12000 Slog.wtf(TAG, "Package " 12001 + (oldPs.name != null ? oldPs.name : "<null>") 12002 + " contains upgrade-key-set reference to unknown key-set: " 12003 + upgradeKeySets[i] 12004 + " reverting to signatures check."); 12005 return false; 12006 } 12007 } 12008 return true; 12009 } 12010 12011 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12012 // Upgrade keysets are being used. Determine if new package has a superset of the 12013 // required keys. 12014 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12015 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12016 for (int i = 0; i < upgradeKeySets.length; i++) { 12017 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12018 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12019 return true; 12020 } 12021 } 12022 return false; 12023 } 12024 12025 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12026 UserHandle user, String installerPackageName, String volumeUuid, 12027 PackageInstalledInfo res) { 12028 final PackageParser.Package oldPackage; 12029 final String pkgName = pkg.packageName; 12030 final int[] allUsers; 12031 final boolean[] perUserInstalled; 12032 12033 // First find the old package info and check signatures 12034 synchronized(mPackages) { 12035 oldPackage = mPackages.get(pkgName); 12036 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12037 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12038 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12039 if(!checkUpgradeKeySetLP(ps, pkg)) { 12040 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12041 "New package not signed by keys specified by upgrade-keysets: " 12042 + pkgName); 12043 return; 12044 } 12045 } else { 12046 // default to original signature matching 12047 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12048 != PackageManager.SIGNATURE_MATCH) { 12049 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12050 "New package has a different signature: " + pkgName); 12051 return; 12052 } 12053 } 12054 12055 // In case of rollback, remember per-user/profile install state 12056 allUsers = sUserManager.getUserIds(); 12057 perUserInstalled = new boolean[allUsers.length]; 12058 for (int i = 0; i < allUsers.length; i++) { 12059 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12060 } 12061 } 12062 12063 boolean sysPkg = (isSystemApp(oldPackage)); 12064 if (sysPkg) { 12065 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12066 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12067 } else { 12068 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12069 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12070 } 12071 } 12072 12073 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12074 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12075 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12076 String volumeUuid, PackageInstalledInfo res) { 12077 String pkgName = deletedPackage.packageName; 12078 boolean deletedPkg = true; 12079 boolean updatedSettings = false; 12080 12081 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12082 + deletedPackage); 12083 long origUpdateTime; 12084 if (pkg.mExtras != null) { 12085 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12086 } else { 12087 origUpdateTime = 0; 12088 } 12089 12090 // First delete the existing package while retaining the data directory 12091 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12092 res.removedInfo, true)) { 12093 // If the existing package wasn't successfully deleted 12094 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12095 deletedPkg = false; 12096 } else { 12097 // Successfully deleted the old package; proceed with replace. 12098 12099 // If deleted package lived in a container, give users a chance to 12100 // relinquish resources before killing. 12101 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12102 if (DEBUG_INSTALL) { 12103 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12104 } 12105 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12106 final ArrayList<String> pkgList = new ArrayList<String>(1); 12107 pkgList.add(deletedPackage.applicationInfo.packageName); 12108 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12109 } 12110 12111 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12112 try { 12113 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12114 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12115 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12116 perUserInstalled, res, user); 12117 updatedSettings = true; 12118 } catch (PackageManagerException e) { 12119 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12120 } 12121 } 12122 12123 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12124 // remove package from internal structures. Note that we want deletePackageX to 12125 // delete the package data and cache directories that it created in 12126 // scanPackageLocked, unless those directories existed before we even tried to 12127 // install. 12128 if(updatedSettings) { 12129 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12130 deletePackageLI( 12131 pkgName, null, true, allUsers, perUserInstalled, 12132 PackageManager.DELETE_KEEP_DATA, 12133 res.removedInfo, true); 12134 } 12135 // Since we failed to install the new package we need to restore the old 12136 // package that we deleted. 12137 if (deletedPkg) { 12138 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12139 File restoreFile = new File(deletedPackage.codePath); 12140 // Parse old package 12141 boolean oldExternal = isExternal(deletedPackage); 12142 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12143 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12144 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12145 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12146 try { 12147 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 12148 } catch (PackageManagerException e) { 12149 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12150 + e.getMessage()); 12151 return; 12152 } 12153 // Restore of old package succeeded. Update permissions. 12154 // writer 12155 synchronized (mPackages) { 12156 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12157 UPDATE_PERMISSIONS_ALL); 12158 // can downgrade to reader 12159 mSettings.writeLPr(); 12160 } 12161 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12162 } 12163 } 12164 } 12165 12166 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12167 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12168 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12169 String volumeUuid, PackageInstalledInfo res) { 12170 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12171 + ", old=" + deletedPackage); 12172 boolean disabledSystem = false; 12173 boolean updatedSettings = false; 12174 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12175 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12176 != 0) { 12177 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12178 } 12179 String packageName = deletedPackage.packageName; 12180 if (packageName == null) { 12181 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12182 "Attempt to delete null packageName."); 12183 return; 12184 } 12185 PackageParser.Package oldPkg; 12186 PackageSetting oldPkgSetting; 12187 // reader 12188 synchronized (mPackages) { 12189 oldPkg = mPackages.get(packageName); 12190 oldPkgSetting = mSettings.mPackages.get(packageName); 12191 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12192 (oldPkgSetting == null)) { 12193 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12194 "Couldn't find package:" + packageName + " information"); 12195 return; 12196 } 12197 } 12198 12199 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12200 12201 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12202 res.removedInfo.removedPackage = packageName; 12203 // Remove existing system package 12204 removePackageLI(oldPkgSetting, true); 12205 // writer 12206 synchronized (mPackages) { 12207 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12208 if (!disabledSystem && deletedPackage != null) { 12209 // We didn't need to disable the .apk as a current system package, 12210 // which means we are replacing another update that is already 12211 // installed. We need to make sure to delete the older one's .apk. 12212 res.removedInfo.args = createInstallArgsForExisting(0, 12213 deletedPackage.applicationInfo.getCodePath(), 12214 deletedPackage.applicationInfo.getResourcePath(), 12215 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12216 } else { 12217 res.removedInfo.args = null; 12218 } 12219 } 12220 12221 // Successfully disabled the old package. Now proceed with re-installation 12222 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12223 12224 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12225 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12226 12227 PackageParser.Package newPackage = null; 12228 try { 12229 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12230 if (newPackage.mExtras != null) { 12231 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12232 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12233 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12234 12235 // is the update attempting to change shared user? that isn't going to work... 12236 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12237 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12238 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12239 + " to " + newPkgSetting.sharedUser); 12240 updatedSettings = true; 12241 } 12242 } 12243 12244 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12245 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12246 perUserInstalled, res, user); 12247 updatedSettings = true; 12248 } 12249 12250 } catch (PackageManagerException e) { 12251 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12252 } 12253 12254 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12255 // Re installation failed. Restore old information 12256 // Remove new pkg information 12257 if (newPackage != null) { 12258 removeInstalledPackageLI(newPackage, true); 12259 } 12260 // Add back the old system package 12261 try { 12262 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12263 } catch (PackageManagerException e) { 12264 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12265 } 12266 // Restore the old system information in Settings 12267 synchronized (mPackages) { 12268 if (disabledSystem) { 12269 mSettings.enableSystemPackageLPw(packageName); 12270 } 12271 if (updatedSettings) { 12272 mSettings.setInstallerPackageName(packageName, 12273 oldPkgSetting.installerPackageName); 12274 } 12275 mSettings.writeLPr(); 12276 } 12277 } 12278 } 12279 12280 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12281 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12282 UserHandle user) { 12283 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12284 12285 String pkgName = newPackage.packageName; 12286 synchronized (mPackages) { 12287 //write settings. the installStatus will be incomplete at this stage. 12288 //note that the new package setting would have already been 12289 //added to mPackages. It hasn't been persisted yet. 12290 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12292 mSettings.writeLPr(); 12293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12294 } 12295 12296 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12297 synchronized (mPackages) { 12298 updatePermissionsLPw(newPackage.packageName, newPackage, 12299 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12300 ? UPDATE_PERMISSIONS_ALL : 0)); 12301 // For system-bundled packages, we assume that installing an upgraded version 12302 // of the package implies that the user actually wants to run that new code, 12303 // so we enable the package. 12304 PackageSetting ps = mSettings.mPackages.get(pkgName); 12305 if (ps != null) { 12306 if (isSystemApp(newPackage)) { 12307 // NB: implicit assumption that system package upgrades apply to all users 12308 if (DEBUG_INSTALL) { 12309 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12310 } 12311 if (res.origUsers != null) { 12312 for (int userHandle : res.origUsers) { 12313 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12314 userHandle, installerPackageName); 12315 } 12316 } 12317 // Also convey the prior install/uninstall state 12318 if (allUsers != null && perUserInstalled != null) { 12319 for (int i = 0; i < allUsers.length; i++) { 12320 if (DEBUG_INSTALL) { 12321 Slog.d(TAG, " user " + allUsers[i] 12322 + " => " + perUserInstalled[i]); 12323 } 12324 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12325 } 12326 // these install state changes will be persisted in the 12327 // upcoming call to mSettings.writeLPr(). 12328 } 12329 } 12330 // It's implied that when a user requests installation, they want the app to be 12331 // installed and enabled. 12332 int userId = user.getIdentifier(); 12333 if (userId != UserHandle.USER_ALL) { 12334 ps.setInstalled(true, userId); 12335 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12336 } 12337 } 12338 res.name = pkgName; 12339 res.uid = newPackage.applicationInfo.uid; 12340 res.pkg = newPackage; 12341 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12342 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12343 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12344 //to update install status 12345 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12346 mSettings.writeLPr(); 12347 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12348 } 12349 12350 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12351 } 12352 12353 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12354 try { 12355 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12356 installPackageLI(args, res); 12357 } finally { 12358 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12359 } 12360 } 12361 12362 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12363 final int installFlags = args.installFlags; 12364 final String installerPackageName = args.installerPackageName; 12365 final String volumeUuid = args.volumeUuid; 12366 final File tmpPackageFile = new File(args.getCodePath()); 12367 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12368 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12369 || (args.volumeUuid != null)); 12370 boolean replace = false; 12371 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12372 if (args.move != null) { 12373 // moving a complete application; perfom an initial scan on the new install location 12374 scanFlags |= SCAN_INITIAL; 12375 } 12376 // Result object to be returned 12377 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12378 12379 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12380 12381 // Retrieve PackageSettings and parse package 12382 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12383 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12384 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12385 PackageParser pp = new PackageParser(); 12386 pp.setSeparateProcesses(mSeparateProcesses); 12387 pp.setDisplayMetrics(mMetrics); 12388 12389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12390 final PackageParser.Package pkg; 12391 try { 12392 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12393 } catch (PackageParserException e) { 12394 res.setError("Failed parse during installPackageLI", e); 12395 return; 12396 } finally { 12397 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12398 } 12399 12400 // Mark that we have an install time CPU ABI override. 12401 pkg.cpuAbiOverride = args.abiOverride; 12402 12403 String pkgName = res.name = pkg.packageName; 12404 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12405 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12406 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12407 return; 12408 } 12409 } 12410 12411 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12412 try { 12413 pp.collectCertificates(pkg, parseFlags); 12414 pp.collectManifestDigest(pkg); 12415 } catch (PackageParserException e) { 12416 res.setError("Failed collect during installPackageLI", e); 12417 return; 12418 } finally { 12419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12420 } 12421 12422 /* If the installer passed in a manifest digest, compare it now. */ 12423 if (args.manifestDigest != null) { 12424 if (DEBUG_INSTALL) { 12425 final String parsedManifest = pkg.manifestDigest == null ? "null" 12426 : pkg.manifestDigest.toString(); 12427 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12428 + parsedManifest); 12429 } 12430 12431 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12432 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12433 return; 12434 } 12435 } else if (DEBUG_INSTALL) { 12436 final String parsedManifest = pkg.manifestDigest == null 12437 ? "null" : pkg.manifestDigest.toString(); 12438 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12439 } 12440 12441 // Get rid of all references to package scan path via parser. 12442 pp = null; 12443 String oldCodePath = null; 12444 boolean systemApp = false; 12445 synchronized (mPackages) { 12446 // Check if installing already existing package 12447 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12448 String oldName = mSettings.mRenamedPackages.get(pkgName); 12449 if (pkg.mOriginalPackages != null 12450 && pkg.mOriginalPackages.contains(oldName) 12451 && mPackages.containsKey(oldName)) { 12452 // This package is derived from an original package, 12453 // and this device has been updating from that original 12454 // name. We must continue using the original name, so 12455 // rename the new package here. 12456 pkg.setPackageName(oldName); 12457 pkgName = pkg.packageName; 12458 replace = true; 12459 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12460 + oldName + " pkgName=" + pkgName); 12461 } else if (mPackages.containsKey(pkgName)) { 12462 // This package, under its official name, already exists 12463 // on the device; we should replace it. 12464 replace = true; 12465 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12466 } 12467 12468 // Prevent apps opting out from runtime permissions 12469 if (replace) { 12470 PackageParser.Package oldPackage = mPackages.get(pkgName); 12471 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12472 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12473 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12474 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12475 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12476 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12477 + " doesn't support runtime permissions but the old" 12478 + " target SDK " + oldTargetSdk + " does."); 12479 return; 12480 } 12481 } 12482 } 12483 12484 PackageSetting ps = mSettings.mPackages.get(pkgName); 12485 if (ps != null) { 12486 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12487 12488 // Quick sanity check that we're signed correctly if updating; 12489 // we'll check this again later when scanning, but we want to 12490 // bail early here before tripping over redefined permissions. 12491 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12492 if (!checkUpgradeKeySetLP(ps, pkg)) { 12493 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12494 + pkg.packageName + " upgrade keys do not match the " 12495 + "previously installed version"); 12496 return; 12497 } 12498 } else { 12499 try { 12500 verifySignaturesLP(ps, pkg); 12501 } catch (PackageManagerException e) { 12502 res.setError(e.error, e.getMessage()); 12503 return; 12504 } 12505 } 12506 12507 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12508 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12509 systemApp = (ps.pkg.applicationInfo.flags & 12510 ApplicationInfo.FLAG_SYSTEM) != 0; 12511 } 12512 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12513 } 12514 12515 // Check whether the newly-scanned package wants to define an already-defined perm 12516 int N = pkg.permissions.size(); 12517 for (int i = N-1; i >= 0; i--) { 12518 PackageParser.Permission perm = pkg.permissions.get(i); 12519 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12520 if (bp != null) { 12521 // If the defining package is signed with our cert, it's okay. This 12522 // also includes the "updating the same package" case, of course. 12523 // "updating same package" could also involve key-rotation. 12524 final boolean sigsOk; 12525 if (bp.sourcePackage.equals(pkg.packageName) 12526 && (bp.packageSetting instanceof PackageSetting) 12527 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12528 scanFlags))) { 12529 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12530 } else { 12531 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12532 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12533 } 12534 if (!sigsOk) { 12535 // If the owning package is the system itself, we log but allow 12536 // install to proceed; we fail the install on all other permission 12537 // redefinitions. 12538 if (!bp.sourcePackage.equals("android")) { 12539 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12540 + pkg.packageName + " attempting to redeclare permission " 12541 + perm.info.name + " already owned by " + bp.sourcePackage); 12542 res.origPermission = perm.info.name; 12543 res.origPackage = bp.sourcePackage; 12544 return; 12545 } else { 12546 Slog.w(TAG, "Package " + pkg.packageName 12547 + " attempting to redeclare system permission " 12548 + perm.info.name + "; ignoring new declaration"); 12549 pkg.permissions.remove(i); 12550 } 12551 } 12552 } 12553 } 12554 12555 } 12556 12557 if (systemApp && onExternal) { 12558 // Disable updates to system apps on sdcard 12559 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12560 "Cannot install updates to system apps on sdcard"); 12561 return; 12562 } 12563 12564 if (args.move != null) { 12565 // We did an in-place move, so dex is ready to roll 12566 scanFlags |= SCAN_NO_DEX; 12567 scanFlags |= SCAN_MOVE; 12568 12569 synchronized (mPackages) { 12570 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12571 if (ps == null) { 12572 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12573 "Missing settings for moved package " + pkgName); 12574 } 12575 12576 // We moved the entire application as-is, so bring over the 12577 // previously derived ABI information. 12578 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12579 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12580 } 12581 12582 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12583 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12584 scanFlags |= SCAN_NO_DEX; 12585 12586 try { 12587 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12588 true /* extract libs */); 12589 } catch (PackageManagerException pme) { 12590 Slog.e(TAG, "Error deriving application ABI", pme); 12591 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12592 return; 12593 } 12594 12595 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12596 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12597 12598 int result = mPackageDexOptimizer 12599 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12600 false /* defer */, false /* inclDependencies */); 12601 12602 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12603 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12604 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12605 return; 12606 } 12607 } 12608 12609 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12610 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12611 return; 12612 } 12613 12614 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12615 12616 if (replace) { 12617 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12618 installerPackageName, volumeUuid, res); 12619 } else { 12620 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12621 args.user, installerPackageName, volumeUuid, res); 12622 } 12623 synchronized (mPackages) { 12624 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12625 if (ps != null) { 12626 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12627 } 12628 } 12629 } 12630 12631 private void startIntentFilterVerifications(int userId, boolean replacing, 12632 PackageParser.Package pkg) { 12633 if (mIntentFilterVerifierComponent == null) { 12634 Slog.w(TAG, "No IntentFilter verification will not be done as " 12635 + "there is no IntentFilterVerifier available!"); 12636 return; 12637 } 12638 12639 final int verifierUid = getPackageUid( 12640 mIntentFilterVerifierComponent.getPackageName(), 12641 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12642 12643 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12644 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12645 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12646 mHandler.sendMessage(msg); 12647 } 12648 12649 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12650 PackageParser.Package pkg) { 12651 int size = pkg.activities.size(); 12652 if (size == 0) { 12653 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12654 "No activity, so no need to verify any IntentFilter!"); 12655 return; 12656 } 12657 12658 final boolean hasDomainURLs = hasDomainURLs(pkg); 12659 if (!hasDomainURLs) { 12660 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12661 "No domain URLs, so no need to verify any IntentFilter!"); 12662 return; 12663 } 12664 12665 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12666 + " if any IntentFilter from the " + size 12667 + " Activities needs verification ..."); 12668 12669 int count = 0; 12670 final String packageName = pkg.packageName; 12671 12672 synchronized (mPackages) { 12673 // If this is a new install and we see that we've already run verification for this 12674 // package, we have nothing to do: it means the state was restored from backup. 12675 if (!replacing) { 12676 IntentFilterVerificationInfo ivi = 12677 mSettings.getIntentFilterVerificationLPr(packageName); 12678 if (ivi != null) { 12679 if (DEBUG_DOMAIN_VERIFICATION) { 12680 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12681 + ivi.getStatusString()); 12682 } 12683 return; 12684 } 12685 } 12686 12687 // If any filters need to be verified, then all need to be. 12688 boolean needToVerify = false; 12689 for (PackageParser.Activity a : pkg.activities) { 12690 for (ActivityIntentInfo filter : a.intents) { 12691 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12692 if (DEBUG_DOMAIN_VERIFICATION) { 12693 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12694 } 12695 needToVerify = true; 12696 break; 12697 } 12698 } 12699 } 12700 12701 if (needToVerify) { 12702 final int verificationId = mIntentFilterVerificationToken++; 12703 for (PackageParser.Activity a : pkg.activities) { 12704 for (ActivityIntentInfo filter : a.intents) { 12705 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12706 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12707 "Verification needed for IntentFilter:" + filter.toString()); 12708 mIntentFilterVerifier.addOneIntentFilterVerification( 12709 verifierUid, userId, verificationId, filter, packageName); 12710 count++; 12711 } 12712 } 12713 } 12714 } 12715 } 12716 12717 if (count > 0) { 12718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12719 + " IntentFilter verification" + (count > 1 ? "s" : "") 12720 + " for userId:" + userId); 12721 mIntentFilterVerifier.startVerifications(userId); 12722 } else { 12723 if (DEBUG_DOMAIN_VERIFICATION) { 12724 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12725 } 12726 } 12727 } 12728 12729 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12730 final ComponentName cn = filter.activity.getComponentName(); 12731 final String packageName = cn.getPackageName(); 12732 12733 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12734 packageName); 12735 if (ivi == null) { 12736 return true; 12737 } 12738 int status = ivi.getStatus(); 12739 switch (status) { 12740 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12741 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12742 return true; 12743 12744 default: 12745 // Nothing to do 12746 return false; 12747 } 12748 } 12749 12750 private static boolean isMultiArch(PackageSetting ps) { 12751 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12752 } 12753 12754 private static boolean isMultiArch(ApplicationInfo info) { 12755 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12756 } 12757 12758 private static boolean isExternal(PackageParser.Package pkg) { 12759 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12760 } 12761 12762 private static boolean isExternal(PackageSetting ps) { 12763 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12764 } 12765 12766 private static boolean isExternal(ApplicationInfo info) { 12767 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12768 } 12769 12770 private static boolean isSystemApp(PackageParser.Package pkg) { 12771 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12772 } 12773 12774 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12775 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12776 } 12777 12778 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12779 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12780 } 12781 12782 private static boolean isSystemApp(PackageSetting ps) { 12783 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12784 } 12785 12786 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12787 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12788 } 12789 12790 private int packageFlagsToInstallFlags(PackageSetting ps) { 12791 int installFlags = 0; 12792 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12793 // This existing package was an external ASEC install when we have 12794 // the external flag without a UUID 12795 installFlags |= PackageManager.INSTALL_EXTERNAL; 12796 } 12797 if (ps.isForwardLocked()) { 12798 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12799 } 12800 return installFlags; 12801 } 12802 12803 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12804 if (isExternal(pkg)) { 12805 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12806 return mSettings.getExternalVersion(); 12807 } else { 12808 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12809 } 12810 } else { 12811 return mSettings.getInternalVersion(); 12812 } 12813 } 12814 12815 private void deleteTempPackageFiles() { 12816 final FilenameFilter filter = new FilenameFilter() { 12817 public boolean accept(File dir, String name) { 12818 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12819 } 12820 }; 12821 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12822 file.delete(); 12823 } 12824 } 12825 12826 @Override 12827 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12828 int flags) { 12829 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12830 flags); 12831 } 12832 12833 @Override 12834 public void deletePackage(final String packageName, 12835 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12836 mContext.enforceCallingOrSelfPermission( 12837 android.Manifest.permission.DELETE_PACKAGES, null); 12838 Preconditions.checkNotNull(packageName); 12839 Preconditions.checkNotNull(observer); 12840 final int uid = Binder.getCallingUid(); 12841 if (UserHandle.getUserId(uid) != userId) { 12842 mContext.enforceCallingPermission( 12843 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12844 "deletePackage for user " + userId); 12845 } 12846 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12847 try { 12848 observer.onPackageDeleted(packageName, 12849 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12850 } catch (RemoteException re) { 12851 } 12852 return; 12853 } 12854 12855 boolean uninstallBlocked = false; 12856 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12857 int[] users = sUserManager.getUserIds(); 12858 for (int i = 0; i < users.length; ++i) { 12859 if (getBlockUninstallForUser(packageName, users[i])) { 12860 uninstallBlocked = true; 12861 break; 12862 } 12863 } 12864 } else { 12865 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12866 } 12867 if (uninstallBlocked) { 12868 try { 12869 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12870 null); 12871 } catch (RemoteException re) { 12872 } 12873 return; 12874 } 12875 12876 if (DEBUG_REMOVE) { 12877 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12878 } 12879 // Queue up an async operation since the package deletion may take a little while. 12880 mHandler.post(new Runnable() { 12881 public void run() { 12882 mHandler.removeCallbacks(this); 12883 final int returnCode = deletePackageX(packageName, userId, flags); 12884 if (observer != null) { 12885 try { 12886 observer.onPackageDeleted(packageName, returnCode, null); 12887 } catch (RemoteException e) { 12888 Log.i(TAG, "Observer no longer exists."); 12889 } //end catch 12890 } //end if 12891 } //end run 12892 }); 12893 } 12894 12895 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12896 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12897 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12898 try { 12899 if (dpm != null) { 12900 if (dpm.isDeviceOwner(packageName)) { 12901 return true; 12902 } 12903 int[] users; 12904 if (userId == UserHandle.USER_ALL) { 12905 users = sUserManager.getUserIds(); 12906 } else { 12907 users = new int[]{userId}; 12908 } 12909 for (int i = 0; i < users.length; ++i) { 12910 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12911 return true; 12912 } 12913 } 12914 } 12915 } catch (RemoteException e) { 12916 } 12917 return false; 12918 } 12919 12920 /** 12921 * This method is an internal method that could be get invoked either 12922 * to delete an installed package or to clean up a failed installation. 12923 * After deleting an installed package, a broadcast is sent to notify any 12924 * listeners that the package has been installed. For cleaning up a failed 12925 * installation, the broadcast is not necessary since the package's 12926 * installation wouldn't have sent the initial broadcast either 12927 * The key steps in deleting a package are 12928 * deleting the package information in internal structures like mPackages, 12929 * deleting the packages base directories through installd 12930 * updating mSettings to reflect current status 12931 * persisting settings for later use 12932 * sending a broadcast if necessary 12933 */ 12934 private int deletePackageX(String packageName, int userId, int flags) { 12935 final PackageRemovedInfo info = new PackageRemovedInfo(); 12936 final boolean res; 12937 12938 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12939 ? UserHandle.ALL : new UserHandle(userId); 12940 12941 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12942 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12943 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12944 } 12945 12946 boolean removedForAllUsers = false; 12947 boolean systemUpdate = false; 12948 12949 // for the uninstall-updates case and restricted profiles, remember the per- 12950 // userhandle installed state 12951 int[] allUsers; 12952 boolean[] perUserInstalled; 12953 synchronized (mPackages) { 12954 PackageSetting ps = mSettings.mPackages.get(packageName); 12955 allUsers = sUserManager.getUserIds(); 12956 perUserInstalled = new boolean[allUsers.length]; 12957 for (int i = 0; i < allUsers.length; i++) { 12958 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12959 } 12960 } 12961 12962 synchronized (mInstallLock) { 12963 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12964 res = deletePackageLI(packageName, removeForUser, 12965 true, allUsers, perUserInstalled, 12966 flags | REMOVE_CHATTY, info, true); 12967 systemUpdate = info.isRemovedPackageSystemUpdate; 12968 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12969 removedForAllUsers = true; 12970 } 12971 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12972 + " removedForAllUsers=" + removedForAllUsers); 12973 } 12974 12975 if (res) { 12976 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12977 12978 // If the removed package was a system update, the old system package 12979 // was re-enabled; we need to broadcast this information 12980 if (systemUpdate) { 12981 Bundle extras = new Bundle(1); 12982 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12983 ? info.removedAppId : info.uid); 12984 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12985 12986 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12987 extras, null, null, null); 12988 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12989 extras, null, null, null); 12990 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12991 null, packageName, null, null); 12992 } 12993 } 12994 // Force a gc here. 12995 Runtime.getRuntime().gc(); 12996 // Delete the resources here after sending the broadcast to let 12997 // other processes clean up before deleting resources. 12998 if (info.args != null) { 12999 synchronized (mInstallLock) { 13000 info.args.doPostDeleteLI(true); 13001 } 13002 } 13003 13004 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13005 } 13006 13007 class PackageRemovedInfo { 13008 String removedPackage; 13009 int uid = -1; 13010 int removedAppId = -1; 13011 int[] removedUsers = null; 13012 boolean isRemovedPackageSystemUpdate = false; 13013 // Clean up resources deleted packages. 13014 InstallArgs args = null; 13015 13016 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13017 Bundle extras = new Bundle(1); 13018 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13019 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13020 if (replacing) { 13021 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13022 } 13023 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13024 if (removedPackage != null) { 13025 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13026 extras, null, null, removedUsers); 13027 if (fullRemove && !replacing) { 13028 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13029 extras, null, null, removedUsers); 13030 } 13031 } 13032 if (removedAppId >= 0) { 13033 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 13034 removedUsers); 13035 } 13036 } 13037 } 13038 13039 /* 13040 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13041 * flag is not set, the data directory is removed as well. 13042 * make sure this flag is set for partially installed apps. If not its meaningless to 13043 * delete a partially installed application. 13044 */ 13045 private void removePackageDataLI(PackageSetting ps, 13046 int[] allUserHandles, boolean[] perUserInstalled, 13047 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13048 String packageName = ps.name; 13049 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13050 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13051 // Retrieve object to delete permissions for shared user later on 13052 final PackageSetting deletedPs; 13053 // reader 13054 synchronized (mPackages) { 13055 deletedPs = mSettings.mPackages.get(packageName); 13056 if (outInfo != null) { 13057 outInfo.removedPackage = packageName; 13058 outInfo.removedUsers = deletedPs != null 13059 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13060 : null; 13061 } 13062 } 13063 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13064 removeDataDirsLI(ps.volumeUuid, packageName); 13065 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13066 } 13067 // writer 13068 synchronized (mPackages) { 13069 if (deletedPs != null) { 13070 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13071 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13072 clearDefaultBrowserIfNeeded(packageName); 13073 if (outInfo != null) { 13074 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13075 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13076 } 13077 updatePermissionsLPw(deletedPs.name, null, 0); 13078 if (deletedPs.sharedUser != null) { 13079 // Remove permissions associated with package. Since runtime 13080 // permissions are per user we have to kill the removed package 13081 // or packages running under the shared user of the removed 13082 // package if revoking the permissions requested only by the removed 13083 // package is successful and this causes a change in gids. 13084 for (int userId : UserManagerService.getInstance().getUserIds()) { 13085 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13086 userId); 13087 if (userIdToKill == UserHandle.USER_ALL 13088 || userIdToKill >= UserHandle.USER_OWNER) { 13089 // If gids changed for this user, kill all affected packages. 13090 mHandler.post(new Runnable() { 13091 @Override 13092 public void run() { 13093 // This has to happen with no lock held. 13094 killApplication(deletedPs.name, deletedPs.appId, 13095 KILL_APP_REASON_GIDS_CHANGED); 13096 } 13097 }); 13098 break; 13099 } 13100 } 13101 } 13102 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13103 } 13104 // make sure to preserve per-user disabled state if this removal was just 13105 // a downgrade of a system app to the factory package 13106 if (allUserHandles != null && perUserInstalled != null) { 13107 if (DEBUG_REMOVE) { 13108 Slog.d(TAG, "Propagating install state across downgrade"); 13109 } 13110 for (int i = 0; i < allUserHandles.length; i++) { 13111 if (DEBUG_REMOVE) { 13112 Slog.d(TAG, " user " + allUserHandles[i] 13113 + " => " + perUserInstalled[i]); 13114 } 13115 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13116 } 13117 } 13118 } 13119 // can downgrade to reader 13120 if (writeSettings) { 13121 // Save settings now 13122 mSettings.writeLPr(); 13123 } 13124 } 13125 if (outInfo != null) { 13126 // A user ID was deleted here. Go through all users and remove it 13127 // from KeyStore. 13128 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13129 } 13130 } 13131 13132 static boolean locationIsPrivileged(File path) { 13133 try { 13134 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13135 .getCanonicalPath(); 13136 return path.getCanonicalPath().startsWith(privilegedAppDir); 13137 } catch (IOException e) { 13138 Slog.e(TAG, "Unable to access code path " + path); 13139 } 13140 return false; 13141 } 13142 13143 /* 13144 * Tries to delete system package. 13145 */ 13146 private boolean deleteSystemPackageLI(PackageSetting newPs, 13147 int[] allUserHandles, boolean[] perUserInstalled, 13148 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13149 final boolean applyUserRestrictions 13150 = (allUserHandles != null) && (perUserInstalled != null); 13151 PackageSetting disabledPs = null; 13152 // Confirm if the system package has been updated 13153 // An updated system app can be deleted. This will also have to restore 13154 // the system pkg from system partition 13155 // reader 13156 synchronized (mPackages) { 13157 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13158 } 13159 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13160 + " disabledPs=" + disabledPs); 13161 if (disabledPs == null) { 13162 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13163 return false; 13164 } else if (DEBUG_REMOVE) { 13165 Slog.d(TAG, "Deleting system pkg from data partition"); 13166 } 13167 if (DEBUG_REMOVE) { 13168 if (applyUserRestrictions) { 13169 Slog.d(TAG, "Remembering install states:"); 13170 for (int i = 0; i < allUserHandles.length; i++) { 13171 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13172 } 13173 } 13174 } 13175 // Delete the updated package 13176 outInfo.isRemovedPackageSystemUpdate = true; 13177 if (disabledPs.versionCode < newPs.versionCode) { 13178 // Delete data for downgrades 13179 flags &= ~PackageManager.DELETE_KEEP_DATA; 13180 } else { 13181 // Preserve data by setting flag 13182 flags |= PackageManager.DELETE_KEEP_DATA; 13183 } 13184 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13185 allUserHandles, perUserInstalled, outInfo, writeSettings); 13186 if (!ret) { 13187 return false; 13188 } 13189 // writer 13190 synchronized (mPackages) { 13191 // Reinstate the old system package 13192 mSettings.enableSystemPackageLPw(newPs.name); 13193 // Remove any native libraries from the upgraded package. 13194 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13195 } 13196 // Install the system package 13197 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13198 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13199 if (locationIsPrivileged(disabledPs.codePath)) { 13200 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13201 } 13202 13203 final PackageParser.Package newPkg; 13204 try { 13205 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13206 } catch (PackageManagerException e) { 13207 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13208 return false; 13209 } 13210 13211 // writer 13212 synchronized (mPackages) { 13213 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13214 13215 // Propagate the permissions state as we do not want to drop on the floor 13216 // runtime permissions. The update permissions method below will take 13217 // care of removing obsolete permissions and grant install permissions. 13218 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13219 updatePermissionsLPw(newPkg.packageName, newPkg, 13220 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13221 13222 if (applyUserRestrictions) { 13223 if (DEBUG_REMOVE) { 13224 Slog.d(TAG, "Propagating install state across reinstall"); 13225 } 13226 for (int i = 0; i < allUserHandles.length; i++) { 13227 if (DEBUG_REMOVE) { 13228 Slog.d(TAG, " user " + allUserHandles[i] 13229 + " => " + perUserInstalled[i]); 13230 } 13231 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13232 13233 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13234 } 13235 // Regardless of writeSettings we need to ensure that this restriction 13236 // state propagation is persisted 13237 mSettings.writeAllUsersPackageRestrictionsLPr(); 13238 } 13239 // can downgrade to reader here 13240 if (writeSettings) { 13241 mSettings.writeLPr(); 13242 } 13243 } 13244 return true; 13245 } 13246 13247 private boolean deleteInstalledPackageLI(PackageSetting ps, 13248 boolean deleteCodeAndResources, int flags, 13249 int[] allUserHandles, boolean[] perUserInstalled, 13250 PackageRemovedInfo outInfo, boolean writeSettings) { 13251 if (outInfo != null) { 13252 outInfo.uid = ps.appId; 13253 } 13254 13255 // Delete package data from internal structures and also remove data if flag is set 13256 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13257 13258 // Delete application code and resources 13259 if (deleteCodeAndResources && (outInfo != null)) { 13260 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13261 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13262 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13263 } 13264 return true; 13265 } 13266 13267 @Override 13268 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13269 int userId) { 13270 mContext.enforceCallingOrSelfPermission( 13271 android.Manifest.permission.DELETE_PACKAGES, null); 13272 synchronized (mPackages) { 13273 PackageSetting ps = mSettings.mPackages.get(packageName); 13274 if (ps == null) { 13275 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13276 return false; 13277 } 13278 if (!ps.getInstalled(userId)) { 13279 // Can't block uninstall for an app that is not installed or enabled. 13280 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13281 return false; 13282 } 13283 ps.setBlockUninstall(blockUninstall, userId); 13284 mSettings.writePackageRestrictionsLPr(userId); 13285 } 13286 return true; 13287 } 13288 13289 @Override 13290 public boolean getBlockUninstallForUser(String packageName, int userId) { 13291 synchronized (mPackages) { 13292 PackageSetting ps = mSettings.mPackages.get(packageName); 13293 if (ps == null) { 13294 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13295 return false; 13296 } 13297 return ps.getBlockUninstall(userId); 13298 } 13299 } 13300 13301 /* 13302 * This method handles package deletion in general 13303 */ 13304 private boolean deletePackageLI(String packageName, UserHandle user, 13305 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13306 int flags, PackageRemovedInfo outInfo, 13307 boolean writeSettings) { 13308 if (packageName == null) { 13309 Slog.w(TAG, "Attempt to delete null packageName."); 13310 return false; 13311 } 13312 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13313 PackageSetting ps; 13314 boolean dataOnly = false; 13315 int removeUser = -1; 13316 int appId = -1; 13317 synchronized (mPackages) { 13318 ps = mSettings.mPackages.get(packageName); 13319 if (ps == null) { 13320 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13321 return false; 13322 } 13323 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13324 && user.getIdentifier() != UserHandle.USER_ALL) { 13325 // The caller is asking that the package only be deleted for a single 13326 // user. To do this, we just mark its uninstalled state and delete 13327 // its data. If this is a system app, we only allow this to happen if 13328 // they have set the special DELETE_SYSTEM_APP which requests different 13329 // semantics than normal for uninstalling system apps. 13330 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13331 final int userId = user.getIdentifier(); 13332 ps.setUserState(userId, 13333 COMPONENT_ENABLED_STATE_DEFAULT, 13334 false, //installed 13335 true, //stopped 13336 true, //notLaunched 13337 false, //hidden 13338 null, null, null, 13339 false, // blockUninstall 13340 ps.readUserState(userId).domainVerificationStatus, 0); 13341 if (!isSystemApp(ps)) { 13342 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13343 // Other user still have this package installed, so all 13344 // we need to do is clear this user's data and save that 13345 // it is uninstalled. 13346 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13347 removeUser = user.getIdentifier(); 13348 appId = ps.appId; 13349 scheduleWritePackageRestrictionsLocked(removeUser); 13350 } else { 13351 // We need to set it back to 'installed' so the uninstall 13352 // broadcasts will be sent correctly. 13353 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13354 ps.setInstalled(true, user.getIdentifier()); 13355 } 13356 } else { 13357 // This is a system app, so we assume that the 13358 // other users still have this package installed, so all 13359 // we need to do is clear this user's data and save that 13360 // it is uninstalled. 13361 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13362 removeUser = user.getIdentifier(); 13363 appId = ps.appId; 13364 scheduleWritePackageRestrictionsLocked(removeUser); 13365 } 13366 } 13367 } 13368 13369 if (removeUser >= 0) { 13370 // From above, we determined that we are deleting this only 13371 // for a single user. Continue the work here. 13372 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13373 if (outInfo != null) { 13374 outInfo.removedPackage = packageName; 13375 outInfo.removedAppId = appId; 13376 outInfo.removedUsers = new int[] {removeUser}; 13377 } 13378 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13379 removeKeystoreDataIfNeeded(removeUser, appId); 13380 schedulePackageCleaning(packageName, removeUser, false); 13381 synchronized (mPackages) { 13382 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13383 scheduleWritePackageRestrictionsLocked(removeUser); 13384 } 13385 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13386 } 13387 return true; 13388 } 13389 13390 if (dataOnly) { 13391 // Delete application data first 13392 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13393 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13394 return true; 13395 } 13396 13397 boolean ret = false; 13398 if (isSystemApp(ps)) { 13399 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13400 // When an updated system application is deleted we delete the existing resources as well and 13401 // fall back to existing code in system partition 13402 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13403 flags, outInfo, writeSettings); 13404 } else { 13405 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13406 // Kill application pre-emptively especially for apps on sd. 13407 killApplication(packageName, ps.appId, "uninstall pkg"); 13408 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13409 allUserHandles, perUserInstalled, 13410 outInfo, writeSettings); 13411 } 13412 13413 return ret; 13414 } 13415 13416 private final class ClearStorageConnection implements ServiceConnection { 13417 IMediaContainerService mContainerService; 13418 13419 @Override 13420 public void onServiceConnected(ComponentName name, IBinder service) { 13421 synchronized (this) { 13422 mContainerService = IMediaContainerService.Stub.asInterface(service); 13423 notifyAll(); 13424 } 13425 } 13426 13427 @Override 13428 public void onServiceDisconnected(ComponentName name) { 13429 } 13430 } 13431 13432 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13433 final boolean mounted; 13434 if (Environment.isExternalStorageEmulated()) { 13435 mounted = true; 13436 } else { 13437 final String status = Environment.getExternalStorageState(); 13438 13439 mounted = status.equals(Environment.MEDIA_MOUNTED) 13440 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13441 } 13442 13443 if (!mounted) { 13444 return; 13445 } 13446 13447 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13448 int[] users; 13449 if (userId == UserHandle.USER_ALL) { 13450 users = sUserManager.getUserIds(); 13451 } else { 13452 users = new int[] { userId }; 13453 } 13454 final ClearStorageConnection conn = new ClearStorageConnection(); 13455 if (mContext.bindServiceAsUser( 13456 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13457 try { 13458 for (int curUser : users) { 13459 long timeout = SystemClock.uptimeMillis() + 5000; 13460 synchronized (conn) { 13461 long now = SystemClock.uptimeMillis(); 13462 while (conn.mContainerService == null && now < timeout) { 13463 try { 13464 conn.wait(timeout - now); 13465 } catch (InterruptedException e) { 13466 } 13467 } 13468 } 13469 if (conn.mContainerService == null) { 13470 return; 13471 } 13472 13473 final UserEnvironment userEnv = new UserEnvironment(curUser); 13474 clearDirectory(conn.mContainerService, 13475 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13476 if (allData) { 13477 clearDirectory(conn.mContainerService, 13478 userEnv.buildExternalStorageAppDataDirs(packageName)); 13479 clearDirectory(conn.mContainerService, 13480 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13481 } 13482 } 13483 } finally { 13484 mContext.unbindService(conn); 13485 } 13486 } 13487 } 13488 13489 @Override 13490 public void clearApplicationUserData(final String packageName, 13491 final IPackageDataObserver observer, final int userId) { 13492 mContext.enforceCallingOrSelfPermission( 13493 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13494 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13495 // Queue up an async operation since the package deletion may take a little while. 13496 mHandler.post(new Runnable() { 13497 public void run() { 13498 mHandler.removeCallbacks(this); 13499 final boolean succeeded; 13500 synchronized (mInstallLock) { 13501 succeeded = clearApplicationUserDataLI(packageName, userId); 13502 } 13503 clearExternalStorageDataSync(packageName, userId, true); 13504 if (succeeded) { 13505 // invoke DeviceStorageMonitor's update method to clear any notifications 13506 DeviceStorageMonitorInternal 13507 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13508 if (dsm != null) { 13509 dsm.checkMemory(); 13510 } 13511 } 13512 if(observer != null) { 13513 try { 13514 observer.onRemoveCompleted(packageName, succeeded); 13515 } catch (RemoteException e) { 13516 Log.i(TAG, "Observer no longer exists."); 13517 } 13518 } //end if observer 13519 } //end run 13520 }); 13521 } 13522 13523 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13524 if (packageName == null) { 13525 Slog.w(TAG, "Attempt to delete null packageName."); 13526 return false; 13527 } 13528 13529 // Try finding details about the requested package 13530 PackageParser.Package pkg; 13531 synchronized (mPackages) { 13532 pkg = mPackages.get(packageName); 13533 if (pkg == null) { 13534 final PackageSetting ps = mSettings.mPackages.get(packageName); 13535 if (ps != null) { 13536 pkg = ps.pkg; 13537 } 13538 } 13539 13540 if (pkg == null) { 13541 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13542 return false; 13543 } 13544 13545 PackageSetting ps = (PackageSetting) pkg.mExtras; 13546 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13547 } 13548 13549 // Always delete data directories for package, even if we found no other 13550 // record of app. This helps users recover from UID mismatches without 13551 // resorting to a full data wipe. 13552 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13553 if (retCode < 0) { 13554 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13555 return false; 13556 } 13557 13558 final int appId = pkg.applicationInfo.uid; 13559 removeKeystoreDataIfNeeded(userId, appId); 13560 13561 // Create a native library symlink only if we have native libraries 13562 // and if the native libraries are 32 bit libraries. We do not provide 13563 // this symlink for 64 bit libraries. 13564 if (pkg.applicationInfo.primaryCpuAbi != null && 13565 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13566 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13567 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13568 nativeLibPath, userId) < 0) { 13569 Slog.w(TAG, "Failed linking native library dir"); 13570 return false; 13571 } 13572 } 13573 13574 return true; 13575 } 13576 13577 /** 13578 * Reverts user permission state changes (permissions and flags) in 13579 * all packages for a given user. 13580 * 13581 * @param userId The device user for which to do a reset. 13582 */ 13583 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13584 final int packageCount = mPackages.size(); 13585 for (int i = 0; i < packageCount; i++) { 13586 PackageParser.Package pkg = mPackages.valueAt(i); 13587 PackageSetting ps = (PackageSetting) pkg.mExtras; 13588 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13589 } 13590 } 13591 13592 /** 13593 * Reverts user permission state changes (permissions and flags). 13594 * 13595 * @param ps The package for which to reset. 13596 * @param userId The device user for which to do a reset. 13597 */ 13598 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13599 final PackageSetting ps, final int userId) { 13600 if (ps.pkg == null) { 13601 return; 13602 } 13603 13604 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13605 | FLAG_PERMISSION_USER_FIXED 13606 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13607 13608 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13609 | FLAG_PERMISSION_POLICY_FIXED; 13610 13611 boolean writeInstallPermissions = false; 13612 boolean writeRuntimePermissions = false; 13613 13614 final int permissionCount = ps.pkg.requestedPermissions.size(); 13615 for (int i = 0; i < permissionCount; i++) { 13616 String permission = ps.pkg.requestedPermissions.get(i); 13617 13618 BasePermission bp = mSettings.mPermissions.get(permission); 13619 if (bp == null) { 13620 continue; 13621 } 13622 13623 // If shared user we just reset the state to which only this app contributed. 13624 if (ps.sharedUser != null) { 13625 boolean used = false; 13626 final int packageCount = ps.sharedUser.packages.size(); 13627 for (int j = 0; j < packageCount; j++) { 13628 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13629 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13630 && pkg.pkg.requestedPermissions.contains(permission)) { 13631 used = true; 13632 break; 13633 } 13634 } 13635 if (used) { 13636 continue; 13637 } 13638 } 13639 13640 PermissionsState permissionsState = ps.getPermissionsState(); 13641 13642 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13643 13644 // Always clear the user settable flags. 13645 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13646 bp.name) != null; 13647 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13648 if (hasInstallState) { 13649 writeInstallPermissions = true; 13650 } else { 13651 writeRuntimePermissions = true; 13652 } 13653 } 13654 13655 // Below is only runtime permission handling. 13656 if (!bp.isRuntime()) { 13657 continue; 13658 } 13659 13660 // Never clobber system or policy. 13661 if ((oldFlags & policyOrSystemFlags) != 0) { 13662 continue; 13663 } 13664 13665 // If this permission was granted by default, make sure it is. 13666 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13667 if (permissionsState.grantRuntimePermission(bp, userId) 13668 != PERMISSION_OPERATION_FAILURE) { 13669 writeRuntimePermissions = true; 13670 } 13671 } else { 13672 // Otherwise, reset the permission. 13673 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13674 switch (revokeResult) { 13675 case PERMISSION_OPERATION_SUCCESS: { 13676 writeRuntimePermissions = true; 13677 } break; 13678 13679 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13680 writeRuntimePermissions = true; 13681 final int appId = ps.appId; 13682 mHandler.post(new Runnable() { 13683 @Override 13684 public void run() { 13685 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13686 } 13687 }); 13688 } break; 13689 } 13690 } 13691 } 13692 13693 // Synchronously write as we are taking permissions away. 13694 if (writeRuntimePermissions) { 13695 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13696 } 13697 13698 // Synchronously write as we are taking permissions away. 13699 if (writeInstallPermissions) { 13700 mSettings.writeLPr(); 13701 } 13702 } 13703 13704 /** 13705 * Remove entries from the keystore daemon. Will only remove it if the 13706 * {@code appId} is valid. 13707 */ 13708 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13709 if (appId < 0) { 13710 return; 13711 } 13712 13713 final KeyStore keyStore = KeyStore.getInstance(); 13714 if (keyStore != null) { 13715 if (userId == UserHandle.USER_ALL) { 13716 for (final int individual : sUserManager.getUserIds()) { 13717 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13718 } 13719 } else { 13720 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13721 } 13722 } else { 13723 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13724 } 13725 } 13726 13727 @Override 13728 public void deleteApplicationCacheFiles(final String packageName, 13729 final IPackageDataObserver observer) { 13730 mContext.enforceCallingOrSelfPermission( 13731 android.Manifest.permission.DELETE_CACHE_FILES, null); 13732 // Queue up an async operation since the package deletion may take a little while. 13733 final int userId = UserHandle.getCallingUserId(); 13734 mHandler.post(new Runnable() { 13735 public void run() { 13736 mHandler.removeCallbacks(this); 13737 final boolean succeded; 13738 synchronized (mInstallLock) { 13739 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13740 } 13741 clearExternalStorageDataSync(packageName, userId, false); 13742 if (observer != null) { 13743 try { 13744 observer.onRemoveCompleted(packageName, succeded); 13745 } catch (RemoteException e) { 13746 Log.i(TAG, "Observer no longer exists."); 13747 } 13748 } //end if observer 13749 } //end run 13750 }); 13751 } 13752 13753 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13754 if (packageName == null) { 13755 Slog.w(TAG, "Attempt to delete null packageName."); 13756 return false; 13757 } 13758 PackageParser.Package p; 13759 synchronized (mPackages) { 13760 p = mPackages.get(packageName); 13761 } 13762 if (p == null) { 13763 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13764 return false; 13765 } 13766 final ApplicationInfo applicationInfo = p.applicationInfo; 13767 if (applicationInfo == null) { 13768 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13769 return false; 13770 } 13771 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13772 if (retCode < 0) { 13773 Slog.w(TAG, "Couldn't remove cache files for package: " 13774 + packageName + " u" + userId); 13775 return false; 13776 } 13777 return true; 13778 } 13779 13780 @Override 13781 public void getPackageSizeInfo(final String packageName, int userHandle, 13782 final IPackageStatsObserver observer) { 13783 mContext.enforceCallingOrSelfPermission( 13784 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13785 if (packageName == null) { 13786 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13787 } 13788 13789 PackageStats stats = new PackageStats(packageName, userHandle); 13790 13791 /* 13792 * Queue up an async operation since the package measurement may take a 13793 * little while. 13794 */ 13795 Message msg = mHandler.obtainMessage(INIT_COPY); 13796 msg.obj = new MeasureParams(stats, observer); 13797 mHandler.sendMessage(msg); 13798 } 13799 13800 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13801 PackageStats pStats) { 13802 if (packageName == null) { 13803 Slog.w(TAG, "Attempt to get size of null packageName."); 13804 return false; 13805 } 13806 PackageParser.Package p; 13807 boolean dataOnly = false; 13808 String libDirRoot = null; 13809 String asecPath = null; 13810 PackageSetting ps = null; 13811 synchronized (mPackages) { 13812 p = mPackages.get(packageName); 13813 ps = mSettings.mPackages.get(packageName); 13814 if(p == null) { 13815 dataOnly = true; 13816 if((ps == null) || (ps.pkg == null)) { 13817 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13818 return false; 13819 } 13820 p = ps.pkg; 13821 } 13822 if (ps != null) { 13823 libDirRoot = ps.legacyNativeLibraryPathString; 13824 } 13825 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13826 final long token = Binder.clearCallingIdentity(); 13827 try { 13828 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13829 if (secureContainerId != null) { 13830 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13831 } 13832 } finally { 13833 Binder.restoreCallingIdentity(token); 13834 } 13835 } 13836 } 13837 String publicSrcDir = null; 13838 if(!dataOnly) { 13839 final ApplicationInfo applicationInfo = p.applicationInfo; 13840 if (applicationInfo == null) { 13841 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13842 return false; 13843 } 13844 if (p.isForwardLocked()) { 13845 publicSrcDir = applicationInfo.getBaseResourcePath(); 13846 } 13847 } 13848 // TODO: extend to measure size of split APKs 13849 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13850 // not just the first level. 13851 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13852 // just the primary. 13853 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13854 13855 String apkPath; 13856 File packageDir = new File(p.codePath); 13857 13858 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13859 apkPath = packageDir.getAbsolutePath(); 13860 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13861 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13862 libDirRoot = null; 13863 } 13864 } else { 13865 apkPath = p.baseCodePath; 13866 } 13867 13868 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13869 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13870 if (res < 0) { 13871 return false; 13872 } 13873 13874 // Fix-up for forward-locked applications in ASEC containers. 13875 if (!isExternal(p)) { 13876 pStats.codeSize += pStats.externalCodeSize; 13877 pStats.externalCodeSize = 0L; 13878 } 13879 13880 return true; 13881 } 13882 13883 13884 @Override 13885 public void addPackageToPreferred(String packageName) { 13886 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13887 } 13888 13889 @Override 13890 public void removePackageFromPreferred(String packageName) { 13891 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13892 } 13893 13894 @Override 13895 public List<PackageInfo> getPreferredPackages(int flags) { 13896 return new ArrayList<PackageInfo>(); 13897 } 13898 13899 private int getUidTargetSdkVersionLockedLPr(int uid) { 13900 Object obj = mSettings.getUserIdLPr(uid); 13901 if (obj instanceof SharedUserSetting) { 13902 final SharedUserSetting sus = (SharedUserSetting) obj; 13903 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13904 final Iterator<PackageSetting> it = sus.packages.iterator(); 13905 while (it.hasNext()) { 13906 final PackageSetting ps = it.next(); 13907 if (ps.pkg != null) { 13908 int v = ps.pkg.applicationInfo.targetSdkVersion; 13909 if (v < vers) vers = v; 13910 } 13911 } 13912 return vers; 13913 } else if (obj instanceof PackageSetting) { 13914 final PackageSetting ps = (PackageSetting) obj; 13915 if (ps.pkg != null) { 13916 return ps.pkg.applicationInfo.targetSdkVersion; 13917 } 13918 } 13919 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13920 } 13921 13922 @Override 13923 public void addPreferredActivity(IntentFilter filter, int match, 13924 ComponentName[] set, ComponentName activity, int userId) { 13925 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13926 "Adding preferred"); 13927 } 13928 13929 private void addPreferredActivityInternal(IntentFilter filter, int match, 13930 ComponentName[] set, ComponentName activity, boolean always, int userId, 13931 String opname) { 13932 // writer 13933 int callingUid = Binder.getCallingUid(); 13934 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13935 if (filter.countActions() == 0) { 13936 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13937 return; 13938 } 13939 synchronized (mPackages) { 13940 if (mContext.checkCallingOrSelfPermission( 13941 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13942 != PackageManager.PERMISSION_GRANTED) { 13943 if (getUidTargetSdkVersionLockedLPr(callingUid) 13944 < Build.VERSION_CODES.FROYO) { 13945 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13946 + callingUid); 13947 return; 13948 } 13949 mContext.enforceCallingOrSelfPermission( 13950 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13951 } 13952 13953 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13954 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13955 + userId + ":"); 13956 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13957 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13958 scheduleWritePackageRestrictionsLocked(userId); 13959 } 13960 } 13961 13962 @Override 13963 public void replacePreferredActivity(IntentFilter filter, int match, 13964 ComponentName[] set, ComponentName activity, int userId) { 13965 if (filter.countActions() != 1) { 13966 throw new IllegalArgumentException( 13967 "replacePreferredActivity expects filter to have only 1 action."); 13968 } 13969 if (filter.countDataAuthorities() != 0 13970 || filter.countDataPaths() != 0 13971 || filter.countDataSchemes() > 1 13972 || filter.countDataTypes() != 0) { 13973 throw new IllegalArgumentException( 13974 "replacePreferredActivity expects filter to have no data authorities, " + 13975 "paths, or types; and at most one scheme."); 13976 } 13977 13978 final int callingUid = Binder.getCallingUid(); 13979 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13980 synchronized (mPackages) { 13981 if (mContext.checkCallingOrSelfPermission( 13982 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13983 != PackageManager.PERMISSION_GRANTED) { 13984 if (getUidTargetSdkVersionLockedLPr(callingUid) 13985 < Build.VERSION_CODES.FROYO) { 13986 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13987 + Binder.getCallingUid()); 13988 return; 13989 } 13990 mContext.enforceCallingOrSelfPermission( 13991 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13992 } 13993 13994 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13995 if (pir != null) { 13996 // Get all of the existing entries that exactly match this filter. 13997 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13998 if (existing != null && existing.size() == 1) { 13999 PreferredActivity cur = existing.get(0); 14000 if (DEBUG_PREFERRED) { 14001 Slog.i(TAG, "Checking replace of preferred:"); 14002 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14003 if (!cur.mPref.mAlways) { 14004 Slog.i(TAG, " -- CUR; not mAlways!"); 14005 } else { 14006 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14007 Slog.i(TAG, " -- CUR: mSet=" 14008 + Arrays.toString(cur.mPref.mSetComponents)); 14009 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14010 Slog.i(TAG, " -- NEW: mMatch=" 14011 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14012 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14013 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14014 } 14015 } 14016 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14017 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14018 && cur.mPref.sameSet(set)) { 14019 // Setting the preferred activity to what it happens to be already 14020 if (DEBUG_PREFERRED) { 14021 Slog.i(TAG, "Replacing with same preferred activity " 14022 + cur.mPref.mShortComponent + " for user " 14023 + userId + ":"); 14024 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14025 } 14026 return; 14027 } 14028 } 14029 14030 if (existing != null) { 14031 if (DEBUG_PREFERRED) { 14032 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14033 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14034 } 14035 for (int i = 0; i < existing.size(); i++) { 14036 PreferredActivity pa = existing.get(i); 14037 if (DEBUG_PREFERRED) { 14038 Slog.i(TAG, "Removing existing preferred activity " 14039 + pa.mPref.mComponent + ":"); 14040 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14041 } 14042 pir.removeFilter(pa); 14043 } 14044 } 14045 } 14046 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14047 "Replacing preferred"); 14048 } 14049 } 14050 14051 @Override 14052 public void clearPackagePreferredActivities(String packageName) { 14053 final int uid = Binder.getCallingUid(); 14054 // writer 14055 synchronized (mPackages) { 14056 PackageParser.Package pkg = mPackages.get(packageName); 14057 if (pkg == null || pkg.applicationInfo.uid != uid) { 14058 if (mContext.checkCallingOrSelfPermission( 14059 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14060 != PackageManager.PERMISSION_GRANTED) { 14061 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14062 < Build.VERSION_CODES.FROYO) { 14063 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14064 + Binder.getCallingUid()); 14065 return; 14066 } 14067 mContext.enforceCallingOrSelfPermission( 14068 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14069 } 14070 } 14071 14072 int user = UserHandle.getCallingUserId(); 14073 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14074 scheduleWritePackageRestrictionsLocked(user); 14075 } 14076 } 14077 } 14078 14079 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14080 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14081 ArrayList<PreferredActivity> removed = null; 14082 boolean changed = false; 14083 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14084 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14085 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14086 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14087 continue; 14088 } 14089 Iterator<PreferredActivity> it = pir.filterIterator(); 14090 while (it.hasNext()) { 14091 PreferredActivity pa = it.next(); 14092 // Mark entry for removal only if it matches the package name 14093 // and the entry is of type "always". 14094 if (packageName == null || 14095 (pa.mPref.mComponent.getPackageName().equals(packageName) 14096 && pa.mPref.mAlways)) { 14097 if (removed == null) { 14098 removed = new ArrayList<PreferredActivity>(); 14099 } 14100 removed.add(pa); 14101 } 14102 } 14103 if (removed != null) { 14104 for (int j=0; j<removed.size(); j++) { 14105 PreferredActivity pa = removed.get(j); 14106 pir.removeFilter(pa); 14107 } 14108 changed = true; 14109 } 14110 } 14111 return changed; 14112 } 14113 14114 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14115 private void clearIntentFilterVerificationsLPw(int userId) { 14116 final int packageCount = mPackages.size(); 14117 for (int i = 0; i < packageCount; i++) { 14118 PackageParser.Package pkg = mPackages.valueAt(i); 14119 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14120 } 14121 } 14122 14123 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14124 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14125 if (userId == UserHandle.USER_ALL) { 14126 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14127 sUserManager.getUserIds())) { 14128 for (int oneUserId : sUserManager.getUserIds()) { 14129 scheduleWritePackageRestrictionsLocked(oneUserId); 14130 } 14131 } 14132 } else { 14133 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14134 scheduleWritePackageRestrictionsLocked(userId); 14135 } 14136 } 14137 } 14138 14139 void clearDefaultBrowserIfNeeded(String packageName) { 14140 for (int oneUserId : sUserManager.getUserIds()) { 14141 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14142 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14143 if (packageName.equals(defaultBrowserPackageName)) { 14144 setDefaultBrowserPackageName(null, oneUserId); 14145 } 14146 } 14147 } 14148 14149 @Override 14150 public void resetApplicationPreferences(int userId) { 14151 mContext.enforceCallingOrSelfPermission( 14152 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14153 // writer 14154 synchronized (mPackages) { 14155 final long identity = Binder.clearCallingIdentity(); 14156 try { 14157 clearPackagePreferredActivitiesLPw(null, userId); 14158 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14159 // TODO: We have to reset the default SMS and Phone. This requires 14160 // significant refactoring to keep all default apps in the package 14161 // manager (cleaner but more work) or have the services provide 14162 // callbacks to the package manager to request a default app reset. 14163 applyFactoryDefaultBrowserLPw(userId); 14164 clearIntentFilterVerificationsLPw(userId); 14165 primeDomainVerificationsLPw(userId); 14166 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14167 scheduleWritePackageRestrictionsLocked(userId); 14168 } finally { 14169 Binder.restoreCallingIdentity(identity); 14170 } 14171 } 14172 } 14173 14174 @Override 14175 public int getPreferredActivities(List<IntentFilter> outFilters, 14176 List<ComponentName> outActivities, String packageName) { 14177 14178 int num = 0; 14179 final int userId = UserHandle.getCallingUserId(); 14180 // reader 14181 synchronized (mPackages) { 14182 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14183 if (pir != null) { 14184 final Iterator<PreferredActivity> it = pir.filterIterator(); 14185 while (it.hasNext()) { 14186 final PreferredActivity pa = it.next(); 14187 if (packageName == null 14188 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14189 && pa.mPref.mAlways)) { 14190 if (outFilters != null) { 14191 outFilters.add(new IntentFilter(pa)); 14192 } 14193 if (outActivities != null) { 14194 outActivities.add(pa.mPref.mComponent); 14195 } 14196 } 14197 } 14198 } 14199 } 14200 14201 return num; 14202 } 14203 14204 @Override 14205 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14206 int userId) { 14207 int callingUid = Binder.getCallingUid(); 14208 if (callingUid != Process.SYSTEM_UID) { 14209 throw new SecurityException( 14210 "addPersistentPreferredActivity can only be run by the system"); 14211 } 14212 if (filter.countActions() == 0) { 14213 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14214 return; 14215 } 14216 synchronized (mPackages) { 14217 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14218 " :"); 14219 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14220 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14221 new PersistentPreferredActivity(filter, activity)); 14222 scheduleWritePackageRestrictionsLocked(userId); 14223 } 14224 } 14225 14226 @Override 14227 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14228 int callingUid = Binder.getCallingUid(); 14229 if (callingUid != Process.SYSTEM_UID) { 14230 throw new SecurityException( 14231 "clearPackagePersistentPreferredActivities can only be run by the system"); 14232 } 14233 ArrayList<PersistentPreferredActivity> removed = null; 14234 boolean changed = false; 14235 synchronized (mPackages) { 14236 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14237 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14238 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14239 .valueAt(i); 14240 if (userId != thisUserId) { 14241 continue; 14242 } 14243 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14244 while (it.hasNext()) { 14245 PersistentPreferredActivity ppa = it.next(); 14246 // Mark entry for removal only if it matches the package name. 14247 if (ppa.mComponent.getPackageName().equals(packageName)) { 14248 if (removed == null) { 14249 removed = new ArrayList<PersistentPreferredActivity>(); 14250 } 14251 removed.add(ppa); 14252 } 14253 } 14254 if (removed != null) { 14255 for (int j=0; j<removed.size(); j++) { 14256 PersistentPreferredActivity ppa = removed.get(j); 14257 ppir.removeFilter(ppa); 14258 } 14259 changed = true; 14260 } 14261 } 14262 14263 if (changed) { 14264 scheduleWritePackageRestrictionsLocked(userId); 14265 } 14266 } 14267 } 14268 14269 /** 14270 * Common machinery for picking apart a restored XML blob and passing 14271 * it to a caller-supplied functor to be applied to the running system. 14272 */ 14273 private void restoreFromXml(XmlPullParser parser, int userId, 14274 String expectedStartTag, BlobXmlRestorer functor) 14275 throws IOException, XmlPullParserException { 14276 int type; 14277 while ((type = parser.next()) != XmlPullParser.START_TAG 14278 && type != XmlPullParser.END_DOCUMENT) { 14279 } 14280 if (type != XmlPullParser.START_TAG) { 14281 // oops didn't find a start tag?! 14282 if (DEBUG_BACKUP) { 14283 Slog.e(TAG, "Didn't find start tag during restore"); 14284 } 14285 return; 14286 } 14287 14288 // this is supposed to be TAG_PREFERRED_BACKUP 14289 if (!expectedStartTag.equals(parser.getName())) { 14290 if (DEBUG_BACKUP) { 14291 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14292 } 14293 return; 14294 } 14295 14296 // skip interfering stuff, then we're aligned with the backing implementation 14297 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14298 functor.apply(parser, userId); 14299 } 14300 14301 private interface BlobXmlRestorer { 14302 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14303 } 14304 14305 /** 14306 * Non-Binder method, support for the backup/restore mechanism: write the 14307 * full set of preferred activities in its canonical XML format. Returns the 14308 * XML output as a byte array, or null if there is none. 14309 */ 14310 @Override 14311 public byte[] getPreferredActivityBackup(int userId) { 14312 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14313 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14314 } 14315 14316 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14317 try { 14318 final XmlSerializer serializer = new FastXmlSerializer(); 14319 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14320 serializer.startDocument(null, true); 14321 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14322 14323 synchronized (mPackages) { 14324 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14325 } 14326 14327 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14328 serializer.endDocument(); 14329 serializer.flush(); 14330 } catch (Exception e) { 14331 if (DEBUG_BACKUP) { 14332 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14333 } 14334 return null; 14335 } 14336 14337 return dataStream.toByteArray(); 14338 } 14339 14340 @Override 14341 public void restorePreferredActivities(byte[] backup, int userId) { 14342 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14343 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14344 } 14345 14346 try { 14347 final XmlPullParser parser = Xml.newPullParser(); 14348 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14349 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14350 new BlobXmlRestorer() { 14351 @Override 14352 public void apply(XmlPullParser parser, int userId) 14353 throws XmlPullParserException, IOException { 14354 synchronized (mPackages) { 14355 mSettings.readPreferredActivitiesLPw(parser, userId); 14356 } 14357 } 14358 } ); 14359 } catch (Exception e) { 14360 if (DEBUG_BACKUP) { 14361 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14362 } 14363 } 14364 } 14365 14366 /** 14367 * Non-Binder method, support for the backup/restore mechanism: write the 14368 * default browser (etc) settings in its canonical XML format. Returns the default 14369 * browser XML representation as a byte array, or null if there is none. 14370 */ 14371 @Override 14372 public byte[] getDefaultAppsBackup(int userId) { 14373 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14374 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14375 } 14376 14377 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14378 try { 14379 final XmlSerializer serializer = new FastXmlSerializer(); 14380 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14381 serializer.startDocument(null, true); 14382 serializer.startTag(null, TAG_DEFAULT_APPS); 14383 14384 synchronized (mPackages) { 14385 mSettings.writeDefaultAppsLPr(serializer, userId); 14386 } 14387 14388 serializer.endTag(null, TAG_DEFAULT_APPS); 14389 serializer.endDocument(); 14390 serializer.flush(); 14391 } catch (Exception e) { 14392 if (DEBUG_BACKUP) { 14393 Slog.e(TAG, "Unable to write default apps for backup", e); 14394 } 14395 return null; 14396 } 14397 14398 return dataStream.toByteArray(); 14399 } 14400 14401 @Override 14402 public void restoreDefaultApps(byte[] backup, int userId) { 14403 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14404 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14405 } 14406 14407 try { 14408 final XmlPullParser parser = Xml.newPullParser(); 14409 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14410 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14411 new BlobXmlRestorer() { 14412 @Override 14413 public void apply(XmlPullParser parser, int userId) 14414 throws XmlPullParserException, IOException { 14415 synchronized (mPackages) { 14416 mSettings.readDefaultAppsLPw(parser, userId); 14417 } 14418 } 14419 } ); 14420 } catch (Exception e) { 14421 if (DEBUG_BACKUP) { 14422 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14423 } 14424 } 14425 } 14426 14427 @Override 14428 public byte[] getIntentFilterVerificationBackup(int userId) { 14429 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14430 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14431 } 14432 14433 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14434 try { 14435 final XmlSerializer serializer = new FastXmlSerializer(); 14436 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14437 serializer.startDocument(null, true); 14438 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14439 14440 synchronized (mPackages) { 14441 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14442 } 14443 14444 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14445 serializer.endDocument(); 14446 serializer.flush(); 14447 } catch (Exception e) { 14448 if (DEBUG_BACKUP) { 14449 Slog.e(TAG, "Unable to write default apps for backup", e); 14450 } 14451 return null; 14452 } 14453 14454 return dataStream.toByteArray(); 14455 } 14456 14457 @Override 14458 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14459 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14460 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14461 } 14462 14463 try { 14464 final XmlPullParser parser = Xml.newPullParser(); 14465 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14466 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14467 new BlobXmlRestorer() { 14468 @Override 14469 public void apply(XmlPullParser parser, int userId) 14470 throws XmlPullParserException, IOException { 14471 synchronized (mPackages) { 14472 mSettings.readAllDomainVerificationsLPr(parser, userId); 14473 mSettings.writeLPr(); 14474 } 14475 } 14476 } ); 14477 } catch (Exception e) { 14478 if (DEBUG_BACKUP) { 14479 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14480 } 14481 } 14482 } 14483 14484 @Override 14485 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14486 int sourceUserId, int targetUserId, int flags) { 14487 mContext.enforceCallingOrSelfPermission( 14488 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14489 int callingUid = Binder.getCallingUid(); 14490 enforceOwnerRights(ownerPackage, callingUid); 14491 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14492 if (intentFilter.countActions() == 0) { 14493 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14494 return; 14495 } 14496 synchronized (mPackages) { 14497 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14498 ownerPackage, targetUserId, flags); 14499 CrossProfileIntentResolver resolver = 14500 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14501 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14502 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14503 if (existing != null) { 14504 int size = existing.size(); 14505 for (int i = 0; i < size; i++) { 14506 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14507 return; 14508 } 14509 } 14510 } 14511 resolver.addFilter(newFilter); 14512 scheduleWritePackageRestrictionsLocked(sourceUserId); 14513 } 14514 } 14515 14516 @Override 14517 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14518 mContext.enforceCallingOrSelfPermission( 14519 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14520 int callingUid = Binder.getCallingUid(); 14521 enforceOwnerRights(ownerPackage, callingUid); 14522 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14523 synchronized (mPackages) { 14524 CrossProfileIntentResolver resolver = 14525 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14526 ArraySet<CrossProfileIntentFilter> set = 14527 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14528 for (CrossProfileIntentFilter filter : set) { 14529 if (filter.getOwnerPackage().equals(ownerPackage)) { 14530 resolver.removeFilter(filter); 14531 } 14532 } 14533 scheduleWritePackageRestrictionsLocked(sourceUserId); 14534 } 14535 } 14536 14537 // Enforcing that callingUid is owning pkg on userId 14538 private void enforceOwnerRights(String pkg, int callingUid) { 14539 // The system owns everything. 14540 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14541 return; 14542 } 14543 int callingUserId = UserHandle.getUserId(callingUid); 14544 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14545 if (pi == null) { 14546 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14547 + callingUserId); 14548 } 14549 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14550 throw new SecurityException("Calling uid " + callingUid 14551 + " does not own package " + pkg); 14552 } 14553 } 14554 14555 @Override 14556 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14557 Intent intent = new Intent(Intent.ACTION_MAIN); 14558 intent.addCategory(Intent.CATEGORY_HOME); 14559 14560 final int callingUserId = UserHandle.getCallingUserId(); 14561 List<ResolveInfo> list = queryIntentActivities(intent, null, 14562 PackageManager.GET_META_DATA, callingUserId); 14563 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14564 true, false, false, callingUserId); 14565 14566 allHomeCandidates.clear(); 14567 if (list != null) { 14568 for (ResolveInfo ri : list) { 14569 allHomeCandidates.add(ri); 14570 } 14571 } 14572 return (preferred == null || preferred.activityInfo == null) 14573 ? null 14574 : new ComponentName(preferred.activityInfo.packageName, 14575 preferred.activityInfo.name); 14576 } 14577 14578 @Override 14579 public void setApplicationEnabledSetting(String appPackageName, 14580 int newState, int flags, int userId, String callingPackage) { 14581 if (!sUserManager.exists(userId)) return; 14582 if (callingPackage == null) { 14583 callingPackage = Integer.toString(Binder.getCallingUid()); 14584 } 14585 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14586 } 14587 14588 @Override 14589 public void setComponentEnabledSetting(ComponentName componentName, 14590 int newState, int flags, int userId) { 14591 if (!sUserManager.exists(userId)) return; 14592 setEnabledSetting(componentName.getPackageName(), 14593 componentName.getClassName(), newState, flags, userId, null); 14594 } 14595 14596 private void setEnabledSetting(final String packageName, String className, int newState, 14597 final int flags, int userId, String callingPackage) { 14598 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14599 || newState == COMPONENT_ENABLED_STATE_ENABLED 14600 || newState == COMPONENT_ENABLED_STATE_DISABLED 14601 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14602 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14603 throw new IllegalArgumentException("Invalid new component state: " 14604 + newState); 14605 } 14606 PackageSetting pkgSetting; 14607 final int uid = Binder.getCallingUid(); 14608 final int permission = mContext.checkCallingOrSelfPermission( 14609 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14610 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14611 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14612 boolean sendNow = false; 14613 boolean isApp = (className == null); 14614 String componentName = isApp ? packageName : className; 14615 int packageUid = -1; 14616 ArrayList<String> components; 14617 14618 // writer 14619 synchronized (mPackages) { 14620 pkgSetting = mSettings.mPackages.get(packageName); 14621 if (pkgSetting == null) { 14622 if (className == null) { 14623 throw new IllegalArgumentException( 14624 "Unknown package: " + packageName); 14625 } 14626 throw new IllegalArgumentException( 14627 "Unknown component: " + packageName 14628 + "/" + className); 14629 } 14630 // Allow root and verify that userId is not being specified by a different user 14631 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14632 throw new SecurityException( 14633 "Permission Denial: attempt to change component state from pid=" 14634 + Binder.getCallingPid() 14635 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14636 } 14637 if (className == null) { 14638 // We're dealing with an application/package level state change 14639 if (pkgSetting.getEnabled(userId) == newState) { 14640 // Nothing to do 14641 return; 14642 } 14643 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14644 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14645 // Don't care about who enables an app. 14646 callingPackage = null; 14647 } 14648 pkgSetting.setEnabled(newState, userId, callingPackage); 14649 // pkgSetting.pkg.mSetEnabled = newState; 14650 } else { 14651 // We're dealing with a component level state change 14652 // First, verify that this is a valid class name. 14653 PackageParser.Package pkg = pkgSetting.pkg; 14654 if (pkg == null || !pkg.hasComponentClassName(className)) { 14655 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14656 throw new IllegalArgumentException("Component class " + className 14657 + " does not exist in " + packageName); 14658 } else { 14659 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14660 + className + " does not exist in " + packageName); 14661 } 14662 } 14663 switch (newState) { 14664 case COMPONENT_ENABLED_STATE_ENABLED: 14665 if (!pkgSetting.enableComponentLPw(className, userId)) { 14666 return; 14667 } 14668 break; 14669 case COMPONENT_ENABLED_STATE_DISABLED: 14670 if (!pkgSetting.disableComponentLPw(className, userId)) { 14671 return; 14672 } 14673 break; 14674 case COMPONENT_ENABLED_STATE_DEFAULT: 14675 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14676 return; 14677 } 14678 break; 14679 default: 14680 Slog.e(TAG, "Invalid new component state: " + newState); 14681 return; 14682 } 14683 } 14684 scheduleWritePackageRestrictionsLocked(userId); 14685 components = mPendingBroadcasts.get(userId, packageName); 14686 final boolean newPackage = components == null; 14687 if (newPackage) { 14688 components = new ArrayList<String>(); 14689 } 14690 if (!components.contains(componentName)) { 14691 components.add(componentName); 14692 } 14693 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14694 sendNow = true; 14695 // Purge entry from pending broadcast list if another one exists already 14696 // since we are sending one right away. 14697 mPendingBroadcasts.remove(userId, packageName); 14698 } else { 14699 if (newPackage) { 14700 mPendingBroadcasts.put(userId, packageName, components); 14701 } 14702 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14703 // Schedule a message 14704 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14705 } 14706 } 14707 } 14708 14709 long callingId = Binder.clearCallingIdentity(); 14710 try { 14711 if (sendNow) { 14712 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14713 sendPackageChangedBroadcast(packageName, 14714 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14715 } 14716 } finally { 14717 Binder.restoreCallingIdentity(callingId); 14718 } 14719 } 14720 14721 private void sendPackageChangedBroadcast(String packageName, 14722 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14723 if (DEBUG_INSTALL) 14724 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14725 + componentNames); 14726 Bundle extras = new Bundle(4); 14727 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14728 String nameList[] = new String[componentNames.size()]; 14729 componentNames.toArray(nameList); 14730 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14731 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14732 extras.putInt(Intent.EXTRA_UID, packageUid); 14733 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14734 new int[] {UserHandle.getUserId(packageUid)}); 14735 } 14736 14737 @Override 14738 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14739 if (!sUserManager.exists(userId)) return; 14740 final int uid = Binder.getCallingUid(); 14741 final int permission = mContext.checkCallingOrSelfPermission( 14742 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14743 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14744 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14745 // writer 14746 synchronized (mPackages) { 14747 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14748 allowedByPermission, uid, userId)) { 14749 scheduleWritePackageRestrictionsLocked(userId); 14750 } 14751 } 14752 } 14753 14754 @Override 14755 public String getInstallerPackageName(String packageName) { 14756 // reader 14757 synchronized (mPackages) { 14758 return mSettings.getInstallerPackageNameLPr(packageName); 14759 } 14760 } 14761 14762 @Override 14763 public int getApplicationEnabledSetting(String packageName, int userId) { 14764 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14765 int uid = Binder.getCallingUid(); 14766 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14767 // reader 14768 synchronized (mPackages) { 14769 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14770 } 14771 } 14772 14773 @Override 14774 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14775 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14776 int uid = Binder.getCallingUid(); 14777 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14778 // reader 14779 synchronized (mPackages) { 14780 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14781 } 14782 } 14783 14784 @Override 14785 public void enterSafeMode() { 14786 enforceSystemOrRoot("Only the system can request entering safe mode"); 14787 14788 if (!mSystemReady) { 14789 mSafeMode = true; 14790 } 14791 } 14792 14793 @Override 14794 public void systemReady() { 14795 mSystemReady = true; 14796 14797 // Read the compatibilty setting when the system is ready. 14798 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14799 mContext.getContentResolver(), 14800 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14801 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14802 if (DEBUG_SETTINGS) { 14803 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14804 } 14805 14806 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14807 14808 synchronized (mPackages) { 14809 // Verify that all of the preferred activity components actually 14810 // exist. It is possible for applications to be updated and at 14811 // that point remove a previously declared activity component that 14812 // had been set as a preferred activity. We try to clean this up 14813 // the next time we encounter that preferred activity, but it is 14814 // possible for the user flow to never be able to return to that 14815 // situation so here we do a sanity check to make sure we haven't 14816 // left any junk around. 14817 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14818 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14819 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14820 removed.clear(); 14821 for (PreferredActivity pa : pir.filterSet()) { 14822 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14823 removed.add(pa); 14824 } 14825 } 14826 if (removed.size() > 0) { 14827 for (int r=0; r<removed.size(); r++) { 14828 PreferredActivity pa = removed.get(r); 14829 Slog.w(TAG, "Removing dangling preferred activity: " 14830 + pa.mPref.mComponent); 14831 pir.removeFilter(pa); 14832 } 14833 mSettings.writePackageRestrictionsLPr( 14834 mSettings.mPreferredActivities.keyAt(i)); 14835 } 14836 } 14837 14838 for (int userId : UserManagerService.getInstance().getUserIds()) { 14839 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14840 grantPermissionsUserIds = ArrayUtils.appendInt( 14841 grantPermissionsUserIds, userId); 14842 } 14843 } 14844 } 14845 sUserManager.systemReady(); 14846 14847 // If we upgraded grant all default permissions before kicking off. 14848 for (int userId : grantPermissionsUserIds) { 14849 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14850 } 14851 14852 // Kick off any messages waiting for system ready 14853 if (mPostSystemReadyMessages != null) { 14854 for (Message msg : mPostSystemReadyMessages) { 14855 msg.sendToTarget(); 14856 } 14857 mPostSystemReadyMessages = null; 14858 } 14859 14860 // Watch for external volumes that come and go over time 14861 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14862 storage.registerListener(mStorageListener); 14863 14864 mInstallerService.systemReady(); 14865 mPackageDexOptimizer.systemReady(); 14866 14867 MountServiceInternal mountServiceInternal = LocalServices.getService( 14868 MountServiceInternal.class); 14869 mountServiceInternal.addExternalStoragePolicy( 14870 new MountServiceInternal.ExternalStorageMountPolicy() { 14871 @Override 14872 public int getMountMode(int uid, String packageName) { 14873 if (Process.isIsolated(uid)) { 14874 return Zygote.MOUNT_EXTERNAL_NONE; 14875 } 14876 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14877 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14878 } 14879 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14880 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14881 } 14882 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14883 return Zygote.MOUNT_EXTERNAL_READ; 14884 } 14885 return Zygote.MOUNT_EXTERNAL_WRITE; 14886 } 14887 14888 @Override 14889 public boolean hasExternalStorage(int uid, String packageName) { 14890 return true; 14891 } 14892 }); 14893 } 14894 14895 @Override 14896 public boolean isSafeMode() { 14897 return mSafeMode; 14898 } 14899 14900 @Override 14901 public boolean hasSystemUidErrors() { 14902 return mHasSystemUidErrors; 14903 } 14904 14905 static String arrayToString(int[] array) { 14906 StringBuffer buf = new StringBuffer(128); 14907 buf.append('['); 14908 if (array != null) { 14909 for (int i=0; i<array.length; i++) { 14910 if (i > 0) buf.append(", "); 14911 buf.append(array[i]); 14912 } 14913 } 14914 buf.append(']'); 14915 return buf.toString(); 14916 } 14917 14918 static class DumpState { 14919 public static final int DUMP_LIBS = 1 << 0; 14920 public static final int DUMP_FEATURES = 1 << 1; 14921 public static final int DUMP_RESOLVERS = 1 << 2; 14922 public static final int DUMP_PERMISSIONS = 1 << 3; 14923 public static final int DUMP_PACKAGES = 1 << 4; 14924 public static final int DUMP_SHARED_USERS = 1 << 5; 14925 public static final int DUMP_MESSAGES = 1 << 6; 14926 public static final int DUMP_PROVIDERS = 1 << 7; 14927 public static final int DUMP_VERIFIERS = 1 << 8; 14928 public static final int DUMP_PREFERRED = 1 << 9; 14929 public static final int DUMP_PREFERRED_XML = 1 << 10; 14930 public static final int DUMP_KEYSETS = 1 << 11; 14931 public static final int DUMP_VERSION = 1 << 12; 14932 public static final int DUMP_INSTALLS = 1 << 13; 14933 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14934 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14935 14936 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14937 14938 private int mTypes; 14939 14940 private int mOptions; 14941 14942 private boolean mTitlePrinted; 14943 14944 private SharedUserSetting mSharedUser; 14945 14946 public boolean isDumping(int type) { 14947 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14948 return true; 14949 } 14950 14951 return (mTypes & type) != 0; 14952 } 14953 14954 public void setDump(int type) { 14955 mTypes |= type; 14956 } 14957 14958 public boolean isOptionEnabled(int option) { 14959 return (mOptions & option) != 0; 14960 } 14961 14962 public void setOptionEnabled(int option) { 14963 mOptions |= option; 14964 } 14965 14966 public boolean onTitlePrinted() { 14967 final boolean printed = mTitlePrinted; 14968 mTitlePrinted = true; 14969 return printed; 14970 } 14971 14972 public boolean getTitlePrinted() { 14973 return mTitlePrinted; 14974 } 14975 14976 public void setTitlePrinted(boolean enabled) { 14977 mTitlePrinted = enabled; 14978 } 14979 14980 public SharedUserSetting getSharedUser() { 14981 return mSharedUser; 14982 } 14983 14984 public void setSharedUser(SharedUserSetting user) { 14985 mSharedUser = user; 14986 } 14987 } 14988 14989 @Override 14990 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14991 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14992 != PackageManager.PERMISSION_GRANTED) { 14993 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14994 + Binder.getCallingPid() 14995 + ", uid=" + Binder.getCallingUid() 14996 + " without permission " 14997 + android.Manifest.permission.DUMP); 14998 return; 14999 } 15000 15001 DumpState dumpState = new DumpState(); 15002 boolean fullPreferred = false; 15003 boolean checkin = false; 15004 15005 String packageName = null; 15006 ArraySet<String> permissionNames = null; 15007 15008 int opti = 0; 15009 while (opti < args.length) { 15010 String opt = args[opti]; 15011 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15012 break; 15013 } 15014 opti++; 15015 15016 if ("-a".equals(opt)) { 15017 // Right now we only know how to print all. 15018 } else if ("-h".equals(opt)) { 15019 pw.println("Package manager dump options:"); 15020 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15021 pw.println(" --checkin: dump for a checkin"); 15022 pw.println(" -f: print details of intent filters"); 15023 pw.println(" -h: print this help"); 15024 pw.println(" cmd may be one of:"); 15025 pw.println(" l[ibraries]: list known shared libraries"); 15026 pw.println(" f[ibraries]: list device features"); 15027 pw.println(" k[eysets]: print known keysets"); 15028 pw.println(" r[esolvers]: dump intent resolvers"); 15029 pw.println(" perm[issions]: dump permissions"); 15030 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15031 pw.println(" pref[erred]: print preferred package settings"); 15032 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15033 pw.println(" prov[iders]: dump content providers"); 15034 pw.println(" p[ackages]: dump installed packages"); 15035 pw.println(" s[hared-users]: dump shared user IDs"); 15036 pw.println(" m[essages]: print collected runtime messages"); 15037 pw.println(" v[erifiers]: print package verifier info"); 15038 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15039 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15040 pw.println(" version: print database version info"); 15041 pw.println(" write: write current settings now"); 15042 pw.println(" installs: details about install sessions"); 15043 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15044 pw.println(" <package.name>: info about given package"); 15045 return; 15046 } else if ("--checkin".equals(opt)) { 15047 checkin = true; 15048 } else if ("-f".equals(opt)) { 15049 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15050 } else { 15051 pw.println("Unknown argument: " + opt + "; use -h for help"); 15052 } 15053 } 15054 15055 // Is the caller requesting to dump a particular piece of data? 15056 if (opti < args.length) { 15057 String cmd = args[opti]; 15058 opti++; 15059 // Is this a package name? 15060 if ("android".equals(cmd) || cmd.contains(".")) { 15061 packageName = cmd; 15062 // When dumping a single package, we always dump all of its 15063 // filter information since the amount of data will be reasonable. 15064 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15065 } else if ("check-permission".equals(cmd)) { 15066 if (opti >= args.length) { 15067 pw.println("Error: check-permission missing permission argument"); 15068 return; 15069 } 15070 String perm = args[opti]; 15071 opti++; 15072 if (opti >= args.length) { 15073 pw.println("Error: check-permission missing package argument"); 15074 return; 15075 } 15076 String pkg = args[opti]; 15077 opti++; 15078 int user = UserHandle.getUserId(Binder.getCallingUid()); 15079 if (opti < args.length) { 15080 try { 15081 user = Integer.parseInt(args[opti]); 15082 } catch (NumberFormatException e) { 15083 pw.println("Error: check-permission user argument is not a number: " 15084 + args[opti]); 15085 return; 15086 } 15087 } 15088 pw.println(checkPermission(perm, pkg, user)); 15089 return; 15090 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15091 dumpState.setDump(DumpState.DUMP_LIBS); 15092 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15093 dumpState.setDump(DumpState.DUMP_FEATURES); 15094 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15095 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15096 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15097 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15098 } else if ("permission".equals(cmd)) { 15099 if (opti >= args.length) { 15100 pw.println("Error: permission requires permission name"); 15101 return; 15102 } 15103 permissionNames = new ArraySet<>(); 15104 while (opti < args.length) { 15105 permissionNames.add(args[opti]); 15106 opti++; 15107 } 15108 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15109 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15110 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15111 dumpState.setDump(DumpState.DUMP_PREFERRED); 15112 } else if ("preferred-xml".equals(cmd)) { 15113 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15114 if (opti < args.length && "--full".equals(args[opti])) { 15115 fullPreferred = true; 15116 opti++; 15117 } 15118 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15119 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15120 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15121 dumpState.setDump(DumpState.DUMP_PACKAGES); 15122 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15123 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15124 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15125 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15126 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15127 dumpState.setDump(DumpState.DUMP_MESSAGES); 15128 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15129 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15130 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15131 || "intent-filter-verifiers".equals(cmd)) { 15132 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15133 } else if ("version".equals(cmd)) { 15134 dumpState.setDump(DumpState.DUMP_VERSION); 15135 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15136 dumpState.setDump(DumpState.DUMP_KEYSETS); 15137 } else if ("installs".equals(cmd)) { 15138 dumpState.setDump(DumpState.DUMP_INSTALLS); 15139 } else if ("write".equals(cmd)) { 15140 synchronized (mPackages) { 15141 mSettings.writeLPr(); 15142 pw.println("Settings written."); 15143 return; 15144 } 15145 } 15146 } 15147 15148 if (checkin) { 15149 pw.println("vers,1"); 15150 } 15151 15152 // reader 15153 synchronized (mPackages) { 15154 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15155 if (!checkin) { 15156 if (dumpState.onTitlePrinted()) 15157 pw.println(); 15158 pw.println("Database versions:"); 15159 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15160 } 15161 } 15162 15163 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15164 if (!checkin) { 15165 if (dumpState.onTitlePrinted()) 15166 pw.println(); 15167 pw.println("Verifiers:"); 15168 pw.print(" Required: "); 15169 pw.print(mRequiredVerifierPackage); 15170 pw.print(" (uid="); 15171 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15172 pw.println(")"); 15173 } else if (mRequiredVerifierPackage != null) { 15174 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15175 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15176 } 15177 } 15178 15179 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15180 packageName == null) { 15181 if (mIntentFilterVerifierComponent != null) { 15182 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15183 if (!checkin) { 15184 if (dumpState.onTitlePrinted()) 15185 pw.println(); 15186 pw.println("Intent Filter Verifier:"); 15187 pw.print(" Using: "); 15188 pw.print(verifierPackageName); 15189 pw.print(" (uid="); 15190 pw.print(getPackageUid(verifierPackageName, 0)); 15191 pw.println(")"); 15192 } else if (verifierPackageName != null) { 15193 pw.print("ifv,"); pw.print(verifierPackageName); 15194 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15195 } 15196 } else { 15197 pw.println(); 15198 pw.println("No Intent Filter Verifier available!"); 15199 } 15200 } 15201 15202 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15203 boolean printedHeader = false; 15204 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15205 while (it.hasNext()) { 15206 String name = it.next(); 15207 SharedLibraryEntry ent = mSharedLibraries.get(name); 15208 if (!checkin) { 15209 if (!printedHeader) { 15210 if (dumpState.onTitlePrinted()) 15211 pw.println(); 15212 pw.println("Libraries:"); 15213 printedHeader = true; 15214 } 15215 pw.print(" "); 15216 } else { 15217 pw.print("lib,"); 15218 } 15219 pw.print(name); 15220 if (!checkin) { 15221 pw.print(" -> "); 15222 } 15223 if (ent.path != null) { 15224 if (!checkin) { 15225 pw.print("(jar) "); 15226 pw.print(ent.path); 15227 } else { 15228 pw.print(",jar,"); 15229 pw.print(ent.path); 15230 } 15231 } else { 15232 if (!checkin) { 15233 pw.print("(apk) "); 15234 pw.print(ent.apk); 15235 } else { 15236 pw.print(",apk,"); 15237 pw.print(ent.apk); 15238 } 15239 } 15240 pw.println(); 15241 } 15242 } 15243 15244 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15245 if (dumpState.onTitlePrinted()) 15246 pw.println(); 15247 if (!checkin) { 15248 pw.println("Features:"); 15249 } 15250 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15251 while (it.hasNext()) { 15252 String name = it.next(); 15253 if (!checkin) { 15254 pw.print(" "); 15255 } else { 15256 pw.print("feat,"); 15257 } 15258 pw.println(name); 15259 } 15260 } 15261 15262 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15263 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15264 : "Activity Resolver Table:", " ", packageName, 15265 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15266 dumpState.setTitlePrinted(true); 15267 } 15268 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15269 : "Receiver Resolver Table:", " ", packageName, 15270 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15271 dumpState.setTitlePrinted(true); 15272 } 15273 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15274 : "Service Resolver Table:", " ", packageName, 15275 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15276 dumpState.setTitlePrinted(true); 15277 } 15278 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15279 : "Provider Resolver Table:", " ", packageName, 15280 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15281 dumpState.setTitlePrinted(true); 15282 } 15283 } 15284 15285 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15286 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15287 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15288 int user = mSettings.mPreferredActivities.keyAt(i); 15289 if (pir.dump(pw, 15290 dumpState.getTitlePrinted() 15291 ? "\nPreferred Activities User " + user + ":" 15292 : "Preferred Activities User " + user + ":", " ", 15293 packageName, true, false)) { 15294 dumpState.setTitlePrinted(true); 15295 } 15296 } 15297 } 15298 15299 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15300 pw.flush(); 15301 FileOutputStream fout = new FileOutputStream(fd); 15302 BufferedOutputStream str = new BufferedOutputStream(fout); 15303 XmlSerializer serializer = new FastXmlSerializer(); 15304 try { 15305 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15306 serializer.startDocument(null, true); 15307 serializer.setFeature( 15308 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15309 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15310 serializer.endDocument(); 15311 serializer.flush(); 15312 } catch (IllegalArgumentException e) { 15313 pw.println("Failed writing: " + e); 15314 } catch (IllegalStateException e) { 15315 pw.println("Failed writing: " + e); 15316 } catch (IOException e) { 15317 pw.println("Failed writing: " + e); 15318 } 15319 } 15320 15321 if (!checkin 15322 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15323 && packageName == null) { 15324 pw.println(); 15325 int count = mSettings.mPackages.size(); 15326 if (count == 0) { 15327 pw.println("No applications!"); 15328 pw.println(); 15329 } else { 15330 final String prefix = " "; 15331 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15332 if (allPackageSettings.size() == 0) { 15333 pw.println("No domain preferred apps!"); 15334 pw.println(); 15335 } else { 15336 pw.println("App verification status:"); 15337 pw.println(); 15338 count = 0; 15339 for (PackageSetting ps : allPackageSettings) { 15340 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15341 if (ivi == null || ivi.getPackageName() == null) continue; 15342 pw.println(prefix + "Package: " + ivi.getPackageName()); 15343 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15344 pw.println(prefix + "Status: " + ivi.getStatusString()); 15345 pw.println(); 15346 count++; 15347 } 15348 if (count == 0) { 15349 pw.println(prefix + "No app verification established."); 15350 pw.println(); 15351 } 15352 for (int userId : sUserManager.getUserIds()) { 15353 pw.println("App linkages for user " + userId + ":"); 15354 pw.println(); 15355 count = 0; 15356 for (PackageSetting ps : allPackageSettings) { 15357 final long status = ps.getDomainVerificationStatusForUser(userId); 15358 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15359 continue; 15360 } 15361 pw.println(prefix + "Package: " + ps.name); 15362 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15363 String statusStr = IntentFilterVerificationInfo. 15364 getStatusStringFromValue(status); 15365 pw.println(prefix + "Status: " + statusStr); 15366 pw.println(); 15367 count++; 15368 } 15369 if (count == 0) { 15370 pw.println(prefix + "No configured app linkages."); 15371 pw.println(); 15372 } 15373 } 15374 } 15375 } 15376 } 15377 15378 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15379 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15380 if (packageName == null && permissionNames == null) { 15381 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15382 if (iperm == 0) { 15383 if (dumpState.onTitlePrinted()) 15384 pw.println(); 15385 pw.println("AppOp Permissions:"); 15386 } 15387 pw.print(" AppOp Permission "); 15388 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15389 pw.println(":"); 15390 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15391 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15392 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15393 } 15394 } 15395 } 15396 } 15397 15398 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15399 boolean printedSomething = false; 15400 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15401 if (packageName != null && !packageName.equals(p.info.packageName)) { 15402 continue; 15403 } 15404 if (!printedSomething) { 15405 if (dumpState.onTitlePrinted()) 15406 pw.println(); 15407 pw.println("Registered ContentProviders:"); 15408 printedSomething = true; 15409 } 15410 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15411 pw.print(" "); pw.println(p.toString()); 15412 } 15413 printedSomething = false; 15414 for (Map.Entry<String, PackageParser.Provider> entry : 15415 mProvidersByAuthority.entrySet()) { 15416 PackageParser.Provider p = entry.getValue(); 15417 if (packageName != null && !packageName.equals(p.info.packageName)) { 15418 continue; 15419 } 15420 if (!printedSomething) { 15421 if (dumpState.onTitlePrinted()) 15422 pw.println(); 15423 pw.println("ContentProvider Authorities:"); 15424 printedSomething = true; 15425 } 15426 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15427 pw.print(" "); pw.println(p.toString()); 15428 if (p.info != null && p.info.applicationInfo != null) { 15429 final String appInfo = p.info.applicationInfo.toString(); 15430 pw.print(" applicationInfo="); pw.println(appInfo); 15431 } 15432 } 15433 } 15434 15435 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15436 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15437 } 15438 15439 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15440 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15441 } 15442 15443 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15444 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15445 } 15446 15447 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15448 // XXX should handle packageName != null by dumping only install data that 15449 // the given package is involved with. 15450 if (dumpState.onTitlePrinted()) pw.println(); 15451 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15452 } 15453 15454 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15455 if (dumpState.onTitlePrinted()) pw.println(); 15456 mSettings.dumpReadMessagesLPr(pw, dumpState); 15457 15458 pw.println(); 15459 pw.println("Package warning 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.println(line); 15467 } 15468 } catch (IOException ignored) { 15469 } finally { 15470 IoUtils.closeQuietly(in); 15471 } 15472 } 15473 15474 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15475 BufferedReader in = null; 15476 String line = null; 15477 try { 15478 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15479 while ((line = in.readLine()) != null) { 15480 if (line.contains("ignored: updated version")) continue; 15481 pw.print("msg,"); 15482 pw.println(line); 15483 } 15484 } catch (IOException ignored) { 15485 } finally { 15486 IoUtils.closeQuietly(in); 15487 } 15488 } 15489 } 15490 } 15491 15492 private String dumpDomainString(String packageName) { 15493 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15494 List<IntentFilter> filters = getAllIntentFilters(packageName); 15495 15496 ArraySet<String> result = new ArraySet<>(); 15497 if (iviList.size() > 0) { 15498 for (IntentFilterVerificationInfo ivi : iviList) { 15499 for (String host : ivi.getDomains()) { 15500 result.add(host); 15501 } 15502 } 15503 } 15504 if (filters != null && filters.size() > 0) { 15505 for (IntentFilter filter : filters) { 15506 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15507 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15508 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15509 result.addAll(filter.getHostsList()); 15510 } 15511 } 15512 } 15513 15514 StringBuilder sb = new StringBuilder(result.size() * 16); 15515 for (String domain : result) { 15516 if (sb.length() > 0) sb.append(" "); 15517 sb.append(domain); 15518 } 15519 return sb.toString(); 15520 } 15521 15522 // ------- apps on sdcard specific code ------- 15523 static final boolean DEBUG_SD_INSTALL = false; 15524 15525 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15526 15527 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15528 15529 private boolean mMediaMounted = false; 15530 15531 static String getEncryptKey() { 15532 try { 15533 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15534 SD_ENCRYPTION_KEYSTORE_NAME); 15535 if (sdEncKey == null) { 15536 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15537 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15538 if (sdEncKey == null) { 15539 Slog.e(TAG, "Failed to create encryption keys"); 15540 return null; 15541 } 15542 } 15543 return sdEncKey; 15544 } catch (NoSuchAlgorithmException nsae) { 15545 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15546 return null; 15547 } catch (IOException ioe) { 15548 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15549 return null; 15550 } 15551 } 15552 15553 /* 15554 * Update media status on PackageManager. 15555 */ 15556 @Override 15557 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15558 int callingUid = Binder.getCallingUid(); 15559 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15560 throw new SecurityException("Media status can only be updated by the system"); 15561 } 15562 // reader; this apparently protects mMediaMounted, but should probably 15563 // be a different lock in that case. 15564 synchronized (mPackages) { 15565 Log.i(TAG, "Updating external media status from " 15566 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15567 + (mediaStatus ? "mounted" : "unmounted")); 15568 if (DEBUG_SD_INSTALL) 15569 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15570 + ", mMediaMounted=" + mMediaMounted); 15571 if (mediaStatus == mMediaMounted) { 15572 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15573 : 0, -1); 15574 mHandler.sendMessage(msg); 15575 return; 15576 } 15577 mMediaMounted = mediaStatus; 15578 } 15579 // Queue up an async operation since the package installation may take a 15580 // little while. 15581 mHandler.post(new Runnable() { 15582 public void run() { 15583 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15584 } 15585 }); 15586 } 15587 15588 /** 15589 * Called by MountService when the initial ASECs to scan are available. 15590 * Should block until all the ASEC containers are finished being scanned. 15591 */ 15592 public void scanAvailableAsecs() { 15593 updateExternalMediaStatusInner(true, false, false); 15594 if (mShouldRestoreconData) { 15595 SELinuxMMAC.setRestoreconDone(); 15596 mShouldRestoreconData = false; 15597 } 15598 } 15599 15600 /* 15601 * Collect information of applications on external media, map them against 15602 * existing containers and update information based on current mount status. 15603 * Please note that we always have to report status if reportStatus has been 15604 * set to true especially when unloading packages. 15605 */ 15606 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15607 boolean externalStorage) { 15608 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15609 int[] uidArr = EmptyArray.INT; 15610 15611 final String[] list = PackageHelper.getSecureContainerList(); 15612 if (ArrayUtils.isEmpty(list)) { 15613 Log.i(TAG, "No secure containers found"); 15614 } else { 15615 // Process list of secure containers and categorize them 15616 // as active or stale based on their package internal state. 15617 15618 // reader 15619 synchronized (mPackages) { 15620 for (String cid : list) { 15621 // Leave stages untouched for now; installer service owns them 15622 if (PackageInstallerService.isStageName(cid)) continue; 15623 15624 if (DEBUG_SD_INSTALL) 15625 Log.i(TAG, "Processing container " + cid); 15626 String pkgName = getAsecPackageName(cid); 15627 if (pkgName == null) { 15628 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15629 continue; 15630 } 15631 if (DEBUG_SD_INSTALL) 15632 Log.i(TAG, "Looking for pkg : " + pkgName); 15633 15634 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15635 if (ps == null) { 15636 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15637 continue; 15638 } 15639 15640 /* 15641 * Skip packages that are not external if we're unmounting 15642 * external storage. 15643 */ 15644 if (externalStorage && !isMounted && !isExternal(ps)) { 15645 continue; 15646 } 15647 15648 final AsecInstallArgs args = new AsecInstallArgs(cid, 15649 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15650 // The package status is changed only if the code path 15651 // matches between settings and the container id. 15652 if (ps.codePathString != null 15653 && ps.codePathString.startsWith(args.getCodePath())) { 15654 if (DEBUG_SD_INSTALL) { 15655 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15656 + " at code path: " + ps.codePathString); 15657 } 15658 15659 // We do have a valid package installed on sdcard 15660 processCids.put(args, ps.codePathString); 15661 final int uid = ps.appId; 15662 if (uid != -1) { 15663 uidArr = ArrayUtils.appendInt(uidArr, uid); 15664 } 15665 } else { 15666 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15667 + ps.codePathString); 15668 } 15669 } 15670 } 15671 15672 Arrays.sort(uidArr); 15673 } 15674 15675 // Process packages with valid entries. 15676 if (isMounted) { 15677 if (DEBUG_SD_INSTALL) 15678 Log.i(TAG, "Loading packages"); 15679 loadMediaPackages(processCids, uidArr); 15680 startCleaningPackages(); 15681 mInstallerService.onSecureContainersAvailable(); 15682 } else { 15683 if (DEBUG_SD_INSTALL) 15684 Log.i(TAG, "Unloading packages"); 15685 unloadMediaPackages(processCids, uidArr, reportStatus); 15686 } 15687 } 15688 15689 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15690 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15691 final int size = infos.size(); 15692 final String[] packageNames = new String[size]; 15693 final int[] packageUids = new int[size]; 15694 for (int i = 0; i < size; i++) { 15695 final ApplicationInfo info = infos.get(i); 15696 packageNames[i] = info.packageName; 15697 packageUids[i] = info.uid; 15698 } 15699 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15700 finishedReceiver); 15701 } 15702 15703 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15704 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15705 sendResourcesChangedBroadcast(mediaStatus, replacing, 15706 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15707 } 15708 15709 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15710 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15711 int size = pkgList.length; 15712 if (size > 0) { 15713 // Send broadcasts here 15714 Bundle extras = new Bundle(); 15715 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15716 if (uidArr != null) { 15717 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15718 } 15719 if (replacing) { 15720 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15721 } 15722 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15723 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15724 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15725 } 15726 } 15727 15728 /* 15729 * Look at potentially valid container ids from processCids If package 15730 * information doesn't match the one on record or package scanning fails, 15731 * the cid is added to list of removeCids. We currently don't delete stale 15732 * containers. 15733 */ 15734 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15735 ArrayList<String> pkgList = new ArrayList<String>(); 15736 Set<AsecInstallArgs> keys = processCids.keySet(); 15737 15738 for (AsecInstallArgs args : keys) { 15739 String codePath = processCids.get(args); 15740 if (DEBUG_SD_INSTALL) 15741 Log.i(TAG, "Loading container : " + args.cid); 15742 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15743 try { 15744 // Make sure there are no container errors first. 15745 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15746 Slog.e(TAG, "Failed to mount cid : " + args.cid 15747 + " when installing from sdcard"); 15748 continue; 15749 } 15750 // Check code path here. 15751 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15752 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15753 + " does not match one in settings " + codePath); 15754 continue; 15755 } 15756 // Parse package 15757 int parseFlags = mDefParseFlags; 15758 if (args.isExternalAsec()) { 15759 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15760 } 15761 if (args.isFwdLocked()) { 15762 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15763 } 15764 15765 synchronized (mInstallLock) { 15766 PackageParser.Package pkg = null; 15767 try { 15768 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15769 } catch (PackageManagerException e) { 15770 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15771 } 15772 // Scan the package 15773 if (pkg != null) { 15774 /* 15775 * TODO why is the lock being held? doPostInstall is 15776 * called in other places without the lock. This needs 15777 * to be straightened out. 15778 */ 15779 // writer 15780 synchronized (mPackages) { 15781 retCode = PackageManager.INSTALL_SUCCEEDED; 15782 pkgList.add(pkg.packageName); 15783 // Post process args 15784 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15785 pkg.applicationInfo.uid); 15786 } 15787 } else { 15788 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15789 } 15790 } 15791 15792 } finally { 15793 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15794 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15795 } 15796 } 15797 } 15798 // writer 15799 synchronized (mPackages) { 15800 // If the platform SDK has changed since the last time we booted, 15801 // we need to re-grant app permission to catch any new ones that 15802 // appear. This is really a hack, and means that apps can in some 15803 // cases get permissions that the user didn't initially explicitly 15804 // allow... it would be nice to have some better way to handle 15805 // this situation. 15806 final VersionInfo ver = mSettings.getExternalVersion(); 15807 15808 int updateFlags = UPDATE_PERMISSIONS_ALL; 15809 if (ver.sdkVersion != mSdkVersion) { 15810 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15811 + mSdkVersion + "; regranting permissions for external"); 15812 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15813 } 15814 updatePermissionsLPw(null, null, updateFlags); 15815 15816 // Yay, everything is now upgraded 15817 ver.forceCurrent(); 15818 15819 // can downgrade to reader 15820 // Persist settings 15821 mSettings.writeLPr(); 15822 } 15823 // Send a broadcast to let everyone know we are done processing 15824 if (pkgList.size() > 0) { 15825 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15826 } 15827 } 15828 15829 /* 15830 * Utility method to unload a list of specified containers 15831 */ 15832 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15833 // Just unmount all valid containers. 15834 for (AsecInstallArgs arg : cidArgs) { 15835 synchronized (mInstallLock) { 15836 arg.doPostDeleteLI(false); 15837 } 15838 } 15839 } 15840 15841 /* 15842 * Unload packages mounted on external media. This involves deleting package 15843 * data from internal structures, sending broadcasts about diabled packages, 15844 * gc'ing to free up references, unmounting all secure containers 15845 * corresponding to packages on external media, and posting a 15846 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15847 * that we always have to post this message if status has been requested no 15848 * matter what. 15849 */ 15850 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15851 final boolean reportStatus) { 15852 if (DEBUG_SD_INSTALL) 15853 Log.i(TAG, "unloading media packages"); 15854 ArrayList<String> pkgList = new ArrayList<String>(); 15855 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15856 final Set<AsecInstallArgs> keys = processCids.keySet(); 15857 for (AsecInstallArgs args : keys) { 15858 String pkgName = args.getPackageName(); 15859 if (DEBUG_SD_INSTALL) 15860 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15861 // Delete package internally 15862 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15863 synchronized (mInstallLock) { 15864 boolean res = deletePackageLI(pkgName, null, false, null, null, 15865 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15866 if (res) { 15867 pkgList.add(pkgName); 15868 } else { 15869 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15870 failedList.add(args); 15871 } 15872 } 15873 } 15874 15875 // reader 15876 synchronized (mPackages) { 15877 // We didn't update the settings after removing each package; 15878 // write them now for all packages. 15879 mSettings.writeLPr(); 15880 } 15881 15882 // We have to absolutely send UPDATED_MEDIA_STATUS only 15883 // after confirming that all the receivers processed the ordered 15884 // broadcast when packages get disabled, force a gc to clean things up. 15885 // and unload all the containers. 15886 if (pkgList.size() > 0) { 15887 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15888 new IIntentReceiver.Stub() { 15889 public void performReceive(Intent intent, int resultCode, String data, 15890 Bundle extras, boolean ordered, boolean sticky, 15891 int sendingUser) throws RemoteException { 15892 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15893 reportStatus ? 1 : 0, 1, keys); 15894 mHandler.sendMessage(msg); 15895 } 15896 }); 15897 } else { 15898 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15899 keys); 15900 mHandler.sendMessage(msg); 15901 } 15902 } 15903 15904 private void loadPrivatePackages(VolumeInfo vol) { 15905 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15906 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15907 synchronized (mInstallLock) { 15908 synchronized (mPackages) { 15909 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15910 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15911 for (PackageSetting ps : packages) { 15912 final PackageParser.Package pkg; 15913 try { 15914 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15915 loaded.add(pkg.applicationInfo); 15916 } catch (PackageManagerException e) { 15917 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15918 } 15919 15920 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15921 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15922 } 15923 } 15924 15925 int updateFlags = UPDATE_PERMISSIONS_ALL; 15926 if (ver.sdkVersion != mSdkVersion) { 15927 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15928 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15929 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15930 } 15931 updatePermissionsLPw(null, null, updateFlags); 15932 15933 // Yay, everything is now upgraded 15934 ver.forceCurrent(); 15935 15936 mSettings.writeLPr(); 15937 } 15938 } 15939 15940 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15941 sendResourcesChangedBroadcast(true, false, loaded, null); 15942 } 15943 15944 private void unloadPrivatePackages(VolumeInfo vol) { 15945 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15946 synchronized (mInstallLock) { 15947 synchronized (mPackages) { 15948 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15949 for (PackageSetting ps : packages) { 15950 if (ps.pkg == null) continue; 15951 15952 final ApplicationInfo info = ps.pkg.applicationInfo; 15953 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15954 if (deletePackageLI(ps.name, null, false, null, null, 15955 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15956 unloaded.add(info); 15957 } else { 15958 Slog.w(TAG, "Failed to unload " + ps.codePath); 15959 } 15960 } 15961 15962 mSettings.writeLPr(); 15963 } 15964 } 15965 15966 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15967 sendResourcesChangedBroadcast(false, false, unloaded, null); 15968 } 15969 15970 /** 15971 * Examine all users present on given mounted volume, and destroy data 15972 * belonging to users that are no longer valid, or whose user ID has been 15973 * recycled. 15974 */ 15975 private void reconcileUsers(String volumeUuid) { 15976 final File[] files = FileUtils 15977 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15978 for (File file : files) { 15979 if (!file.isDirectory()) continue; 15980 15981 final int userId; 15982 final UserInfo info; 15983 try { 15984 userId = Integer.parseInt(file.getName()); 15985 info = sUserManager.getUserInfo(userId); 15986 } catch (NumberFormatException e) { 15987 Slog.w(TAG, "Invalid user directory " + file); 15988 continue; 15989 } 15990 15991 boolean destroyUser = false; 15992 if (info == null) { 15993 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15994 + " because no matching user was found"); 15995 destroyUser = true; 15996 } else { 15997 try { 15998 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15999 } catch (IOException e) { 16000 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16001 + " because we failed to enforce serial number: " + e); 16002 destroyUser = true; 16003 } 16004 } 16005 16006 if (destroyUser) { 16007 synchronized (mInstallLock) { 16008 mInstaller.removeUserDataDirs(volumeUuid, userId); 16009 } 16010 } 16011 } 16012 16013 final UserManager um = mContext.getSystemService(UserManager.class); 16014 for (UserInfo user : um.getUsers()) { 16015 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16016 if (userDir.exists()) continue; 16017 16018 try { 16019 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 16020 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16021 } catch (IOException e) { 16022 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16023 } 16024 } 16025 } 16026 16027 /** 16028 * Examine all apps present on given mounted volume, and destroy apps that 16029 * aren't expected, either due to uninstallation or reinstallation on 16030 * another volume. 16031 */ 16032 private void reconcileApps(String volumeUuid) { 16033 final File[] files = FileUtils 16034 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16035 for (File file : files) { 16036 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16037 && !PackageInstallerService.isStageName(file.getName()); 16038 if (!isPackage) { 16039 // Ignore entries which are not packages 16040 continue; 16041 } 16042 16043 boolean destroyApp = false; 16044 String packageName = null; 16045 try { 16046 final PackageLite pkg = PackageParser.parsePackageLite(file, 16047 PackageParser.PARSE_MUST_BE_APK); 16048 packageName = pkg.packageName; 16049 16050 synchronized (mPackages) { 16051 final PackageSetting ps = mSettings.mPackages.get(packageName); 16052 if (ps == null) { 16053 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16054 + volumeUuid + " because we found no install record"); 16055 destroyApp = true; 16056 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16057 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16058 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16059 destroyApp = true; 16060 } 16061 } 16062 16063 } catch (PackageParserException e) { 16064 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16065 destroyApp = true; 16066 } 16067 16068 if (destroyApp) { 16069 synchronized (mInstallLock) { 16070 if (packageName != null) { 16071 removeDataDirsLI(volumeUuid, packageName); 16072 } 16073 if (file.isDirectory()) { 16074 mInstaller.rmPackageDir(file.getAbsolutePath()); 16075 } else { 16076 file.delete(); 16077 } 16078 } 16079 } 16080 } 16081 } 16082 16083 private void unfreezePackage(String packageName) { 16084 synchronized (mPackages) { 16085 final PackageSetting ps = mSettings.mPackages.get(packageName); 16086 if (ps != null) { 16087 ps.frozen = false; 16088 } 16089 } 16090 } 16091 16092 @Override 16093 public int movePackage(final String packageName, final String volumeUuid) { 16094 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16095 16096 final int moveId = mNextMoveId.getAndIncrement(); 16097 try { 16098 movePackageInternal(packageName, volumeUuid, moveId); 16099 } catch (PackageManagerException e) { 16100 Slog.w(TAG, "Failed to move " + packageName, e); 16101 mMoveCallbacks.notifyStatusChanged(moveId, 16102 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16103 } 16104 return moveId; 16105 } 16106 16107 private void movePackageInternal(final String packageName, final String volumeUuid, 16108 final int moveId) throws PackageManagerException { 16109 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16110 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16111 final PackageManager pm = mContext.getPackageManager(); 16112 16113 final boolean currentAsec; 16114 final String currentVolumeUuid; 16115 final File codeFile; 16116 final String installerPackageName; 16117 final String packageAbiOverride; 16118 final int appId; 16119 final String seinfo; 16120 final String label; 16121 16122 // reader 16123 synchronized (mPackages) { 16124 final PackageParser.Package pkg = mPackages.get(packageName); 16125 final PackageSetting ps = mSettings.mPackages.get(packageName); 16126 if (pkg == null || ps == null) { 16127 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16128 } 16129 16130 if (pkg.applicationInfo.isSystemApp()) { 16131 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16132 "Cannot move system application"); 16133 } 16134 16135 if (pkg.applicationInfo.isExternalAsec()) { 16136 currentAsec = true; 16137 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16138 } else if (pkg.applicationInfo.isForwardLocked()) { 16139 currentAsec = true; 16140 currentVolumeUuid = "forward_locked"; 16141 } else { 16142 currentAsec = false; 16143 currentVolumeUuid = ps.volumeUuid; 16144 16145 final File probe = new File(pkg.codePath); 16146 final File probeOat = new File(probe, "oat"); 16147 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16148 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16149 "Move only supported for modern cluster style installs"); 16150 } 16151 } 16152 16153 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16154 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16155 "Package already moved to " + volumeUuid); 16156 } 16157 16158 if (ps.frozen) { 16159 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16160 "Failed to move already frozen package"); 16161 } 16162 ps.frozen = true; 16163 16164 codeFile = new File(pkg.codePath); 16165 installerPackageName = ps.installerPackageName; 16166 packageAbiOverride = ps.cpuAbiOverrideString; 16167 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16168 seinfo = pkg.applicationInfo.seinfo; 16169 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16170 } 16171 16172 // Now that we're guarded by frozen state, kill app during move 16173 final long token = Binder.clearCallingIdentity(); 16174 try { 16175 killApplication(packageName, appId, "move pkg"); 16176 } finally { 16177 Binder.restoreCallingIdentity(token); 16178 } 16179 16180 final Bundle extras = new Bundle(); 16181 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16182 extras.putString(Intent.EXTRA_TITLE, label); 16183 mMoveCallbacks.notifyCreated(moveId, extras); 16184 16185 int installFlags; 16186 final boolean moveCompleteApp; 16187 final File measurePath; 16188 16189 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16190 installFlags = INSTALL_INTERNAL; 16191 moveCompleteApp = !currentAsec; 16192 measurePath = Environment.getDataAppDirectory(volumeUuid); 16193 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16194 installFlags = INSTALL_EXTERNAL; 16195 moveCompleteApp = false; 16196 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16197 } else { 16198 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16199 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16200 || !volume.isMountedWritable()) { 16201 unfreezePackage(packageName); 16202 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16203 "Move location not mounted private volume"); 16204 } 16205 16206 Preconditions.checkState(!currentAsec); 16207 16208 installFlags = INSTALL_INTERNAL; 16209 moveCompleteApp = true; 16210 measurePath = Environment.getDataAppDirectory(volumeUuid); 16211 } 16212 16213 final PackageStats stats = new PackageStats(null, -1); 16214 synchronized (mInstaller) { 16215 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16216 unfreezePackage(packageName); 16217 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16218 "Failed to measure package size"); 16219 } 16220 } 16221 16222 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16223 + stats.dataSize); 16224 16225 final long startFreeBytes = measurePath.getFreeSpace(); 16226 final long sizeBytes; 16227 if (moveCompleteApp) { 16228 sizeBytes = stats.codeSize + stats.dataSize; 16229 } else { 16230 sizeBytes = stats.codeSize; 16231 } 16232 16233 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16234 unfreezePackage(packageName); 16235 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16236 "Not enough free space to move"); 16237 } 16238 16239 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16240 16241 final CountDownLatch installedLatch = new CountDownLatch(1); 16242 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16243 @Override 16244 public void onUserActionRequired(Intent intent) throws RemoteException { 16245 throw new IllegalStateException(); 16246 } 16247 16248 @Override 16249 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16250 Bundle extras) throws RemoteException { 16251 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16252 + PackageManager.installStatusToString(returnCode, msg)); 16253 16254 installedLatch.countDown(); 16255 16256 // Regardless of success or failure of the move operation, 16257 // always unfreeze the package 16258 unfreezePackage(packageName); 16259 16260 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16261 switch (status) { 16262 case PackageInstaller.STATUS_SUCCESS: 16263 mMoveCallbacks.notifyStatusChanged(moveId, 16264 PackageManager.MOVE_SUCCEEDED); 16265 break; 16266 case PackageInstaller.STATUS_FAILURE_STORAGE: 16267 mMoveCallbacks.notifyStatusChanged(moveId, 16268 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16269 break; 16270 default: 16271 mMoveCallbacks.notifyStatusChanged(moveId, 16272 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16273 break; 16274 } 16275 } 16276 }; 16277 16278 final MoveInfo move; 16279 if (moveCompleteApp) { 16280 // Kick off a thread to report progress estimates 16281 new Thread() { 16282 @Override 16283 public void run() { 16284 while (true) { 16285 try { 16286 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16287 break; 16288 } 16289 } catch (InterruptedException ignored) { 16290 } 16291 16292 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16293 final int progress = 10 + (int) MathUtils.constrain( 16294 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16295 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16296 } 16297 } 16298 }.start(); 16299 16300 final String dataAppName = codeFile.getName(); 16301 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16302 dataAppName, appId, seinfo); 16303 } else { 16304 move = null; 16305 } 16306 16307 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16308 16309 final Message msg = mHandler.obtainMessage(INIT_COPY); 16310 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16311 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16312 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16313 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16314 msg.obj = params; 16315 16316 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16317 System.identityHashCode(msg.obj)); 16318 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16319 System.identityHashCode(msg.obj)); 16320 16321 mHandler.sendMessage(msg); 16322 } 16323 16324 @Override 16325 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16326 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16327 16328 final int realMoveId = mNextMoveId.getAndIncrement(); 16329 final Bundle extras = new Bundle(); 16330 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16331 mMoveCallbacks.notifyCreated(realMoveId, extras); 16332 16333 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16334 @Override 16335 public void onCreated(int moveId, Bundle extras) { 16336 // Ignored 16337 } 16338 16339 @Override 16340 public void onStatusChanged(int moveId, int status, long estMillis) { 16341 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16342 } 16343 }; 16344 16345 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16346 storage.setPrimaryStorageUuid(volumeUuid, callback); 16347 return realMoveId; 16348 } 16349 16350 @Override 16351 public int getMoveStatus(int moveId) { 16352 mContext.enforceCallingOrSelfPermission( 16353 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16354 return mMoveCallbacks.mLastStatus.get(moveId); 16355 } 16356 16357 @Override 16358 public void registerMoveCallback(IPackageMoveObserver callback) { 16359 mContext.enforceCallingOrSelfPermission( 16360 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16361 mMoveCallbacks.register(callback); 16362 } 16363 16364 @Override 16365 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16366 mContext.enforceCallingOrSelfPermission( 16367 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16368 mMoveCallbacks.unregister(callback); 16369 } 16370 16371 @Override 16372 public boolean setInstallLocation(int loc) { 16373 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16374 null); 16375 if (getInstallLocation() == loc) { 16376 return true; 16377 } 16378 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16379 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16380 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16381 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16382 return true; 16383 } 16384 return false; 16385 } 16386 16387 @Override 16388 public int getInstallLocation() { 16389 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16390 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16391 PackageHelper.APP_INSTALL_AUTO); 16392 } 16393 16394 /** Called by UserManagerService */ 16395 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16396 mDirtyUsers.remove(userHandle); 16397 mSettings.removeUserLPw(userHandle); 16398 mPendingBroadcasts.remove(userHandle); 16399 if (mInstaller != null) { 16400 // Technically, we shouldn't be doing this with the package lock 16401 // held. However, this is very rare, and there is already so much 16402 // other disk I/O going on, that we'll let it slide for now. 16403 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16404 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16405 final String volumeUuid = vol.getFsUuid(); 16406 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16407 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16408 } 16409 } 16410 mUserNeedsBadging.delete(userHandle); 16411 removeUnusedPackagesLILPw(userManager, userHandle); 16412 } 16413 16414 /** 16415 * We're removing userHandle and would like to remove any downloaded packages 16416 * that are no longer in use by any other user. 16417 * @param userHandle the user being removed 16418 */ 16419 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16420 final boolean DEBUG_CLEAN_APKS = false; 16421 int [] users = userManager.getUserIdsLPr(); 16422 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16423 while (psit.hasNext()) { 16424 PackageSetting ps = psit.next(); 16425 if (ps.pkg == null) { 16426 continue; 16427 } 16428 final String packageName = ps.pkg.packageName; 16429 // Skip over if system app 16430 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16431 continue; 16432 } 16433 if (DEBUG_CLEAN_APKS) { 16434 Slog.i(TAG, "Checking package " + packageName); 16435 } 16436 boolean keep = false; 16437 for (int i = 0; i < users.length; i++) { 16438 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16439 keep = true; 16440 if (DEBUG_CLEAN_APKS) { 16441 Slog.i(TAG, " Keeping package " + packageName + " for user " 16442 + users[i]); 16443 } 16444 break; 16445 } 16446 } 16447 if (!keep) { 16448 if (DEBUG_CLEAN_APKS) { 16449 Slog.i(TAG, " Removing package " + packageName); 16450 } 16451 mHandler.post(new Runnable() { 16452 public void run() { 16453 deletePackageX(packageName, userHandle, 0); 16454 } //end run 16455 }); 16456 } 16457 } 16458 } 16459 16460 /** Called by UserManagerService */ 16461 void createNewUserLILPw(int userHandle) { 16462 if (mInstaller != null) { 16463 mInstaller.createUserConfig(userHandle); 16464 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16465 applyFactoryDefaultBrowserLPw(userHandle); 16466 primeDomainVerificationsLPw(userHandle); 16467 } 16468 } 16469 16470 void newUserCreated(final int userHandle) { 16471 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16472 } 16473 16474 @Override 16475 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16476 mContext.enforceCallingOrSelfPermission( 16477 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16478 "Only package verification agents can read the verifier device identity"); 16479 16480 synchronized (mPackages) { 16481 return mSettings.getVerifierDeviceIdentityLPw(); 16482 } 16483 } 16484 16485 @Override 16486 public void setPermissionEnforced(String permission, boolean enforced) { 16487 // TODO: Now that we no longer change GID for storage, this should to away. 16488 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16489 "setPermissionEnforced"); 16490 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16491 synchronized (mPackages) { 16492 if (mSettings.mReadExternalStorageEnforced == null 16493 || mSettings.mReadExternalStorageEnforced != enforced) { 16494 mSettings.mReadExternalStorageEnforced = enforced; 16495 mSettings.writeLPr(); 16496 } 16497 } 16498 // kill any non-foreground processes so we restart them and 16499 // grant/revoke the GID. 16500 final IActivityManager am = ActivityManagerNative.getDefault(); 16501 if (am != null) { 16502 final long token = Binder.clearCallingIdentity(); 16503 try { 16504 am.killProcessesBelowForeground("setPermissionEnforcement"); 16505 } catch (RemoteException e) { 16506 } finally { 16507 Binder.restoreCallingIdentity(token); 16508 } 16509 } 16510 } else { 16511 throw new IllegalArgumentException("No selective enforcement for " + permission); 16512 } 16513 } 16514 16515 @Override 16516 @Deprecated 16517 public boolean isPermissionEnforced(String permission) { 16518 return true; 16519 } 16520 16521 @Override 16522 public boolean isStorageLow() { 16523 final long token = Binder.clearCallingIdentity(); 16524 try { 16525 final DeviceStorageMonitorInternal 16526 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16527 if (dsm != null) { 16528 return dsm.isMemoryLow(); 16529 } else { 16530 return false; 16531 } 16532 } finally { 16533 Binder.restoreCallingIdentity(token); 16534 } 16535 } 16536 16537 @Override 16538 public IPackageInstaller getPackageInstaller() { 16539 return mInstallerService; 16540 } 16541 16542 private boolean userNeedsBadging(int userId) { 16543 int index = mUserNeedsBadging.indexOfKey(userId); 16544 if (index < 0) { 16545 final UserInfo userInfo; 16546 final long token = Binder.clearCallingIdentity(); 16547 try { 16548 userInfo = sUserManager.getUserInfo(userId); 16549 } finally { 16550 Binder.restoreCallingIdentity(token); 16551 } 16552 final boolean b; 16553 if (userInfo != null && userInfo.isManagedProfile()) { 16554 b = true; 16555 } else { 16556 b = false; 16557 } 16558 mUserNeedsBadging.put(userId, b); 16559 return b; 16560 } 16561 return mUserNeedsBadging.valueAt(index); 16562 } 16563 16564 @Override 16565 public KeySet getKeySetByAlias(String packageName, String alias) { 16566 if (packageName == null || alias == null) { 16567 return null; 16568 } 16569 synchronized(mPackages) { 16570 final PackageParser.Package pkg = mPackages.get(packageName); 16571 if (pkg == null) { 16572 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16573 throw new IllegalArgumentException("Unknown package: " + packageName); 16574 } 16575 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16576 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16577 } 16578 } 16579 16580 @Override 16581 public KeySet getSigningKeySet(String packageName) { 16582 if (packageName == null) { 16583 return null; 16584 } 16585 synchronized(mPackages) { 16586 final PackageParser.Package pkg = mPackages.get(packageName); 16587 if (pkg == null) { 16588 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16589 throw new IllegalArgumentException("Unknown package: " + packageName); 16590 } 16591 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16592 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16593 throw new SecurityException("May not access signing KeySet of other apps."); 16594 } 16595 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16596 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16597 } 16598 } 16599 16600 @Override 16601 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16602 if (packageName == null || ks == null) { 16603 return false; 16604 } 16605 synchronized(mPackages) { 16606 final PackageParser.Package pkg = mPackages.get(packageName); 16607 if (pkg == null) { 16608 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16609 throw new IllegalArgumentException("Unknown package: " + packageName); 16610 } 16611 IBinder ksh = ks.getToken(); 16612 if (ksh instanceof KeySetHandle) { 16613 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16614 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16615 } 16616 return false; 16617 } 16618 } 16619 16620 @Override 16621 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16622 if (packageName == null || ks == null) { 16623 return false; 16624 } 16625 synchronized(mPackages) { 16626 final PackageParser.Package pkg = mPackages.get(packageName); 16627 if (pkg == null) { 16628 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16629 throw new IllegalArgumentException("Unknown package: " + packageName); 16630 } 16631 IBinder ksh = ks.getToken(); 16632 if (ksh instanceof KeySetHandle) { 16633 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16634 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16635 } 16636 return false; 16637 } 16638 } 16639 16640 public void getUsageStatsIfNoPackageUsageInfo() { 16641 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16642 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16643 if (usm == null) { 16644 throw new IllegalStateException("UsageStatsManager must be initialized"); 16645 } 16646 long now = System.currentTimeMillis(); 16647 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16648 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16649 String packageName = entry.getKey(); 16650 PackageParser.Package pkg = mPackages.get(packageName); 16651 if (pkg == null) { 16652 continue; 16653 } 16654 UsageStats usage = entry.getValue(); 16655 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16656 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16657 } 16658 } 16659 } 16660 16661 /** 16662 * Check and throw if the given before/after packages would be considered a 16663 * downgrade. 16664 */ 16665 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16666 throws PackageManagerException { 16667 if (after.versionCode < before.mVersionCode) { 16668 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16669 "Update version code " + after.versionCode + " is older than current " 16670 + before.mVersionCode); 16671 } else if (after.versionCode == before.mVersionCode) { 16672 if (after.baseRevisionCode < before.baseRevisionCode) { 16673 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16674 "Update base revision code " + after.baseRevisionCode 16675 + " is older than current " + before.baseRevisionCode); 16676 } 16677 16678 if (!ArrayUtils.isEmpty(after.splitNames)) { 16679 for (int i = 0; i < after.splitNames.length; i++) { 16680 final String splitName = after.splitNames[i]; 16681 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16682 if (j != -1) { 16683 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16684 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16685 "Update split " + splitName + " revision code " 16686 + after.splitRevisionCodes[i] + " is older than current " 16687 + before.splitRevisionCodes[j]); 16688 } 16689 } 16690 } 16691 } 16692 } 16693 } 16694 16695 private static class MoveCallbacks extends Handler { 16696 private static final int MSG_CREATED = 1; 16697 private static final int MSG_STATUS_CHANGED = 2; 16698 16699 private final RemoteCallbackList<IPackageMoveObserver> 16700 mCallbacks = new RemoteCallbackList<>(); 16701 16702 private final SparseIntArray mLastStatus = new SparseIntArray(); 16703 16704 public MoveCallbacks(Looper looper) { 16705 super(looper); 16706 } 16707 16708 public void register(IPackageMoveObserver callback) { 16709 mCallbacks.register(callback); 16710 } 16711 16712 public void unregister(IPackageMoveObserver callback) { 16713 mCallbacks.unregister(callback); 16714 } 16715 16716 @Override 16717 public void handleMessage(Message msg) { 16718 final SomeArgs args = (SomeArgs) msg.obj; 16719 final int n = mCallbacks.beginBroadcast(); 16720 for (int i = 0; i < n; i++) { 16721 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16722 try { 16723 invokeCallback(callback, msg.what, args); 16724 } catch (RemoteException ignored) { 16725 } 16726 } 16727 mCallbacks.finishBroadcast(); 16728 args.recycle(); 16729 } 16730 16731 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16732 throws RemoteException { 16733 switch (what) { 16734 case MSG_CREATED: { 16735 callback.onCreated(args.argi1, (Bundle) args.arg2); 16736 break; 16737 } 16738 case MSG_STATUS_CHANGED: { 16739 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16740 break; 16741 } 16742 } 16743 } 16744 16745 private void notifyCreated(int moveId, Bundle extras) { 16746 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16747 16748 final SomeArgs args = SomeArgs.obtain(); 16749 args.argi1 = moveId; 16750 args.arg2 = extras; 16751 obtainMessage(MSG_CREATED, args).sendToTarget(); 16752 } 16753 16754 private void notifyStatusChanged(int moveId, int status) { 16755 notifyStatusChanged(moveId, status, -1); 16756 } 16757 16758 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16759 Slog.v(TAG, "Move " + moveId + " status " + status); 16760 16761 final SomeArgs args = SomeArgs.obtain(); 16762 args.argi1 = moveId; 16763 args.argi2 = status; 16764 args.arg3 = estMillis; 16765 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16766 16767 synchronized (mLastStatus) { 16768 mLastStatus.put(moveId, status); 16769 } 16770 } 16771 } 16772 16773 private final class OnPermissionChangeListeners extends Handler { 16774 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16775 16776 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16777 new RemoteCallbackList<>(); 16778 16779 public OnPermissionChangeListeners(Looper looper) { 16780 super(looper); 16781 } 16782 16783 @Override 16784 public void handleMessage(Message msg) { 16785 switch (msg.what) { 16786 case MSG_ON_PERMISSIONS_CHANGED: { 16787 final int uid = msg.arg1; 16788 handleOnPermissionsChanged(uid); 16789 } break; 16790 } 16791 } 16792 16793 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16794 mPermissionListeners.register(listener); 16795 16796 } 16797 16798 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16799 mPermissionListeners.unregister(listener); 16800 } 16801 16802 public void onPermissionsChanged(int uid) { 16803 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16804 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16805 } 16806 } 16807 16808 private void handleOnPermissionsChanged(int uid) { 16809 final int count = mPermissionListeners.beginBroadcast(); 16810 try { 16811 for (int i = 0; i < count; i++) { 16812 IOnPermissionsChangeListener callback = mPermissionListeners 16813 .getBroadcastItem(i); 16814 try { 16815 callback.onPermissionsChanged(uid); 16816 } catch (RemoteException e) { 16817 Log.e(TAG, "Permission listener is dead", e); 16818 } 16819 } 16820 } finally { 16821 mPermissionListeners.finishBroadcast(); 16822 } 16823 } 16824 } 16825 16826 private class PackageManagerInternalImpl extends PackageManagerInternal { 16827 @Override 16828 public void setLocationPackagesProvider(PackagesProvider provider) { 16829 synchronized (mPackages) { 16830 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16831 } 16832 } 16833 16834 @Override 16835 public void setImePackagesProvider(PackagesProvider provider) { 16836 synchronized (mPackages) { 16837 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16838 } 16839 } 16840 16841 @Override 16842 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16843 synchronized (mPackages) { 16844 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16845 } 16846 } 16847 16848 @Override 16849 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16850 synchronized (mPackages) { 16851 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16852 } 16853 } 16854 16855 @Override 16856 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16857 synchronized (mPackages) { 16858 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16859 } 16860 } 16861 16862 @Override 16863 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16864 synchronized (mPackages) { 16865 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16866 } 16867 } 16868 16869 @Override 16870 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16871 synchronized (mPackages) { 16872 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16873 } 16874 } 16875 16876 @Override 16877 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16878 synchronized (mPackages) { 16879 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16880 packageName, userId); 16881 } 16882 } 16883 16884 @Override 16885 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16886 synchronized (mPackages) { 16887 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16888 packageName, userId); 16889 } 16890 } 16891 @Override 16892 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16893 synchronized (mPackages) { 16894 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16895 packageName, userId); 16896 } 16897 } 16898 } 16899 16900 @Override 16901 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16902 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16903 synchronized (mPackages) { 16904 final long identity = Binder.clearCallingIdentity(); 16905 try { 16906 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16907 packageNames, userId); 16908 } finally { 16909 Binder.restoreCallingIdentity(identity); 16910 } 16911 } 16912 } 16913 16914 private static void enforceSystemOrPhoneCaller(String tag) { 16915 int callingUid = Binder.getCallingUid(); 16916 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16917 throw new SecurityException( 16918 "Cannot call " + tag + " from UID " + callingUid); 16919 } 16920 } 16921} 16922