PackageManagerService.java revision c3008a698b32ef91e13fe9559570db1ebbd07439
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 try { 1150 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1151 System.identityHashCode(params)); 1152 // If this is the only one pending we might 1153 // have to bind to the service again. 1154 if (!connectToService()) { 1155 Slog.e(TAG, "Failed to bind to media container service"); 1156 params.serviceError(); 1157 return; 1158 } else { 1159 // Once we bind to the service, the first 1160 // pending request will be processed. 1161 mPendingInstalls.add(idx, params); 1162 } 1163 } finally { 1164 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1165 System.identityHashCode(params)); 1166 } 1167 } else { 1168 mPendingInstalls.add(idx, params); 1169 // Already bound to the service. Just make 1170 // sure we trigger off processing the first request. 1171 if (idx == 0) { 1172 mHandler.sendEmptyMessage(MCS_BOUND); 1173 } 1174 } 1175 break; 1176 } 1177 case MCS_BOUND: { 1178 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1179 if (msg.obj != null) { 1180 mContainerService = (IMediaContainerService) msg.obj; 1181 } 1182 if (mContainerService == null) { 1183 if (!mBound) { 1184 // Something seriously wrong since we are not bound and we are not 1185 // waiting for connection. Bail out. 1186 Slog.e(TAG, "Cannot bind to media container service"); 1187 for (HandlerParams params : mPendingInstalls) { 1188 // Indicate service bind error 1189 params.serviceError(); 1190 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1191 System.identityHashCode(params)); 1192 } 1193 mPendingInstalls.clear(); 1194 } else { 1195 Slog.w(TAG, "Waiting to connect to media container service"); 1196 } 1197 } else if (mPendingInstalls.size() > 0) { 1198 HandlerParams params = mPendingInstalls.get(0); 1199 if (params != null) { 1200 if (params.startCopy()) { 1201 // We are done... look for more work or to 1202 // go idle. 1203 if (DEBUG_SD_INSTALL) Log.i(TAG, 1204 "Checking for more work or unbind..."); 1205 // Delete pending install 1206 if (mPendingInstalls.size() > 0) { 1207 mPendingInstalls.remove(0); 1208 } 1209 if (mPendingInstalls.size() == 0) { 1210 if (mBound) { 1211 if (DEBUG_SD_INSTALL) Log.i(TAG, 1212 "Posting delayed MCS_UNBIND"); 1213 removeMessages(MCS_UNBIND); 1214 Message ubmsg = obtainMessage(MCS_UNBIND); 1215 // Unbind after a little delay, to avoid 1216 // continual thrashing. 1217 sendMessageDelayed(ubmsg, 10000); 1218 } 1219 } else { 1220 // There are more pending requests in queue. 1221 // Just post MCS_BOUND message to trigger processing 1222 // of next pending install. 1223 if (DEBUG_SD_INSTALL) Log.i(TAG, 1224 "Posting MCS_BOUND for next work"); 1225 mHandler.sendEmptyMessage(MCS_BOUND); 1226 } 1227 } 1228 } 1229 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1230 System.identityHashCode(params)); 1231 } else { 1232 // Should never happen ideally. 1233 Slog.w(TAG, "Empty queue"); 1234 } 1235 break; 1236 } 1237 case MCS_RECONNECT: { 1238 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1239 if (mPendingInstalls.size() > 0) { 1240 if (mBound) { 1241 disconnectService(); 1242 } 1243 if (!connectToService()) { 1244 Slog.e(TAG, "Failed to bind to media container service"); 1245 for (HandlerParams params : mPendingInstalls) { 1246 // Indicate service bind error 1247 params.serviceError(); 1248 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1249 System.identityHashCode(params)); 1250 } 1251 mPendingInstalls.clear(); 1252 } 1253 } 1254 break; 1255 } 1256 case MCS_UNBIND: { 1257 // If there is no actual work left, then time to unbind. 1258 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1259 1260 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1261 if (mBound) { 1262 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1263 1264 disconnectService(); 1265 } 1266 } else if (mPendingInstalls.size() > 0) { 1267 // There are more pending requests in queue. 1268 // Just post MCS_BOUND message to trigger processing 1269 // of next pending install. 1270 mHandler.sendEmptyMessage(MCS_BOUND); 1271 } 1272 1273 break; 1274 } 1275 case MCS_GIVE_UP: { 1276 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1277 HandlerParams params = mPendingInstalls.remove(0); 1278 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1279 System.identityHashCode(params)); 1280 break; 1281 } 1282 case SEND_PENDING_BROADCAST: { 1283 String packages[]; 1284 ArrayList<String> components[]; 1285 int size = 0; 1286 int uids[]; 1287 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1288 synchronized (mPackages) { 1289 if (mPendingBroadcasts == null) { 1290 return; 1291 } 1292 size = mPendingBroadcasts.size(); 1293 if (size <= 0) { 1294 // Nothing to be done. Just return 1295 return; 1296 } 1297 packages = new String[size]; 1298 components = new ArrayList[size]; 1299 uids = new int[size]; 1300 int i = 0; // filling out the above arrays 1301 1302 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1303 int packageUserId = mPendingBroadcasts.userIdAt(n); 1304 Iterator<Map.Entry<String, ArrayList<String>>> it 1305 = mPendingBroadcasts.packagesForUserId(packageUserId) 1306 .entrySet().iterator(); 1307 while (it.hasNext() && i < size) { 1308 Map.Entry<String, ArrayList<String>> ent = it.next(); 1309 packages[i] = ent.getKey(); 1310 components[i] = ent.getValue(); 1311 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1312 uids[i] = (ps != null) 1313 ? UserHandle.getUid(packageUserId, ps.appId) 1314 : -1; 1315 i++; 1316 } 1317 } 1318 size = i; 1319 mPendingBroadcasts.clear(); 1320 } 1321 // Send broadcasts 1322 for (int i = 0; i < size; i++) { 1323 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1324 } 1325 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1326 break; 1327 } 1328 case START_CLEANING_PACKAGE: { 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1330 final String packageName = (String)msg.obj; 1331 final int userId = msg.arg1; 1332 final boolean andCode = msg.arg2 != 0; 1333 synchronized (mPackages) { 1334 if (userId == UserHandle.USER_ALL) { 1335 int[] users = sUserManager.getUserIds(); 1336 for (int user : users) { 1337 mSettings.addPackageToCleanLPw( 1338 new PackageCleanItem(user, packageName, andCode)); 1339 } 1340 } else { 1341 mSettings.addPackageToCleanLPw( 1342 new PackageCleanItem(userId, packageName, andCode)); 1343 } 1344 } 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 startCleaningPackages(); 1347 } break; 1348 case POST_INSTALL: { 1349 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1350 PostInstallData data = mRunningInstalls.get(msg.arg1); 1351 mRunningInstalls.delete(msg.arg1); 1352 boolean deleteOld = false; 1353 1354 if (data != null) { 1355 InstallArgs args = data.args; 1356 PackageInstalledInfo res = data.res; 1357 1358 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1359 final String packageName = res.pkg.applicationInfo.packageName; 1360 res.removedInfo.sendBroadcast(false, true, false); 1361 Bundle extras = new Bundle(1); 1362 extras.putInt(Intent.EXTRA_UID, res.uid); 1363 1364 // Now that we successfully installed the package, grant runtime 1365 // permissions if requested before broadcasting the install. 1366 if ((args.installFlags 1367 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1368 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1369 args.installGrantPermissions); 1370 } 1371 1372 // Determine the set of users who are adding this 1373 // package for the first time vs. those who are seeing 1374 // an update. 1375 int[] firstUsers; 1376 int[] updateUsers = new int[0]; 1377 if (res.origUsers == null || res.origUsers.length == 0) { 1378 firstUsers = res.newUsers; 1379 } else { 1380 firstUsers = new int[0]; 1381 for (int i=0; i<res.newUsers.length; i++) { 1382 int user = res.newUsers[i]; 1383 boolean isNew = true; 1384 for (int j=0; j<res.origUsers.length; j++) { 1385 if (res.origUsers[j] == user) { 1386 isNew = false; 1387 break; 1388 } 1389 } 1390 if (isNew) { 1391 int[] newFirst = new int[firstUsers.length+1]; 1392 System.arraycopy(firstUsers, 0, newFirst, 0, 1393 firstUsers.length); 1394 newFirst[firstUsers.length] = user; 1395 firstUsers = newFirst; 1396 } else { 1397 int[] newUpdate = new int[updateUsers.length+1]; 1398 System.arraycopy(updateUsers, 0, newUpdate, 0, 1399 updateUsers.length); 1400 newUpdate[updateUsers.length] = user; 1401 updateUsers = newUpdate; 1402 } 1403 } 1404 } 1405 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1406 packageName, extras, null, null, firstUsers); 1407 final boolean update = res.removedInfo.removedPackage != null; 1408 if (update) { 1409 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1410 } 1411 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1412 packageName, extras, null, null, updateUsers); 1413 if (update) { 1414 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1415 packageName, extras, null, null, updateUsers); 1416 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1417 null, null, packageName, null, updateUsers); 1418 1419 // treat asec-hosted packages like removable media on upgrade 1420 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1421 if (DEBUG_INSTALL) { 1422 Slog.i(TAG, "upgrading pkg " + res.pkg 1423 + " is ASEC-hosted -> AVAILABLE"); 1424 } 1425 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1426 ArrayList<String> pkgList = new ArrayList<String>(1); 1427 pkgList.add(packageName); 1428 sendResourcesChangedBroadcast(true, true, 1429 pkgList,uidArray, null); 1430 } 1431 } 1432 if (res.removedInfo.args != null) { 1433 // Remove the replaced package's older resources safely now 1434 deleteOld = true; 1435 } 1436 1437 // If this app is a browser and it's newly-installed for some 1438 // users, clear any default-browser state in those users 1439 if (firstUsers.length > 0) { 1440 // the app's nature doesn't depend on the user, so we can just 1441 // check its browser nature in any user and generalize. 1442 if (packageIsBrowser(packageName, firstUsers[0])) { 1443 synchronized (mPackages) { 1444 for (int userId : firstUsers) { 1445 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1446 } 1447 } 1448 } 1449 } 1450 // Log current value of "unknown sources" setting 1451 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1452 getUnknownSourcesSettings()); 1453 } 1454 // Force a gc to clear up things 1455 Runtime.getRuntime().gc(); 1456 // We delete after a gc for applications on sdcard. 1457 if (deleteOld) { 1458 synchronized (mInstallLock) { 1459 res.removedInfo.args.doPostDeleteLI(true); 1460 } 1461 } 1462 if (args.observer != null) { 1463 try { 1464 Bundle extras = extrasForInstallResult(res); 1465 args.observer.onPackageInstalled(res.name, res.returnCode, 1466 res.returnMsg, extras); 1467 } catch (RemoteException e) { 1468 Slog.i(TAG, "Observer no longer exists."); 1469 } 1470 } 1471 } else { 1472 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1473 } 1474 1475 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1476 } break; 1477 case UPDATED_MEDIA_STATUS: { 1478 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1479 boolean reportStatus = msg.arg1 == 1; 1480 boolean doGc = msg.arg2 == 1; 1481 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1482 if (doGc) { 1483 // Force a gc to clear up stale containers. 1484 Runtime.getRuntime().gc(); 1485 } 1486 if (msg.obj != null) { 1487 @SuppressWarnings("unchecked") 1488 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1489 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1490 // Unload containers 1491 unloadAllContainers(args); 1492 } 1493 if (reportStatus) { 1494 try { 1495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1496 PackageHelper.getMountService().finishMediaUpdate(); 1497 } catch (RemoteException e) { 1498 Log.e(TAG, "MountService not running?"); 1499 } 1500 } 1501 } break; 1502 case WRITE_SETTINGS: { 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1504 synchronized (mPackages) { 1505 removeMessages(WRITE_SETTINGS); 1506 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1507 mSettings.writeLPr(); 1508 mDirtyUsers.clear(); 1509 } 1510 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1511 } break; 1512 case WRITE_PACKAGE_RESTRICTIONS: { 1513 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1514 synchronized (mPackages) { 1515 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1516 for (int userId : mDirtyUsers) { 1517 mSettings.writePackageRestrictionsLPr(userId); 1518 } 1519 mDirtyUsers.clear(); 1520 } 1521 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1522 } break; 1523 case CHECK_PENDING_VERIFICATION: { 1524 final int verificationId = msg.arg1; 1525 final PackageVerificationState state = mPendingVerification.get(verificationId); 1526 1527 if ((state != null) && !state.timeoutExtended()) { 1528 final InstallArgs args = state.getInstallArgs(); 1529 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1530 1531 Slog.i(TAG, "Verification timed out for " + originUri); 1532 mPendingVerification.remove(verificationId); 1533 1534 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1535 1536 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1537 Slog.i(TAG, "Continuing with installation of " + originUri); 1538 state.setVerifierResponse(Binder.getCallingUid(), 1539 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1540 broadcastPackageVerified(verificationId, originUri, 1541 PackageManager.VERIFICATION_ALLOW, 1542 state.getInstallArgs().getUser()); 1543 try { 1544 ret = args.copyApk(mContainerService, true); 1545 } catch (RemoteException e) { 1546 Slog.e(TAG, "Could not contact the ContainerService"); 1547 } 1548 } else { 1549 broadcastPackageVerified(verificationId, originUri, 1550 PackageManager.VERIFICATION_REJECT, 1551 state.getInstallArgs().getUser()); 1552 } 1553 1554 processPendingInstall(args, ret); 1555 mHandler.sendEmptyMessage(MCS_UNBIND); 1556 } 1557 Trace.asyncTraceEnd( 1558 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 1559 break; 1560 } 1561 case PACKAGE_VERIFIED: { 1562 final int verificationId = msg.arg1; 1563 1564 final PackageVerificationState state = mPendingVerification.get(verificationId); 1565 if (state == null) { 1566 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1567 break; 1568 } 1569 1570 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1571 1572 state.setVerifierResponse(response.callerUid, response.code); 1573 1574 if (state.isVerificationComplete()) { 1575 mPendingVerification.remove(verificationId); 1576 1577 final InstallArgs args = state.getInstallArgs(); 1578 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1579 1580 int ret; 1581 if (state.isInstallAllowed()) { 1582 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1583 broadcastPackageVerified(verificationId, originUri, 1584 response.code, state.getInstallArgs().getUser()); 1585 try { 1586 ret = args.copyApk(mContainerService, true); 1587 } catch (RemoteException e) { 1588 Slog.e(TAG, "Could not contact the ContainerService"); 1589 } 1590 } else { 1591 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1592 } 1593 1594 processPendingInstall(args, ret); 1595 1596 mHandler.sendEmptyMessage(MCS_UNBIND); 1597 } 1598 1599 break; 1600 } 1601 case START_INTENT_FILTER_VERIFICATIONS: { 1602 IFVerificationParams params = (IFVerificationParams) msg.obj; 1603 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1604 params.replacing, params.pkg); 1605 break; 1606 } 1607 case INTENT_FILTER_VERIFIED: { 1608 final int verificationId = msg.arg1; 1609 1610 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1611 verificationId); 1612 if (state == null) { 1613 Slog.w(TAG, "Invalid IntentFilter verification token " 1614 + verificationId + " received"); 1615 break; 1616 } 1617 1618 final int userId = state.getUserId(); 1619 1620 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1621 "Processing IntentFilter verification with token:" 1622 + verificationId + " and userId:" + userId); 1623 1624 final IntentFilterVerificationResponse response = 1625 (IntentFilterVerificationResponse) msg.obj; 1626 1627 state.setVerifierResponse(response.callerUid, response.code); 1628 1629 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1630 "IntentFilter verification with token:" + verificationId 1631 + " and userId:" + userId 1632 + " is settings verifier response with response code:" 1633 + response.code); 1634 1635 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1636 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1637 + response.getFailedDomainsString()); 1638 } 1639 1640 if (state.isVerificationComplete()) { 1641 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1642 } else { 1643 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1644 "IntentFilter verification with token:" + verificationId 1645 + " was not said to be complete"); 1646 } 1647 1648 break; 1649 } 1650 } 1651 } 1652 } 1653 1654 private StorageEventListener mStorageListener = new StorageEventListener() { 1655 @Override 1656 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1657 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1658 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1659 final String volumeUuid = vol.getFsUuid(); 1660 1661 // Clean up any users or apps that were removed or recreated 1662 // while this volume was missing 1663 reconcileUsers(volumeUuid); 1664 reconcileApps(volumeUuid); 1665 1666 // Clean up any install sessions that expired or were 1667 // cancelled while this volume was missing 1668 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1669 1670 loadPrivatePackages(vol); 1671 1672 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1673 unloadPrivatePackages(vol); 1674 } 1675 } 1676 1677 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1678 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1679 updateExternalMediaStatus(true, false); 1680 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1681 updateExternalMediaStatus(false, false); 1682 } 1683 } 1684 } 1685 1686 @Override 1687 public void onVolumeForgotten(String fsUuid) { 1688 if (TextUtils.isEmpty(fsUuid)) { 1689 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1690 return; 1691 } 1692 1693 // Remove any apps installed on the forgotten volume 1694 synchronized (mPackages) { 1695 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1696 for (PackageSetting ps : packages) { 1697 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1698 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1699 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1700 } 1701 1702 mSettings.onVolumeForgotten(fsUuid); 1703 mSettings.writeLPr(); 1704 } 1705 } 1706 }; 1707 1708 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1709 String[] grantedPermissions) { 1710 if (userId >= UserHandle.USER_OWNER) { 1711 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1712 } else if (userId == UserHandle.USER_ALL) { 1713 final int[] userIds; 1714 synchronized (mPackages) { 1715 userIds = UserManagerService.getInstance().getUserIds(); 1716 } 1717 for (int someUserId : userIds) { 1718 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1719 } 1720 } 1721 1722 // We could have touched GID membership, so flush out packages.list 1723 synchronized (mPackages) { 1724 mSettings.writePackageListLPr(); 1725 } 1726 } 1727 1728 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1729 String[] grantedPermissions) { 1730 SettingBase sb = (SettingBase) pkg.mExtras; 1731 if (sb == null) { 1732 return; 1733 } 1734 1735 PermissionsState permissionsState = sb.getPermissionsState(); 1736 1737 for (String permission : pkg.requestedPermissions) { 1738 BasePermission bp = mSettings.mPermissions.get(permission); 1739 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1740 || ArrayUtils.contains(grantedPermissions, permission))) { 1741 permissionsState.grantRuntimePermission(bp, userId); 1742 } 1743 } 1744 } 1745 1746 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1747 Bundle extras = null; 1748 switch (res.returnCode) { 1749 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1750 extras = new Bundle(); 1751 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1752 res.origPermission); 1753 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1754 res.origPackage); 1755 break; 1756 } 1757 case PackageManager.INSTALL_SUCCEEDED: { 1758 extras = new Bundle(); 1759 extras.putBoolean(Intent.EXTRA_REPLACING, 1760 res.removedInfo != null && res.removedInfo.removedPackage != null); 1761 break; 1762 } 1763 } 1764 return extras; 1765 } 1766 1767 void scheduleWriteSettingsLocked() { 1768 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1769 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1770 } 1771 } 1772 1773 void scheduleWritePackageRestrictionsLocked(int userId) { 1774 if (!sUserManager.exists(userId)) return; 1775 mDirtyUsers.add(userId); 1776 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1777 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1778 } 1779 } 1780 1781 public static PackageManagerService main(Context context, Installer installer, 1782 boolean factoryTest, boolean onlyCore) { 1783 PackageManagerService m = new PackageManagerService(context, installer, 1784 factoryTest, onlyCore); 1785 ServiceManager.addService("package", m); 1786 return m; 1787 } 1788 1789 static String[] splitString(String str, char sep) { 1790 int count = 1; 1791 int i = 0; 1792 while ((i=str.indexOf(sep, i)) >= 0) { 1793 count++; 1794 i++; 1795 } 1796 1797 String[] res = new String[count]; 1798 i=0; 1799 count = 0; 1800 int lastI=0; 1801 while ((i=str.indexOf(sep, i)) >= 0) { 1802 res[count] = str.substring(lastI, i); 1803 count++; 1804 i++; 1805 lastI = i; 1806 } 1807 res[count] = str.substring(lastI, str.length()); 1808 return res; 1809 } 1810 1811 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1812 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1813 Context.DISPLAY_SERVICE); 1814 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1815 } 1816 1817 public PackageManagerService(Context context, Installer installer, 1818 boolean factoryTest, boolean onlyCore) { 1819 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1820 SystemClock.uptimeMillis()); 1821 1822 if (mSdkVersion <= 0) { 1823 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1824 } 1825 1826 mContext = context; 1827 mFactoryTest = factoryTest; 1828 mOnlyCore = onlyCore; 1829 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1830 mMetrics = new DisplayMetrics(); 1831 mSettings = new Settings(mPackages); 1832 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1833 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1834 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1835 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1836 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1837 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1838 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1839 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1840 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1841 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1842 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1843 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1844 1845 // TODO: add a property to control this? 1846 long dexOptLRUThresholdInMinutes; 1847 if (mLazyDexOpt) { 1848 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1849 } else { 1850 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1851 } 1852 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1853 1854 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1855 if (separateProcesses != null && separateProcesses.length() > 0) { 1856 if ("*".equals(separateProcesses)) { 1857 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1858 mSeparateProcesses = null; 1859 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1860 } else { 1861 mDefParseFlags = 0; 1862 mSeparateProcesses = separateProcesses.split(","); 1863 Slog.w(TAG, "Running with debug.separate_processes: " 1864 + separateProcesses); 1865 } 1866 } else { 1867 mDefParseFlags = 0; 1868 mSeparateProcesses = null; 1869 } 1870 1871 mInstaller = installer; 1872 mPackageDexOptimizer = new PackageDexOptimizer(this); 1873 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1874 1875 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1876 FgThread.get().getLooper()); 1877 1878 getDefaultDisplayMetrics(context, mMetrics); 1879 1880 SystemConfig systemConfig = SystemConfig.getInstance(); 1881 mGlobalGids = systemConfig.getGlobalGids(); 1882 mSystemPermissions = systemConfig.getSystemPermissions(); 1883 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1884 1885 synchronized (mInstallLock) { 1886 // writer 1887 synchronized (mPackages) { 1888 mHandlerThread = new ServiceThread(TAG, 1889 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1890 mHandlerThread.start(); 1891 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1892 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1893 1894 File dataDir = Environment.getDataDirectory(); 1895 mAppDataDir = new File(dataDir, "data"); 1896 mAppInstallDir = new File(dataDir, "app"); 1897 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1898 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1899 mUserAppDataDir = new File(dataDir, "user"); 1900 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1901 1902 sUserManager = new UserManagerService(context, this, 1903 mInstallLock, mPackages); 1904 1905 // Propagate permission configuration in to package manager. 1906 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1907 = systemConfig.getPermissions(); 1908 for (int i=0; i<permConfig.size(); i++) { 1909 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1910 BasePermission bp = mSettings.mPermissions.get(perm.name); 1911 if (bp == null) { 1912 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1913 mSettings.mPermissions.put(perm.name, bp); 1914 } 1915 if (perm.gids != null) { 1916 bp.setGids(perm.gids, perm.perUser); 1917 } 1918 } 1919 1920 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1921 for (int i=0; i<libConfig.size(); i++) { 1922 mSharedLibraries.put(libConfig.keyAt(i), 1923 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1924 } 1925 1926 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1927 1928 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1929 1930 String customResolverActivity = Resources.getSystem().getString( 1931 R.string.config_customResolverActivity); 1932 if (TextUtils.isEmpty(customResolverActivity)) { 1933 customResolverActivity = null; 1934 } else { 1935 mCustomResolverComponentName = ComponentName.unflattenFromString( 1936 customResolverActivity); 1937 } 1938 1939 long startTime = SystemClock.uptimeMillis(); 1940 1941 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1942 startTime); 1943 1944 // Set flag to monitor and not change apk file paths when 1945 // scanning install directories. 1946 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1947 1948 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1949 1950 /** 1951 * Add everything in the in the boot class path to the 1952 * list of process files because dexopt will have been run 1953 * if necessary during zygote startup. 1954 */ 1955 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1956 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1957 1958 if (bootClassPath != null) { 1959 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1960 for (String element : bootClassPathElements) { 1961 alreadyDexOpted.add(element); 1962 } 1963 } else { 1964 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1965 } 1966 1967 if (systemServerClassPath != null) { 1968 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1969 for (String element : systemServerClassPathElements) { 1970 alreadyDexOpted.add(element); 1971 } 1972 } else { 1973 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1974 } 1975 1976 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1977 final String[] dexCodeInstructionSets = 1978 getDexCodeInstructionSets( 1979 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1980 1981 /** 1982 * Ensure all external libraries have had dexopt run on them. 1983 */ 1984 if (mSharedLibraries.size() > 0) { 1985 // NOTE: For now, we're compiling these system "shared libraries" 1986 // (and framework jars) into all available architectures. It's possible 1987 // to compile them only when we come across an app that uses them (there's 1988 // already logic for that in scanPackageLI) but that adds some complexity. 1989 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1990 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1991 final String lib = libEntry.path; 1992 if (lib == null) { 1993 continue; 1994 } 1995 1996 try { 1997 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1998 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1999 alreadyDexOpted.add(lib); 2000 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2001 } 2002 } catch (FileNotFoundException e) { 2003 Slog.w(TAG, "Library not found: " + lib); 2004 } catch (IOException e) { 2005 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2006 + e.getMessage()); 2007 } 2008 } 2009 } 2010 } 2011 2012 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2013 2014 // Gross hack for now: we know this file doesn't contain any 2015 // code, so don't dexopt it to avoid the resulting log spew. 2016 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2017 2018 // Gross hack for now: we know this file is only part of 2019 // the boot class path for art, so don't dexopt it to 2020 // avoid the resulting log spew. 2021 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2022 2023 /** 2024 * There are a number of commands implemented in Java, which 2025 * we currently need to do the dexopt on so that they can be 2026 * run from a non-root shell. 2027 */ 2028 String[] frameworkFiles = frameworkDir.list(); 2029 if (frameworkFiles != null) { 2030 // TODO: We could compile these only for the most preferred ABI. We should 2031 // first double check that the dex files for these commands are not referenced 2032 // by other system apps. 2033 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2034 for (int i=0; i<frameworkFiles.length; i++) { 2035 File libPath = new File(frameworkDir, frameworkFiles[i]); 2036 String path = libPath.getPath(); 2037 // Skip the file if we already did it. 2038 if (alreadyDexOpted.contains(path)) { 2039 continue; 2040 } 2041 // Skip the file if it is not a type we want to dexopt. 2042 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2043 continue; 2044 } 2045 try { 2046 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2047 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2048 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2049 } 2050 } catch (FileNotFoundException e) { 2051 Slog.w(TAG, "Jar not found: " + path); 2052 } catch (IOException e) { 2053 Slog.w(TAG, "Exception reading jar: " + path, e); 2054 } 2055 } 2056 } 2057 } 2058 2059 final VersionInfo ver = mSettings.getInternalVersion(); 2060 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2061 // when upgrading from pre-M, promote system app permissions from install to runtime 2062 mPromoteSystemApps = 2063 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2064 2065 // save off the names of pre-existing system packages prior to scanning; we don't 2066 // want to automatically grant runtime permissions for new system apps 2067 if (mPromoteSystemApps) { 2068 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2069 while (pkgSettingIter.hasNext()) { 2070 PackageSetting ps = pkgSettingIter.next(); 2071 if (isSystemApp(ps)) { 2072 mExistingSystemPackages.add(ps.name); 2073 } 2074 } 2075 } 2076 2077 // Collect vendor overlay packages. 2078 // (Do this before scanning any apps.) 2079 // For security and version matching reason, only consider 2080 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2081 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2082 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2083 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2084 2085 // Find base frameworks (resource packages without code). 2086 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2087 | PackageParser.PARSE_IS_SYSTEM_DIR 2088 | PackageParser.PARSE_IS_PRIVILEGED, 2089 scanFlags | SCAN_NO_DEX, 0); 2090 2091 // Collected privileged system packages. 2092 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2093 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2094 | PackageParser.PARSE_IS_SYSTEM_DIR 2095 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2096 2097 // Collect ordinary system packages. 2098 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2099 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2100 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2101 2102 // Collect all vendor packages. 2103 File vendorAppDir = new File("/vendor/app"); 2104 try { 2105 vendorAppDir = vendorAppDir.getCanonicalFile(); 2106 } catch (IOException e) { 2107 // failed to look up canonical path, continue with original one 2108 } 2109 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2110 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2111 2112 // Collect all OEM packages. 2113 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2114 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2116 2117 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2118 mInstaller.moveFiles(); 2119 2120 // Prune any system packages that no longer exist. 2121 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2122 if (!mOnlyCore) { 2123 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2124 while (psit.hasNext()) { 2125 PackageSetting ps = psit.next(); 2126 2127 /* 2128 * If this is not a system app, it can't be a 2129 * disable system app. 2130 */ 2131 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2132 continue; 2133 } 2134 2135 /* 2136 * If the package is scanned, it's not erased. 2137 */ 2138 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2139 if (scannedPkg != null) { 2140 /* 2141 * If the system app is both scanned and in the 2142 * disabled packages list, then it must have been 2143 * added via OTA. Remove it from the currently 2144 * scanned package so the previously user-installed 2145 * application can be scanned. 2146 */ 2147 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2148 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2149 + ps.name + "; removing system app. Last known codePath=" 2150 + ps.codePathString + ", installStatus=" + ps.installStatus 2151 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2152 + scannedPkg.mVersionCode); 2153 removePackageLI(ps, true); 2154 mExpectingBetter.put(ps.name, ps.codePath); 2155 } 2156 2157 continue; 2158 } 2159 2160 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2161 psit.remove(); 2162 logCriticalInfo(Log.WARN, "System package " + ps.name 2163 + " no longer exists; wiping its data"); 2164 removeDataDirsLI(null, ps.name); 2165 } else { 2166 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2167 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2168 possiblyDeletedUpdatedSystemApps.add(ps.name); 2169 } 2170 } 2171 } 2172 } 2173 2174 //look for any incomplete package installations 2175 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2176 //clean up list 2177 for(int i = 0; i < deletePkgsList.size(); i++) { 2178 //clean up here 2179 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2180 } 2181 //delete tmp files 2182 deleteTempPackageFiles(); 2183 2184 // Remove any shared userIDs that have no associated packages 2185 mSettings.pruneSharedUsersLPw(); 2186 2187 if (!mOnlyCore) { 2188 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2189 SystemClock.uptimeMillis()); 2190 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2191 2192 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2193 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2194 2195 /** 2196 * Remove disable package settings for any updated system 2197 * apps that were removed via an OTA. If they're not a 2198 * previously-updated app, remove them completely. 2199 * Otherwise, just revoke their system-level permissions. 2200 */ 2201 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2202 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2203 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2204 2205 String msg; 2206 if (deletedPkg == null) { 2207 msg = "Updated system package " + deletedAppName 2208 + " no longer exists; wiping its data"; 2209 removeDataDirsLI(null, deletedAppName); 2210 } else { 2211 msg = "Updated system app + " + deletedAppName 2212 + " no longer present; removing system privileges for " 2213 + deletedAppName; 2214 2215 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2216 2217 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2218 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2219 } 2220 logCriticalInfo(Log.WARN, msg); 2221 } 2222 2223 /** 2224 * Make sure all system apps that we expected to appear on 2225 * the userdata partition actually showed up. If they never 2226 * appeared, crawl back and revive the system version. 2227 */ 2228 for (int i = 0; i < mExpectingBetter.size(); i++) { 2229 final String packageName = mExpectingBetter.keyAt(i); 2230 if (!mPackages.containsKey(packageName)) { 2231 final File scanFile = mExpectingBetter.valueAt(i); 2232 2233 logCriticalInfo(Log.WARN, "Expected better " + packageName 2234 + " but never showed up; reverting to system"); 2235 2236 final int reparseFlags; 2237 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2238 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2239 | PackageParser.PARSE_IS_SYSTEM_DIR 2240 | PackageParser.PARSE_IS_PRIVILEGED; 2241 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2242 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2243 | PackageParser.PARSE_IS_SYSTEM_DIR; 2244 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2245 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2246 | PackageParser.PARSE_IS_SYSTEM_DIR; 2247 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2248 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2249 | PackageParser.PARSE_IS_SYSTEM_DIR; 2250 } else { 2251 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2252 continue; 2253 } 2254 2255 mSettings.enableSystemPackageLPw(packageName); 2256 2257 try { 2258 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2259 } catch (PackageManagerException e) { 2260 Slog.e(TAG, "Failed to parse original system package: " 2261 + e.getMessage()); 2262 } 2263 } 2264 } 2265 } 2266 mExpectingBetter.clear(); 2267 2268 // Now that we know all of the shared libraries, update all clients to have 2269 // the correct library paths. 2270 updateAllSharedLibrariesLPw(); 2271 2272 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2273 // NOTE: We ignore potential failures here during a system scan (like 2274 // the rest of the commands above) because there's precious little we 2275 // can do about it. A settings error is reported, though. 2276 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2277 false /* force dexopt */, false /* defer dexopt */); 2278 } 2279 2280 // Now that we know all the packages we are keeping, 2281 // read and update their last usage times. 2282 mPackageUsage.readLP(); 2283 2284 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2285 SystemClock.uptimeMillis()); 2286 Slog.i(TAG, "Time to scan packages: " 2287 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2288 + " seconds"); 2289 2290 // If the platform SDK has changed since the last time we booted, 2291 // we need to re-grant app permission to catch any new ones that 2292 // appear. This is really a hack, and means that apps can in some 2293 // cases get permissions that the user didn't initially explicitly 2294 // allow... it would be nice to have some better way to handle 2295 // this situation. 2296 int updateFlags = UPDATE_PERMISSIONS_ALL; 2297 if (ver.sdkVersion != mSdkVersion) { 2298 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2299 + mSdkVersion + "; regranting permissions for internal storage"); 2300 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2301 } 2302 updatePermissionsLPw(null, null, updateFlags); 2303 ver.sdkVersion = mSdkVersion; 2304 // clear only after permissions have been updated 2305 mExistingSystemPackages.clear(); 2306 mPromoteSystemApps = false; 2307 2308 // If this is the first boot, and it is a normal boot, then 2309 // we need to initialize the default preferred apps. 2310 if (!mRestoredSettings && !onlyCore) { 2311 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2312 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2313 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2314 } 2315 2316 // If this is first boot after an OTA, and a normal boot, then 2317 // we need to clear code cache directories. 2318 if (mIsUpgrade && !onlyCore) { 2319 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2320 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2321 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2322 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2323 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2324 } 2325 } 2326 ver.fingerprint = Build.FINGERPRINT; 2327 } 2328 2329 checkDefaultBrowser(); 2330 2331 // All the changes are done during package scanning. 2332 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2333 2334 // can downgrade to reader 2335 mSettings.writeLPr(); 2336 2337 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2338 SystemClock.uptimeMillis()); 2339 2340 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2341 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2342 2343 mInstallerService = new PackageInstallerService(context, this); 2344 2345 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2346 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2347 mIntentFilterVerifierComponent); 2348 2349 } // synchronized (mPackages) 2350 } // synchronized (mInstallLock) 2351 2352 // Now after opening every single application zip, make sure they 2353 // are all flushed. Not really needed, but keeps things nice and 2354 // tidy. 2355 Runtime.getRuntime().gc(); 2356 2357 // Expose private service for system components to use. 2358 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2359 } 2360 2361 @Override 2362 public boolean isFirstBoot() { 2363 return !mRestoredSettings; 2364 } 2365 2366 @Override 2367 public boolean isOnlyCoreApps() { 2368 return mOnlyCore; 2369 } 2370 2371 @Override 2372 public boolean isUpgrade() { 2373 return mIsUpgrade; 2374 } 2375 2376 private String getRequiredVerifierLPr() { 2377 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2378 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2379 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2380 2381 String requiredVerifier = null; 2382 2383 final int N = receivers.size(); 2384 for (int i = 0; i < N; i++) { 2385 final ResolveInfo info = receivers.get(i); 2386 2387 if (info.activityInfo == null) { 2388 continue; 2389 } 2390 2391 final String packageName = info.activityInfo.packageName; 2392 2393 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2394 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2395 continue; 2396 } 2397 2398 if (requiredVerifier != null) { 2399 throw new RuntimeException("There can be only one required verifier"); 2400 } 2401 2402 requiredVerifier = packageName; 2403 } 2404 2405 return requiredVerifier; 2406 } 2407 2408 private String getRequiredInstallerLPr() { 2409 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2410 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2411 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2412 2413 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2414 PACKAGE_MIME_TYPE, 0, 0); 2415 2416 String requiredInstaller = null; 2417 2418 final int N = installers.size(); 2419 for (int i = 0; i < N; i++) { 2420 final ResolveInfo info = installers.get(i); 2421 final String packageName = info.activityInfo.packageName; 2422 2423 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2424 continue; 2425 } 2426 2427 if (requiredInstaller != null) { 2428 throw new RuntimeException("There must be one required installer"); 2429 } 2430 2431 requiredInstaller = packageName; 2432 } 2433 2434 if (requiredInstaller == null) { 2435 throw new RuntimeException("There must be one required installer"); 2436 } 2437 2438 return requiredInstaller; 2439 } 2440 2441 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2442 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2443 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2444 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2445 2446 ComponentName verifierComponentName = null; 2447 2448 int priority = -1000; 2449 final int N = receivers.size(); 2450 for (int i = 0; i < N; i++) { 2451 final ResolveInfo info = receivers.get(i); 2452 2453 if (info.activityInfo == null) { 2454 continue; 2455 } 2456 2457 final String packageName = info.activityInfo.packageName; 2458 2459 final PackageSetting ps = mSettings.mPackages.get(packageName); 2460 if (ps == null) { 2461 continue; 2462 } 2463 2464 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2465 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2466 continue; 2467 } 2468 2469 // Select the IntentFilterVerifier with the highest priority 2470 if (priority < info.priority) { 2471 priority = info.priority; 2472 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2473 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2474 + verifierComponentName + " with priority: " + info.priority); 2475 } 2476 } 2477 2478 return verifierComponentName; 2479 } 2480 2481 private void primeDomainVerificationsLPw(int userId) { 2482 if (DEBUG_DOMAIN_VERIFICATION) { 2483 Slog.d(TAG, "Priming domain verifications in user " + userId); 2484 } 2485 2486 SystemConfig systemConfig = SystemConfig.getInstance(); 2487 ArraySet<String> packages = systemConfig.getLinkedApps(); 2488 ArraySet<String> domains = new ArraySet<String>(); 2489 2490 for (String packageName : packages) { 2491 PackageParser.Package pkg = mPackages.get(packageName); 2492 if (pkg != null) { 2493 if (!pkg.isSystemApp()) { 2494 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2495 continue; 2496 } 2497 2498 domains.clear(); 2499 for (PackageParser.Activity a : pkg.activities) { 2500 for (ActivityIntentInfo filter : a.intents) { 2501 if (hasValidDomains(filter)) { 2502 domains.addAll(filter.getHostsList()); 2503 } 2504 } 2505 } 2506 2507 if (domains.size() > 0) { 2508 if (DEBUG_DOMAIN_VERIFICATION) { 2509 Slog.v(TAG, " + " + packageName); 2510 } 2511 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2512 // state w.r.t. the formal app-linkage "no verification attempted" state; 2513 // and then 'always' in the per-user state actually used for intent resolution. 2514 final IntentFilterVerificationInfo ivi; 2515 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2516 new ArrayList<String>(domains)); 2517 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2518 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2519 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2520 } else { 2521 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2522 + "' does not handle web links"); 2523 } 2524 } else { 2525 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2526 } 2527 } 2528 2529 scheduleWritePackageRestrictionsLocked(userId); 2530 scheduleWriteSettingsLocked(); 2531 } 2532 2533 private void applyFactoryDefaultBrowserLPw(int userId) { 2534 // The default browser app's package name is stored in a string resource, 2535 // with a product-specific overlay used for vendor customization. 2536 String browserPkg = mContext.getResources().getString( 2537 com.android.internal.R.string.default_browser); 2538 if (!TextUtils.isEmpty(browserPkg)) { 2539 // non-empty string => required to be a known package 2540 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2541 if (ps == null) { 2542 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2543 browserPkg = null; 2544 } else { 2545 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2546 } 2547 } 2548 2549 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2550 // default. If there's more than one, just leave everything alone. 2551 if (browserPkg == null) { 2552 calculateDefaultBrowserLPw(userId); 2553 } 2554 } 2555 2556 private void calculateDefaultBrowserLPw(int userId) { 2557 List<String> allBrowsers = resolveAllBrowserApps(userId); 2558 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2559 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2560 } 2561 2562 private List<String> resolveAllBrowserApps(int userId) { 2563 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2564 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2565 PackageManager.MATCH_ALL, userId); 2566 2567 final int count = list.size(); 2568 List<String> result = new ArrayList<String>(count); 2569 for (int i=0; i<count; i++) { 2570 ResolveInfo info = list.get(i); 2571 if (info.activityInfo == null 2572 || !info.handleAllWebDataURI 2573 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2574 || result.contains(info.activityInfo.packageName)) { 2575 continue; 2576 } 2577 result.add(info.activityInfo.packageName); 2578 } 2579 2580 return result; 2581 } 2582 2583 private boolean packageIsBrowser(String packageName, int userId) { 2584 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2585 PackageManager.MATCH_ALL, userId); 2586 final int N = list.size(); 2587 for (int i = 0; i < N; i++) { 2588 ResolveInfo info = list.get(i); 2589 if (packageName.equals(info.activityInfo.packageName)) { 2590 return true; 2591 } 2592 } 2593 return false; 2594 } 2595 2596 private void checkDefaultBrowser() { 2597 final int myUserId = UserHandle.myUserId(); 2598 final String packageName = getDefaultBrowserPackageName(myUserId); 2599 if (packageName != null) { 2600 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2601 if (info == null) { 2602 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2603 synchronized (mPackages) { 2604 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2605 } 2606 } 2607 } 2608 } 2609 2610 @Override 2611 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2612 throws RemoteException { 2613 try { 2614 return super.onTransact(code, data, reply, flags); 2615 } catch (RuntimeException e) { 2616 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2617 Slog.wtf(TAG, "Package Manager Crash", e); 2618 } 2619 throw e; 2620 } 2621 } 2622 2623 void cleanupInstallFailedPackage(PackageSetting ps) { 2624 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2625 2626 removeDataDirsLI(ps.volumeUuid, ps.name); 2627 if (ps.codePath != null) { 2628 if (ps.codePath.isDirectory()) { 2629 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2630 } else { 2631 ps.codePath.delete(); 2632 } 2633 } 2634 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2635 if (ps.resourcePath.isDirectory()) { 2636 FileUtils.deleteContents(ps.resourcePath); 2637 } 2638 ps.resourcePath.delete(); 2639 } 2640 mSettings.removePackageLPw(ps.name); 2641 } 2642 2643 static int[] appendInts(int[] cur, int[] add) { 2644 if (add == null) return cur; 2645 if (cur == null) return add; 2646 final int N = add.length; 2647 for (int i=0; i<N; i++) { 2648 cur = appendInt(cur, add[i]); 2649 } 2650 return cur; 2651 } 2652 2653 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2654 if (!sUserManager.exists(userId)) return null; 2655 final PackageSetting ps = (PackageSetting) p.mExtras; 2656 if (ps == null) { 2657 return null; 2658 } 2659 2660 final PermissionsState permissionsState = ps.getPermissionsState(); 2661 2662 final int[] gids = permissionsState.computeGids(userId); 2663 final Set<String> permissions = permissionsState.getPermissions(userId); 2664 final PackageUserState state = ps.readUserState(userId); 2665 2666 return PackageParser.generatePackageInfo(p, gids, flags, 2667 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2668 } 2669 2670 @Override 2671 public boolean isPackageFrozen(String packageName) { 2672 synchronized (mPackages) { 2673 final PackageSetting ps = mSettings.mPackages.get(packageName); 2674 if (ps != null) { 2675 return ps.frozen; 2676 } 2677 } 2678 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2679 return true; 2680 } 2681 2682 @Override 2683 public boolean isPackageAvailable(String packageName, int userId) { 2684 if (!sUserManager.exists(userId)) return false; 2685 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2686 synchronized (mPackages) { 2687 PackageParser.Package p = mPackages.get(packageName); 2688 if (p != null) { 2689 final PackageSetting ps = (PackageSetting) p.mExtras; 2690 if (ps != null) { 2691 final PackageUserState state = ps.readUserState(userId); 2692 if (state != null) { 2693 return PackageParser.isAvailable(state); 2694 } 2695 } 2696 } 2697 } 2698 return false; 2699 } 2700 2701 @Override 2702 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2703 if (!sUserManager.exists(userId)) return null; 2704 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2705 // reader 2706 synchronized (mPackages) { 2707 PackageParser.Package p = mPackages.get(packageName); 2708 if (DEBUG_PACKAGE_INFO) 2709 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2710 if (p != null) { 2711 return generatePackageInfo(p, flags, userId); 2712 } 2713 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2714 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2715 } 2716 } 2717 return null; 2718 } 2719 2720 @Override 2721 public String[] currentToCanonicalPackageNames(String[] names) { 2722 String[] out = new String[names.length]; 2723 // reader 2724 synchronized (mPackages) { 2725 for (int i=names.length-1; i>=0; i--) { 2726 PackageSetting ps = mSettings.mPackages.get(names[i]); 2727 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2728 } 2729 } 2730 return out; 2731 } 2732 2733 @Override 2734 public String[] canonicalToCurrentPackageNames(String[] names) { 2735 String[] out = new String[names.length]; 2736 // reader 2737 synchronized (mPackages) { 2738 for (int i=names.length-1; i>=0; i--) { 2739 String cur = mSettings.mRenamedPackages.get(names[i]); 2740 out[i] = cur != null ? cur : names[i]; 2741 } 2742 } 2743 return out; 2744 } 2745 2746 @Override 2747 public int getPackageUid(String packageName, int userId) { 2748 if (!sUserManager.exists(userId)) return -1; 2749 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2750 2751 // reader 2752 synchronized (mPackages) { 2753 PackageParser.Package p = mPackages.get(packageName); 2754 if(p != null) { 2755 return UserHandle.getUid(userId, p.applicationInfo.uid); 2756 } 2757 PackageSetting ps = mSettings.mPackages.get(packageName); 2758 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2759 return -1; 2760 } 2761 p = ps.pkg; 2762 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2763 } 2764 } 2765 2766 @Override 2767 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2768 if (!sUserManager.exists(userId)) { 2769 return null; 2770 } 2771 2772 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2773 "getPackageGids"); 2774 2775 // reader 2776 synchronized (mPackages) { 2777 PackageParser.Package p = mPackages.get(packageName); 2778 if (DEBUG_PACKAGE_INFO) { 2779 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2780 } 2781 if (p != null) { 2782 PackageSetting ps = (PackageSetting) p.mExtras; 2783 return ps.getPermissionsState().computeGids(userId); 2784 } 2785 } 2786 2787 return null; 2788 } 2789 2790 static PermissionInfo generatePermissionInfo( 2791 BasePermission bp, int flags) { 2792 if (bp.perm != null) { 2793 return PackageParser.generatePermissionInfo(bp.perm, flags); 2794 } 2795 PermissionInfo pi = new PermissionInfo(); 2796 pi.name = bp.name; 2797 pi.packageName = bp.sourcePackage; 2798 pi.nonLocalizedLabel = bp.name; 2799 pi.protectionLevel = bp.protectionLevel; 2800 return pi; 2801 } 2802 2803 @Override 2804 public PermissionInfo getPermissionInfo(String name, int flags) { 2805 // reader 2806 synchronized (mPackages) { 2807 final BasePermission p = mSettings.mPermissions.get(name); 2808 if (p != null) { 2809 return generatePermissionInfo(p, flags); 2810 } 2811 return null; 2812 } 2813 } 2814 2815 @Override 2816 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2817 // reader 2818 synchronized (mPackages) { 2819 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2820 for (BasePermission p : mSettings.mPermissions.values()) { 2821 if (group == null) { 2822 if (p.perm == null || p.perm.info.group == null) { 2823 out.add(generatePermissionInfo(p, flags)); 2824 } 2825 } else { 2826 if (p.perm != null && group.equals(p.perm.info.group)) { 2827 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2828 } 2829 } 2830 } 2831 2832 if (out.size() > 0) { 2833 return out; 2834 } 2835 return mPermissionGroups.containsKey(group) ? out : null; 2836 } 2837 } 2838 2839 @Override 2840 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2841 // reader 2842 synchronized (mPackages) { 2843 return PackageParser.generatePermissionGroupInfo( 2844 mPermissionGroups.get(name), flags); 2845 } 2846 } 2847 2848 @Override 2849 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2850 // reader 2851 synchronized (mPackages) { 2852 final int N = mPermissionGroups.size(); 2853 ArrayList<PermissionGroupInfo> out 2854 = new ArrayList<PermissionGroupInfo>(N); 2855 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2856 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2857 } 2858 return out; 2859 } 2860 } 2861 2862 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2863 int userId) { 2864 if (!sUserManager.exists(userId)) return null; 2865 PackageSetting ps = mSettings.mPackages.get(packageName); 2866 if (ps != null) { 2867 if (ps.pkg == null) { 2868 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2869 flags, userId); 2870 if (pInfo != null) { 2871 return pInfo.applicationInfo; 2872 } 2873 return null; 2874 } 2875 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2876 ps.readUserState(userId), userId); 2877 } 2878 return null; 2879 } 2880 2881 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2882 int userId) { 2883 if (!sUserManager.exists(userId)) return null; 2884 PackageSetting ps = mSettings.mPackages.get(packageName); 2885 if (ps != null) { 2886 PackageParser.Package pkg = ps.pkg; 2887 if (pkg == null) { 2888 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2889 return null; 2890 } 2891 // Only data remains, so we aren't worried about code paths 2892 pkg = new PackageParser.Package(packageName); 2893 pkg.applicationInfo.packageName = packageName; 2894 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2895 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2896 pkg.applicationInfo.dataDir = Environment 2897 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2898 .getAbsolutePath(); 2899 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2900 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2901 } 2902 return generatePackageInfo(pkg, flags, userId); 2903 } 2904 return null; 2905 } 2906 2907 @Override 2908 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2911 // writer 2912 synchronized (mPackages) { 2913 PackageParser.Package p = mPackages.get(packageName); 2914 if (DEBUG_PACKAGE_INFO) Log.v( 2915 TAG, "getApplicationInfo " + packageName 2916 + ": " + p); 2917 if (p != null) { 2918 PackageSetting ps = mSettings.mPackages.get(packageName); 2919 if (ps == null) return null; 2920 // Note: isEnabledLP() does not apply here - always return info 2921 return PackageParser.generateApplicationInfo( 2922 p, flags, ps.readUserState(userId), userId); 2923 } 2924 if ("android".equals(packageName)||"system".equals(packageName)) { 2925 return mAndroidApplication; 2926 } 2927 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2928 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2929 } 2930 } 2931 return null; 2932 } 2933 2934 @Override 2935 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2936 final IPackageDataObserver observer) { 2937 mContext.enforceCallingOrSelfPermission( 2938 android.Manifest.permission.CLEAR_APP_CACHE, null); 2939 // Queue up an async operation since clearing cache may take a little while. 2940 mHandler.post(new Runnable() { 2941 public void run() { 2942 mHandler.removeCallbacks(this); 2943 int retCode = -1; 2944 synchronized (mInstallLock) { 2945 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2946 if (retCode < 0) { 2947 Slog.w(TAG, "Couldn't clear application caches"); 2948 } 2949 } 2950 if (observer != null) { 2951 try { 2952 observer.onRemoveCompleted(null, (retCode >= 0)); 2953 } catch (RemoteException e) { 2954 Slog.w(TAG, "RemoveException when invoking call back"); 2955 } 2956 } 2957 } 2958 }); 2959 } 2960 2961 @Override 2962 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2963 final IntentSender pi) { 2964 mContext.enforceCallingOrSelfPermission( 2965 android.Manifest.permission.CLEAR_APP_CACHE, null); 2966 // Queue up an async operation since clearing cache may take a little while. 2967 mHandler.post(new Runnable() { 2968 public void run() { 2969 mHandler.removeCallbacks(this); 2970 int retCode = -1; 2971 synchronized (mInstallLock) { 2972 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2973 if (retCode < 0) { 2974 Slog.w(TAG, "Couldn't clear application caches"); 2975 } 2976 } 2977 if(pi != null) { 2978 try { 2979 // Callback via pending intent 2980 int code = (retCode >= 0) ? 1 : 0; 2981 pi.sendIntent(null, code, null, 2982 null, null); 2983 } catch (SendIntentException e1) { 2984 Slog.i(TAG, "Failed to send pending intent"); 2985 } 2986 } 2987 } 2988 }); 2989 } 2990 2991 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2992 synchronized (mInstallLock) { 2993 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2994 throw new IOException("Failed to free enough space"); 2995 } 2996 } 2997 } 2998 2999 @Override 3000 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3001 if (!sUserManager.exists(userId)) return null; 3002 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3003 synchronized (mPackages) { 3004 PackageParser.Activity a = mActivities.mActivities.get(component); 3005 3006 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3007 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3008 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3009 if (ps == null) return null; 3010 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3011 userId); 3012 } 3013 if (mResolveComponentName.equals(component)) { 3014 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3015 new PackageUserState(), userId); 3016 } 3017 } 3018 return null; 3019 } 3020 3021 @Override 3022 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3023 String resolvedType) { 3024 synchronized (mPackages) { 3025 if (component.equals(mResolveComponentName)) { 3026 // The resolver supports EVERYTHING! 3027 return true; 3028 } 3029 PackageParser.Activity a = mActivities.mActivities.get(component); 3030 if (a == null) { 3031 return false; 3032 } 3033 for (int i=0; i<a.intents.size(); i++) { 3034 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3035 intent.getData(), intent.getCategories(), TAG) >= 0) { 3036 return true; 3037 } 3038 } 3039 return false; 3040 } 3041 } 3042 3043 @Override 3044 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3045 if (!sUserManager.exists(userId)) return null; 3046 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3047 synchronized (mPackages) { 3048 PackageParser.Activity a = mReceivers.mActivities.get(component); 3049 if (DEBUG_PACKAGE_INFO) Log.v( 3050 TAG, "getReceiverInfo " + component + ": " + a); 3051 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3052 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3053 if (ps == null) return null; 3054 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3055 userId); 3056 } 3057 } 3058 return null; 3059 } 3060 3061 @Override 3062 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3063 if (!sUserManager.exists(userId)) return null; 3064 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3065 synchronized (mPackages) { 3066 PackageParser.Service s = mServices.mServices.get(component); 3067 if (DEBUG_PACKAGE_INFO) Log.v( 3068 TAG, "getServiceInfo " + component + ": " + s); 3069 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3070 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3071 if (ps == null) return null; 3072 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3073 userId); 3074 } 3075 } 3076 return null; 3077 } 3078 3079 @Override 3080 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3081 if (!sUserManager.exists(userId)) return null; 3082 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3083 synchronized (mPackages) { 3084 PackageParser.Provider p = mProviders.mProviders.get(component); 3085 if (DEBUG_PACKAGE_INFO) Log.v( 3086 TAG, "getProviderInfo " + component + ": " + p); 3087 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3088 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3089 if (ps == null) return null; 3090 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3091 userId); 3092 } 3093 } 3094 return null; 3095 } 3096 3097 @Override 3098 public String[] getSystemSharedLibraryNames() { 3099 Set<String> libSet; 3100 synchronized (mPackages) { 3101 libSet = mSharedLibraries.keySet(); 3102 int size = libSet.size(); 3103 if (size > 0) { 3104 String[] libs = new String[size]; 3105 libSet.toArray(libs); 3106 return libs; 3107 } 3108 } 3109 return null; 3110 } 3111 3112 /** 3113 * @hide 3114 */ 3115 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3116 synchronized (mPackages) { 3117 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3118 if (lib != null && lib.apk != null) { 3119 return mPackages.get(lib.apk); 3120 } 3121 } 3122 return null; 3123 } 3124 3125 @Override 3126 public FeatureInfo[] getSystemAvailableFeatures() { 3127 Collection<FeatureInfo> featSet; 3128 synchronized (mPackages) { 3129 featSet = mAvailableFeatures.values(); 3130 int size = featSet.size(); 3131 if (size > 0) { 3132 FeatureInfo[] features = new FeatureInfo[size+1]; 3133 featSet.toArray(features); 3134 FeatureInfo fi = new FeatureInfo(); 3135 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3136 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3137 features[size] = fi; 3138 return features; 3139 } 3140 } 3141 return null; 3142 } 3143 3144 @Override 3145 public boolean hasSystemFeature(String name) { 3146 synchronized (mPackages) { 3147 return mAvailableFeatures.containsKey(name); 3148 } 3149 } 3150 3151 private void checkValidCaller(int uid, int userId) { 3152 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3153 return; 3154 3155 throw new SecurityException("Caller uid=" + uid 3156 + " is not privileged to communicate with user=" + userId); 3157 } 3158 3159 @Override 3160 public int checkPermission(String permName, String pkgName, int userId) { 3161 if (!sUserManager.exists(userId)) { 3162 return PackageManager.PERMISSION_DENIED; 3163 } 3164 3165 synchronized (mPackages) { 3166 final PackageParser.Package p = mPackages.get(pkgName); 3167 if (p != null && p.mExtras != null) { 3168 final PackageSetting ps = (PackageSetting) p.mExtras; 3169 final PermissionsState permissionsState = ps.getPermissionsState(); 3170 if (permissionsState.hasPermission(permName, userId)) { 3171 return PackageManager.PERMISSION_GRANTED; 3172 } 3173 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3174 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3175 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3176 return PackageManager.PERMISSION_GRANTED; 3177 } 3178 } 3179 } 3180 3181 return PackageManager.PERMISSION_DENIED; 3182 } 3183 3184 @Override 3185 public int checkUidPermission(String permName, int uid) { 3186 final int userId = UserHandle.getUserId(uid); 3187 3188 if (!sUserManager.exists(userId)) { 3189 return PackageManager.PERMISSION_DENIED; 3190 } 3191 3192 synchronized (mPackages) { 3193 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3194 if (obj != null) { 3195 final SettingBase ps = (SettingBase) obj; 3196 final PermissionsState permissionsState = ps.getPermissionsState(); 3197 if (permissionsState.hasPermission(permName, userId)) { 3198 return PackageManager.PERMISSION_GRANTED; 3199 } 3200 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3201 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3202 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3203 return PackageManager.PERMISSION_GRANTED; 3204 } 3205 } else { 3206 ArraySet<String> perms = mSystemPermissions.get(uid); 3207 if (perms != null) { 3208 if (perms.contains(permName)) { 3209 return PackageManager.PERMISSION_GRANTED; 3210 } 3211 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3212 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3213 return PackageManager.PERMISSION_GRANTED; 3214 } 3215 } 3216 } 3217 } 3218 3219 return PackageManager.PERMISSION_DENIED; 3220 } 3221 3222 @Override 3223 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3224 if (UserHandle.getCallingUserId() != userId) { 3225 mContext.enforceCallingPermission( 3226 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3227 "isPermissionRevokedByPolicy for user " + userId); 3228 } 3229 3230 if (checkPermission(permission, packageName, userId) 3231 == PackageManager.PERMISSION_GRANTED) { 3232 return false; 3233 } 3234 3235 final long identity = Binder.clearCallingIdentity(); 3236 try { 3237 final int flags = getPermissionFlags(permission, packageName, userId); 3238 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3239 } finally { 3240 Binder.restoreCallingIdentity(identity); 3241 } 3242 } 3243 3244 @Override 3245 public String getPermissionControllerPackageName() { 3246 synchronized (mPackages) { 3247 return mRequiredInstallerPackage; 3248 } 3249 } 3250 3251 /** 3252 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3253 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3254 * @param checkShell TODO(yamasani): 3255 * @param message the message to log on security exception 3256 */ 3257 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3258 boolean checkShell, String message) { 3259 if (userId < 0) { 3260 throw new IllegalArgumentException("Invalid userId " + userId); 3261 } 3262 if (checkShell) { 3263 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3264 } 3265 if (userId == UserHandle.getUserId(callingUid)) return; 3266 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3267 if (requireFullPermission) { 3268 mContext.enforceCallingOrSelfPermission( 3269 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3270 } else { 3271 try { 3272 mContext.enforceCallingOrSelfPermission( 3273 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3274 } catch (SecurityException se) { 3275 mContext.enforceCallingOrSelfPermission( 3276 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3277 } 3278 } 3279 } 3280 } 3281 3282 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3283 if (callingUid == Process.SHELL_UID) { 3284 if (userHandle >= 0 3285 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3286 throw new SecurityException("Shell does not have permission to access user " 3287 + userHandle); 3288 } else if (userHandle < 0) { 3289 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3290 + Debug.getCallers(3)); 3291 } 3292 } 3293 } 3294 3295 private BasePermission findPermissionTreeLP(String permName) { 3296 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3297 if (permName.startsWith(bp.name) && 3298 permName.length() > bp.name.length() && 3299 permName.charAt(bp.name.length()) == '.') { 3300 return bp; 3301 } 3302 } 3303 return null; 3304 } 3305 3306 private BasePermission checkPermissionTreeLP(String permName) { 3307 if (permName != null) { 3308 BasePermission bp = findPermissionTreeLP(permName); 3309 if (bp != null) { 3310 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3311 return bp; 3312 } 3313 throw new SecurityException("Calling uid " 3314 + Binder.getCallingUid() 3315 + " is not allowed to add to permission tree " 3316 + bp.name + " owned by uid " + bp.uid); 3317 } 3318 } 3319 throw new SecurityException("No permission tree found for " + permName); 3320 } 3321 3322 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3323 if (s1 == null) { 3324 return s2 == null; 3325 } 3326 if (s2 == null) { 3327 return false; 3328 } 3329 if (s1.getClass() != s2.getClass()) { 3330 return false; 3331 } 3332 return s1.equals(s2); 3333 } 3334 3335 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3336 if (pi1.icon != pi2.icon) return false; 3337 if (pi1.logo != pi2.logo) return false; 3338 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3339 if (!compareStrings(pi1.name, pi2.name)) return false; 3340 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3341 // We'll take care of setting this one. 3342 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3343 // These are not currently stored in settings. 3344 //if (!compareStrings(pi1.group, pi2.group)) return false; 3345 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3346 //if (pi1.labelRes != pi2.labelRes) return false; 3347 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3348 return true; 3349 } 3350 3351 int permissionInfoFootprint(PermissionInfo info) { 3352 int size = info.name.length(); 3353 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3354 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3355 return size; 3356 } 3357 3358 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3359 int size = 0; 3360 for (BasePermission perm : mSettings.mPermissions.values()) { 3361 if (perm.uid == tree.uid) { 3362 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3363 } 3364 } 3365 return size; 3366 } 3367 3368 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3369 // We calculate the max size of permissions defined by this uid and throw 3370 // if that plus the size of 'info' would exceed our stated maximum. 3371 if (tree.uid != Process.SYSTEM_UID) { 3372 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3373 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3374 throw new SecurityException("Permission tree size cap exceeded"); 3375 } 3376 } 3377 } 3378 3379 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3380 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3381 throw new SecurityException("Label must be specified in permission"); 3382 } 3383 BasePermission tree = checkPermissionTreeLP(info.name); 3384 BasePermission bp = mSettings.mPermissions.get(info.name); 3385 boolean added = bp == null; 3386 boolean changed = true; 3387 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3388 if (added) { 3389 enforcePermissionCapLocked(info, tree); 3390 bp = new BasePermission(info.name, tree.sourcePackage, 3391 BasePermission.TYPE_DYNAMIC); 3392 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3393 throw new SecurityException( 3394 "Not allowed to modify non-dynamic permission " 3395 + info.name); 3396 } else { 3397 if (bp.protectionLevel == fixedLevel 3398 && bp.perm.owner.equals(tree.perm.owner) 3399 && bp.uid == tree.uid 3400 && comparePermissionInfos(bp.perm.info, info)) { 3401 changed = false; 3402 } 3403 } 3404 bp.protectionLevel = fixedLevel; 3405 info = new PermissionInfo(info); 3406 info.protectionLevel = fixedLevel; 3407 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3408 bp.perm.info.packageName = tree.perm.info.packageName; 3409 bp.uid = tree.uid; 3410 if (added) { 3411 mSettings.mPermissions.put(info.name, bp); 3412 } 3413 if (changed) { 3414 if (!async) { 3415 mSettings.writeLPr(); 3416 } else { 3417 scheduleWriteSettingsLocked(); 3418 } 3419 } 3420 return added; 3421 } 3422 3423 @Override 3424 public boolean addPermission(PermissionInfo info) { 3425 synchronized (mPackages) { 3426 return addPermissionLocked(info, false); 3427 } 3428 } 3429 3430 @Override 3431 public boolean addPermissionAsync(PermissionInfo info) { 3432 synchronized (mPackages) { 3433 return addPermissionLocked(info, true); 3434 } 3435 } 3436 3437 @Override 3438 public void removePermission(String name) { 3439 synchronized (mPackages) { 3440 checkPermissionTreeLP(name); 3441 BasePermission bp = mSettings.mPermissions.get(name); 3442 if (bp != null) { 3443 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3444 throw new SecurityException( 3445 "Not allowed to modify non-dynamic permission " 3446 + name); 3447 } 3448 mSettings.mPermissions.remove(name); 3449 mSettings.writeLPr(); 3450 } 3451 } 3452 } 3453 3454 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3455 BasePermission bp) { 3456 int index = pkg.requestedPermissions.indexOf(bp.name); 3457 if (index == -1) { 3458 throw new SecurityException("Package " + pkg.packageName 3459 + " has not requested permission " + bp.name); 3460 } 3461 if (!bp.isRuntime() && !bp.isDevelopment()) { 3462 throw new SecurityException("Permission " + bp.name 3463 + " is not a changeable permission type"); 3464 } 3465 } 3466 3467 @Override 3468 public void grantRuntimePermission(String packageName, String name, final int userId) { 3469 if (!sUserManager.exists(userId)) { 3470 Log.e(TAG, "No such user:" + userId); 3471 return; 3472 } 3473 3474 mContext.enforceCallingOrSelfPermission( 3475 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3476 "grantRuntimePermission"); 3477 3478 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3479 "grantRuntimePermission"); 3480 3481 final int uid; 3482 final SettingBase sb; 3483 3484 synchronized (mPackages) { 3485 final PackageParser.Package pkg = mPackages.get(packageName); 3486 if (pkg == null) { 3487 throw new IllegalArgumentException("Unknown package: " + packageName); 3488 } 3489 3490 final BasePermission bp = mSettings.mPermissions.get(name); 3491 if (bp == null) { 3492 throw new IllegalArgumentException("Unknown permission: " + name); 3493 } 3494 3495 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3496 3497 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3498 sb = (SettingBase) pkg.mExtras; 3499 if (sb == null) { 3500 throw new IllegalArgumentException("Unknown package: " + packageName); 3501 } 3502 3503 final PermissionsState permissionsState = sb.getPermissionsState(); 3504 3505 final int flags = permissionsState.getPermissionFlags(name, userId); 3506 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3507 throw new SecurityException("Cannot grant system fixed permission: " 3508 + name + " for package: " + packageName); 3509 } 3510 3511 if (bp.isDevelopment()) { 3512 // Development permissions must be handled specially, since they are not 3513 // normal runtime permissions. For now they apply to all users. 3514 if (permissionsState.grantInstallPermission(bp) != 3515 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3516 scheduleWriteSettingsLocked(); 3517 } 3518 return; 3519 } 3520 3521 final int result = permissionsState.grantRuntimePermission(bp, userId); 3522 switch (result) { 3523 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3524 return; 3525 } 3526 3527 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3528 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3529 mHandler.post(new Runnable() { 3530 @Override 3531 public void run() { 3532 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3533 } 3534 }); 3535 } break; 3536 } 3537 3538 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3539 3540 // Not critical if that is lost - app has to request again. 3541 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3542 } 3543 3544 // Only need to do this if user is initialized. Otherwise it's a new user 3545 // and there are no processes running as the user yet and there's no need 3546 // to make an expensive call to remount processes for the changed permissions. 3547 if (READ_EXTERNAL_STORAGE.equals(name) 3548 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3549 final long token = Binder.clearCallingIdentity(); 3550 try { 3551 if (sUserManager.isInitialized(userId)) { 3552 MountServiceInternal mountServiceInternal = LocalServices.getService( 3553 MountServiceInternal.class); 3554 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3555 } 3556 } finally { 3557 Binder.restoreCallingIdentity(token); 3558 } 3559 } 3560 } 3561 3562 @Override 3563 public void revokeRuntimePermission(String packageName, String name, int userId) { 3564 if (!sUserManager.exists(userId)) { 3565 Log.e(TAG, "No such user:" + userId); 3566 return; 3567 } 3568 3569 mContext.enforceCallingOrSelfPermission( 3570 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3571 "revokeRuntimePermission"); 3572 3573 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3574 "revokeRuntimePermission"); 3575 3576 final int appId; 3577 3578 synchronized (mPackages) { 3579 final PackageParser.Package pkg = mPackages.get(packageName); 3580 if (pkg == null) { 3581 throw new IllegalArgumentException("Unknown package: " + packageName); 3582 } 3583 3584 final BasePermission bp = mSettings.mPermissions.get(name); 3585 if (bp == null) { 3586 throw new IllegalArgumentException("Unknown permission: " + name); 3587 } 3588 3589 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3590 3591 SettingBase sb = (SettingBase) pkg.mExtras; 3592 if (sb == null) { 3593 throw new IllegalArgumentException("Unknown package: " + packageName); 3594 } 3595 3596 final PermissionsState permissionsState = sb.getPermissionsState(); 3597 3598 final int flags = permissionsState.getPermissionFlags(name, userId); 3599 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3600 throw new SecurityException("Cannot revoke system fixed permission: " 3601 + name + " for package: " + packageName); 3602 } 3603 3604 if (bp.isDevelopment()) { 3605 // Development permissions must be handled specially, since they are not 3606 // normal runtime permissions. For now they apply to all users. 3607 if (permissionsState.revokeInstallPermission(bp) != 3608 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3609 scheduleWriteSettingsLocked(); 3610 } 3611 return; 3612 } 3613 3614 if (permissionsState.revokeRuntimePermission(bp, userId) == 3615 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3616 return; 3617 } 3618 3619 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3620 3621 // Critical, after this call app should never have the permission. 3622 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3623 3624 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3625 } 3626 3627 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3628 } 3629 3630 @Override 3631 public void resetRuntimePermissions() { 3632 mContext.enforceCallingOrSelfPermission( 3633 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3634 "revokeRuntimePermission"); 3635 3636 int callingUid = Binder.getCallingUid(); 3637 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3638 mContext.enforceCallingOrSelfPermission( 3639 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3640 "resetRuntimePermissions"); 3641 } 3642 3643 synchronized (mPackages) { 3644 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3645 for (int userId : UserManagerService.getInstance().getUserIds()) { 3646 final int packageCount = mPackages.size(); 3647 for (int i = 0; i < packageCount; i++) { 3648 PackageParser.Package pkg = mPackages.valueAt(i); 3649 if (!(pkg.mExtras instanceof PackageSetting)) { 3650 continue; 3651 } 3652 PackageSetting ps = (PackageSetting) pkg.mExtras; 3653 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3654 } 3655 } 3656 } 3657 } 3658 3659 @Override 3660 public int getPermissionFlags(String name, String packageName, int userId) { 3661 if (!sUserManager.exists(userId)) { 3662 return 0; 3663 } 3664 3665 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3666 3667 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3668 "getPermissionFlags"); 3669 3670 synchronized (mPackages) { 3671 final PackageParser.Package pkg = mPackages.get(packageName); 3672 if (pkg == null) { 3673 throw new IllegalArgumentException("Unknown package: " + packageName); 3674 } 3675 3676 final BasePermission bp = mSettings.mPermissions.get(name); 3677 if (bp == null) { 3678 throw new IllegalArgumentException("Unknown permission: " + name); 3679 } 3680 3681 SettingBase sb = (SettingBase) pkg.mExtras; 3682 if (sb == null) { 3683 throw new IllegalArgumentException("Unknown package: " + packageName); 3684 } 3685 3686 PermissionsState permissionsState = sb.getPermissionsState(); 3687 return permissionsState.getPermissionFlags(name, userId); 3688 } 3689 } 3690 3691 @Override 3692 public void updatePermissionFlags(String name, String packageName, int flagMask, 3693 int flagValues, int userId) { 3694 if (!sUserManager.exists(userId)) { 3695 return; 3696 } 3697 3698 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3699 3700 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3701 "updatePermissionFlags"); 3702 3703 // Only the system can change these flags and nothing else. 3704 if (getCallingUid() != Process.SYSTEM_UID) { 3705 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3706 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3707 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3708 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3709 } 3710 3711 synchronized (mPackages) { 3712 final PackageParser.Package pkg = mPackages.get(packageName); 3713 if (pkg == null) { 3714 throw new IllegalArgumentException("Unknown package: " + packageName); 3715 } 3716 3717 final BasePermission bp = mSettings.mPermissions.get(name); 3718 if (bp == null) { 3719 throw new IllegalArgumentException("Unknown permission: " + name); 3720 } 3721 3722 SettingBase sb = (SettingBase) pkg.mExtras; 3723 if (sb == null) { 3724 throw new IllegalArgumentException("Unknown package: " + packageName); 3725 } 3726 3727 PermissionsState permissionsState = sb.getPermissionsState(); 3728 3729 // Only the package manager can change flags for system component permissions. 3730 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3731 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3732 return; 3733 } 3734 3735 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3736 3737 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3738 // Install and runtime permissions are stored in different places, 3739 // so figure out what permission changed and persist the change. 3740 if (permissionsState.getInstallPermissionState(name) != null) { 3741 scheduleWriteSettingsLocked(); 3742 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3743 || hadState) { 3744 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3745 } 3746 } 3747 } 3748 } 3749 3750 /** 3751 * Update the permission flags for all packages and runtime permissions of a user in order 3752 * to allow device or profile owner to remove POLICY_FIXED. 3753 */ 3754 @Override 3755 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3756 if (!sUserManager.exists(userId)) { 3757 return; 3758 } 3759 3760 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3761 3762 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3763 "updatePermissionFlagsForAllApps"); 3764 3765 // Only the system can change system fixed flags. 3766 if (getCallingUid() != Process.SYSTEM_UID) { 3767 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3768 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3769 } 3770 3771 synchronized (mPackages) { 3772 boolean changed = false; 3773 final int packageCount = mPackages.size(); 3774 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3775 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3776 SettingBase sb = (SettingBase) pkg.mExtras; 3777 if (sb == null) { 3778 continue; 3779 } 3780 PermissionsState permissionsState = sb.getPermissionsState(); 3781 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3782 userId, flagMask, flagValues); 3783 } 3784 if (changed) { 3785 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3786 } 3787 } 3788 } 3789 3790 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3791 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3792 != PackageManager.PERMISSION_GRANTED 3793 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3794 != PackageManager.PERMISSION_GRANTED) { 3795 throw new SecurityException(message + " requires " 3796 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3797 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3798 } 3799 } 3800 3801 @Override 3802 public boolean shouldShowRequestPermissionRationale(String permissionName, 3803 String packageName, int userId) { 3804 if (UserHandle.getCallingUserId() != userId) { 3805 mContext.enforceCallingPermission( 3806 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3807 "canShowRequestPermissionRationale for user " + userId); 3808 } 3809 3810 final int uid = getPackageUid(packageName, userId); 3811 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3812 return false; 3813 } 3814 3815 if (checkPermission(permissionName, packageName, userId) 3816 == PackageManager.PERMISSION_GRANTED) { 3817 return false; 3818 } 3819 3820 final int flags; 3821 3822 final long identity = Binder.clearCallingIdentity(); 3823 try { 3824 flags = getPermissionFlags(permissionName, 3825 packageName, userId); 3826 } finally { 3827 Binder.restoreCallingIdentity(identity); 3828 } 3829 3830 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3831 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3832 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3833 3834 if ((flags & fixedFlags) != 0) { 3835 return false; 3836 } 3837 3838 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3839 } 3840 3841 @Override 3842 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3843 mContext.enforceCallingOrSelfPermission( 3844 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3845 "addOnPermissionsChangeListener"); 3846 3847 synchronized (mPackages) { 3848 mOnPermissionChangeListeners.addListenerLocked(listener); 3849 } 3850 } 3851 3852 @Override 3853 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3854 synchronized (mPackages) { 3855 mOnPermissionChangeListeners.removeListenerLocked(listener); 3856 } 3857 } 3858 3859 @Override 3860 public boolean isProtectedBroadcast(String actionName) { 3861 synchronized (mPackages) { 3862 return mProtectedBroadcasts.contains(actionName); 3863 } 3864 } 3865 3866 @Override 3867 public int checkSignatures(String pkg1, String pkg2) { 3868 synchronized (mPackages) { 3869 final PackageParser.Package p1 = mPackages.get(pkg1); 3870 final PackageParser.Package p2 = mPackages.get(pkg2); 3871 if (p1 == null || p1.mExtras == null 3872 || p2 == null || p2.mExtras == null) { 3873 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3874 } 3875 return compareSignatures(p1.mSignatures, p2.mSignatures); 3876 } 3877 } 3878 3879 @Override 3880 public int checkUidSignatures(int uid1, int uid2) { 3881 // Map to base uids. 3882 uid1 = UserHandle.getAppId(uid1); 3883 uid2 = UserHandle.getAppId(uid2); 3884 // reader 3885 synchronized (mPackages) { 3886 Signature[] s1; 3887 Signature[] s2; 3888 Object obj = mSettings.getUserIdLPr(uid1); 3889 if (obj != null) { 3890 if (obj instanceof SharedUserSetting) { 3891 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3892 } else if (obj instanceof PackageSetting) { 3893 s1 = ((PackageSetting)obj).signatures.mSignatures; 3894 } else { 3895 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3896 } 3897 } else { 3898 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3899 } 3900 obj = mSettings.getUserIdLPr(uid2); 3901 if (obj != null) { 3902 if (obj instanceof SharedUserSetting) { 3903 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3904 } else if (obj instanceof PackageSetting) { 3905 s2 = ((PackageSetting)obj).signatures.mSignatures; 3906 } else { 3907 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3908 } 3909 } else { 3910 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3911 } 3912 return compareSignatures(s1, s2); 3913 } 3914 } 3915 3916 private void killUid(int appId, int userId, String reason) { 3917 final long identity = Binder.clearCallingIdentity(); 3918 try { 3919 IActivityManager am = ActivityManagerNative.getDefault(); 3920 if (am != null) { 3921 try { 3922 am.killUid(appId, userId, reason); 3923 } catch (RemoteException e) { 3924 /* ignore - same process */ 3925 } 3926 } 3927 } finally { 3928 Binder.restoreCallingIdentity(identity); 3929 } 3930 } 3931 3932 /** 3933 * Compares two sets of signatures. Returns: 3934 * <br /> 3935 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3936 * <br /> 3937 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3938 * <br /> 3939 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3940 * <br /> 3941 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3942 * <br /> 3943 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3944 */ 3945 static int compareSignatures(Signature[] s1, Signature[] s2) { 3946 if (s1 == null) { 3947 return s2 == null 3948 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3949 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3950 } 3951 3952 if (s2 == null) { 3953 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3954 } 3955 3956 if (s1.length != s2.length) { 3957 return PackageManager.SIGNATURE_NO_MATCH; 3958 } 3959 3960 // Since both signature sets are of size 1, we can compare without HashSets. 3961 if (s1.length == 1) { 3962 return s1[0].equals(s2[0]) ? 3963 PackageManager.SIGNATURE_MATCH : 3964 PackageManager.SIGNATURE_NO_MATCH; 3965 } 3966 3967 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3968 for (Signature sig : s1) { 3969 set1.add(sig); 3970 } 3971 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3972 for (Signature sig : s2) { 3973 set2.add(sig); 3974 } 3975 // Make sure s2 contains all signatures in s1. 3976 if (set1.equals(set2)) { 3977 return PackageManager.SIGNATURE_MATCH; 3978 } 3979 return PackageManager.SIGNATURE_NO_MATCH; 3980 } 3981 3982 /** 3983 * If the database version for this type of package (internal storage or 3984 * external storage) is less than the version where package signatures 3985 * were updated, return true. 3986 */ 3987 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3988 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3989 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3990 } 3991 3992 /** 3993 * Used for backward compatibility to make sure any packages with 3994 * certificate chains get upgraded to the new style. {@code existingSigs} 3995 * will be in the old format (since they were stored on disk from before the 3996 * system upgrade) and {@code scannedSigs} will be in the newer format. 3997 */ 3998 private int compareSignaturesCompat(PackageSignatures existingSigs, 3999 PackageParser.Package scannedPkg) { 4000 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4001 return PackageManager.SIGNATURE_NO_MATCH; 4002 } 4003 4004 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4005 for (Signature sig : existingSigs.mSignatures) { 4006 existingSet.add(sig); 4007 } 4008 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4009 for (Signature sig : scannedPkg.mSignatures) { 4010 try { 4011 Signature[] chainSignatures = sig.getChainSignatures(); 4012 for (Signature chainSig : chainSignatures) { 4013 scannedCompatSet.add(chainSig); 4014 } 4015 } catch (CertificateEncodingException e) { 4016 scannedCompatSet.add(sig); 4017 } 4018 } 4019 /* 4020 * Make sure the expanded scanned set contains all signatures in the 4021 * existing one. 4022 */ 4023 if (scannedCompatSet.equals(existingSet)) { 4024 // Migrate the old signatures to the new scheme. 4025 existingSigs.assignSignatures(scannedPkg.mSignatures); 4026 // The new KeySets will be re-added later in the scanning process. 4027 synchronized (mPackages) { 4028 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4029 } 4030 return PackageManager.SIGNATURE_MATCH; 4031 } 4032 return PackageManager.SIGNATURE_NO_MATCH; 4033 } 4034 4035 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4036 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4037 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4038 } 4039 4040 private int compareSignaturesRecover(PackageSignatures existingSigs, 4041 PackageParser.Package scannedPkg) { 4042 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4043 return PackageManager.SIGNATURE_NO_MATCH; 4044 } 4045 4046 String msg = null; 4047 try { 4048 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4049 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4050 + scannedPkg.packageName); 4051 return PackageManager.SIGNATURE_MATCH; 4052 } 4053 } catch (CertificateException e) { 4054 msg = e.getMessage(); 4055 } 4056 4057 logCriticalInfo(Log.INFO, 4058 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4059 return PackageManager.SIGNATURE_NO_MATCH; 4060 } 4061 4062 @Override 4063 public String[] getPackagesForUid(int uid) { 4064 uid = UserHandle.getAppId(uid); 4065 // reader 4066 synchronized (mPackages) { 4067 Object obj = mSettings.getUserIdLPr(uid); 4068 if (obj instanceof SharedUserSetting) { 4069 final SharedUserSetting sus = (SharedUserSetting) obj; 4070 final int N = sus.packages.size(); 4071 final String[] res = new String[N]; 4072 final Iterator<PackageSetting> it = sus.packages.iterator(); 4073 int i = 0; 4074 while (it.hasNext()) { 4075 res[i++] = it.next().name; 4076 } 4077 return res; 4078 } else if (obj instanceof PackageSetting) { 4079 final PackageSetting ps = (PackageSetting) obj; 4080 return new String[] { ps.name }; 4081 } 4082 } 4083 return null; 4084 } 4085 4086 @Override 4087 public String getNameForUid(int uid) { 4088 // reader 4089 synchronized (mPackages) { 4090 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4091 if (obj instanceof SharedUserSetting) { 4092 final SharedUserSetting sus = (SharedUserSetting) obj; 4093 return sus.name + ":" + sus.userId; 4094 } else if (obj instanceof PackageSetting) { 4095 final PackageSetting ps = (PackageSetting) obj; 4096 return ps.name; 4097 } 4098 } 4099 return null; 4100 } 4101 4102 @Override 4103 public int getUidForSharedUser(String sharedUserName) { 4104 if(sharedUserName == null) { 4105 return -1; 4106 } 4107 // reader 4108 synchronized (mPackages) { 4109 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4110 if (suid == null) { 4111 return -1; 4112 } 4113 return suid.userId; 4114 } 4115 } 4116 4117 @Override 4118 public int getFlagsForUid(int uid) { 4119 synchronized (mPackages) { 4120 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4121 if (obj instanceof SharedUserSetting) { 4122 final SharedUserSetting sus = (SharedUserSetting) obj; 4123 return sus.pkgFlags; 4124 } else if (obj instanceof PackageSetting) { 4125 final PackageSetting ps = (PackageSetting) obj; 4126 return ps.pkgFlags; 4127 } 4128 } 4129 return 0; 4130 } 4131 4132 @Override 4133 public int getPrivateFlagsForUid(int uid) { 4134 synchronized (mPackages) { 4135 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4136 if (obj instanceof SharedUserSetting) { 4137 final SharedUserSetting sus = (SharedUserSetting) obj; 4138 return sus.pkgPrivateFlags; 4139 } else if (obj instanceof PackageSetting) { 4140 final PackageSetting ps = (PackageSetting) obj; 4141 return ps.pkgPrivateFlags; 4142 } 4143 } 4144 return 0; 4145 } 4146 4147 @Override 4148 public boolean isUidPrivileged(int uid) { 4149 uid = UserHandle.getAppId(uid); 4150 // reader 4151 synchronized (mPackages) { 4152 Object obj = mSettings.getUserIdLPr(uid); 4153 if (obj instanceof SharedUserSetting) { 4154 final SharedUserSetting sus = (SharedUserSetting) obj; 4155 final Iterator<PackageSetting> it = sus.packages.iterator(); 4156 while (it.hasNext()) { 4157 if (it.next().isPrivileged()) { 4158 return true; 4159 } 4160 } 4161 } else if (obj instanceof PackageSetting) { 4162 final PackageSetting ps = (PackageSetting) obj; 4163 return ps.isPrivileged(); 4164 } 4165 } 4166 return false; 4167 } 4168 4169 @Override 4170 public String[] getAppOpPermissionPackages(String permissionName) { 4171 synchronized (mPackages) { 4172 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4173 if (pkgs == null) { 4174 return null; 4175 } 4176 return pkgs.toArray(new String[pkgs.size()]); 4177 } 4178 } 4179 4180 @Override 4181 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4182 int flags, int userId) { 4183 if (!sUserManager.exists(userId)) return null; 4184 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4185 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4186 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4187 } 4188 4189 @Override 4190 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4191 IntentFilter filter, int match, ComponentName activity) { 4192 final int userId = UserHandle.getCallingUserId(); 4193 if (DEBUG_PREFERRED) { 4194 Log.v(TAG, "setLastChosenActivity intent=" + intent 4195 + " resolvedType=" + resolvedType 4196 + " flags=" + flags 4197 + " filter=" + filter 4198 + " match=" + match 4199 + " activity=" + activity); 4200 filter.dump(new PrintStreamPrinter(System.out), " "); 4201 } 4202 intent.setComponent(null); 4203 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4204 // Find any earlier preferred or last chosen entries and nuke them 4205 findPreferredActivity(intent, resolvedType, 4206 flags, query, 0, false, true, false, userId); 4207 // Add the new activity as the last chosen for this filter 4208 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4209 "Setting last chosen"); 4210 } 4211 4212 @Override 4213 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4214 final int userId = UserHandle.getCallingUserId(); 4215 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4216 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4217 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4218 false, false, false, userId); 4219 } 4220 4221 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4222 int flags, List<ResolveInfo> query, int userId) { 4223 if (query != null) { 4224 final int N = query.size(); 4225 if (N == 1) { 4226 return query.get(0); 4227 } else if (N > 1) { 4228 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4229 // If there is more than one activity with the same priority, 4230 // then let the user decide between them. 4231 ResolveInfo r0 = query.get(0); 4232 ResolveInfo r1 = query.get(1); 4233 if (DEBUG_INTENT_MATCHING || debug) { 4234 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4235 + r1.activityInfo.name + "=" + r1.priority); 4236 } 4237 // If the first activity has a higher priority, or a different 4238 // default, then it is always desireable to pick it. 4239 if (r0.priority != r1.priority 4240 || r0.preferredOrder != r1.preferredOrder 4241 || r0.isDefault != r1.isDefault) { 4242 return query.get(0); 4243 } 4244 // If we have saved a preference for a preferred activity for 4245 // this Intent, use that. 4246 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4247 flags, query, r0.priority, true, false, debug, userId); 4248 if (ri != null) { 4249 return ri; 4250 } 4251 ri = new ResolveInfo(mResolveInfo); 4252 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4253 ri.activityInfo.applicationInfo = new ApplicationInfo( 4254 ri.activityInfo.applicationInfo); 4255 if (userId != 0) { 4256 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4257 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4258 } 4259 // Make sure that the resolver is displayable in car mode 4260 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4261 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4262 return ri; 4263 } 4264 } 4265 return null; 4266 } 4267 4268 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4269 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4270 final int N = query.size(); 4271 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4272 .get(userId); 4273 // Get the list of persistent preferred activities that handle the intent 4274 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4275 List<PersistentPreferredActivity> pprefs = ppir != null 4276 ? ppir.queryIntent(intent, resolvedType, 4277 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4278 : null; 4279 if (pprefs != null && pprefs.size() > 0) { 4280 final int M = pprefs.size(); 4281 for (int i=0; i<M; i++) { 4282 final PersistentPreferredActivity ppa = pprefs.get(i); 4283 if (DEBUG_PREFERRED || debug) { 4284 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4285 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4286 + "\n component=" + ppa.mComponent); 4287 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4288 } 4289 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4290 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4291 if (DEBUG_PREFERRED || debug) { 4292 Slog.v(TAG, "Found persistent preferred activity:"); 4293 if (ai != null) { 4294 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4295 } else { 4296 Slog.v(TAG, " null"); 4297 } 4298 } 4299 if (ai == null) { 4300 // This previously registered persistent preferred activity 4301 // component is no longer known. Ignore it and do NOT remove it. 4302 continue; 4303 } 4304 for (int j=0; j<N; j++) { 4305 final ResolveInfo ri = query.get(j); 4306 if (!ri.activityInfo.applicationInfo.packageName 4307 .equals(ai.applicationInfo.packageName)) { 4308 continue; 4309 } 4310 if (!ri.activityInfo.name.equals(ai.name)) { 4311 continue; 4312 } 4313 // Found a persistent preference that can handle the intent. 4314 if (DEBUG_PREFERRED || debug) { 4315 Slog.v(TAG, "Returning persistent preferred activity: " + 4316 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4317 } 4318 return ri; 4319 } 4320 } 4321 } 4322 return null; 4323 } 4324 4325 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4326 List<ResolveInfo> query, int priority, boolean always, 4327 boolean removeMatches, boolean debug, int userId) { 4328 if (!sUserManager.exists(userId)) return null; 4329 // writer 4330 synchronized (mPackages) { 4331 if (intent.getSelector() != null) { 4332 intent = intent.getSelector(); 4333 } 4334 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4335 4336 // Try to find a matching persistent preferred activity. 4337 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4338 debug, userId); 4339 4340 // If a persistent preferred activity matched, use it. 4341 if (pri != null) { 4342 return pri; 4343 } 4344 4345 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4346 // Get the list of preferred activities that handle the intent 4347 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4348 List<PreferredActivity> prefs = pir != null 4349 ? pir.queryIntent(intent, resolvedType, 4350 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4351 : null; 4352 if (prefs != null && prefs.size() > 0) { 4353 boolean changed = false; 4354 try { 4355 // First figure out how good the original match set is. 4356 // We will only allow preferred activities that came 4357 // from the same match quality. 4358 int match = 0; 4359 4360 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4361 4362 final int N = query.size(); 4363 for (int j=0; j<N; j++) { 4364 final ResolveInfo ri = query.get(j); 4365 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4366 + ": 0x" + Integer.toHexString(match)); 4367 if (ri.match > match) { 4368 match = ri.match; 4369 } 4370 } 4371 4372 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4373 + Integer.toHexString(match)); 4374 4375 match &= IntentFilter.MATCH_CATEGORY_MASK; 4376 final int M = prefs.size(); 4377 for (int i=0; i<M; i++) { 4378 final PreferredActivity pa = prefs.get(i); 4379 if (DEBUG_PREFERRED || debug) { 4380 Slog.v(TAG, "Checking PreferredActivity ds=" 4381 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4382 + "\n component=" + pa.mPref.mComponent); 4383 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4384 } 4385 if (pa.mPref.mMatch != match) { 4386 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4387 + Integer.toHexString(pa.mPref.mMatch)); 4388 continue; 4389 } 4390 // If it's not an "always" type preferred activity and that's what we're 4391 // looking for, skip it. 4392 if (always && !pa.mPref.mAlways) { 4393 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4394 continue; 4395 } 4396 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4397 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4398 if (DEBUG_PREFERRED || debug) { 4399 Slog.v(TAG, "Found preferred activity:"); 4400 if (ai != null) { 4401 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4402 } else { 4403 Slog.v(TAG, " null"); 4404 } 4405 } 4406 if (ai == null) { 4407 // This previously registered preferred activity 4408 // component is no longer known. Most likely an update 4409 // to the app was installed and in the new version this 4410 // component no longer exists. Clean it up by removing 4411 // it from the preferred activities list, and skip it. 4412 Slog.w(TAG, "Removing dangling preferred activity: " 4413 + pa.mPref.mComponent); 4414 pir.removeFilter(pa); 4415 changed = true; 4416 continue; 4417 } 4418 for (int j=0; j<N; j++) { 4419 final ResolveInfo ri = query.get(j); 4420 if (!ri.activityInfo.applicationInfo.packageName 4421 .equals(ai.applicationInfo.packageName)) { 4422 continue; 4423 } 4424 if (!ri.activityInfo.name.equals(ai.name)) { 4425 continue; 4426 } 4427 4428 if (removeMatches) { 4429 pir.removeFilter(pa); 4430 changed = true; 4431 if (DEBUG_PREFERRED) { 4432 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4433 } 4434 break; 4435 } 4436 4437 // Okay we found a previously set preferred or last chosen app. 4438 // If the result set is different from when this 4439 // was created, we need to clear it and re-ask the 4440 // user their preference, if we're looking for an "always" type entry. 4441 if (always && !pa.mPref.sameSet(query)) { 4442 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4443 + intent + " type " + resolvedType); 4444 if (DEBUG_PREFERRED) { 4445 Slog.v(TAG, "Removing preferred activity since set changed " 4446 + pa.mPref.mComponent); 4447 } 4448 pir.removeFilter(pa); 4449 // Re-add the filter as a "last chosen" entry (!always) 4450 PreferredActivity lastChosen = new PreferredActivity( 4451 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4452 pir.addFilter(lastChosen); 4453 changed = true; 4454 return null; 4455 } 4456 4457 // Yay! Either the set matched or we're looking for the last chosen 4458 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4459 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4460 return ri; 4461 } 4462 } 4463 } finally { 4464 if (changed) { 4465 if (DEBUG_PREFERRED) { 4466 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4467 } 4468 scheduleWritePackageRestrictionsLocked(userId); 4469 } 4470 } 4471 } 4472 } 4473 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4474 return null; 4475 } 4476 4477 /* 4478 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4479 */ 4480 @Override 4481 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4482 int targetUserId) { 4483 mContext.enforceCallingOrSelfPermission( 4484 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4485 List<CrossProfileIntentFilter> matches = 4486 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4487 if (matches != null) { 4488 int size = matches.size(); 4489 for (int i = 0; i < size; i++) { 4490 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4491 } 4492 } 4493 if (hasWebURI(intent)) { 4494 // cross-profile app linking works only towards the parent. 4495 final UserInfo parent = getProfileParent(sourceUserId); 4496 synchronized(mPackages) { 4497 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4498 intent, resolvedType, 0, sourceUserId, parent.id); 4499 return xpDomainInfo != null; 4500 } 4501 } 4502 return false; 4503 } 4504 4505 private UserInfo getProfileParent(int userId) { 4506 final long identity = Binder.clearCallingIdentity(); 4507 try { 4508 return sUserManager.getProfileParent(userId); 4509 } finally { 4510 Binder.restoreCallingIdentity(identity); 4511 } 4512 } 4513 4514 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4515 String resolvedType, int userId) { 4516 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4517 if (resolver != null) { 4518 return resolver.queryIntent(intent, resolvedType, false, userId); 4519 } 4520 return null; 4521 } 4522 4523 @Override 4524 public List<ResolveInfo> queryIntentActivities(Intent intent, 4525 String resolvedType, int flags, int userId) { 4526 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4527 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4528 ComponentName comp = intent.getComponent(); 4529 if (comp == null) { 4530 if (intent.getSelector() != null) { 4531 intent = intent.getSelector(); 4532 comp = intent.getComponent(); 4533 } 4534 } 4535 4536 if (comp != null) { 4537 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4538 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4539 if (ai != null) { 4540 final ResolveInfo ri = new ResolveInfo(); 4541 ri.activityInfo = ai; 4542 list.add(ri); 4543 } 4544 return list; 4545 } 4546 4547 // reader 4548 synchronized (mPackages) { 4549 final String pkgName = intent.getPackage(); 4550 if (pkgName == null) { 4551 List<CrossProfileIntentFilter> matchingFilters = 4552 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4553 // Check for results that need to skip the current profile. 4554 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4555 resolvedType, flags, userId); 4556 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4557 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4558 result.add(xpResolveInfo); 4559 return filterIfNotSystemUser(result, userId); 4560 } 4561 4562 // Check for results in the current profile. 4563 List<ResolveInfo> result = mActivities.queryIntent( 4564 intent, resolvedType, flags, userId); 4565 4566 // Check for cross profile results. 4567 xpResolveInfo = queryCrossProfileIntents( 4568 matchingFilters, intent, resolvedType, flags, userId); 4569 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4570 result.add(xpResolveInfo); 4571 Collections.sort(result, mResolvePrioritySorter); 4572 } 4573 result = filterIfNotSystemUser(result, userId); 4574 if (hasWebURI(intent)) { 4575 CrossProfileDomainInfo xpDomainInfo = null; 4576 final UserInfo parent = getProfileParent(userId); 4577 if (parent != null) { 4578 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4579 flags, userId, parent.id); 4580 } 4581 if (xpDomainInfo != null) { 4582 if (xpResolveInfo != null) { 4583 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4584 // in the result. 4585 result.remove(xpResolveInfo); 4586 } 4587 if (result.size() == 0) { 4588 result.add(xpDomainInfo.resolveInfo); 4589 return result; 4590 } 4591 } else if (result.size() <= 1) { 4592 return result; 4593 } 4594 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4595 xpDomainInfo, userId); 4596 Collections.sort(result, mResolvePrioritySorter); 4597 } 4598 return result; 4599 } 4600 final PackageParser.Package pkg = mPackages.get(pkgName); 4601 if (pkg != null) { 4602 return filterIfNotSystemUser( 4603 mActivities.queryIntentForPackage( 4604 intent, resolvedType, flags, pkg.activities, userId), 4605 userId); 4606 } 4607 return new ArrayList<ResolveInfo>(); 4608 } 4609 } 4610 4611 private static class CrossProfileDomainInfo { 4612 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4613 ResolveInfo resolveInfo; 4614 /* Best domain verification status of the activities found in the other profile */ 4615 int bestDomainVerificationStatus; 4616 } 4617 4618 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4619 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4620 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4621 sourceUserId)) { 4622 return null; 4623 } 4624 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4625 resolvedType, flags, parentUserId); 4626 4627 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4628 return null; 4629 } 4630 CrossProfileDomainInfo result = null; 4631 int size = resultTargetUser.size(); 4632 for (int i = 0; i < size; i++) { 4633 ResolveInfo riTargetUser = resultTargetUser.get(i); 4634 // Intent filter verification is only for filters that specify a host. So don't return 4635 // those that handle all web uris. 4636 if (riTargetUser.handleAllWebDataURI) { 4637 continue; 4638 } 4639 String packageName = riTargetUser.activityInfo.packageName; 4640 PackageSetting ps = mSettings.mPackages.get(packageName); 4641 if (ps == null) { 4642 continue; 4643 } 4644 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4645 int status = (int)(verificationState >> 32); 4646 if (result == null) { 4647 result = new CrossProfileDomainInfo(); 4648 result.resolveInfo = 4649 createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId); 4650 result.bestDomainVerificationStatus = status; 4651 } else { 4652 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4653 result.bestDomainVerificationStatus); 4654 } 4655 } 4656 // Don't consider matches with status NEVER across profiles. 4657 if (result != null && result.bestDomainVerificationStatus 4658 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4659 return null; 4660 } 4661 return result; 4662 } 4663 4664 /** 4665 * Verification statuses are ordered from the worse to the best, except for 4666 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4667 */ 4668 private int bestDomainVerificationStatus(int status1, int status2) { 4669 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4670 return status2; 4671 } 4672 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4673 return status1; 4674 } 4675 return (int) MathUtils.max(status1, status2); 4676 } 4677 4678 private boolean isUserEnabled(int userId) { 4679 long callingId = Binder.clearCallingIdentity(); 4680 try { 4681 UserInfo userInfo = sUserManager.getUserInfo(userId); 4682 return userInfo != null && userInfo.isEnabled(); 4683 } finally { 4684 Binder.restoreCallingIdentity(callingId); 4685 } 4686 } 4687 4688 /** 4689 * Filter out activities with systemUserOnly flag set, when current user is not System. 4690 * 4691 * @return filtered list 4692 */ 4693 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4694 if (userId == UserHandle.USER_SYSTEM) { 4695 return resolveInfos; 4696 } 4697 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4698 ResolveInfo info = resolveInfos.get(i); 4699 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4700 resolveInfos.remove(i); 4701 } 4702 } 4703 return resolveInfos; 4704 } 4705 4706 private static boolean hasWebURI(Intent intent) { 4707 if (intent.getData() == null) { 4708 return false; 4709 } 4710 final String scheme = intent.getScheme(); 4711 if (TextUtils.isEmpty(scheme)) { 4712 return false; 4713 } 4714 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4715 } 4716 4717 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4718 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4719 int userId) { 4720 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4721 4722 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4723 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4724 candidates.size()); 4725 } 4726 4727 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4728 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4729 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4730 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4731 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4732 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4733 4734 synchronized (mPackages) { 4735 final int count = candidates.size(); 4736 // First, try to use linked apps. Partition the candidates into four lists: 4737 // one for the final results, one for the "do not use ever", one for "undefined status" 4738 // and finally one for "browser app type". 4739 for (int n=0; n<count; n++) { 4740 ResolveInfo info = candidates.get(n); 4741 String packageName = info.activityInfo.packageName; 4742 PackageSetting ps = mSettings.mPackages.get(packageName); 4743 if (ps != null) { 4744 // Add to the special match all list (Browser use case) 4745 if (info.handleAllWebDataURI) { 4746 matchAllList.add(info); 4747 continue; 4748 } 4749 // Try to get the status from User settings first 4750 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4751 int status = (int)(packedStatus >> 32); 4752 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4753 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4754 if (DEBUG_DOMAIN_VERIFICATION) { 4755 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4756 + " : linkgen=" + linkGeneration); 4757 } 4758 // Use link-enabled generation as preferredOrder, i.e. 4759 // prefer newly-enabled over earlier-enabled. 4760 info.preferredOrder = linkGeneration; 4761 alwaysList.add(info); 4762 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4763 if (DEBUG_DOMAIN_VERIFICATION) { 4764 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4765 } 4766 neverList.add(info); 4767 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4768 if (DEBUG_DOMAIN_VERIFICATION) { 4769 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4770 } 4771 alwaysAskList.add(info); 4772 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4773 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4774 if (DEBUG_DOMAIN_VERIFICATION) { 4775 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4776 } 4777 undefinedList.add(info); 4778 } 4779 } 4780 } 4781 4782 // We'll want to include browser possibilities in a few cases 4783 boolean includeBrowser = false; 4784 4785 // First try to add the "always" resolution(s) for the current user, if any 4786 if (alwaysList.size() > 0) { 4787 result.addAll(alwaysList); 4788 // if there is an "always" for the parent user, add it. 4789 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4790 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4791 result.add(xpDomainInfo.resolveInfo); 4792 } else { 4793 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4794 result.addAll(undefinedList); 4795 if (xpDomainInfo != null && ( 4796 xpDomainInfo.bestDomainVerificationStatus 4797 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4798 || xpDomainInfo.bestDomainVerificationStatus 4799 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4800 result.add(xpDomainInfo.resolveInfo); 4801 } 4802 includeBrowser = true; 4803 } 4804 4805 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4806 // If there were 'always' entries their preferred order has been set, so we also 4807 // back that off to make the alternatives equivalent 4808 if (alwaysAskList.size() > 0) { 4809 for (ResolveInfo i : result) { 4810 i.preferredOrder = 0; 4811 } 4812 result.addAll(alwaysAskList); 4813 includeBrowser = true; 4814 } 4815 4816 if (includeBrowser) { 4817 // Also add browsers (all of them or only the default one) 4818 if (DEBUG_DOMAIN_VERIFICATION) { 4819 Slog.v(TAG, " ...including browsers in candidate set"); 4820 } 4821 if ((matchFlags & MATCH_ALL) != 0) { 4822 result.addAll(matchAllList); 4823 } else { 4824 // Browser/generic handling case. If there's a default browser, go straight 4825 // to that (but only if there is no other higher-priority match). 4826 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4827 int maxMatchPrio = 0; 4828 ResolveInfo defaultBrowserMatch = null; 4829 final int numCandidates = matchAllList.size(); 4830 for (int n = 0; n < numCandidates; n++) { 4831 ResolveInfo info = matchAllList.get(n); 4832 // track the highest overall match priority... 4833 if (info.priority > maxMatchPrio) { 4834 maxMatchPrio = info.priority; 4835 } 4836 // ...and the highest-priority default browser match 4837 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4838 if (defaultBrowserMatch == null 4839 || (defaultBrowserMatch.priority < info.priority)) { 4840 if (debug) { 4841 Slog.v(TAG, "Considering default browser match " + info); 4842 } 4843 defaultBrowserMatch = info; 4844 } 4845 } 4846 } 4847 if (defaultBrowserMatch != null 4848 && defaultBrowserMatch.priority >= maxMatchPrio 4849 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4850 { 4851 if (debug) { 4852 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4853 } 4854 result.add(defaultBrowserMatch); 4855 } else { 4856 result.addAll(matchAllList); 4857 } 4858 } 4859 4860 // If there is nothing selected, add all candidates and remove the ones that the user 4861 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4862 if (result.size() == 0) { 4863 result.addAll(candidates); 4864 result.removeAll(neverList); 4865 } 4866 } 4867 } 4868 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4869 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4870 result.size()); 4871 for (ResolveInfo info : result) { 4872 Slog.v(TAG, " + " + info.activityInfo); 4873 } 4874 } 4875 return result; 4876 } 4877 4878 // Returns a packed value as a long: 4879 // 4880 // high 'int'-sized word: link status: undefined/ask/never/always. 4881 // low 'int'-sized word: relative priority among 'always' results. 4882 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4883 long result = ps.getDomainVerificationStatusForUser(userId); 4884 // if none available, get the master status 4885 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4886 if (ps.getIntentFilterVerificationInfo() != null) { 4887 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4888 } 4889 } 4890 return result; 4891 } 4892 4893 private ResolveInfo querySkipCurrentProfileIntents( 4894 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4895 int flags, int sourceUserId) { 4896 if (matchingFilters != null) { 4897 int size = matchingFilters.size(); 4898 for (int i = 0; i < size; i ++) { 4899 CrossProfileIntentFilter filter = matchingFilters.get(i); 4900 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4901 // Checking if there are activities in the target user that can handle the 4902 // intent. 4903 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4904 flags, sourceUserId); 4905 if (resolveInfo != null) { 4906 return resolveInfo; 4907 } 4908 } 4909 } 4910 } 4911 return null; 4912 } 4913 4914 // Return matching ResolveInfo if any for skip current profile intent filters. 4915 private ResolveInfo queryCrossProfileIntents( 4916 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4917 int flags, int sourceUserId) { 4918 if (matchingFilters != null) { 4919 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4920 // match the same intent. For performance reasons, it is better not to 4921 // run queryIntent twice for the same userId 4922 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4923 int size = matchingFilters.size(); 4924 for (int i = 0; i < size; i++) { 4925 CrossProfileIntentFilter filter = matchingFilters.get(i); 4926 int targetUserId = filter.getTargetUserId(); 4927 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4928 && !alreadyTriedUserIds.get(targetUserId)) { 4929 // Checking if there are activities in the target user that can handle the 4930 // intent. 4931 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4932 flags, sourceUserId); 4933 if (resolveInfo != null) return resolveInfo; 4934 alreadyTriedUserIds.put(targetUserId, true); 4935 } 4936 } 4937 } 4938 return null; 4939 } 4940 4941 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4942 String resolvedType, int flags, int sourceUserId) { 4943 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4944 resolvedType, flags, filter.getTargetUserId()); 4945 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4946 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4947 } 4948 return null; 4949 } 4950 4951 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4952 int sourceUserId, int targetUserId) { 4953 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4954 long ident = Binder.clearCallingIdentity(); 4955 boolean targetIsProfile; 4956 try { 4957 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4958 } finally { 4959 Binder.restoreCallingIdentity(ident); 4960 } 4961 String className; 4962 if (targetIsProfile) { 4963 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4964 } else { 4965 className = FORWARD_INTENT_TO_PARENT; 4966 } 4967 ComponentName forwardingActivityComponentName = new ComponentName( 4968 mAndroidApplication.packageName, className); 4969 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4970 sourceUserId); 4971 if (!targetIsProfile) { 4972 forwardingActivityInfo.showUserIcon = targetUserId; 4973 forwardingResolveInfo.noResourceId = true; 4974 } 4975 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4976 forwardingResolveInfo.priority = 0; 4977 forwardingResolveInfo.preferredOrder = 0; 4978 forwardingResolveInfo.match = 0; 4979 forwardingResolveInfo.isDefault = true; 4980 forwardingResolveInfo.filter = filter; 4981 forwardingResolveInfo.targetUserId = targetUserId; 4982 return forwardingResolveInfo; 4983 } 4984 4985 @Override 4986 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4987 Intent[] specifics, String[] specificTypes, Intent intent, 4988 String resolvedType, int flags, int userId) { 4989 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4990 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4991 false, "query intent activity options"); 4992 final String resultsAction = intent.getAction(); 4993 4994 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4995 | PackageManager.GET_RESOLVED_FILTER, userId); 4996 4997 if (DEBUG_INTENT_MATCHING) { 4998 Log.v(TAG, "Query " + intent + ": " + results); 4999 } 5000 5001 int specificsPos = 0; 5002 int N; 5003 5004 // todo: note that the algorithm used here is O(N^2). This 5005 // isn't a problem in our current environment, but if we start running 5006 // into situations where we have more than 5 or 10 matches then this 5007 // should probably be changed to something smarter... 5008 5009 // First we go through and resolve each of the specific items 5010 // that were supplied, taking care of removing any corresponding 5011 // duplicate items in the generic resolve list. 5012 if (specifics != null) { 5013 for (int i=0; i<specifics.length; i++) { 5014 final Intent sintent = specifics[i]; 5015 if (sintent == null) { 5016 continue; 5017 } 5018 5019 if (DEBUG_INTENT_MATCHING) { 5020 Log.v(TAG, "Specific #" + i + ": " + sintent); 5021 } 5022 5023 String action = sintent.getAction(); 5024 if (resultsAction != null && resultsAction.equals(action)) { 5025 // If this action was explicitly requested, then don't 5026 // remove things that have it. 5027 action = null; 5028 } 5029 5030 ResolveInfo ri = null; 5031 ActivityInfo ai = null; 5032 5033 ComponentName comp = sintent.getComponent(); 5034 if (comp == null) { 5035 ri = resolveIntent( 5036 sintent, 5037 specificTypes != null ? specificTypes[i] : null, 5038 flags, userId); 5039 if (ri == null) { 5040 continue; 5041 } 5042 if (ri == mResolveInfo) { 5043 // ACK! Must do something better with this. 5044 } 5045 ai = ri.activityInfo; 5046 comp = new ComponentName(ai.applicationInfo.packageName, 5047 ai.name); 5048 } else { 5049 ai = getActivityInfo(comp, flags, userId); 5050 if (ai == null) { 5051 continue; 5052 } 5053 } 5054 5055 // Look for any generic query activities that are duplicates 5056 // of this specific one, and remove them from the results. 5057 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5058 N = results.size(); 5059 int j; 5060 for (j=specificsPos; j<N; j++) { 5061 ResolveInfo sri = results.get(j); 5062 if ((sri.activityInfo.name.equals(comp.getClassName()) 5063 && sri.activityInfo.applicationInfo.packageName.equals( 5064 comp.getPackageName())) 5065 || (action != null && sri.filter.matchAction(action))) { 5066 results.remove(j); 5067 if (DEBUG_INTENT_MATCHING) Log.v( 5068 TAG, "Removing duplicate item from " + j 5069 + " due to specific " + specificsPos); 5070 if (ri == null) { 5071 ri = sri; 5072 } 5073 j--; 5074 N--; 5075 } 5076 } 5077 5078 // Add this specific item to its proper place. 5079 if (ri == null) { 5080 ri = new ResolveInfo(); 5081 ri.activityInfo = ai; 5082 } 5083 results.add(specificsPos, ri); 5084 ri.specificIndex = i; 5085 specificsPos++; 5086 } 5087 } 5088 5089 // Now we go through the remaining generic results and remove any 5090 // duplicate actions that are found here. 5091 N = results.size(); 5092 for (int i=specificsPos; i<N-1; i++) { 5093 final ResolveInfo rii = results.get(i); 5094 if (rii.filter == null) { 5095 continue; 5096 } 5097 5098 // Iterate over all of the actions of this result's intent 5099 // filter... typically this should be just one. 5100 final Iterator<String> it = rii.filter.actionsIterator(); 5101 if (it == null) { 5102 continue; 5103 } 5104 while (it.hasNext()) { 5105 final String action = it.next(); 5106 if (resultsAction != null && resultsAction.equals(action)) { 5107 // If this action was explicitly requested, then don't 5108 // remove things that have it. 5109 continue; 5110 } 5111 for (int j=i+1; j<N; j++) { 5112 final ResolveInfo rij = results.get(j); 5113 if (rij.filter != null && rij.filter.hasAction(action)) { 5114 results.remove(j); 5115 if (DEBUG_INTENT_MATCHING) Log.v( 5116 TAG, "Removing duplicate item from " + j 5117 + " due to action " + action + " at " + i); 5118 j--; 5119 N--; 5120 } 5121 } 5122 } 5123 5124 // If the caller didn't request filter information, drop it now 5125 // so we don't have to marshall/unmarshall it. 5126 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5127 rii.filter = null; 5128 } 5129 } 5130 5131 // Filter out the caller activity if so requested. 5132 if (caller != null) { 5133 N = results.size(); 5134 for (int i=0; i<N; i++) { 5135 ActivityInfo ainfo = results.get(i).activityInfo; 5136 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5137 && caller.getClassName().equals(ainfo.name)) { 5138 results.remove(i); 5139 break; 5140 } 5141 } 5142 } 5143 5144 // If the caller didn't request filter information, 5145 // drop them now so we don't have to 5146 // marshall/unmarshall it. 5147 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5148 N = results.size(); 5149 for (int i=0; i<N; i++) { 5150 results.get(i).filter = null; 5151 } 5152 } 5153 5154 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5155 return results; 5156 } 5157 5158 @Override 5159 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5160 int userId) { 5161 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5162 ComponentName comp = intent.getComponent(); 5163 if (comp == null) { 5164 if (intent.getSelector() != null) { 5165 intent = intent.getSelector(); 5166 comp = intent.getComponent(); 5167 } 5168 } 5169 if (comp != null) { 5170 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5171 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5172 if (ai != null) { 5173 ResolveInfo ri = new ResolveInfo(); 5174 ri.activityInfo = ai; 5175 list.add(ri); 5176 } 5177 return list; 5178 } 5179 5180 // reader 5181 synchronized (mPackages) { 5182 String pkgName = intent.getPackage(); 5183 if (pkgName == null) { 5184 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5185 } 5186 final PackageParser.Package pkg = mPackages.get(pkgName); 5187 if (pkg != null) { 5188 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5189 userId); 5190 } 5191 return null; 5192 } 5193 } 5194 5195 @Override 5196 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5197 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5198 if (!sUserManager.exists(userId)) return null; 5199 if (query != null) { 5200 if (query.size() >= 1) { 5201 // If there is more than one service with the same priority, 5202 // just arbitrarily pick the first one. 5203 return query.get(0); 5204 } 5205 } 5206 return null; 5207 } 5208 5209 @Override 5210 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5211 int userId) { 5212 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5213 ComponentName comp = intent.getComponent(); 5214 if (comp == null) { 5215 if (intent.getSelector() != null) { 5216 intent = intent.getSelector(); 5217 comp = intent.getComponent(); 5218 } 5219 } 5220 if (comp != null) { 5221 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5222 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5223 if (si != null) { 5224 final ResolveInfo ri = new ResolveInfo(); 5225 ri.serviceInfo = si; 5226 list.add(ri); 5227 } 5228 return list; 5229 } 5230 5231 // reader 5232 synchronized (mPackages) { 5233 String pkgName = intent.getPackage(); 5234 if (pkgName == null) { 5235 return mServices.queryIntent(intent, resolvedType, flags, userId); 5236 } 5237 final PackageParser.Package pkg = mPackages.get(pkgName); 5238 if (pkg != null) { 5239 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5240 userId); 5241 } 5242 return null; 5243 } 5244 } 5245 5246 @Override 5247 public List<ResolveInfo> queryIntentContentProviders( 5248 Intent intent, String resolvedType, int flags, int userId) { 5249 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5250 ComponentName comp = intent.getComponent(); 5251 if (comp == null) { 5252 if (intent.getSelector() != null) { 5253 intent = intent.getSelector(); 5254 comp = intent.getComponent(); 5255 } 5256 } 5257 if (comp != null) { 5258 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5259 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5260 if (pi != null) { 5261 final ResolveInfo ri = new ResolveInfo(); 5262 ri.providerInfo = pi; 5263 list.add(ri); 5264 } 5265 return list; 5266 } 5267 5268 // reader 5269 synchronized (mPackages) { 5270 String pkgName = intent.getPackage(); 5271 if (pkgName == null) { 5272 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5273 } 5274 final PackageParser.Package pkg = mPackages.get(pkgName); 5275 if (pkg != null) { 5276 return mProviders.queryIntentForPackage( 5277 intent, resolvedType, flags, pkg.providers, userId); 5278 } 5279 return null; 5280 } 5281 } 5282 5283 @Override 5284 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5285 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5286 5287 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5288 5289 // writer 5290 synchronized (mPackages) { 5291 ArrayList<PackageInfo> list; 5292 if (listUninstalled) { 5293 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5294 for (PackageSetting ps : mSettings.mPackages.values()) { 5295 PackageInfo pi; 5296 if (ps.pkg != null) { 5297 pi = generatePackageInfo(ps.pkg, flags, userId); 5298 } else { 5299 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5300 } 5301 if (pi != null) { 5302 list.add(pi); 5303 } 5304 } 5305 } else { 5306 list = new ArrayList<PackageInfo>(mPackages.size()); 5307 for (PackageParser.Package p : mPackages.values()) { 5308 PackageInfo pi = generatePackageInfo(p, flags, userId); 5309 if (pi != null) { 5310 list.add(pi); 5311 } 5312 } 5313 } 5314 5315 return new ParceledListSlice<PackageInfo>(list); 5316 } 5317 } 5318 5319 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5320 String[] permissions, boolean[] tmp, int flags, int userId) { 5321 int numMatch = 0; 5322 final PermissionsState permissionsState = ps.getPermissionsState(); 5323 for (int i=0; i<permissions.length; i++) { 5324 final String permission = permissions[i]; 5325 if (permissionsState.hasPermission(permission, userId)) { 5326 tmp[i] = true; 5327 numMatch++; 5328 } else { 5329 tmp[i] = false; 5330 } 5331 } 5332 if (numMatch == 0) { 5333 return; 5334 } 5335 PackageInfo pi; 5336 if (ps.pkg != null) { 5337 pi = generatePackageInfo(ps.pkg, flags, userId); 5338 } else { 5339 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5340 } 5341 // The above might return null in cases of uninstalled apps or install-state 5342 // skew across users/profiles. 5343 if (pi != null) { 5344 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5345 if (numMatch == permissions.length) { 5346 pi.requestedPermissions = permissions; 5347 } else { 5348 pi.requestedPermissions = new String[numMatch]; 5349 numMatch = 0; 5350 for (int i=0; i<permissions.length; i++) { 5351 if (tmp[i]) { 5352 pi.requestedPermissions[numMatch] = permissions[i]; 5353 numMatch++; 5354 } 5355 } 5356 } 5357 } 5358 list.add(pi); 5359 } 5360 } 5361 5362 @Override 5363 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5364 String[] permissions, int flags, int userId) { 5365 if (!sUserManager.exists(userId)) return null; 5366 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5367 5368 // writer 5369 synchronized (mPackages) { 5370 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5371 boolean[] tmpBools = new boolean[permissions.length]; 5372 if (listUninstalled) { 5373 for (PackageSetting ps : mSettings.mPackages.values()) { 5374 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5375 } 5376 } else { 5377 for (PackageParser.Package pkg : mPackages.values()) { 5378 PackageSetting ps = (PackageSetting)pkg.mExtras; 5379 if (ps != null) { 5380 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5381 userId); 5382 } 5383 } 5384 } 5385 5386 return new ParceledListSlice<PackageInfo>(list); 5387 } 5388 } 5389 5390 @Override 5391 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5392 if (!sUserManager.exists(userId)) return null; 5393 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5394 5395 // writer 5396 synchronized (mPackages) { 5397 ArrayList<ApplicationInfo> list; 5398 if (listUninstalled) { 5399 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5400 for (PackageSetting ps : mSettings.mPackages.values()) { 5401 ApplicationInfo ai; 5402 if (ps.pkg != null) { 5403 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5404 ps.readUserState(userId), userId); 5405 } else { 5406 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5407 } 5408 if (ai != null) { 5409 list.add(ai); 5410 } 5411 } 5412 } else { 5413 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5414 for (PackageParser.Package p : mPackages.values()) { 5415 if (p.mExtras != null) { 5416 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5417 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5418 if (ai != null) { 5419 list.add(ai); 5420 } 5421 } 5422 } 5423 } 5424 5425 return new ParceledListSlice<ApplicationInfo>(list); 5426 } 5427 } 5428 5429 public List<ApplicationInfo> getPersistentApplications(int flags) { 5430 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5431 5432 // reader 5433 synchronized (mPackages) { 5434 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5435 final int userId = UserHandle.getCallingUserId(); 5436 while (i.hasNext()) { 5437 final PackageParser.Package p = i.next(); 5438 if (p.applicationInfo != null 5439 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5440 && (!mSafeMode || isSystemApp(p))) { 5441 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5442 if (ps != null) { 5443 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5444 ps.readUserState(userId), userId); 5445 if (ai != null) { 5446 finalList.add(ai); 5447 } 5448 } 5449 } 5450 } 5451 } 5452 5453 return finalList; 5454 } 5455 5456 @Override 5457 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5458 if (!sUserManager.exists(userId)) return null; 5459 // reader 5460 synchronized (mPackages) { 5461 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5462 PackageSetting ps = provider != null 5463 ? mSettings.mPackages.get(provider.owner.packageName) 5464 : null; 5465 return ps != null 5466 && mSettings.isEnabledLPr(provider.info, flags, userId) 5467 && (!mSafeMode || (provider.info.applicationInfo.flags 5468 &ApplicationInfo.FLAG_SYSTEM) != 0) 5469 ? PackageParser.generateProviderInfo(provider, flags, 5470 ps.readUserState(userId), userId) 5471 : null; 5472 } 5473 } 5474 5475 /** 5476 * @deprecated 5477 */ 5478 @Deprecated 5479 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5480 // reader 5481 synchronized (mPackages) { 5482 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5483 .entrySet().iterator(); 5484 final int userId = UserHandle.getCallingUserId(); 5485 while (i.hasNext()) { 5486 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5487 PackageParser.Provider p = entry.getValue(); 5488 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5489 5490 if (ps != null && p.syncable 5491 && (!mSafeMode || (p.info.applicationInfo.flags 5492 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5493 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5494 ps.readUserState(userId), userId); 5495 if (info != null) { 5496 outNames.add(entry.getKey()); 5497 outInfo.add(info); 5498 } 5499 } 5500 } 5501 } 5502 } 5503 5504 @Override 5505 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5506 int uid, int flags) { 5507 ArrayList<ProviderInfo> finalList = null; 5508 // reader 5509 synchronized (mPackages) { 5510 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5511 final int userId = processName != null ? 5512 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5513 while (i.hasNext()) { 5514 final PackageParser.Provider p = i.next(); 5515 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5516 if (ps != null && p.info.authority != null 5517 && (processName == null 5518 || (p.info.processName.equals(processName) 5519 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5520 && mSettings.isEnabledLPr(p.info, flags, userId) 5521 && (!mSafeMode 5522 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5523 if (finalList == null) { 5524 finalList = new ArrayList<ProviderInfo>(3); 5525 } 5526 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5527 ps.readUserState(userId), userId); 5528 if (info != null) { 5529 finalList.add(info); 5530 } 5531 } 5532 } 5533 } 5534 5535 if (finalList != null) { 5536 Collections.sort(finalList, mProviderInitOrderSorter); 5537 return new ParceledListSlice<ProviderInfo>(finalList); 5538 } 5539 5540 return null; 5541 } 5542 5543 @Override 5544 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5545 int flags) { 5546 // reader 5547 synchronized (mPackages) { 5548 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5549 return PackageParser.generateInstrumentationInfo(i, flags); 5550 } 5551 } 5552 5553 @Override 5554 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5555 int flags) { 5556 ArrayList<InstrumentationInfo> finalList = 5557 new ArrayList<InstrumentationInfo>(); 5558 5559 // reader 5560 synchronized (mPackages) { 5561 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5562 while (i.hasNext()) { 5563 final PackageParser.Instrumentation p = i.next(); 5564 if (targetPackage == null 5565 || targetPackage.equals(p.info.targetPackage)) { 5566 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5567 flags); 5568 if (ii != null) { 5569 finalList.add(ii); 5570 } 5571 } 5572 } 5573 } 5574 5575 return finalList; 5576 } 5577 5578 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5579 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5580 if (overlays == null) { 5581 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5582 return; 5583 } 5584 for (PackageParser.Package opkg : overlays.values()) { 5585 // Not much to do if idmap fails: we already logged the error 5586 // and we certainly don't want to abort installation of pkg simply 5587 // because an overlay didn't fit properly. For these reasons, 5588 // ignore the return value of createIdmapForPackagePairLI. 5589 createIdmapForPackagePairLI(pkg, opkg); 5590 } 5591 } 5592 5593 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5594 PackageParser.Package opkg) { 5595 if (!opkg.mTrustedOverlay) { 5596 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5597 opkg.baseCodePath + ": overlay not trusted"); 5598 return false; 5599 } 5600 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5601 if (overlaySet == null) { 5602 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5603 opkg.baseCodePath + " but target package has no known overlays"); 5604 return false; 5605 } 5606 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5607 // TODO: generate idmap for split APKs 5608 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5609 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5610 + opkg.baseCodePath); 5611 return false; 5612 } 5613 PackageParser.Package[] overlayArray = 5614 overlaySet.values().toArray(new PackageParser.Package[0]); 5615 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5616 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5617 return p1.mOverlayPriority - p2.mOverlayPriority; 5618 } 5619 }; 5620 Arrays.sort(overlayArray, cmp); 5621 5622 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5623 int i = 0; 5624 for (PackageParser.Package p : overlayArray) { 5625 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5626 } 5627 return true; 5628 } 5629 5630 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5631 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5632 try { 5633 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5634 } finally { 5635 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5636 } 5637 } 5638 5639 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5640 final File[] files = dir.listFiles(); 5641 if (ArrayUtils.isEmpty(files)) { 5642 Log.d(TAG, "No files in app dir " + dir); 5643 return; 5644 } 5645 5646 if (DEBUG_PACKAGE_SCANNING) { 5647 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5648 + " flags=0x" + Integer.toHexString(parseFlags)); 5649 } 5650 5651 for (File file : files) { 5652 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5653 && !PackageInstallerService.isStageName(file.getName()); 5654 if (!isPackage) { 5655 // Ignore entries which are not packages 5656 continue; 5657 } 5658 try { 5659 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5660 scanFlags, currentTime, null); 5661 } catch (PackageManagerException e) { 5662 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5663 5664 // Delete invalid userdata apps 5665 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5666 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5667 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5668 if (file.isDirectory()) { 5669 mInstaller.rmPackageDir(file.getAbsolutePath()); 5670 } else { 5671 file.delete(); 5672 } 5673 } 5674 } 5675 } 5676 } 5677 5678 private static File getSettingsProblemFile() { 5679 File dataDir = Environment.getDataDirectory(); 5680 File systemDir = new File(dataDir, "system"); 5681 File fname = new File(systemDir, "uiderrors.txt"); 5682 return fname; 5683 } 5684 5685 static void reportSettingsProblem(int priority, String msg) { 5686 logCriticalInfo(priority, msg); 5687 } 5688 5689 static void logCriticalInfo(int priority, String msg) { 5690 Slog.println(priority, TAG, msg); 5691 EventLogTags.writePmCriticalInfo(msg); 5692 try { 5693 File fname = getSettingsProblemFile(); 5694 FileOutputStream out = new FileOutputStream(fname, true); 5695 PrintWriter pw = new FastPrintWriter(out); 5696 SimpleDateFormat formatter = new SimpleDateFormat(); 5697 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5698 pw.println(dateString + ": " + msg); 5699 pw.close(); 5700 FileUtils.setPermissions( 5701 fname.toString(), 5702 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5703 -1, -1); 5704 } catch (java.io.IOException e) { 5705 } 5706 } 5707 5708 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5709 PackageParser.Package pkg, File srcFile, int parseFlags) 5710 throws PackageManagerException { 5711 if (ps != null 5712 && ps.codePath.equals(srcFile) 5713 && ps.timeStamp == srcFile.lastModified() 5714 && !isCompatSignatureUpdateNeeded(pkg) 5715 && !isRecoverSignatureUpdateNeeded(pkg)) { 5716 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5717 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5718 ArraySet<PublicKey> signingKs; 5719 synchronized (mPackages) { 5720 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5721 } 5722 if (ps.signatures.mSignatures != null 5723 && ps.signatures.mSignatures.length != 0 5724 && signingKs != null) { 5725 // Optimization: reuse the existing cached certificates 5726 // if the package appears to be unchanged. 5727 pkg.mSignatures = ps.signatures.mSignatures; 5728 pkg.mSigningKeys = signingKs; 5729 return; 5730 } 5731 5732 Slog.w(TAG, "PackageSetting for " + ps.name 5733 + " is missing signatures. Collecting certs again to recover them."); 5734 } else { 5735 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5736 } 5737 5738 try { 5739 pp.collectCertificates(pkg, parseFlags); 5740 pp.collectManifestDigest(pkg); 5741 } catch (PackageParserException e) { 5742 throw PackageManagerException.from(e); 5743 } 5744 } 5745 5746 /** 5747 * Traces a package scan. 5748 * @see #scanPackageLI(File, int, int, long, UserHandle) 5749 */ 5750 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5751 long currentTime, UserHandle user) throws PackageManagerException { 5752 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5753 try { 5754 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5755 } finally { 5756 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5757 } 5758 } 5759 5760 /** 5761 * Scans a package and returns the newly parsed package. 5762 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5763 */ 5764 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5765 long currentTime, UserHandle user) throws PackageManagerException { 5766 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5767 parseFlags |= mDefParseFlags; 5768 PackageParser pp = new PackageParser(); 5769 pp.setSeparateProcesses(mSeparateProcesses); 5770 pp.setOnlyCoreApps(mOnlyCore); 5771 pp.setDisplayMetrics(mMetrics); 5772 5773 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5774 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5775 } 5776 5777 final PackageParser.Package pkg; 5778 try { 5779 pkg = pp.parsePackage(scanFile, parseFlags); 5780 } catch (PackageParserException e) { 5781 throw PackageManagerException.from(e); 5782 } 5783 5784 PackageSetting ps = null; 5785 PackageSetting updatedPkg; 5786 // reader 5787 synchronized (mPackages) { 5788 // Look to see if we already know about this package. 5789 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5790 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5791 // This package has been renamed to its original name. Let's 5792 // use that. 5793 ps = mSettings.peekPackageLPr(oldName); 5794 } 5795 // If there was no original package, see one for the real package name. 5796 if (ps == null) { 5797 ps = mSettings.peekPackageLPr(pkg.packageName); 5798 } 5799 // Check to see if this package could be hiding/updating a system 5800 // package. Must look for it either under the original or real 5801 // package name depending on our state. 5802 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5803 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5804 } 5805 boolean updatedPkgBetter = false; 5806 // First check if this is a system package that may involve an update 5807 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5808 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5809 // it needs to drop FLAG_PRIVILEGED. 5810 if (locationIsPrivileged(scanFile)) { 5811 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5812 } else { 5813 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5814 } 5815 5816 if (ps != null && !ps.codePath.equals(scanFile)) { 5817 // The path has changed from what was last scanned... check the 5818 // version of the new path against what we have stored to determine 5819 // what to do. 5820 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5821 if (pkg.mVersionCode <= ps.versionCode) { 5822 // The system package has been updated and the code path does not match 5823 // Ignore entry. Skip it. 5824 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5825 + " ignored: updated version " + ps.versionCode 5826 + " better than this " + pkg.mVersionCode); 5827 if (!updatedPkg.codePath.equals(scanFile)) { 5828 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5829 + ps.name + " changing from " + updatedPkg.codePathString 5830 + " to " + scanFile); 5831 updatedPkg.codePath = scanFile; 5832 updatedPkg.codePathString = scanFile.toString(); 5833 updatedPkg.resourcePath = scanFile; 5834 updatedPkg.resourcePathString = scanFile.toString(); 5835 } 5836 updatedPkg.pkg = pkg; 5837 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5838 "Package " + ps.name + " at " + scanFile 5839 + " ignored: updated version " + ps.versionCode 5840 + " better than this " + pkg.mVersionCode); 5841 } else { 5842 // The current app on the system partition is better than 5843 // what we have updated to on the data partition; switch 5844 // back to the system partition version. 5845 // At this point, its safely assumed that package installation for 5846 // apps in system partition will go through. If not there won't be a working 5847 // version of the app 5848 // writer 5849 synchronized (mPackages) { 5850 // Just remove the loaded entries from package lists. 5851 mPackages.remove(ps.name); 5852 } 5853 5854 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5855 + " reverting from " + ps.codePathString 5856 + ": new version " + pkg.mVersionCode 5857 + " better than installed " + ps.versionCode); 5858 5859 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5860 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5861 synchronized (mInstallLock) { 5862 args.cleanUpResourcesLI(); 5863 } 5864 synchronized (mPackages) { 5865 mSettings.enableSystemPackageLPw(ps.name); 5866 } 5867 updatedPkgBetter = true; 5868 } 5869 } 5870 } 5871 5872 if (updatedPkg != null) { 5873 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5874 // initially 5875 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5876 5877 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5878 // flag set initially 5879 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5880 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5881 } 5882 } 5883 5884 // Verify certificates against what was last scanned 5885 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5886 5887 /* 5888 * A new system app appeared, but we already had a non-system one of the 5889 * same name installed earlier. 5890 */ 5891 boolean shouldHideSystemApp = false; 5892 if (updatedPkg == null && ps != null 5893 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5894 /* 5895 * Check to make sure the signatures match first. If they don't, 5896 * wipe the installed application and its data. 5897 */ 5898 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5899 != PackageManager.SIGNATURE_MATCH) { 5900 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5901 + " signatures don't match existing userdata copy; removing"); 5902 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5903 ps = null; 5904 } else { 5905 /* 5906 * If the newly-added system app is an older version than the 5907 * already installed version, hide it. It will be scanned later 5908 * and re-added like an update. 5909 */ 5910 if (pkg.mVersionCode <= ps.versionCode) { 5911 shouldHideSystemApp = true; 5912 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5913 + " but new version " + pkg.mVersionCode + " better than installed " 5914 + ps.versionCode + "; hiding system"); 5915 } else { 5916 /* 5917 * The newly found system app is a newer version that the 5918 * one previously installed. Simply remove the 5919 * already-installed application and replace it with our own 5920 * while keeping the application data. 5921 */ 5922 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5923 + " reverting from " + ps.codePathString + ": new version " 5924 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5925 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5926 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5927 synchronized (mInstallLock) { 5928 args.cleanUpResourcesLI(); 5929 } 5930 } 5931 } 5932 } 5933 5934 // The apk is forward locked (not public) if its code and resources 5935 // are kept in different files. (except for app in either system or 5936 // vendor path). 5937 // TODO grab this value from PackageSettings 5938 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5939 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5940 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5941 } 5942 } 5943 5944 // TODO: extend to support forward-locked splits 5945 String resourcePath = null; 5946 String baseResourcePath = null; 5947 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5948 if (ps != null && ps.resourcePathString != null) { 5949 resourcePath = ps.resourcePathString; 5950 baseResourcePath = ps.resourcePathString; 5951 } else { 5952 // Should not happen at all. Just log an error. 5953 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5954 } 5955 } else { 5956 resourcePath = pkg.codePath; 5957 baseResourcePath = pkg.baseCodePath; 5958 } 5959 5960 // Set application objects path explicitly. 5961 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5962 pkg.applicationInfo.setCodePath(pkg.codePath); 5963 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5964 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5965 pkg.applicationInfo.setResourcePath(resourcePath); 5966 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5967 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5968 5969 // Note that we invoke the following method only if we are about to unpack an application 5970 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5971 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5972 5973 /* 5974 * If the system app should be overridden by a previously installed 5975 * data, hide the system app now and let the /data/app scan pick it up 5976 * again. 5977 */ 5978 if (shouldHideSystemApp) { 5979 synchronized (mPackages) { 5980 /* 5981 * We have to grant systems permissions before we hide, because 5982 * grantPermissions will assume the package update is trying to 5983 * expand its permissions. 5984 */ 5985 grantPermissionsLPw(pkg, true, pkg.packageName); 5986 mSettings.disableSystemPackageLPw(pkg.packageName); 5987 } 5988 } 5989 5990 return scannedPkg; 5991 } 5992 5993 private static String fixProcessName(String defProcessName, 5994 String processName, int uid) { 5995 if (processName == null) { 5996 return defProcessName; 5997 } 5998 return processName; 5999 } 6000 6001 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6002 throws PackageManagerException { 6003 if (pkgSetting.signatures.mSignatures != null) { 6004 // Already existing package. Make sure signatures match 6005 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6006 == PackageManager.SIGNATURE_MATCH; 6007 if (!match) { 6008 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6009 == PackageManager.SIGNATURE_MATCH; 6010 } 6011 if (!match) { 6012 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6013 == PackageManager.SIGNATURE_MATCH; 6014 } 6015 if (!match) { 6016 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6017 + pkg.packageName + " signatures do not match the " 6018 + "previously installed version; ignoring!"); 6019 } 6020 } 6021 6022 // Check for shared user signatures 6023 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6024 // Already existing package. Make sure signatures match 6025 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6026 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6027 if (!match) { 6028 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6029 == PackageManager.SIGNATURE_MATCH; 6030 } 6031 if (!match) { 6032 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6033 == PackageManager.SIGNATURE_MATCH; 6034 } 6035 if (!match) { 6036 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6037 "Package " + pkg.packageName 6038 + " has no signatures that match those in shared user " 6039 + pkgSetting.sharedUser.name + "; ignoring!"); 6040 } 6041 } 6042 } 6043 6044 /** 6045 * Enforces that only the system UID or root's UID can call a method exposed 6046 * via Binder. 6047 * 6048 * @param message used as message if SecurityException is thrown 6049 * @throws SecurityException if the caller is not system or root 6050 */ 6051 private static final void enforceSystemOrRoot(String message) { 6052 final int uid = Binder.getCallingUid(); 6053 if (uid != Process.SYSTEM_UID && uid != 0) { 6054 throw new SecurityException(message); 6055 } 6056 } 6057 6058 @Override 6059 public void performBootDexOpt() { 6060 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6061 6062 // Before everything else, see whether we need to fstrim. 6063 try { 6064 IMountService ms = PackageHelper.getMountService(); 6065 if (ms != null) { 6066 final boolean isUpgrade = isUpgrade(); 6067 boolean doTrim = isUpgrade; 6068 if (doTrim) { 6069 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6070 } else { 6071 final long interval = android.provider.Settings.Global.getLong( 6072 mContext.getContentResolver(), 6073 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6074 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6075 if (interval > 0) { 6076 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6077 if (timeSinceLast > interval) { 6078 doTrim = true; 6079 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6080 + "; running immediately"); 6081 } 6082 } 6083 } 6084 if (doTrim) { 6085 if (!isFirstBoot()) { 6086 try { 6087 ActivityManagerNative.getDefault().showBootMessage( 6088 mContext.getResources().getString( 6089 R.string.android_upgrading_fstrim), true); 6090 } catch (RemoteException e) { 6091 } 6092 } 6093 ms.runMaintenance(); 6094 } 6095 } else { 6096 Slog.e(TAG, "Mount service unavailable!"); 6097 } 6098 } catch (RemoteException e) { 6099 // Can't happen; MountService is local 6100 } 6101 6102 final ArraySet<PackageParser.Package> pkgs; 6103 synchronized (mPackages) { 6104 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6105 } 6106 6107 if (pkgs != null) { 6108 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6109 // in case the device runs out of space. 6110 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6111 // Give priority to core apps. 6112 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6113 PackageParser.Package pkg = it.next(); 6114 if (pkg.coreApp) { 6115 if (DEBUG_DEXOPT) { 6116 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6117 } 6118 sortedPkgs.add(pkg); 6119 it.remove(); 6120 } 6121 } 6122 // Give priority to system apps that listen for pre boot complete. 6123 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6124 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6125 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6126 PackageParser.Package pkg = it.next(); 6127 if (pkgNames.contains(pkg.packageName)) { 6128 if (DEBUG_DEXOPT) { 6129 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6130 } 6131 sortedPkgs.add(pkg); 6132 it.remove(); 6133 } 6134 } 6135 // Give priority to system apps. 6136 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6137 PackageParser.Package pkg = it.next(); 6138 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6139 if (DEBUG_DEXOPT) { 6140 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6141 } 6142 sortedPkgs.add(pkg); 6143 it.remove(); 6144 } 6145 } 6146 // Give priority to updated system apps. 6147 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6148 PackageParser.Package pkg = it.next(); 6149 if (pkg.isUpdatedSystemApp()) { 6150 if (DEBUG_DEXOPT) { 6151 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6152 } 6153 sortedPkgs.add(pkg); 6154 it.remove(); 6155 } 6156 } 6157 // Give priority to apps that listen for boot complete. 6158 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6159 pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6160 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6161 PackageParser.Package pkg = it.next(); 6162 if (pkgNames.contains(pkg.packageName)) { 6163 if (DEBUG_DEXOPT) { 6164 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6165 } 6166 sortedPkgs.add(pkg); 6167 it.remove(); 6168 } 6169 } 6170 // Filter out packages that aren't recently used. 6171 filterRecentlyUsedApps(pkgs); 6172 // Add all remaining apps. 6173 for (PackageParser.Package pkg : pkgs) { 6174 if (DEBUG_DEXOPT) { 6175 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6176 } 6177 sortedPkgs.add(pkg); 6178 } 6179 6180 // If we want to be lazy, filter everything that wasn't recently used. 6181 if (mLazyDexOpt) { 6182 filterRecentlyUsedApps(sortedPkgs); 6183 } 6184 6185 int i = 0; 6186 int total = sortedPkgs.size(); 6187 File dataDir = Environment.getDataDirectory(); 6188 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6189 if (lowThreshold == 0) { 6190 throw new IllegalStateException("Invalid low memory threshold"); 6191 } 6192 for (PackageParser.Package pkg : sortedPkgs) { 6193 long usableSpace = dataDir.getUsableSpace(); 6194 if (usableSpace < lowThreshold) { 6195 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6196 break; 6197 } 6198 performBootDexOpt(pkg, ++i, total); 6199 } 6200 } 6201 } 6202 6203 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6204 // Filter out packages that aren't recently used. 6205 // 6206 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6207 // should do a full dexopt. 6208 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6209 int total = pkgs.size(); 6210 int skipped = 0; 6211 long now = System.currentTimeMillis(); 6212 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6213 PackageParser.Package pkg = i.next(); 6214 long then = pkg.mLastPackageUsageTimeInMills; 6215 if (then + mDexOptLRUThresholdInMills < now) { 6216 if (DEBUG_DEXOPT) { 6217 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6218 ((then == 0) ? "never" : new Date(then))); 6219 } 6220 i.remove(); 6221 skipped++; 6222 } 6223 } 6224 if (DEBUG_DEXOPT) { 6225 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6226 } 6227 } 6228 } 6229 6230 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6231 List<ResolveInfo> ris = null; 6232 try { 6233 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6234 intent, null, 0, userId); 6235 } catch (RemoteException e) { 6236 } 6237 ArraySet<String> pkgNames = new ArraySet<String>(); 6238 if (ris != null) { 6239 for (ResolveInfo ri : ris) { 6240 pkgNames.add(ri.activityInfo.packageName); 6241 } 6242 } 6243 return pkgNames; 6244 } 6245 6246 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6247 if (DEBUG_DEXOPT) { 6248 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6249 } 6250 if (!isFirstBoot()) { 6251 try { 6252 ActivityManagerNative.getDefault().showBootMessage( 6253 mContext.getResources().getString(R.string.android_upgrading_apk, 6254 curr, total), true); 6255 } catch (RemoteException e) { 6256 } 6257 } 6258 PackageParser.Package p = pkg; 6259 synchronized (mInstallLock) { 6260 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6261 false /* force dex */, false /* defer */, true /* include dependencies */); 6262 } 6263 } 6264 6265 @Override 6266 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6267 return performDexOpt(packageName, instructionSet, false); 6268 } 6269 6270 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6271 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6272 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6273 if (!dexopt && !updateUsage) { 6274 // We aren't going to dexopt or update usage, so bail early. 6275 return false; 6276 } 6277 PackageParser.Package p; 6278 final String targetInstructionSet; 6279 synchronized (mPackages) { 6280 p = mPackages.get(packageName); 6281 if (p == null) { 6282 return false; 6283 } 6284 if (updateUsage) { 6285 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6286 } 6287 mPackageUsage.write(false); 6288 if (!dexopt) { 6289 // We aren't going to dexopt, so bail early. 6290 return false; 6291 } 6292 6293 targetInstructionSet = instructionSet != null ? instructionSet : 6294 getPrimaryInstructionSet(p.applicationInfo); 6295 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6296 return false; 6297 } 6298 } 6299 long callingId = Binder.clearCallingIdentity(); 6300 try { 6301 synchronized (mInstallLock) { 6302 final String[] instructionSets = new String[] { targetInstructionSet }; 6303 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6304 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6305 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6306 } 6307 } finally { 6308 Binder.restoreCallingIdentity(callingId); 6309 } 6310 } 6311 6312 public ArraySet<String> getPackagesThatNeedDexOpt() { 6313 ArraySet<String> pkgs = null; 6314 synchronized (mPackages) { 6315 for (PackageParser.Package p : mPackages.values()) { 6316 if (DEBUG_DEXOPT) { 6317 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6318 } 6319 if (!p.mDexOptPerformed.isEmpty()) { 6320 continue; 6321 } 6322 if (pkgs == null) { 6323 pkgs = new ArraySet<String>(); 6324 } 6325 pkgs.add(p.packageName); 6326 } 6327 } 6328 return pkgs; 6329 } 6330 6331 public void shutdown() { 6332 mPackageUsage.write(true); 6333 } 6334 6335 @Override 6336 public void forceDexOpt(String packageName) { 6337 enforceSystemOrRoot("forceDexOpt"); 6338 6339 PackageParser.Package pkg; 6340 synchronized (mPackages) { 6341 pkg = mPackages.get(packageName); 6342 if (pkg == null) { 6343 throw new IllegalArgumentException("Missing package: " + packageName); 6344 } 6345 } 6346 6347 synchronized (mInstallLock) { 6348 final String[] instructionSets = new String[] { 6349 getPrimaryInstructionSet(pkg.applicationInfo) }; 6350 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6351 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6352 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6353 throw new IllegalStateException("Failed to dexopt: " + res); 6354 } 6355 } 6356 } 6357 6358 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6359 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6360 Slog.w(TAG, "Unable to update from " + oldPkg.name 6361 + " to " + newPkg.packageName 6362 + ": old package not in system partition"); 6363 return false; 6364 } else if (mPackages.get(oldPkg.name) != null) { 6365 Slog.w(TAG, "Unable to update from " + oldPkg.name 6366 + " to " + newPkg.packageName 6367 + ": old package still exists"); 6368 return false; 6369 } 6370 return true; 6371 } 6372 6373 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6374 int[] users = sUserManager.getUserIds(); 6375 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6376 if (res < 0) { 6377 return res; 6378 } 6379 for (int user : users) { 6380 if (user != 0) { 6381 res = mInstaller.createUserData(volumeUuid, packageName, 6382 UserHandle.getUid(user, uid), user, seinfo); 6383 if (res < 0) { 6384 return res; 6385 } 6386 } 6387 } 6388 return res; 6389 } 6390 6391 private int removeDataDirsLI(String volumeUuid, String packageName) { 6392 int[] users = sUserManager.getUserIds(); 6393 int res = 0; 6394 for (int user : users) { 6395 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6396 if (resInner < 0) { 6397 res = resInner; 6398 } 6399 } 6400 6401 return res; 6402 } 6403 6404 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6405 int[] users = sUserManager.getUserIds(); 6406 int res = 0; 6407 for (int user : users) { 6408 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6409 if (resInner < 0) { 6410 res = resInner; 6411 } 6412 } 6413 return res; 6414 } 6415 6416 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6417 PackageParser.Package changingLib) { 6418 if (file.path != null) { 6419 usesLibraryFiles.add(file.path); 6420 return; 6421 } 6422 PackageParser.Package p = mPackages.get(file.apk); 6423 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6424 // If we are doing this while in the middle of updating a library apk, 6425 // then we need to make sure to use that new apk for determining the 6426 // dependencies here. (We haven't yet finished committing the new apk 6427 // to the package manager state.) 6428 if (p == null || p.packageName.equals(changingLib.packageName)) { 6429 p = changingLib; 6430 } 6431 } 6432 if (p != null) { 6433 usesLibraryFiles.addAll(p.getAllCodePaths()); 6434 } 6435 } 6436 6437 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6438 PackageParser.Package changingLib) throws PackageManagerException { 6439 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6440 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6441 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6442 for (int i=0; i<N; i++) { 6443 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6444 if (file == null) { 6445 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6446 "Package " + pkg.packageName + " requires unavailable shared library " 6447 + pkg.usesLibraries.get(i) + "; failing!"); 6448 } 6449 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6450 } 6451 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6452 for (int i=0; i<N; i++) { 6453 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6454 if (file == null) { 6455 Slog.w(TAG, "Package " + pkg.packageName 6456 + " desires unavailable shared library " 6457 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6458 } else { 6459 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6460 } 6461 } 6462 N = usesLibraryFiles.size(); 6463 if (N > 0) { 6464 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6465 } else { 6466 pkg.usesLibraryFiles = null; 6467 } 6468 } 6469 } 6470 6471 private static boolean hasString(List<String> list, List<String> which) { 6472 if (list == null) { 6473 return false; 6474 } 6475 for (int i=list.size()-1; i>=0; i--) { 6476 for (int j=which.size()-1; j>=0; j--) { 6477 if (which.get(j).equals(list.get(i))) { 6478 return true; 6479 } 6480 } 6481 } 6482 return false; 6483 } 6484 6485 private void updateAllSharedLibrariesLPw() { 6486 for (PackageParser.Package pkg : mPackages.values()) { 6487 try { 6488 updateSharedLibrariesLPw(pkg, null); 6489 } catch (PackageManagerException e) { 6490 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6491 } 6492 } 6493 } 6494 6495 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6496 PackageParser.Package changingPkg) { 6497 ArrayList<PackageParser.Package> res = null; 6498 for (PackageParser.Package pkg : mPackages.values()) { 6499 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6500 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6501 if (res == null) { 6502 res = new ArrayList<PackageParser.Package>(); 6503 } 6504 res.add(pkg); 6505 try { 6506 updateSharedLibrariesLPw(pkg, changingPkg); 6507 } catch (PackageManagerException e) { 6508 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6509 } 6510 } 6511 } 6512 return res; 6513 } 6514 6515 /** 6516 * Derive the value of the {@code cpuAbiOverride} based on the provided 6517 * value and an optional stored value from the package settings. 6518 */ 6519 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6520 String cpuAbiOverride = null; 6521 6522 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6523 cpuAbiOverride = null; 6524 } else if (abiOverride != null) { 6525 cpuAbiOverride = abiOverride; 6526 } else if (settings != null) { 6527 cpuAbiOverride = settings.cpuAbiOverrideString; 6528 } 6529 6530 return cpuAbiOverride; 6531 } 6532 6533 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6534 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6535 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6536 try { 6537 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6538 } finally { 6539 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6540 } 6541 } 6542 6543 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6544 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6545 boolean success = false; 6546 try { 6547 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6548 currentTime, user); 6549 success = true; 6550 return res; 6551 } finally { 6552 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6553 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6554 } 6555 } 6556 } 6557 6558 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6559 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6560 final File scanFile = new File(pkg.codePath); 6561 if (pkg.applicationInfo.getCodePath() == null || 6562 pkg.applicationInfo.getResourcePath() == null) { 6563 // Bail out. The resource and code paths haven't been set. 6564 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6565 "Code and resource paths haven't been set correctly"); 6566 } 6567 6568 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6569 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6570 } else { 6571 // Only allow system apps to be flagged as core apps. 6572 pkg.coreApp = false; 6573 } 6574 6575 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6576 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6577 } 6578 6579 if (mCustomResolverComponentName != null && 6580 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6581 setUpCustomResolverActivity(pkg); 6582 } 6583 6584 if (pkg.packageName.equals("android")) { 6585 synchronized (mPackages) { 6586 if (mAndroidApplication != null) { 6587 Slog.w(TAG, "*************************************************"); 6588 Slog.w(TAG, "Core android package being redefined. Skipping."); 6589 Slog.w(TAG, " file=" + scanFile); 6590 Slog.w(TAG, "*************************************************"); 6591 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6592 "Core android package being redefined. Skipping."); 6593 } 6594 6595 // Set up information for our fall-back user intent resolution activity. 6596 mPlatformPackage = pkg; 6597 pkg.mVersionCode = mSdkVersion; 6598 mAndroidApplication = pkg.applicationInfo; 6599 6600 if (!mResolverReplaced) { 6601 mResolveActivity.applicationInfo = mAndroidApplication; 6602 mResolveActivity.name = ResolverActivity.class.getName(); 6603 mResolveActivity.packageName = mAndroidApplication.packageName; 6604 mResolveActivity.processName = "system:ui"; 6605 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6606 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6607 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6608 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6609 mResolveActivity.exported = true; 6610 mResolveActivity.enabled = true; 6611 mResolveInfo.activityInfo = mResolveActivity; 6612 mResolveInfo.priority = 0; 6613 mResolveInfo.preferredOrder = 0; 6614 mResolveInfo.match = 0; 6615 mResolveComponentName = new ComponentName( 6616 mAndroidApplication.packageName, mResolveActivity.name); 6617 } 6618 } 6619 } 6620 6621 if (DEBUG_PACKAGE_SCANNING) { 6622 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6623 Log.d(TAG, "Scanning package " + pkg.packageName); 6624 } 6625 6626 if (mPackages.containsKey(pkg.packageName) 6627 || mSharedLibraries.containsKey(pkg.packageName)) { 6628 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6629 "Application package " + pkg.packageName 6630 + " already installed. Skipping duplicate."); 6631 } 6632 6633 // If we're only installing presumed-existing packages, require that the 6634 // scanned APK is both already known and at the path previously established 6635 // for it. Previously unknown packages we pick up normally, but if we have an 6636 // a priori expectation about this package's install presence, enforce it. 6637 // With a singular exception for new system packages. When an OTA contains 6638 // a new system package, we allow the codepath to change from a system location 6639 // to the user-installed location. If we don't allow this change, any newer, 6640 // user-installed version of the application will be ignored. 6641 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6642 if (mExpectingBetter.containsKey(pkg.packageName)) { 6643 logCriticalInfo(Log.WARN, 6644 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6645 } else { 6646 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6647 if (known != null) { 6648 if (DEBUG_PACKAGE_SCANNING) { 6649 Log.d(TAG, "Examining " + pkg.codePath 6650 + " and requiring known paths " + known.codePathString 6651 + " & " + known.resourcePathString); 6652 } 6653 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6654 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6655 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6656 "Application package " + pkg.packageName 6657 + " found at " + pkg.applicationInfo.getCodePath() 6658 + " but expected at " + known.codePathString + "; ignoring."); 6659 } 6660 } 6661 } 6662 } 6663 6664 // Initialize package source and resource directories 6665 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6666 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6667 6668 SharedUserSetting suid = null; 6669 PackageSetting pkgSetting = null; 6670 6671 if (!isSystemApp(pkg)) { 6672 // Only system apps can use these features. 6673 pkg.mOriginalPackages = null; 6674 pkg.mRealPackage = null; 6675 pkg.mAdoptPermissions = null; 6676 } 6677 6678 // writer 6679 synchronized (mPackages) { 6680 if (pkg.mSharedUserId != null) { 6681 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6682 if (suid == null) { 6683 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6684 "Creating application package " + pkg.packageName 6685 + " for shared user failed"); 6686 } 6687 if (DEBUG_PACKAGE_SCANNING) { 6688 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6689 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6690 + "): packages=" + suid.packages); 6691 } 6692 } 6693 6694 // Check if we are renaming from an original package name. 6695 PackageSetting origPackage = null; 6696 String realName = null; 6697 if (pkg.mOriginalPackages != null) { 6698 // This package may need to be renamed to a previously 6699 // installed name. Let's check on that... 6700 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6701 if (pkg.mOriginalPackages.contains(renamed)) { 6702 // This package had originally been installed as the 6703 // original name, and we have already taken care of 6704 // transitioning to the new one. Just update the new 6705 // one to continue using the old name. 6706 realName = pkg.mRealPackage; 6707 if (!pkg.packageName.equals(renamed)) { 6708 // Callers into this function may have already taken 6709 // care of renaming the package; only do it here if 6710 // it is not already done. 6711 pkg.setPackageName(renamed); 6712 } 6713 6714 } else { 6715 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6716 if ((origPackage = mSettings.peekPackageLPr( 6717 pkg.mOriginalPackages.get(i))) != null) { 6718 // We do have the package already installed under its 6719 // original name... should we use it? 6720 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6721 // New package is not compatible with original. 6722 origPackage = null; 6723 continue; 6724 } else if (origPackage.sharedUser != null) { 6725 // Make sure uid is compatible between packages. 6726 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6727 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6728 + " to " + pkg.packageName + ": old uid " 6729 + origPackage.sharedUser.name 6730 + " differs from " + pkg.mSharedUserId); 6731 origPackage = null; 6732 continue; 6733 } 6734 } else { 6735 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6736 + pkg.packageName + " to old name " + origPackage.name); 6737 } 6738 break; 6739 } 6740 } 6741 } 6742 } 6743 6744 if (mTransferedPackages.contains(pkg.packageName)) { 6745 Slog.w(TAG, "Package " + pkg.packageName 6746 + " was transferred to another, but its .apk remains"); 6747 } 6748 6749 // Just create the setting, don't add it yet. For already existing packages 6750 // the PkgSetting exists already and doesn't have to be created. 6751 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6752 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6753 pkg.applicationInfo.primaryCpuAbi, 6754 pkg.applicationInfo.secondaryCpuAbi, 6755 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6756 user, false); 6757 if (pkgSetting == null) { 6758 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6759 "Creating application package " + pkg.packageName + " failed"); 6760 } 6761 6762 if (pkgSetting.origPackage != null) { 6763 // If we are first transitioning from an original package, 6764 // fix up the new package's name now. We need to do this after 6765 // looking up the package under its new name, so getPackageLP 6766 // can take care of fiddling things correctly. 6767 pkg.setPackageName(origPackage.name); 6768 6769 // File a report about this. 6770 String msg = "New package " + pkgSetting.realName 6771 + " renamed to replace old package " + pkgSetting.name; 6772 reportSettingsProblem(Log.WARN, msg); 6773 6774 // Make a note of it. 6775 mTransferedPackages.add(origPackage.name); 6776 6777 // No longer need to retain this. 6778 pkgSetting.origPackage = null; 6779 } 6780 6781 if (realName != null) { 6782 // Make a note of it. 6783 mTransferedPackages.add(pkg.packageName); 6784 } 6785 6786 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6787 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6788 } 6789 6790 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6791 // Check all shared libraries and map to their actual file path. 6792 // We only do this here for apps not on a system dir, because those 6793 // are the only ones that can fail an install due to this. We 6794 // will take care of the system apps by updating all of their 6795 // library paths after the scan is done. 6796 updateSharedLibrariesLPw(pkg, null); 6797 } 6798 6799 if (mFoundPolicyFile) { 6800 SELinuxMMAC.assignSeinfoValue(pkg); 6801 } 6802 6803 pkg.applicationInfo.uid = pkgSetting.appId; 6804 pkg.mExtras = pkgSetting; 6805 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6806 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6807 // We just determined the app is signed correctly, so bring 6808 // over the latest parsed certs. 6809 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6810 } else { 6811 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6812 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6813 "Package " + pkg.packageName + " upgrade keys do not match the " 6814 + "previously installed version"); 6815 } else { 6816 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6817 String msg = "System package " + pkg.packageName 6818 + " signature changed; retaining data."; 6819 reportSettingsProblem(Log.WARN, msg); 6820 } 6821 } 6822 } else { 6823 try { 6824 verifySignaturesLP(pkgSetting, pkg); 6825 // We just determined the app is signed correctly, so bring 6826 // over the latest parsed certs. 6827 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6828 } catch (PackageManagerException e) { 6829 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6830 throw e; 6831 } 6832 // The signature has changed, but this package is in the system 6833 // image... let's recover! 6834 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6835 // However... if this package is part of a shared user, but it 6836 // doesn't match the signature of the shared user, let's fail. 6837 // What this means is that you can't change the signatures 6838 // associated with an overall shared user, which doesn't seem all 6839 // that unreasonable. 6840 if (pkgSetting.sharedUser != null) { 6841 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6842 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6843 throw new PackageManagerException( 6844 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6845 "Signature mismatch for shared user : " 6846 + pkgSetting.sharedUser); 6847 } 6848 } 6849 // File a report about this. 6850 String msg = "System package " + pkg.packageName 6851 + " signature changed; retaining data."; 6852 reportSettingsProblem(Log.WARN, msg); 6853 } 6854 } 6855 // Verify that this new package doesn't have any content providers 6856 // that conflict with existing packages. Only do this if the 6857 // package isn't already installed, since we don't want to break 6858 // things that are installed. 6859 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6860 final int N = pkg.providers.size(); 6861 int i; 6862 for (i=0; i<N; i++) { 6863 PackageParser.Provider p = pkg.providers.get(i); 6864 if (p.info.authority != null) { 6865 String names[] = p.info.authority.split(";"); 6866 for (int j = 0; j < names.length; j++) { 6867 if (mProvidersByAuthority.containsKey(names[j])) { 6868 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6869 final String otherPackageName = 6870 ((other != null && other.getComponentName() != null) ? 6871 other.getComponentName().getPackageName() : "?"); 6872 throw new PackageManagerException( 6873 INSTALL_FAILED_CONFLICTING_PROVIDER, 6874 "Can't install because provider name " + names[j] 6875 + " (in package " + pkg.applicationInfo.packageName 6876 + ") is already used by " + otherPackageName); 6877 } 6878 } 6879 } 6880 } 6881 } 6882 6883 if (pkg.mAdoptPermissions != null) { 6884 // This package wants to adopt ownership of permissions from 6885 // another package. 6886 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6887 final String origName = pkg.mAdoptPermissions.get(i); 6888 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6889 if (orig != null) { 6890 if (verifyPackageUpdateLPr(orig, pkg)) { 6891 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6892 + pkg.packageName); 6893 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6894 } 6895 } 6896 } 6897 } 6898 } 6899 6900 final String pkgName = pkg.packageName; 6901 6902 final long scanFileTime = scanFile.lastModified(); 6903 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6904 pkg.applicationInfo.processName = fixProcessName( 6905 pkg.applicationInfo.packageName, 6906 pkg.applicationInfo.processName, 6907 pkg.applicationInfo.uid); 6908 6909 File dataPath; 6910 if (mPlatformPackage == pkg) { 6911 // The system package is special. 6912 dataPath = new File(Environment.getDataDirectory(), "system"); 6913 6914 pkg.applicationInfo.dataDir = dataPath.getPath(); 6915 6916 } else { 6917 // This is a normal package, need to make its data directory. 6918 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6919 UserHandle.USER_OWNER, pkg.packageName); 6920 6921 boolean uidError = false; 6922 if (dataPath.exists()) { 6923 int currentUid = 0; 6924 try { 6925 StructStat stat = Os.stat(dataPath.getPath()); 6926 currentUid = stat.st_uid; 6927 } catch (ErrnoException e) { 6928 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6929 } 6930 6931 // If we have mismatched owners for the data path, we have a problem. 6932 if (currentUid != pkg.applicationInfo.uid) { 6933 boolean recovered = false; 6934 if (currentUid == 0) { 6935 // The directory somehow became owned by root. Wow. 6936 // This is probably because the system was stopped while 6937 // installd was in the middle of messing with its libs 6938 // directory. Ask installd to fix that. 6939 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6940 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6941 if (ret >= 0) { 6942 recovered = true; 6943 String msg = "Package " + pkg.packageName 6944 + " unexpectedly changed to uid 0; recovered to " + 6945 + pkg.applicationInfo.uid; 6946 reportSettingsProblem(Log.WARN, msg); 6947 } 6948 } 6949 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6950 || (scanFlags&SCAN_BOOTING) != 0)) { 6951 // If this is a system app, we can at least delete its 6952 // current data so the application will still work. 6953 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6954 if (ret >= 0) { 6955 // TODO: Kill the processes first 6956 // Old data gone! 6957 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6958 ? "System package " : "Third party package "; 6959 String msg = prefix + pkg.packageName 6960 + " has changed from uid: " 6961 + currentUid + " to " 6962 + pkg.applicationInfo.uid + "; old data erased"; 6963 reportSettingsProblem(Log.WARN, msg); 6964 recovered = true; 6965 6966 // And now re-install the app. 6967 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6968 pkg.applicationInfo.seinfo); 6969 if (ret == -1) { 6970 // Ack should not happen! 6971 msg = prefix + pkg.packageName 6972 + " could not have data directory re-created after delete."; 6973 reportSettingsProblem(Log.WARN, msg); 6974 throw new PackageManagerException( 6975 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6976 } 6977 } 6978 if (!recovered) { 6979 mHasSystemUidErrors = true; 6980 } 6981 } else if (!recovered) { 6982 // If we allow this install to proceed, we will be broken. 6983 // Abort, abort! 6984 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6985 "scanPackageLI"); 6986 } 6987 if (!recovered) { 6988 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6989 + pkg.applicationInfo.uid + "/fs_" 6990 + currentUid; 6991 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6992 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6993 String msg = "Package " + pkg.packageName 6994 + " has mismatched uid: " 6995 + currentUid + " on disk, " 6996 + pkg.applicationInfo.uid + " in settings"; 6997 // writer 6998 synchronized (mPackages) { 6999 mSettings.mReadMessages.append(msg); 7000 mSettings.mReadMessages.append('\n'); 7001 uidError = true; 7002 if (!pkgSetting.uidError) { 7003 reportSettingsProblem(Log.ERROR, msg); 7004 } 7005 } 7006 } 7007 } 7008 pkg.applicationInfo.dataDir = dataPath.getPath(); 7009 if (mShouldRestoreconData) { 7010 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7011 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7012 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7013 } 7014 } else { 7015 if (DEBUG_PACKAGE_SCANNING) { 7016 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7017 Log.v(TAG, "Want this data dir: " + dataPath); 7018 } 7019 //invoke installer to do the actual installation 7020 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7021 pkg.applicationInfo.seinfo); 7022 if (ret < 0) { 7023 // Error from installer 7024 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7025 "Unable to create data dirs [errorCode=" + ret + "]"); 7026 } 7027 7028 if (dataPath.exists()) { 7029 pkg.applicationInfo.dataDir = dataPath.getPath(); 7030 } else { 7031 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7032 pkg.applicationInfo.dataDir = null; 7033 } 7034 } 7035 7036 pkgSetting.uidError = uidError; 7037 } 7038 7039 final String path = scanFile.getPath(); 7040 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7041 7042 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7043 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7044 7045 // Some system apps still use directory structure for native libraries 7046 // in which case we might end up not detecting abi solely based on apk 7047 // structure. Try to detect abi based on directory structure. 7048 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7049 pkg.applicationInfo.primaryCpuAbi == null) { 7050 setBundledAppAbisAndRoots(pkg, pkgSetting); 7051 setNativeLibraryPaths(pkg); 7052 } 7053 7054 } else { 7055 if ((scanFlags & SCAN_MOVE) != 0) { 7056 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7057 // but we already have this packages package info in the PackageSetting. We just 7058 // use that and derive the native library path based on the new codepath. 7059 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7060 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7061 } 7062 7063 // Set native library paths again. For moves, the path will be updated based on the 7064 // ABIs we've determined above. For non-moves, the path will be updated based on the 7065 // ABIs we determined during compilation, but the path will depend on the final 7066 // package path (after the rename away from the stage path). 7067 setNativeLibraryPaths(pkg); 7068 } 7069 7070 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7071 final int[] userIds = sUserManager.getUserIds(); 7072 synchronized (mInstallLock) { 7073 // Make sure all user data directories are ready to roll; we're okay 7074 // if they already exist 7075 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7076 for (int userId : userIds) { 7077 if (userId != 0) { 7078 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7079 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7080 pkg.applicationInfo.seinfo); 7081 } 7082 } 7083 } 7084 7085 // Create a native library symlink only if we have native libraries 7086 // and if the native libraries are 32 bit libraries. We do not provide 7087 // this symlink for 64 bit libraries. 7088 if (pkg.applicationInfo.primaryCpuAbi != null && 7089 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7090 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7091 try { 7092 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7093 for (int userId : userIds) { 7094 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7095 nativeLibPath, userId) < 0) { 7096 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7097 "Failed linking native library dir (user=" + userId + ")"); 7098 } 7099 } 7100 } finally { 7101 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7102 } 7103 } 7104 } 7105 7106 // This is a special case for the "system" package, where the ABI is 7107 // dictated by the zygote configuration (and init.rc). We should keep track 7108 // of this ABI so that we can deal with "normal" applications that run under 7109 // the same UID correctly. 7110 if (mPlatformPackage == pkg) { 7111 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7112 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7113 } 7114 7115 // If there's a mismatch between the abi-override in the package setting 7116 // and the abiOverride specified for the install. Warn about this because we 7117 // would've already compiled the app without taking the package setting into 7118 // account. 7119 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7120 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7121 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7122 " for package: " + pkg.packageName); 7123 } 7124 } 7125 7126 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7127 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7128 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7129 7130 // Copy the derived override back to the parsed package, so that we can 7131 // update the package settings accordingly. 7132 pkg.cpuAbiOverride = cpuAbiOverride; 7133 7134 if (DEBUG_ABI_SELECTION) { 7135 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7136 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7137 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7138 } 7139 7140 // Push the derived path down into PackageSettings so we know what to 7141 // clean up at uninstall time. 7142 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7143 7144 if (DEBUG_ABI_SELECTION) { 7145 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7146 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7147 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7148 } 7149 7150 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7151 // We don't do this here during boot because we can do it all 7152 // at once after scanning all existing packages. 7153 // 7154 // We also do this *before* we perform dexopt on this package, so that 7155 // we can avoid redundant dexopts, and also to make sure we've got the 7156 // code and package path correct. 7157 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7158 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7159 } 7160 7161 if ((scanFlags & SCAN_NO_DEX) == 0) { 7162 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7163 7164 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7165 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7166 7167 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7168 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7169 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7170 } 7171 } 7172 if (mFactoryTest && pkg.requestedPermissions.contains( 7173 android.Manifest.permission.FACTORY_TEST)) { 7174 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7175 } 7176 7177 ArrayList<PackageParser.Package> clientLibPkgs = null; 7178 7179 // writer 7180 synchronized (mPackages) { 7181 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7182 // Only system apps can add new shared libraries. 7183 if (pkg.libraryNames != null) { 7184 for (int i=0; i<pkg.libraryNames.size(); i++) { 7185 String name = pkg.libraryNames.get(i); 7186 boolean allowed = false; 7187 if (pkg.isUpdatedSystemApp()) { 7188 // New library entries can only be added through the 7189 // system image. This is important to get rid of a lot 7190 // of nasty edge cases: for example if we allowed a non- 7191 // system update of the app to add a library, then uninstalling 7192 // the update would make the library go away, and assumptions 7193 // we made such as through app install filtering would now 7194 // have allowed apps on the device which aren't compatible 7195 // with it. Better to just have the restriction here, be 7196 // conservative, and create many fewer cases that can negatively 7197 // impact the user experience. 7198 final PackageSetting sysPs = mSettings 7199 .getDisabledSystemPkgLPr(pkg.packageName); 7200 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7201 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7202 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7203 allowed = true; 7204 allowed = true; 7205 break; 7206 } 7207 } 7208 } 7209 } else { 7210 allowed = true; 7211 } 7212 if (allowed) { 7213 if (!mSharedLibraries.containsKey(name)) { 7214 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7215 } else if (!name.equals(pkg.packageName)) { 7216 Slog.w(TAG, "Package " + pkg.packageName + " library " 7217 + name + " already exists; skipping"); 7218 } 7219 } else { 7220 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7221 + name + " that is not declared on system image; skipping"); 7222 } 7223 } 7224 if ((scanFlags&SCAN_BOOTING) == 0) { 7225 // If we are not booting, we need to update any applications 7226 // that are clients of our shared library. If we are booting, 7227 // this will all be done once the scan is complete. 7228 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7229 } 7230 } 7231 } 7232 } 7233 7234 // We also need to dexopt any apps that are dependent on this library. Note that 7235 // if these fail, we should abort the install since installing the library will 7236 // result in some apps being broken. 7237 if (clientLibPkgs != null) { 7238 if ((scanFlags & SCAN_NO_DEX) == 0) { 7239 for (int i = 0; i < clientLibPkgs.size(); i++) { 7240 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7241 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7242 null /* instruction sets */, forceDex, 7243 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7244 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7245 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7246 "scanPackageLI failed to dexopt clientLibPkgs"); 7247 } 7248 } 7249 } 7250 } 7251 7252 // Request the ActivityManager to kill the process(only for existing packages) 7253 // so that we do not end up in a confused state while the user is still using the older 7254 // version of the application while the new one gets installed. 7255 if ((scanFlags & SCAN_REPLACING) != 0) { 7256 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7257 7258 killApplication(pkg.applicationInfo.packageName, 7259 pkg.applicationInfo.uid, "replace pkg"); 7260 7261 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7262 } 7263 7264 // Also need to kill any apps that are dependent on the library. 7265 if (clientLibPkgs != null) { 7266 for (int i=0; i<clientLibPkgs.size(); i++) { 7267 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7268 killApplication(clientPkg.applicationInfo.packageName, 7269 clientPkg.applicationInfo.uid, "update lib"); 7270 } 7271 } 7272 7273 // Make sure we're not adding any bogus keyset info 7274 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7275 ksms.assertScannedPackageValid(pkg); 7276 7277 // writer 7278 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7279 7280 boolean createIdmapFailed = false; 7281 synchronized (mPackages) { 7282 // We don't expect installation to fail beyond this point 7283 7284 // Add the new setting to mSettings 7285 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7286 // Add the new setting to mPackages 7287 mPackages.put(pkg.applicationInfo.packageName, pkg); 7288 // Make sure we don't accidentally delete its data. 7289 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7290 while (iter.hasNext()) { 7291 PackageCleanItem item = iter.next(); 7292 if (pkgName.equals(item.packageName)) { 7293 iter.remove(); 7294 } 7295 } 7296 7297 // Take care of first install / last update times. 7298 if (currentTime != 0) { 7299 if (pkgSetting.firstInstallTime == 0) { 7300 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7301 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7302 pkgSetting.lastUpdateTime = currentTime; 7303 } 7304 } else if (pkgSetting.firstInstallTime == 0) { 7305 // We need *something*. Take time time stamp of the file. 7306 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7307 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7308 if (scanFileTime != pkgSetting.timeStamp) { 7309 // A package on the system image has changed; consider this 7310 // to be an update. 7311 pkgSetting.lastUpdateTime = scanFileTime; 7312 } 7313 } 7314 7315 // Add the package's KeySets to the global KeySetManagerService 7316 ksms.addScannedPackageLPw(pkg); 7317 7318 int N = pkg.providers.size(); 7319 StringBuilder r = null; 7320 int i; 7321 for (i=0; i<N; i++) { 7322 PackageParser.Provider p = pkg.providers.get(i); 7323 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7324 p.info.processName, pkg.applicationInfo.uid); 7325 mProviders.addProvider(p); 7326 p.syncable = p.info.isSyncable; 7327 if (p.info.authority != null) { 7328 String names[] = p.info.authority.split(";"); 7329 p.info.authority = null; 7330 for (int j = 0; j < names.length; j++) { 7331 if (j == 1 && p.syncable) { 7332 // We only want the first authority for a provider to possibly be 7333 // syncable, so if we already added this provider using a different 7334 // authority clear the syncable flag. We copy the provider before 7335 // changing it because the mProviders object contains a reference 7336 // to a provider that we don't want to change. 7337 // Only do this for the second authority since the resulting provider 7338 // object can be the same for all future authorities for this provider. 7339 p = new PackageParser.Provider(p); 7340 p.syncable = false; 7341 } 7342 if (!mProvidersByAuthority.containsKey(names[j])) { 7343 mProvidersByAuthority.put(names[j], p); 7344 if (p.info.authority == null) { 7345 p.info.authority = names[j]; 7346 } else { 7347 p.info.authority = p.info.authority + ";" + names[j]; 7348 } 7349 if (DEBUG_PACKAGE_SCANNING) { 7350 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7351 Log.d(TAG, "Registered content provider: " + names[j] 7352 + ", className = " + p.info.name + ", isSyncable = " 7353 + p.info.isSyncable); 7354 } 7355 } else { 7356 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7357 Slog.w(TAG, "Skipping provider name " + names[j] + 7358 " (in package " + pkg.applicationInfo.packageName + 7359 "): name already used by " 7360 + ((other != null && other.getComponentName() != null) 7361 ? other.getComponentName().getPackageName() : "?")); 7362 } 7363 } 7364 } 7365 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7366 if (r == null) { 7367 r = new StringBuilder(256); 7368 } else { 7369 r.append(' '); 7370 } 7371 r.append(p.info.name); 7372 } 7373 } 7374 if (r != null) { 7375 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7376 } 7377 7378 N = pkg.services.size(); 7379 r = null; 7380 for (i=0; i<N; i++) { 7381 PackageParser.Service s = pkg.services.get(i); 7382 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7383 s.info.processName, pkg.applicationInfo.uid); 7384 mServices.addService(s); 7385 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7386 if (r == null) { 7387 r = new StringBuilder(256); 7388 } else { 7389 r.append(' '); 7390 } 7391 r.append(s.info.name); 7392 } 7393 } 7394 if (r != null) { 7395 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7396 } 7397 7398 N = pkg.receivers.size(); 7399 r = null; 7400 for (i=0; i<N; i++) { 7401 PackageParser.Activity a = pkg.receivers.get(i); 7402 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7403 a.info.processName, pkg.applicationInfo.uid); 7404 mReceivers.addActivity(a, "receiver"); 7405 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7406 if (r == null) { 7407 r = new StringBuilder(256); 7408 } else { 7409 r.append(' '); 7410 } 7411 r.append(a.info.name); 7412 } 7413 } 7414 if (r != null) { 7415 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7416 } 7417 7418 N = pkg.activities.size(); 7419 r = null; 7420 for (i=0; i<N; i++) { 7421 PackageParser.Activity a = pkg.activities.get(i); 7422 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7423 a.info.processName, pkg.applicationInfo.uid); 7424 mActivities.addActivity(a, "activity"); 7425 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7426 if (r == null) { 7427 r = new StringBuilder(256); 7428 } else { 7429 r.append(' '); 7430 } 7431 r.append(a.info.name); 7432 } 7433 } 7434 if (r != null) { 7435 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7436 } 7437 7438 N = pkg.permissionGroups.size(); 7439 r = null; 7440 for (i=0; i<N; i++) { 7441 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7442 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7443 if (cur == null) { 7444 mPermissionGroups.put(pg.info.name, pg); 7445 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7446 if (r == null) { 7447 r = new StringBuilder(256); 7448 } else { 7449 r.append(' '); 7450 } 7451 r.append(pg.info.name); 7452 } 7453 } else { 7454 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7455 + pg.info.packageName + " ignored: original from " 7456 + cur.info.packageName); 7457 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7458 if (r == null) { 7459 r = new StringBuilder(256); 7460 } else { 7461 r.append(' '); 7462 } 7463 r.append("DUP:"); 7464 r.append(pg.info.name); 7465 } 7466 } 7467 } 7468 if (r != null) { 7469 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7470 } 7471 7472 N = pkg.permissions.size(); 7473 r = null; 7474 for (i=0; i<N; i++) { 7475 PackageParser.Permission p = pkg.permissions.get(i); 7476 7477 // Assume by default that we did not install this permission into the system. 7478 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7479 7480 // Now that permission groups have a special meaning, we ignore permission 7481 // groups for legacy apps to prevent unexpected behavior. In particular, 7482 // permissions for one app being granted to someone just becuase they happen 7483 // to be in a group defined by another app (before this had no implications). 7484 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7485 p.group = mPermissionGroups.get(p.info.group); 7486 // Warn for a permission in an unknown group. 7487 if (p.info.group != null && p.group == null) { 7488 Slog.w(TAG, "Permission " + p.info.name + " from package " 7489 + p.info.packageName + " in an unknown group " + p.info.group); 7490 } 7491 } 7492 7493 ArrayMap<String, BasePermission> permissionMap = 7494 p.tree ? mSettings.mPermissionTrees 7495 : mSettings.mPermissions; 7496 BasePermission bp = permissionMap.get(p.info.name); 7497 7498 // Allow system apps to redefine non-system permissions 7499 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7500 final boolean currentOwnerIsSystem = (bp.perm != null 7501 && isSystemApp(bp.perm.owner)); 7502 if (isSystemApp(p.owner)) { 7503 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7504 // It's a built-in permission and no owner, take ownership now 7505 bp.packageSetting = pkgSetting; 7506 bp.perm = p; 7507 bp.uid = pkg.applicationInfo.uid; 7508 bp.sourcePackage = p.info.packageName; 7509 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7510 } else if (!currentOwnerIsSystem) { 7511 String msg = "New decl " + p.owner + " of permission " 7512 + p.info.name + " is system; overriding " + bp.sourcePackage; 7513 reportSettingsProblem(Log.WARN, msg); 7514 bp = null; 7515 } 7516 } 7517 } 7518 7519 if (bp == null) { 7520 bp = new BasePermission(p.info.name, p.info.packageName, 7521 BasePermission.TYPE_NORMAL); 7522 permissionMap.put(p.info.name, bp); 7523 } 7524 7525 if (bp.perm == null) { 7526 if (bp.sourcePackage == null 7527 || bp.sourcePackage.equals(p.info.packageName)) { 7528 BasePermission tree = findPermissionTreeLP(p.info.name); 7529 if (tree == null 7530 || tree.sourcePackage.equals(p.info.packageName)) { 7531 bp.packageSetting = pkgSetting; 7532 bp.perm = p; 7533 bp.uid = pkg.applicationInfo.uid; 7534 bp.sourcePackage = p.info.packageName; 7535 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7536 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7537 if (r == null) { 7538 r = new StringBuilder(256); 7539 } else { 7540 r.append(' '); 7541 } 7542 r.append(p.info.name); 7543 } 7544 } else { 7545 Slog.w(TAG, "Permission " + p.info.name + " from package " 7546 + p.info.packageName + " ignored: base tree " 7547 + tree.name + " is from package " 7548 + tree.sourcePackage); 7549 } 7550 } else { 7551 Slog.w(TAG, "Permission " + p.info.name + " from package " 7552 + p.info.packageName + " ignored: original from " 7553 + bp.sourcePackage); 7554 } 7555 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7556 if (r == null) { 7557 r = new StringBuilder(256); 7558 } else { 7559 r.append(' '); 7560 } 7561 r.append("DUP:"); 7562 r.append(p.info.name); 7563 } 7564 if (bp.perm == p) { 7565 bp.protectionLevel = p.info.protectionLevel; 7566 } 7567 } 7568 7569 if (r != null) { 7570 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7571 } 7572 7573 N = pkg.instrumentation.size(); 7574 r = null; 7575 for (i=0; i<N; i++) { 7576 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7577 a.info.packageName = pkg.applicationInfo.packageName; 7578 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7579 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7580 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7581 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7582 a.info.dataDir = pkg.applicationInfo.dataDir; 7583 7584 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7585 // need other information about the application, like the ABI and what not ? 7586 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7587 mInstrumentation.put(a.getComponentName(), a); 7588 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7589 if (r == null) { 7590 r = new StringBuilder(256); 7591 } else { 7592 r.append(' '); 7593 } 7594 r.append(a.info.name); 7595 } 7596 } 7597 if (r != null) { 7598 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7599 } 7600 7601 if (pkg.protectedBroadcasts != null) { 7602 N = pkg.protectedBroadcasts.size(); 7603 for (i=0; i<N; i++) { 7604 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7605 } 7606 } 7607 7608 pkgSetting.setTimeStamp(scanFileTime); 7609 7610 // Create idmap files for pairs of (packages, overlay packages). 7611 // Note: "android", ie framework-res.apk, is handled by native layers. 7612 if (pkg.mOverlayTarget != null) { 7613 // This is an overlay package. 7614 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7615 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7616 mOverlays.put(pkg.mOverlayTarget, 7617 new ArrayMap<String, PackageParser.Package>()); 7618 } 7619 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7620 map.put(pkg.packageName, pkg); 7621 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7622 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7623 createIdmapFailed = true; 7624 } 7625 } 7626 } else if (mOverlays.containsKey(pkg.packageName) && 7627 !pkg.packageName.equals("android")) { 7628 // This is a regular package, with one or more known overlay packages. 7629 createIdmapsForPackageLI(pkg); 7630 } 7631 } 7632 7633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7634 7635 if (createIdmapFailed) { 7636 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7637 "scanPackageLI failed to createIdmap"); 7638 } 7639 return pkg; 7640 } 7641 7642 /** 7643 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7644 * is derived purely on the basis of the contents of {@code scanFile} and 7645 * {@code cpuAbiOverride}. 7646 * 7647 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7648 */ 7649 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7650 String cpuAbiOverride, boolean extractLibs) 7651 throws PackageManagerException { 7652 // TODO: We can probably be smarter about this stuff. For installed apps, 7653 // we can calculate this information at install time once and for all. For 7654 // system apps, we can probably assume that this information doesn't change 7655 // after the first boot scan. As things stand, we do lots of unnecessary work. 7656 7657 // Give ourselves some initial paths; we'll come back for another 7658 // pass once we've determined ABI below. 7659 setNativeLibraryPaths(pkg); 7660 7661 // We would never need to extract libs for forward-locked and external packages, 7662 // since the container service will do it for us. We shouldn't attempt to 7663 // extract libs from system app when it was not updated. 7664 if (pkg.isForwardLocked() || isExternal(pkg) || 7665 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7666 extractLibs = false; 7667 } 7668 7669 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7670 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7671 7672 NativeLibraryHelper.Handle handle = null; 7673 try { 7674 handle = NativeLibraryHelper.Handle.create(pkg); 7675 // TODO(multiArch): This can be null for apps that didn't go through the 7676 // usual installation process. We can calculate it again, like we 7677 // do during install time. 7678 // 7679 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7680 // unnecessary. 7681 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7682 7683 // Null out the abis so that they can be recalculated. 7684 pkg.applicationInfo.primaryCpuAbi = null; 7685 pkg.applicationInfo.secondaryCpuAbi = null; 7686 if (isMultiArch(pkg.applicationInfo)) { 7687 // Warn if we've set an abiOverride for multi-lib packages.. 7688 // By definition, we need to copy both 32 and 64 bit libraries for 7689 // such packages. 7690 if (pkg.cpuAbiOverride != null 7691 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7692 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7693 } 7694 7695 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7696 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7697 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7698 if (extractLibs) { 7699 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7700 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7701 useIsaSpecificSubdirs); 7702 } else { 7703 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7704 } 7705 } 7706 7707 maybeThrowExceptionForMultiArchCopy( 7708 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7709 7710 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7711 if (extractLibs) { 7712 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7713 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7714 useIsaSpecificSubdirs); 7715 } else { 7716 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7717 } 7718 } 7719 7720 maybeThrowExceptionForMultiArchCopy( 7721 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7722 7723 if (abi64 >= 0) { 7724 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7725 } 7726 7727 if (abi32 >= 0) { 7728 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7729 if (abi64 >= 0) { 7730 pkg.applicationInfo.secondaryCpuAbi = abi; 7731 } else { 7732 pkg.applicationInfo.primaryCpuAbi = abi; 7733 } 7734 } 7735 } else { 7736 String[] abiList = (cpuAbiOverride != null) ? 7737 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7738 7739 // Enable gross and lame hacks for apps that are built with old 7740 // SDK tools. We must scan their APKs for renderscript bitcode and 7741 // not launch them if it's present. Don't bother checking on devices 7742 // that don't have 64 bit support. 7743 boolean needsRenderScriptOverride = false; 7744 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7745 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7746 abiList = Build.SUPPORTED_32_BIT_ABIS; 7747 needsRenderScriptOverride = true; 7748 } 7749 7750 final int copyRet; 7751 if (extractLibs) { 7752 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7753 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7754 } else { 7755 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7756 } 7757 7758 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7759 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7760 "Error unpackaging native libs for app, errorCode=" + copyRet); 7761 } 7762 7763 if (copyRet >= 0) { 7764 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7765 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7766 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7767 } else if (needsRenderScriptOverride) { 7768 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7769 } 7770 } 7771 } catch (IOException ioe) { 7772 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7773 } finally { 7774 IoUtils.closeQuietly(handle); 7775 } 7776 7777 // Now that we've calculated the ABIs and determined if it's an internal app, 7778 // we will go ahead and populate the nativeLibraryPath. 7779 setNativeLibraryPaths(pkg); 7780 } 7781 7782 /** 7783 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7784 * i.e, so that all packages can be run inside a single process if required. 7785 * 7786 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7787 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7788 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7789 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7790 * updating a package that belongs to a shared user. 7791 * 7792 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7793 * adds unnecessary complexity. 7794 */ 7795 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7796 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7797 String requiredInstructionSet = null; 7798 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7799 requiredInstructionSet = VMRuntime.getInstructionSet( 7800 scannedPackage.applicationInfo.primaryCpuAbi); 7801 } 7802 7803 PackageSetting requirer = null; 7804 for (PackageSetting ps : packagesForUser) { 7805 // If packagesForUser contains scannedPackage, we skip it. This will happen 7806 // when scannedPackage is an update of an existing package. Without this check, 7807 // we will never be able to change the ABI of any package belonging to a shared 7808 // user, even if it's compatible with other packages. 7809 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7810 if (ps.primaryCpuAbiString == null) { 7811 continue; 7812 } 7813 7814 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7815 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7816 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7817 // this but there's not much we can do. 7818 String errorMessage = "Instruction set mismatch, " 7819 + ((requirer == null) ? "[caller]" : requirer) 7820 + " requires " + requiredInstructionSet + " whereas " + ps 7821 + " requires " + instructionSet; 7822 Slog.w(TAG, errorMessage); 7823 } 7824 7825 if (requiredInstructionSet == null) { 7826 requiredInstructionSet = instructionSet; 7827 requirer = ps; 7828 } 7829 } 7830 } 7831 7832 if (requiredInstructionSet != null) { 7833 String adjustedAbi; 7834 if (requirer != null) { 7835 // requirer != null implies that either scannedPackage was null or that scannedPackage 7836 // did not require an ABI, in which case we have to adjust scannedPackage to match 7837 // the ABI of the set (which is the same as requirer's ABI) 7838 adjustedAbi = requirer.primaryCpuAbiString; 7839 if (scannedPackage != null) { 7840 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7841 } 7842 } else { 7843 // requirer == null implies that we're updating all ABIs in the set to 7844 // match scannedPackage. 7845 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7846 } 7847 7848 for (PackageSetting ps : packagesForUser) { 7849 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7850 if (ps.primaryCpuAbiString != null) { 7851 continue; 7852 } 7853 7854 ps.primaryCpuAbiString = adjustedAbi; 7855 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7856 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7857 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7858 7859 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7860 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7861 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7862 ps.primaryCpuAbiString = null; 7863 ps.pkg.applicationInfo.primaryCpuAbi = null; 7864 return; 7865 } else { 7866 mInstaller.rmdex(ps.codePathString, 7867 getDexCodeInstructionSet(getPreferredInstructionSet())); 7868 } 7869 } 7870 } 7871 } 7872 } 7873 } 7874 7875 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7876 synchronized (mPackages) { 7877 mResolverReplaced = true; 7878 // Set up information for custom user intent resolution activity. 7879 mResolveActivity.applicationInfo = pkg.applicationInfo; 7880 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7881 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7882 mResolveActivity.processName = pkg.applicationInfo.packageName; 7883 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7884 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7885 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7886 mResolveActivity.theme = 0; 7887 mResolveActivity.exported = true; 7888 mResolveActivity.enabled = true; 7889 mResolveInfo.activityInfo = mResolveActivity; 7890 mResolveInfo.priority = 0; 7891 mResolveInfo.preferredOrder = 0; 7892 mResolveInfo.match = 0; 7893 mResolveComponentName = mCustomResolverComponentName; 7894 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7895 mResolveComponentName); 7896 } 7897 } 7898 7899 private static String calculateBundledApkRoot(final String codePathString) { 7900 final File codePath = new File(codePathString); 7901 final File codeRoot; 7902 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7903 codeRoot = Environment.getRootDirectory(); 7904 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7905 codeRoot = Environment.getOemDirectory(); 7906 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7907 codeRoot = Environment.getVendorDirectory(); 7908 } else { 7909 // Unrecognized code path; take its top real segment as the apk root: 7910 // e.g. /something/app/blah.apk => /something 7911 try { 7912 File f = codePath.getCanonicalFile(); 7913 File parent = f.getParentFile(); // non-null because codePath is a file 7914 File tmp; 7915 while ((tmp = parent.getParentFile()) != null) { 7916 f = parent; 7917 parent = tmp; 7918 } 7919 codeRoot = f; 7920 Slog.w(TAG, "Unrecognized code path " 7921 + codePath + " - using " + codeRoot); 7922 } catch (IOException e) { 7923 // Can't canonicalize the code path -- shenanigans? 7924 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7925 return Environment.getRootDirectory().getPath(); 7926 } 7927 } 7928 return codeRoot.getPath(); 7929 } 7930 7931 /** 7932 * Derive and set the location of native libraries for the given package, 7933 * which varies depending on where and how the package was installed. 7934 */ 7935 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7936 final ApplicationInfo info = pkg.applicationInfo; 7937 final String codePath = pkg.codePath; 7938 final File codeFile = new File(codePath); 7939 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7940 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7941 7942 info.nativeLibraryRootDir = null; 7943 info.nativeLibraryRootRequiresIsa = false; 7944 info.nativeLibraryDir = null; 7945 info.secondaryNativeLibraryDir = null; 7946 7947 if (isApkFile(codeFile)) { 7948 // Monolithic install 7949 if (bundledApp) { 7950 // If "/system/lib64/apkname" exists, assume that is the per-package 7951 // native library directory to use; otherwise use "/system/lib/apkname". 7952 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7953 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7954 getPrimaryInstructionSet(info)); 7955 7956 // This is a bundled system app so choose the path based on the ABI. 7957 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7958 // is just the default path. 7959 final String apkName = deriveCodePathName(codePath); 7960 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7961 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7962 apkName).getAbsolutePath(); 7963 7964 if (info.secondaryCpuAbi != null) { 7965 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7966 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7967 secondaryLibDir, apkName).getAbsolutePath(); 7968 } 7969 } else if (asecApp) { 7970 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7971 .getAbsolutePath(); 7972 } else { 7973 final String apkName = deriveCodePathName(codePath); 7974 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7975 .getAbsolutePath(); 7976 } 7977 7978 info.nativeLibraryRootRequiresIsa = false; 7979 info.nativeLibraryDir = info.nativeLibraryRootDir; 7980 } else { 7981 // Cluster install 7982 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7983 info.nativeLibraryRootRequiresIsa = true; 7984 7985 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7986 getPrimaryInstructionSet(info)).getAbsolutePath(); 7987 7988 if (info.secondaryCpuAbi != null) { 7989 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7990 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7991 } 7992 } 7993 } 7994 7995 /** 7996 * Calculate the abis and roots for a bundled app. These can uniquely 7997 * be determined from the contents of the system partition, i.e whether 7998 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7999 * of this information, and instead assume that the system was built 8000 * sensibly. 8001 */ 8002 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8003 PackageSetting pkgSetting) { 8004 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8005 8006 // If "/system/lib64/apkname" exists, assume that is the per-package 8007 // native library directory to use; otherwise use "/system/lib/apkname". 8008 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8009 setBundledAppAbi(pkg, apkRoot, apkName); 8010 // pkgSetting might be null during rescan following uninstall of updates 8011 // to a bundled app, so accommodate that possibility. The settings in 8012 // that case will be established later from the parsed package. 8013 // 8014 // If the settings aren't null, sync them up with what we've just derived. 8015 // note that apkRoot isn't stored in the package settings. 8016 if (pkgSetting != null) { 8017 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8018 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8019 } 8020 } 8021 8022 /** 8023 * Deduces the ABI of a bundled app and sets the relevant fields on the 8024 * parsed pkg object. 8025 * 8026 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8027 * under which system libraries are installed. 8028 * @param apkName the name of the installed package. 8029 */ 8030 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8031 final File codeFile = new File(pkg.codePath); 8032 8033 final boolean has64BitLibs; 8034 final boolean has32BitLibs; 8035 if (isApkFile(codeFile)) { 8036 // Monolithic install 8037 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8038 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8039 } else { 8040 // Cluster install 8041 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8042 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8043 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8044 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8045 has64BitLibs = (new File(rootDir, isa)).exists(); 8046 } else { 8047 has64BitLibs = false; 8048 } 8049 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8050 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8051 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8052 has32BitLibs = (new File(rootDir, isa)).exists(); 8053 } else { 8054 has32BitLibs = false; 8055 } 8056 } 8057 8058 if (has64BitLibs && !has32BitLibs) { 8059 // The package has 64 bit libs, but not 32 bit libs. Its primary 8060 // ABI should be 64 bit. We can safely assume here that the bundled 8061 // native libraries correspond to the most preferred ABI in the list. 8062 8063 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8064 pkg.applicationInfo.secondaryCpuAbi = null; 8065 } else if (has32BitLibs && !has64BitLibs) { 8066 // The package has 32 bit libs but not 64 bit libs. Its primary 8067 // ABI should be 32 bit. 8068 8069 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8070 pkg.applicationInfo.secondaryCpuAbi = null; 8071 } else if (has32BitLibs && has64BitLibs) { 8072 // The application has both 64 and 32 bit bundled libraries. We check 8073 // here that the app declares multiArch support, and warn if it doesn't. 8074 // 8075 // We will be lenient here and record both ABIs. The primary will be the 8076 // ABI that's higher on the list, i.e, a device that's configured to prefer 8077 // 64 bit apps will see a 64 bit primary ABI, 8078 8079 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8080 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8081 } 8082 8083 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8084 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8085 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8086 } else { 8087 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8088 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8089 } 8090 } else { 8091 pkg.applicationInfo.primaryCpuAbi = null; 8092 pkg.applicationInfo.secondaryCpuAbi = null; 8093 } 8094 } 8095 8096 private void killApplication(String pkgName, int appId, String reason) { 8097 // Request the ActivityManager to kill the process(only for existing packages) 8098 // so that we do not end up in a confused state while the user is still using the older 8099 // version of the application while the new one gets installed. 8100 IActivityManager am = ActivityManagerNative.getDefault(); 8101 if (am != null) { 8102 try { 8103 am.killApplicationWithAppId(pkgName, appId, reason); 8104 } catch (RemoteException e) { 8105 } 8106 } 8107 } 8108 8109 void removePackageLI(PackageSetting ps, boolean chatty) { 8110 if (DEBUG_INSTALL) { 8111 if (chatty) 8112 Log.d(TAG, "Removing package " + ps.name); 8113 } 8114 8115 // writer 8116 synchronized (mPackages) { 8117 mPackages.remove(ps.name); 8118 final PackageParser.Package pkg = ps.pkg; 8119 if (pkg != null) { 8120 cleanPackageDataStructuresLILPw(pkg, chatty); 8121 } 8122 } 8123 } 8124 8125 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8126 if (DEBUG_INSTALL) { 8127 if (chatty) 8128 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8129 } 8130 8131 // writer 8132 synchronized (mPackages) { 8133 mPackages.remove(pkg.applicationInfo.packageName); 8134 cleanPackageDataStructuresLILPw(pkg, chatty); 8135 } 8136 } 8137 8138 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8139 int N = pkg.providers.size(); 8140 StringBuilder r = null; 8141 int i; 8142 for (i=0; i<N; i++) { 8143 PackageParser.Provider p = pkg.providers.get(i); 8144 mProviders.removeProvider(p); 8145 if (p.info.authority == null) { 8146 8147 /* There was another ContentProvider with this authority when 8148 * this app was installed so this authority is null, 8149 * Ignore it as we don't have to unregister the provider. 8150 */ 8151 continue; 8152 } 8153 String names[] = p.info.authority.split(";"); 8154 for (int j = 0; j < names.length; j++) { 8155 if (mProvidersByAuthority.get(names[j]) == p) { 8156 mProvidersByAuthority.remove(names[j]); 8157 if (DEBUG_REMOVE) { 8158 if (chatty) 8159 Log.d(TAG, "Unregistered content provider: " + names[j] 8160 + ", className = " + p.info.name + ", isSyncable = " 8161 + p.info.isSyncable); 8162 } 8163 } 8164 } 8165 if (DEBUG_REMOVE && chatty) { 8166 if (r == null) { 8167 r = new StringBuilder(256); 8168 } else { 8169 r.append(' '); 8170 } 8171 r.append(p.info.name); 8172 } 8173 } 8174 if (r != null) { 8175 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8176 } 8177 8178 N = pkg.services.size(); 8179 r = null; 8180 for (i=0; i<N; i++) { 8181 PackageParser.Service s = pkg.services.get(i); 8182 mServices.removeService(s); 8183 if (chatty) { 8184 if (r == null) { 8185 r = new StringBuilder(256); 8186 } else { 8187 r.append(' '); 8188 } 8189 r.append(s.info.name); 8190 } 8191 } 8192 if (r != null) { 8193 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8194 } 8195 8196 N = pkg.receivers.size(); 8197 r = null; 8198 for (i=0; i<N; i++) { 8199 PackageParser.Activity a = pkg.receivers.get(i); 8200 mReceivers.removeActivity(a, "receiver"); 8201 if (DEBUG_REMOVE && chatty) { 8202 if (r == null) { 8203 r = new StringBuilder(256); 8204 } else { 8205 r.append(' '); 8206 } 8207 r.append(a.info.name); 8208 } 8209 } 8210 if (r != null) { 8211 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8212 } 8213 8214 N = pkg.activities.size(); 8215 r = null; 8216 for (i=0; i<N; i++) { 8217 PackageParser.Activity a = pkg.activities.get(i); 8218 mActivities.removeActivity(a, "activity"); 8219 if (DEBUG_REMOVE && chatty) { 8220 if (r == null) { 8221 r = new StringBuilder(256); 8222 } else { 8223 r.append(' '); 8224 } 8225 r.append(a.info.name); 8226 } 8227 } 8228 if (r != null) { 8229 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8230 } 8231 8232 N = pkg.permissions.size(); 8233 r = null; 8234 for (i=0; i<N; i++) { 8235 PackageParser.Permission p = pkg.permissions.get(i); 8236 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8237 if (bp == null) { 8238 bp = mSettings.mPermissionTrees.get(p.info.name); 8239 } 8240 if (bp != null && bp.perm == p) { 8241 bp.perm = null; 8242 if (DEBUG_REMOVE && chatty) { 8243 if (r == null) { 8244 r = new StringBuilder(256); 8245 } else { 8246 r.append(' '); 8247 } 8248 r.append(p.info.name); 8249 } 8250 } 8251 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8252 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8253 if (appOpPerms != null) { 8254 appOpPerms.remove(pkg.packageName); 8255 } 8256 } 8257 } 8258 if (r != null) { 8259 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8260 } 8261 8262 N = pkg.requestedPermissions.size(); 8263 r = null; 8264 for (i=0; i<N; i++) { 8265 String perm = pkg.requestedPermissions.get(i); 8266 BasePermission bp = mSettings.mPermissions.get(perm); 8267 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8268 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8269 if (appOpPerms != null) { 8270 appOpPerms.remove(pkg.packageName); 8271 if (appOpPerms.isEmpty()) { 8272 mAppOpPermissionPackages.remove(perm); 8273 } 8274 } 8275 } 8276 } 8277 if (r != null) { 8278 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8279 } 8280 8281 N = pkg.instrumentation.size(); 8282 r = null; 8283 for (i=0; i<N; i++) { 8284 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8285 mInstrumentation.remove(a.getComponentName()); 8286 if (DEBUG_REMOVE && chatty) { 8287 if (r == null) { 8288 r = new StringBuilder(256); 8289 } else { 8290 r.append(' '); 8291 } 8292 r.append(a.info.name); 8293 } 8294 } 8295 if (r != null) { 8296 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8297 } 8298 8299 r = null; 8300 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8301 // Only system apps can hold shared libraries. 8302 if (pkg.libraryNames != null) { 8303 for (i=0; i<pkg.libraryNames.size(); i++) { 8304 String name = pkg.libraryNames.get(i); 8305 SharedLibraryEntry cur = mSharedLibraries.get(name); 8306 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8307 mSharedLibraries.remove(name); 8308 if (DEBUG_REMOVE && chatty) { 8309 if (r == null) { 8310 r = new StringBuilder(256); 8311 } else { 8312 r.append(' '); 8313 } 8314 r.append(name); 8315 } 8316 } 8317 } 8318 } 8319 } 8320 if (r != null) { 8321 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8322 } 8323 } 8324 8325 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8326 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8327 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8328 return true; 8329 } 8330 } 8331 return false; 8332 } 8333 8334 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8335 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8336 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8337 8338 private void updatePermissionsLPw(String changingPkg, 8339 PackageParser.Package pkgInfo, int flags) { 8340 // Make sure there are no dangling permission trees. 8341 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8342 while (it.hasNext()) { 8343 final BasePermission bp = it.next(); 8344 if (bp.packageSetting == null) { 8345 // We may not yet have parsed the package, so just see if 8346 // we still know about its settings. 8347 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8348 } 8349 if (bp.packageSetting == null) { 8350 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8351 + " from package " + bp.sourcePackage); 8352 it.remove(); 8353 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8354 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8355 Slog.i(TAG, "Removing old permission tree: " + bp.name 8356 + " from package " + bp.sourcePackage); 8357 flags |= UPDATE_PERMISSIONS_ALL; 8358 it.remove(); 8359 } 8360 } 8361 } 8362 8363 // Make sure all dynamic permissions have been assigned to a package, 8364 // and make sure there are no dangling permissions. 8365 it = mSettings.mPermissions.values().iterator(); 8366 while (it.hasNext()) { 8367 final BasePermission bp = it.next(); 8368 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8369 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8370 + bp.name + " pkg=" + bp.sourcePackage 8371 + " info=" + bp.pendingInfo); 8372 if (bp.packageSetting == null && bp.pendingInfo != null) { 8373 final BasePermission tree = findPermissionTreeLP(bp.name); 8374 if (tree != null && tree.perm != null) { 8375 bp.packageSetting = tree.packageSetting; 8376 bp.perm = new PackageParser.Permission(tree.perm.owner, 8377 new PermissionInfo(bp.pendingInfo)); 8378 bp.perm.info.packageName = tree.perm.info.packageName; 8379 bp.perm.info.name = bp.name; 8380 bp.uid = tree.uid; 8381 } 8382 } 8383 } 8384 if (bp.packageSetting == null) { 8385 // We may not yet have parsed the package, so just see if 8386 // we still know about its settings. 8387 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8388 } 8389 if (bp.packageSetting == null) { 8390 Slog.w(TAG, "Removing dangling permission: " + bp.name 8391 + " from package " + bp.sourcePackage); 8392 it.remove(); 8393 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8394 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8395 Slog.i(TAG, "Removing old permission: " + bp.name 8396 + " from package " + bp.sourcePackage); 8397 flags |= UPDATE_PERMISSIONS_ALL; 8398 it.remove(); 8399 } 8400 } 8401 } 8402 8403 // Now update the permissions for all packages, in particular 8404 // replace the granted permissions of the system packages. 8405 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8406 for (PackageParser.Package pkg : mPackages.values()) { 8407 if (pkg != pkgInfo) { 8408 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8409 changingPkg); 8410 } 8411 } 8412 } 8413 8414 if (pkgInfo != null) { 8415 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8416 } 8417 } 8418 8419 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8420 String packageOfInterest) { 8421 // IMPORTANT: There are two types of permissions: install and runtime. 8422 // Install time permissions are granted when the app is installed to 8423 // all device users and users added in the future. Runtime permissions 8424 // are granted at runtime explicitly to specific users. Normal and signature 8425 // protected permissions are install time permissions. Dangerous permissions 8426 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8427 // otherwise they are runtime permissions. This function does not manage 8428 // runtime permissions except for the case an app targeting Lollipop MR1 8429 // being upgraded to target a newer SDK, in which case dangerous permissions 8430 // are transformed from install time to runtime ones. 8431 8432 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8433 if (ps == null) { 8434 return; 8435 } 8436 8437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8438 8439 PermissionsState permissionsState = ps.getPermissionsState(); 8440 PermissionsState origPermissions = permissionsState; 8441 8442 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8443 8444 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8445 8446 boolean changedInstallPermission = false; 8447 8448 if (replace) { 8449 ps.installPermissionsFixed = false; 8450 if (!ps.isSharedUser()) { 8451 origPermissions = new PermissionsState(permissionsState); 8452 permissionsState.reset(); 8453 } 8454 } 8455 8456 permissionsState.setGlobalGids(mGlobalGids); 8457 8458 final int N = pkg.requestedPermissions.size(); 8459 for (int i=0; i<N; i++) { 8460 final String name = pkg.requestedPermissions.get(i); 8461 final BasePermission bp = mSettings.mPermissions.get(name); 8462 8463 if (DEBUG_INSTALL) { 8464 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8465 } 8466 8467 if (bp == null || bp.packageSetting == null) { 8468 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8469 Slog.w(TAG, "Unknown permission " + name 8470 + " in package " + pkg.packageName); 8471 } 8472 continue; 8473 } 8474 8475 final String perm = bp.name; 8476 boolean allowedSig = false; 8477 int grant = GRANT_DENIED; 8478 8479 // Keep track of app op permissions. 8480 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8481 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8482 if (pkgs == null) { 8483 pkgs = new ArraySet<>(); 8484 mAppOpPermissionPackages.put(bp.name, pkgs); 8485 } 8486 pkgs.add(pkg.packageName); 8487 } 8488 8489 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8490 switch (level) { 8491 case PermissionInfo.PROTECTION_NORMAL: { 8492 // For all apps normal permissions are install time ones. 8493 grant = GRANT_INSTALL; 8494 } break; 8495 8496 case PermissionInfo.PROTECTION_DANGEROUS: { 8497 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8498 // For legacy apps dangerous permissions are install time ones. 8499 grant = GRANT_INSTALL_LEGACY; 8500 } else if (origPermissions.hasInstallPermission(bp.name)) { 8501 // For legacy apps that became modern, install becomes runtime. 8502 grant = GRANT_UPGRADE; 8503 } else if (mPromoteSystemApps 8504 && isSystemApp(ps) 8505 && mExistingSystemPackages.contains(ps.name)) { 8506 // For legacy system apps, install becomes runtime. 8507 // We cannot check hasInstallPermission() for system apps since those 8508 // permissions were granted implicitly and not persisted pre-M. 8509 grant = GRANT_UPGRADE; 8510 } else { 8511 // For modern apps keep runtime permissions unchanged. 8512 grant = GRANT_RUNTIME; 8513 } 8514 } break; 8515 8516 case PermissionInfo.PROTECTION_SIGNATURE: { 8517 // For all apps signature permissions are install time ones. 8518 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8519 if (allowedSig) { 8520 grant = GRANT_INSTALL; 8521 } 8522 } break; 8523 } 8524 8525 if (DEBUG_INSTALL) { 8526 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8527 } 8528 8529 if (grant != GRANT_DENIED) { 8530 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8531 // If this is an existing, non-system package, then 8532 // we can't add any new permissions to it. 8533 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8534 // Except... if this is a permission that was added 8535 // to the platform (note: need to only do this when 8536 // updating the platform). 8537 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8538 grant = GRANT_DENIED; 8539 } 8540 } 8541 } 8542 8543 switch (grant) { 8544 case GRANT_INSTALL: { 8545 // Revoke this as runtime permission to handle the case of 8546 // a runtime permission being downgraded to an install one. 8547 for (int userId : UserManagerService.getInstance().getUserIds()) { 8548 if (origPermissions.getRuntimePermissionState( 8549 bp.name, userId) != null) { 8550 // Revoke the runtime permission and clear the flags. 8551 origPermissions.revokeRuntimePermission(bp, userId); 8552 origPermissions.updatePermissionFlags(bp, userId, 8553 PackageManager.MASK_PERMISSION_FLAGS, 0); 8554 // If we revoked a permission permission, we have to write. 8555 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8556 changedRuntimePermissionUserIds, userId); 8557 } 8558 } 8559 // Grant an install permission. 8560 if (permissionsState.grantInstallPermission(bp) != 8561 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8562 changedInstallPermission = true; 8563 } 8564 } break; 8565 8566 case GRANT_INSTALL_LEGACY: { 8567 // Grant an install permission. 8568 if (permissionsState.grantInstallPermission(bp) != 8569 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8570 changedInstallPermission = true; 8571 } 8572 } break; 8573 8574 case GRANT_RUNTIME: { 8575 // Grant previously granted runtime permissions. 8576 for (int userId : UserManagerService.getInstance().getUserIds()) { 8577 PermissionState permissionState = origPermissions 8578 .getRuntimePermissionState(bp.name, userId); 8579 final int flags = permissionState != null 8580 ? permissionState.getFlags() : 0; 8581 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8582 if (permissionsState.grantRuntimePermission(bp, userId) == 8583 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8584 // If we cannot put the permission as it was, we have to write. 8585 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8586 changedRuntimePermissionUserIds, userId); 8587 } 8588 } 8589 // Propagate the permission flags. 8590 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8591 } 8592 } break; 8593 8594 case GRANT_UPGRADE: { 8595 // Grant runtime permissions for a previously held install permission. 8596 PermissionState permissionState = origPermissions 8597 .getInstallPermissionState(bp.name); 8598 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8599 8600 if (origPermissions.revokeInstallPermission(bp) 8601 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8602 // We will be transferring the permission flags, so clear them. 8603 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8604 PackageManager.MASK_PERMISSION_FLAGS, 0); 8605 changedInstallPermission = true; 8606 } 8607 8608 // If the permission is not to be promoted to runtime we ignore it and 8609 // also its other flags as they are not applicable to install permissions. 8610 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8611 for (int userId : currentUserIds) { 8612 if (permissionsState.grantRuntimePermission(bp, userId) != 8613 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8614 // Transfer the permission flags. 8615 permissionsState.updatePermissionFlags(bp, userId, 8616 flags, flags); 8617 // If we granted the permission, we have to write. 8618 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8619 changedRuntimePermissionUserIds, userId); 8620 } 8621 } 8622 } 8623 } break; 8624 8625 default: { 8626 if (packageOfInterest == null 8627 || packageOfInterest.equals(pkg.packageName)) { 8628 Slog.w(TAG, "Not granting permission " + perm 8629 + " to package " + pkg.packageName 8630 + " because it was previously installed without"); 8631 } 8632 } break; 8633 } 8634 } else { 8635 if (permissionsState.revokeInstallPermission(bp) != 8636 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8637 // Also drop the permission flags. 8638 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8639 PackageManager.MASK_PERMISSION_FLAGS, 0); 8640 changedInstallPermission = true; 8641 Slog.i(TAG, "Un-granting permission " + perm 8642 + " from package " + pkg.packageName 8643 + " (protectionLevel=" + bp.protectionLevel 8644 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8645 + ")"); 8646 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8647 // Don't print warning for app op permissions, since it is fine for them 8648 // not to be granted, there is a UI for the user to decide. 8649 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8650 Slog.w(TAG, "Not granting permission " + perm 8651 + " to package " + pkg.packageName 8652 + " (protectionLevel=" + bp.protectionLevel 8653 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8654 + ")"); 8655 } 8656 } 8657 } 8658 } 8659 8660 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8661 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8662 // This is the first that we have heard about this package, so the 8663 // permissions we have now selected are fixed until explicitly 8664 // changed. 8665 ps.installPermissionsFixed = true; 8666 } 8667 8668 // Persist the runtime permissions state for users with changes. 8669 for (int userId : changedRuntimePermissionUserIds) { 8670 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8671 } 8672 8673 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8674 } 8675 8676 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8677 boolean allowed = false; 8678 final int NP = PackageParser.NEW_PERMISSIONS.length; 8679 for (int ip=0; ip<NP; ip++) { 8680 final PackageParser.NewPermissionInfo npi 8681 = PackageParser.NEW_PERMISSIONS[ip]; 8682 if (npi.name.equals(perm) 8683 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8684 allowed = true; 8685 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8686 + pkg.packageName); 8687 break; 8688 } 8689 } 8690 return allowed; 8691 } 8692 8693 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8694 BasePermission bp, PermissionsState origPermissions) { 8695 boolean allowed; 8696 allowed = (compareSignatures( 8697 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8698 == PackageManager.SIGNATURE_MATCH) 8699 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8700 == PackageManager.SIGNATURE_MATCH); 8701 if (!allowed && (bp.protectionLevel 8702 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8703 if (isSystemApp(pkg)) { 8704 // For updated system applications, a system permission 8705 // is granted only if it had been defined by the original application. 8706 if (pkg.isUpdatedSystemApp()) { 8707 final PackageSetting sysPs = mSettings 8708 .getDisabledSystemPkgLPr(pkg.packageName); 8709 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8710 // If the original was granted this permission, we take 8711 // that grant decision as read and propagate it to the 8712 // update. 8713 if (sysPs.isPrivileged()) { 8714 allowed = true; 8715 } 8716 } else { 8717 // The system apk may have been updated with an older 8718 // version of the one on the data partition, but which 8719 // granted a new system permission that it didn't have 8720 // before. In this case we do want to allow the app to 8721 // now get the new permission if the ancestral apk is 8722 // privileged to get it. 8723 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8724 for (int j=0; 8725 j<sysPs.pkg.requestedPermissions.size(); j++) { 8726 if (perm.equals( 8727 sysPs.pkg.requestedPermissions.get(j))) { 8728 allowed = true; 8729 break; 8730 } 8731 } 8732 } 8733 } 8734 } else { 8735 allowed = isPrivilegedApp(pkg); 8736 } 8737 } 8738 } 8739 if (!allowed) { 8740 if (!allowed && (bp.protectionLevel 8741 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8742 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8743 // If this was a previously normal/dangerous permission that got moved 8744 // to a system permission as part of the runtime permission redesign, then 8745 // we still want to blindly grant it to old apps. 8746 allowed = true; 8747 } 8748 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8749 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8750 // If this permission is to be granted to the system installer and 8751 // this app is an installer, then it gets the permission. 8752 allowed = true; 8753 } 8754 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8755 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8756 // If this permission is to be granted to the system verifier and 8757 // this app is a verifier, then it gets the permission. 8758 allowed = true; 8759 } 8760 if (!allowed && (bp.protectionLevel 8761 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8762 && isSystemApp(pkg)) { 8763 // Any pre-installed system app is allowed to get this permission. 8764 allowed = true; 8765 } 8766 if (!allowed && (bp.protectionLevel 8767 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8768 // For development permissions, a development permission 8769 // is granted only if it was already granted. 8770 allowed = origPermissions.hasInstallPermission(perm); 8771 } 8772 } 8773 return allowed; 8774 } 8775 8776 final class ActivityIntentResolver 8777 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8778 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8779 boolean defaultOnly, int userId) { 8780 if (!sUserManager.exists(userId)) return null; 8781 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8782 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8783 } 8784 8785 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8786 int userId) { 8787 if (!sUserManager.exists(userId)) return null; 8788 mFlags = flags; 8789 return super.queryIntent(intent, resolvedType, 8790 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8791 } 8792 8793 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8794 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8795 if (!sUserManager.exists(userId)) return null; 8796 if (packageActivities == null) { 8797 return null; 8798 } 8799 mFlags = flags; 8800 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8801 final int N = packageActivities.size(); 8802 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8803 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8804 8805 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8806 for (int i = 0; i < N; ++i) { 8807 intentFilters = packageActivities.get(i).intents; 8808 if (intentFilters != null && intentFilters.size() > 0) { 8809 PackageParser.ActivityIntentInfo[] array = 8810 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8811 intentFilters.toArray(array); 8812 listCut.add(array); 8813 } 8814 } 8815 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8816 } 8817 8818 public final void addActivity(PackageParser.Activity a, String type) { 8819 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8820 mActivities.put(a.getComponentName(), a); 8821 if (DEBUG_SHOW_INFO) 8822 Log.v( 8823 TAG, " " + type + " " + 8824 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8825 if (DEBUG_SHOW_INFO) 8826 Log.v(TAG, " Class=" + a.info.name); 8827 final int NI = a.intents.size(); 8828 for (int j=0; j<NI; j++) { 8829 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8830 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8831 intent.setPriority(0); 8832 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8833 + a.className + " with priority > 0, forcing to 0"); 8834 } 8835 if (DEBUG_SHOW_INFO) { 8836 Log.v(TAG, " IntentFilter:"); 8837 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8838 } 8839 if (!intent.debugCheck()) { 8840 Log.w(TAG, "==> For Activity " + a.info.name); 8841 } 8842 addFilter(intent); 8843 } 8844 } 8845 8846 public final void removeActivity(PackageParser.Activity a, String type) { 8847 mActivities.remove(a.getComponentName()); 8848 if (DEBUG_SHOW_INFO) { 8849 Log.v(TAG, " " + type + " " 8850 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8851 : a.info.name) + ":"); 8852 Log.v(TAG, " Class=" + a.info.name); 8853 } 8854 final int NI = a.intents.size(); 8855 for (int j=0; j<NI; j++) { 8856 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8857 if (DEBUG_SHOW_INFO) { 8858 Log.v(TAG, " IntentFilter:"); 8859 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8860 } 8861 removeFilter(intent); 8862 } 8863 } 8864 8865 @Override 8866 protected boolean allowFilterResult( 8867 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8868 ActivityInfo filterAi = filter.activity.info; 8869 for (int i=dest.size()-1; i>=0; i--) { 8870 ActivityInfo destAi = dest.get(i).activityInfo; 8871 if (destAi.name == filterAi.name 8872 && destAi.packageName == filterAi.packageName) { 8873 return false; 8874 } 8875 } 8876 return true; 8877 } 8878 8879 @Override 8880 protected ActivityIntentInfo[] newArray(int size) { 8881 return new ActivityIntentInfo[size]; 8882 } 8883 8884 @Override 8885 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8886 if (!sUserManager.exists(userId)) return true; 8887 PackageParser.Package p = filter.activity.owner; 8888 if (p != null) { 8889 PackageSetting ps = (PackageSetting)p.mExtras; 8890 if (ps != null) { 8891 // System apps are never considered stopped for purposes of 8892 // filtering, because there may be no way for the user to 8893 // actually re-launch them. 8894 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8895 && ps.getStopped(userId); 8896 } 8897 } 8898 return false; 8899 } 8900 8901 @Override 8902 protected boolean isPackageForFilter(String packageName, 8903 PackageParser.ActivityIntentInfo info) { 8904 return packageName.equals(info.activity.owner.packageName); 8905 } 8906 8907 @Override 8908 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8909 int match, int userId) { 8910 if (!sUserManager.exists(userId)) return null; 8911 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8912 return null; 8913 } 8914 final PackageParser.Activity activity = info.activity; 8915 if (mSafeMode && (activity.info.applicationInfo.flags 8916 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8917 return null; 8918 } 8919 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8920 if (ps == null) { 8921 return null; 8922 } 8923 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8924 ps.readUserState(userId), userId); 8925 if (ai == null) { 8926 return null; 8927 } 8928 final ResolveInfo res = new ResolveInfo(); 8929 res.activityInfo = ai; 8930 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8931 res.filter = info; 8932 } 8933 if (info != null) { 8934 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8935 } 8936 res.priority = info.getPriority(); 8937 res.preferredOrder = activity.owner.mPreferredOrder; 8938 //System.out.println("Result: " + res.activityInfo.className + 8939 // " = " + res.priority); 8940 res.match = match; 8941 res.isDefault = info.hasDefault; 8942 res.labelRes = info.labelRes; 8943 res.nonLocalizedLabel = info.nonLocalizedLabel; 8944 if (userNeedsBadging(userId)) { 8945 res.noResourceId = true; 8946 } else { 8947 res.icon = info.icon; 8948 } 8949 res.iconResourceId = info.icon; 8950 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8951 return res; 8952 } 8953 8954 @Override 8955 protected void sortResults(List<ResolveInfo> results) { 8956 Collections.sort(results, mResolvePrioritySorter); 8957 } 8958 8959 @Override 8960 protected void dumpFilter(PrintWriter out, String prefix, 8961 PackageParser.ActivityIntentInfo filter) { 8962 out.print(prefix); out.print( 8963 Integer.toHexString(System.identityHashCode(filter.activity))); 8964 out.print(' '); 8965 filter.activity.printComponentShortName(out); 8966 out.print(" filter "); 8967 out.println(Integer.toHexString(System.identityHashCode(filter))); 8968 } 8969 8970 @Override 8971 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8972 return filter.activity; 8973 } 8974 8975 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8976 PackageParser.Activity activity = (PackageParser.Activity)label; 8977 out.print(prefix); out.print( 8978 Integer.toHexString(System.identityHashCode(activity))); 8979 out.print(' '); 8980 activity.printComponentShortName(out); 8981 if (count > 1) { 8982 out.print(" ("); out.print(count); out.print(" filters)"); 8983 } 8984 out.println(); 8985 } 8986 8987// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8988// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8989// final List<ResolveInfo> retList = Lists.newArrayList(); 8990// while (i.hasNext()) { 8991// final ResolveInfo resolveInfo = i.next(); 8992// if (isEnabledLP(resolveInfo.activityInfo)) { 8993// retList.add(resolveInfo); 8994// } 8995// } 8996// return retList; 8997// } 8998 8999 // Keys are String (activity class name), values are Activity. 9000 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9001 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9002 private int mFlags; 9003 } 9004 9005 private final class ServiceIntentResolver 9006 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9007 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9008 boolean defaultOnly, int userId) { 9009 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9010 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9011 } 9012 9013 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9014 int userId) { 9015 if (!sUserManager.exists(userId)) return null; 9016 mFlags = flags; 9017 return super.queryIntent(intent, resolvedType, 9018 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9019 } 9020 9021 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9022 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9023 if (!sUserManager.exists(userId)) return null; 9024 if (packageServices == null) { 9025 return null; 9026 } 9027 mFlags = flags; 9028 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9029 final int N = packageServices.size(); 9030 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9031 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9032 9033 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9034 for (int i = 0; i < N; ++i) { 9035 intentFilters = packageServices.get(i).intents; 9036 if (intentFilters != null && intentFilters.size() > 0) { 9037 PackageParser.ServiceIntentInfo[] array = 9038 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9039 intentFilters.toArray(array); 9040 listCut.add(array); 9041 } 9042 } 9043 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9044 } 9045 9046 public final void addService(PackageParser.Service s) { 9047 mServices.put(s.getComponentName(), s); 9048 if (DEBUG_SHOW_INFO) { 9049 Log.v(TAG, " " 9050 + (s.info.nonLocalizedLabel != null 9051 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9052 Log.v(TAG, " Class=" + s.info.name); 9053 } 9054 final int NI = s.intents.size(); 9055 int j; 9056 for (j=0; j<NI; j++) { 9057 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9058 if (DEBUG_SHOW_INFO) { 9059 Log.v(TAG, " IntentFilter:"); 9060 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9061 } 9062 if (!intent.debugCheck()) { 9063 Log.w(TAG, "==> For Service " + s.info.name); 9064 } 9065 addFilter(intent); 9066 } 9067 } 9068 9069 public final void removeService(PackageParser.Service s) { 9070 mServices.remove(s.getComponentName()); 9071 if (DEBUG_SHOW_INFO) { 9072 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9073 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9074 Log.v(TAG, " Class=" + s.info.name); 9075 } 9076 final int NI = s.intents.size(); 9077 int j; 9078 for (j=0; j<NI; j++) { 9079 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9080 if (DEBUG_SHOW_INFO) { 9081 Log.v(TAG, " IntentFilter:"); 9082 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9083 } 9084 removeFilter(intent); 9085 } 9086 } 9087 9088 @Override 9089 protected boolean allowFilterResult( 9090 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9091 ServiceInfo filterSi = filter.service.info; 9092 for (int i=dest.size()-1; i>=0; i--) { 9093 ServiceInfo destAi = dest.get(i).serviceInfo; 9094 if (destAi.name == filterSi.name 9095 && destAi.packageName == filterSi.packageName) { 9096 return false; 9097 } 9098 } 9099 return true; 9100 } 9101 9102 @Override 9103 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9104 return new PackageParser.ServiceIntentInfo[size]; 9105 } 9106 9107 @Override 9108 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9109 if (!sUserManager.exists(userId)) return true; 9110 PackageParser.Package p = filter.service.owner; 9111 if (p != null) { 9112 PackageSetting ps = (PackageSetting)p.mExtras; 9113 if (ps != null) { 9114 // System apps are never considered stopped for purposes of 9115 // filtering, because there may be no way for the user to 9116 // actually re-launch them. 9117 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9118 && ps.getStopped(userId); 9119 } 9120 } 9121 return false; 9122 } 9123 9124 @Override 9125 protected boolean isPackageForFilter(String packageName, 9126 PackageParser.ServiceIntentInfo info) { 9127 return packageName.equals(info.service.owner.packageName); 9128 } 9129 9130 @Override 9131 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9132 int match, int userId) { 9133 if (!sUserManager.exists(userId)) return null; 9134 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9135 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9136 return null; 9137 } 9138 final PackageParser.Service service = info.service; 9139 if (mSafeMode && (service.info.applicationInfo.flags 9140 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9141 return null; 9142 } 9143 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9144 if (ps == null) { 9145 return null; 9146 } 9147 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9148 ps.readUserState(userId), userId); 9149 if (si == null) { 9150 return null; 9151 } 9152 final ResolveInfo res = new ResolveInfo(); 9153 res.serviceInfo = si; 9154 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9155 res.filter = filter; 9156 } 9157 res.priority = info.getPriority(); 9158 res.preferredOrder = service.owner.mPreferredOrder; 9159 res.match = match; 9160 res.isDefault = info.hasDefault; 9161 res.labelRes = info.labelRes; 9162 res.nonLocalizedLabel = info.nonLocalizedLabel; 9163 res.icon = info.icon; 9164 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9165 return res; 9166 } 9167 9168 @Override 9169 protected void sortResults(List<ResolveInfo> results) { 9170 Collections.sort(results, mResolvePrioritySorter); 9171 } 9172 9173 @Override 9174 protected void dumpFilter(PrintWriter out, String prefix, 9175 PackageParser.ServiceIntentInfo filter) { 9176 out.print(prefix); out.print( 9177 Integer.toHexString(System.identityHashCode(filter.service))); 9178 out.print(' '); 9179 filter.service.printComponentShortName(out); 9180 out.print(" filter "); 9181 out.println(Integer.toHexString(System.identityHashCode(filter))); 9182 } 9183 9184 @Override 9185 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9186 return filter.service; 9187 } 9188 9189 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9190 PackageParser.Service service = (PackageParser.Service)label; 9191 out.print(prefix); out.print( 9192 Integer.toHexString(System.identityHashCode(service))); 9193 out.print(' '); 9194 service.printComponentShortName(out); 9195 if (count > 1) { 9196 out.print(" ("); out.print(count); out.print(" filters)"); 9197 } 9198 out.println(); 9199 } 9200 9201// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9202// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9203// final List<ResolveInfo> retList = Lists.newArrayList(); 9204// while (i.hasNext()) { 9205// final ResolveInfo resolveInfo = (ResolveInfo) i; 9206// if (isEnabledLP(resolveInfo.serviceInfo)) { 9207// retList.add(resolveInfo); 9208// } 9209// } 9210// return retList; 9211// } 9212 9213 // Keys are String (activity class name), values are Activity. 9214 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9215 = new ArrayMap<ComponentName, PackageParser.Service>(); 9216 private int mFlags; 9217 }; 9218 9219 private final class ProviderIntentResolver 9220 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9221 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9222 boolean defaultOnly, int userId) { 9223 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9224 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9225 } 9226 9227 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9228 int userId) { 9229 if (!sUserManager.exists(userId)) 9230 return null; 9231 mFlags = flags; 9232 return super.queryIntent(intent, resolvedType, 9233 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9234 } 9235 9236 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9237 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9238 if (!sUserManager.exists(userId)) 9239 return null; 9240 if (packageProviders == null) { 9241 return null; 9242 } 9243 mFlags = flags; 9244 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9245 final int N = packageProviders.size(); 9246 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9247 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9248 9249 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9250 for (int i = 0; i < N; ++i) { 9251 intentFilters = packageProviders.get(i).intents; 9252 if (intentFilters != null && intentFilters.size() > 0) { 9253 PackageParser.ProviderIntentInfo[] array = 9254 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9255 intentFilters.toArray(array); 9256 listCut.add(array); 9257 } 9258 } 9259 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9260 } 9261 9262 public final void addProvider(PackageParser.Provider p) { 9263 if (mProviders.containsKey(p.getComponentName())) { 9264 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9265 return; 9266 } 9267 9268 mProviders.put(p.getComponentName(), p); 9269 if (DEBUG_SHOW_INFO) { 9270 Log.v(TAG, " " 9271 + (p.info.nonLocalizedLabel != null 9272 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9273 Log.v(TAG, " Class=" + p.info.name); 9274 } 9275 final int NI = p.intents.size(); 9276 int j; 9277 for (j = 0; j < NI; j++) { 9278 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9279 if (DEBUG_SHOW_INFO) { 9280 Log.v(TAG, " IntentFilter:"); 9281 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9282 } 9283 if (!intent.debugCheck()) { 9284 Log.w(TAG, "==> For Provider " + p.info.name); 9285 } 9286 addFilter(intent); 9287 } 9288 } 9289 9290 public final void removeProvider(PackageParser.Provider p) { 9291 mProviders.remove(p.getComponentName()); 9292 if (DEBUG_SHOW_INFO) { 9293 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9294 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9295 Log.v(TAG, " Class=" + p.info.name); 9296 } 9297 final int NI = p.intents.size(); 9298 int j; 9299 for (j = 0; j < NI; j++) { 9300 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9301 if (DEBUG_SHOW_INFO) { 9302 Log.v(TAG, " IntentFilter:"); 9303 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9304 } 9305 removeFilter(intent); 9306 } 9307 } 9308 9309 @Override 9310 protected boolean allowFilterResult( 9311 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9312 ProviderInfo filterPi = filter.provider.info; 9313 for (int i = dest.size() - 1; i >= 0; i--) { 9314 ProviderInfo destPi = dest.get(i).providerInfo; 9315 if (destPi.name == filterPi.name 9316 && destPi.packageName == filterPi.packageName) { 9317 return false; 9318 } 9319 } 9320 return true; 9321 } 9322 9323 @Override 9324 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9325 return new PackageParser.ProviderIntentInfo[size]; 9326 } 9327 9328 @Override 9329 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9330 if (!sUserManager.exists(userId)) 9331 return true; 9332 PackageParser.Package p = filter.provider.owner; 9333 if (p != null) { 9334 PackageSetting ps = (PackageSetting) p.mExtras; 9335 if (ps != null) { 9336 // System apps are never considered stopped for purposes of 9337 // filtering, because there may be no way for the user to 9338 // actually re-launch them. 9339 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9340 && ps.getStopped(userId); 9341 } 9342 } 9343 return false; 9344 } 9345 9346 @Override 9347 protected boolean isPackageForFilter(String packageName, 9348 PackageParser.ProviderIntentInfo info) { 9349 return packageName.equals(info.provider.owner.packageName); 9350 } 9351 9352 @Override 9353 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9354 int match, int userId) { 9355 if (!sUserManager.exists(userId)) 9356 return null; 9357 final PackageParser.ProviderIntentInfo info = filter; 9358 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9359 return null; 9360 } 9361 final PackageParser.Provider provider = info.provider; 9362 if (mSafeMode && (provider.info.applicationInfo.flags 9363 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9364 return null; 9365 } 9366 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9367 if (ps == null) { 9368 return null; 9369 } 9370 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9371 ps.readUserState(userId), userId); 9372 if (pi == null) { 9373 return null; 9374 } 9375 final ResolveInfo res = new ResolveInfo(); 9376 res.providerInfo = pi; 9377 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9378 res.filter = filter; 9379 } 9380 res.priority = info.getPriority(); 9381 res.preferredOrder = provider.owner.mPreferredOrder; 9382 res.match = match; 9383 res.isDefault = info.hasDefault; 9384 res.labelRes = info.labelRes; 9385 res.nonLocalizedLabel = info.nonLocalizedLabel; 9386 res.icon = info.icon; 9387 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9388 return res; 9389 } 9390 9391 @Override 9392 protected void sortResults(List<ResolveInfo> results) { 9393 Collections.sort(results, mResolvePrioritySorter); 9394 } 9395 9396 @Override 9397 protected void dumpFilter(PrintWriter out, String prefix, 9398 PackageParser.ProviderIntentInfo filter) { 9399 out.print(prefix); 9400 out.print( 9401 Integer.toHexString(System.identityHashCode(filter.provider))); 9402 out.print(' '); 9403 filter.provider.printComponentShortName(out); 9404 out.print(" filter "); 9405 out.println(Integer.toHexString(System.identityHashCode(filter))); 9406 } 9407 9408 @Override 9409 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9410 return filter.provider; 9411 } 9412 9413 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9414 PackageParser.Provider provider = (PackageParser.Provider)label; 9415 out.print(prefix); out.print( 9416 Integer.toHexString(System.identityHashCode(provider))); 9417 out.print(' '); 9418 provider.printComponentShortName(out); 9419 if (count > 1) { 9420 out.print(" ("); out.print(count); out.print(" filters)"); 9421 } 9422 out.println(); 9423 } 9424 9425 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9426 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9427 private int mFlags; 9428 }; 9429 9430 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9431 new Comparator<ResolveInfo>() { 9432 public int compare(ResolveInfo r1, ResolveInfo r2) { 9433 int v1 = r1.priority; 9434 int v2 = r2.priority; 9435 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9436 if (v1 != v2) { 9437 return (v1 > v2) ? -1 : 1; 9438 } 9439 v1 = r1.preferredOrder; 9440 v2 = r2.preferredOrder; 9441 if (v1 != v2) { 9442 return (v1 > v2) ? -1 : 1; 9443 } 9444 if (r1.isDefault != r2.isDefault) { 9445 return r1.isDefault ? -1 : 1; 9446 } 9447 v1 = r1.match; 9448 v2 = r2.match; 9449 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9450 if (v1 != v2) { 9451 return (v1 > v2) ? -1 : 1; 9452 } 9453 if (r1.system != r2.system) { 9454 return r1.system ? -1 : 1; 9455 } 9456 return 0; 9457 } 9458 }; 9459 9460 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9461 new Comparator<ProviderInfo>() { 9462 public int compare(ProviderInfo p1, ProviderInfo p2) { 9463 final int v1 = p1.initOrder; 9464 final int v2 = p2.initOrder; 9465 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9466 } 9467 }; 9468 9469 final void sendPackageBroadcast(final String action, final String pkg, 9470 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9471 final int[] userIds) { 9472 mHandler.post(new Runnable() { 9473 @Override 9474 public void run() { 9475 try { 9476 final IActivityManager am = ActivityManagerNative.getDefault(); 9477 if (am == null) return; 9478 final int[] resolvedUserIds; 9479 if (userIds == null) { 9480 resolvedUserIds = am.getRunningUserIds(); 9481 } else { 9482 resolvedUserIds = userIds; 9483 } 9484 for (int id : resolvedUserIds) { 9485 final Intent intent = new Intent(action, 9486 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9487 if (extras != null) { 9488 intent.putExtras(extras); 9489 } 9490 if (targetPkg != null) { 9491 intent.setPackage(targetPkg); 9492 } 9493 // Modify the UID when posting to other users 9494 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9495 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9496 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9497 intent.putExtra(Intent.EXTRA_UID, uid); 9498 } 9499 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9500 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9501 if (DEBUG_BROADCASTS) { 9502 RuntimeException here = new RuntimeException("here"); 9503 here.fillInStackTrace(); 9504 Slog.d(TAG, "Sending to user " + id + ": " 9505 + intent.toShortString(false, true, false, false) 9506 + " " + intent.getExtras(), here); 9507 } 9508 am.broadcastIntent(null, intent, null, finishedReceiver, 9509 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9510 null, finishedReceiver != null, false, id); 9511 } 9512 } catch (RemoteException ex) { 9513 } 9514 } 9515 }); 9516 } 9517 9518 /** 9519 * Check if the external storage media is available. This is true if there 9520 * is a mounted external storage medium or if the external storage is 9521 * emulated. 9522 */ 9523 private boolean isExternalMediaAvailable() { 9524 return mMediaMounted || Environment.isExternalStorageEmulated(); 9525 } 9526 9527 @Override 9528 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9529 // writer 9530 synchronized (mPackages) { 9531 if (!isExternalMediaAvailable()) { 9532 // If the external storage is no longer mounted at this point, 9533 // the caller may not have been able to delete all of this 9534 // packages files and can not delete any more. Bail. 9535 return null; 9536 } 9537 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9538 if (lastPackage != null) { 9539 pkgs.remove(lastPackage); 9540 } 9541 if (pkgs.size() > 0) { 9542 return pkgs.get(0); 9543 } 9544 } 9545 return null; 9546 } 9547 9548 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9549 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9550 userId, andCode ? 1 : 0, packageName); 9551 if (mSystemReady) { 9552 msg.sendToTarget(); 9553 } else { 9554 if (mPostSystemReadyMessages == null) { 9555 mPostSystemReadyMessages = new ArrayList<>(); 9556 } 9557 mPostSystemReadyMessages.add(msg); 9558 } 9559 } 9560 9561 void startCleaningPackages() { 9562 // reader 9563 synchronized (mPackages) { 9564 if (!isExternalMediaAvailable()) { 9565 return; 9566 } 9567 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9568 return; 9569 } 9570 } 9571 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9572 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9573 IActivityManager am = ActivityManagerNative.getDefault(); 9574 if (am != null) { 9575 try { 9576 am.startService(null, intent, null, mContext.getOpPackageName(), 9577 UserHandle.USER_OWNER); 9578 } catch (RemoteException e) { 9579 } 9580 } 9581 } 9582 9583 @Override 9584 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9585 int installFlags, String installerPackageName, VerificationParams verificationParams, 9586 String packageAbiOverride) { 9587 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9588 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9589 } 9590 9591 @Override 9592 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9593 int installFlags, String installerPackageName, VerificationParams verificationParams, 9594 String packageAbiOverride, int userId) { 9595 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9596 9597 final int callingUid = Binder.getCallingUid(); 9598 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9599 9600 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9601 try { 9602 if (observer != null) { 9603 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9604 } 9605 } catch (RemoteException re) { 9606 } 9607 return; 9608 } 9609 9610 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9611 installFlags |= PackageManager.INSTALL_FROM_ADB; 9612 9613 } else { 9614 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9615 // about installerPackageName. 9616 9617 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9618 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9619 } 9620 9621 UserHandle user; 9622 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9623 user = UserHandle.ALL; 9624 } else { 9625 user = new UserHandle(userId); 9626 } 9627 9628 // Only system components can circumvent runtime permissions when installing. 9629 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9630 && mContext.checkCallingOrSelfPermission(Manifest.permission 9631 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9632 throw new SecurityException("You need the " 9633 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9634 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9635 } 9636 9637 verificationParams.setInstallerUid(callingUid); 9638 9639 final File originFile = new File(originPath); 9640 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9641 9642 final Message msg = mHandler.obtainMessage(INIT_COPY); 9643 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9644 null, verificationParams, user, packageAbiOverride, null); 9645 mHandler.sendMessage(msg); 9646 } 9647 9648 void installStage(String packageName, File stagedDir, String stagedCid, 9649 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9650 String installerPackageName, int installerUid, UserHandle user) { 9651 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9652 params.referrerUri, installerUid, null); 9653 verifParams.setInstallerUid(installerUid); 9654 9655 final OriginInfo origin; 9656 if (stagedDir != null) { 9657 origin = OriginInfo.fromStagedFile(stagedDir); 9658 } else { 9659 origin = OriginInfo.fromStagedContainer(stagedCid); 9660 } 9661 9662 final Message msg = mHandler.obtainMessage(INIT_COPY); 9663 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9664 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9665 params.grantedRuntimePermissions); 9666 9667 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9668 System.identityHashCode(msg.obj)); 9669 9670 mHandler.sendMessage(msg); 9671 } 9672 9673 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9674 Bundle extras = new Bundle(1); 9675 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9676 9677 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9678 packageName, extras, null, null, new int[] {userId}); 9679 try { 9680 IActivityManager am = ActivityManagerNative.getDefault(); 9681 final boolean isSystem = 9682 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9683 if (isSystem && am.isUserRunning(userId, false)) { 9684 // The just-installed/enabled app is bundled on the system, so presumed 9685 // to be able to run automatically without needing an explicit launch. 9686 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9687 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9688 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9689 .setPackage(packageName); 9690 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9691 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9692 } 9693 } catch (RemoteException e) { 9694 // shouldn't happen 9695 Slog.w(TAG, "Unable to bootstrap installed package", e); 9696 } 9697 } 9698 9699 @Override 9700 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9701 int userId) { 9702 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9703 PackageSetting pkgSetting; 9704 final int uid = Binder.getCallingUid(); 9705 enforceCrossUserPermission(uid, userId, true, true, 9706 "setApplicationHiddenSetting for user " + userId); 9707 9708 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9709 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9710 return false; 9711 } 9712 9713 long callingId = Binder.clearCallingIdentity(); 9714 try { 9715 boolean sendAdded = false; 9716 boolean sendRemoved = false; 9717 // writer 9718 synchronized (mPackages) { 9719 pkgSetting = mSettings.mPackages.get(packageName); 9720 if (pkgSetting == null) { 9721 return false; 9722 } 9723 if (pkgSetting.getHidden(userId) != hidden) { 9724 pkgSetting.setHidden(hidden, userId); 9725 mSettings.writePackageRestrictionsLPr(userId); 9726 if (hidden) { 9727 sendRemoved = true; 9728 } else { 9729 sendAdded = true; 9730 } 9731 } 9732 } 9733 if (sendAdded) { 9734 sendPackageAddedForUser(packageName, pkgSetting, userId); 9735 return true; 9736 } 9737 if (sendRemoved) { 9738 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9739 "hiding pkg"); 9740 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9741 return true; 9742 } 9743 } finally { 9744 Binder.restoreCallingIdentity(callingId); 9745 } 9746 return false; 9747 } 9748 9749 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9750 int userId) { 9751 final PackageRemovedInfo info = new PackageRemovedInfo(); 9752 info.removedPackage = packageName; 9753 info.removedUsers = new int[] {userId}; 9754 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9755 info.sendBroadcast(false, false, false); 9756 } 9757 9758 /** 9759 * Returns true if application is not found or there was an error. Otherwise it returns 9760 * the hidden state of the package for the given user. 9761 */ 9762 @Override 9763 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9765 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9766 false, "getApplicationHidden for user " + userId); 9767 PackageSetting pkgSetting; 9768 long callingId = Binder.clearCallingIdentity(); 9769 try { 9770 // writer 9771 synchronized (mPackages) { 9772 pkgSetting = mSettings.mPackages.get(packageName); 9773 if (pkgSetting == null) { 9774 return true; 9775 } 9776 return pkgSetting.getHidden(userId); 9777 } 9778 } finally { 9779 Binder.restoreCallingIdentity(callingId); 9780 } 9781 } 9782 9783 /** 9784 * @hide 9785 */ 9786 @Override 9787 public int installExistingPackageAsUser(String packageName, int userId) { 9788 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9789 null); 9790 PackageSetting pkgSetting; 9791 final int uid = Binder.getCallingUid(); 9792 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9793 + userId); 9794 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9795 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9796 } 9797 9798 long callingId = Binder.clearCallingIdentity(); 9799 try { 9800 boolean sendAdded = false; 9801 9802 // writer 9803 synchronized (mPackages) { 9804 pkgSetting = mSettings.mPackages.get(packageName); 9805 if (pkgSetting == null) { 9806 return PackageManager.INSTALL_FAILED_INVALID_URI; 9807 } 9808 if (!pkgSetting.getInstalled(userId)) { 9809 pkgSetting.setInstalled(true, userId); 9810 pkgSetting.setHidden(false, userId); 9811 mSettings.writePackageRestrictionsLPr(userId); 9812 sendAdded = true; 9813 } 9814 } 9815 9816 if (sendAdded) { 9817 sendPackageAddedForUser(packageName, pkgSetting, userId); 9818 } 9819 } finally { 9820 Binder.restoreCallingIdentity(callingId); 9821 } 9822 9823 return PackageManager.INSTALL_SUCCEEDED; 9824 } 9825 9826 boolean isUserRestricted(int userId, String restrictionKey) { 9827 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9828 if (restrictions.getBoolean(restrictionKey, false)) { 9829 Log.w(TAG, "User is restricted: " + restrictionKey); 9830 return true; 9831 } 9832 return false; 9833 } 9834 9835 @Override 9836 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9837 mContext.enforceCallingOrSelfPermission( 9838 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9839 "Only package verification agents can verify applications"); 9840 9841 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9842 final PackageVerificationResponse response = new PackageVerificationResponse( 9843 verificationCode, Binder.getCallingUid()); 9844 msg.arg1 = id; 9845 msg.obj = response; 9846 mHandler.sendMessage(msg); 9847 } 9848 9849 @Override 9850 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9851 long millisecondsToDelay) { 9852 mContext.enforceCallingOrSelfPermission( 9853 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9854 "Only package verification agents can extend verification timeouts"); 9855 9856 final PackageVerificationState state = mPendingVerification.get(id); 9857 final PackageVerificationResponse response = new PackageVerificationResponse( 9858 verificationCodeAtTimeout, Binder.getCallingUid()); 9859 9860 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9861 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9862 } 9863 if (millisecondsToDelay < 0) { 9864 millisecondsToDelay = 0; 9865 } 9866 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9867 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9868 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9869 } 9870 9871 if ((state != null) && !state.timeoutExtended()) { 9872 state.extendTimeout(); 9873 9874 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9875 msg.arg1 = id; 9876 msg.obj = response; 9877 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9878 } 9879 } 9880 9881 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9882 int verificationCode, UserHandle user) { 9883 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9884 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9885 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9886 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9887 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9888 9889 mContext.sendBroadcastAsUser(intent, user, 9890 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9891 } 9892 9893 private ComponentName matchComponentForVerifier(String packageName, 9894 List<ResolveInfo> receivers) { 9895 ActivityInfo targetReceiver = null; 9896 9897 final int NR = receivers.size(); 9898 for (int i = 0; i < NR; i++) { 9899 final ResolveInfo info = receivers.get(i); 9900 if (info.activityInfo == null) { 9901 continue; 9902 } 9903 9904 if (packageName.equals(info.activityInfo.packageName)) { 9905 targetReceiver = info.activityInfo; 9906 break; 9907 } 9908 } 9909 9910 if (targetReceiver == null) { 9911 return null; 9912 } 9913 9914 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9915 } 9916 9917 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9918 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9919 if (pkgInfo.verifiers.length == 0) { 9920 return null; 9921 } 9922 9923 final int N = pkgInfo.verifiers.length; 9924 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9925 for (int i = 0; i < N; i++) { 9926 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9927 9928 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9929 receivers); 9930 if (comp == null) { 9931 continue; 9932 } 9933 9934 final int verifierUid = getUidForVerifier(verifierInfo); 9935 if (verifierUid == -1) { 9936 continue; 9937 } 9938 9939 if (DEBUG_VERIFY) { 9940 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9941 + " with the correct signature"); 9942 } 9943 sufficientVerifiers.add(comp); 9944 verificationState.addSufficientVerifier(verifierUid); 9945 } 9946 9947 return sufficientVerifiers; 9948 } 9949 9950 private int getUidForVerifier(VerifierInfo verifierInfo) { 9951 synchronized (mPackages) { 9952 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9953 if (pkg == null) { 9954 return -1; 9955 } else if (pkg.mSignatures.length != 1) { 9956 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9957 + " has more than one signature; ignoring"); 9958 return -1; 9959 } 9960 9961 /* 9962 * If the public key of the package's signature does not match 9963 * our expected public key, then this is a different package and 9964 * we should skip. 9965 */ 9966 9967 final byte[] expectedPublicKey; 9968 try { 9969 final Signature verifierSig = pkg.mSignatures[0]; 9970 final PublicKey publicKey = verifierSig.getPublicKey(); 9971 expectedPublicKey = publicKey.getEncoded(); 9972 } catch (CertificateException e) { 9973 return -1; 9974 } 9975 9976 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9977 9978 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9979 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9980 + " does not have the expected public key; ignoring"); 9981 return -1; 9982 } 9983 9984 return pkg.applicationInfo.uid; 9985 } 9986 } 9987 9988 @Override 9989 public void finishPackageInstall(int token) { 9990 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9991 9992 if (DEBUG_INSTALL) { 9993 Slog.v(TAG, "BM finishing package install for " + token); 9994 } 9995 9996 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9997 mHandler.sendMessage(msg); 9998 } 9999 10000 /** 10001 * Get the verification agent timeout. 10002 * 10003 * @return verification timeout in milliseconds 10004 */ 10005 private long getVerificationTimeout() { 10006 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10007 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10008 DEFAULT_VERIFICATION_TIMEOUT); 10009 } 10010 10011 /** 10012 * Get the default verification agent response code. 10013 * 10014 * @return default verification response code 10015 */ 10016 private int getDefaultVerificationResponse() { 10017 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10018 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10019 DEFAULT_VERIFICATION_RESPONSE); 10020 } 10021 10022 /** 10023 * Check whether or not package verification has been enabled. 10024 * 10025 * @return true if verification should be performed 10026 */ 10027 private boolean isVerificationEnabled(int userId, int installFlags) { 10028 if (!DEFAULT_VERIFY_ENABLE) { 10029 return false; 10030 } 10031 10032 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10033 10034 // Check if installing from ADB 10035 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10036 // Do not run verification in a test harness environment 10037 if (ActivityManager.isRunningInTestHarness()) { 10038 return false; 10039 } 10040 if (ensureVerifyAppsEnabled) { 10041 return true; 10042 } 10043 // Check if the developer does not want package verification for ADB installs 10044 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10045 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10046 return false; 10047 } 10048 } 10049 10050 if (ensureVerifyAppsEnabled) { 10051 return true; 10052 } 10053 10054 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10055 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10056 } 10057 10058 @Override 10059 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10060 throws RemoteException { 10061 mContext.enforceCallingOrSelfPermission( 10062 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10063 "Only intentfilter verification agents can verify applications"); 10064 10065 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10066 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10067 Binder.getCallingUid(), verificationCode, failedDomains); 10068 msg.arg1 = id; 10069 msg.obj = response; 10070 mHandler.sendMessage(msg); 10071 } 10072 10073 @Override 10074 public int getIntentVerificationStatus(String packageName, int userId) { 10075 synchronized (mPackages) { 10076 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10077 } 10078 } 10079 10080 @Override 10081 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10082 mContext.enforceCallingOrSelfPermission( 10083 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10084 10085 boolean result = false; 10086 synchronized (mPackages) { 10087 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10088 } 10089 if (result) { 10090 scheduleWritePackageRestrictionsLocked(userId); 10091 } 10092 return result; 10093 } 10094 10095 @Override 10096 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10097 synchronized (mPackages) { 10098 return mSettings.getIntentFilterVerificationsLPr(packageName); 10099 } 10100 } 10101 10102 @Override 10103 public List<IntentFilter> getAllIntentFilters(String packageName) { 10104 if (TextUtils.isEmpty(packageName)) { 10105 return Collections.<IntentFilter>emptyList(); 10106 } 10107 synchronized (mPackages) { 10108 PackageParser.Package pkg = mPackages.get(packageName); 10109 if (pkg == null || pkg.activities == null) { 10110 return Collections.<IntentFilter>emptyList(); 10111 } 10112 final int count = pkg.activities.size(); 10113 ArrayList<IntentFilter> result = new ArrayList<>(); 10114 for (int n=0; n<count; n++) { 10115 PackageParser.Activity activity = pkg.activities.get(n); 10116 if (activity.intents != null || activity.intents.size() > 0) { 10117 result.addAll(activity.intents); 10118 } 10119 } 10120 return result; 10121 } 10122 } 10123 10124 @Override 10125 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10126 mContext.enforceCallingOrSelfPermission( 10127 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10128 10129 synchronized (mPackages) { 10130 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10131 if (packageName != null) { 10132 result |= updateIntentVerificationStatus(packageName, 10133 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10134 userId); 10135 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10136 packageName, userId); 10137 } 10138 return result; 10139 } 10140 } 10141 10142 @Override 10143 public String getDefaultBrowserPackageName(int userId) { 10144 synchronized (mPackages) { 10145 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10146 } 10147 } 10148 10149 /** 10150 * Get the "allow unknown sources" setting. 10151 * 10152 * @return the current "allow unknown sources" setting 10153 */ 10154 private int getUnknownSourcesSettings() { 10155 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10156 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10157 -1); 10158 } 10159 10160 @Override 10161 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10162 final int uid = Binder.getCallingUid(); 10163 // writer 10164 synchronized (mPackages) { 10165 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10166 if (targetPackageSetting == null) { 10167 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10168 } 10169 10170 PackageSetting installerPackageSetting; 10171 if (installerPackageName != null) { 10172 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10173 if (installerPackageSetting == null) { 10174 throw new IllegalArgumentException("Unknown installer package: " 10175 + installerPackageName); 10176 } 10177 } else { 10178 installerPackageSetting = null; 10179 } 10180 10181 Signature[] callerSignature; 10182 Object obj = mSettings.getUserIdLPr(uid); 10183 if (obj != null) { 10184 if (obj instanceof SharedUserSetting) { 10185 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10186 } else if (obj instanceof PackageSetting) { 10187 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10188 } else { 10189 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10190 } 10191 } else { 10192 throw new SecurityException("Unknown calling uid " + uid); 10193 } 10194 10195 // Verify: can't set installerPackageName to a package that is 10196 // not signed with the same cert as the caller. 10197 if (installerPackageSetting != null) { 10198 if (compareSignatures(callerSignature, 10199 installerPackageSetting.signatures.mSignatures) 10200 != PackageManager.SIGNATURE_MATCH) { 10201 throw new SecurityException( 10202 "Caller does not have same cert as new installer package " 10203 + installerPackageName); 10204 } 10205 } 10206 10207 // Verify: if target already has an installer package, it must 10208 // be signed with the same cert as the caller. 10209 if (targetPackageSetting.installerPackageName != null) { 10210 PackageSetting setting = mSettings.mPackages.get( 10211 targetPackageSetting.installerPackageName); 10212 // If the currently set package isn't valid, then it's always 10213 // okay to change it. 10214 if (setting != null) { 10215 if (compareSignatures(callerSignature, 10216 setting.signatures.mSignatures) 10217 != PackageManager.SIGNATURE_MATCH) { 10218 throw new SecurityException( 10219 "Caller does not have same cert as old installer package " 10220 + targetPackageSetting.installerPackageName); 10221 } 10222 } 10223 } 10224 10225 // Okay! 10226 targetPackageSetting.installerPackageName = installerPackageName; 10227 scheduleWriteSettingsLocked(); 10228 } 10229 } 10230 10231 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10232 // Queue up an async operation since the package installation may take a little while. 10233 mHandler.post(new Runnable() { 10234 public void run() { 10235 mHandler.removeCallbacks(this); 10236 // Result object to be returned 10237 PackageInstalledInfo res = new PackageInstalledInfo(); 10238 res.returnCode = currentStatus; 10239 res.uid = -1; 10240 res.pkg = null; 10241 res.removedInfo = new PackageRemovedInfo(); 10242 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10243 args.doPreInstall(res.returnCode); 10244 synchronized (mInstallLock) { 10245 installPackageTracedLI(args, res); 10246 } 10247 args.doPostInstall(res.returnCode, res.uid); 10248 } 10249 10250 // A restore should be performed at this point if (a) the install 10251 // succeeded, (b) the operation is not an update, and (c) the new 10252 // package has not opted out of backup participation. 10253 final boolean update = res.removedInfo.removedPackage != null; 10254 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10255 boolean doRestore = !update 10256 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10257 10258 // Set up the post-install work request bookkeeping. This will be used 10259 // and cleaned up by the post-install event handling regardless of whether 10260 // there's a restore pass performed. Token values are >= 1. 10261 int token; 10262 if (mNextInstallToken < 0) mNextInstallToken = 1; 10263 token = mNextInstallToken++; 10264 10265 PostInstallData data = new PostInstallData(args, res); 10266 mRunningInstalls.put(token, data); 10267 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10268 10269 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10270 // Pass responsibility to the Backup Manager. It will perform a 10271 // restore if appropriate, then pass responsibility back to the 10272 // Package Manager to run the post-install observer callbacks 10273 // and broadcasts. 10274 IBackupManager bm = IBackupManager.Stub.asInterface( 10275 ServiceManager.getService(Context.BACKUP_SERVICE)); 10276 if (bm != null) { 10277 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10278 + " to BM for possible restore"); 10279 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10280 try { 10281 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10282 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10283 } else { 10284 doRestore = false; 10285 } 10286 } catch (RemoteException e) { 10287 // can't happen; the backup manager is local 10288 } catch (Exception e) { 10289 Slog.e(TAG, "Exception trying to enqueue restore", e); 10290 doRestore = false; 10291 } finally { 10292 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10293 } 10294 } else { 10295 Slog.e(TAG, "Backup Manager not found!"); 10296 doRestore = false; 10297 } 10298 } 10299 10300 if (!doRestore) { 10301 // No restore possible, or the Backup Manager was mysteriously not 10302 // available -- just fire the post-install work request directly. 10303 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10304 10305 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10306 10307 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10308 mHandler.sendMessage(msg); 10309 } 10310 } 10311 }); 10312 } 10313 10314 private abstract class HandlerParams { 10315 private static final int MAX_RETRIES = 4; 10316 10317 /** 10318 * Number of times startCopy() has been attempted and had a non-fatal 10319 * error. 10320 */ 10321 private int mRetries = 0; 10322 10323 /** User handle for the user requesting the information or installation. */ 10324 private final UserHandle mUser; 10325 10326 HandlerParams(UserHandle user) { 10327 mUser = user; 10328 } 10329 10330 UserHandle getUser() { 10331 return mUser; 10332 } 10333 10334 final boolean startCopy() { 10335 boolean res; 10336 try { 10337 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10338 10339 if (++mRetries > MAX_RETRIES) { 10340 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10341 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10342 handleServiceError(); 10343 return false; 10344 } else { 10345 handleStartCopy(); 10346 res = true; 10347 } 10348 } catch (RemoteException e) { 10349 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10350 mHandler.sendEmptyMessage(MCS_RECONNECT); 10351 res = false; 10352 } 10353 handleReturnCode(); 10354 return res; 10355 } 10356 10357 final void serviceError() { 10358 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10359 handleServiceError(); 10360 handleReturnCode(); 10361 } 10362 10363 abstract void handleStartCopy() throws RemoteException; 10364 abstract void handleServiceError(); 10365 abstract void handleReturnCode(); 10366 } 10367 10368 class MeasureParams extends HandlerParams { 10369 private final PackageStats mStats; 10370 private boolean mSuccess; 10371 10372 private final IPackageStatsObserver mObserver; 10373 10374 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10375 super(new UserHandle(stats.userHandle)); 10376 mObserver = observer; 10377 mStats = stats; 10378 } 10379 10380 @Override 10381 public String toString() { 10382 return "MeasureParams{" 10383 + Integer.toHexString(System.identityHashCode(this)) 10384 + " " + mStats.packageName + "}"; 10385 } 10386 10387 @Override 10388 void handleStartCopy() throws RemoteException { 10389 synchronized (mInstallLock) { 10390 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10391 } 10392 10393 if (mSuccess) { 10394 final boolean mounted; 10395 if (Environment.isExternalStorageEmulated()) { 10396 mounted = true; 10397 } else { 10398 final String status = Environment.getExternalStorageState(); 10399 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10400 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10401 } 10402 10403 if (mounted) { 10404 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10405 10406 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10407 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10408 10409 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10410 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10411 10412 // Always subtract cache size, since it's a subdirectory 10413 mStats.externalDataSize -= mStats.externalCacheSize; 10414 10415 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10416 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10417 10418 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10419 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10420 } 10421 } 10422 } 10423 10424 @Override 10425 void handleReturnCode() { 10426 if (mObserver != null) { 10427 try { 10428 mObserver.onGetStatsCompleted(mStats, mSuccess); 10429 } catch (RemoteException e) { 10430 Slog.i(TAG, "Observer no longer exists."); 10431 } 10432 } 10433 } 10434 10435 @Override 10436 void handleServiceError() { 10437 Slog.e(TAG, "Could not measure application " + mStats.packageName 10438 + " external storage"); 10439 } 10440 } 10441 10442 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10443 throws RemoteException { 10444 long result = 0; 10445 for (File path : paths) { 10446 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10447 } 10448 return result; 10449 } 10450 10451 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10452 for (File path : paths) { 10453 try { 10454 mcs.clearDirectory(path.getAbsolutePath()); 10455 } catch (RemoteException e) { 10456 } 10457 } 10458 } 10459 10460 static class OriginInfo { 10461 /** 10462 * Location where install is coming from, before it has been 10463 * copied/renamed into place. This could be a single monolithic APK 10464 * file, or a cluster directory. This location may be untrusted. 10465 */ 10466 final File file; 10467 final String cid; 10468 10469 /** 10470 * Flag indicating that {@link #file} or {@link #cid} has already been 10471 * staged, meaning downstream users don't need to defensively copy the 10472 * contents. 10473 */ 10474 final boolean staged; 10475 10476 /** 10477 * Flag indicating that {@link #file} or {@link #cid} is an already 10478 * installed app that is being moved. 10479 */ 10480 final boolean existing; 10481 10482 final String resolvedPath; 10483 final File resolvedFile; 10484 10485 static OriginInfo fromNothing() { 10486 return new OriginInfo(null, null, false, false); 10487 } 10488 10489 static OriginInfo fromUntrustedFile(File file) { 10490 return new OriginInfo(file, null, false, false); 10491 } 10492 10493 static OriginInfo fromExistingFile(File file) { 10494 return new OriginInfo(file, null, false, true); 10495 } 10496 10497 static OriginInfo fromStagedFile(File file) { 10498 return new OriginInfo(file, null, true, false); 10499 } 10500 10501 static OriginInfo fromStagedContainer(String cid) { 10502 return new OriginInfo(null, cid, true, false); 10503 } 10504 10505 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10506 this.file = file; 10507 this.cid = cid; 10508 this.staged = staged; 10509 this.existing = existing; 10510 10511 if (cid != null) { 10512 resolvedPath = PackageHelper.getSdDir(cid); 10513 resolvedFile = new File(resolvedPath); 10514 } else if (file != null) { 10515 resolvedPath = file.getAbsolutePath(); 10516 resolvedFile = file; 10517 } else { 10518 resolvedPath = null; 10519 resolvedFile = null; 10520 } 10521 } 10522 } 10523 10524 class MoveInfo { 10525 final int moveId; 10526 final String fromUuid; 10527 final String toUuid; 10528 final String packageName; 10529 final String dataAppName; 10530 final int appId; 10531 final String seinfo; 10532 10533 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10534 String dataAppName, int appId, String seinfo) { 10535 this.moveId = moveId; 10536 this.fromUuid = fromUuid; 10537 this.toUuid = toUuid; 10538 this.packageName = packageName; 10539 this.dataAppName = dataAppName; 10540 this.appId = appId; 10541 this.seinfo = seinfo; 10542 } 10543 } 10544 10545 class InstallParams extends HandlerParams { 10546 final OriginInfo origin; 10547 final MoveInfo move; 10548 final IPackageInstallObserver2 observer; 10549 int installFlags; 10550 final String installerPackageName; 10551 final String volumeUuid; 10552 final VerificationParams verificationParams; 10553 private InstallArgs mArgs; 10554 private int mRet; 10555 final String packageAbiOverride; 10556 final String[] grantedRuntimePermissions; 10557 10558 10559 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10560 int installFlags, String installerPackageName, String volumeUuid, 10561 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10562 String[] grantedPermissions) { 10563 super(user); 10564 this.origin = origin; 10565 this.move = move; 10566 this.observer = observer; 10567 this.installFlags = installFlags; 10568 this.installerPackageName = installerPackageName; 10569 this.volumeUuid = volumeUuid; 10570 this.verificationParams = verificationParams; 10571 this.packageAbiOverride = packageAbiOverride; 10572 this.grantedRuntimePermissions = grantedPermissions; 10573 } 10574 10575 @Override 10576 public String toString() { 10577 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10578 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10579 } 10580 10581 public ManifestDigest getManifestDigest() { 10582 if (verificationParams == null) { 10583 return null; 10584 } 10585 return verificationParams.getManifestDigest(); 10586 } 10587 10588 private int installLocationPolicy(PackageInfoLite pkgLite) { 10589 String packageName = pkgLite.packageName; 10590 int installLocation = pkgLite.installLocation; 10591 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10592 // reader 10593 synchronized (mPackages) { 10594 PackageParser.Package pkg = mPackages.get(packageName); 10595 if (pkg != null) { 10596 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10597 // Check for downgrading. 10598 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10599 try { 10600 checkDowngrade(pkg, pkgLite); 10601 } catch (PackageManagerException e) { 10602 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10603 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10604 } 10605 } 10606 // Check for updated system application. 10607 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10608 if (onSd) { 10609 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10610 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10611 } 10612 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10613 } else { 10614 if (onSd) { 10615 // Install flag overrides everything. 10616 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10617 } 10618 // If current upgrade specifies particular preference 10619 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10620 // Application explicitly specified internal. 10621 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10622 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10623 // App explictly prefers external. Let policy decide 10624 } else { 10625 // Prefer previous location 10626 if (isExternal(pkg)) { 10627 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10628 } 10629 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10630 } 10631 } 10632 } else { 10633 // Invalid install. Return error code 10634 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10635 } 10636 } 10637 } 10638 // All the special cases have been taken care of. 10639 // Return result based on recommended install location. 10640 if (onSd) { 10641 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10642 } 10643 return pkgLite.recommendedInstallLocation; 10644 } 10645 10646 /* 10647 * Invoke remote method to get package information and install 10648 * location values. Override install location based on default 10649 * policy if needed and then create install arguments based 10650 * on the install location. 10651 */ 10652 public void handleStartCopy() throws RemoteException { 10653 int ret = PackageManager.INSTALL_SUCCEEDED; 10654 10655 // If we're already staged, we've firmly committed to an install location 10656 if (origin.staged) { 10657 if (origin.file != null) { 10658 installFlags |= PackageManager.INSTALL_INTERNAL; 10659 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10660 } else if (origin.cid != null) { 10661 installFlags |= PackageManager.INSTALL_EXTERNAL; 10662 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10663 } else { 10664 throw new IllegalStateException("Invalid stage location"); 10665 } 10666 } 10667 10668 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10669 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10670 PackageInfoLite pkgLite = null; 10671 10672 if (onInt && onSd) { 10673 // Check if both bits are set. 10674 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10675 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10676 } else { 10677 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10678 packageAbiOverride); 10679 10680 /* 10681 * If we have too little free space, try to free cache 10682 * before giving up. 10683 */ 10684 if (!origin.staged && pkgLite.recommendedInstallLocation 10685 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10686 // TODO: focus freeing disk space on the target device 10687 final StorageManager storage = StorageManager.from(mContext); 10688 final long lowThreshold = storage.getStorageLowBytes( 10689 Environment.getDataDirectory()); 10690 10691 final long sizeBytes = mContainerService.calculateInstalledSize( 10692 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10693 10694 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10695 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10696 installFlags, packageAbiOverride); 10697 } 10698 10699 /* 10700 * The cache free must have deleted the file we 10701 * downloaded to install. 10702 * 10703 * TODO: fix the "freeCache" call to not delete 10704 * the file we care about. 10705 */ 10706 if (pkgLite.recommendedInstallLocation 10707 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10708 pkgLite.recommendedInstallLocation 10709 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10710 } 10711 } 10712 } 10713 10714 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10715 int loc = pkgLite.recommendedInstallLocation; 10716 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10717 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10718 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10719 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10720 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10721 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10722 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10723 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10724 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10725 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10726 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10727 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10728 } else { 10729 // Override with defaults if needed. 10730 loc = installLocationPolicy(pkgLite); 10731 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10732 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10733 } else if (!onSd && !onInt) { 10734 // Override install location with flags 10735 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10736 // Set the flag to install on external media. 10737 installFlags |= PackageManager.INSTALL_EXTERNAL; 10738 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10739 } else { 10740 // Make sure the flag for installing on external 10741 // media is unset 10742 installFlags |= PackageManager.INSTALL_INTERNAL; 10743 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10744 } 10745 } 10746 } 10747 } 10748 10749 final InstallArgs args = createInstallArgs(this); 10750 mArgs = args; 10751 10752 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10753 /* 10754 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10755 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10756 */ 10757 int userIdentifier = getUser().getIdentifier(); 10758 if (userIdentifier == UserHandle.USER_ALL 10759 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10760 userIdentifier = UserHandle.USER_OWNER; 10761 } 10762 10763 /* 10764 * Determine if we have any installed package verifiers. If we 10765 * do, then we'll defer to them to verify the packages. 10766 */ 10767 final int requiredUid = mRequiredVerifierPackage == null ? -1 10768 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10769 if (!origin.existing && requiredUid != -1 10770 && isVerificationEnabled(userIdentifier, installFlags)) { 10771 final Intent verification = new Intent( 10772 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10773 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10774 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10775 PACKAGE_MIME_TYPE); 10776 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10777 10778 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10779 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10780 0 /* TODO: Which userId? */); 10781 10782 if (DEBUG_VERIFY) { 10783 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10784 + verification.toString() + " with " + pkgLite.verifiers.length 10785 + " optional verifiers"); 10786 } 10787 10788 final int verificationId = mPendingVerificationToken++; 10789 10790 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10791 10792 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10793 installerPackageName); 10794 10795 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10796 installFlags); 10797 10798 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10799 pkgLite.packageName); 10800 10801 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10802 pkgLite.versionCode); 10803 10804 if (verificationParams != null) { 10805 if (verificationParams.getVerificationURI() != null) { 10806 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10807 verificationParams.getVerificationURI()); 10808 } 10809 if (verificationParams.getOriginatingURI() != null) { 10810 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10811 verificationParams.getOriginatingURI()); 10812 } 10813 if (verificationParams.getReferrer() != null) { 10814 verification.putExtra(Intent.EXTRA_REFERRER, 10815 verificationParams.getReferrer()); 10816 } 10817 if (verificationParams.getOriginatingUid() >= 0) { 10818 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10819 verificationParams.getOriginatingUid()); 10820 } 10821 if (verificationParams.getInstallerUid() >= 0) { 10822 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10823 verificationParams.getInstallerUid()); 10824 } 10825 } 10826 10827 final PackageVerificationState verificationState = new PackageVerificationState( 10828 requiredUid, args); 10829 10830 mPendingVerification.append(verificationId, verificationState); 10831 10832 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10833 receivers, verificationState); 10834 10835 // Apps installed for "all" users use the device owner to verify the app 10836 UserHandle verifierUser = getUser(); 10837 if (verifierUser == UserHandle.ALL) { 10838 verifierUser = UserHandle.OWNER; 10839 } 10840 10841 /* 10842 * If any sufficient verifiers were listed in the package 10843 * manifest, attempt to ask them. 10844 */ 10845 if (sufficientVerifiers != null) { 10846 final int N = sufficientVerifiers.size(); 10847 if (N == 0) { 10848 Slog.i(TAG, "Additional verifiers required, but none installed."); 10849 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10850 } else { 10851 for (int i = 0; i < N; i++) { 10852 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10853 10854 final Intent sufficientIntent = new Intent(verification); 10855 sufficientIntent.setComponent(verifierComponent); 10856 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10857 } 10858 } 10859 } 10860 10861 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10862 mRequiredVerifierPackage, receivers); 10863 if (ret == PackageManager.INSTALL_SUCCEEDED 10864 && mRequiredVerifierPackage != null) { 10865 Trace.asyncTraceBegin( 10866 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 10867 /* 10868 * Send the intent to the required verification agent, 10869 * but only start the verification timeout after the 10870 * target BroadcastReceivers have run. 10871 */ 10872 verification.setComponent(requiredVerifierComponent); 10873 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10874 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10875 new BroadcastReceiver() { 10876 @Override 10877 public void onReceive(Context context, Intent intent) { 10878 final Message msg = mHandler 10879 .obtainMessage(CHECK_PENDING_VERIFICATION); 10880 msg.arg1 = verificationId; 10881 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10882 } 10883 }, null, 0, null, null); 10884 10885 /* 10886 * We don't want the copy to proceed until verification 10887 * succeeds, so null out this field. 10888 */ 10889 mArgs = null; 10890 } 10891 } else { 10892 /* 10893 * No package verification is enabled, so immediately start 10894 * the remote call to initiate copy using temporary file. 10895 */ 10896 ret = args.copyApk(mContainerService, true); 10897 } 10898 } 10899 10900 mRet = ret; 10901 } 10902 10903 @Override 10904 void handleReturnCode() { 10905 // If mArgs is null, then MCS couldn't be reached. When it 10906 // reconnects, it will try again to install. At that point, this 10907 // will succeed. 10908 if (mArgs != null) { 10909 processPendingInstall(mArgs, mRet); 10910 } 10911 } 10912 10913 @Override 10914 void handleServiceError() { 10915 mArgs = createInstallArgs(this); 10916 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10917 } 10918 10919 public boolean isForwardLocked() { 10920 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10921 } 10922 } 10923 10924 /** 10925 * Used during creation of InstallArgs 10926 * 10927 * @param installFlags package installation flags 10928 * @return true if should be installed on external storage 10929 */ 10930 private static boolean installOnExternalAsec(int installFlags) { 10931 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10932 return false; 10933 } 10934 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10935 return true; 10936 } 10937 return false; 10938 } 10939 10940 /** 10941 * Used during creation of InstallArgs 10942 * 10943 * @param installFlags package installation flags 10944 * @return true if should be installed as forward locked 10945 */ 10946 private static boolean installForwardLocked(int installFlags) { 10947 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10948 } 10949 10950 private InstallArgs createInstallArgs(InstallParams params) { 10951 if (params.move != null) { 10952 return new MoveInstallArgs(params); 10953 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10954 return new AsecInstallArgs(params); 10955 } else { 10956 return new FileInstallArgs(params); 10957 } 10958 } 10959 10960 /** 10961 * Create args that describe an existing installed package. Typically used 10962 * when cleaning up old installs, or used as a move source. 10963 */ 10964 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10965 String resourcePath, String[] instructionSets) { 10966 final boolean isInAsec; 10967 if (installOnExternalAsec(installFlags)) { 10968 /* Apps on SD card are always in ASEC containers. */ 10969 isInAsec = true; 10970 } else if (installForwardLocked(installFlags) 10971 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10972 /* 10973 * Forward-locked apps are only in ASEC containers if they're the 10974 * new style 10975 */ 10976 isInAsec = true; 10977 } else { 10978 isInAsec = false; 10979 } 10980 10981 if (isInAsec) { 10982 return new AsecInstallArgs(codePath, instructionSets, 10983 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10984 } else { 10985 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10986 } 10987 } 10988 10989 static abstract class InstallArgs { 10990 /** @see InstallParams#origin */ 10991 final OriginInfo origin; 10992 /** @see InstallParams#move */ 10993 final MoveInfo move; 10994 10995 final IPackageInstallObserver2 observer; 10996 // Always refers to PackageManager flags only 10997 final int installFlags; 10998 final String installerPackageName; 10999 final String volumeUuid; 11000 final ManifestDigest manifestDigest; 11001 final UserHandle user; 11002 final String abiOverride; 11003 final String[] installGrantPermissions; 11004 11005 // The list of instruction sets supported by this app. This is currently 11006 // only used during the rmdex() phase to clean up resources. We can get rid of this 11007 // if we move dex files under the common app path. 11008 /* nullable */ String[] instructionSets; 11009 11010 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11011 int installFlags, String installerPackageName, String volumeUuid, 11012 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11013 String abiOverride, String[] installGrantPermissions) { 11014 this.origin = origin; 11015 this.move = move; 11016 this.installFlags = installFlags; 11017 this.observer = observer; 11018 this.installerPackageName = installerPackageName; 11019 this.volumeUuid = volumeUuid; 11020 this.manifestDigest = manifestDigest; 11021 this.user = user; 11022 this.instructionSets = instructionSets; 11023 this.abiOverride = abiOverride; 11024 this.installGrantPermissions = installGrantPermissions; 11025 } 11026 11027 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11028 abstract int doPreInstall(int status); 11029 11030 /** 11031 * Rename package into final resting place. All paths on the given 11032 * scanned package should be updated to reflect the rename. 11033 */ 11034 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11035 abstract int doPostInstall(int status, int uid); 11036 11037 /** @see PackageSettingBase#codePathString */ 11038 abstract String getCodePath(); 11039 /** @see PackageSettingBase#resourcePathString */ 11040 abstract String getResourcePath(); 11041 11042 // Need installer lock especially for dex file removal. 11043 abstract void cleanUpResourcesLI(); 11044 abstract boolean doPostDeleteLI(boolean delete); 11045 11046 /** 11047 * Called before the source arguments are copied. This is used mostly 11048 * for MoveParams when it needs to read the source file to put it in the 11049 * destination. 11050 */ 11051 int doPreCopy() { 11052 return PackageManager.INSTALL_SUCCEEDED; 11053 } 11054 11055 /** 11056 * Called after the source arguments are copied. This is used mostly for 11057 * MoveParams when it needs to read the source file to put it in the 11058 * destination. 11059 * 11060 * @return 11061 */ 11062 int doPostCopy(int uid) { 11063 return PackageManager.INSTALL_SUCCEEDED; 11064 } 11065 11066 protected boolean isFwdLocked() { 11067 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11068 } 11069 11070 protected boolean isExternalAsec() { 11071 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11072 } 11073 11074 UserHandle getUser() { 11075 return user; 11076 } 11077 } 11078 11079 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11080 if (!allCodePaths.isEmpty()) { 11081 if (instructionSets == null) { 11082 throw new IllegalStateException("instructionSet == null"); 11083 } 11084 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11085 for (String codePath : allCodePaths) { 11086 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11087 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11088 if (retCode < 0) { 11089 Slog.w(TAG, "Couldn't remove dex file for package: " 11090 + " at location " + codePath + ", retcode=" + retCode); 11091 // we don't consider this to be a failure of the core package deletion 11092 } 11093 } 11094 } 11095 } 11096 } 11097 11098 /** 11099 * Logic to handle installation of non-ASEC applications, including copying 11100 * and renaming logic. 11101 */ 11102 class FileInstallArgs extends InstallArgs { 11103 private File codeFile; 11104 private File resourceFile; 11105 11106 // Example topology: 11107 // /data/app/com.example/base.apk 11108 // /data/app/com.example/split_foo.apk 11109 // /data/app/com.example/lib/arm/libfoo.so 11110 // /data/app/com.example/lib/arm64/libfoo.so 11111 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11112 11113 /** New install */ 11114 FileInstallArgs(InstallParams params) { 11115 super(params.origin, params.move, params.observer, params.installFlags, 11116 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11117 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11118 params.grantedRuntimePermissions); 11119 if (isFwdLocked()) { 11120 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11121 } 11122 } 11123 11124 /** Existing install */ 11125 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11126 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11127 null, null); 11128 this.codeFile = (codePath != null) ? new File(codePath) : null; 11129 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11130 } 11131 11132 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11133 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11134 try { 11135 return doCopyApk(imcs, temp); 11136 } finally { 11137 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11138 } 11139 } 11140 11141 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11142 if (origin.staged) { 11143 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11144 codeFile = origin.file; 11145 resourceFile = origin.file; 11146 return PackageManager.INSTALL_SUCCEEDED; 11147 } 11148 11149 try { 11150 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11151 codeFile = tempDir; 11152 resourceFile = tempDir; 11153 } catch (IOException e) { 11154 Slog.w(TAG, "Failed to create copy file: " + e); 11155 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11156 } 11157 11158 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11159 @Override 11160 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11161 if (!FileUtils.isValidExtFilename(name)) { 11162 throw new IllegalArgumentException("Invalid filename: " + name); 11163 } 11164 try { 11165 final File file = new File(codeFile, name); 11166 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11167 O_RDWR | O_CREAT, 0644); 11168 Os.chmod(file.getAbsolutePath(), 0644); 11169 return new ParcelFileDescriptor(fd); 11170 } catch (ErrnoException e) { 11171 throw new RemoteException("Failed to open: " + e.getMessage()); 11172 } 11173 } 11174 }; 11175 11176 int ret = PackageManager.INSTALL_SUCCEEDED; 11177 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11178 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11179 Slog.e(TAG, "Failed to copy package"); 11180 return ret; 11181 } 11182 11183 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11184 NativeLibraryHelper.Handle handle = null; 11185 try { 11186 handle = NativeLibraryHelper.Handle.create(codeFile); 11187 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11188 abiOverride); 11189 } catch (IOException e) { 11190 Slog.e(TAG, "Copying native libraries failed", e); 11191 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11192 } finally { 11193 IoUtils.closeQuietly(handle); 11194 } 11195 11196 return ret; 11197 } 11198 11199 int doPreInstall(int status) { 11200 if (status != PackageManager.INSTALL_SUCCEEDED) { 11201 cleanUp(); 11202 } 11203 return status; 11204 } 11205 11206 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11207 if (status != PackageManager.INSTALL_SUCCEEDED) { 11208 cleanUp(); 11209 return false; 11210 } 11211 11212 final File targetDir = codeFile.getParentFile(); 11213 final File beforeCodeFile = codeFile; 11214 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11215 11216 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11217 try { 11218 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11219 } catch (ErrnoException e) { 11220 Slog.w(TAG, "Failed to rename", e); 11221 return false; 11222 } 11223 11224 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11225 Slog.w(TAG, "Failed to restorecon"); 11226 return false; 11227 } 11228 11229 // Reflect the rename internally 11230 codeFile = afterCodeFile; 11231 resourceFile = afterCodeFile; 11232 11233 // Reflect the rename in scanned details 11234 pkg.codePath = afterCodeFile.getAbsolutePath(); 11235 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11236 pkg.baseCodePath); 11237 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11238 pkg.splitCodePaths); 11239 11240 // Reflect the rename in app info 11241 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11242 pkg.applicationInfo.setCodePath(pkg.codePath); 11243 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11244 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11245 pkg.applicationInfo.setResourcePath(pkg.codePath); 11246 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11247 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11248 11249 return true; 11250 } 11251 11252 int doPostInstall(int status, int uid) { 11253 if (status != PackageManager.INSTALL_SUCCEEDED) { 11254 cleanUp(); 11255 } 11256 return status; 11257 } 11258 11259 @Override 11260 String getCodePath() { 11261 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11262 } 11263 11264 @Override 11265 String getResourcePath() { 11266 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11267 } 11268 11269 private boolean cleanUp() { 11270 if (codeFile == null || !codeFile.exists()) { 11271 return false; 11272 } 11273 11274 if (codeFile.isDirectory()) { 11275 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11276 } else { 11277 codeFile.delete(); 11278 } 11279 11280 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11281 resourceFile.delete(); 11282 } 11283 11284 return true; 11285 } 11286 11287 void cleanUpResourcesLI() { 11288 // Try enumerating all code paths before deleting 11289 List<String> allCodePaths = Collections.EMPTY_LIST; 11290 if (codeFile != null && codeFile.exists()) { 11291 try { 11292 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11293 allCodePaths = pkg.getAllCodePaths(); 11294 } catch (PackageParserException e) { 11295 // Ignored; we tried our best 11296 } 11297 } 11298 11299 cleanUp(); 11300 removeDexFiles(allCodePaths, instructionSets); 11301 } 11302 11303 boolean doPostDeleteLI(boolean delete) { 11304 // XXX err, shouldn't we respect the delete flag? 11305 cleanUpResourcesLI(); 11306 return true; 11307 } 11308 } 11309 11310 private boolean isAsecExternal(String cid) { 11311 final String asecPath = PackageHelper.getSdFilesystem(cid); 11312 return !asecPath.startsWith(mAsecInternalPath); 11313 } 11314 11315 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11316 PackageManagerException { 11317 if (copyRet < 0) { 11318 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11319 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11320 throw new PackageManagerException(copyRet, message); 11321 } 11322 } 11323 } 11324 11325 /** 11326 * Extract the MountService "container ID" from the full code path of an 11327 * .apk. 11328 */ 11329 static String cidFromCodePath(String fullCodePath) { 11330 int eidx = fullCodePath.lastIndexOf("/"); 11331 String subStr1 = fullCodePath.substring(0, eidx); 11332 int sidx = subStr1.lastIndexOf("/"); 11333 return subStr1.substring(sidx+1, eidx); 11334 } 11335 11336 /** 11337 * Logic to handle installation of ASEC applications, including copying and 11338 * renaming logic. 11339 */ 11340 class AsecInstallArgs extends InstallArgs { 11341 static final String RES_FILE_NAME = "pkg.apk"; 11342 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11343 11344 String cid; 11345 String packagePath; 11346 String resourcePath; 11347 11348 /** New install */ 11349 AsecInstallArgs(InstallParams params) { 11350 super(params.origin, params.move, params.observer, params.installFlags, 11351 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11352 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11353 params.grantedRuntimePermissions); 11354 } 11355 11356 /** Existing install */ 11357 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11358 boolean isExternal, boolean isForwardLocked) { 11359 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11360 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11361 instructionSets, null, null); 11362 // Hackily pretend we're still looking at a full code path 11363 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11364 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11365 } 11366 11367 // Extract cid from fullCodePath 11368 int eidx = fullCodePath.lastIndexOf("/"); 11369 String subStr1 = fullCodePath.substring(0, eidx); 11370 int sidx = subStr1.lastIndexOf("/"); 11371 cid = subStr1.substring(sidx+1, eidx); 11372 setMountPath(subStr1); 11373 } 11374 11375 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11376 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11377 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11378 instructionSets, null, null); 11379 this.cid = cid; 11380 setMountPath(PackageHelper.getSdDir(cid)); 11381 } 11382 11383 void createCopyFile() { 11384 cid = mInstallerService.allocateExternalStageCidLegacy(); 11385 } 11386 11387 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11388 if (origin.staged) { 11389 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11390 cid = origin.cid; 11391 setMountPath(PackageHelper.getSdDir(cid)); 11392 return PackageManager.INSTALL_SUCCEEDED; 11393 } 11394 11395 if (temp) { 11396 createCopyFile(); 11397 } else { 11398 /* 11399 * Pre-emptively destroy the container since it's destroyed if 11400 * copying fails due to it existing anyway. 11401 */ 11402 PackageHelper.destroySdDir(cid); 11403 } 11404 11405 final String newMountPath = imcs.copyPackageToContainer( 11406 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11407 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11408 11409 if (newMountPath != null) { 11410 setMountPath(newMountPath); 11411 return PackageManager.INSTALL_SUCCEEDED; 11412 } else { 11413 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11414 } 11415 } 11416 11417 @Override 11418 String getCodePath() { 11419 return packagePath; 11420 } 11421 11422 @Override 11423 String getResourcePath() { 11424 return resourcePath; 11425 } 11426 11427 int doPreInstall(int status) { 11428 if (status != PackageManager.INSTALL_SUCCEEDED) { 11429 // Destroy container 11430 PackageHelper.destroySdDir(cid); 11431 } else { 11432 boolean mounted = PackageHelper.isContainerMounted(cid); 11433 if (!mounted) { 11434 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11435 Process.SYSTEM_UID); 11436 if (newMountPath != null) { 11437 setMountPath(newMountPath); 11438 } else { 11439 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11440 } 11441 } 11442 } 11443 return status; 11444 } 11445 11446 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11447 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11448 String newMountPath = null; 11449 if (PackageHelper.isContainerMounted(cid)) { 11450 // Unmount the container 11451 if (!PackageHelper.unMountSdDir(cid)) { 11452 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11453 return false; 11454 } 11455 } 11456 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11457 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11458 " which might be stale. Will try to clean up."); 11459 // Clean up the stale container and proceed to recreate. 11460 if (!PackageHelper.destroySdDir(newCacheId)) { 11461 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11462 return false; 11463 } 11464 // Successfully cleaned up stale container. Try to rename again. 11465 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11466 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11467 + " inspite of cleaning it up."); 11468 return false; 11469 } 11470 } 11471 if (!PackageHelper.isContainerMounted(newCacheId)) { 11472 Slog.w(TAG, "Mounting container " + newCacheId); 11473 newMountPath = PackageHelper.mountSdDir(newCacheId, 11474 getEncryptKey(), Process.SYSTEM_UID); 11475 } else { 11476 newMountPath = PackageHelper.getSdDir(newCacheId); 11477 } 11478 if (newMountPath == null) { 11479 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11480 return false; 11481 } 11482 Log.i(TAG, "Succesfully renamed " + cid + 11483 " to " + newCacheId + 11484 " at new path: " + newMountPath); 11485 cid = newCacheId; 11486 11487 final File beforeCodeFile = new File(packagePath); 11488 setMountPath(newMountPath); 11489 final File afterCodeFile = new File(packagePath); 11490 11491 // Reflect the rename in scanned details 11492 pkg.codePath = afterCodeFile.getAbsolutePath(); 11493 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11494 pkg.baseCodePath); 11495 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11496 pkg.splitCodePaths); 11497 11498 // Reflect the rename in app info 11499 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11500 pkg.applicationInfo.setCodePath(pkg.codePath); 11501 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11502 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11503 pkg.applicationInfo.setResourcePath(pkg.codePath); 11504 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11505 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11506 11507 return true; 11508 } 11509 11510 private void setMountPath(String mountPath) { 11511 final File mountFile = new File(mountPath); 11512 11513 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11514 if (monolithicFile.exists()) { 11515 packagePath = monolithicFile.getAbsolutePath(); 11516 if (isFwdLocked()) { 11517 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11518 } else { 11519 resourcePath = packagePath; 11520 } 11521 } else { 11522 packagePath = mountFile.getAbsolutePath(); 11523 resourcePath = packagePath; 11524 } 11525 } 11526 11527 int doPostInstall(int status, int uid) { 11528 if (status != PackageManager.INSTALL_SUCCEEDED) { 11529 cleanUp(); 11530 } else { 11531 final int groupOwner; 11532 final String protectedFile; 11533 if (isFwdLocked()) { 11534 groupOwner = UserHandle.getSharedAppGid(uid); 11535 protectedFile = RES_FILE_NAME; 11536 } else { 11537 groupOwner = -1; 11538 protectedFile = null; 11539 } 11540 11541 if (uid < Process.FIRST_APPLICATION_UID 11542 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11543 Slog.e(TAG, "Failed to finalize " + cid); 11544 PackageHelper.destroySdDir(cid); 11545 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11546 } 11547 11548 boolean mounted = PackageHelper.isContainerMounted(cid); 11549 if (!mounted) { 11550 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11551 } 11552 } 11553 return status; 11554 } 11555 11556 private void cleanUp() { 11557 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11558 11559 // Destroy secure container 11560 PackageHelper.destroySdDir(cid); 11561 } 11562 11563 private List<String> getAllCodePaths() { 11564 final File codeFile = new File(getCodePath()); 11565 if (codeFile != null && codeFile.exists()) { 11566 try { 11567 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11568 return pkg.getAllCodePaths(); 11569 } catch (PackageParserException e) { 11570 // Ignored; we tried our best 11571 } 11572 } 11573 return Collections.EMPTY_LIST; 11574 } 11575 11576 void cleanUpResourcesLI() { 11577 // Enumerate all code paths before deleting 11578 cleanUpResourcesLI(getAllCodePaths()); 11579 } 11580 11581 private void cleanUpResourcesLI(List<String> allCodePaths) { 11582 cleanUp(); 11583 removeDexFiles(allCodePaths, instructionSets); 11584 } 11585 11586 String getPackageName() { 11587 return getAsecPackageName(cid); 11588 } 11589 11590 boolean doPostDeleteLI(boolean delete) { 11591 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11592 final List<String> allCodePaths = getAllCodePaths(); 11593 boolean mounted = PackageHelper.isContainerMounted(cid); 11594 if (mounted) { 11595 // Unmount first 11596 if (PackageHelper.unMountSdDir(cid)) { 11597 mounted = false; 11598 } 11599 } 11600 if (!mounted && delete) { 11601 cleanUpResourcesLI(allCodePaths); 11602 } 11603 return !mounted; 11604 } 11605 11606 @Override 11607 int doPreCopy() { 11608 if (isFwdLocked()) { 11609 if (!PackageHelper.fixSdPermissions(cid, 11610 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11611 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11612 } 11613 } 11614 11615 return PackageManager.INSTALL_SUCCEEDED; 11616 } 11617 11618 @Override 11619 int doPostCopy(int uid) { 11620 if (isFwdLocked()) { 11621 if (uid < Process.FIRST_APPLICATION_UID 11622 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11623 RES_FILE_NAME)) { 11624 Slog.e(TAG, "Failed to finalize " + cid); 11625 PackageHelper.destroySdDir(cid); 11626 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11627 } 11628 } 11629 11630 return PackageManager.INSTALL_SUCCEEDED; 11631 } 11632 } 11633 11634 /** 11635 * Logic to handle movement of existing installed applications. 11636 */ 11637 class MoveInstallArgs extends InstallArgs { 11638 private File codeFile; 11639 private File resourceFile; 11640 11641 /** New install */ 11642 MoveInstallArgs(InstallParams params) { 11643 super(params.origin, params.move, params.observer, params.installFlags, 11644 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11645 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11646 params.grantedRuntimePermissions); 11647 } 11648 11649 int copyApk(IMediaContainerService imcs, boolean temp) { 11650 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11651 + move.fromUuid + " to " + move.toUuid); 11652 synchronized (mInstaller) { 11653 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11654 move.dataAppName, move.appId, move.seinfo) != 0) { 11655 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11656 } 11657 } 11658 11659 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11660 resourceFile = codeFile; 11661 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11662 11663 return PackageManager.INSTALL_SUCCEEDED; 11664 } 11665 11666 int doPreInstall(int status) { 11667 if (status != PackageManager.INSTALL_SUCCEEDED) { 11668 cleanUp(move.toUuid); 11669 } 11670 return status; 11671 } 11672 11673 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11674 if (status != PackageManager.INSTALL_SUCCEEDED) { 11675 cleanUp(move.toUuid); 11676 return false; 11677 } 11678 11679 // Reflect the move in app info 11680 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11681 pkg.applicationInfo.setCodePath(pkg.codePath); 11682 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11683 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11684 pkg.applicationInfo.setResourcePath(pkg.codePath); 11685 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11686 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11687 11688 return true; 11689 } 11690 11691 int doPostInstall(int status, int uid) { 11692 if (status == PackageManager.INSTALL_SUCCEEDED) { 11693 cleanUp(move.fromUuid); 11694 } else { 11695 cleanUp(move.toUuid); 11696 } 11697 return status; 11698 } 11699 11700 @Override 11701 String getCodePath() { 11702 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11703 } 11704 11705 @Override 11706 String getResourcePath() { 11707 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11708 } 11709 11710 private boolean cleanUp(String volumeUuid) { 11711 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11712 move.dataAppName); 11713 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11714 synchronized (mInstallLock) { 11715 // Clean up both app data and code 11716 removeDataDirsLI(volumeUuid, move.packageName); 11717 if (codeFile.isDirectory()) { 11718 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11719 } else { 11720 codeFile.delete(); 11721 } 11722 } 11723 return true; 11724 } 11725 11726 void cleanUpResourcesLI() { 11727 throw new UnsupportedOperationException(); 11728 } 11729 11730 boolean doPostDeleteLI(boolean delete) { 11731 throw new UnsupportedOperationException(); 11732 } 11733 } 11734 11735 static String getAsecPackageName(String packageCid) { 11736 int idx = packageCid.lastIndexOf("-"); 11737 if (idx == -1) { 11738 return packageCid; 11739 } 11740 return packageCid.substring(0, idx); 11741 } 11742 11743 // Utility method used to create code paths based on package name and available index. 11744 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11745 String idxStr = ""; 11746 int idx = 1; 11747 // Fall back to default value of idx=1 if prefix is not 11748 // part of oldCodePath 11749 if (oldCodePath != null) { 11750 String subStr = oldCodePath; 11751 // Drop the suffix right away 11752 if (suffix != null && subStr.endsWith(suffix)) { 11753 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11754 } 11755 // If oldCodePath already contains prefix find out the 11756 // ending index to either increment or decrement. 11757 int sidx = subStr.lastIndexOf(prefix); 11758 if (sidx != -1) { 11759 subStr = subStr.substring(sidx + prefix.length()); 11760 if (subStr != null) { 11761 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11762 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11763 } 11764 try { 11765 idx = Integer.parseInt(subStr); 11766 if (idx <= 1) { 11767 idx++; 11768 } else { 11769 idx--; 11770 } 11771 } catch(NumberFormatException e) { 11772 } 11773 } 11774 } 11775 } 11776 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11777 return prefix + idxStr; 11778 } 11779 11780 private File getNextCodePath(File targetDir, String packageName) { 11781 int suffix = 1; 11782 File result; 11783 do { 11784 result = new File(targetDir, packageName + "-" + suffix); 11785 suffix++; 11786 } while (result.exists()); 11787 return result; 11788 } 11789 11790 // Utility method that returns the relative package path with respect 11791 // to the installation directory. Like say for /data/data/com.test-1.apk 11792 // string com.test-1 is returned. 11793 static String deriveCodePathName(String codePath) { 11794 if (codePath == null) { 11795 return null; 11796 } 11797 final File codeFile = new File(codePath); 11798 final String name = codeFile.getName(); 11799 if (codeFile.isDirectory()) { 11800 return name; 11801 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11802 final int lastDot = name.lastIndexOf('.'); 11803 return name.substring(0, lastDot); 11804 } else { 11805 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11806 return null; 11807 } 11808 } 11809 11810 class PackageInstalledInfo { 11811 String name; 11812 int uid; 11813 // The set of users that originally had this package installed. 11814 int[] origUsers; 11815 // The set of users that now have this package installed. 11816 int[] newUsers; 11817 PackageParser.Package pkg; 11818 int returnCode; 11819 String returnMsg; 11820 PackageRemovedInfo removedInfo; 11821 11822 public void setError(int code, String msg) { 11823 returnCode = code; 11824 returnMsg = msg; 11825 Slog.w(TAG, msg); 11826 } 11827 11828 public void setError(String msg, PackageParserException e) { 11829 returnCode = e.error; 11830 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11831 Slog.w(TAG, msg, e); 11832 } 11833 11834 public void setError(String msg, PackageManagerException e) { 11835 returnCode = e.error; 11836 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11837 Slog.w(TAG, msg, e); 11838 } 11839 11840 // In some error cases we want to convey more info back to the observer 11841 String origPackage; 11842 String origPermission; 11843 } 11844 11845 /* 11846 * Install a non-existing package. 11847 */ 11848 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11849 UserHandle user, String installerPackageName, String volumeUuid, 11850 PackageInstalledInfo res) { 11851 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11852 11853 // Remember this for later, in case we need to rollback this install 11854 String pkgName = pkg.packageName; 11855 11856 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11857 // TODO: b/23350563 11858 final boolean dataDirExists = Environment 11859 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11860 11861 synchronized(mPackages) { 11862 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11863 // A package with the same name is already installed, though 11864 // it has been renamed to an older name. The package we 11865 // are trying to install should be installed as an update to 11866 // the existing one, but that has not been requested, so bail. 11867 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11868 + " without first uninstalling package running as " 11869 + mSettings.mRenamedPackages.get(pkgName)); 11870 return; 11871 } 11872 if (mPackages.containsKey(pkgName)) { 11873 // Don't allow installation over an existing package with the same name. 11874 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11875 + " without first uninstalling."); 11876 return; 11877 } 11878 } 11879 11880 try { 11881 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11882 System.currentTimeMillis(), user); 11883 11884 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11885 // delete the partially installed application. the data directory will have to be 11886 // restored if it was already existing 11887 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11888 // remove package from internal structures. Note that we want deletePackageX to 11889 // delete the package data and cache directories that it created in 11890 // scanPackageLocked, unless those directories existed before we even tried to 11891 // install. 11892 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11893 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11894 res.removedInfo, true); 11895 } 11896 11897 } catch (PackageManagerException e) { 11898 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11899 } 11900 11901 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11902 } 11903 11904 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11905 // Can't rotate keys during boot or if sharedUser. 11906 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11907 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11908 return false; 11909 } 11910 // app is using upgradeKeySets; make sure all are valid 11911 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11912 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11913 for (int i = 0; i < upgradeKeySets.length; i++) { 11914 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11915 Slog.wtf(TAG, "Package " 11916 + (oldPs.name != null ? oldPs.name : "<null>") 11917 + " contains upgrade-key-set reference to unknown key-set: " 11918 + upgradeKeySets[i] 11919 + " reverting to signatures check."); 11920 return false; 11921 } 11922 } 11923 return true; 11924 } 11925 11926 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11927 // Upgrade keysets are being used. Determine if new package has a superset of the 11928 // required keys. 11929 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11930 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11931 for (int i = 0; i < upgradeKeySets.length; i++) { 11932 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11933 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11934 return true; 11935 } 11936 } 11937 return false; 11938 } 11939 11940 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11941 UserHandle user, String installerPackageName, String volumeUuid, 11942 PackageInstalledInfo res) { 11943 final PackageParser.Package oldPackage; 11944 final String pkgName = pkg.packageName; 11945 final int[] allUsers; 11946 final boolean[] perUserInstalled; 11947 11948 // First find the old package info and check signatures 11949 synchronized(mPackages) { 11950 oldPackage = mPackages.get(pkgName); 11951 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11952 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11953 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11954 if(!checkUpgradeKeySetLP(ps, pkg)) { 11955 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11956 "New package not signed by keys specified by upgrade-keysets: " 11957 + pkgName); 11958 return; 11959 } 11960 } else { 11961 // default to original signature matching 11962 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11963 != PackageManager.SIGNATURE_MATCH) { 11964 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11965 "New package has a different signature: " + pkgName); 11966 return; 11967 } 11968 } 11969 11970 // In case of rollback, remember per-user/profile install state 11971 allUsers = sUserManager.getUserIds(); 11972 perUserInstalled = new boolean[allUsers.length]; 11973 for (int i = 0; i < allUsers.length; i++) { 11974 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11975 } 11976 } 11977 11978 boolean sysPkg = (isSystemApp(oldPackage)); 11979 if (sysPkg) { 11980 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11981 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11982 } else { 11983 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11984 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11985 } 11986 } 11987 11988 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11989 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11990 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11991 String volumeUuid, PackageInstalledInfo res) { 11992 String pkgName = deletedPackage.packageName; 11993 boolean deletedPkg = true; 11994 boolean updatedSettings = false; 11995 11996 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11997 + deletedPackage); 11998 long origUpdateTime; 11999 if (pkg.mExtras != null) { 12000 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12001 } else { 12002 origUpdateTime = 0; 12003 } 12004 12005 // First delete the existing package while retaining the data directory 12006 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12007 res.removedInfo, true)) { 12008 // If the existing package wasn't successfully deleted 12009 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12010 deletedPkg = false; 12011 } else { 12012 // Successfully deleted the old package; proceed with replace. 12013 12014 // If deleted package lived in a container, give users a chance to 12015 // relinquish resources before killing. 12016 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12017 if (DEBUG_INSTALL) { 12018 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12019 } 12020 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12021 final ArrayList<String> pkgList = new ArrayList<String>(1); 12022 pkgList.add(deletedPackage.applicationInfo.packageName); 12023 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12024 } 12025 12026 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12027 try { 12028 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12029 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12030 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12031 perUserInstalled, res, user); 12032 updatedSettings = true; 12033 } catch (PackageManagerException e) { 12034 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12035 } 12036 } 12037 12038 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12039 // remove package from internal structures. Note that we want deletePackageX to 12040 // delete the package data and cache directories that it created in 12041 // scanPackageLocked, unless those directories existed before we even tried to 12042 // install. 12043 if(updatedSettings) { 12044 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12045 deletePackageLI( 12046 pkgName, null, true, allUsers, perUserInstalled, 12047 PackageManager.DELETE_KEEP_DATA, 12048 res.removedInfo, true); 12049 } 12050 // Since we failed to install the new package we need to restore the old 12051 // package that we deleted. 12052 if (deletedPkg) { 12053 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12054 File restoreFile = new File(deletedPackage.codePath); 12055 // Parse old package 12056 boolean oldExternal = isExternal(deletedPackage); 12057 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12058 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12059 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12060 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12061 try { 12062 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 12063 } catch (PackageManagerException e) { 12064 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12065 + e.getMessage()); 12066 return; 12067 } 12068 // Restore of old package succeeded. Update permissions. 12069 // writer 12070 synchronized (mPackages) { 12071 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12072 UPDATE_PERMISSIONS_ALL); 12073 // can downgrade to reader 12074 mSettings.writeLPr(); 12075 } 12076 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12077 } 12078 } 12079 } 12080 12081 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12082 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12083 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12084 String volumeUuid, PackageInstalledInfo res) { 12085 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12086 + ", old=" + deletedPackage); 12087 boolean disabledSystem = false; 12088 boolean updatedSettings = false; 12089 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12090 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12091 != 0) { 12092 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12093 } 12094 String packageName = deletedPackage.packageName; 12095 if (packageName == null) { 12096 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12097 "Attempt to delete null packageName."); 12098 return; 12099 } 12100 PackageParser.Package oldPkg; 12101 PackageSetting oldPkgSetting; 12102 // reader 12103 synchronized (mPackages) { 12104 oldPkg = mPackages.get(packageName); 12105 oldPkgSetting = mSettings.mPackages.get(packageName); 12106 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12107 (oldPkgSetting == null)) { 12108 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12109 "Couldn't find package:" + packageName + " information"); 12110 return; 12111 } 12112 } 12113 12114 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12115 12116 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12117 res.removedInfo.removedPackage = packageName; 12118 // Remove existing system package 12119 removePackageLI(oldPkgSetting, true); 12120 // writer 12121 synchronized (mPackages) { 12122 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12123 if (!disabledSystem && deletedPackage != null) { 12124 // We didn't need to disable the .apk as a current system package, 12125 // which means we are replacing another update that is already 12126 // installed. We need to make sure to delete the older one's .apk. 12127 res.removedInfo.args = createInstallArgsForExisting(0, 12128 deletedPackage.applicationInfo.getCodePath(), 12129 deletedPackage.applicationInfo.getResourcePath(), 12130 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12131 } else { 12132 res.removedInfo.args = null; 12133 } 12134 } 12135 12136 // Successfully disabled the old package. Now proceed with re-installation 12137 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12138 12139 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12140 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12141 12142 PackageParser.Package newPackage = null; 12143 try { 12144 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12145 if (newPackage.mExtras != null) { 12146 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12147 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12148 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12149 12150 // is the update attempting to change shared user? that isn't going to work... 12151 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12152 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12153 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12154 + " to " + newPkgSetting.sharedUser); 12155 updatedSettings = true; 12156 } 12157 } 12158 12159 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12160 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12161 perUserInstalled, res, user); 12162 updatedSettings = true; 12163 } 12164 12165 } catch (PackageManagerException e) { 12166 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12167 } 12168 12169 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12170 // Re installation failed. Restore old information 12171 // Remove new pkg information 12172 if (newPackage != null) { 12173 removeInstalledPackageLI(newPackage, true); 12174 } 12175 // Add back the old system package 12176 try { 12177 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12178 } catch (PackageManagerException e) { 12179 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12180 } 12181 // Restore the old system information in Settings 12182 synchronized (mPackages) { 12183 if (disabledSystem) { 12184 mSettings.enableSystemPackageLPw(packageName); 12185 } 12186 if (updatedSettings) { 12187 mSettings.setInstallerPackageName(packageName, 12188 oldPkgSetting.installerPackageName); 12189 } 12190 mSettings.writeLPr(); 12191 } 12192 } 12193 } 12194 12195 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12196 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12197 UserHandle user) { 12198 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12199 12200 String pkgName = newPackage.packageName; 12201 synchronized (mPackages) { 12202 //write settings. the installStatus will be incomplete at this stage. 12203 //note that the new package setting would have already been 12204 //added to mPackages. It hasn't been persisted yet. 12205 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12206 mSettings.writeLPr(); 12207 } 12208 12209 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12210 synchronized (mPackages) { 12211 updatePermissionsLPw(newPackage.packageName, newPackage, 12212 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12213 ? UPDATE_PERMISSIONS_ALL : 0)); 12214 // For system-bundled packages, we assume that installing an upgraded version 12215 // of the package implies that the user actually wants to run that new code, 12216 // so we enable the package. 12217 PackageSetting ps = mSettings.mPackages.get(pkgName); 12218 if (ps != null) { 12219 if (isSystemApp(newPackage)) { 12220 // NB: implicit assumption that system package upgrades apply to all users 12221 if (DEBUG_INSTALL) { 12222 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12223 } 12224 if (res.origUsers != null) { 12225 for (int userHandle : res.origUsers) { 12226 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12227 userHandle, installerPackageName); 12228 } 12229 } 12230 // Also convey the prior install/uninstall state 12231 if (allUsers != null && perUserInstalled != null) { 12232 for (int i = 0; i < allUsers.length; i++) { 12233 if (DEBUG_INSTALL) { 12234 Slog.d(TAG, " user " + allUsers[i] 12235 + " => " + perUserInstalled[i]); 12236 } 12237 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12238 } 12239 // these install state changes will be persisted in the 12240 // upcoming call to mSettings.writeLPr(). 12241 } 12242 } 12243 // It's implied that when a user requests installation, they want the app to be 12244 // installed and enabled. 12245 int userId = user.getIdentifier(); 12246 if (userId != UserHandle.USER_ALL) { 12247 ps.setInstalled(true, userId); 12248 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12249 } 12250 } 12251 res.name = pkgName; 12252 res.uid = newPackage.applicationInfo.uid; 12253 res.pkg = newPackage; 12254 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12255 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12256 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12257 //to update install status 12258 mSettings.writeLPr(); 12259 } 12260 12261 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12262 } 12263 12264 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12265 try { 12266 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12267 installPackageLI(args, res); 12268 } finally { 12269 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12270 } 12271 } 12272 12273 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12274 final int installFlags = args.installFlags; 12275 final String installerPackageName = args.installerPackageName; 12276 final String volumeUuid = args.volumeUuid; 12277 final File tmpPackageFile = new File(args.getCodePath()); 12278 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12279 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12280 || (args.volumeUuid != null)); 12281 boolean replace = false; 12282 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12283 if (args.move != null) { 12284 // moving a complete application; perfom an initial scan on the new install location 12285 scanFlags |= SCAN_INITIAL; 12286 } 12287 // Result object to be returned 12288 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12289 12290 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12291 12292 // Retrieve PackageSettings and parse package 12293 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12294 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12295 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12296 PackageParser pp = new PackageParser(); 12297 pp.setSeparateProcesses(mSeparateProcesses); 12298 pp.setDisplayMetrics(mMetrics); 12299 12300 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12301 final PackageParser.Package pkg; 12302 try { 12303 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12304 } catch (PackageParserException e) { 12305 res.setError("Failed parse during installPackageLI", e); 12306 return; 12307 } finally { 12308 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12309 } 12310 12311 // Mark that we have an install time CPU ABI override. 12312 pkg.cpuAbiOverride = args.abiOverride; 12313 12314 String pkgName = res.name = pkg.packageName; 12315 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12316 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12317 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12318 return; 12319 } 12320 } 12321 12322 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12323 try { 12324 pp.collectCertificates(pkg, parseFlags); 12325 pp.collectManifestDigest(pkg); 12326 } catch (PackageParserException e) { 12327 res.setError("Failed collect during installPackageLI", e); 12328 return; 12329 } finally { 12330 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12331 } 12332 12333 /* If the installer passed in a manifest digest, compare it now. */ 12334 if (args.manifestDigest != null) { 12335 if (DEBUG_INSTALL) { 12336 final String parsedManifest = pkg.manifestDigest == null ? "null" 12337 : pkg.manifestDigest.toString(); 12338 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12339 + parsedManifest); 12340 } 12341 12342 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12343 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12344 return; 12345 } 12346 } else if (DEBUG_INSTALL) { 12347 final String parsedManifest = pkg.manifestDigest == null 12348 ? "null" : pkg.manifestDigest.toString(); 12349 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12350 } 12351 12352 // Get rid of all references to package scan path via parser. 12353 pp = null; 12354 String oldCodePath = null; 12355 boolean systemApp = false; 12356 synchronized (mPackages) { 12357 // Check if installing already existing package 12358 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12359 String oldName = mSettings.mRenamedPackages.get(pkgName); 12360 if (pkg.mOriginalPackages != null 12361 && pkg.mOriginalPackages.contains(oldName) 12362 && mPackages.containsKey(oldName)) { 12363 // This package is derived from an original package, 12364 // and this device has been updating from that original 12365 // name. We must continue using the original name, so 12366 // rename the new package here. 12367 pkg.setPackageName(oldName); 12368 pkgName = pkg.packageName; 12369 replace = true; 12370 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12371 + oldName + " pkgName=" + pkgName); 12372 } else if (mPackages.containsKey(pkgName)) { 12373 // This package, under its official name, already exists 12374 // on the device; we should replace it. 12375 replace = true; 12376 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12377 } 12378 12379 // Prevent apps opting out from runtime permissions 12380 if (replace) { 12381 PackageParser.Package oldPackage = mPackages.get(pkgName); 12382 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12383 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12384 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12385 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12386 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12387 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12388 + " doesn't support runtime permissions but the old" 12389 + " target SDK " + oldTargetSdk + " does."); 12390 return; 12391 } 12392 } 12393 } 12394 12395 PackageSetting ps = mSettings.mPackages.get(pkgName); 12396 if (ps != null) { 12397 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12398 12399 // Quick sanity check that we're signed correctly if updating; 12400 // we'll check this again later when scanning, but we want to 12401 // bail early here before tripping over redefined permissions. 12402 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12403 if (!checkUpgradeKeySetLP(ps, pkg)) { 12404 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12405 + pkg.packageName + " upgrade keys do not match the " 12406 + "previously installed version"); 12407 return; 12408 } 12409 } else { 12410 try { 12411 verifySignaturesLP(ps, pkg); 12412 } catch (PackageManagerException e) { 12413 res.setError(e.error, e.getMessage()); 12414 return; 12415 } 12416 } 12417 12418 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12419 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12420 systemApp = (ps.pkg.applicationInfo.flags & 12421 ApplicationInfo.FLAG_SYSTEM) != 0; 12422 } 12423 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12424 } 12425 12426 // Check whether the newly-scanned package wants to define an already-defined perm 12427 int N = pkg.permissions.size(); 12428 for (int i = N-1; i >= 0; i--) { 12429 PackageParser.Permission perm = pkg.permissions.get(i); 12430 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12431 if (bp != null) { 12432 // If the defining package is signed with our cert, it's okay. This 12433 // also includes the "updating the same package" case, of course. 12434 // "updating same package" could also involve key-rotation. 12435 final boolean sigsOk; 12436 if (bp.sourcePackage.equals(pkg.packageName) 12437 && (bp.packageSetting instanceof PackageSetting) 12438 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12439 scanFlags))) { 12440 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12441 } else { 12442 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12443 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12444 } 12445 if (!sigsOk) { 12446 // If the owning package is the system itself, we log but allow 12447 // install to proceed; we fail the install on all other permission 12448 // redefinitions. 12449 if (!bp.sourcePackage.equals("android")) { 12450 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12451 + pkg.packageName + " attempting to redeclare permission " 12452 + perm.info.name + " already owned by " + bp.sourcePackage); 12453 res.origPermission = perm.info.name; 12454 res.origPackage = bp.sourcePackage; 12455 return; 12456 } else { 12457 Slog.w(TAG, "Package " + pkg.packageName 12458 + " attempting to redeclare system permission " 12459 + perm.info.name + "; ignoring new declaration"); 12460 pkg.permissions.remove(i); 12461 } 12462 } 12463 } 12464 } 12465 12466 } 12467 12468 if (systemApp && onExternal) { 12469 // Disable updates to system apps on sdcard 12470 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12471 "Cannot install updates to system apps on sdcard"); 12472 return; 12473 } 12474 12475 if (args.move != null) { 12476 // We did an in-place move, so dex is ready to roll 12477 scanFlags |= SCAN_NO_DEX; 12478 scanFlags |= SCAN_MOVE; 12479 12480 synchronized (mPackages) { 12481 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12482 if (ps == null) { 12483 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12484 "Missing settings for moved package " + pkgName); 12485 } 12486 12487 // We moved the entire application as-is, so bring over the 12488 // previously derived ABI information. 12489 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12490 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12491 } 12492 12493 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12494 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12495 scanFlags |= SCAN_NO_DEX; 12496 12497 try { 12498 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12499 true /* extract libs */); 12500 } catch (PackageManagerException pme) { 12501 Slog.e(TAG, "Error deriving application ABI", pme); 12502 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12503 return; 12504 } 12505 12506 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12507 int result = mPackageDexOptimizer 12508 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12509 false /* defer */, false /* inclDependencies */); 12510 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12511 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12512 return; 12513 } 12514 } 12515 12516 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12517 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12518 return; 12519 } 12520 12521 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12522 12523 if (replace) { 12524 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12525 installerPackageName, volumeUuid, res); 12526 } else { 12527 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12528 args.user, installerPackageName, volumeUuid, res); 12529 } 12530 synchronized (mPackages) { 12531 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12532 if (ps != null) { 12533 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12534 } 12535 } 12536 } 12537 12538 private void startIntentFilterVerifications(int userId, boolean replacing, 12539 PackageParser.Package pkg) { 12540 if (mIntentFilterVerifierComponent == null) { 12541 Slog.w(TAG, "No IntentFilter verification will not be done as " 12542 + "there is no IntentFilterVerifier available!"); 12543 return; 12544 } 12545 12546 final int verifierUid = getPackageUid( 12547 mIntentFilterVerifierComponent.getPackageName(), 12548 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12549 12550 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12551 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12552 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12553 mHandler.sendMessage(msg); 12554 } 12555 12556 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12557 PackageParser.Package pkg) { 12558 int size = pkg.activities.size(); 12559 if (size == 0) { 12560 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12561 "No activity, so no need to verify any IntentFilter!"); 12562 return; 12563 } 12564 12565 final boolean hasDomainURLs = hasDomainURLs(pkg); 12566 if (!hasDomainURLs) { 12567 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12568 "No domain URLs, so no need to verify any IntentFilter!"); 12569 return; 12570 } 12571 12572 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12573 + " if any IntentFilter from the " + size 12574 + " Activities needs verification ..."); 12575 12576 int count = 0; 12577 final String packageName = pkg.packageName; 12578 12579 synchronized (mPackages) { 12580 // If this is a new install and we see that we've already run verification for this 12581 // package, we have nothing to do: it means the state was restored from backup. 12582 if (!replacing) { 12583 IntentFilterVerificationInfo ivi = 12584 mSettings.getIntentFilterVerificationLPr(packageName); 12585 if (ivi != null) { 12586 if (DEBUG_DOMAIN_VERIFICATION) { 12587 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12588 + ivi.getStatusString()); 12589 } 12590 return; 12591 } 12592 } 12593 12594 // If any filters need to be verified, then all need to be. 12595 boolean needToVerify = false; 12596 for (PackageParser.Activity a : pkg.activities) { 12597 for (ActivityIntentInfo filter : a.intents) { 12598 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12599 if (DEBUG_DOMAIN_VERIFICATION) { 12600 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12601 } 12602 needToVerify = true; 12603 break; 12604 } 12605 } 12606 } 12607 12608 if (needToVerify) { 12609 final int verificationId = mIntentFilterVerificationToken++; 12610 for (PackageParser.Activity a : pkg.activities) { 12611 for (ActivityIntentInfo filter : a.intents) { 12612 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12613 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12614 "Verification needed for IntentFilter:" + filter.toString()); 12615 mIntentFilterVerifier.addOneIntentFilterVerification( 12616 verifierUid, userId, verificationId, filter, packageName); 12617 count++; 12618 } 12619 } 12620 } 12621 } 12622 } 12623 12624 if (count > 0) { 12625 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12626 + " IntentFilter verification" + (count > 1 ? "s" : "") 12627 + " for userId:" + userId); 12628 mIntentFilterVerifier.startVerifications(userId); 12629 } else { 12630 if (DEBUG_DOMAIN_VERIFICATION) { 12631 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12632 } 12633 } 12634 } 12635 12636 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12637 final ComponentName cn = filter.activity.getComponentName(); 12638 final String packageName = cn.getPackageName(); 12639 12640 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12641 packageName); 12642 if (ivi == null) { 12643 return true; 12644 } 12645 int status = ivi.getStatus(); 12646 switch (status) { 12647 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12648 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12649 return true; 12650 12651 default: 12652 // Nothing to do 12653 return false; 12654 } 12655 } 12656 12657 private static boolean isMultiArch(PackageSetting ps) { 12658 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12659 } 12660 12661 private static boolean isMultiArch(ApplicationInfo info) { 12662 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12663 } 12664 12665 private static boolean isExternal(PackageParser.Package pkg) { 12666 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12667 } 12668 12669 private static boolean isExternal(PackageSetting ps) { 12670 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12671 } 12672 12673 private static boolean isExternal(ApplicationInfo info) { 12674 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12675 } 12676 12677 private static boolean isSystemApp(PackageParser.Package pkg) { 12678 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12679 } 12680 12681 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12682 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12683 } 12684 12685 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12686 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12687 } 12688 12689 private static boolean isSystemApp(PackageSetting ps) { 12690 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12691 } 12692 12693 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12694 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12695 } 12696 12697 private int packageFlagsToInstallFlags(PackageSetting ps) { 12698 int installFlags = 0; 12699 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12700 // This existing package was an external ASEC install when we have 12701 // the external flag without a UUID 12702 installFlags |= PackageManager.INSTALL_EXTERNAL; 12703 } 12704 if (ps.isForwardLocked()) { 12705 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12706 } 12707 return installFlags; 12708 } 12709 12710 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12711 if (isExternal(pkg)) { 12712 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12713 return mSettings.getExternalVersion(); 12714 } else { 12715 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12716 } 12717 } else { 12718 return mSettings.getInternalVersion(); 12719 } 12720 } 12721 12722 private void deleteTempPackageFiles() { 12723 final FilenameFilter filter = new FilenameFilter() { 12724 public boolean accept(File dir, String name) { 12725 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12726 } 12727 }; 12728 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12729 file.delete(); 12730 } 12731 } 12732 12733 @Override 12734 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12735 int flags) { 12736 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12737 flags); 12738 } 12739 12740 @Override 12741 public void deletePackage(final String packageName, 12742 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12743 mContext.enforceCallingOrSelfPermission( 12744 android.Manifest.permission.DELETE_PACKAGES, null); 12745 Preconditions.checkNotNull(packageName); 12746 Preconditions.checkNotNull(observer); 12747 final int uid = Binder.getCallingUid(); 12748 if (UserHandle.getUserId(uid) != userId) { 12749 mContext.enforceCallingPermission( 12750 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12751 "deletePackage for user " + userId); 12752 } 12753 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12754 try { 12755 observer.onPackageDeleted(packageName, 12756 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12757 } catch (RemoteException re) { 12758 } 12759 return; 12760 } 12761 12762 boolean uninstallBlocked = false; 12763 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12764 int[] users = sUserManager.getUserIds(); 12765 for (int i = 0; i < users.length; ++i) { 12766 if (getBlockUninstallForUser(packageName, users[i])) { 12767 uninstallBlocked = true; 12768 break; 12769 } 12770 } 12771 } else { 12772 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12773 } 12774 if (uninstallBlocked) { 12775 try { 12776 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12777 null); 12778 } catch (RemoteException re) { 12779 } 12780 return; 12781 } 12782 12783 if (DEBUG_REMOVE) { 12784 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12785 } 12786 // Queue up an async operation since the package deletion may take a little while. 12787 mHandler.post(new Runnable() { 12788 public void run() { 12789 mHandler.removeCallbacks(this); 12790 final int returnCode = deletePackageX(packageName, userId, flags); 12791 if (observer != null) { 12792 try { 12793 observer.onPackageDeleted(packageName, returnCode, null); 12794 } catch (RemoteException e) { 12795 Log.i(TAG, "Observer no longer exists."); 12796 } //end catch 12797 } //end if 12798 } //end run 12799 }); 12800 } 12801 12802 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12803 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12804 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12805 try { 12806 if (dpm != null) { 12807 if (dpm.isDeviceOwner(packageName)) { 12808 return true; 12809 } 12810 int[] users; 12811 if (userId == UserHandle.USER_ALL) { 12812 users = sUserManager.getUserIds(); 12813 } else { 12814 users = new int[]{userId}; 12815 } 12816 for (int i = 0; i < users.length; ++i) { 12817 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12818 return true; 12819 } 12820 } 12821 } 12822 } catch (RemoteException e) { 12823 } 12824 return false; 12825 } 12826 12827 /** 12828 * This method is an internal method that could be get invoked either 12829 * to delete an installed package or to clean up a failed installation. 12830 * After deleting an installed package, a broadcast is sent to notify any 12831 * listeners that the package has been installed. For cleaning up a failed 12832 * installation, the broadcast is not necessary since the package's 12833 * installation wouldn't have sent the initial broadcast either 12834 * The key steps in deleting a package are 12835 * deleting the package information in internal structures like mPackages, 12836 * deleting the packages base directories through installd 12837 * updating mSettings to reflect current status 12838 * persisting settings for later use 12839 * sending a broadcast if necessary 12840 */ 12841 private int deletePackageX(String packageName, int userId, int flags) { 12842 final PackageRemovedInfo info = new PackageRemovedInfo(); 12843 final boolean res; 12844 12845 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12846 ? UserHandle.ALL : new UserHandle(userId); 12847 12848 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12849 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12850 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12851 } 12852 12853 boolean removedForAllUsers = false; 12854 boolean systemUpdate = false; 12855 12856 // for the uninstall-updates case and restricted profiles, remember the per- 12857 // userhandle installed state 12858 int[] allUsers; 12859 boolean[] perUserInstalled; 12860 synchronized (mPackages) { 12861 PackageSetting ps = mSettings.mPackages.get(packageName); 12862 allUsers = sUserManager.getUserIds(); 12863 perUserInstalled = new boolean[allUsers.length]; 12864 for (int i = 0; i < allUsers.length; i++) { 12865 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12866 } 12867 } 12868 12869 synchronized (mInstallLock) { 12870 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12871 res = deletePackageLI(packageName, removeForUser, 12872 true, allUsers, perUserInstalled, 12873 flags | REMOVE_CHATTY, info, true); 12874 systemUpdate = info.isRemovedPackageSystemUpdate; 12875 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12876 removedForAllUsers = true; 12877 } 12878 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12879 + " removedForAllUsers=" + removedForAllUsers); 12880 } 12881 12882 if (res) { 12883 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12884 12885 // If the removed package was a system update, the old system package 12886 // was re-enabled; we need to broadcast this information 12887 if (systemUpdate) { 12888 Bundle extras = new Bundle(1); 12889 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12890 ? info.removedAppId : info.uid); 12891 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12892 12893 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12894 extras, null, null, null); 12895 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12896 extras, null, null, null); 12897 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12898 null, packageName, null, null); 12899 } 12900 } 12901 // Force a gc here. 12902 Runtime.getRuntime().gc(); 12903 // Delete the resources here after sending the broadcast to let 12904 // other processes clean up before deleting resources. 12905 if (info.args != null) { 12906 synchronized (mInstallLock) { 12907 info.args.doPostDeleteLI(true); 12908 } 12909 } 12910 12911 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12912 } 12913 12914 class PackageRemovedInfo { 12915 String removedPackage; 12916 int uid = -1; 12917 int removedAppId = -1; 12918 int[] removedUsers = null; 12919 boolean isRemovedPackageSystemUpdate = false; 12920 // Clean up resources deleted packages. 12921 InstallArgs args = null; 12922 12923 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12924 Bundle extras = new Bundle(1); 12925 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12926 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12927 if (replacing) { 12928 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12929 } 12930 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12931 if (removedPackage != null) { 12932 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12933 extras, null, null, removedUsers); 12934 if (fullRemove && !replacing) { 12935 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12936 extras, null, null, removedUsers); 12937 } 12938 } 12939 if (removedAppId >= 0) { 12940 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12941 removedUsers); 12942 } 12943 } 12944 } 12945 12946 /* 12947 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12948 * flag is not set, the data directory is removed as well. 12949 * make sure this flag is set for partially installed apps. If not its meaningless to 12950 * delete a partially installed application. 12951 */ 12952 private void removePackageDataLI(PackageSetting ps, 12953 int[] allUserHandles, boolean[] perUserInstalled, 12954 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12955 String packageName = ps.name; 12956 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12957 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12958 // Retrieve object to delete permissions for shared user later on 12959 final PackageSetting deletedPs; 12960 // reader 12961 synchronized (mPackages) { 12962 deletedPs = mSettings.mPackages.get(packageName); 12963 if (outInfo != null) { 12964 outInfo.removedPackage = packageName; 12965 outInfo.removedUsers = deletedPs != null 12966 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12967 : null; 12968 } 12969 } 12970 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12971 removeDataDirsLI(ps.volumeUuid, packageName); 12972 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12973 } 12974 // writer 12975 synchronized (mPackages) { 12976 if (deletedPs != null) { 12977 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12978 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12979 clearDefaultBrowserIfNeeded(packageName); 12980 if (outInfo != null) { 12981 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12982 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12983 } 12984 updatePermissionsLPw(deletedPs.name, null, 0); 12985 if (deletedPs.sharedUser != null) { 12986 // Remove permissions associated with package. Since runtime 12987 // permissions are per user we have to kill the removed package 12988 // or packages running under the shared user of the removed 12989 // package if revoking the permissions requested only by the removed 12990 // package is successful and this causes a change in gids. 12991 for (int userId : UserManagerService.getInstance().getUserIds()) { 12992 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12993 userId); 12994 if (userIdToKill == UserHandle.USER_ALL 12995 || userIdToKill >= UserHandle.USER_OWNER) { 12996 // If gids changed for this user, kill all affected packages. 12997 mHandler.post(new Runnable() { 12998 @Override 12999 public void run() { 13000 // This has to happen with no lock held. 13001 killApplication(deletedPs.name, deletedPs.appId, 13002 KILL_APP_REASON_GIDS_CHANGED); 13003 } 13004 }); 13005 break; 13006 } 13007 } 13008 } 13009 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13010 } 13011 // make sure to preserve per-user disabled state if this removal was just 13012 // a downgrade of a system app to the factory package 13013 if (allUserHandles != null && perUserInstalled != null) { 13014 if (DEBUG_REMOVE) { 13015 Slog.d(TAG, "Propagating install state across downgrade"); 13016 } 13017 for (int i = 0; i < allUserHandles.length; i++) { 13018 if (DEBUG_REMOVE) { 13019 Slog.d(TAG, " user " + allUserHandles[i] 13020 + " => " + perUserInstalled[i]); 13021 } 13022 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13023 } 13024 } 13025 } 13026 // can downgrade to reader 13027 if (writeSettings) { 13028 // Save settings now 13029 mSettings.writeLPr(); 13030 } 13031 } 13032 if (outInfo != null) { 13033 // A user ID was deleted here. Go through all users and remove it 13034 // from KeyStore. 13035 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13036 } 13037 } 13038 13039 static boolean locationIsPrivileged(File path) { 13040 try { 13041 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13042 .getCanonicalPath(); 13043 return path.getCanonicalPath().startsWith(privilegedAppDir); 13044 } catch (IOException e) { 13045 Slog.e(TAG, "Unable to access code path " + path); 13046 } 13047 return false; 13048 } 13049 13050 /* 13051 * Tries to delete system package. 13052 */ 13053 private boolean deleteSystemPackageLI(PackageSetting newPs, 13054 int[] allUserHandles, boolean[] perUserInstalled, 13055 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13056 final boolean applyUserRestrictions 13057 = (allUserHandles != null) && (perUserInstalled != null); 13058 PackageSetting disabledPs = null; 13059 // Confirm if the system package has been updated 13060 // An updated system app can be deleted. This will also have to restore 13061 // the system pkg from system partition 13062 // reader 13063 synchronized (mPackages) { 13064 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13065 } 13066 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13067 + " disabledPs=" + disabledPs); 13068 if (disabledPs == null) { 13069 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13070 return false; 13071 } else if (DEBUG_REMOVE) { 13072 Slog.d(TAG, "Deleting system pkg from data partition"); 13073 } 13074 if (DEBUG_REMOVE) { 13075 if (applyUserRestrictions) { 13076 Slog.d(TAG, "Remembering install states:"); 13077 for (int i = 0; i < allUserHandles.length; i++) { 13078 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13079 } 13080 } 13081 } 13082 // Delete the updated package 13083 outInfo.isRemovedPackageSystemUpdate = true; 13084 if (disabledPs.versionCode < newPs.versionCode) { 13085 // Delete data for downgrades 13086 flags &= ~PackageManager.DELETE_KEEP_DATA; 13087 } else { 13088 // Preserve data by setting flag 13089 flags |= PackageManager.DELETE_KEEP_DATA; 13090 } 13091 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13092 allUserHandles, perUserInstalled, outInfo, writeSettings); 13093 if (!ret) { 13094 return false; 13095 } 13096 // writer 13097 synchronized (mPackages) { 13098 // Reinstate the old system package 13099 mSettings.enableSystemPackageLPw(newPs.name); 13100 // Remove any native libraries from the upgraded package. 13101 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13102 } 13103 // Install the system package 13104 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13105 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13106 if (locationIsPrivileged(disabledPs.codePath)) { 13107 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13108 } 13109 13110 final PackageParser.Package newPkg; 13111 try { 13112 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13113 } catch (PackageManagerException e) { 13114 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13115 return false; 13116 } 13117 13118 // writer 13119 synchronized (mPackages) { 13120 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13121 13122 // Propagate the permissions state as we do not want to drop on the floor 13123 // runtime permissions. The update permissions method below will take 13124 // care of removing obsolete permissions and grant install permissions. 13125 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13126 updatePermissionsLPw(newPkg.packageName, newPkg, 13127 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13128 13129 if (applyUserRestrictions) { 13130 if (DEBUG_REMOVE) { 13131 Slog.d(TAG, "Propagating install state across reinstall"); 13132 } 13133 for (int i = 0; i < allUserHandles.length; i++) { 13134 if (DEBUG_REMOVE) { 13135 Slog.d(TAG, " user " + allUserHandles[i] 13136 + " => " + perUserInstalled[i]); 13137 } 13138 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13139 13140 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13141 } 13142 // Regardless of writeSettings we need to ensure that this restriction 13143 // state propagation is persisted 13144 mSettings.writeAllUsersPackageRestrictionsLPr(); 13145 } 13146 // can downgrade to reader here 13147 if (writeSettings) { 13148 mSettings.writeLPr(); 13149 } 13150 } 13151 return true; 13152 } 13153 13154 private boolean deleteInstalledPackageLI(PackageSetting ps, 13155 boolean deleteCodeAndResources, int flags, 13156 int[] allUserHandles, boolean[] perUserInstalled, 13157 PackageRemovedInfo outInfo, boolean writeSettings) { 13158 if (outInfo != null) { 13159 outInfo.uid = ps.appId; 13160 } 13161 13162 // Delete package data from internal structures and also remove data if flag is set 13163 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13164 13165 // Delete application code and resources 13166 if (deleteCodeAndResources && (outInfo != null)) { 13167 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13168 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13169 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13170 } 13171 return true; 13172 } 13173 13174 @Override 13175 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13176 int userId) { 13177 mContext.enforceCallingOrSelfPermission( 13178 android.Manifest.permission.DELETE_PACKAGES, null); 13179 synchronized (mPackages) { 13180 PackageSetting ps = mSettings.mPackages.get(packageName); 13181 if (ps == null) { 13182 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13183 return false; 13184 } 13185 if (!ps.getInstalled(userId)) { 13186 // Can't block uninstall for an app that is not installed or enabled. 13187 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13188 return false; 13189 } 13190 ps.setBlockUninstall(blockUninstall, userId); 13191 mSettings.writePackageRestrictionsLPr(userId); 13192 } 13193 return true; 13194 } 13195 13196 @Override 13197 public boolean getBlockUninstallForUser(String packageName, int userId) { 13198 synchronized (mPackages) { 13199 PackageSetting ps = mSettings.mPackages.get(packageName); 13200 if (ps == null) { 13201 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13202 return false; 13203 } 13204 return ps.getBlockUninstall(userId); 13205 } 13206 } 13207 13208 /* 13209 * This method handles package deletion in general 13210 */ 13211 private boolean deletePackageLI(String packageName, UserHandle user, 13212 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13213 int flags, PackageRemovedInfo outInfo, 13214 boolean writeSettings) { 13215 if (packageName == null) { 13216 Slog.w(TAG, "Attempt to delete null packageName."); 13217 return false; 13218 } 13219 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13220 PackageSetting ps; 13221 boolean dataOnly = false; 13222 int removeUser = -1; 13223 int appId = -1; 13224 synchronized (mPackages) { 13225 ps = mSettings.mPackages.get(packageName); 13226 if (ps == null) { 13227 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13228 return false; 13229 } 13230 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13231 && user.getIdentifier() != UserHandle.USER_ALL) { 13232 // The caller is asking that the package only be deleted for a single 13233 // user. To do this, we just mark its uninstalled state and delete 13234 // its data. If this is a system app, we only allow this to happen if 13235 // they have set the special DELETE_SYSTEM_APP which requests different 13236 // semantics than normal for uninstalling system apps. 13237 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13238 final int userId = user.getIdentifier(); 13239 ps.setUserState(userId, 13240 COMPONENT_ENABLED_STATE_DEFAULT, 13241 false, //installed 13242 true, //stopped 13243 true, //notLaunched 13244 false, //hidden 13245 null, null, null, 13246 false, // blockUninstall 13247 ps.readUserState(userId).domainVerificationStatus, 0); 13248 if (!isSystemApp(ps)) { 13249 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13250 // Other user still have this package installed, so all 13251 // we need to do is clear this user's data and save that 13252 // it is uninstalled. 13253 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13254 removeUser = user.getIdentifier(); 13255 appId = ps.appId; 13256 scheduleWritePackageRestrictionsLocked(removeUser); 13257 } else { 13258 // We need to set it back to 'installed' so the uninstall 13259 // broadcasts will be sent correctly. 13260 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13261 ps.setInstalled(true, user.getIdentifier()); 13262 } 13263 } else { 13264 // This is a system app, so we assume that the 13265 // other users still have this package installed, so all 13266 // we need to do is clear this user's data and save that 13267 // it is uninstalled. 13268 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13269 removeUser = user.getIdentifier(); 13270 appId = ps.appId; 13271 scheduleWritePackageRestrictionsLocked(removeUser); 13272 } 13273 } 13274 } 13275 13276 if (removeUser >= 0) { 13277 // From above, we determined that we are deleting this only 13278 // for a single user. Continue the work here. 13279 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13280 if (outInfo != null) { 13281 outInfo.removedPackage = packageName; 13282 outInfo.removedAppId = appId; 13283 outInfo.removedUsers = new int[] {removeUser}; 13284 } 13285 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13286 removeKeystoreDataIfNeeded(removeUser, appId); 13287 schedulePackageCleaning(packageName, removeUser, false); 13288 synchronized (mPackages) { 13289 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13290 scheduleWritePackageRestrictionsLocked(removeUser); 13291 } 13292 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13293 } 13294 return true; 13295 } 13296 13297 if (dataOnly) { 13298 // Delete application data first 13299 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13300 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13301 return true; 13302 } 13303 13304 boolean ret = false; 13305 if (isSystemApp(ps)) { 13306 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13307 // When an updated system application is deleted we delete the existing resources as well and 13308 // fall back to existing code in system partition 13309 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13310 flags, outInfo, writeSettings); 13311 } else { 13312 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13313 // Kill application pre-emptively especially for apps on sd. 13314 killApplication(packageName, ps.appId, "uninstall pkg"); 13315 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13316 allUserHandles, perUserInstalled, 13317 outInfo, writeSettings); 13318 } 13319 13320 return ret; 13321 } 13322 13323 private final class ClearStorageConnection implements ServiceConnection { 13324 IMediaContainerService mContainerService; 13325 13326 @Override 13327 public void onServiceConnected(ComponentName name, IBinder service) { 13328 synchronized (this) { 13329 mContainerService = IMediaContainerService.Stub.asInterface(service); 13330 notifyAll(); 13331 } 13332 } 13333 13334 @Override 13335 public void onServiceDisconnected(ComponentName name) { 13336 } 13337 } 13338 13339 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13340 final boolean mounted; 13341 if (Environment.isExternalStorageEmulated()) { 13342 mounted = true; 13343 } else { 13344 final String status = Environment.getExternalStorageState(); 13345 13346 mounted = status.equals(Environment.MEDIA_MOUNTED) 13347 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13348 } 13349 13350 if (!mounted) { 13351 return; 13352 } 13353 13354 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13355 int[] users; 13356 if (userId == UserHandle.USER_ALL) { 13357 users = sUserManager.getUserIds(); 13358 } else { 13359 users = new int[] { userId }; 13360 } 13361 final ClearStorageConnection conn = new ClearStorageConnection(); 13362 if (mContext.bindServiceAsUser( 13363 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13364 try { 13365 for (int curUser : users) { 13366 long timeout = SystemClock.uptimeMillis() + 5000; 13367 synchronized (conn) { 13368 long now = SystemClock.uptimeMillis(); 13369 while (conn.mContainerService == null && now < timeout) { 13370 try { 13371 conn.wait(timeout - now); 13372 } catch (InterruptedException e) { 13373 } 13374 } 13375 } 13376 if (conn.mContainerService == null) { 13377 return; 13378 } 13379 13380 final UserEnvironment userEnv = new UserEnvironment(curUser); 13381 clearDirectory(conn.mContainerService, 13382 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13383 if (allData) { 13384 clearDirectory(conn.mContainerService, 13385 userEnv.buildExternalStorageAppDataDirs(packageName)); 13386 clearDirectory(conn.mContainerService, 13387 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13388 } 13389 } 13390 } finally { 13391 mContext.unbindService(conn); 13392 } 13393 } 13394 } 13395 13396 @Override 13397 public void clearApplicationUserData(final String packageName, 13398 final IPackageDataObserver observer, final int userId) { 13399 mContext.enforceCallingOrSelfPermission( 13400 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13401 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13402 // Queue up an async operation since the package deletion may take a little while. 13403 mHandler.post(new Runnable() { 13404 public void run() { 13405 mHandler.removeCallbacks(this); 13406 final boolean succeeded; 13407 synchronized (mInstallLock) { 13408 succeeded = clearApplicationUserDataLI(packageName, userId); 13409 } 13410 clearExternalStorageDataSync(packageName, userId, true); 13411 if (succeeded) { 13412 // invoke DeviceStorageMonitor's update method to clear any notifications 13413 DeviceStorageMonitorInternal 13414 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13415 if (dsm != null) { 13416 dsm.checkMemory(); 13417 } 13418 } 13419 if(observer != null) { 13420 try { 13421 observer.onRemoveCompleted(packageName, succeeded); 13422 } catch (RemoteException e) { 13423 Log.i(TAG, "Observer no longer exists."); 13424 } 13425 } //end if observer 13426 } //end run 13427 }); 13428 } 13429 13430 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13431 if (packageName == null) { 13432 Slog.w(TAG, "Attempt to delete null packageName."); 13433 return false; 13434 } 13435 13436 // Try finding details about the requested package 13437 PackageParser.Package pkg; 13438 synchronized (mPackages) { 13439 pkg = mPackages.get(packageName); 13440 if (pkg == null) { 13441 final PackageSetting ps = mSettings.mPackages.get(packageName); 13442 if (ps != null) { 13443 pkg = ps.pkg; 13444 } 13445 } 13446 13447 if (pkg == null) { 13448 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13449 return false; 13450 } 13451 13452 PackageSetting ps = (PackageSetting) pkg.mExtras; 13453 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13454 } 13455 13456 // Always delete data directories for package, even if we found no other 13457 // record of app. This helps users recover from UID mismatches without 13458 // resorting to a full data wipe. 13459 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13460 if (retCode < 0) { 13461 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13462 return false; 13463 } 13464 13465 final int appId = pkg.applicationInfo.uid; 13466 removeKeystoreDataIfNeeded(userId, appId); 13467 13468 // Create a native library symlink only if we have native libraries 13469 // and if the native libraries are 32 bit libraries. We do not provide 13470 // this symlink for 64 bit libraries. 13471 if (pkg.applicationInfo.primaryCpuAbi != null && 13472 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13473 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13474 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13475 nativeLibPath, userId) < 0) { 13476 Slog.w(TAG, "Failed linking native library dir"); 13477 return false; 13478 } 13479 } 13480 13481 return true; 13482 } 13483 13484 /** 13485 * Reverts user permission state changes (permissions and flags) in 13486 * all packages for a given user. 13487 * 13488 * @param userId The device user for which to do a reset. 13489 */ 13490 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13491 final int packageCount = mPackages.size(); 13492 for (int i = 0; i < packageCount; i++) { 13493 PackageParser.Package pkg = mPackages.valueAt(i); 13494 PackageSetting ps = (PackageSetting) pkg.mExtras; 13495 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13496 } 13497 } 13498 13499 /** 13500 * Reverts user permission state changes (permissions and flags). 13501 * 13502 * @param ps The package for which to reset. 13503 * @param userId The device user for which to do a reset. 13504 */ 13505 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13506 final PackageSetting ps, final int userId) { 13507 if (ps.pkg == null) { 13508 return; 13509 } 13510 13511 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13512 | FLAG_PERMISSION_USER_FIXED 13513 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13514 13515 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13516 | FLAG_PERMISSION_POLICY_FIXED; 13517 13518 boolean writeInstallPermissions = false; 13519 boolean writeRuntimePermissions = false; 13520 13521 final int permissionCount = ps.pkg.requestedPermissions.size(); 13522 for (int i = 0; i < permissionCount; i++) { 13523 String permission = ps.pkg.requestedPermissions.get(i); 13524 13525 BasePermission bp = mSettings.mPermissions.get(permission); 13526 if (bp == null) { 13527 continue; 13528 } 13529 13530 // If shared user we just reset the state to which only this app contributed. 13531 if (ps.sharedUser != null) { 13532 boolean used = false; 13533 final int packageCount = ps.sharedUser.packages.size(); 13534 for (int j = 0; j < packageCount; j++) { 13535 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13536 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13537 && pkg.pkg.requestedPermissions.contains(permission)) { 13538 used = true; 13539 break; 13540 } 13541 } 13542 if (used) { 13543 continue; 13544 } 13545 } 13546 13547 PermissionsState permissionsState = ps.getPermissionsState(); 13548 13549 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13550 13551 // Always clear the user settable flags. 13552 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13553 bp.name) != null; 13554 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13555 if (hasInstallState) { 13556 writeInstallPermissions = true; 13557 } else { 13558 writeRuntimePermissions = true; 13559 } 13560 } 13561 13562 // Below is only runtime permission handling. 13563 if (!bp.isRuntime()) { 13564 continue; 13565 } 13566 13567 // Never clobber system or policy. 13568 if ((oldFlags & policyOrSystemFlags) != 0) { 13569 continue; 13570 } 13571 13572 // If this permission was granted by default, make sure it is. 13573 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13574 if (permissionsState.grantRuntimePermission(bp, userId) 13575 != PERMISSION_OPERATION_FAILURE) { 13576 writeRuntimePermissions = true; 13577 } 13578 } else { 13579 // Otherwise, reset the permission. 13580 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13581 switch (revokeResult) { 13582 case PERMISSION_OPERATION_SUCCESS: { 13583 writeRuntimePermissions = true; 13584 } break; 13585 13586 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13587 writeRuntimePermissions = true; 13588 final int appId = ps.appId; 13589 mHandler.post(new Runnable() { 13590 @Override 13591 public void run() { 13592 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13593 } 13594 }); 13595 } break; 13596 } 13597 } 13598 } 13599 13600 // Synchronously write as we are taking permissions away. 13601 if (writeRuntimePermissions) { 13602 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13603 } 13604 13605 // Synchronously write as we are taking permissions away. 13606 if (writeInstallPermissions) { 13607 mSettings.writeLPr(); 13608 } 13609 } 13610 13611 /** 13612 * Remove entries from the keystore daemon. Will only remove it if the 13613 * {@code appId} is valid. 13614 */ 13615 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13616 if (appId < 0) { 13617 return; 13618 } 13619 13620 final KeyStore keyStore = KeyStore.getInstance(); 13621 if (keyStore != null) { 13622 if (userId == UserHandle.USER_ALL) { 13623 for (final int individual : sUserManager.getUserIds()) { 13624 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13625 } 13626 } else { 13627 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13628 } 13629 } else { 13630 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13631 } 13632 } 13633 13634 @Override 13635 public void deleteApplicationCacheFiles(final String packageName, 13636 final IPackageDataObserver observer) { 13637 mContext.enforceCallingOrSelfPermission( 13638 android.Manifest.permission.DELETE_CACHE_FILES, null); 13639 // Queue up an async operation since the package deletion may take a little while. 13640 final int userId = UserHandle.getCallingUserId(); 13641 mHandler.post(new Runnable() { 13642 public void run() { 13643 mHandler.removeCallbacks(this); 13644 final boolean succeded; 13645 synchronized (mInstallLock) { 13646 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13647 } 13648 clearExternalStorageDataSync(packageName, userId, false); 13649 if (observer != null) { 13650 try { 13651 observer.onRemoveCompleted(packageName, succeded); 13652 } catch (RemoteException e) { 13653 Log.i(TAG, "Observer no longer exists."); 13654 } 13655 } //end if observer 13656 } //end run 13657 }); 13658 } 13659 13660 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13661 if (packageName == null) { 13662 Slog.w(TAG, "Attempt to delete null packageName."); 13663 return false; 13664 } 13665 PackageParser.Package p; 13666 synchronized (mPackages) { 13667 p = mPackages.get(packageName); 13668 } 13669 if (p == null) { 13670 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13671 return false; 13672 } 13673 final ApplicationInfo applicationInfo = p.applicationInfo; 13674 if (applicationInfo == null) { 13675 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13676 return false; 13677 } 13678 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13679 if (retCode < 0) { 13680 Slog.w(TAG, "Couldn't remove cache files for package: " 13681 + packageName + " u" + userId); 13682 return false; 13683 } 13684 return true; 13685 } 13686 13687 @Override 13688 public void getPackageSizeInfo(final String packageName, int userHandle, 13689 final IPackageStatsObserver observer) { 13690 mContext.enforceCallingOrSelfPermission( 13691 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13692 if (packageName == null) { 13693 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13694 } 13695 13696 PackageStats stats = new PackageStats(packageName, userHandle); 13697 13698 /* 13699 * Queue up an async operation since the package measurement may take a 13700 * little while. 13701 */ 13702 Message msg = mHandler.obtainMessage(INIT_COPY); 13703 msg.obj = new MeasureParams(stats, observer); 13704 mHandler.sendMessage(msg); 13705 } 13706 13707 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13708 PackageStats pStats) { 13709 if (packageName == null) { 13710 Slog.w(TAG, "Attempt to get size of null packageName."); 13711 return false; 13712 } 13713 PackageParser.Package p; 13714 boolean dataOnly = false; 13715 String libDirRoot = null; 13716 String asecPath = null; 13717 PackageSetting ps = null; 13718 synchronized (mPackages) { 13719 p = mPackages.get(packageName); 13720 ps = mSettings.mPackages.get(packageName); 13721 if(p == null) { 13722 dataOnly = true; 13723 if((ps == null) || (ps.pkg == null)) { 13724 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13725 return false; 13726 } 13727 p = ps.pkg; 13728 } 13729 if (ps != null) { 13730 libDirRoot = ps.legacyNativeLibraryPathString; 13731 } 13732 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13733 final long token = Binder.clearCallingIdentity(); 13734 try { 13735 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13736 if (secureContainerId != null) { 13737 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13738 } 13739 } finally { 13740 Binder.restoreCallingIdentity(token); 13741 } 13742 } 13743 } 13744 String publicSrcDir = null; 13745 if(!dataOnly) { 13746 final ApplicationInfo applicationInfo = p.applicationInfo; 13747 if (applicationInfo == null) { 13748 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13749 return false; 13750 } 13751 if (p.isForwardLocked()) { 13752 publicSrcDir = applicationInfo.getBaseResourcePath(); 13753 } 13754 } 13755 // TODO: extend to measure size of split APKs 13756 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13757 // not just the first level. 13758 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13759 // just the primary. 13760 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13761 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13762 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13763 if (res < 0) { 13764 return false; 13765 } 13766 13767 // Fix-up for forward-locked applications in ASEC containers. 13768 if (!isExternal(p)) { 13769 pStats.codeSize += pStats.externalCodeSize; 13770 pStats.externalCodeSize = 0L; 13771 } 13772 13773 return true; 13774 } 13775 13776 13777 @Override 13778 public void addPackageToPreferred(String packageName) { 13779 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13780 } 13781 13782 @Override 13783 public void removePackageFromPreferred(String packageName) { 13784 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13785 } 13786 13787 @Override 13788 public List<PackageInfo> getPreferredPackages(int flags) { 13789 return new ArrayList<PackageInfo>(); 13790 } 13791 13792 private int getUidTargetSdkVersionLockedLPr(int uid) { 13793 Object obj = mSettings.getUserIdLPr(uid); 13794 if (obj instanceof SharedUserSetting) { 13795 final SharedUserSetting sus = (SharedUserSetting) obj; 13796 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13797 final Iterator<PackageSetting> it = sus.packages.iterator(); 13798 while (it.hasNext()) { 13799 final PackageSetting ps = it.next(); 13800 if (ps.pkg != null) { 13801 int v = ps.pkg.applicationInfo.targetSdkVersion; 13802 if (v < vers) vers = v; 13803 } 13804 } 13805 return vers; 13806 } else if (obj instanceof PackageSetting) { 13807 final PackageSetting ps = (PackageSetting) obj; 13808 if (ps.pkg != null) { 13809 return ps.pkg.applicationInfo.targetSdkVersion; 13810 } 13811 } 13812 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13813 } 13814 13815 @Override 13816 public void addPreferredActivity(IntentFilter filter, int match, 13817 ComponentName[] set, ComponentName activity, int userId) { 13818 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13819 "Adding preferred"); 13820 } 13821 13822 private void addPreferredActivityInternal(IntentFilter filter, int match, 13823 ComponentName[] set, ComponentName activity, boolean always, int userId, 13824 String opname) { 13825 // writer 13826 int callingUid = Binder.getCallingUid(); 13827 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13828 if (filter.countActions() == 0) { 13829 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13830 return; 13831 } 13832 synchronized (mPackages) { 13833 if (mContext.checkCallingOrSelfPermission( 13834 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13835 != PackageManager.PERMISSION_GRANTED) { 13836 if (getUidTargetSdkVersionLockedLPr(callingUid) 13837 < Build.VERSION_CODES.FROYO) { 13838 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13839 + callingUid); 13840 return; 13841 } 13842 mContext.enforceCallingOrSelfPermission( 13843 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13844 } 13845 13846 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13847 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13848 + userId + ":"); 13849 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13850 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13851 scheduleWritePackageRestrictionsLocked(userId); 13852 } 13853 } 13854 13855 @Override 13856 public void replacePreferredActivity(IntentFilter filter, int match, 13857 ComponentName[] set, ComponentName activity, int userId) { 13858 if (filter.countActions() != 1) { 13859 throw new IllegalArgumentException( 13860 "replacePreferredActivity expects filter to have only 1 action."); 13861 } 13862 if (filter.countDataAuthorities() != 0 13863 || filter.countDataPaths() != 0 13864 || filter.countDataSchemes() > 1 13865 || filter.countDataTypes() != 0) { 13866 throw new IllegalArgumentException( 13867 "replacePreferredActivity expects filter to have no data authorities, " + 13868 "paths, or types; and at most one scheme."); 13869 } 13870 13871 final int callingUid = Binder.getCallingUid(); 13872 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13873 synchronized (mPackages) { 13874 if (mContext.checkCallingOrSelfPermission( 13875 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13876 != PackageManager.PERMISSION_GRANTED) { 13877 if (getUidTargetSdkVersionLockedLPr(callingUid) 13878 < Build.VERSION_CODES.FROYO) { 13879 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13880 + Binder.getCallingUid()); 13881 return; 13882 } 13883 mContext.enforceCallingOrSelfPermission( 13884 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13885 } 13886 13887 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13888 if (pir != null) { 13889 // Get all of the existing entries that exactly match this filter. 13890 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13891 if (existing != null && existing.size() == 1) { 13892 PreferredActivity cur = existing.get(0); 13893 if (DEBUG_PREFERRED) { 13894 Slog.i(TAG, "Checking replace of preferred:"); 13895 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13896 if (!cur.mPref.mAlways) { 13897 Slog.i(TAG, " -- CUR; not mAlways!"); 13898 } else { 13899 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13900 Slog.i(TAG, " -- CUR: mSet=" 13901 + Arrays.toString(cur.mPref.mSetComponents)); 13902 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13903 Slog.i(TAG, " -- NEW: mMatch=" 13904 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13905 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13906 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13907 } 13908 } 13909 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13910 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13911 && cur.mPref.sameSet(set)) { 13912 // Setting the preferred activity to what it happens to be already 13913 if (DEBUG_PREFERRED) { 13914 Slog.i(TAG, "Replacing with same preferred activity " 13915 + cur.mPref.mShortComponent + " for user " 13916 + userId + ":"); 13917 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13918 } 13919 return; 13920 } 13921 } 13922 13923 if (existing != null) { 13924 if (DEBUG_PREFERRED) { 13925 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13926 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13927 } 13928 for (int i = 0; i < existing.size(); i++) { 13929 PreferredActivity pa = existing.get(i); 13930 if (DEBUG_PREFERRED) { 13931 Slog.i(TAG, "Removing existing preferred activity " 13932 + pa.mPref.mComponent + ":"); 13933 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13934 } 13935 pir.removeFilter(pa); 13936 } 13937 } 13938 } 13939 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13940 "Replacing preferred"); 13941 } 13942 } 13943 13944 @Override 13945 public void clearPackagePreferredActivities(String packageName) { 13946 final int uid = Binder.getCallingUid(); 13947 // writer 13948 synchronized (mPackages) { 13949 PackageParser.Package pkg = mPackages.get(packageName); 13950 if (pkg == null || pkg.applicationInfo.uid != uid) { 13951 if (mContext.checkCallingOrSelfPermission( 13952 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13953 != PackageManager.PERMISSION_GRANTED) { 13954 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13955 < Build.VERSION_CODES.FROYO) { 13956 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13957 + Binder.getCallingUid()); 13958 return; 13959 } 13960 mContext.enforceCallingOrSelfPermission( 13961 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13962 } 13963 } 13964 13965 int user = UserHandle.getCallingUserId(); 13966 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13967 scheduleWritePackageRestrictionsLocked(user); 13968 } 13969 } 13970 } 13971 13972 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13973 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13974 ArrayList<PreferredActivity> removed = null; 13975 boolean changed = false; 13976 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13977 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13978 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13979 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13980 continue; 13981 } 13982 Iterator<PreferredActivity> it = pir.filterIterator(); 13983 while (it.hasNext()) { 13984 PreferredActivity pa = it.next(); 13985 // Mark entry for removal only if it matches the package name 13986 // and the entry is of type "always". 13987 if (packageName == null || 13988 (pa.mPref.mComponent.getPackageName().equals(packageName) 13989 && pa.mPref.mAlways)) { 13990 if (removed == null) { 13991 removed = new ArrayList<PreferredActivity>(); 13992 } 13993 removed.add(pa); 13994 } 13995 } 13996 if (removed != null) { 13997 for (int j=0; j<removed.size(); j++) { 13998 PreferredActivity pa = removed.get(j); 13999 pir.removeFilter(pa); 14000 } 14001 changed = true; 14002 } 14003 } 14004 return changed; 14005 } 14006 14007 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14008 private void clearIntentFilterVerificationsLPw(int userId) { 14009 final int packageCount = mPackages.size(); 14010 for (int i = 0; i < packageCount; i++) { 14011 PackageParser.Package pkg = mPackages.valueAt(i); 14012 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14013 } 14014 } 14015 14016 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14017 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14018 if (userId == UserHandle.USER_ALL) { 14019 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14020 sUserManager.getUserIds())) { 14021 for (int oneUserId : sUserManager.getUserIds()) { 14022 scheduleWritePackageRestrictionsLocked(oneUserId); 14023 } 14024 } 14025 } else { 14026 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14027 scheduleWritePackageRestrictionsLocked(userId); 14028 } 14029 } 14030 } 14031 14032 void clearDefaultBrowserIfNeeded(String packageName) { 14033 for (int oneUserId : sUserManager.getUserIds()) { 14034 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14035 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14036 if (packageName.equals(defaultBrowserPackageName)) { 14037 setDefaultBrowserPackageName(null, oneUserId); 14038 } 14039 } 14040 } 14041 14042 @Override 14043 public void resetApplicationPreferences(int userId) { 14044 mContext.enforceCallingOrSelfPermission( 14045 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14046 // writer 14047 synchronized (mPackages) { 14048 final long identity = Binder.clearCallingIdentity(); 14049 try { 14050 clearPackagePreferredActivitiesLPw(null, userId); 14051 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14052 // TODO: We have to reset the default SMS and Phone. This requires 14053 // significant refactoring to keep all default apps in the package 14054 // manager (cleaner but more work) or have the services provide 14055 // callbacks to the package manager to request a default app reset. 14056 applyFactoryDefaultBrowserLPw(userId); 14057 clearIntentFilterVerificationsLPw(userId); 14058 primeDomainVerificationsLPw(userId); 14059 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14060 scheduleWritePackageRestrictionsLocked(userId); 14061 } finally { 14062 Binder.restoreCallingIdentity(identity); 14063 } 14064 } 14065 } 14066 14067 @Override 14068 public int getPreferredActivities(List<IntentFilter> outFilters, 14069 List<ComponentName> outActivities, String packageName) { 14070 14071 int num = 0; 14072 final int userId = UserHandle.getCallingUserId(); 14073 // reader 14074 synchronized (mPackages) { 14075 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14076 if (pir != null) { 14077 final Iterator<PreferredActivity> it = pir.filterIterator(); 14078 while (it.hasNext()) { 14079 final PreferredActivity pa = it.next(); 14080 if (packageName == null 14081 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14082 && pa.mPref.mAlways)) { 14083 if (outFilters != null) { 14084 outFilters.add(new IntentFilter(pa)); 14085 } 14086 if (outActivities != null) { 14087 outActivities.add(pa.mPref.mComponent); 14088 } 14089 } 14090 } 14091 } 14092 } 14093 14094 return num; 14095 } 14096 14097 @Override 14098 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14099 int userId) { 14100 int callingUid = Binder.getCallingUid(); 14101 if (callingUid != Process.SYSTEM_UID) { 14102 throw new SecurityException( 14103 "addPersistentPreferredActivity can only be run by the system"); 14104 } 14105 if (filter.countActions() == 0) { 14106 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14107 return; 14108 } 14109 synchronized (mPackages) { 14110 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14111 " :"); 14112 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14113 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14114 new PersistentPreferredActivity(filter, activity)); 14115 scheduleWritePackageRestrictionsLocked(userId); 14116 } 14117 } 14118 14119 @Override 14120 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14121 int callingUid = Binder.getCallingUid(); 14122 if (callingUid != Process.SYSTEM_UID) { 14123 throw new SecurityException( 14124 "clearPackagePersistentPreferredActivities can only be run by the system"); 14125 } 14126 ArrayList<PersistentPreferredActivity> removed = null; 14127 boolean changed = false; 14128 synchronized (mPackages) { 14129 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14130 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14131 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14132 .valueAt(i); 14133 if (userId != thisUserId) { 14134 continue; 14135 } 14136 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14137 while (it.hasNext()) { 14138 PersistentPreferredActivity ppa = it.next(); 14139 // Mark entry for removal only if it matches the package name. 14140 if (ppa.mComponent.getPackageName().equals(packageName)) { 14141 if (removed == null) { 14142 removed = new ArrayList<PersistentPreferredActivity>(); 14143 } 14144 removed.add(ppa); 14145 } 14146 } 14147 if (removed != null) { 14148 for (int j=0; j<removed.size(); j++) { 14149 PersistentPreferredActivity ppa = removed.get(j); 14150 ppir.removeFilter(ppa); 14151 } 14152 changed = true; 14153 } 14154 } 14155 14156 if (changed) { 14157 scheduleWritePackageRestrictionsLocked(userId); 14158 } 14159 } 14160 } 14161 14162 /** 14163 * Common machinery for picking apart a restored XML blob and passing 14164 * it to a caller-supplied functor to be applied to the running system. 14165 */ 14166 private void restoreFromXml(XmlPullParser parser, int userId, 14167 String expectedStartTag, BlobXmlRestorer functor) 14168 throws IOException, XmlPullParserException { 14169 int type; 14170 while ((type = parser.next()) != XmlPullParser.START_TAG 14171 && type != XmlPullParser.END_DOCUMENT) { 14172 } 14173 if (type != XmlPullParser.START_TAG) { 14174 // oops didn't find a start tag?! 14175 if (DEBUG_BACKUP) { 14176 Slog.e(TAG, "Didn't find start tag during restore"); 14177 } 14178 return; 14179 } 14180 14181 // this is supposed to be TAG_PREFERRED_BACKUP 14182 if (!expectedStartTag.equals(parser.getName())) { 14183 if (DEBUG_BACKUP) { 14184 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14185 } 14186 return; 14187 } 14188 14189 // skip interfering stuff, then we're aligned with the backing implementation 14190 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14191 functor.apply(parser, userId); 14192 } 14193 14194 private interface BlobXmlRestorer { 14195 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14196 } 14197 14198 /** 14199 * Non-Binder method, support for the backup/restore mechanism: write the 14200 * full set of preferred activities in its canonical XML format. Returns the 14201 * XML output as a byte array, or null if there is none. 14202 */ 14203 @Override 14204 public byte[] getPreferredActivityBackup(int userId) { 14205 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14206 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14207 } 14208 14209 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14210 try { 14211 final XmlSerializer serializer = new FastXmlSerializer(); 14212 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14213 serializer.startDocument(null, true); 14214 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14215 14216 synchronized (mPackages) { 14217 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14218 } 14219 14220 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14221 serializer.endDocument(); 14222 serializer.flush(); 14223 } catch (Exception e) { 14224 if (DEBUG_BACKUP) { 14225 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14226 } 14227 return null; 14228 } 14229 14230 return dataStream.toByteArray(); 14231 } 14232 14233 @Override 14234 public void restorePreferredActivities(byte[] backup, int userId) { 14235 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14236 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14237 } 14238 14239 try { 14240 final XmlPullParser parser = Xml.newPullParser(); 14241 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14242 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14243 new BlobXmlRestorer() { 14244 @Override 14245 public void apply(XmlPullParser parser, int userId) 14246 throws XmlPullParserException, IOException { 14247 synchronized (mPackages) { 14248 mSettings.readPreferredActivitiesLPw(parser, userId); 14249 } 14250 } 14251 } ); 14252 } catch (Exception e) { 14253 if (DEBUG_BACKUP) { 14254 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14255 } 14256 } 14257 } 14258 14259 /** 14260 * Non-Binder method, support for the backup/restore mechanism: write the 14261 * default browser (etc) settings in its canonical XML format. Returns the default 14262 * browser XML representation as a byte array, or null if there is none. 14263 */ 14264 @Override 14265 public byte[] getDefaultAppsBackup(int userId) { 14266 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14267 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14268 } 14269 14270 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14271 try { 14272 final XmlSerializer serializer = new FastXmlSerializer(); 14273 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14274 serializer.startDocument(null, true); 14275 serializer.startTag(null, TAG_DEFAULT_APPS); 14276 14277 synchronized (mPackages) { 14278 mSettings.writeDefaultAppsLPr(serializer, userId); 14279 } 14280 14281 serializer.endTag(null, TAG_DEFAULT_APPS); 14282 serializer.endDocument(); 14283 serializer.flush(); 14284 } catch (Exception e) { 14285 if (DEBUG_BACKUP) { 14286 Slog.e(TAG, "Unable to write default apps for backup", e); 14287 } 14288 return null; 14289 } 14290 14291 return dataStream.toByteArray(); 14292 } 14293 14294 @Override 14295 public void restoreDefaultApps(byte[] backup, int userId) { 14296 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14297 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14298 } 14299 14300 try { 14301 final XmlPullParser parser = Xml.newPullParser(); 14302 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14303 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14304 new BlobXmlRestorer() { 14305 @Override 14306 public void apply(XmlPullParser parser, int userId) 14307 throws XmlPullParserException, IOException { 14308 synchronized (mPackages) { 14309 mSettings.readDefaultAppsLPw(parser, userId); 14310 } 14311 } 14312 } ); 14313 } catch (Exception e) { 14314 if (DEBUG_BACKUP) { 14315 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14316 } 14317 } 14318 } 14319 14320 @Override 14321 public byte[] getIntentFilterVerificationBackup(int userId) { 14322 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14323 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14324 } 14325 14326 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14327 try { 14328 final XmlSerializer serializer = new FastXmlSerializer(); 14329 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14330 serializer.startDocument(null, true); 14331 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14332 14333 synchronized (mPackages) { 14334 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14335 } 14336 14337 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14338 serializer.endDocument(); 14339 serializer.flush(); 14340 } catch (Exception e) { 14341 if (DEBUG_BACKUP) { 14342 Slog.e(TAG, "Unable to write default apps for backup", e); 14343 } 14344 return null; 14345 } 14346 14347 return dataStream.toByteArray(); 14348 } 14349 14350 @Override 14351 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14352 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14353 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14354 } 14355 14356 try { 14357 final XmlPullParser parser = Xml.newPullParser(); 14358 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14359 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14360 new BlobXmlRestorer() { 14361 @Override 14362 public void apply(XmlPullParser parser, int userId) 14363 throws XmlPullParserException, IOException { 14364 synchronized (mPackages) { 14365 mSettings.readAllDomainVerificationsLPr(parser, userId); 14366 mSettings.writeLPr(); 14367 } 14368 } 14369 } ); 14370 } catch (Exception e) { 14371 if (DEBUG_BACKUP) { 14372 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14373 } 14374 } 14375 } 14376 14377 @Override 14378 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14379 int sourceUserId, int targetUserId, int flags) { 14380 mContext.enforceCallingOrSelfPermission( 14381 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14382 int callingUid = Binder.getCallingUid(); 14383 enforceOwnerRights(ownerPackage, callingUid); 14384 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14385 if (intentFilter.countActions() == 0) { 14386 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14387 return; 14388 } 14389 synchronized (mPackages) { 14390 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14391 ownerPackage, targetUserId, flags); 14392 CrossProfileIntentResolver resolver = 14393 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14394 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14395 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14396 if (existing != null) { 14397 int size = existing.size(); 14398 for (int i = 0; i < size; i++) { 14399 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14400 return; 14401 } 14402 } 14403 } 14404 resolver.addFilter(newFilter); 14405 scheduleWritePackageRestrictionsLocked(sourceUserId); 14406 } 14407 } 14408 14409 @Override 14410 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14411 mContext.enforceCallingOrSelfPermission( 14412 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14413 int callingUid = Binder.getCallingUid(); 14414 enforceOwnerRights(ownerPackage, callingUid); 14415 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14416 synchronized (mPackages) { 14417 CrossProfileIntentResolver resolver = 14418 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14419 ArraySet<CrossProfileIntentFilter> set = 14420 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14421 for (CrossProfileIntentFilter filter : set) { 14422 if (filter.getOwnerPackage().equals(ownerPackage)) { 14423 resolver.removeFilter(filter); 14424 } 14425 } 14426 scheduleWritePackageRestrictionsLocked(sourceUserId); 14427 } 14428 } 14429 14430 // Enforcing that callingUid is owning pkg on userId 14431 private void enforceOwnerRights(String pkg, int callingUid) { 14432 // The system owns everything. 14433 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14434 return; 14435 } 14436 int callingUserId = UserHandle.getUserId(callingUid); 14437 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14438 if (pi == null) { 14439 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14440 + callingUserId); 14441 } 14442 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14443 throw new SecurityException("Calling uid " + callingUid 14444 + " does not own package " + pkg); 14445 } 14446 } 14447 14448 @Override 14449 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14450 Intent intent = new Intent(Intent.ACTION_MAIN); 14451 intent.addCategory(Intent.CATEGORY_HOME); 14452 14453 final int callingUserId = UserHandle.getCallingUserId(); 14454 List<ResolveInfo> list = queryIntentActivities(intent, null, 14455 PackageManager.GET_META_DATA, callingUserId); 14456 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14457 true, false, false, callingUserId); 14458 14459 allHomeCandidates.clear(); 14460 if (list != null) { 14461 for (ResolveInfo ri : list) { 14462 allHomeCandidates.add(ri); 14463 } 14464 } 14465 return (preferred == null || preferred.activityInfo == null) 14466 ? null 14467 : new ComponentName(preferred.activityInfo.packageName, 14468 preferred.activityInfo.name); 14469 } 14470 14471 @Override 14472 public void setApplicationEnabledSetting(String appPackageName, 14473 int newState, int flags, int userId, String callingPackage) { 14474 if (!sUserManager.exists(userId)) return; 14475 if (callingPackage == null) { 14476 callingPackage = Integer.toString(Binder.getCallingUid()); 14477 } 14478 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14479 } 14480 14481 @Override 14482 public void setComponentEnabledSetting(ComponentName componentName, 14483 int newState, int flags, int userId) { 14484 if (!sUserManager.exists(userId)) return; 14485 setEnabledSetting(componentName.getPackageName(), 14486 componentName.getClassName(), newState, flags, userId, null); 14487 } 14488 14489 private void setEnabledSetting(final String packageName, String className, int newState, 14490 final int flags, int userId, String callingPackage) { 14491 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14492 || newState == COMPONENT_ENABLED_STATE_ENABLED 14493 || newState == COMPONENT_ENABLED_STATE_DISABLED 14494 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14495 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14496 throw new IllegalArgumentException("Invalid new component state: " 14497 + newState); 14498 } 14499 PackageSetting pkgSetting; 14500 final int uid = Binder.getCallingUid(); 14501 final int permission = mContext.checkCallingOrSelfPermission( 14502 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14503 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14504 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14505 boolean sendNow = false; 14506 boolean isApp = (className == null); 14507 String componentName = isApp ? packageName : className; 14508 int packageUid = -1; 14509 ArrayList<String> components; 14510 14511 // writer 14512 synchronized (mPackages) { 14513 pkgSetting = mSettings.mPackages.get(packageName); 14514 if (pkgSetting == null) { 14515 if (className == null) { 14516 throw new IllegalArgumentException( 14517 "Unknown package: " + packageName); 14518 } 14519 throw new IllegalArgumentException( 14520 "Unknown component: " + packageName 14521 + "/" + className); 14522 } 14523 // Allow root and verify that userId is not being specified by a different user 14524 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14525 throw new SecurityException( 14526 "Permission Denial: attempt to change component state from pid=" 14527 + Binder.getCallingPid() 14528 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14529 } 14530 if (className == null) { 14531 // We're dealing with an application/package level state change 14532 if (pkgSetting.getEnabled(userId) == newState) { 14533 // Nothing to do 14534 return; 14535 } 14536 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14537 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14538 // Don't care about who enables an app. 14539 callingPackage = null; 14540 } 14541 pkgSetting.setEnabled(newState, userId, callingPackage); 14542 // pkgSetting.pkg.mSetEnabled = newState; 14543 } else { 14544 // We're dealing with a component level state change 14545 // First, verify that this is a valid class name. 14546 PackageParser.Package pkg = pkgSetting.pkg; 14547 if (pkg == null || !pkg.hasComponentClassName(className)) { 14548 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14549 throw new IllegalArgumentException("Component class " + className 14550 + " does not exist in " + packageName); 14551 } else { 14552 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14553 + className + " does not exist in " + packageName); 14554 } 14555 } 14556 switch (newState) { 14557 case COMPONENT_ENABLED_STATE_ENABLED: 14558 if (!pkgSetting.enableComponentLPw(className, userId)) { 14559 return; 14560 } 14561 break; 14562 case COMPONENT_ENABLED_STATE_DISABLED: 14563 if (!pkgSetting.disableComponentLPw(className, userId)) { 14564 return; 14565 } 14566 break; 14567 case COMPONENT_ENABLED_STATE_DEFAULT: 14568 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14569 return; 14570 } 14571 break; 14572 default: 14573 Slog.e(TAG, "Invalid new component state: " + newState); 14574 return; 14575 } 14576 } 14577 scheduleWritePackageRestrictionsLocked(userId); 14578 components = mPendingBroadcasts.get(userId, packageName); 14579 final boolean newPackage = components == null; 14580 if (newPackage) { 14581 components = new ArrayList<String>(); 14582 } 14583 if (!components.contains(componentName)) { 14584 components.add(componentName); 14585 } 14586 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14587 sendNow = true; 14588 // Purge entry from pending broadcast list if another one exists already 14589 // since we are sending one right away. 14590 mPendingBroadcasts.remove(userId, packageName); 14591 } else { 14592 if (newPackage) { 14593 mPendingBroadcasts.put(userId, packageName, components); 14594 } 14595 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14596 // Schedule a message 14597 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14598 } 14599 } 14600 } 14601 14602 long callingId = Binder.clearCallingIdentity(); 14603 try { 14604 if (sendNow) { 14605 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14606 sendPackageChangedBroadcast(packageName, 14607 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14608 } 14609 } finally { 14610 Binder.restoreCallingIdentity(callingId); 14611 } 14612 } 14613 14614 private void sendPackageChangedBroadcast(String packageName, 14615 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14616 if (DEBUG_INSTALL) 14617 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14618 + componentNames); 14619 Bundle extras = new Bundle(4); 14620 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14621 String nameList[] = new String[componentNames.size()]; 14622 componentNames.toArray(nameList); 14623 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14624 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14625 extras.putInt(Intent.EXTRA_UID, packageUid); 14626 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14627 new int[] {UserHandle.getUserId(packageUid)}); 14628 } 14629 14630 @Override 14631 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14632 if (!sUserManager.exists(userId)) return; 14633 final int uid = Binder.getCallingUid(); 14634 final int permission = mContext.checkCallingOrSelfPermission( 14635 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14636 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14637 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14638 // writer 14639 synchronized (mPackages) { 14640 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14641 allowedByPermission, uid, userId)) { 14642 scheduleWritePackageRestrictionsLocked(userId); 14643 } 14644 } 14645 } 14646 14647 @Override 14648 public String getInstallerPackageName(String packageName) { 14649 // reader 14650 synchronized (mPackages) { 14651 return mSettings.getInstallerPackageNameLPr(packageName); 14652 } 14653 } 14654 14655 @Override 14656 public int getApplicationEnabledSetting(String packageName, int userId) { 14657 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14658 int uid = Binder.getCallingUid(); 14659 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14660 // reader 14661 synchronized (mPackages) { 14662 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14663 } 14664 } 14665 14666 @Override 14667 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14668 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14669 int uid = Binder.getCallingUid(); 14670 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14671 // reader 14672 synchronized (mPackages) { 14673 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14674 } 14675 } 14676 14677 @Override 14678 public void enterSafeMode() { 14679 enforceSystemOrRoot("Only the system can request entering safe mode"); 14680 14681 if (!mSystemReady) { 14682 mSafeMode = true; 14683 } 14684 } 14685 14686 @Override 14687 public void systemReady() { 14688 mSystemReady = true; 14689 14690 // Read the compatibilty setting when the system is ready. 14691 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14692 mContext.getContentResolver(), 14693 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14694 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14695 if (DEBUG_SETTINGS) { 14696 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14697 } 14698 14699 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14700 14701 synchronized (mPackages) { 14702 // Verify that all of the preferred activity components actually 14703 // exist. It is possible for applications to be updated and at 14704 // that point remove a previously declared activity component that 14705 // had been set as a preferred activity. We try to clean this up 14706 // the next time we encounter that preferred activity, but it is 14707 // possible for the user flow to never be able to return to that 14708 // situation so here we do a sanity check to make sure we haven't 14709 // left any junk around. 14710 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14711 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14712 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14713 removed.clear(); 14714 for (PreferredActivity pa : pir.filterSet()) { 14715 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14716 removed.add(pa); 14717 } 14718 } 14719 if (removed.size() > 0) { 14720 for (int r=0; r<removed.size(); r++) { 14721 PreferredActivity pa = removed.get(r); 14722 Slog.w(TAG, "Removing dangling preferred activity: " 14723 + pa.mPref.mComponent); 14724 pir.removeFilter(pa); 14725 } 14726 mSettings.writePackageRestrictionsLPr( 14727 mSettings.mPreferredActivities.keyAt(i)); 14728 } 14729 } 14730 14731 for (int userId : UserManagerService.getInstance().getUserIds()) { 14732 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14733 grantPermissionsUserIds = ArrayUtils.appendInt( 14734 grantPermissionsUserIds, userId); 14735 } 14736 } 14737 } 14738 sUserManager.systemReady(); 14739 14740 // If we upgraded grant all default permissions before kicking off. 14741 for (int userId : grantPermissionsUserIds) { 14742 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14743 } 14744 14745 // Kick off any messages waiting for system ready 14746 if (mPostSystemReadyMessages != null) { 14747 for (Message msg : mPostSystemReadyMessages) { 14748 msg.sendToTarget(); 14749 } 14750 mPostSystemReadyMessages = null; 14751 } 14752 14753 // Watch for external volumes that come and go over time 14754 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14755 storage.registerListener(mStorageListener); 14756 14757 mInstallerService.systemReady(); 14758 mPackageDexOptimizer.systemReady(); 14759 14760 MountServiceInternal mountServiceInternal = LocalServices.getService( 14761 MountServiceInternal.class); 14762 mountServiceInternal.addExternalStoragePolicy( 14763 new MountServiceInternal.ExternalStorageMountPolicy() { 14764 @Override 14765 public int getMountMode(int uid, String packageName) { 14766 if (Process.isIsolated(uid)) { 14767 return Zygote.MOUNT_EXTERNAL_NONE; 14768 } 14769 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14770 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14771 } 14772 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14773 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14774 } 14775 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14776 return Zygote.MOUNT_EXTERNAL_READ; 14777 } 14778 return Zygote.MOUNT_EXTERNAL_WRITE; 14779 } 14780 14781 @Override 14782 public boolean hasExternalStorage(int uid, String packageName) { 14783 return true; 14784 } 14785 }); 14786 } 14787 14788 @Override 14789 public boolean isSafeMode() { 14790 return mSafeMode; 14791 } 14792 14793 @Override 14794 public boolean hasSystemUidErrors() { 14795 return mHasSystemUidErrors; 14796 } 14797 14798 static String arrayToString(int[] array) { 14799 StringBuffer buf = new StringBuffer(128); 14800 buf.append('['); 14801 if (array != null) { 14802 for (int i=0; i<array.length; i++) { 14803 if (i > 0) buf.append(", "); 14804 buf.append(array[i]); 14805 } 14806 } 14807 buf.append(']'); 14808 return buf.toString(); 14809 } 14810 14811 static class DumpState { 14812 public static final int DUMP_LIBS = 1 << 0; 14813 public static final int DUMP_FEATURES = 1 << 1; 14814 public static final int DUMP_RESOLVERS = 1 << 2; 14815 public static final int DUMP_PERMISSIONS = 1 << 3; 14816 public static final int DUMP_PACKAGES = 1 << 4; 14817 public static final int DUMP_SHARED_USERS = 1 << 5; 14818 public static final int DUMP_MESSAGES = 1 << 6; 14819 public static final int DUMP_PROVIDERS = 1 << 7; 14820 public static final int DUMP_VERIFIERS = 1 << 8; 14821 public static final int DUMP_PREFERRED = 1 << 9; 14822 public static final int DUMP_PREFERRED_XML = 1 << 10; 14823 public static final int DUMP_KEYSETS = 1 << 11; 14824 public static final int DUMP_VERSION = 1 << 12; 14825 public static final int DUMP_INSTALLS = 1 << 13; 14826 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14827 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14828 14829 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14830 14831 private int mTypes; 14832 14833 private int mOptions; 14834 14835 private boolean mTitlePrinted; 14836 14837 private SharedUserSetting mSharedUser; 14838 14839 public boolean isDumping(int type) { 14840 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14841 return true; 14842 } 14843 14844 return (mTypes & type) != 0; 14845 } 14846 14847 public void setDump(int type) { 14848 mTypes |= type; 14849 } 14850 14851 public boolean isOptionEnabled(int option) { 14852 return (mOptions & option) != 0; 14853 } 14854 14855 public void setOptionEnabled(int option) { 14856 mOptions |= option; 14857 } 14858 14859 public boolean onTitlePrinted() { 14860 final boolean printed = mTitlePrinted; 14861 mTitlePrinted = true; 14862 return printed; 14863 } 14864 14865 public boolean getTitlePrinted() { 14866 return mTitlePrinted; 14867 } 14868 14869 public void setTitlePrinted(boolean enabled) { 14870 mTitlePrinted = enabled; 14871 } 14872 14873 public SharedUserSetting getSharedUser() { 14874 return mSharedUser; 14875 } 14876 14877 public void setSharedUser(SharedUserSetting user) { 14878 mSharedUser = user; 14879 } 14880 } 14881 14882 @Override 14883 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14884 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14885 != PackageManager.PERMISSION_GRANTED) { 14886 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14887 + Binder.getCallingPid() 14888 + ", uid=" + Binder.getCallingUid() 14889 + " without permission " 14890 + android.Manifest.permission.DUMP); 14891 return; 14892 } 14893 14894 DumpState dumpState = new DumpState(); 14895 boolean fullPreferred = false; 14896 boolean checkin = false; 14897 14898 String packageName = null; 14899 ArraySet<String> permissionNames = null; 14900 14901 int opti = 0; 14902 while (opti < args.length) { 14903 String opt = args[opti]; 14904 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14905 break; 14906 } 14907 opti++; 14908 14909 if ("-a".equals(opt)) { 14910 // Right now we only know how to print all. 14911 } else if ("-h".equals(opt)) { 14912 pw.println("Package manager dump options:"); 14913 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14914 pw.println(" --checkin: dump for a checkin"); 14915 pw.println(" -f: print details of intent filters"); 14916 pw.println(" -h: print this help"); 14917 pw.println(" cmd may be one of:"); 14918 pw.println(" l[ibraries]: list known shared libraries"); 14919 pw.println(" f[ibraries]: list device features"); 14920 pw.println(" k[eysets]: print known keysets"); 14921 pw.println(" r[esolvers]: dump intent resolvers"); 14922 pw.println(" perm[issions]: dump permissions"); 14923 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14924 pw.println(" pref[erred]: print preferred package settings"); 14925 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14926 pw.println(" prov[iders]: dump content providers"); 14927 pw.println(" p[ackages]: dump installed packages"); 14928 pw.println(" s[hared-users]: dump shared user IDs"); 14929 pw.println(" m[essages]: print collected runtime messages"); 14930 pw.println(" v[erifiers]: print package verifier info"); 14931 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14932 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14933 pw.println(" version: print database version info"); 14934 pw.println(" write: write current settings now"); 14935 pw.println(" installs: details about install sessions"); 14936 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14937 pw.println(" <package.name>: info about given package"); 14938 return; 14939 } else if ("--checkin".equals(opt)) { 14940 checkin = true; 14941 } else if ("-f".equals(opt)) { 14942 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14943 } else { 14944 pw.println("Unknown argument: " + opt + "; use -h for help"); 14945 } 14946 } 14947 14948 // Is the caller requesting to dump a particular piece of data? 14949 if (opti < args.length) { 14950 String cmd = args[opti]; 14951 opti++; 14952 // Is this a package name? 14953 if ("android".equals(cmd) || cmd.contains(".")) { 14954 packageName = cmd; 14955 // When dumping a single package, we always dump all of its 14956 // filter information since the amount of data will be reasonable. 14957 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14958 } else if ("check-permission".equals(cmd)) { 14959 if (opti >= args.length) { 14960 pw.println("Error: check-permission missing permission argument"); 14961 return; 14962 } 14963 String perm = args[opti]; 14964 opti++; 14965 if (opti >= args.length) { 14966 pw.println("Error: check-permission missing package argument"); 14967 return; 14968 } 14969 String pkg = args[opti]; 14970 opti++; 14971 int user = UserHandle.getUserId(Binder.getCallingUid()); 14972 if (opti < args.length) { 14973 try { 14974 user = Integer.parseInt(args[opti]); 14975 } catch (NumberFormatException e) { 14976 pw.println("Error: check-permission user argument is not a number: " 14977 + args[opti]); 14978 return; 14979 } 14980 } 14981 pw.println(checkPermission(perm, pkg, user)); 14982 return; 14983 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14984 dumpState.setDump(DumpState.DUMP_LIBS); 14985 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14986 dumpState.setDump(DumpState.DUMP_FEATURES); 14987 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14988 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14989 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14990 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14991 } else if ("permission".equals(cmd)) { 14992 if (opti >= args.length) { 14993 pw.println("Error: permission requires permission name"); 14994 return; 14995 } 14996 permissionNames = new ArraySet<>(); 14997 while (opti < args.length) { 14998 permissionNames.add(args[opti]); 14999 opti++; 15000 } 15001 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15002 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15003 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15004 dumpState.setDump(DumpState.DUMP_PREFERRED); 15005 } else if ("preferred-xml".equals(cmd)) { 15006 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15007 if (opti < args.length && "--full".equals(args[opti])) { 15008 fullPreferred = true; 15009 opti++; 15010 } 15011 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15012 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15013 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15014 dumpState.setDump(DumpState.DUMP_PACKAGES); 15015 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15016 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15017 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15018 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15019 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15020 dumpState.setDump(DumpState.DUMP_MESSAGES); 15021 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15022 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15023 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15024 || "intent-filter-verifiers".equals(cmd)) { 15025 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15026 } else if ("version".equals(cmd)) { 15027 dumpState.setDump(DumpState.DUMP_VERSION); 15028 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15029 dumpState.setDump(DumpState.DUMP_KEYSETS); 15030 } else if ("installs".equals(cmd)) { 15031 dumpState.setDump(DumpState.DUMP_INSTALLS); 15032 } else if ("write".equals(cmd)) { 15033 synchronized (mPackages) { 15034 mSettings.writeLPr(); 15035 pw.println("Settings written."); 15036 return; 15037 } 15038 } 15039 } 15040 15041 if (checkin) { 15042 pw.println("vers,1"); 15043 } 15044 15045 // reader 15046 synchronized (mPackages) { 15047 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15048 if (!checkin) { 15049 if (dumpState.onTitlePrinted()) 15050 pw.println(); 15051 pw.println("Database versions:"); 15052 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15053 } 15054 } 15055 15056 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15057 if (!checkin) { 15058 if (dumpState.onTitlePrinted()) 15059 pw.println(); 15060 pw.println("Verifiers:"); 15061 pw.print(" Required: "); 15062 pw.print(mRequiredVerifierPackage); 15063 pw.print(" (uid="); 15064 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15065 pw.println(")"); 15066 } else if (mRequiredVerifierPackage != null) { 15067 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15068 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15069 } 15070 } 15071 15072 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15073 packageName == null) { 15074 if (mIntentFilterVerifierComponent != null) { 15075 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15076 if (!checkin) { 15077 if (dumpState.onTitlePrinted()) 15078 pw.println(); 15079 pw.println("Intent Filter Verifier:"); 15080 pw.print(" Using: "); 15081 pw.print(verifierPackageName); 15082 pw.print(" (uid="); 15083 pw.print(getPackageUid(verifierPackageName, 0)); 15084 pw.println(")"); 15085 } else if (verifierPackageName != null) { 15086 pw.print("ifv,"); pw.print(verifierPackageName); 15087 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15088 } 15089 } else { 15090 pw.println(); 15091 pw.println("No Intent Filter Verifier available!"); 15092 } 15093 } 15094 15095 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15096 boolean printedHeader = false; 15097 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15098 while (it.hasNext()) { 15099 String name = it.next(); 15100 SharedLibraryEntry ent = mSharedLibraries.get(name); 15101 if (!checkin) { 15102 if (!printedHeader) { 15103 if (dumpState.onTitlePrinted()) 15104 pw.println(); 15105 pw.println("Libraries:"); 15106 printedHeader = true; 15107 } 15108 pw.print(" "); 15109 } else { 15110 pw.print("lib,"); 15111 } 15112 pw.print(name); 15113 if (!checkin) { 15114 pw.print(" -> "); 15115 } 15116 if (ent.path != null) { 15117 if (!checkin) { 15118 pw.print("(jar) "); 15119 pw.print(ent.path); 15120 } else { 15121 pw.print(",jar,"); 15122 pw.print(ent.path); 15123 } 15124 } else { 15125 if (!checkin) { 15126 pw.print("(apk) "); 15127 pw.print(ent.apk); 15128 } else { 15129 pw.print(",apk,"); 15130 pw.print(ent.apk); 15131 } 15132 } 15133 pw.println(); 15134 } 15135 } 15136 15137 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15138 if (dumpState.onTitlePrinted()) 15139 pw.println(); 15140 if (!checkin) { 15141 pw.println("Features:"); 15142 } 15143 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15144 while (it.hasNext()) { 15145 String name = it.next(); 15146 if (!checkin) { 15147 pw.print(" "); 15148 } else { 15149 pw.print("feat,"); 15150 } 15151 pw.println(name); 15152 } 15153 } 15154 15155 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15156 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15157 : "Activity Resolver Table:", " ", packageName, 15158 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15159 dumpState.setTitlePrinted(true); 15160 } 15161 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15162 : "Receiver Resolver Table:", " ", packageName, 15163 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15164 dumpState.setTitlePrinted(true); 15165 } 15166 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15167 : "Service Resolver Table:", " ", packageName, 15168 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15169 dumpState.setTitlePrinted(true); 15170 } 15171 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15172 : "Provider Resolver Table:", " ", packageName, 15173 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15174 dumpState.setTitlePrinted(true); 15175 } 15176 } 15177 15178 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15179 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15180 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15181 int user = mSettings.mPreferredActivities.keyAt(i); 15182 if (pir.dump(pw, 15183 dumpState.getTitlePrinted() 15184 ? "\nPreferred Activities User " + user + ":" 15185 : "Preferred Activities User " + user + ":", " ", 15186 packageName, true, false)) { 15187 dumpState.setTitlePrinted(true); 15188 } 15189 } 15190 } 15191 15192 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15193 pw.flush(); 15194 FileOutputStream fout = new FileOutputStream(fd); 15195 BufferedOutputStream str = new BufferedOutputStream(fout); 15196 XmlSerializer serializer = new FastXmlSerializer(); 15197 try { 15198 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15199 serializer.startDocument(null, true); 15200 serializer.setFeature( 15201 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15202 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15203 serializer.endDocument(); 15204 serializer.flush(); 15205 } catch (IllegalArgumentException e) { 15206 pw.println("Failed writing: " + e); 15207 } catch (IllegalStateException e) { 15208 pw.println("Failed writing: " + e); 15209 } catch (IOException e) { 15210 pw.println("Failed writing: " + e); 15211 } 15212 } 15213 15214 if (!checkin 15215 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15216 && packageName == null) { 15217 pw.println(); 15218 int count = mSettings.mPackages.size(); 15219 if (count == 0) { 15220 pw.println("No applications!"); 15221 pw.println(); 15222 } else { 15223 final String prefix = " "; 15224 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15225 if (allPackageSettings.size() == 0) { 15226 pw.println("No domain preferred apps!"); 15227 pw.println(); 15228 } else { 15229 pw.println("App verification status:"); 15230 pw.println(); 15231 count = 0; 15232 for (PackageSetting ps : allPackageSettings) { 15233 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15234 if (ivi == null || ivi.getPackageName() == null) continue; 15235 pw.println(prefix + "Package: " + ivi.getPackageName()); 15236 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15237 pw.println(prefix + "Status: " + ivi.getStatusString()); 15238 pw.println(); 15239 count++; 15240 } 15241 if (count == 0) { 15242 pw.println(prefix + "No app verification established."); 15243 pw.println(); 15244 } 15245 for (int userId : sUserManager.getUserIds()) { 15246 pw.println("App linkages for user " + userId + ":"); 15247 pw.println(); 15248 count = 0; 15249 for (PackageSetting ps : allPackageSettings) { 15250 final long status = ps.getDomainVerificationStatusForUser(userId); 15251 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15252 continue; 15253 } 15254 pw.println(prefix + "Package: " + ps.name); 15255 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15256 String statusStr = IntentFilterVerificationInfo. 15257 getStatusStringFromValue(status); 15258 pw.println(prefix + "Status: " + statusStr); 15259 pw.println(); 15260 count++; 15261 } 15262 if (count == 0) { 15263 pw.println(prefix + "No configured app linkages."); 15264 pw.println(); 15265 } 15266 } 15267 } 15268 } 15269 } 15270 15271 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15272 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15273 if (packageName == null && permissionNames == null) { 15274 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15275 if (iperm == 0) { 15276 if (dumpState.onTitlePrinted()) 15277 pw.println(); 15278 pw.println("AppOp Permissions:"); 15279 } 15280 pw.print(" AppOp Permission "); 15281 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15282 pw.println(":"); 15283 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15284 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15285 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15286 } 15287 } 15288 } 15289 } 15290 15291 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15292 boolean printedSomething = false; 15293 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15294 if (packageName != null && !packageName.equals(p.info.packageName)) { 15295 continue; 15296 } 15297 if (!printedSomething) { 15298 if (dumpState.onTitlePrinted()) 15299 pw.println(); 15300 pw.println("Registered ContentProviders:"); 15301 printedSomething = true; 15302 } 15303 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15304 pw.print(" "); pw.println(p.toString()); 15305 } 15306 printedSomething = false; 15307 for (Map.Entry<String, PackageParser.Provider> entry : 15308 mProvidersByAuthority.entrySet()) { 15309 PackageParser.Provider p = entry.getValue(); 15310 if (packageName != null && !packageName.equals(p.info.packageName)) { 15311 continue; 15312 } 15313 if (!printedSomething) { 15314 if (dumpState.onTitlePrinted()) 15315 pw.println(); 15316 pw.println("ContentProvider Authorities:"); 15317 printedSomething = true; 15318 } 15319 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15320 pw.print(" "); pw.println(p.toString()); 15321 if (p.info != null && p.info.applicationInfo != null) { 15322 final String appInfo = p.info.applicationInfo.toString(); 15323 pw.print(" applicationInfo="); pw.println(appInfo); 15324 } 15325 } 15326 } 15327 15328 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15329 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15330 } 15331 15332 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15333 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15334 } 15335 15336 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15337 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15338 } 15339 15340 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15341 // XXX should handle packageName != null by dumping only install data that 15342 // the given package is involved with. 15343 if (dumpState.onTitlePrinted()) pw.println(); 15344 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15345 } 15346 15347 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15348 if (dumpState.onTitlePrinted()) pw.println(); 15349 mSettings.dumpReadMessagesLPr(pw, dumpState); 15350 15351 pw.println(); 15352 pw.println("Package warning messages:"); 15353 BufferedReader in = null; 15354 String line = null; 15355 try { 15356 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15357 while ((line = in.readLine()) != null) { 15358 if (line.contains("ignored: updated version")) continue; 15359 pw.println(line); 15360 } 15361 } catch (IOException ignored) { 15362 } finally { 15363 IoUtils.closeQuietly(in); 15364 } 15365 } 15366 15367 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15368 BufferedReader in = null; 15369 String line = null; 15370 try { 15371 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15372 while ((line = in.readLine()) != null) { 15373 if (line.contains("ignored: updated version")) continue; 15374 pw.print("msg,"); 15375 pw.println(line); 15376 } 15377 } catch (IOException ignored) { 15378 } finally { 15379 IoUtils.closeQuietly(in); 15380 } 15381 } 15382 } 15383 } 15384 15385 private String dumpDomainString(String packageName) { 15386 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15387 List<IntentFilter> filters = getAllIntentFilters(packageName); 15388 15389 ArraySet<String> result = new ArraySet<>(); 15390 if (iviList.size() > 0) { 15391 for (IntentFilterVerificationInfo ivi : iviList) { 15392 for (String host : ivi.getDomains()) { 15393 result.add(host); 15394 } 15395 } 15396 } 15397 if (filters != null && filters.size() > 0) { 15398 for (IntentFilter filter : filters) { 15399 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15400 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15401 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15402 result.addAll(filter.getHostsList()); 15403 } 15404 } 15405 } 15406 15407 StringBuilder sb = new StringBuilder(result.size() * 16); 15408 for (String domain : result) { 15409 if (sb.length() > 0) sb.append(" "); 15410 sb.append(domain); 15411 } 15412 return sb.toString(); 15413 } 15414 15415 // ------- apps on sdcard specific code ------- 15416 static final boolean DEBUG_SD_INSTALL = false; 15417 15418 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15419 15420 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15421 15422 private boolean mMediaMounted = false; 15423 15424 static String getEncryptKey() { 15425 try { 15426 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15427 SD_ENCRYPTION_KEYSTORE_NAME); 15428 if (sdEncKey == null) { 15429 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15430 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15431 if (sdEncKey == null) { 15432 Slog.e(TAG, "Failed to create encryption keys"); 15433 return null; 15434 } 15435 } 15436 return sdEncKey; 15437 } catch (NoSuchAlgorithmException nsae) { 15438 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15439 return null; 15440 } catch (IOException ioe) { 15441 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15442 return null; 15443 } 15444 } 15445 15446 /* 15447 * Update media status on PackageManager. 15448 */ 15449 @Override 15450 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15451 int callingUid = Binder.getCallingUid(); 15452 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15453 throw new SecurityException("Media status can only be updated by the system"); 15454 } 15455 // reader; this apparently protects mMediaMounted, but should probably 15456 // be a different lock in that case. 15457 synchronized (mPackages) { 15458 Log.i(TAG, "Updating external media status from " 15459 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15460 + (mediaStatus ? "mounted" : "unmounted")); 15461 if (DEBUG_SD_INSTALL) 15462 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15463 + ", mMediaMounted=" + mMediaMounted); 15464 if (mediaStatus == mMediaMounted) { 15465 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15466 : 0, -1); 15467 mHandler.sendMessage(msg); 15468 return; 15469 } 15470 mMediaMounted = mediaStatus; 15471 } 15472 // Queue up an async operation since the package installation may take a 15473 // little while. 15474 mHandler.post(new Runnable() { 15475 public void run() { 15476 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15477 } 15478 }); 15479 } 15480 15481 /** 15482 * Called by MountService when the initial ASECs to scan are available. 15483 * Should block until all the ASEC containers are finished being scanned. 15484 */ 15485 public void scanAvailableAsecs() { 15486 updateExternalMediaStatusInner(true, false, false); 15487 if (mShouldRestoreconData) { 15488 SELinuxMMAC.setRestoreconDone(); 15489 mShouldRestoreconData = false; 15490 } 15491 } 15492 15493 /* 15494 * Collect information of applications on external media, map them against 15495 * existing containers and update information based on current mount status. 15496 * Please note that we always have to report status if reportStatus has been 15497 * set to true especially when unloading packages. 15498 */ 15499 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15500 boolean externalStorage) { 15501 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15502 int[] uidArr = EmptyArray.INT; 15503 15504 final String[] list = PackageHelper.getSecureContainerList(); 15505 if (ArrayUtils.isEmpty(list)) { 15506 Log.i(TAG, "No secure containers found"); 15507 } else { 15508 // Process list of secure containers and categorize them 15509 // as active or stale based on their package internal state. 15510 15511 // reader 15512 synchronized (mPackages) { 15513 for (String cid : list) { 15514 // Leave stages untouched for now; installer service owns them 15515 if (PackageInstallerService.isStageName(cid)) continue; 15516 15517 if (DEBUG_SD_INSTALL) 15518 Log.i(TAG, "Processing container " + cid); 15519 String pkgName = getAsecPackageName(cid); 15520 if (pkgName == null) { 15521 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15522 continue; 15523 } 15524 if (DEBUG_SD_INSTALL) 15525 Log.i(TAG, "Looking for pkg : " + pkgName); 15526 15527 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15528 if (ps == null) { 15529 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15530 continue; 15531 } 15532 15533 /* 15534 * Skip packages that are not external if we're unmounting 15535 * external storage. 15536 */ 15537 if (externalStorage && !isMounted && !isExternal(ps)) { 15538 continue; 15539 } 15540 15541 final AsecInstallArgs args = new AsecInstallArgs(cid, 15542 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15543 // The package status is changed only if the code path 15544 // matches between settings and the container id. 15545 if (ps.codePathString != null 15546 && ps.codePathString.startsWith(args.getCodePath())) { 15547 if (DEBUG_SD_INSTALL) { 15548 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15549 + " at code path: " + ps.codePathString); 15550 } 15551 15552 // We do have a valid package installed on sdcard 15553 processCids.put(args, ps.codePathString); 15554 final int uid = ps.appId; 15555 if (uid != -1) { 15556 uidArr = ArrayUtils.appendInt(uidArr, uid); 15557 } 15558 } else { 15559 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15560 + ps.codePathString); 15561 } 15562 } 15563 } 15564 15565 Arrays.sort(uidArr); 15566 } 15567 15568 // Process packages with valid entries. 15569 if (isMounted) { 15570 if (DEBUG_SD_INSTALL) 15571 Log.i(TAG, "Loading packages"); 15572 loadMediaPackages(processCids, uidArr); 15573 startCleaningPackages(); 15574 mInstallerService.onSecureContainersAvailable(); 15575 } else { 15576 if (DEBUG_SD_INSTALL) 15577 Log.i(TAG, "Unloading packages"); 15578 unloadMediaPackages(processCids, uidArr, reportStatus); 15579 } 15580 } 15581 15582 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15583 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15584 final int size = infos.size(); 15585 final String[] packageNames = new String[size]; 15586 final int[] packageUids = new int[size]; 15587 for (int i = 0; i < size; i++) { 15588 final ApplicationInfo info = infos.get(i); 15589 packageNames[i] = info.packageName; 15590 packageUids[i] = info.uid; 15591 } 15592 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15593 finishedReceiver); 15594 } 15595 15596 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15597 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15598 sendResourcesChangedBroadcast(mediaStatus, replacing, 15599 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15600 } 15601 15602 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15603 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15604 int size = pkgList.length; 15605 if (size > 0) { 15606 // Send broadcasts here 15607 Bundle extras = new Bundle(); 15608 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15609 if (uidArr != null) { 15610 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15611 } 15612 if (replacing) { 15613 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15614 } 15615 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15616 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15617 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15618 } 15619 } 15620 15621 /* 15622 * Look at potentially valid container ids from processCids If package 15623 * information doesn't match the one on record or package scanning fails, 15624 * the cid is added to list of removeCids. We currently don't delete stale 15625 * containers. 15626 */ 15627 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15628 ArrayList<String> pkgList = new ArrayList<String>(); 15629 Set<AsecInstallArgs> keys = processCids.keySet(); 15630 15631 for (AsecInstallArgs args : keys) { 15632 String codePath = processCids.get(args); 15633 if (DEBUG_SD_INSTALL) 15634 Log.i(TAG, "Loading container : " + args.cid); 15635 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15636 try { 15637 // Make sure there are no container errors first. 15638 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15639 Slog.e(TAG, "Failed to mount cid : " + args.cid 15640 + " when installing from sdcard"); 15641 continue; 15642 } 15643 // Check code path here. 15644 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15645 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15646 + " does not match one in settings " + codePath); 15647 continue; 15648 } 15649 // Parse package 15650 int parseFlags = mDefParseFlags; 15651 if (args.isExternalAsec()) { 15652 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15653 } 15654 if (args.isFwdLocked()) { 15655 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15656 } 15657 15658 synchronized (mInstallLock) { 15659 PackageParser.Package pkg = null; 15660 try { 15661 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15662 } catch (PackageManagerException e) { 15663 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15664 } 15665 // Scan the package 15666 if (pkg != null) { 15667 /* 15668 * TODO why is the lock being held? doPostInstall is 15669 * called in other places without the lock. This needs 15670 * to be straightened out. 15671 */ 15672 // writer 15673 synchronized (mPackages) { 15674 retCode = PackageManager.INSTALL_SUCCEEDED; 15675 pkgList.add(pkg.packageName); 15676 // Post process args 15677 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15678 pkg.applicationInfo.uid); 15679 } 15680 } else { 15681 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15682 } 15683 } 15684 15685 } finally { 15686 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15687 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15688 } 15689 } 15690 } 15691 // writer 15692 synchronized (mPackages) { 15693 // If the platform SDK has changed since the last time we booted, 15694 // we need to re-grant app permission to catch any new ones that 15695 // appear. This is really a hack, and means that apps can in some 15696 // cases get permissions that the user didn't initially explicitly 15697 // allow... it would be nice to have some better way to handle 15698 // this situation. 15699 final VersionInfo ver = mSettings.getExternalVersion(); 15700 15701 int updateFlags = UPDATE_PERMISSIONS_ALL; 15702 if (ver.sdkVersion != mSdkVersion) { 15703 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15704 + mSdkVersion + "; regranting permissions for external"); 15705 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15706 } 15707 updatePermissionsLPw(null, null, updateFlags); 15708 15709 // Yay, everything is now upgraded 15710 ver.forceCurrent(); 15711 15712 // can downgrade to reader 15713 // Persist settings 15714 mSettings.writeLPr(); 15715 } 15716 // Send a broadcast to let everyone know we are done processing 15717 if (pkgList.size() > 0) { 15718 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15719 } 15720 } 15721 15722 /* 15723 * Utility method to unload a list of specified containers 15724 */ 15725 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15726 // Just unmount all valid containers. 15727 for (AsecInstallArgs arg : cidArgs) { 15728 synchronized (mInstallLock) { 15729 arg.doPostDeleteLI(false); 15730 } 15731 } 15732 } 15733 15734 /* 15735 * Unload packages mounted on external media. This involves deleting package 15736 * data from internal structures, sending broadcasts about diabled packages, 15737 * gc'ing to free up references, unmounting all secure containers 15738 * corresponding to packages on external media, and posting a 15739 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15740 * that we always have to post this message if status has been requested no 15741 * matter what. 15742 */ 15743 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15744 final boolean reportStatus) { 15745 if (DEBUG_SD_INSTALL) 15746 Log.i(TAG, "unloading media packages"); 15747 ArrayList<String> pkgList = new ArrayList<String>(); 15748 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15749 final Set<AsecInstallArgs> keys = processCids.keySet(); 15750 for (AsecInstallArgs args : keys) { 15751 String pkgName = args.getPackageName(); 15752 if (DEBUG_SD_INSTALL) 15753 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15754 // Delete package internally 15755 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15756 synchronized (mInstallLock) { 15757 boolean res = deletePackageLI(pkgName, null, false, null, null, 15758 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15759 if (res) { 15760 pkgList.add(pkgName); 15761 } else { 15762 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15763 failedList.add(args); 15764 } 15765 } 15766 } 15767 15768 // reader 15769 synchronized (mPackages) { 15770 // We didn't update the settings after removing each package; 15771 // write them now for all packages. 15772 mSettings.writeLPr(); 15773 } 15774 15775 // We have to absolutely send UPDATED_MEDIA_STATUS only 15776 // after confirming that all the receivers processed the ordered 15777 // broadcast when packages get disabled, force a gc to clean things up. 15778 // and unload all the containers. 15779 if (pkgList.size() > 0) { 15780 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15781 new IIntentReceiver.Stub() { 15782 public void performReceive(Intent intent, int resultCode, String data, 15783 Bundle extras, boolean ordered, boolean sticky, 15784 int sendingUser) throws RemoteException { 15785 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15786 reportStatus ? 1 : 0, 1, keys); 15787 mHandler.sendMessage(msg); 15788 } 15789 }); 15790 } else { 15791 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15792 keys); 15793 mHandler.sendMessage(msg); 15794 } 15795 } 15796 15797 private void loadPrivatePackages(VolumeInfo vol) { 15798 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15799 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15800 synchronized (mInstallLock) { 15801 synchronized (mPackages) { 15802 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15803 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15804 for (PackageSetting ps : packages) { 15805 final PackageParser.Package pkg; 15806 try { 15807 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15808 loaded.add(pkg.applicationInfo); 15809 } catch (PackageManagerException e) { 15810 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15811 } 15812 15813 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15814 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15815 } 15816 } 15817 15818 int updateFlags = UPDATE_PERMISSIONS_ALL; 15819 if (ver.sdkVersion != mSdkVersion) { 15820 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15821 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15822 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15823 } 15824 updatePermissionsLPw(null, null, updateFlags); 15825 15826 // Yay, everything is now upgraded 15827 ver.forceCurrent(); 15828 15829 mSettings.writeLPr(); 15830 } 15831 } 15832 15833 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15834 sendResourcesChangedBroadcast(true, false, loaded, null); 15835 } 15836 15837 private void unloadPrivatePackages(VolumeInfo vol) { 15838 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15839 synchronized (mInstallLock) { 15840 synchronized (mPackages) { 15841 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15842 for (PackageSetting ps : packages) { 15843 if (ps.pkg == null) continue; 15844 15845 final ApplicationInfo info = ps.pkg.applicationInfo; 15846 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15847 if (deletePackageLI(ps.name, null, false, null, null, 15848 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15849 unloaded.add(info); 15850 } else { 15851 Slog.w(TAG, "Failed to unload " + ps.codePath); 15852 } 15853 } 15854 15855 mSettings.writeLPr(); 15856 } 15857 } 15858 15859 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15860 sendResourcesChangedBroadcast(false, false, unloaded, null); 15861 } 15862 15863 /** 15864 * Examine all users present on given mounted volume, and destroy data 15865 * belonging to users that are no longer valid, or whose user ID has been 15866 * recycled. 15867 */ 15868 private void reconcileUsers(String volumeUuid) { 15869 final File[] files = FileUtils 15870 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15871 for (File file : files) { 15872 if (!file.isDirectory()) continue; 15873 15874 final int userId; 15875 final UserInfo info; 15876 try { 15877 userId = Integer.parseInt(file.getName()); 15878 info = sUserManager.getUserInfo(userId); 15879 } catch (NumberFormatException e) { 15880 Slog.w(TAG, "Invalid user directory " + file); 15881 continue; 15882 } 15883 15884 boolean destroyUser = false; 15885 if (info == null) { 15886 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15887 + " because no matching user was found"); 15888 destroyUser = true; 15889 } else { 15890 try { 15891 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15892 } catch (IOException e) { 15893 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15894 + " because we failed to enforce serial number: " + e); 15895 destroyUser = true; 15896 } 15897 } 15898 15899 if (destroyUser) { 15900 synchronized (mInstallLock) { 15901 mInstaller.removeUserDataDirs(volumeUuid, userId); 15902 } 15903 } 15904 } 15905 15906 final UserManager um = mContext.getSystemService(UserManager.class); 15907 for (UserInfo user : um.getUsers()) { 15908 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15909 if (userDir.exists()) continue; 15910 15911 try { 15912 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15913 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15914 } catch (IOException e) { 15915 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15916 } 15917 } 15918 } 15919 15920 /** 15921 * Examine all apps present on given mounted volume, and destroy apps that 15922 * aren't expected, either due to uninstallation or reinstallation on 15923 * another volume. 15924 */ 15925 private void reconcileApps(String volumeUuid) { 15926 final File[] files = FileUtils 15927 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15928 for (File file : files) { 15929 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15930 && !PackageInstallerService.isStageName(file.getName()); 15931 if (!isPackage) { 15932 // Ignore entries which are not packages 15933 continue; 15934 } 15935 15936 boolean destroyApp = false; 15937 String packageName = null; 15938 try { 15939 final PackageLite pkg = PackageParser.parsePackageLite(file, 15940 PackageParser.PARSE_MUST_BE_APK); 15941 packageName = pkg.packageName; 15942 15943 synchronized (mPackages) { 15944 final PackageSetting ps = mSettings.mPackages.get(packageName); 15945 if (ps == null) { 15946 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15947 + volumeUuid + " because we found no install record"); 15948 destroyApp = true; 15949 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15950 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15951 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15952 destroyApp = true; 15953 } 15954 } 15955 15956 } catch (PackageParserException e) { 15957 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15958 destroyApp = true; 15959 } 15960 15961 if (destroyApp) { 15962 synchronized (mInstallLock) { 15963 if (packageName != null) { 15964 removeDataDirsLI(volumeUuid, packageName); 15965 } 15966 if (file.isDirectory()) { 15967 mInstaller.rmPackageDir(file.getAbsolutePath()); 15968 } else { 15969 file.delete(); 15970 } 15971 } 15972 } 15973 } 15974 } 15975 15976 private void unfreezePackage(String packageName) { 15977 synchronized (mPackages) { 15978 final PackageSetting ps = mSettings.mPackages.get(packageName); 15979 if (ps != null) { 15980 ps.frozen = false; 15981 } 15982 } 15983 } 15984 15985 @Override 15986 public int movePackage(final String packageName, final String volumeUuid) { 15987 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15988 15989 final int moveId = mNextMoveId.getAndIncrement(); 15990 try { 15991 movePackageInternal(packageName, volumeUuid, moveId); 15992 } catch (PackageManagerException e) { 15993 Slog.w(TAG, "Failed to move " + packageName, e); 15994 mMoveCallbacks.notifyStatusChanged(moveId, 15995 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15996 } 15997 return moveId; 15998 } 15999 16000 private void movePackageInternal(final String packageName, final String volumeUuid, 16001 final int moveId) throws PackageManagerException { 16002 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16003 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16004 final PackageManager pm = mContext.getPackageManager(); 16005 16006 final boolean currentAsec; 16007 final String currentVolumeUuid; 16008 final File codeFile; 16009 final String installerPackageName; 16010 final String packageAbiOverride; 16011 final int appId; 16012 final String seinfo; 16013 final String label; 16014 16015 // reader 16016 synchronized (mPackages) { 16017 final PackageParser.Package pkg = mPackages.get(packageName); 16018 final PackageSetting ps = mSettings.mPackages.get(packageName); 16019 if (pkg == null || ps == null) { 16020 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16021 } 16022 16023 if (pkg.applicationInfo.isSystemApp()) { 16024 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16025 "Cannot move system application"); 16026 } 16027 16028 if (pkg.applicationInfo.isExternalAsec()) { 16029 currentAsec = true; 16030 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16031 } else if (pkg.applicationInfo.isForwardLocked()) { 16032 currentAsec = true; 16033 currentVolumeUuid = "forward_locked"; 16034 } else { 16035 currentAsec = false; 16036 currentVolumeUuid = ps.volumeUuid; 16037 16038 final File probe = new File(pkg.codePath); 16039 final File probeOat = new File(probe, "oat"); 16040 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16041 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16042 "Move only supported for modern cluster style installs"); 16043 } 16044 } 16045 16046 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16047 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16048 "Package already moved to " + volumeUuid); 16049 } 16050 16051 if (ps.frozen) { 16052 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16053 "Failed to move already frozen package"); 16054 } 16055 ps.frozen = true; 16056 16057 codeFile = new File(pkg.codePath); 16058 installerPackageName = ps.installerPackageName; 16059 packageAbiOverride = ps.cpuAbiOverrideString; 16060 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16061 seinfo = pkg.applicationInfo.seinfo; 16062 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16063 } 16064 16065 // Now that we're guarded by frozen state, kill app during move 16066 final long token = Binder.clearCallingIdentity(); 16067 try { 16068 killApplication(packageName, appId, "move pkg"); 16069 } finally { 16070 Binder.restoreCallingIdentity(token); 16071 } 16072 16073 final Bundle extras = new Bundle(); 16074 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16075 extras.putString(Intent.EXTRA_TITLE, label); 16076 mMoveCallbacks.notifyCreated(moveId, extras); 16077 16078 int installFlags; 16079 final boolean moveCompleteApp; 16080 final File measurePath; 16081 16082 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16083 installFlags = INSTALL_INTERNAL; 16084 moveCompleteApp = !currentAsec; 16085 measurePath = Environment.getDataAppDirectory(volumeUuid); 16086 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16087 installFlags = INSTALL_EXTERNAL; 16088 moveCompleteApp = false; 16089 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16090 } else { 16091 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16092 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16093 || !volume.isMountedWritable()) { 16094 unfreezePackage(packageName); 16095 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16096 "Move location not mounted private volume"); 16097 } 16098 16099 Preconditions.checkState(!currentAsec); 16100 16101 installFlags = INSTALL_INTERNAL; 16102 moveCompleteApp = true; 16103 measurePath = Environment.getDataAppDirectory(volumeUuid); 16104 } 16105 16106 final PackageStats stats = new PackageStats(null, -1); 16107 synchronized (mInstaller) { 16108 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16109 unfreezePackage(packageName); 16110 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16111 "Failed to measure package size"); 16112 } 16113 } 16114 16115 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16116 + stats.dataSize); 16117 16118 final long startFreeBytes = measurePath.getFreeSpace(); 16119 final long sizeBytes; 16120 if (moveCompleteApp) { 16121 sizeBytes = stats.codeSize + stats.dataSize; 16122 } else { 16123 sizeBytes = stats.codeSize; 16124 } 16125 16126 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16127 unfreezePackage(packageName); 16128 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16129 "Not enough free space to move"); 16130 } 16131 16132 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16133 16134 final CountDownLatch installedLatch = new CountDownLatch(1); 16135 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16136 @Override 16137 public void onUserActionRequired(Intent intent) throws RemoteException { 16138 throw new IllegalStateException(); 16139 } 16140 16141 @Override 16142 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16143 Bundle extras) throws RemoteException { 16144 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16145 + PackageManager.installStatusToString(returnCode, msg)); 16146 16147 installedLatch.countDown(); 16148 16149 // Regardless of success or failure of the move operation, 16150 // always unfreeze the package 16151 unfreezePackage(packageName); 16152 16153 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16154 switch (status) { 16155 case PackageInstaller.STATUS_SUCCESS: 16156 mMoveCallbacks.notifyStatusChanged(moveId, 16157 PackageManager.MOVE_SUCCEEDED); 16158 break; 16159 case PackageInstaller.STATUS_FAILURE_STORAGE: 16160 mMoveCallbacks.notifyStatusChanged(moveId, 16161 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16162 break; 16163 default: 16164 mMoveCallbacks.notifyStatusChanged(moveId, 16165 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16166 break; 16167 } 16168 } 16169 }; 16170 16171 final MoveInfo move; 16172 if (moveCompleteApp) { 16173 // Kick off a thread to report progress estimates 16174 new Thread() { 16175 @Override 16176 public void run() { 16177 while (true) { 16178 try { 16179 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16180 break; 16181 } 16182 } catch (InterruptedException ignored) { 16183 } 16184 16185 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16186 final int progress = 10 + (int) MathUtils.constrain( 16187 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16188 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16189 } 16190 } 16191 }.start(); 16192 16193 final String dataAppName = codeFile.getName(); 16194 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16195 dataAppName, appId, seinfo); 16196 } else { 16197 move = null; 16198 } 16199 16200 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16201 16202 final Message msg = mHandler.obtainMessage(INIT_COPY); 16203 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16204 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16205 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16206 mHandler.sendMessage(msg); 16207 } 16208 16209 @Override 16210 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16211 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16212 16213 final int realMoveId = mNextMoveId.getAndIncrement(); 16214 final Bundle extras = new Bundle(); 16215 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16216 mMoveCallbacks.notifyCreated(realMoveId, extras); 16217 16218 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16219 @Override 16220 public void onCreated(int moveId, Bundle extras) { 16221 // Ignored 16222 } 16223 16224 @Override 16225 public void onStatusChanged(int moveId, int status, long estMillis) { 16226 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16227 } 16228 }; 16229 16230 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16231 storage.setPrimaryStorageUuid(volumeUuid, callback); 16232 return realMoveId; 16233 } 16234 16235 @Override 16236 public int getMoveStatus(int moveId) { 16237 mContext.enforceCallingOrSelfPermission( 16238 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16239 return mMoveCallbacks.mLastStatus.get(moveId); 16240 } 16241 16242 @Override 16243 public void registerMoveCallback(IPackageMoveObserver callback) { 16244 mContext.enforceCallingOrSelfPermission( 16245 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16246 mMoveCallbacks.register(callback); 16247 } 16248 16249 @Override 16250 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16251 mContext.enforceCallingOrSelfPermission( 16252 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16253 mMoveCallbacks.unregister(callback); 16254 } 16255 16256 @Override 16257 public boolean setInstallLocation(int loc) { 16258 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16259 null); 16260 if (getInstallLocation() == loc) { 16261 return true; 16262 } 16263 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16264 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16265 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16266 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16267 return true; 16268 } 16269 return false; 16270 } 16271 16272 @Override 16273 public int getInstallLocation() { 16274 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16275 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16276 PackageHelper.APP_INSTALL_AUTO); 16277 } 16278 16279 /** Called by UserManagerService */ 16280 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16281 mDirtyUsers.remove(userHandle); 16282 mSettings.removeUserLPw(userHandle); 16283 mPendingBroadcasts.remove(userHandle); 16284 if (mInstaller != null) { 16285 // Technically, we shouldn't be doing this with the package lock 16286 // held. However, this is very rare, and there is already so much 16287 // other disk I/O going on, that we'll let it slide for now. 16288 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16289 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16290 final String volumeUuid = vol.getFsUuid(); 16291 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16292 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16293 } 16294 } 16295 mUserNeedsBadging.delete(userHandle); 16296 removeUnusedPackagesLILPw(userManager, userHandle); 16297 } 16298 16299 /** 16300 * We're removing userHandle and would like to remove any downloaded packages 16301 * that are no longer in use by any other user. 16302 * @param userHandle the user being removed 16303 */ 16304 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16305 final boolean DEBUG_CLEAN_APKS = false; 16306 int [] users = userManager.getUserIdsLPr(); 16307 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16308 while (psit.hasNext()) { 16309 PackageSetting ps = psit.next(); 16310 if (ps.pkg == null) { 16311 continue; 16312 } 16313 final String packageName = ps.pkg.packageName; 16314 // Skip over if system app 16315 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16316 continue; 16317 } 16318 if (DEBUG_CLEAN_APKS) { 16319 Slog.i(TAG, "Checking package " + packageName); 16320 } 16321 boolean keep = false; 16322 for (int i = 0; i < users.length; i++) { 16323 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16324 keep = true; 16325 if (DEBUG_CLEAN_APKS) { 16326 Slog.i(TAG, " Keeping package " + packageName + " for user " 16327 + users[i]); 16328 } 16329 break; 16330 } 16331 } 16332 if (!keep) { 16333 if (DEBUG_CLEAN_APKS) { 16334 Slog.i(TAG, " Removing package " + packageName); 16335 } 16336 mHandler.post(new Runnable() { 16337 public void run() { 16338 deletePackageX(packageName, userHandle, 0); 16339 } //end run 16340 }); 16341 } 16342 } 16343 } 16344 16345 /** Called by UserManagerService */ 16346 void createNewUserLILPw(int userHandle) { 16347 if (mInstaller != null) { 16348 mInstaller.createUserConfig(userHandle); 16349 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16350 applyFactoryDefaultBrowserLPw(userHandle); 16351 primeDomainVerificationsLPw(userHandle); 16352 } 16353 } 16354 16355 void newUserCreated(final int userHandle) { 16356 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16357 } 16358 16359 @Override 16360 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16361 mContext.enforceCallingOrSelfPermission( 16362 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16363 "Only package verification agents can read the verifier device identity"); 16364 16365 synchronized (mPackages) { 16366 return mSettings.getVerifierDeviceIdentityLPw(); 16367 } 16368 } 16369 16370 @Override 16371 public void setPermissionEnforced(String permission, boolean enforced) { 16372 // TODO: Now that we no longer change GID for storage, this should to away. 16373 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16374 "setPermissionEnforced"); 16375 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16376 synchronized (mPackages) { 16377 if (mSettings.mReadExternalStorageEnforced == null 16378 || mSettings.mReadExternalStorageEnforced != enforced) { 16379 mSettings.mReadExternalStorageEnforced = enforced; 16380 mSettings.writeLPr(); 16381 } 16382 } 16383 // kill any non-foreground processes so we restart them and 16384 // grant/revoke the GID. 16385 final IActivityManager am = ActivityManagerNative.getDefault(); 16386 if (am != null) { 16387 final long token = Binder.clearCallingIdentity(); 16388 try { 16389 am.killProcessesBelowForeground("setPermissionEnforcement"); 16390 } catch (RemoteException e) { 16391 } finally { 16392 Binder.restoreCallingIdentity(token); 16393 } 16394 } 16395 } else { 16396 throw new IllegalArgumentException("No selective enforcement for " + permission); 16397 } 16398 } 16399 16400 @Override 16401 @Deprecated 16402 public boolean isPermissionEnforced(String permission) { 16403 return true; 16404 } 16405 16406 @Override 16407 public boolean isStorageLow() { 16408 final long token = Binder.clearCallingIdentity(); 16409 try { 16410 final DeviceStorageMonitorInternal 16411 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16412 if (dsm != null) { 16413 return dsm.isMemoryLow(); 16414 } else { 16415 return false; 16416 } 16417 } finally { 16418 Binder.restoreCallingIdentity(token); 16419 } 16420 } 16421 16422 @Override 16423 public IPackageInstaller getPackageInstaller() { 16424 return mInstallerService; 16425 } 16426 16427 private boolean userNeedsBadging(int userId) { 16428 int index = mUserNeedsBadging.indexOfKey(userId); 16429 if (index < 0) { 16430 final UserInfo userInfo; 16431 final long token = Binder.clearCallingIdentity(); 16432 try { 16433 userInfo = sUserManager.getUserInfo(userId); 16434 } finally { 16435 Binder.restoreCallingIdentity(token); 16436 } 16437 final boolean b; 16438 if (userInfo != null && userInfo.isManagedProfile()) { 16439 b = true; 16440 } else { 16441 b = false; 16442 } 16443 mUserNeedsBadging.put(userId, b); 16444 return b; 16445 } 16446 return mUserNeedsBadging.valueAt(index); 16447 } 16448 16449 @Override 16450 public KeySet getKeySetByAlias(String packageName, String alias) { 16451 if (packageName == null || alias == null) { 16452 return null; 16453 } 16454 synchronized(mPackages) { 16455 final PackageParser.Package pkg = mPackages.get(packageName); 16456 if (pkg == null) { 16457 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16458 throw new IllegalArgumentException("Unknown package: " + packageName); 16459 } 16460 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16461 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16462 } 16463 } 16464 16465 @Override 16466 public KeySet getSigningKeySet(String packageName) { 16467 if (packageName == null) { 16468 return null; 16469 } 16470 synchronized(mPackages) { 16471 final PackageParser.Package pkg = mPackages.get(packageName); 16472 if (pkg == null) { 16473 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16474 throw new IllegalArgumentException("Unknown package: " + packageName); 16475 } 16476 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16477 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16478 throw new SecurityException("May not access signing KeySet of other apps."); 16479 } 16480 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16481 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16482 } 16483 } 16484 16485 @Override 16486 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16487 if (packageName == null || ks == null) { 16488 return false; 16489 } 16490 synchronized(mPackages) { 16491 final PackageParser.Package pkg = mPackages.get(packageName); 16492 if (pkg == null) { 16493 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16494 throw new IllegalArgumentException("Unknown package: " + packageName); 16495 } 16496 IBinder ksh = ks.getToken(); 16497 if (ksh instanceof KeySetHandle) { 16498 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16499 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16500 } 16501 return false; 16502 } 16503 } 16504 16505 @Override 16506 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16507 if (packageName == null || ks == null) { 16508 return false; 16509 } 16510 synchronized(mPackages) { 16511 final PackageParser.Package pkg = mPackages.get(packageName); 16512 if (pkg == null) { 16513 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16514 throw new IllegalArgumentException("Unknown package: " + packageName); 16515 } 16516 IBinder ksh = ks.getToken(); 16517 if (ksh instanceof KeySetHandle) { 16518 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16519 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16520 } 16521 return false; 16522 } 16523 } 16524 16525 public void getUsageStatsIfNoPackageUsageInfo() { 16526 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16527 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16528 if (usm == null) { 16529 throw new IllegalStateException("UsageStatsManager must be initialized"); 16530 } 16531 long now = System.currentTimeMillis(); 16532 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16533 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16534 String packageName = entry.getKey(); 16535 PackageParser.Package pkg = mPackages.get(packageName); 16536 if (pkg == null) { 16537 continue; 16538 } 16539 UsageStats usage = entry.getValue(); 16540 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16541 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16542 } 16543 } 16544 } 16545 16546 /** 16547 * Check and throw if the given before/after packages would be considered a 16548 * downgrade. 16549 */ 16550 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16551 throws PackageManagerException { 16552 if (after.versionCode < before.mVersionCode) { 16553 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16554 "Update version code " + after.versionCode + " is older than current " 16555 + before.mVersionCode); 16556 } else if (after.versionCode == before.mVersionCode) { 16557 if (after.baseRevisionCode < before.baseRevisionCode) { 16558 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16559 "Update base revision code " + after.baseRevisionCode 16560 + " is older than current " + before.baseRevisionCode); 16561 } 16562 16563 if (!ArrayUtils.isEmpty(after.splitNames)) { 16564 for (int i = 0; i < after.splitNames.length; i++) { 16565 final String splitName = after.splitNames[i]; 16566 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16567 if (j != -1) { 16568 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16569 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16570 "Update split " + splitName + " revision code " 16571 + after.splitRevisionCodes[i] + " is older than current " 16572 + before.splitRevisionCodes[j]); 16573 } 16574 } 16575 } 16576 } 16577 } 16578 } 16579 16580 private static class MoveCallbacks extends Handler { 16581 private static final int MSG_CREATED = 1; 16582 private static final int MSG_STATUS_CHANGED = 2; 16583 16584 private final RemoteCallbackList<IPackageMoveObserver> 16585 mCallbacks = new RemoteCallbackList<>(); 16586 16587 private final SparseIntArray mLastStatus = new SparseIntArray(); 16588 16589 public MoveCallbacks(Looper looper) { 16590 super(looper); 16591 } 16592 16593 public void register(IPackageMoveObserver callback) { 16594 mCallbacks.register(callback); 16595 } 16596 16597 public void unregister(IPackageMoveObserver callback) { 16598 mCallbacks.unregister(callback); 16599 } 16600 16601 @Override 16602 public void handleMessage(Message msg) { 16603 final SomeArgs args = (SomeArgs) msg.obj; 16604 final int n = mCallbacks.beginBroadcast(); 16605 for (int i = 0; i < n; i++) { 16606 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16607 try { 16608 invokeCallback(callback, msg.what, args); 16609 } catch (RemoteException ignored) { 16610 } 16611 } 16612 mCallbacks.finishBroadcast(); 16613 args.recycle(); 16614 } 16615 16616 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16617 throws RemoteException { 16618 switch (what) { 16619 case MSG_CREATED: { 16620 callback.onCreated(args.argi1, (Bundle) args.arg2); 16621 break; 16622 } 16623 case MSG_STATUS_CHANGED: { 16624 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16625 break; 16626 } 16627 } 16628 } 16629 16630 private void notifyCreated(int moveId, Bundle extras) { 16631 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16632 16633 final SomeArgs args = SomeArgs.obtain(); 16634 args.argi1 = moveId; 16635 args.arg2 = extras; 16636 obtainMessage(MSG_CREATED, args).sendToTarget(); 16637 } 16638 16639 private void notifyStatusChanged(int moveId, int status) { 16640 notifyStatusChanged(moveId, status, -1); 16641 } 16642 16643 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16644 Slog.v(TAG, "Move " + moveId + " status " + status); 16645 16646 final SomeArgs args = SomeArgs.obtain(); 16647 args.argi1 = moveId; 16648 args.argi2 = status; 16649 args.arg3 = estMillis; 16650 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16651 16652 synchronized (mLastStatus) { 16653 mLastStatus.put(moveId, status); 16654 } 16655 } 16656 } 16657 16658 private final class OnPermissionChangeListeners extends Handler { 16659 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16660 16661 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16662 new RemoteCallbackList<>(); 16663 16664 public OnPermissionChangeListeners(Looper looper) { 16665 super(looper); 16666 } 16667 16668 @Override 16669 public void handleMessage(Message msg) { 16670 switch (msg.what) { 16671 case MSG_ON_PERMISSIONS_CHANGED: { 16672 final int uid = msg.arg1; 16673 handleOnPermissionsChanged(uid); 16674 } break; 16675 } 16676 } 16677 16678 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16679 mPermissionListeners.register(listener); 16680 16681 } 16682 16683 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16684 mPermissionListeners.unregister(listener); 16685 } 16686 16687 public void onPermissionsChanged(int uid) { 16688 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16689 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16690 } 16691 } 16692 16693 private void handleOnPermissionsChanged(int uid) { 16694 final int count = mPermissionListeners.beginBroadcast(); 16695 try { 16696 for (int i = 0; i < count; i++) { 16697 IOnPermissionsChangeListener callback = mPermissionListeners 16698 .getBroadcastItem(i); 16699 try { 16700 callback.onPermissionsChanged(uid); 16701 } catch (RemoteException e) { 16702 Log.e(TAG, "Permission listener is dead", e); 16703 } 16704 } 16705 } finally { 16706 mPermissionListeners.finishBroadcast(); 16707 } 16708 } 16709 } 16710 16711 private class PackageManagerInternalImpl extends PackageManagerInternal { 16712 @Override 16713 public void setLocationPackagesProvider(PackagesProvider provider) { 16714 synchronized (mPackages) { 16715 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16716 } 16717 } 16718 16719 @Override 16720 public void setImePackagesProvider(PackagesProvider provider) { 16721 synchronized (mPackages) { 16722 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16723 } 16724 } 16725 16726 @Override 16727 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16728 synchronized (mPackages) { 16729 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16730 } 16731 } 16732 16733 @Override 16734 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16735 synchronized (mPackages) { 16736 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16737 } 16738 } 16739 16740 @Override 16741 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16742 synchronized (mPackages) { 16743 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16744 } 16745 } 16746 16747 @Override 16748 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16749 synchronized (mPackages) { 16750 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16751 } 16752 } 16753 16754 @Override 16755 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16756 synchronized (mPackages) { 16757 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16758 } 16759 } 16760 16761 @Override 16762 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16763 synchronized (mPackages) { 16764 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16765 packageName, userId); 16766 } 16767 } 16768 16769 @Override 16770 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16771 synchronized (mPackages) { 16772 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16773 packageName, userId); 16774 } 16775 } 16776 @Override 16777 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16778 synchronized (mPackages) { 16779 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16780 packageName, userId); 16781 } 16782 } 16783 } 16784 16785 @Override 16786 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16787 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16788 synchronized (mPackages) { 16789 final long identity = Binder.clearCallingIdentity(); 16790 try { 16791 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16792 packageNames, userId); 16793 } finally { 16794 Binder.restoreCallingIdentity(identity); 16795 } 16796 } 16797 } 16798 16799 private static void enforceSystemOrPhoneCaller(String tag) { 16800 int callingUid = Binder.getCallingUid(); 16801 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16802 throw new SecurityException( 16803 "Cannot call " + tag + " from UID " + callingUid); 16804 } 16805 } 16806} 16807