PackageManagerService.java revision 2fee91c5683d4f3e89c9bd2485207044ab495f43
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.MATCH_ALL; 60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 64import static android.content.pm.PackageManager.PERMISSION_DENIED; 65import static android.content.pm.PackageManager.PERMISSION_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 70import static android.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 85 86import android.Manifest; 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IOnPermissionsChangeListener; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.IntentFilterVerificationInfo; 118import android.content.pm.KeySet; 119import android.content.pm.ManifestDigest; 120import android.content.pm.PackageCleanItem; 121import android.content.pm.PackageInfo; 122import android.content.pm.PackageInfoLite; 123import android.content.pm.PackageInstaller; 124import android.content.pm.PackageManager; 125import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 126import android.content.pm.PackageManagerInternal; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageStats; 132import android.content.pm.PackageUserState; 133import android.content.pm.ParceledListSlice; 134import android.content.pm.PermissionGroupInfo; 135import android.content.pm.PermissionInfo; 136import android.content.pm.ProviderInfo; 137import android.content.pm.ResolveInfo; 138import android.content.pm.ServiceInfo; 139import android.content.pm.Signature; 140import android.content.pm.UserInfo; 141import android.content.pm.VerificationParams; 142import android.content.pm.VerifierDeviceIdentity; 143import android.content.pm.VerifierInfo; 144import android.content.res.Resources; 145import android.hardware.display.DisplayManager; 146import android.net.Uri; 147import android.os.Debug; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteCallbackList; 162import android.os.RemoteException; 163import android.os.SELinux; 164import android.os.ServiceManager; 165import android.os.SystemClock; 166import android.os.SystemProperties; 167import android.os.Trace; 168import android.os.UserHandle; 169import android.os.UserManager; 170import android.os.storage.IMountService; 171import android.os.storage.MountServiceInternal; 172import android.os.storage.StorageEventListener; 173import android.os.storage.StorageManager; 174import android.os.storage.VolumeInfo; 175import android.os.storage.VolumeRecord; 176import android.security.KeyStore; 177import android.security.SystemKeyStore; 178import android.system.ErrnoException; 179import android.system.Os; 180import android.system.StructStat; 181import android.text.TextUtils; 182import android.text.format.DateUtils; 183import android.util.ArrayMap; 184import android.util.ArraySet; 185import android.util.AtomicFile; 186import android.util.DisplayMetrics; 187import android.util.EventLog; 188import android.util.ExceptionUtils; 189import android.util.Log; 190import android.util.LogPrinter; 191import android.util.MathUtils; 192import android.util.PrintStreamPrinter; 193import android.util.Slog; 194import android.util.SparseArray; 195import android.util.SparseBooleanArray; 196import android.util.SparseIntArray; 197import android.util.Xml; 198import android.view.Display; 199 200import dalvik.system.DexFile; 201import dalvik.system.VMRuntime; 202 203import libcore.io.IoUtils; 204import libcore.util.EmptyArray; 205 206import com.android.internal.R; 207import com.android.internal.annotations.GuardedBy; 208import com.android.internal.app.IMediaContainerService; 209import com.android.internal.app.ResolverActivity; 210import com.android.internal.content.NativeLibraryHelper; 211import com.android.internal.content.PackageHelper; 212import com.android.internal.os.IParcelFileDescriptorFactory; 213import com.android.internal.os.SomeArgs; 214import com.android.internal.os.Zygote; 215import com.android.internal.util.ArrayUtils; 216import com.android.internal.util.FastPrintWriter; 217import com.android.internal.util.FastXmlSerializer; 218import com.android.internal.util.IndentingPrintWriter; 219import com.android.internal.util.Preconditions; 220import com.android.server.EventLogTags; 221import com.android.server.FgThread; 222import com.android.server.IntentResolver; 223import com.android.server.LocalServices; 224import com.android.server.ServiceThread; 225import com.android.server.SystemConfig; 226import com.android.server.Watchdog; 227import com.android.server.pm.PermissionsState.PermissionState; 228import com.android.server.pm.Settings.DatabaseVersion; 229import com.android.server.pm.Settings.VersionInfo; 230import com.android.server.storage.DeviceStorageMonitorInternal; 231 232import org.xmlpull.v1.XmlPullParser; 233import org.xmlpull.v1.XmlPullParserException; 234import org.xmlpull.v1.XmlSerializer; 235 236import java.io.BufferedInputStream; 237import java.io.BufferedOutputStream; 238import java.io.BufferedReader; 239import java.io.ByteArrayInputStream; 240import java.io.ByteArrayOutputStream; 241import java.io.File; 242import java.io.FileDescriptor; 243import java.io.FileNotFoundException; 244import java.io.FileOutputStream; 245import java.io.FileReader; 246import java.io.FilenameFilter; 247import java.io.IOException; 248import java.io.InputStream; 249import java.io.PrintWriter; 250import java.nio.charset.StandardCharsets; 251import java.security.NoSuchAlgorithmException; 252import java.security.PublicKey; 253import java.security.cert.CertificateEncodingException; 254import java.security.cert.CertificateException; 255import java.text.SimpleDateFormat; 256import java.util.ArrayList; 257import java.util.Arrays; 258import java.util.Collection; 259import java.util.Collections; 260import java.util.Comparator; 261import java.util.Date; 262import java.util.Iterator; 263import java.util.List; 264import java.util.Map; 265import java.util.Objects; 266import java.util.Set; 267import java.util.concurrent.CountDownLatch; 268import java.util.concurrent.TimeUnit; 269import java.util.concurrent.atomic.AtomicBoolean; 270import java.util.concurrent.atomic.AtomicInteger; 271import java.util.concurrent.atomic.AtomicLong; 272 273/** 274 * Keep track of all those .apks everywhere. 275 * 276 * This is very central to the platform's security; please run the unit 277 * tests whenever making modifications here: 278 * 279runtest -c android.content.pm.PackageManagerTests frameworks-core 280 * 281 * {@hide} 282 */ 283public class PackageManagerService extends IPackageManager.Stub { 284 static final String TAG = "PackageManager"; 285 static final boolean DEBUG_SETTINGS = false; 286 static final boolean DEBUG_PREFERRED = false; 287 static final boolean DEBUG_UPGRADE = false; 288 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 289 private static final boolean DEBUG_BACKUP = false; 290 private static final boolean DEBUG_INSTALL = false; 291 private static final boolean DEBUG_REMOVE = false; 292 private static final boolean DEBUG_BROADCASTS = false; 293 private static final boolean DEBUG_SHOW_INFO = false; 294 private static final boolean DEBUG_PACKAGE_INFO = false; 295 private static final boolean DEBUG_INTENT_MATCHING = false; 296 private static final boolean DEBUG_PACKAGE_SCANNING = false; 297 private static final boolean DEBUG_VERIFY = false; 298 private static final boolean DEBUG_DEXOPT = false; 299 private static final boolean DEBUG_ABI_SELECTION = false; 300 301 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 302 303 private static final int RADIO_UID = Process.PHONE_UID; 304 private static final int LOG_UID = Process.LOG_UID; 305 private static final int NFC_UID = Process.NFC_UID; 306 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 307 private static final int SHELL_UID = Process.SHELL_UID; 308 309 // Cap the size of permission trees that 3rd party apps can define 310 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 311 312 // Suffix used during package installation when copying/moving 313 // package apks to install directory. 314 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 315 316 static final int SCAN_NO_DEX = 1<<1; 317 static final int SCAN_FORCE_DEX = 1<<2; 318 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 319 static final int SCAN_NEW_INSTALL = 1<<4; 320 static final int SCAN_NO_PATHS = 1<<5; 321 static final int SCAN_UPDATE_TIME = 1<<6; 322 static final int SCAN_DEFER_DEX = 1<<7; 323 static final int SCAN_BOOTING = 1<<8; 324 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 325 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 326 static final int SCAN_REPLACING = 1<<11; 327 static final int SCAN_REQUIRE_KNOWN = 1<<12; 328 static final int SCAN_MOVE = 1<<13; 329 static final int SCAN_INITIAL = 1<<14; 330 331 static final int REMOVE_CHATTY = 1<<16; 332 333 private static final int[] EMPTY_INT_ARRAY = new int[0]; 334 335 /** 336 * Timeout (in milliseconds) after which the watchdog should declare that 337 * our handler thread is wedged. The usual default for such things is one 338 * minute but we sometimes do very lengthy I/O operations on this thread, 339 * such as installing multi-gigabyte applications, so ours needs to be longer. 340 */ 341 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 342 343 /** 344 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 345 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 346 * settings entry if available, otherwise we use the hardcoded default. If it's been 347 * more than this long since the last fstrim, we force one during the boot sequence. 348 * 349 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 350 * one gets run at the next available charging+idle time. This final mandatory 351 * no-fstrim check kicks in only of the other scheduling criteria is never met. 352 */ 353 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 354 355 /** 356 * Whether verification is enabled by default. 357 */ 358 private static final boolean DEFAULT_VERIFY_ENABLE = true; 359 360 /** 361 * The default maximum time to wait for the verification agent to return in 362 * milliseconds. 363 */ 364 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 365 366 /** 367 * The default response for package verification timeout. 368 * 369 * This can be either PackageManager.VERIFICATION_ALLOW or 370 * PackageManager.VERIFICATION_REJECT. 371 */ 372 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 373 374 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 375 376 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 377 DEFAULT_CONTAINER_PACKAGE, 378 "com.android.defcontainer.DefaultContainerService"); 379 380 private static final String KILL_APP_REASON_GIDS_CHANGED = 381 "permission grant or revoke changed gids"; 382 383 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 384 "permissions revoked"; 385 386 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 387 388 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 389 390 /** Permission grant: not grant the permission. */ 391 private static final int GRANT_DENIED = 1; 392 393 /** Permission grant: grant the permission as an install permission. */ 394 private static final int GRANT_INSTALL = 2; 395 396 /** Permission grant: grant the permission as an install permission for a legacy app. */ 397 private static final int GRANT_INSTALL_LEGACY = 3; 398 399 /** Permission grant: grant the permission as a runtime one. */ 400 private static final int GRANT_RUNTIME = 4; 401 402 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 403 private static final int GRANT_UPGRADE = 5; 404 405 /** Canonical intent used to identify what counts as a "web browser" app */ 406 private static final Intent sBrowserIntent; 407 static { 408 sBrowserIntent = new Intent(); 409 sBrowserIntent.setAction(Intent.ACTION_VIEW); 410 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 411 sBrowserIntent.setData(Uri.parse("http:")); 412 } 413 414 final ServiceThread mHandlerThread; 415 416 final PackageHandler mHandler; 417 418 /** 419 * Messages for {@link #mHandler} that need to wait for system ready before 420 * being dispatched. 421 */ 422 private ArrayList<Message> mPostSystemReadyMessages; 423 424 final int mSdkVersion = Build.VERSION.SDK_INT; 425 426 final Context mContext; 427 final boolean mFactoryTest; 428 final boolean mOnlyCore; 429 final boolean mLazyDexOpt; 430 final long mDexOptLRUThresholdInMills; 431 final DisplayMetrics mMetrics; 432 final int mDefParseFlags; 433 final String[] mSeparateProcesses; 434 final boolean mIsUpgrade; 435 436 // This is where all application persistent data goes. 437 final File mAppDataDir; 438 439 // This is where all application persistent data goes for secondary users. 440 final File mUserAppDataDir; 441 442 /** The location for ASEC container files on internal storage. */ 443 final String mAsecInternalPath; 444 445 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 446 // LOCK HELD. Can be called with mInstallLock held. 447 @GuardedBy("mInstallLock") 448 final Installer mInstaller; 449 450 /** Directory where installed third-party apps stored */ 451 final File mAppInstallDir; 452 453 /** 454 * Directory to which applications installed internally have their 455 * 32 bit native libraries copied. 456 */ 457 private File mAppLib32InstallDir; 458 459 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 460 // apps. 461 final File mDrmAppPrivateInstallDir; 462 463 // ---------------------------------------------------------------- 464 465 // Lock for state used when installing and doing other long running 466 // operations. Methods that must be called with this lock held have 467 // the suffix "LI". 468 final Object mInstallLock = new Object(); 469 470 // ---------------------------------------------------------------- 471 472 // Keys are String (package name), values are Package. This also serves 473 // as the lock for the global state. Methods that must be called with 474 // this lock held have the prefix "LP". 475 @GuardedBy("mPackages") 476 final ArrayMap<String, PackageParser.Package> mPackages = 477 new ArrayMap<String, PackageParser.Package>(); 478 479 // Tracks available target package names -> overlay package paths. 480 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 481 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 482 483 /** 484 * Tracks new system packages [received in an OTA] that we expect to 485 * find updated user-installed versions. Keys are package name, values 486 * are package location. 487 */ 488 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 489 490 /** 491 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 492 */ 493 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 494 /** 495 * Whether or not system app permissions should be promoted from install to runtime. 496 */ 497 boolean mPromoteSystemApps; 498 499 final Settings mSettings; 500 boolean mRestoredSettings; 501 502 // System configuration read by SystemConfig. 503 final int[] mGlobalGids; 504 final SparseArray<ArraySet<String>> mSystemPermissions; 505 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 506 507 // If mac_permissions.xml was found for seinfo labeling. 508 boolean mFoundPolicyFile; 509 510 // If a recursive restorecon of /data/data/<pkg> is needed. 511 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 512 513 public static final class SharedLibraryEntry { 514 public final String path; 515 public final String apk; 516 517 SharedLibraryEntry(String _path, String _apk) { 518 path = _path; 519 apk = _apk; 520 } 521 } 522 523 // Currently known shared libraries. 524 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 525 new ArrayMap<String, SharedLibraryEntry>(); 526 527 // All available activities, for your resolving pleasure. 528 final ActivityIntentResolver mActivities = 529 new ActivityIntentResolver(); 530 531 // All available receivers, for your resolving pleasure. 532 final ActivityIntentResolver mReceivers = 533 new ActivityIntentResolver(); 534 535 // All available services, for your resolving pleasure. 536 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 537 538 // All available providers, for your resolving pleasure. 539 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 540 541 // Mapping from provider base names (first directory in content URI codePath) 542 // to the provider information. 543 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 544 new ArrayMap<String, PackageParser.Provider>(); 545 546 // Mapping from instrumentation class names to info about them. 547 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 548 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 549 550 // Mapping from permission names to info about them. 551 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 552 new ArrayMap<String, PackageParser.PermissionGroup>(); 553 554 // Packages whose data we have transfered into another package, thus 555 // should no longer exist. 556 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 557 558 // Broadcast actions that are only available to the system. 559 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 560 561 /** List of packages waiting for verification. */ 562 final SparseArray<PackageVerificationState> mPendingVerification 563 = new SparseArray<PackageVerificationState>(); 564 565 /** Set of packages associated with each app op permission. */ 566 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 567 568 final PackageInstallerService mInstallerService; 569 570 private final PackageDexOptimizer mPackageDexOptimizer; 571 572 private AtomicInteger mNextMoveId = new AtomicInteger(); 573 private final MoveCallbacks mMoveCallbacks; 574 575 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 576 577 // Cache of users who need badging. 578 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 579 580 /** Token for keys in mPendingVerification. */ 581 private int mPendingVerificationToken = 0; 582 583 volatile boolean mSystemReady; 584 volatile boolean mSafeMode; 585 volatile boolean mHasSystemUidErrors; 586 587 ApplicationInfo mAndroidApplication; 588 final ActivityInfo mResolveActivity = new ActivityInfo(); 589 final ResolveInfo mResolveInfo = new ResolveInfo(); 590 ComponentName mResolveComponentName; 591 PackageParser.Package mPlatformPackage; 592 ComponentName mCustomResolverComponentName; 593 594 boolean mResolverReplaced = false; 595 596 private final ComponentName mIntentFilterVerifierComponent; 597 private int mIntentFilterVerificationToken = 0; 598 599 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 600 = new SparseArray<IntentFilterVerificationState>(); 601 602 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 603 new DefaultPermissionGrantPolicy(this); 604 605 private static class IFVerificationParams { 606 PackageParser.Package pkg; 607 boolean replacing; 608 int userId; 609 int verifierUid; 610 611 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 612 int _userId, int _verifierUid) { 613 pkg = _pkg; 614 replacing = _replacing; 615 userId = _userId; 616 replacing = _replacing; 617 verifierUid = _verifierUid; 618 } 619 } 620 621 private interface IntentFilterVerifier<T extends IntentFilter> { 622 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 623 T filter, String packageName); 624 void startVerifications(int userId); 625 void receiveVerificationResponse(int verificationId); 626 } 627 628 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 629 private Context mContext; 630 private ComponentName mIntentFilterVerifierComponent; 631 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 632 633 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 634 mContext = context; 635 mIntentFilterVerifierComponent = verifierComponent; 636 } 637 638 private String getDefaultScheme() { 639 return IntentFilter.SCHEME_HTTPS; 640 } 641 642 @Override 643 public void startVerifications(int userId) { 644 // Launch verifications requests 645 int count = mCurrentIntentFilterVerifications.size(); 646 for (int n=0; n<count; n++) { 647 int verificationId = mCurrentIntentFilterVerifications.get(n); 648 final IntentFilterVerificationState ivs = 649 mIntentFilterVerificationStates.get(verificationId); 650 651 String packageName = ivs.getPackageName(); 652 653 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 654 final int filterCount = filters.size(); 655 ArraySet<String> domainsSet = new ArraySet<>(); 656 for (int m=0; m<filterCount; m++) { 657 PackageParser.ActivityIntentInfo filter = filters.get(m); 658 domainsSet.addAll(filter.getHostsList()); 659 } 660 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 661 synchronized (mPackages) { 662 if (mSettings.createIntentFilterVerificationIfNeededLPw( 663 packageName, domainsList) != null) { 664 scheduleWriteSettingsLocked(); 665 } 666 } 667 sendVerificationRequest(userId, verificationId, ivs); 668 } 669 mCurrentIntentFilterVerifications.clear(); 670 } 671 672 private void sendVerificationRequest(int userId, int verificationId, 673 IntentFilterVerificationState ivs) { 674 675 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 676 verificationIntent.putExtra( 677 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 678 verificationId); 679 verificationIntent.putExtra( 680 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 681 getDefaultScheme()); 682 verificationIntent.putExtra( 683 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 684 ivs.getHostsString()); 685 verificationIntent.putExtra( 686 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 687 ivs.getPackageName()); 688 verificationIntent.setComponent(mIntentFilterVerifierComponent); 689 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 690 691 UserHandle user = new UserHandle(userId); 692 mContext.sendBroadcastAsUser(verificationIntent, user); 693 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 694 "Sending IntentFilter verification broadcast"); 695 } 696 697 public void receiveVerificationResponse(int verificationId) { 698 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 699 700 final boolean verified = ivs.isVerified(); 701 702 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 703 final int count = filters.size(); 704 if (DEBUG_DOMAIN_VERIFICATION) { 705 Slog.i(TAG, "Received verification response " + verificationId 706 + " for " + count + " filters, verified=" + verified); 707 } 708 for (int n=0; n<count; n++) { 709 PackageParser.ActivityIntentInfo filter = filters.get(n); 710 filter.setVerified(verified); 711 712 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 713 + " verified with result:" + verified + " and hosts:" 714 + ivs.getHostsString()); 715 } 716 717 mIntentFilterVerificationStates.remove(verificationId); 718 719 final String packageName = ivs.getPackageName(); 720 IntentFilterVerificationInfo ivi = null; 721 722 synchronized (mPackages) { 723 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 724 } 725 if (ivi == null) { 726 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 727 + verificationId + " packageName:" + packageName); 728 return; 729 } 730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 731 "Updating IntentFilterVerificationInfo for package " + packageName 732 +" verificationId:" + verificationId); 733 734 synchronized (mPackages) { 735 if (verified) { 736 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 737 } else { 738 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 739 } 740 scheduleWriteSettingsLocked(); 741 742 final int userId = ivs.getUserId(); 743 if (userId != UserHandle.USER_ALL) { 744 final int userStatus = 745 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 746 747 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 748 boolean needUpdate = false; 749 750 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 751 // already been set by the User thru the Disambiguation dialog 752 switch (userStatus) { 753 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 754 if (verified) { 755 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 756 } else { 757 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 758 } 759 needUpdate = true; 760 break; 761 762 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 763 if (verified) { 764 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 765 needUpdate = true; 766 } 767 break; 768 769 default: 770 // Nothing to do 771 } 772 773 if (needUpdate) { 774 mSettings.updateIntentFilterVerificationStatusLPw( 775 packageName, updatedStatus, userId); 776 scheduleWritePackageRestrictionsLocked(userId); 777 } 778 } 779 } 780 } 781 782 @Override 783 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 784 ActivityIntentInfo filter, String packageName) { 785 if (!hasValidDomains(filter)) { 786 return false; 787 } 788 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 789 if (ivs == null) { 790 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 791 packageName); 792 } 793 if (DEBUG_DOMAIN_VERIFICATION) { 794 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 795 } 796 ivs.addFilter(filter); 797 return true; 798 } 799 800 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 801 int userId, int verificationId, String packageName) { 802 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 803 verifierUid, userId, packageName); 804 ivs.setPendingState(); 805 synchronized (mPackages) { 806 mIntentFilterVerificationStates.append(verificationId, ivs); 807 mCurrentIntentFilterVerifications.add(verificationId); 808 } 809 return ivs; 810 } 811 } 812 813 private static boolean hasValidDomains(ActivityIntentInfo filter) { 814 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 815 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 816 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 817 } 818 819 private IntentFilterVerifier mIntentFilterVerifier; 820 821 // Set of pending broadcasts for aggregating enable/disable of components. 822 static class PendingPackageBroadcasts { 823 // for each user id, a map of <package name -> components within that package> 824 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 825 826 public PendingPackageBroadcasts() { 827 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 828 } 829 830 public ArrayList<String> get(int userId, String packageName) { 831 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 832 return packages.get(packageName); 833 } 834 835 public void put(int userId, String packageName, ArrayList<String> components) { 836 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 837 packages.put(packageName, components); 838 } 839 840 public void remove(int userId, String packageName) { 841 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 842 if (packages != null) { 843 packages.remove(packageName); 844 } 845 } 846 847 public void remove(int userId) { 848 mUidMap.remove(userId); 849 } 850 851 public int userIdCount() { 852 return mUidMap.size(); 853 } 854 855 public int userIdAt(int n) { 856 return mUidMap.keyAt(n); 857 } 858 859 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 860 return mUidMap.get(userId); 861 } 862 863 public int size() { 864 // total number of pending broadcast entries across all userIds 865 int num = 0; 866 for (int i = 0; i< mUidMap.size(); i++) { 867 num += mUidMap.valueAt(i).size(); 868 } 869 return num; 870 } 871 872 public void clear() { 873 mUidMap.clear(); 874 } 875 876 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 877 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 878 if (map == null) { 879 map = new ArrayMap<String, ArrayList<String>>(); 880 mUidMap.put(userId, map); 881 } 882 return map; 883 } 884 } 885 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 886 887 // Service Connection to remote media container service to copy 888 // package uri's from external media onto secure containers 889 // or internal storage. 890 private IMediaContainerService mContainerService = null; 891 892 static final int SEND_PENDING_BROADCAST = 1; 893 static final int MCS_BOUND = 3; 894 static final int END_COPY = 4; 895 static final int INIT_COPY = 5; 896 static final int MCS_UNBIND = 6; 897 static final int START_CLEANING_PACKAGE = 7; 898 static final int FIND_INSTALL_LOC = 8; 899 static final int POST_INSTALL = 9; 900 static final int MCS_RECONNECT = 10; 901 static final int MCS_GIVE_UP = 11; 902 static final int UPDATED_MEDIA_STATUS = 12; 903 static final int WRITE_SETTINGS = 13; 904 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 905 static final int PACKAGE_VERIFIED = 15; 906 static final int CHECK_PENDING_VERIFICATION = 16; 907 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 908 static final int INTENT_FILTER_VERIFIED = 18; 909 910 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 911 912 // Delay time in millisecs 913 static final int BROADCAST_DELAY = 10 * 1000; 914 915 static UserManagerService sUserManager; 916 917 // Stores a list of users whose package restrictions file needs to be updated 918 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 919 920 final private DefaultContainerConnection mDefContainerConn = 921 new DefaultContainerConnection(); 922 class DefaultContainerConnection implements ServiceConnection { 923 public void onServiceConnected(ComponentName name, IBinder service) { 924 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 925 IMediaContainerService imcs = 926 IMediaContainerService.Stub.asInterface(service); 927 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 928 } 929 930 public void onServiceDisconnected(ComponentName name) { 931 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 932 } 933 } 934 935 // Recordkeeping of restore-after-install operations that are currently in flight 936 // between the Package Manager and the Backup Manager 937 class PostInstallData { 938 public InstallArgs args; 939 public PackageInstalledInfo res; 940 941 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 942 args = _a; 943 res = _r; 944 } 945 } 946 947 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 948 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 949 950 // XML tags for backup/restore of various bits of state 951 private static final String TAG_PREFERRED_BACKUP = "pa"; 952 private static final String TAG_DEFAULT_APPS = "da"; 953 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 954 955 final String mRequiredVerifierPackage; 956 final String mRequiredInstallerPackage; 957 958 private final PackageUsage mPackageUsage = new PackageUsage(); 959 960 private class PackageUsage { 961 private static final int WRITE_INTERVAL 962 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 963 964 private final Object mFileLock = new Object(); 965 private final AtomicLong mLastWritten = new AtomicLong(0); 966 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 967 968 private boolean mIsHistoricalPackageUsageAvailable = true; 969 970 boolean isHistoricalPackageUsageAvailable() { 971 return mIsHistoricalPackageUsageAvailable; 972 } 973 974 void write(boolean force) { 975 if (force) { 976 writeInternal(); 977 return; 978 } 979 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 980 && !DEBUG_DEXOPT) { 981 return; 982 } 983 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 984 new Thread("PackageUsage_DiskWriter") { 985 @Override 986 public void run() { 987 try { 988 writeInternal(); 989 } finally { 990 mBackgroundWriteRunning.set(false); 991 } 992 } 993 }.start(); 994 } 995 } 996 997 private void writeInternal() { 998 synchronized (mPackages) { 999 synchronized (mFileLock) { 1000 AtomicFile file = getFile(); 1001 FileOutputStream f = null; 1002 try { 1003 f = file.startWrite(); 1004 BufferedOutputStream out = new BufferedOutputStream(f); 1005 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1006 StringBuilder sb = new StringBuilder(); 1007 for (PackageParser.Package pkg : mPackages.values()) { 1008 if (pkg.mLastPackageUsageTimeInMills == 0) { 1009 continue; 1010 } 1011 sb.setLength(0); 1012 sb.append(pkg.packageName); 1013 sb.append(' '); 1014 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1015 sb.append('\n'); 1016 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1017 } 1018 out.flush(); 1019 file.finishWrite(f); 1020 } catch (IOException e) { 1021 if (f != null) { 1022 file.failWrite(f); 1023 } 1024 Log.e(TAG, "Failed to write package usage times", e); 1025 } 1026 } 1027 } 1028 mLastWritten.set(SystemClock.elapsedRealtime()); 1029 } 1030 1031 void readLP() { 1032 synchronized (mFileLock) { 1033 AtomicFile file = getFile(); 1034 BufferedInputStream in = null; 1035 try { 1036 in = new BufferedInputStream(file.openRead()); 1037 StringBuffer sb = new StringBuffer(); 1038 while (true) { 1039 String packageName = readToken(in, sb, ' '); 1040 if (packageName == null) { 1041 break; 1042 } 1043 String timeInMillisString = readToken(in, sb, '\n'); 1044 if (timeInMillisString == null) { 1045 throw new IOException("Failed to find last usage time for package " 1046 + packageName); 1047 } 1048 PackageParser.Package pkg = mPackages.get(packageName); 1049 if (pkg == null) { 1050 continue; 1051 } 1052 long timeInMillis; 1053 try { 1054 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1055 } catch (NumberFormatException e) { 1056 throw new IOException("Failed to parse " + timeInMillisString 1057 + " as a long.", e); 1058 } 1059 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1060 } 1061 } catch (FileNotFoundException expected) { 1062 mIsHistoricalPackageUsageAvailable = false; 1063 } catch (IOException e) { 1064 Log.w(TAG, "Failed to read package usage times", e); 1065 } finally { 1066 IoUtils.closeQuietly(in); 1067 } 1068 } 1069 mLastWritten.set(SystemClock.elapsedRealtime()); 1070 } 1071 1072 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1073 throws IOException { 1074 sb.setLength(0); 1075 while (true) { 1076 int ch = in.read(); 1077 if (ch == -1) { 1078 if (sb.length() == 0) { 1079 return null; 1080 } 1081 throw new IOException("Unexpected EOF"); 1082 } 1083 if (ch == endOfToken) { 1084 return sb.toString(); 1085 } 1086 sb.append((char)ch); 1087 } 1088 } 1089 1090 private AtomicFile getFile() { 1091 File dataDir = Environment.getDataDirectory(); 1092 File systemDir = new File(dataDir, "system"); 1093 File fname = new File(systemDir, "package-usage.list"); 1094 return new AtomicFile(fname); 1095 } 1096 } 1097 1098 class PackageHandler extends Handler { 1099 private boolean mBound = false; 1100 final ArrayList<HandlerParams> mPendingInstalls = 1101 new ArrayList<HandlerParams>(); 1102 1103 private boolean connectToService() { 1104 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1105 " DefaultContainerService"); 1106 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1107 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1108 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1109 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1111 mBound = true; 1112 return true; 1113 } 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 return false; 1116 } 1117 1118 private void disconnectService() { 1119 mContainerService = null; 1120 mBound = false; 1121 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1122 mContext.unbindService(mDefContainerConn); 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1124 } 1125 1126 PackageHandler(Looper looper) { 1127 super(looper); 1128 } 1129 1130 public void handleMessage(Message msg) { 1131 try { 1132 doHandleMessage(msg); 1133 } finally { 1134 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1135 } 1136 } 1137 1138 void doHandleMessage(Message msg) { 1139 switch (msg.what) { 1140 case INIT_COPY: { 1141 HandlerParams params = (HandlerParams) msg.obj; 1142 int idx = mPendingInstalls.size(); 1143 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1144 // If a bind was already initiated we dont really 1145 // need to do anything. The pending install 1146 // will be processed later on. 1147 if (!mBound) { 1148 try { 1149 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1150 System.identityHashCode(params)); 1151 // If this is the only one pending we might 1152 // have to bind to the service again. 1153 if (!connectToService()) { 1154 Slog.e(TAG, "Failed to bind to media container service"); 1155 params.serviceError(); 1156 return; 1157 } else { 1158 // Once we bind to the service, the first 1159 // pending request will be processed. 1160 mPendingInstalls.add(idx, params); 1161 } 1162 } finally { 1163 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1164 System.identityHashCode(params)); 1165 } 1166 } else { 1167 mPendingInstalls.add(idx, params); 1168 // Already bound to the service. Just make 1169 // sure we trigger off processing the first request. 1170 if (idx == 0) { 1171 mHandler.sendEmptyMessage(MCS_BOUND); 1172 } 1173 } 1174 break; 1175 } 1176 case MCS_BOUND: { 1177 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1178 if (msg.obj != null) { 1179 mContainerService = (IMediaContainerService) msg.obj; 1180 } 1181 if (mContainerService == null) { 1182 if (!mBound) { 1183 // Something seriously wrong since we are not bound and we are not 1184 // waiting for connection. Bail out. 1185 Slog.e(TAG, "Cannot bind to media container service"); 1186 for (HandlerParams params : mPendingInstalls) { 1187 // Indicate service bind error 1188 params.serviceError(); 1189 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1190 System.identityHashCode(params)); 1191 } 1192 mPendingInstalls.clear(); 1193 } else { 1194 Slog.w(TAG, "Waiting to connect to media container service"); 1195 } 1196 } else if (mPendingInstalls.size() > 0) { 1197 HandlerParams params = mPendingInstalls.get(0); 1198 if (params != null) { 1199 if (params.startCopy()) { 1200 // We are done... look for more work or to 1201 // go idle. 1202 if (DEBUG_SD_INSTALL) Log.i(TAG, 1203 "Checking for more work or unbind..."); 1204 // Delete pending install 1205 if (mPendingInstalls.size() > 0) { 1206 mPendingInstalls.remove(0); 1207 } 1208 if (mPendingInstalls.size() == 0) { 1209 if (mBound) { 1210 if (DEBUG_SD_INSTALL) Log.i(TAG, 1211 "Posting delayed MCS_UNBIND"); 1212 removeMessages(MCS_UNBIND); 1213 Message ubmsg = obtainMessage(MCS_UNBIND); 1214 // Unbind after a little delay, to avoid 1215 // continual thrashing. 1216 sendMessageDelayed(ubmsg, 10000); 1217 } 1218 } else { 1219 // There are more pending requests in queue. 1220 // Just post MCS_BOUND message to trigger processing 1221 // of next pending install. 1222 if (DEBUG_SD_INSTALL) Log.i(TAG, 1223 "Posting MCS_BOUND for next work"); 1224 mHandler.sendEmptyMessage(MCS_BOUND); 1225 } 1226 } 1227 } 1228 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1229 System.identityHashCode(params)); 1230 } else { 1231 // Should never happen ideally. 1232 Slog.w(TAG, "Empty queue"); 1233 } 1234 break; 1235 } 1236 case MCS_RECONNECT: { 1237 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1238 if (mPendingInstalls.size() > 0) { 1239 if (mBound) { 1240 disconnectService(); 1241 } 1242 if (!connectToService()) { 1243 Slog.e(TAG, "Failed to bind to media container service"); 1244 for (HandlerParams params : mPendingInstalls) { 1245 // Indicate service bind error 1246 params.serviceError(); 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1248 System.identityHashCode(params)); 1249 } 1250 mPendingInstalls.clear(); 1251 } 1252 } 1253 break; 1254 } 1255 case MCS_UNBIND: { 1256 // If there is no actual work left, then time to unbind. 1257 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1258 1259 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1260 if (mBound) { 1261 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1262 1263 disconnectService(); 1264 } 1265 } else if (mPendingInstalls.size() > 0) { 1266 // There are more pending requests in queue. 1267 // Just post MCS_BOUND message to trigger processing 1268 // of next pending install. 1269 mHandler.sendEmptyMessage(MCS_BOUND); 1270 } 1271 1272 break; 1273 } 1274 case MCS_GIVE_UP: { 1275 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1276 HandlerParams params = mPendingInstalls.remove(0); 1277 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1278 System.identityHashCode(params)); 1279 break; 1280 } 1281 case SEND_PENDING_BROADCAST: { 1282 String packages[]; 1283 ArrayList<String> components[]; 1284 int size = 0; 1285 int uids[]; 1286 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1287 synchronized (mPackages) { 1288 if (mPendingBroadcasts == null) { 1289 return; 1290 } 1291 size = mPendingBroadcasts.size(); 1292 if (size <= 0) { 1293 // Nothing to be done. Just return 1294 return; 1295 } 1296 packages = new String[size]; 1297 components = new ArrayList[size]; 1298 uids = new int[size]; 1299 int i = 0; // filling out the above arrays 1300 1301 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1302 int packageUserId = mPendingBroadcasts.userIdAt(n); 1303 Iterator<Map.Entry<String, ArrayList<String>>> it 1304 = mPendingBroadcasts.packagesForUserId(packageUserId) 1305 .entrySet().iterator(); 1306 while (it.hasNext() && i < size) { 1307 Map.Entry<String, ArrayList<String>> ent = it.next(); 1308 packages[i] = ent.getKey(); 1309 components[i] = ent.getValue(); 1310 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1311 uids[i] = (ps != null) 1312 ? UserHandle.getUid(packageUserId, ps.appId) 1313 : -1; 1314 i++; 1315 } 1316 } 1317 size = i; 1318 mPendingBroadcasts.clear(); 1319 } 1320 // Send broadcasts 1321 for (int i = 0; i < size; i++) { 1322 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1323 } 1324 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1325 break; 1326 } 1327 case START_CLEANING_PACKAGE: { 1328 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1329 final String packageName = (String)msg.obj; 1330 final int userId = msg.arg1; 1331 final boolean andCode = msg.arg2 != 0; 1332 synchronized (mPackages) { 1333 if (userId == UserHandle.USER_ALL) { 1334 int[] users = sUserManager.getUserIds(); 1335 for (int user : users) { 1336 mSettings.addPackageToCleanLPw( 1337 new PackageCleanItem(user, packageName, andCode)); 1338 } 1339 } else { 1340 mSettings.addPackageToCleanLPw( 1341 new PackageCleanItem(userId, packageName, andCode)); 1342 } 1343 } 1344 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1345 startCleaningPackages(); 1346 } break; 1347 case POST_INSTALL: { 1348 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1349 PostInstallData data = mRunningInstalls.get(msg.arg1); 1350 mRunningInstalls.delete(msg.arg1); 1351 boolean deleteOld = false; 1352 1353 if (data != null) { 1354 InstallArgs args = data.args; 1355 PackageInstalledInfo res = data.res; 1356 1357 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1358 final String packageName = res.pkg.applicationInfo.packageName; 1359 res.removedInfo.sendBroadcast(false, true, false); 1360 Bundle extras = new Bundle(1); 1361 extras.putInt(Intent.EXTRA_UID, res.uid); 1362 1363 // Now that we successfully installed the package, grant runtime 1364 // permissions if requested before broadcasting the install. 1365 if ((args.installFlags 1366 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1367 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1368 args.installGrantPermissions); 1369 } 1370 1371 // Determine the set of users who are adding this 1372 // package for the first time vs. those who are seeing 1373 // an update. 1374 int[] firstUsers; 1375 int[] updateUsers = new int[0]; 1376 if (res.origUsers == null || res.origUsers.length == 0) { 1377 firstUsers = res.newUsers; 1378 } else { 1379 firstUsers = new int[0]; 1380 for (int i=0; i<res.newUsers.length; i++) { 1381 int user = res.newUsers[i]; 1382 boolean isNew = true; 1383 for (int j=0; j<res.origUsers.length; j++) { 1384 if (res.origUsers[j] == user) { 1385 isNew = false; 1386 break; 1387 } 1388 } 1389 if (isNew) { 1390 int[] newFirst = new int[firstUsers.length+1]; 1391 System.arraycopy(firstUsers, 0, newFirst, 0, 1392 firstUsers.length); 1393 newFirst[firstUsers.length] = user; 1394 firstUsers = newFirst; 1395 } else { 1396 int[] newUpdate = new int[updateUsers.length+1]; 1397 System.arraycopy(updateUsers, 0, newUpdate, 0, 1398 updateUsers.length); 1399 newUpdate[updateUsers.length] = user; 1400 updateUsers = newUpdate; 1401 } 1402 } 1403 } 1404 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1405 packageName, extras, null, null, firstUsers); 1406 final boolean update = res.removedInfo.removedPackage != null; 1407 if (update) { 1408 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1409 } 1410 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1411 packageName, extras, null, null, updateUsers); 1412 if (update) { 1413 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1414 packageName, extras, null, null, updateUsers); 1415 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1416 null, null, packageName, null, updateUsers); 1417 1418 // treat asec-hosted packages like removable media on upgrade 1419 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1420 if (DEBUG_INSTALL) { 1421 Slog.i(TAG, "upgrading pkg " + res.pkg 1422 + " is ASEC-hosted -> AVAILABLE"); 1423 } 1424 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1425 ArrayList<String> pkgList = new ArrayList<String>(1); 1426 pkgList.add(packageName); 1427 sendResourcesChangedBroadcast(true, true, 1428 pkgList,uidArray, null); 1429 } 1430 } 1431 if (res.removedInfo.args != null) { 1432 // Remove the replaced package's older resources safely now 1433 deleteOld = true; 1434 } 1435 1436 // If this app is a browser and it's newly-installed for some 1437 // users, clear any default-browser state in those users 1438 if (firstUsers.length > 0) { 1439 // the app's nature doesn't depend on the user, so we can just 1440 // check its browser nature in any user and generalize. 1441 if (packageIsBrowser(packageName, firstUsers[0])) { 1442 synchronized (mPackages) { 1443 for (int userId : firstUsers) { 1444 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1445 } 1446 } 1447 } 1448 } 1449 // Log current value of "unknown sources" setting 1450 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1451 getUnknownSourcesSettings()); 1452 } 1453 // Force a gc to clear up things 1454 Runtime.getRuntime().gc(); 1455 // We delete after a gc for applications on sdcard. 1456 if (deleteOld) { 1457 synchronized (mInstallLock) { 1458 res.removedInfo.args.doPostDeleteLI(true); 1459 } 1460 } 1461 if (args.observer != null) { 1462 try { 1463 Bundle extras = extrasForInstallResult(res); 1464 args.observer.onPackageInstalled(res.name, res.returnCode, 1465 res.returnMsg, extras); 1466 } catch (RemoteException e) { 1467 Slog.i(TAG, "Observer no longer exists."); 1468 } 1469 } 1470 } else { 1471 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1472 } 1473 1474 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1475 } break; 1476 case UPDATED_MEDIA_STATUS: { 1477 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1478 boolean reportStatus = msg.arg1 == 1; 1479 boolean doGc = msg.arg2 == 1; 1480 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1481 if (doGc) { 1482 // Force a gc to clear up stale containers. 1483 Runtime.getRuntime().gc(); 1484 } 1485 if (msg.obj != null) { 1486 @SuppressWarnings("unchecked") 1487 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1488 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1489 // Unload containers 1490 unloadAllContainers(args); 1491 } 1492 if (reportStatus) { 1493 try { 1494 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1495 PackageHelper.getMountService().finishMediaUpdate(); 1496 } catch (RemoteException e) { 1497 Log.e(TAG, "MountService not running?"); 1498 } 1499 } 1500 } break; 1501 case WRITE_SETTINGS: { 1502 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1503 synchronized (mPackages) { 1504 removeMessages(WRITE_SETTINGS); 1505 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1506 mSettings.writeLPr(); 1507 mDirtyUsers.clear(); 1508 } 1509 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1510 } break; 1511 case WRITE_PACKAGE_RESTRICTIONS: { 1512 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1513 synchronized (mPackages) { 1514 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1515 for (int userId : mDirtyUsers) { 1516 mSettings.writePackageRestrictionsLPr(userId); 1517 } 1518 mDirtyUsers.clear(); 1519 } 1520 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1521 } break; 1522 case CHECK_PENDING_VERIFICATION: { 1523 final int verificationId = msg.arg1; 1524 final PackageVerificationState state = mPendingVerification.get(verificationId); 1525 1526 if ((state != null) && !state.timeoutExtended()) { 1527 final InstallArgs args = state.getInstallArgs(); 1528 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1529 1530 Slog.i(TAG, "Verification timed out for " + originUri); 1531 mPendingVerification.remove(verificationId); 1532 1533 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1534 1535 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1536 Slog.i(TAG, "Continuing with installation of " + originUri); 1537 state.setVerifierResponse(Binder.getCallingUid(), 1538 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1539 broadcastPackageVerified(verificationId, originUri, 1540 PackageManager.VERIFICATION_ALLOW, 1541 state.getInstallArgs().getUser()); 1542 try { 1543 ret = args.copyApk(mContainerService, true); 1544 } catch (RemoteException e) { 1545 Slog.e(TAG, "Could not contact the ContainerService"); 1546 } 1547 } else { 1548 broadcastPackageVerified(verificationId, originUri, 1549 PackageManager.VERIFICATION_REJECT, 1550 state.getInstallArgs().getUser()); 1551 } 1552 1553 processPendingInstall(args, ret); 1554 mHandler.sendEmptyMessage(MCS_UNBIND); 1555 } 1556 Trace.asyncTraceEnd( 1557 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 1558 break; 1559 } 1560 case PACKAGE_VERIFIED: { 1561 final int verificationId = msg.arg1; 1562 1563 final PackageVerificationState state = mPendingVerification.get(verificationId); 1564 if (state == null) { 1565 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1566 break; 1567 } 1568 1569 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1570 1571 state.setVerifierResponse(response.callerUid, response.code); 1572 1573 if (state.isVerificationComplete()) { 1574 mPendingVerification.remove(verificationId); 1575 1576 final InstallArgs args = state.getInstallArgs(); 1577 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1578 1579 int ret; 1580 if (state.isInstallAllowed()) { 1581 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1582 broadcastPackageVerified(verificationId, originUri, 1583 response.code, state.getInstallArgs().getUser()); 1584 try { 1585 ret = args.copyApk(mContainerService, true); 1586 } catch (RemoteException e) { 1587 Slog.e(TAG, "Could not contact the ContainerService"); 1588 } 1589 } else { 1590 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1591 } 1592 1593 processPendingInstall(args, ret); 1594 1595 mHandler.sendEmptyMessage(MCS_UNBIND); 1596 } 1597 1598 break; 1599 } 1600 case START_INTENT_FILTER_VERIFICATIONS: { 1601 IFVerificationParams params = (IFVerificationParams) msg.obj; 1602 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1603 params.replacing, params.pkg); 1604 break; 1605 } 1606 case INTENT_FILTER_VERIFIED: { 1607 final int verificationId = msg.arg1; 1608 1609 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1610 verificationId); 1611 if (state == null) { 1612 Slog.w(TAG, "Invalid IntentFilter verification token " 1613 + verificationId + " received"); 1614 break; 1615 } 1616 1617 final int userId = state.getUserId(); 1618 1619 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1620 "Processing IntentFilter verification with token:" 1621 + verificationId + " and userId:" + userId); 1622 1623 final IntentFilterVerificationResponse response = 1624 (IntentFilterVerificationResponse) msg.obj; 1625 1626 state.setVerifierResponse(response.callerUid, response.code); 1627 1628 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1629 "IntentFilter verification with token:" + verificationId 1630 + " and userId:" + userId 1631 + " is settings verifier response with response code:" 1632 + response.code); 1633 1634 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1635 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1636 + response.getFailedDomainsString()); 1637 } 1638 1639 if (state.isVerificationComplete()) { 1640 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1641 } else { 1642 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1643 "IntentFilter verification with token:" + verificationId 1644 + " was not said to be complete"); 1645 } 1646 1647 break; 1648 } 1649 } 1650 } 1651 } 1652 1653 private StorageEventListener mStorageListener = new StorageEventListener() { 1654 @Override 1655 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1656 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1657 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1658 final String volumeUuid = vol.getFsUuid(); 1659 1660 // Clean up any users or apps that were removed or recreated 1661 // while this volume was missing 1662 reconcileUsers(volumeUuid); 1663 reconcileApps(volumeUuid); 1664 1665 // Clean up any install sessions that expired or were 1666 // cancelled while this volume was missing 1667 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1668 1669 loadPrivatePackages(vol); 1670 1671 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1672 unloadPrivatePackages(vol); 1673 } 1674 } 1675 1676 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1677 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1678 updateExternalMediaStatus(true, false); 1679 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1680 updateExternalMediaStatus(false, false); 1681 } 1682 } 1683 } 1684 1685 @Override 1686 public void onVolumeForgotten(String fsUuid) { 1687 if (TextUtils.isEmpty(fsUuid)) { 1688 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1689 return; 1690 } 1691 1692 // Remove any apps installed on the forgotten volume 1693 synchronized (mPackages) { 1694 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1695 for (PackageSetting ps : packages) { 1696 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1697 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1698 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1699 } 1700 1701 mSettings.onVolumeForgotten(fsUuid); 1702 mSettings.writeLPr(); 1703 } 1704 } 1705 }; 1706 1707 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1708 String[] grantedPermissions) { 1709 if (userId >= UserHandle.USER_OWNER) { 1710 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1711 } else if (userId == UserHandle.USER_ALL) { 1712 final int[] userIds; 1713 synchronized (mPackages) { 1714 userIds = UserManagerService.getInstance().getUserIds(); 1715 } 1716 for (int someUserId : userIds) { 1717 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1718 } 1719 } 1720 1721 // We could have touched GID membership, so flush out packages.list 1722 synchronized (mPackages) { 1723 mSettings.writePackageListLPr(); 1724 } 1725 } 1726 1727 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1728 String[] grantedPermissions) { 1729 SettingBase sb = (SettingBase) pkg.mExtras; 1730 if (sb == null) { 1731 return; 1732 } 1733 1734 PermissionsState permissionsState = sb.getPermissionsState(); 1735 1736 for (String permission : pkg.requestedPermissions) { 1737 BasePermission bp = mSettings.mPermissions.get(permission); 1738 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1739 || ArrayUtils.contains(grantedPermissions, permission))) { 1740 permissionsState.grantRuntimePermission(bp, userId); 1741 } 1742 } 1743 } 1744 1745 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1746 Bundle extras = null; 1747 switch (res.returnCode) { 1748 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1749 extras = new Bundle(); 1750 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1751 res.origPermission); 1752 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1753 res.origPackage); 1754 break; 1755 } 1756 case PackageManager.INSTALL_SUCCEEDED: { 1757 extras = new Bundle(); 1758 extras.putBoolean(Intent.EXTRA_REPLACING, 1759 res.removedInfo != null && res.removedInfo.removedPackage != null); 1760 break; 1761 } 1762 } 1763 return extras; 1764 } 1765 1766 void scheduleWriteSettingsLocked() { 1767 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1768 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1769 } 1770 } 1771 1772 void scheduleWritePackageRestrictionsLocked(int userId) { 1773 if (!sUserManager.exists(userId)) return; 1774 mDirtyUsers.add(userId); 1775 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1776 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1777 } 1778 } 1779 1780 public static PackageManagerService main(Context context, Installer installer, 1781 boolean factoryTest, boolean onlyCore) { 1782 PackageManagerService m = new PackageManagerService(context, installer, 1783 factoryTest, onlyCore); 1784 ServiceManager.addService("package", m); 1785 return m; 1786 } 1787 1788 static String[] splitString(String str, char sep) { 1789 int count = 1; 1790 int i = 0; 1791 while ((i=str.indexOf(sep, i)) >= 0) { 1792 count++; 1793 i++; 1794 } 1795 1796 String[] res = new String[count]; 1797 i=0; 1798 count = 0; 1799 int lastI=0; 1800 while ((i=str.indexOf(sep, i)) >= 0) { 1801 res[count] = str.substring(lastI, i); 1802 count++; 1803 i++; 1804 lastI = i; 1805 } 1806 res[count] = str.substring(lastI, str.length()); 1807 return res; 1808 } 1809 1810 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1811 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1812 Context.DISPLAY_SERVICE); 1813 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1814 } 1815 1816 public PackageManagerService(Context context, Installer installer, 1817 boolean factoryTest, boolean onlyCore) { 1818 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1819 SystemClock.uptimeMillis()); 1820 1821 if (mSdkVersion <= 0) { 1822 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1823 } 1824 1825 mContext = context; 1826 mFactoryTest = factoryTest; 1827 mOnlyCore = onlyCore; 1828 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1829 mMetrics = new DisplayMetrics(); 1830 mSettings = new Settings(mPackages); 1831 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1832 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1833 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1834 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1835 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1836 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1837 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1838 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1839 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1840 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1841 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1842 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1843 1844 // TODO: add a property to control this? 1845 long dexOptLRUThresholdInMinutes; 1846 if (mLazyDexOpt) { 1847 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1848 } else { 1849 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1850 } 1851 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1852 1853 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1854 if (separateProcesses != null && separateProcesses.length() > 0) { 1855 if ("*".equals(separateProcesses)) { 1856 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1857 mSeparateProcesses = null; 1858 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1859 } else { 1860 mDefParseFlags = 0; 1861 mSeparateProcesses = separateProcesses.split(","); 1862 Slog.w(TAG, "Running with debug.separate_processes: " 1863 + separateProcesses); 1864 } 1865 } else { 1866 mDefParseFlags = 0; 1867 mSeparateProcesses = null; 1868 } 1869 1870 mInstaller = installer; 1871 mPackageDexOptimizer = new PackageDexOptimizer(this); 1872 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1873 1874 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1875 FgThread.get().getLooper()); 1876 1877 getDefaultDisplayMetrics(context, mMetrics); 1878 1879 SystemConfig systemConfig = SystemConfig.getInstance(); 1880 mGlobalGids = systemConfig.getGlobalGids(); 1881 mSystemPermissions = systemConfig.getSystemPermissions(); 1882 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1883 1884 synchronized (mInstallLock) { 1885 // writer 1886 synchronized (mPackages) { 1887 mHandlerThread = new ServiceThread(TAG, 1888 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1889 mHandlerThread.start(); 1890 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1891 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1892 1893 File dataDir = Environment.getDataDirectory(); 1894 mAppDataDir = new File(dataDir, "data"); 1895 mAppInstallDir = new File(dataDir, "app"); 1896 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1897 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1898 mUserAppDataDir = new File(dataDir, "user"); 1899 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1900 1901 sUserManager = new UserManagerService(context, this, 1902 mInstallLock, mPackages); 1903 1904 // Propagate permission configuration in to package manager. 1905 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1906 = systemConfig.getPermissions(); 1907 for (int i=0; i<permConfig.size(); i++) { 1908 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1909 BasePermission bp = mSettings.mPermissions.get(perm.name); 1910 if (bp == null) { 1911 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1912 mSettings.mPermissions.put(perm.name, bp); 1913 } 1914 if (perm.gids != null) { 1915 bp.setGids(perm.gids, perm.perUser); 1916 } 1917 } 1918 1919 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1920 for (int i=0; i<libConfig.size(); i++) { 1921 mSharedLibraries.put(libConfig.keyAt(i), 1922 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1923 } 1924 1925 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1926 1927 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1928 mSdkVersion, mOnlyCore); 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 scanDirLI(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 scanDirLI(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 scanDirLI(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 scanDirLI(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 scanDirLI(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 scanDirLI(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 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2191 2192 scanDirLI(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 enforceDeclaredAsUsedAndRuntimePermission(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()) { 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 enforceDeclaredAsUsedAndRuntimePermission(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 final int result = permissionsState.grantRuntimePermission(bp, userId); 3512 switch (result) { 3513 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3514 return; 3515 } 3516 3517 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3518 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3519 mHandler.post(new Runnable() { 3520 @Override 3521 public void run() { 3522 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3523 } 3524 }); 3525 } break; 3526 } 3527 3528 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3529 3530 // Not critical if that is lost - app has to request again. 3531 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3532 } 3533 3534 // Only need to do this if user is initialized. Otherwise it's a new user 3535 // and there are no processes running as the user yet and there's no need 3536 // to make an expensive call to remount processes for the changed permissions. 3537 if (READ_EXTERNAL_STORAGE.equals(name) 3538 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3539 final long token = Binder.clearCallingIdentity(); 3540 try { 3541 if (sUserManager.isInitialized(userId)) { 3542 MountServiceInternal mountServiceInternal = LocalServices.getService( 3543 MountServiceInternal.class); 3544 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3545 } 3546 } finally { 3547 Binder.restoreCallingIdentity(token); 3548 } 3549 } 3550 } 3551 3552 @Override 3553 public void revokeRuntimePermission(String packageName, String name, int userId) { 3554 if (!sUserManager.exists(userId)) { 3555 Log.e(TAG, "No such user:" + userId); 3556 return; 3557 } 3558 3559 mContext.enforceCallingOrSelfPermission( 3560 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3561 "revokeRuntimePermission"); 3562 3563 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3564 "revokeRuntimePermission"); 3565 3566 final int appId; 3567 3568 synchronized (mPackages) { 3569 final PackageParser.Package pkg = mPackages.get(packageName); 3570 if (pkg == null) { 3571 throw new IllegalArgumentException("Unknown package: " + packageName); 3572 } 3573 3574 final BasePermission bp = mSettings.mPermissions.get(name); 3575 if (bp == null) { 3576 throw new IllegalArgumentException("Unknown permission: " + name); 3577 } 3578 3579 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3580 3581 SettingBase sb = (SettingBase) pkg.mExtras; 3582 if (sb == null) { 3583 throw new IllegalArgumentException("Unknown package: " + packageName); 3584 } 3585 3586 final PermissionsState permissionsState = sb.getPermissionsState(); 3587 3588 final int flags = permissionsState.getPermissionFlags(name, userId); 3589 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3590 throw new SecurityException("Cannot revoke system fixed permission: " 3591 + name + " for package: " + packageName); 3592 } 3593 3594 if (permissionsState.revokeRuntimePermission(bp, userId) == 3595 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3596 return; 3597 } 3598 3599 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3600 3601 // Critical, after this call app should never have the permission. 3602 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3603 3604 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3605 } 3606 3607 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3608 } 3609 3610 @Override 3611 public void resetRuntimePermissions() { 3612 mContext.enforceCallingOrSelfPermission( 3613 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3614 "revokeRuntimePermission"); 3615 3616 int callingUid = Binder.getCallingUid(); 3617 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3618 mContext.enforceCallingOrSelfPermission( 3619 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3620 "resetRuntimePermissions"); 3621 } 3622 3623 synchronized (mPackages) { 3624 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3625 for (int userId : UserManagerService.getInstance().getUserIds()) { 3626 final int packageCount = mPackages.size(); 3627 for (int i = 0; i < packageCount; i++) { 3628 PackageParser.Package pkg = mPackages.valueAt(i); 3629 if (!(pkg.mExtras instanceof PackageSetting)) { 3630 continue; 3631 } 3632 PackageSetting ps = (PackageSetting) pkg.mExtras; 3633 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3634 } 3635 } 3636 } 3637 } 3638 3639 @Override 3640 public int getPermissionFlags(String name, String packageName, int userId) { 3641 if (!sUserManager.exists(userId)) { 3642 return 0; 3643 } 3644 3645 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3646 3647 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3648 "getPermissionFlags"); 3649 3650 synchronized (mPackages) { 3651 final PackageParser.Package pkg = mPackages.get(packageName); 3652 if (pkg == null) { 3653 throw new IllegalArgumentException("Unknown package: " + packageName); 3654 } 3655 3656 final BasePermission bp = mSettings.mPermissions.get(name); 3657 if (bp == null) { 3658 throw new IllegalArgumentException("Unknown permission: " + name); 3659 } 3660 3661 SettingBase sb = (SettingBase) pkg.mExtras; 3662 if (sb == null) { 3663 throw new IllegalArgumentException("Unknown package: " + packageName); 3664 } 3665 3666 PermissionsState permissionsState = sb.getPermissionsState(); 3667 return permissionsState.getPermissionFlags(name, userId); 3668 } 3669 } 3670 3671 @Override 3672 public void updatePermissionFlags(String name, String packageName, int flagMask, 3673 int flagValues, int userId) { 3674 if (!sUserManager.exists(userId)) { 3675 return; 3676 } 3677 3678 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3679 3680 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3681 "updatePermissionFlags"); 3682 3683 // Only the system can change these flags and nothing else. 3684 if (getCallingUid() != Process.SYSTEM_UID) { 3685 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3686 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3687 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3688 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3689 } 3690 3691 synchronized (mPackages) { 3692 final PackageParser.Package pkg = mPackages.get(packageName); 3693 if (pkg == null) { 3694 throw new IllegalArgumentException("Unknown package: " + packageName); 3695 } 3696 3697 final BasePermission bp = mSettings.mPermissions.get(name); 3698 if (bp == null) { 3699 throw new IllegalArgumentException("Unknown permission: " + name); 3700 } 3701 3702 SettingBase sb = (SettingBase) pkg.mExtras; 3703 if (sb == null) { 3704 throw new IllegalArgumentException("Unknown package: " + packageName); 3705 } 3706 3707 PermissionsState permissionsState = sb.getPermissionsState(); 3708 3709 // Only the package manager can change flags for system component permissions. 3710 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3711 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3712 return; 3713 } 3714 3715 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3716 3717 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3718 // Install and runtime permissions are stored in different places, 3719 // so figure out what permission changed and persist the change. 3720 if (permissionsState.getInstallPermissionState(name) != null) { 3721 scheduleWriteSettingsLocked(); 3722 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3723 || hadState) { 3724 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3725 } 3726 } 3727 } 3728 } 3729 3730 /** 3731 * Update the permission flags for all packages and runtime permissions of a user in order 3732 * to allow device or profile owner to remove POLICY_FIXED. 3733 */ 3734 @Override 3735 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3736 if (!sUserManager.exists(userId)) { 3737 return; 3738 } 3739 3740 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3741 3742 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3743 "updatePermissionFlagsForAllApps"); 3744 3745 // Only the system can change system fixed flags. 3746 if (getCallingUid() != Process.SYSTEM_UID) { 3747 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3748 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3749 } 3750 3751 synchronized (mPackages) { 3752 boolean changed = false; 3753 final int packageCount = mPackages.size(); 3754 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3755 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3756 SettingBase sb = (SettingBase) pkg.mExtras; 3757 if (sb == null) { 3758 continue; 3759 } 3760 PermissionsState permissionsState = sb.getPermissionsState(); 3761 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3762 userId, flagMask, flagValues); 3763 } 3764 if (changed) { 3765 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3766 } 3767 } 3768 } 3769 3770 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3771 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3772 != PackageManager.PERMISSION_GRANTED 3773 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3774 != PackageManager.PERMISSION_GRANTED) { 3775 throw new SecurityException(message + " requires " 3776 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3777 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3778 } 3779 } 3780 3781 @Override 3782 public boolean shouldShowRequestPermissionRationale(String permissionName, 3783 String packageName, int userId) { 3784 if (UserHandle.getCallingUserId() != userId) { 3785 mContext.enforceCallingPermission( 3786 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3787 "canShowRequestPermissionRationale for user " + userId); 3788 } 3789 3790 final int uid = getPackageUid(packageName, userId); 3791 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3792 return false; 3793 } 3794 3795 if (checkPermission(permissionName, packageName, userId) 3796 == PackageManager.PERMISSION_GRANTED) { 3797 return false; 3798 } 3799 3800 final int flags; 3801 3802 final long identity = Binder.clearCallingIdentity(); 3803 try { 3804 flags = getPermissionFlags(permissionName, 3805 packageName, userId); 3806 } finally { 3807 Binder.restoreCallingIdentity(identity); 3808 } 3809 3810 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3811 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3812 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3813 3814 if ((flags & fixedFlags) != 0) { 3815 return false; 3816 } 3817 3818 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3819 } 3820 3821 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3822 BasePermission bp = mSettings.mPermissions.get(permission); 3823 if (bp == null) { 3824 throw new SecurityException("Missing " + permission + " permission"); 3825 } 3826 3827 SettingBase sb = (SettingBase) pkg.mExtras; 3828 PermissionsState permissionsState = sb.getPermissionsState(); 3829 3830 if (permissionsState.grantInstallPermission(bp) != 3831 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3832 scheduleWriteSettingsLocked(); 3833 } 3834 } 3835 3836 @Override 3837 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3838 mContext.enforceCallingOrSelfPermission( 3839 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3840 "addOnPermissionsChangeListener"); 3841 3842 synchronized (mPackages) { 3843 mOnPermissionChangeListeners.addListenerLocked(listener); 3844 } 3845 } 3846 3847 @Override 3848 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3849 synchronized (mPackages) { 3850 mOnPermissionChangeListeners.removeListenerLocked(listener); 3851 } 3852 } 3853 3854 @Override 3855 public boolean isProtectedBroadcast(String actionName) { 3856 synchronized (mPackages) { 3857 return mProtectedBroadcasts.contains(actionName); 3858 } 3859 } 3860 3861 @Override 3862 public int checkSignatures(String pkg1, String pkg2) { 3863 synchronized (mPackages) { 3864 final PackageParser.Package p1 = mPackages.get(pkg1); 3865 final PackageParser.Package p2 = mPackages.get(pkg2); 3866 if (p1 == null || p1.mExtras == null 3867 || p2 == null || p2.mExtras == null) { 3868 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3869 } 3870 return compareSignatures(p1.mSignatures, p2.mSignatures); 3871 } 3872 } 3873 3874 @Override 3875 public int checkUidSignatures(int uid1, int uid2) { 3876 // Map to base uids. 3877 uid1 = UserHandle.getAppId(uid1); 3878 uid2 = UserHandle.getAppId(uid2); 3879 // reader 3880 synchronized (mPackages) { 3881 Signature[] s1; 3882 Signature[] s2; 3883 Object obj = mSettings.getUserIdLPr(uid1); 3884 if (obj != null) { 3885 if (obj instanceof SharedUserSetting) { 3886 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3887 } else if (obj instanceof PackageSetting) { 3888 s1 = ((PackageSetting)obj).signatures.mSignatures; 3889 } else { 3890 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3891 } 3892 } else { 3893 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3894 } 3895 obj = mSettings.getUserIdLPr(uid2); 3896 if (obj != null) { 3897 if (obj instanceof SharedUserSetting) { 3898 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3899 } else if (obj instanceof PackageSetting) { 3900 s2 = ((PackageSetting)obj).signatures.mSignatures; 3901 } else { 3902 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3903 } 3904 } else { 3905 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3906 } 3907 return compareSignatures(s1, s2); 3908 } 3909 } 3910 3911 private void killUid(int appId, int userId, String reason) { 3912 final long identity = Binder.clearCallingIdentity(); 3913 try { 3914 IActivityManager am = ActivityManagerNative.getDefault(); 3915 if (am != null) { 3916 try { 3917 am.killUid(appId, userId, reason); 3918 } catch (RemoteException e) { 3919 /* ignore - same process */ 3920 } 3921 } 3922 } finally { 3923 Binder.restoreCallingIdentity(identity); 3924 } 3925 } 3926 3927 /** 3928 * Compares two sets of signatures. Returns: 3929 * <br /> 3930 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3931 * <br /> 3932 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3933 * <br /> 3934 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3935 * <br /> 3936 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3937 * <br /> 3938 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3939 */ 3940 static int compareSignatures(Signature[] s1, Signature[] s2) { 3941 if (s1 == null) { 3942 return s2 == null 3943 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3944 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3945 } 3946 3947 if (s2 == null) { 3948 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3949 } 3950 3951 if (s1.length != s2.length) { 3952 return PackageManager.SIGNATURE_NO_MATCH; 3953 } 3954 3955 // Since both signature sets are of size 1, we can compare without HashSets. 3956 if (s1.length == 1) { 3957 return s1[0].equals(s2[0]) ? 3958 PackageManager.SIGNATURE_MATCH : 3959 PackageManager.SIGNATURE_NO_MATCH; 3960 } 3961 3962 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3963 for (Signature sig : s1) { 3964 set1.add(sig); 3965 } 3966 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3967 for (Signature sig : s2) { 3968 set2.add(sig); 3969 } 3970 // Make sure s2 contains all signatures in s1. 3971 if (set1.equals(set2)) { 3972 return PackageManager.SIGNATURE_MATCH; 3973 } 3974 return PackageManager.SIGNATURE_NO_MATCH; 3975 } 3976 3977 /** 3978 * If the database version for this type of package (internal storage or 3979 * external storage) is less than the version where package signatures 3980 * were updated, return true. 3981 */ 3982 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3983 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3984 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3985 } 3986 3987 /** 3988 * Used for backward compatibility to make sure any packages with 3989 * certificate chains get upgraded to the new style. {@code existingSigs} 3990 * will be in the old format (since they were stored on disk from before the 3991 * system upgrade) and {@code scannedSigs} will be in the newer format. 3992 */ 3993 private int compareSignaturesCompat(PackageSignatures existingSigs, 3994 PackageParser.Package scannedPkg) { 3995 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3996 return PackageManager.SIGNATURE_NO_MATCH; 3997 } 3998 3999 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4000 for (Signature sig : existingSigs.mSignatures) { 4001 existingSet.add(sig); 4002 } 4003 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4004 for (Signature sig : scannedPkg.mSignatures) { 4005 try { 4006 Signature[] chainSignatures = sig.getChainSignatures(); 4007 for (Signature chainSig : chainSignatures) { 4008 scannedCompatSet.add(chainSig); 4009 } 4010 } catch (CertificateEncodingException e) { 4011 scannedCompatSet.add(sig); 4012 } 4013 } 4014 /* 4015 * Make sure the expanded scanned set contains all signatures in the 4016 * existing one. 4017 */ 4018 if (scannedCompatSet.equals(existingSet)) { 4019 // Migrate the old signatures to the new scheme. 4020 existingSigs.assignSignatures(scannedPkg.mSignatures); 4021 // The new KeySets will be re-added later in the scanning process. 4022 synchronized (mPackages) { 4023 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4024 } 4025 return PackageManager.SIGNATURE_MATCH; 4026 } 4027 return PackageManager.SIGNATURE_NO_MATCH; 4028 } 4029 4030 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4031 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4032 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4033 } 4034 4035 private int compareSignaturesRecover(PackageSignatures existingSigs, 4036 PackageParser.Package scannedPkg) { 4037 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4038 return PackageManager.SIGNATURE_NO_MATCH; 4039 } 4040 4041 String msg = null; 4042 try { 4043 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4044 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4045 + scannedPkg.packageName); 4046 return PackageManager.SIGNATURE_MATCH; 4047 } 4048 } catch (CertificateException e) { 4049 msg = e.getMessage(); 4050 } 4051 4052 logCriticalInfo(Log.INFO, 4053 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4054 return PackageManager.SIGNATURE_NO_MATCH; 4055 } 4056 4057 @Override 4058 public String[] getPackagesForUid(int uid) { 4059 uid = UserHandle.getAppId(uid); 4060 // reader 4061 synchronized (mPackages) { 4062 Object obj = mSettings.getUserIdLPr(uid); 4063 if (obj instanceof SharedUserSetting) { 4064 final SharedUserSetting sus = (SharedUserSetting) obj; 4065 final int N = sus.packages.size(); 4066 final String[] res = new String[N]; 4067 final Iterator<PackageSetting> it = sus.packages.iterator(); 4068 int i = 0; 4069 while (it.hasNext()) { 4070 res[i++] = it.next().name; 4071 } 4072 return res; 4073 } else if (obj instanceof PackageSetting) { 4074 final PackageSetting ps = (PackageSetting) obj; 4075 return new String[] { ps.name }; 4076 } 4077 } 4078 return null; 4079 } 4080 4081 @Override 4082 public String getNameForUid(int uid) { 4083 // reader 4084 synchronized (mPackages) { 4085 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4086 if (obj instanceof SharedUserSetting) { 4087 final SharedUserSetting sus = (SharedUserSetting) obj; 4088 return sus.name + ":" + sus.userId; 4089 } else if (obj instanceof PackageSetting) { 4090 final PackageSetting ps = (PackageSetting) obj; 4091 return ps.name; 4092 } 4093 } 4094 return null; 4095 } 4096 4097 @Override 4098 public int getUidForSharedUser(String sharedUserName) { 4099 if(sharedUserName == null) { 4100 return -1; 4101 } 4102 // reader 4103 synchronized (mPackages) { 4104 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4105 if (suid == null) { 4106 return -1; 4107 } 4108 return suid.userId; 4109 } 4110 } 4111 4112 @Override 4113 public int getFlagsForUid(int uid) { 4114 synchronized (mPackages) { 4115 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4116 if (obj instanceof SharedUserSetting) { 4117 final SharedUserSetting sus = (SharedUserSetting) obj; 4118 return sus.pkgFlags; 4119 } else if (obj instanceof PackageSetting) { 4120 final PackageSetting ps = (PackageSetting) obj; 4121 return ps.pkgFlags; 4122 } 4123 } 4124 return 0; 4125 } 4126 4127 @Override 4128 public int getPrivateFlagsForUid(int uid) { 4129 synchronized (mPackages) { 4130 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4131 if (obj instanceof SharedUserSetting) { 4132 final SharedUserSetting sus = (SharedUserSetting) obj; 4133 return sus.pkgPrivateFlags; 4134 } else if (obj instanceof PackageSetting) { 4135 final PackageSetting ps = (PackageSetting) obj; 4136 return ps.pkgPrivateFlags; 4137 } 4138 } 4139 return 0; 4140 } 4141 4142 @Override 4143 public boolean isUidPrivileged(int uid) { 4144 uid = UserHandle.getAppId(uid); 4145 // reader 4146 synchronized (mPackages) { 4147 Object obj = mSettings.getUserIdLPr(uid); 4148 if (obj instanceof SharedUserSetting) { 4149 final SharedUserSetting sus = (SharedUserSetting) obj; 4150 final Iterator<PackageSetting> it = sus.packages.iterator(); 4151 while (it.hasNext()) { 4152 if (it.next().isPrivileged()) { 4153 return true; 4154 } 4155 } 4156 } else if (obj instanceof PackageSetting) { 4157 final PackageSetting ps = (PackageSetting) obj; 4158 return ps.isPrivileged(); 4159 } 4160 } 4161 return false; 4162 } 4163 4164 @Override 4165 public String[] getAppOpPermissionPackages(String permissionName) { 4166 synchronized (mPackages) { 4167 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4168 if (pkgs == null) { 4169 return null; 4170 } 4171 return pkgs.toArray(new String[pkgs.size()]); 4172 } 4173 } 4174 4175 @Override 4176 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4177 int flags, int userId) { 4178 if (!sUserManager.exists(userId)) return null; 4179 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4180 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4181 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4182 } 4183 4184 @Override 4185 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4186 IntentFilter filter, int match, ComponentName activity) { 4187 final int userId = UserHandle.getCallingUserId(); 4188 if (DEBUG_PREFERRED) { 4189 Log.v(TAG, "setLastChosenActivity intent=" + intent 4190 + " resolvedType=" + resolvedType 4191 + " flags=" + flags 4192 + " filter=" + filter 4193 + " match=" + match 4194 + " activity=" + activity); 4195 filter.dump(new PrintStreamPrinter(System.out), " "); 4196 } 4197 intent.setComponent(null); 4198 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4199 // Find any earlier preferred or last chosen entries and nuke them 4200 findPreferredActivity(intent, resolvedType, 4201 flags, query, 0, false, true, false, userId); 4202 // Add the new activity as the last chosen for this filter 4203 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4204 "Setting last chosen"); 4205 } 4206 4207 @Override 4208 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4209 final int userId = UserHandle.getCallingUserId(); 4210 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4211 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4212 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4213 false, false, false, userId); 4214 } 4215 4216 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4217 int flags, List<ResolveInfo> query, int userId) { 4218 if (query != null) { 4219 final int N = query.size(); 4220 if (N == 1) { 4221 return query.get(0); 4222 } else if (N > 1) { 4223 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4224 // If there is more than one activity with the same priority, 4225 // then let the user decide between them. 4226 ResolveInfo r0 = query.get(0); 4227 ResolveInfo r1 = query.get(1); 4228 if (DEBUG_INTENT_MATCHING || debug) { 4229 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4230 + r1.activityInfo.name + "=" + r1.priority); 4231 } 4232 // If the first activity has a higher priority, or a different 4233 // default, then it is always desireable to pick it. 4234 if (r0.priority != r1.priority 4235 || r0.preferredOrder != r1.preferredOrder 4236 || r0.isDefault != r1.isDefault) { 4237 return query.get(0); 4238 } 4239 // If we have saved a preference for a preferred activity for 4240 // this Intent, use that. 4241 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4242 flags, query, r0.priority, true, false, debug, userId); 4243 if (ri != null) { 4244 return ri; 4245 } 4246 if (userId != 0) { 4247 ri = new ResolveInfo(mResolveInfo); 4248 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4249 ri.activityInfo.applicationInfo = new ApplicationInfo( 4250 ri.activityInfo.applicationInfo); 4251 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4252 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4253 return ri; 4254 } 4255 return mResolveInfo; 4256 } 4257 } 4258 return null; 4259 } 4260 4261 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4262 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4263 final int N = query.size(); 4264 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4265 .get(userId); 4266 // Get the list of persistent preferred activities that handle the intent 4267 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4268 List<PersistentPreferredActivity> pprefs = ppir != null 4269 ? ppir.queryIntent(intent, resolvedType, 4270 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4271 : null; 4272 if (pprefs != null && pprefs.size() > 0) { 4273 final int M = pprefs.size(); 4274 for (int i=0; i<M; i++) { 4275 final PersistentPreferredActivity ppa = pprefs.get(i); 4276 if (DEBUG_PREFERRED || debug) { 4277 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4278 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4279 + "\n component=" + ppa.mComponent); 4280 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4281 } 4282 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4283 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4284 if (DEBUG_PREFERRED || debug) { 4285 Slog.v(TAG, "Found persistent preferred activity:"); 4286 if (ai != null) { 4287 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4288 } else { 4289 Slog.v(TAG, " null"); 4290 } 4291 } 4292 if (ai == null) { 4293 // This previously registered persistent preferred activity 4294 // component is no longer known. Ignore it and do NOT remove it. 4295 continue; 4296 } 4297 for (int j=0; j<N; j++) { 4298 final ResolveInfo ri = query.get(j); 4299 if (!ri.activityInfo.applicationInfo.packageName 4300 .equals(ai.applicationInfo.packageName)) { 4301 continue; 4302 } 4303 if (!ri.activityInfo.name.equals(ai.name)) { 4304 continue; 4305 } 4306 // Found a persistent preference that can handle the intent. 4307 if (DEBUG_PREFERRED || debug) { 4308 Slog.v(TAG, "Returning persistent preferred activity: " + 4309 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4310 } 4311 return ri; 4312 } 4313 } 4314 } 4315 return null; 4316 } 4317 4318 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4319 List<ResolveInfo> query, int priority, boolean always, 4320 boolean removeMatches, boolean debug, int userId) { 4321 if (!sUserManager.exists(userId)) return null; 4322 // writer 4323 synchronized (mPackages) { 4324 if (intent.getSelector() != null) { 4325 intent = intent.getSelector(); 4326 } 4327 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4328 4329 // Try to find a matching persistent preferred activity. 4330 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4331 debug, userId); 4332 4333 // If a persistent preferred activity matched, use it. 4334 if (pri != null) { 4335 return pri; 4336 } 4337 4338 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4339 // Get the list of preferred activities that handle the intent 4340 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4341 List<PreferredActivity> prefs = pir != null 4342 ? pir.queryIntent(intent, resolvedType, 4343 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4344 : null; 4345 if (prefs != null && prefs.size() > 0) { 4346 boolean changed = false; 4347 try { 4348 // First figure out how good the original match set is. 4349 // We will only allow preferred activities that came 4350 // from the same match quality. 4351 int match = 0; 4352 4353 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4354 4355 final int N = query.size(); 4356 for (int j=0; j<N; j++) { 4357 final ResolveInfo ri = query.get(j); 4358 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4359 + ": 0x" + Integer.toHexString(match)); 4360 if (ri.match > match) { 4361 match = ri.match; 4362 } 4363 } 4364 4365 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4366 + Integer.toHexString(match)); 4367 4368 match &= IntentFilter.MATCH_CATEGORY_MASK; 4369 final int M = prefs.size(); 4370 for (int i=0; i<M; i++) { 4371 final PreferredActivity pa = prefs.get(i); 4372 if (DEBUG_PREFERRED || debug) { 4373 Slog.v(TAG, "Checking PreferredActivity ds=" 4374 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4375 + "\n component=" + pa.mPref.mComponent); 4376 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4377 } 4378 if (pa.mPref.mMatch != match) { 4379 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4380 + Integer.toHexString(pa.mPref.mMatch)); 4381 continue; 4382 } 4383 // If it's not an "always" type preferred activity and that's what we're 4384 // looking for, skip it. 4385 if (always && !pa.mPref.mAlways) { 4386 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4387 continue; 4388 } 4389 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4390 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4391 if (DEBUG_PREFERRED || debug) { 4392 Slog.v(TAG, "Found preferred activity:"); 4393 if (ai != null) { 4394 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4395 } else { 4396 Slog.v(TAG, " null"); 4397 } 4398 } 4399 if (ai == null) { 4400 // This previously registered preferred activity 4401 // component is no longer known. Most likely an update 4402 // to the app was installed and in the new version this 4403 // component no longer exists. Clean it up by removing 4404 // it from the preferred activities list, and skip it. 4405 Slog.w(TAG, "Removing dangling preferred activity: " 4406 + pa.mPref.mComponent); 4407 pir.removeFilter(pa); 4408 changed = true; 4409 continue; 4410 } 4411 for (int j=0; j<N; j++) { 4412 final ResolveInfo ri = query.get(j); 4413 if (!ri.activityInfo.applicationInfo.packageName 4414 .equals(ai.applicationInfo.packageName)) { 4415 continue; 4416 } 4417 if (!ri.activityInfo.name.equals(ai.name)) { 4418 continue; 4419 } 4420 4421 if (removeMatches) { 4422 pir.removeFilter(pa); 4423 changed = true; 4424 if (DEBUG_PREFERRED) { 4425 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4426 } 4427 break; 4428 } 4429 4430 // Okay we found a previously set preferred or last chosen app. 4431 // If the result set is different from when this 4432 // was created, we need to clear it and re-ask the 4433 // user their preference, if we're looking for an "always" type entry. 4434 if (always && !pa.mPref.sameSet(query)) { 4435 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4436 + intent + " type " + resolvedType); 4437 if (DEBUG_PREFERRED) { 4438 Slog.v(TAG, "Removing preferred activity since set changed " 4439 + pa.mPref.mComponent); 4440 } 4441 pir.removeFilter(pa); 4442 // Re-add the filter as a "last chosen" entry (!always) 4443 PreferredActivity lastChosen = new PreferredActivity( 4444 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4445 pir.addFilter(lastChosen); 4446 changed = true; 4447 return null; 4448 } 4449 4450 // Yay! Either the set matched or we're looking for the last chosen 4451 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4452 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4453 return ri; 4454 } 4455 } 4456 } finally { 4457 if (changed) { 4458 if (DEBUG_PREFERRED) { 4459 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4460 } 4461 scheduleWritePackageRestrictionsLocked(userId); 4462 } 4463 } 4464 } 4465 } 4466 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4467 return null; 4468 } 4469 4470 /* 4471 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4472 */ 4473 @Override 4474 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4475 int targetUserId) { 4476 mContext.enforceCallingOrSelfPermission( 4477 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4478 List<CrossProfileIntentFilter> matches = 4479 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4480 if (matches != null) { 4481 int size = matches.size(); 4482 for (int i = 0; i < size; i++) { 4483 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4484 } 4485 } 4486 if (hasWebURI(intent)) { 4487 // cross-profile app linking works only towards the parent. 4488 final UserInfo parent = getProfileParent(sourceUserId); 4489 synchronized(mPackages) { 4490 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4491 intent, resolvedType, 0, sourceUserId, parent.id); 4492 return xpDomainInfo != null; 4493 } 4494 } 4495 return false; 4496 } 4497 4498 private UserInfo getProfileParent(int userId) { 4499 final long identity = Binder.clearCallingIdentity(); 4500 try { 4501 return sUserManager.getProfileParent(userId); 4502 } finally { 4503 Binder.restoreCallingIdentity(identity); 4504 } 4505 } 4506 4507 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4508 String resolvedType, int userId) { 4509 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4510 if (resolver != null) { 4511 return resolver.queryIntent(intent, resolvedType, false, userId); 4512 } 4513 return null; 4514 } 4515 4516 @Override 4517 public List<ResolveInfo> queryIntentActivities(Intent intent, 4518 String resolvedType, int flags, int userId) { 4519 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4520 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4521 ComponentName comp = intent.getComponent(); 4522 if (comp == null) { 4523 if (intent.getSelector() != null) { 4524 intent = intent.getSelector(); 4525 comp = intent.getComponent(); 4526 } 4527 } 4528 4529 if (comp != null) { 4530 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4531 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4532 if (ai != null) { 4533 final ResolveInfo ri = new ResolveInfo(); 4534 ri.activityInfo = ai; 4535 list.add(ri); 4536 } 4537 return list; 4538 } 4539 4540 // reader 4541 synchronized (mPackages) { 4542 final String pkgName = intent.getPackage(); 4543 if (pkgName == null) { 4544 List<CrossProfileIntentFilter> matchingFilters = 4545 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4546 // Check for results that need to skip the current profile. 4547 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4548 resolvedType, flags, userId); 4549 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4550 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4551 result.add(xpResolveInfo); 4552 return filterIfNotPrimaryUser(result, userId); 4553 } 4554 4555 // Check for results in the current profile. 4556 List<ResolveInfo> result = mActivities.queryIntent( 4557 intent, resolvedType, flags, userId); 4558 4559 // Check for cross profile results. 4560 xpResolveInfo = queryCrossProfileIntents( 4561 matchingFilters, intent, resolvedType, flags, userId); 4562 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4563 result.add(xpResolveInfo); 4564 Collections.sort(result, mResolvePrioritySorter); 4565 } 4566 result = filterIfNotPrimaryUser(result, userId); 4567 if (hasWebURI(intent)) { 4568 CrossProfileDomainInfo xpDomainInfo = null; 4569 final UserInfo parent = getProfileParent(userId); 4570 if (parent != null) { 4571 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4572 flags, userId, parent.id); 4573 } 4574 if (xpDomainInfo != null) { 4575 if (xpResolveInfo != null) { 4576 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4577 // in the result. 4578 result.remove(xpResolveInfo); 4579 } 4580 if (result.size() == 0) { 4581 result.add(xpDomainInfo.resolveInfo); 4582 return result; 4583 } 4584 } else if (result.size() <= 1) { 4585 return result; 4586 } 4587 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4588 xpDomainInfo, userId); 4589 Collections.sort(result, mResolvePrioritySorter); 4590 } 4591 return result; 4592 } 4593 final PackageParser.Package pkg = mPackages.get(pkgName); 4594 if (pkg != null) { 4595 return filterIfNotPrimaryUser( 4596 mActivities.queryIntentForPackage( 4597 intent, resolvedType, flags, pkg.activities, userId), 4598 userId); 4599 } 4600 return new ArrayList<ResolveInfo>(); 4601 } 4602 } 4603 4604 private static class CrossProfileDomainInfo { 4605 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4606 ResolveInfo resolveInfo; 4607 /* Best domain verification status of the activities found in the other profile */ 4608 int bestDomainVerificationStatus; 4609 } 4610 4611 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4612 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4613 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4614 sourceUserId)) { 4615 return null; 4616 } 4617 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4618 resolvedType, flags, parentUserId); 4619 4620 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4621 return null; 4622 } 4623 CrossProfileDomainInfo result = null; 4624 int size = resultTargetUser.size(); 4625 for (int i = 0; i < size; i++) { 4626 ResolveInfo riTargetUser = resultTargetUser.get(i); 4627 // Intent filter verification is only for filters that specify a host. So don't return 4628 // those that handle all web uris. 4629 if (riTargetUser.handleAllWebDataURI) { 4630 continue; 4631 } 4632 String packageName = riTargetUser.activityInfo.packageName; 4633 PackageSetting ps = mSettings.mPackages.get(packageName); 4634 if (ps == null) { 4635 continue; 4636 } 4637 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4638 int status = (int)(verificationState >> 32); 4639 if (result == null) { 4640 result = new CrossProfileDomainInfo(); 4641 result.resolveInfo = 4642 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4643 result.bestDomainVerificationStatus = status; 4644 } else { 4645 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4646 result.bestDomainVerificationStatus); 4647 } 4648 } 4649 // Don't consider matches with status NEVER across profiles. 4650 if (result != null && result.bestDomainVerificationStatus 4651 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4652 return null; 4653 } 4654 return result; 4655 } 4656 4657 /** 4658 * Verification statuses are ordered from the worse to the best, except for 4659 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4660 */ 4661 private int bestDomainVerificationStatus(int status1, int status2) { 4662 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4663 return status2; 4664 } 4665 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4666 return status1; 4667 } 4668 return (int) MathUtils.max(status1, status2); 4669 } 4670 4671 private boolean isUserEnabled(int userId) { 4672 long callingId = Binder.clearCallingIdentity(); 4673 try { 4674 UserInfo userInfo = sUserManager.getUserInfo(userId); 4675 return userInfo != null && userInfo.isEnabled(); 4676 } finally { 4677 Binder.restoreCallingIdentity(callingId); 4678 } 4679 } 4680 4681 /** 4682 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4683 * 4684 * @return filtered list 4685 */ 4686 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4687 if (userId == UserHandle.USER_OWNER) { 4688 return resolveInfos; 4689 } 4690 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4691 ResolveInfo info = resolveInfos.get(i); 4692 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4693 resolveInfos.remove(i); 4694 } 4695 } 4696 return resolveInfos; 4697 } 4698 4699 private static boolean hasWebURI(Intent intent) { 4700 if (intent.getData() == null) { 4701 return false; 4702 } 4703 final String scheme = intent.getScheme(); 4704 if (TextUtils.isEmpty(scheme)) { 4705 return false; 4706 } 4707 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4708 } 4709 4710 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4711 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4712 int userId) { 4713 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4714 4715 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4716 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4717 candidates.size()); 4718 } 4719 4720 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4721 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4722 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4723 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4724 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4725 4726 synchronized (mPackages) { 4727 final int count = candidates.size(); 4728 // First, try to use linked apps. Partition the candidates into four lists: 4729 // one for the final results, one for the "do not use ever", one for "undefined status" 4730 // and finally one for "browser app type". 4731 for (int n=0; n<count; n++) { 4732 ResolveInfo info = candidates.get(n); 4733 String packageName = info.activityInfo.packageName; 4734 PackageSetting ps = mSettings.mPackages.get(packageName); 4735 if (ps != null) { 4736 // Add to the special match all list (Browser use case) 4737 if (info.handleAllWebDataURI) { 4738 matchAllList.add(info); 4739 continue; 4740 } 4741 // Try to get the status from User settings first 4742 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4743 int status = (int)(packedStatus >> 32); 4744 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4745 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4746 if (DEBUG_DOMAIN_VERIFICATION) { 4747 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4748 + " : linkgen=" + linkGeneration); 4749 } 4750 // Use link-enabled generation as preferredOrder, i.e. 4751 // prefer newly-enabled over earlier-enabled. 4752 info.preferredOrder = linkGeneration; 4753 alwaysList.add(info); 4754 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4755 if (DEBUG_DOMAIN_VERIFICATION) { 4756 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4757 } 4758 neverList.add(info); 4759 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4760 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4761 if (DEBUG_DOMAIN_VERIFICATION) { 4762 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4763 } 4764 undefinedList.add(info); 4765 } 4766 } 4767 } 4768 // First try to add the "always" resolution(s) for the current user, if any 4769 if (alwaysList.size() > 0) { 4770 result.addAll(alwaysList); 4771 // if there is an "always" for the parent user, add it. 4772 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4773 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4774 result.add(xpDomainInfo.resolveInfo); 4775 } else { 4776 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4777 result.addAll(undefinedList); 4778 if (xpDomainInfo != null && ( 4779 xpDomainInfo.bestDomainVerificationStatus 4780 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4781 || xpDomainInfo.bestDomainVerificationStatus 4782 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4783 result.add(xpDomainInfo.resolveInfo); 4784 } 4785 // Also add Browsers (all of them or only the default one) 4786 if ((matchFlags & MATCH_ALL) != 0) { 4787 result.addAll(matchAllList); 4788 } else { 4789 // Browser/generic handling case. If there's a default browser, go straight 4790 // to that (but only if there is no other higher-priority match). 4791 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4792 int maxMatchPrio = 0; 4793 ResolveInfo defaultBrowserMatch = null; 4794 final int numCandidates = matchAllList.size(); 4795 for (int n = 0; n < numCandidates; n++) { 4796 ResolveInfo info = matchAllList.get(n); 4797 // track the highest overall match priority... 4798 if (info.priority > maxMatchPrio) { 4799 maxMatchPrio = info.priority; 4800 } 4801 // ...and the highest-priority default browser match 4802 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4803 if (defaultBrowserMatch == null 4804 || (defaultBrowserMatch.priority < info.priority)) { 4805 if (debug) { 4806 Slog.v(TAG, "Considering default browser match " + info); 4807 } 4808 defaultBrowserMatch = info; 4809 } 4810 } 4811 } 4812 if (defaultBrowserMatch != null 4813 && defaultBrowserMatch.priority >= maxMatchPrio 4814 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4815 { 4816 if (debug) { 4817 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4818 } 4819 result.add(defaultBrowserMatch); 4820 } else { 4821 result.addAll(matchAllList); 4822 } 4823 } 4824 4825 // If there is nothing selected, add all candidates and remove the ones that the user 4826 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4827 if (result.size() == 0) { 4828 result.addAll(candidates); 4829 result.removeAll(neverList); 4830 } 4831 } 4832 } 4833 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4834 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4835 result.size()); 4836 for (ResolveInfo info : result) { 4837 Slog.v(TAG, " + " + info.activityInfo); 4838 } 4839 } 4840 return result; 4841 } 4842 4843 // Returns a packed value as a long: 4844 // 4845 // high 'int'-sized word: link status: undefined/ask/never/always. 4846 // low 'int'-sized word: relative priority among 'always' results. 4847 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4848 long result = ps.getDomainVerificationStatusForUser(userId); 4849 // if none available, get the master status 4850 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4851 if (ps.getIntentFilterVerificationInfo() != null) { 4852 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4853 } 4854 } 4855 return result; 4856 } 4857 4858 private ResolveInfo querySkipCurrentProfileIntents( 4859 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4860 int flags, int sourceUserId) { 4861 if (matchingFilters != null) { 4862 int size = matchingFilters.size(); 4863 for (int i = 0; i < size; i ++) { 4864 CrossProfileIntentFilter filter = matchingFilters.get(i); 4865 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4866 // Checking if there are activities in the target user that can handle the 4867 // intent. 4868 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4869 flags, sourceUserId); 4870 if (resolveInfo != null) { 4871 return resolveInfo; 4872 } 4873 } 4874 } 4875 } 4876 return null; 4877 } 4878 4879 // Return matching ResolveInfo if any for skip current profile intent filters. 4880 private ResolveInfo queryCrossProfileIntents( 4881 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4882 int flags, int sourceUserId) { 4883 if (matchingFilters != null) { 4884 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4885 // match the same intent. For performance reasons, it is better not to 4886 // run queryIntent twice for the same userId 4887 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4888 int size = matchingFilters.size(); 4889 for (int i = 0; i < size; i++) { 4890 CrossProfileIntentFilter filter = matchingFilters.get(i); 4891 int targetUserId = filter.getTargetUserId(); 4892 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4893 && !alreadyTriedUserIds.get(targetUserId)) { 4894 // Checking if there are activities in the target user that can handle the 4895 // intent. 4896 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4897 flags, sourceUserId); 4898 if (resolveInfo != null) return resolveInfo; 4899 alreadyTriedUserIds.put(targetUserId, true); 4900 } 4901 } 4902 } 4903 return null; 4904 } 4905 4906 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4907 String resolvedType, int flags, int sourceUserId) { 4908 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4909 resolvedType, flags, filter.getTargetUserId()); 4910 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4911 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4912 } 4913 return null; 4914 } 4915 4916 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4917 int sourceUserId, int targetUserId) { 4918 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4919 String className; 4920 if (targetUserId == UserHandle.USER_OWNER) { 4921 className = FORWARD_INTENT_TO_USER_OWNER; 4922 } else { 4923 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4924 } 4925 ComponentName forwardingActivityComponentName = new ComponentName( 4926 mAndroidApplication.packageName, className); 4927 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4928 sourceUserId); 4929 if (targetUserId == UserHandle.USER_OWNER) { 4930 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4931 forwardingResolveInfo.noResourceId = true; 4932 } 4933 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4934 forwardingResolveInfo.priority = 0; 4935 forwardingResolveInfo.preferredOrder = 0; 4936 forwardingResolveInfo.match = 0; 4937 forwardingResolveInfo.isDefault = true; 4938 forwardingResolveInfo.filter = filter; 4939 forwardingResolveInfo.targetUserId = targetUserId; 4940 return forwardingResolveInfo; 4941 } 4942 4943 @Override 4944 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4945 Intent[] specifics, String[] specificTypes, Intent intent, 4946 String resolvedType, int flags, int userId) { 4947 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4948 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4949 false, "query intent activity options"); 4950 final String resultsAction = intent.getAction(); 4951 4952 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4953 | PackageManager.GET_RESOLVED_FILTER, userId); 4954 4955 if (DEBUG_INTENT_MATCHING) { 4956 Log.v(TAG, "Query " + intent + ": " + results); 4957 } 4958 4959 int specificsPos = 0; 4960 int N; 4961 4962 // todo: note that the algorithm used here is O(N^2). This 4963 // isn't a problem in our current environment, but if we start running 4964 // into situations where we have more than 5 or 10 matches then this 4965 // should probably be changed to something smarter... 4966 4967 // First we go through and resolve each of the specific items 4968 // that were supplied, taking care of removing any corresponding 4969 // duplicate items in the generic resolve list. 4970 if (specifics != null) { 4971 for (int i=0; i<specifics.length; i++) { 4972 final Intent sintent = specifics[i]; 4973 if (sintent == null) { 4974 continue; 4975 } 4976 4977 if (DEBUG_INTENT_MATCHING) { 4978 Log.v(TAG, "Specific #" + i + ": " + sintent); 4979 } 4980 4981 String action = sintent.getAction(); 4982 if (resultsAction != null && resultsAction.equals(action)) { 4983 // If this action was explicitly requested, then don't 4984 // remove things that have it. 4985 action = null; 4986 } 4987 4988 ResolveInfo ri = null; 4989 ActivityInfo ai = null; 4990 4991 ComponentName comp = sintent.getComponent(); 4992 if (comp == null) { 4993 ri = resolveIntent( 4994 sintent, 4995 specificTypes != null ? specificTypes[i] : null, 4996 flags, userId); 4997 if (ri == null) { 4998 continue; 4999 } 5000 if (ri == mResolveInfo) { 5001 // ACK! Must do something better with this. 5002 } 5003 ai = ri.activityInfo; 5004 comp = new ComponentName(ai.applicationInfo.packageName, 5005 ai.name); 5006 } else { 5007 ai = getActivityInfo(comp, flags, userId); 5008 if (ai == null) { 5009 continue; 5010 } 5011 } 5012 5013 // Look for any generic query activities that are duplicates 5014 // of this specific one, and remove them from the results. 5015 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5016 N = results.size(); 5017 int j; 5018 for (j=specificsPos; j<N; j++) { 5019 ResolveInfo sri = results.get(j); 5020 if ((sri.activityInfo.name.equals(comp.getClassName()) 5021 && sri.activityInfo.applicationInfo.packageName.equals( 5022 comp.getPackageName())) 5023 || (action != null && sri.filter.matchAction(action))) { 5024 results.remove(j); 5025 if (DEBUG_INTENT_MATCHING) Log.v( 5026 TAG, "Removing duplicate item from " + j 5027 + " due to specific " + specificsPos); 5028 if (ri == null) { 5029 ri = sri; 5030 } 5031 j--; 5032 N--; 5033 } 5034 } 5035 5036 // Add this specific item to its proper place. 5037 if (ri == null) { 5038 ri = new ResolveInfo(); 5039 ri.activityInfo = ai; 5040 } 5041 results.add(specificsPos, ri); 5042 ri.specificIndex = i; 5043 specificsPos++; 5044 } 5045 } 5046 5047 // Now we go through the remaining generic results and remove any 5048 // duplicate actions that are found here. 5049 N = results.size(); 5050 for (int i=specificsPos; i<N-1; i++) { 5051 final ResolveInfo rii = results.get(i); 5052 if (rii.filter == null) { 5053 continue; 5054 } 5055 5056 // Iterate over all of the actions of this result's intent 5057 // filter... typically this should be just one. 5058 final Iterator<String> it = rii.filter.actionsIterator(); 5059 if (it == null) { 5060 continue; 5061 } 5062 while (it.hasNext()) { 5063 final String action = it.next(); 5064 if (resultsAction != null && resultsAction.equals(action)) { 5065 // If this action was explicitly requested, then don't 5066 // remove things that have it. 5067 continue; 5068 } 5069 for (int j=i+1; j<N; j++) { 5070 final ResolveInfo rij = results.get(j); 5071 if (rij.filter != null && rij.filter.hasAction(action)) { 5072 results.remove(j); 5073 if (DEBUG_INTENT_MATCHING) Log.v( 5074 TAG, "Removing duplicate item from " + j 5075 + " due to action " + action + " at " + i); 5076 j--; 5077 N--; 5078 } 5079 } 5080 } 5081 5082 // If the caller didn't request filter information, drop it now 5083 // so we don't have to marshall/unmarshall it. 5084 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5085 rii.filter = null; 5086 } 5087 } 5088 5089 // Filter out the caller activity if so requested. 5090 if (caller != null) { 5091 N = results.size(); 5092 for (int i=0; i<N; i++) { 5093 ActivityInfo ainfo = results.get(i).activityInfo; 5094 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5095 && caller.getClassName().equals(ainfo.name)) { 5096 results.remove(i); 5097 break; 5098 } 5099 } 5100 } 5101 5102 // If the caller didn't request filter information, 5103 // drop them now so we don't have to 5104 // marshall/unmarshall it. 5105 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5106 N = results.size(); 5107 for (int i=0; i<N; i++) { 5108 results.get(i).filter = null; 5109 } 5110 } 5111 5112 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5113 return results; 5114 } 5115 5116 @Override 5117 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5118 int userId) { 5119 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5120 ComponentName comp = intent.getComponent(); 5121 if (comp == null) { 5122 if (intent.getSelector() != null) { 5123 intent = intent.getSelector(); 5124 comp = intent.getComponent(); 5125 } 5126 } 5127 if (comp != null) { 5128 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5129 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5130 if (ai != null) { 5131 ResolveInfo ri = new ResolveInfo(); 5132 ri.activityInfo = ai; 5133 list.add(ri); 5134 } 5135 return list; 5136 } 5137 5138 // reader 5139 synchronized (mPackages) { 5140 String pkgName = intent.getPackage(); 5141 if (pkgName == null) { 5142 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5143 } 5144 final PackageParser.Package pkg = mPackages.get(pkgName); 5145 if (pkg != null) { 5146 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5147 userId); 5148 } 5149 return null; 5150 } 5151 } 5152 5153 @Override 5154 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5155 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5156 if (!sUserManager.exists(userId)) return null; 5157 if (query != null) { 5158 if (query.size() >= 1) { 5159 // If there is more than one service with the same priority, 5160 // just arbitrarily pick the first one. 5161 return query.get(0); 5162 } 5163 } 5164 return null; 5165 } 5166 5167 @Override 5168 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5169 int userId) { 5170 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5171 ComponentName comp = intent.getComponent(); 5172 if (comp == null) { 5173 if (intent.getSelector() != null) { 5174 intent = intent.getSelector(); 5175 comp = intent.getComponent(); 5176 } 5177 } 5178 if (comp != null) { 5179 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5180 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5181 if (si != null) { 5182 final ResolveInfo ri = new ResolveInfo(); 5183 ri.serviceInfo = si; 5184 list.add(ri); 5185 } 5186 return list; 5187 } 5188 5189 // reader 5190 synchronized (mPackages) { 5191 String pkgName = intent.getPackage(); 5192 if (pkgName == null) { 5193 return mServices.queryIntent(intent, resolvedType, flags, userId); 5194 } 5195 final PackageParser.Package pkg = mPackages.get(pkgName); 5196 if (pkg != null) { 5197 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5198 userId); 5199 } 5200 return null; 5201 } 5202 } 5203 5204 @Override 5205 public List<ResolveInfo> queryIntentContentProviders( 5206 Intent intent, String resolvedType, int flags, int userId) { 5207 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5208 ComponentName comp = intent.getComponent(); 5209 if (comp == null) { 5210 if (intent.getSelector() != null) { 5211 intent = intent.getSelector(); 5212 comp = intent.getComponent(); 5213 } 5214 } 5215 if (comp != null) { 5216 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5217 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5218 if (pi != null) { 5219 final ResolveInfo ri = new ResolveInfo(); 5220 ri.providerInfo = pi; 5221 list.add(ri); 5222 } 5223 return list; 5224 } 5225 5226 // reader 5227 synchronized (mPackages) { 5228 String pkgName = intent.getPackage(); 5229 if (pkgName == null) { 5230 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5231 } 5232 final PackageParser.Package pkg = mPackages.get(pkgName); 5233 if (pkg != null) { 5234 return mProviders.queryIntentForPackage( 5235 intent, resolvedType, flags, pkg.providers, userId); 5236 } 5237 return null; 5238 } 5239 } 5240 5241 @Override 5242 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5243 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5244 5245 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5246 5247 // writer 5248 synchronized (mPackages) { 5249 ArrayList<PackageInfo> list; 5250 if (listUninstalled) { 5251 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5252 for (PackageSetting ps : mSettings.mPackages.values()) { 5253 PackageInfo pi; 5254 if (ps.pkg != null) { 5255 pi = generatePackageInfo(ps.pkg, flags, userId); 5256 } else { 5257 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5258 } 5259 if (pi != null) { 5260 list.add(pi); 5261 } 5262 } 5263 } else { 5264 list = new ArrayList<PackageInfo>(mPackages.size()); 5265 for (PackageParser.Package p : mPackages.values()) { 5266 PackageInfo pi = generatePackageInfo(p, flags, userId); 5267 if (pi != null) { 5268 list.add(pi); 5269 } 5270 } 5271 } 5272 5273 return new ParceledListSlice<PackageInfo>(list); 5274 } 5275 } 5276 5277 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5278 String[] permissions, boolean[] tmp, int flags, int userId) { 5279 int numMatch = 0; 5280 final PermissionsState permissionsState = ps.getPermissionsState(); 5281 for (int i=0; i<permissions.length; i++) { 5282 final String permission = permissions[i]; 5283 if (permissionsState.hasPermission(permission, userId)) { 5284 tmp[i] = true; 5285 numMatch++; 5286 } else { 5287 tmp[i] = false; 5288 } 5289 } 5290 if (numMatch == 0) { 5291 return; 5292 } 5293 PackageInfo pi; 5294 if (ps.pkg != null) { 5295 pi = generatePackageInfo(ps.pkg, flags, userId); 5296 } else { 5297 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5298 } 5299 // The above might return null in cases of uninstalled apps or install-state 5300 // skew across users/profiles. 5301 if (pi != null) { 5302 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5303 if (numMatch == permissions.length) { 5304 pi.requestedPermissions = permissions; 5305 } else { 5306 pi.requestedPermissions = new String[numMatch]; 5307 numMatch = 0; 5308 for (int i=0; i<permissions.length; i++) { 5309 if (tmp[i]) { 5310 pi.requestedPermissions[numMatch] = permissions[i]; 5311 numMatch++; 5312 } 5313 } 5314 } 5315 } 5316 list.add(pi); 5317 } 5318 } 5319 5320 @Override 5321 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5322 String[] permissions, int flags, int userId) { 5323 if (!sUserManager.exists(userId)) return null; 5324 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5325 5326 // writer 5327 synchronized (mPackages) { 5328 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5329 boolean[] tmpBools = new boolean[permissions.length]; 5330 if (listUninstalled) { 5331 for (PackageSetting ps : mSettings.mPackages.values()) { 5332 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5333 } 5334 } else { 5335 for (PackageParser.Package pkg : mPackages.values()) { 5336 PackageSetting ps = (PackageSetting)pkg.mExtras; 5337 if (ps != null) { 5338 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5339 userId); 5340 } 5341 } 5342 } 5343 5344 return new ParceledListSlice<PackageInfo>(list); 5345 } 5346 } 5347 5348 @Override 5349 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5350 if (!sUserManager.exists(userId)) return null; 5351 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5352 5353 // writer 5354 synchronized (mPackages) { 5355 ArrayList<ApplicationInfo> list; 5356 if (listUninstalled) { 5357 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5358 for (PackageSetting ps : mSettings.mPackages.values()) { 5359 ApplicationInfo ai; 5360 if (ps.pkg != null) { 5361 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5362 ps.readUserState(userId), userId); 5363 } else { 5364 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5365 } 5366 if (ai != null) { 5367 list.add(ai); 5368 } 5369 } 5370 } else { 5371 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5372 for (PackageParser.Package p : mPackages.values()) { 5373 if (p.mExtras != null) { 5374 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5375 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5376 if (ai != null) { 5377 list.add(ai); 5378 } 5379 } 5380 } 5381 } 5382 5383 return new ParceledListSlice<ApplicationInfo>(list); 5384 } 5385 } 5386 5387 public List<ApplicationInfo> getPersistentApplications(int flags) { 5388 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5389 5390 // reader 5391 synchronized (mPackages) { 5392 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5393 final int userId = UserHandle.getCallingUserId(); 5394 while (i.hasNext()) { 5395 final PackageParser.Package p = i.next(); 5396 if (p.applicationInfo != null 5397 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5398 && (!mSafeMode || isSystemApp(p))) { 5399 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5400 if (ps != null) { 5401 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5402 ps.readUserState(userId), userId); 5403 if (ai != null) { 5404 finalList.add(ai); 5405 } 5406 } 5407 } 5408 } 5409 } 5410 5411 return finalList; 5412 } 5413 5414 @Override 5415 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5416 if (!sUserManager.exists(userId)) return null; 5417 // reader 5418 synchronized (mPackages) { 5419 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5420 PackageSetting ps = provider != null 5421 ? mSettings.mPackages.get(provider.owner.packageName) 5422 : null; 5423 return ps != null 5424 && mSettings.isEnabledLPr(provider.info, flags, userId) 5425 && (!mSafeMode || (provider.info.applicationInfo.flags 5426 &ApplicationInfo.FLAG_SYSTEM) != 0) 5427 ? PackageParser.generateProviderInfo(provider, flags, 5428 ps.readUserState(userId), userId) 5429 : null; 5430 } 5431 } 5432 5433 /** 5434 * @deprecated 5435 */ 5436 @Deprecated 5437 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5438 // reader 5439 synchronized (mPackages) { 5440 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5441 .entrySet().iterator(); 5442 final int userId = UserHandle.getCallingUserId(); 5443 while (i.hasNext()) { 5444 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5445 PackageParser.Provider p = entry.getValue(); 5446 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5447 5448 if (ps != null && p.syncable 5449 && (!mSafeMode || (p.info.applicationInfo.flags 5450 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5451 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5452 ps.readUserState(userId), userId); 5453 if (info != null) { 5454 outNames.add(entry.getKey()); 5455 outInfo.add(info); 5456 } 5457 } 5458 } 5459 } 5460 } 5461 5462 @Override 5463 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5464 int uid, int flags) { 5465 ArrayList<ProviderInfo> finalList = null; 5466 // reader 5467 synchronized (mPackages) { 5468 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5469 final int userId = processName != null ? 5470 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5471 while (i.hasNext()) { 5472 final PackageParser.Provider p = i.next(); 5473 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5474 if (ps != null && p.info.authority != null 5475 && (processName == null 5476 || (p.info.processName.equals(processName) 5477 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5478 && mSettings.isEnabledLPr(p.info, flags, userId) 5479 && (!mSafeMode 5480 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5481 if (finalList == null) { 5482 finalList = new ArrayList<ProviderInfo>(3); 5483 } 5484 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5485 ps.readUserState(userId), userId); 5486 if (info != null) { 5487 finalList.add(info); 5488 } 5489 } 5490 } 5491 } 5492 5493 if (finalList != null) { 5494 Collections.sort(finalList, mProviderInitOrderSorter); 5495 return new ParceledListSlice<ProviderInfo>(finalList); 5496 } 5497 5498 return null; 5499 } 5500 5501 @Override 5502 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5503 int flags) { 5504 // reader 5505 synchronized (mPackages) { 5506 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5507 return PackageParser.generateInstrumentationInfo(i, flags); 5508 } 5509 } 5510 5511 @Override 5512 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5513 int flags) { 5514 ArrayList<InstrumentationInfo> finalList = 5515 new ArrayList<InstrumentationInfo>(); 5516 5517 // reader 5518 synchronized (mPackages) { 5519 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5520 while (i.hasNext()) { 5521 final PackageParser.Instrumentation p = i.next(); 5522 if (targetPackage == null 5523 || targetPackage.equals(p.info.targetPackage)) { 5524 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5525 flags); 5526 if (ii != null) { 5527 finalList.add(ii); 5528 } 5529 } 5530 } 5531 } 5532 5533 return finalList; 5534 } 5535 5536 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5537 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5538 if (overlays == null) { 5539 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5540 return; 5541 } 5542 for (PackageParser.Package opkg : overlays.values()) { 5543 // Not much to do if idmap fails: we already logged the error 5544 // and we certainly don't want to abort installation of pkg simply 5545 // because an overlay didn't fit properly. For these reasons, 5546 // ignore the return value of createIdmapForPackagePairLI. 5547 createIdmapForPackagePairLI(pkg, opkg); 5548 } 5549 } 5550 5551 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5552 PackageParser.Package opkg) { 5553 if (!opkg.mTrustedOverlay) { 5554 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5555 opkg.baseCodePath + ": overlay not trusted"); 5556 return false; 5557 } 5558 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5559 if (overlaySet == null) { 5560 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5561 opkg.baseCodePath + " but target package has no known overlays"); 5562 return false; 5563 } 5564 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5565 // TODO: generate idmap for split APKs 5566 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5567 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5568 + opkg.baseCodePath); 5569 return false; 5570 } 5571 PackageParser.Package[] overlayArray = 5572 overlaySet.values().toArray(new PackageParser.Package[0]); 5573 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5574 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5575 return p1.mOverlayPriority - p2.mOverlayPriority; 5576 } 5577 }; 5578 Arrays.sort(overlayArray, cmp); 5579 5580 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5581 int i = 0; 5582 for (PackageParser.Package p : overlayArray) { 5583 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5584 } 5585 return true; 5586 } 5587 5588 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5589 final File[] files = dir.listFiles(); 5590 if (ArrayUtils.isEmpty(files)) { 5591 Log.d(TAG, "No files in app dir " + dir); 5592 return; 5593 } 5594 5595 if (DEBUG_PACKAGE_SCANNING) { 5596 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5597 + " flags=0x" + Integer.toHexString(parseFlags)); 5598 } 5599 5600 for (File file : files) { 5601 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5602 && !PackageInstallerService.isStageName(file.getName()); 5603 if (!isPackage) { 5604 // Ignore entries which are not packages 5605 continue; 5606 } 5607 try { 5608 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5609 scanFlags, currentTime, null); 5610 } catch (PackageManagerException e) { 5611 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5612 5613 // Delete invalid userdata apps 5614 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5615 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5616 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5617 if (file.isDirectory()) { 5618 mInstaller.rmPackageDir(file.getAbsolutePath()); 5619 } else { 5620 file.delete(); 5621 } 5622 } 5623 } 5624 } 5625 } 5626 5627 private static File getSettingsProblemFile() { 5628 File dataDir = Environment.getDataDirectory(); 5629 File systemDir = new File(dataDir, "system"); 5630 File fname = new File(systemDir, "uiderrors.txt"); 5631 return fname; 5632 } 5633 5634 static void reportSettingsProblem(int priority, String msg) { 5635 logCriticalInfo(priority, msg); 5636 } 5637 5638 static void logCriticalInfo(int priority, String msg) { 5639 Slog.println(priority, TAG, msg); 5640 EventLogTags.writePmCriticalInfo(msg); 5641 try { 5642 File fname = getSettingsProblemFile(); 5643 FileOutputStream out = new FileOutputStream(fname, true); 5644 PrintWriter pw = new FastPrintWriter(out); 5645 SimpleDateFormat formatter = new SimpleDateFormat(); 5646 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5647 pw.println(dateString + ": " + msg); 5648 pw.close(); 5649 FileUtils.setPermissions( 5650 fname.toString(), 5651 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5652 -1, -1); 5653 } catch (java.io.IOException e) { 5654 } 5655 } 5656 5657 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5658 PackageParser.Package pkg, File srcFile, int parseFlags) 5659 throws PackageManagerException { 5660 if (ps != null 5661 && ps.codePath.equals(srcFile) 5662 && ps.timeStamp == srcFile.lastModified() 5663 && !isCompatSignatureUpdateNeeded(pkg) 5664 && !isRecoverSignatureUpdateNeeded(pkg)) { 5665 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5666 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5667 ArraySet<PublicKey> signingKs; 5668 synchronized (mPackages) { 5669 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5670 } 5671 if (ps.signatures.mSignatures != null 5672 && ps.signatures.mSignatures.length != 0 5673 && signingKs != null) { 5674 // Optimization: reuse the existing cached certificates 5675 // if the package appears to be unchanged. 5676 pkg.mSignatures = ps.signatures.mSignatures; 5677 pkg.mSigningKeys = signingKs; 5678 return; 5679 } 5680 5681 Slog.w(TAG, "PackageSetting for " + ps.name 5682 + " is missing signatures. Collecting certs again to recover them."); 5683 } else { 5684 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5685 } 5686 5687 try { 5688 pp.collectCertificates(pkg, parseFlags); 5689 pp.collectManifestDigest(pkg); 5690 } catch (PackageParserException e) { 5691 throw PackageManagerException.from(e); 5692 } 5693 } 5694 5695 /** 5696 * Traces a package scan. 5697 * @see #scanPackageLI(File, int, int, long, UserHandle) 5698 */ 5699 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5700 long currentTime, UserHandle user) throws PackageManagerException { 5701 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5702 try { 5703 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5704 } finally { 5705 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5706 } 5707 } 5708 5709 /** 5710 * Scans a package and returns the newly parsed package. 5711 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5712 */ 5713 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5714 long currentTime, UserHandle user) throws PackageManagerException { 5715 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5716 parseFlags |= mDefParseFlags; 5717 PackageParser pp = new PackageParser(); 5718 pp.setSeparateProcesses(mSeparateProcesses); 5719 pp.setOnlyCoreApps(mOnlyCore); 5720 pp.setDisplayMetrics(mMetrics); 5721 5722 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5723 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5724 } 5725 5726 final PackageParser.Package pkg; 5727 try { 5728 pkg = pp.parsePackage(scanFile, parseFlags); 5729 } catch (PackageParserException e) { 5730 throw PackageManagerException.from(e); 5731 } 5732 5733 PackageSetting ps = null; 5734 PackageSetting updatedPkg; 5735 // reader 5736 synchronized (mPackages) { 5737 // Look to see if we already know about this package. 5738 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5739 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5740 // This package has been renamed to its original name. Let's 5741 // use that. 5742 ps = mSettings.peekPackageLPr(oldName); 5743 } 5744 // If there was no original package, see one for the real package name. 5745 if (ps == null) { 5746 ps = mSettings.peekPackageLPr(pkg.packageName); 5747 } 5748 // Check to see if this package could be hiding/updating a system 5749 // package. Must look for it either under the original or real 5750 // package name depending on our state. 5751 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5752 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5753 } 5754 boolean updatedPkgBetter = false; 5755 // First check if this is a system package that may involve an update 5756 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5757 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5758 // it needs to drop FLAG_PRIVILEGED. 5759 if (locationIsPrivileged(scanFile)) { 5760 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5761 } else { 5762 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5763 } 5764 5765 if (ps != null && !ps.codePath.equals(scanFile)) { 5766 // The path has changed from what was last scanned... check the 5767 // version of the new path against what we have stored to determine 5768 // what to do. 5769 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5770 if (pkg.mVersionCode <= ps.versionCode) { 5771 // The system package has been updated and the code path does not match 5772 // Ignore entry. Skip it. 5773 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5774 + " ignored: updated version " + ps.versionCode 5775 + " better than this " + pkg.mVersionCode); 5776 if (!updatedPkg.codePath.equals(scanFile)) { 5777 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5778 + ps.name + " changing from " + updatedPkg.codePathString 5779 + " to " + scanFile); 5780 updatedPkg.codePath = scanFile; 5781 updatedPkg.codePathString = scanFile.toString(); 5782 updatedPkg.resourcePath = scanFile; 5783 updatedPkg.resourcePathString = scanFile.toString(); 5784 } 5785 updatedPkg.pkg = pkg; 5786 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5787 "Package " + ps.name + " at " + scanFile 5788 + " ignored: updated version " + ps.versionCode 5789 + " better than this " + pkg.mVersionCode); 5790 } else { 5791 // The current app on the system partition is better than 5792 // what we have updated to on the data partition; switch 5793 // back to the system partition version. 5794 // At this point, its safely assumed that package installation for 5795 // apps in system partition will go through. If not there won't be a working 5796 // version of the app 5797 // writer 5798 synchronized (mPackages) { 5799 // Just remove the loaded entries from package lists. 5800 mPackages.remove(ps.name); 5801 } 5802 5803 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5804 + " reverting from " + ps.codePathString 5805 + ": new version " + pkg.mVersionCode 5806 + " better than installed " + ps.versionCode); 5807 5808 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5809 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5810 synchronized (mInstallLock) { 5811 args.cleanUpResourcesLI(); 5812 } 5813 synchronized (mPackages) { 5814 mSettings.enableSystemPackageLPw(ps.name); 5815 } 5816 updatedPkgBetter = true; 5817 } 5818 } 5819 } 5820 5821 if (updatedPkg != null) { 5822 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5823 // initially 5824 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5825 5826 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5827 // flag set initially 5828 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5829 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5830 } 5831 } 5832 5833 // Verify certificates against what was last scanned 5834 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5835 5836 /* 5837 * A new system app appeared, but we already had a non-system one of the 5838 * same name installed earlier. 5839 */ 5840 boolean shouldHideSystemApp = false; 5841 if (updatedPkg == null && ps != null 5842 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5843 /* 5844 * Check to make sure the signatures match first. If they don't, 5845 * wipe the installed application and its data. 5846 */ 5847 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5848 != PackageManager.SIGNATURE_MATCH) { 5849 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5850 + " signatures don't match existing userdata copy; removing"); 5851 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5852 ps = null; 5853 } else { 5854 /* 5855 * If the newly-added system app is an older version than the 5856 * already installed version, hide it. It will be scanned later 5857 * and re-added like an update. 5858 */ 5859 if (pkg.mVersionCode <= ps.versionCode) { 5860 shouldHideSystemApp = true; 5861 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5862 + " but new version " + pkg.mVersionCode + " better than installed " 5863 + ps.versionCode + "; hiding system"); 5864 } else { 5865 /* 5866 * The newly found system app is a newer version that the 5867 * one previously installed. Simply remove the 5868 * already-installed application and replace it with our own 5869 * while keeping the application data. 5870 */ 5871 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5872 + " reverting from " + ps.codePathString + ": new version " 5873 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5874 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5875 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5876 synchronized (mInstallLock) { 5877 args.cleanUpResourcesLI(); 5878 } 5879 } 5880 } 5881 } 5882 5883 // The apk is forward locked (not public) if its code and resources 5884 // are kept in different files. (except for app in either system or 5885 // vendor path). 5886 // TODO grab this value from PackageSettings 5887 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5888 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5889 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5890 } 5891 } 5892 5893 // TODO: extend to support forward-locked splits 5894 String resourcePath = null; 5895 String baseResourcePath = null; 5896 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5897 if (ps != null && ps.resourcePathString != null) { 5898 resourcePath = ps.resourcePathString; 5899 baseResourcePath = ps.resourcePathString; 5900 } else { 5901 // Should not happen at all. Just log an error. 5902 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5903 } 5904 } else { 5905 resourcePath = pkg.codePath; 5906 baseResourcePath = pkg.baseCodePath; 5907 } 5908 5909 // Set application objects path explicitly. 5910 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5911 pkg.applicationInfo.setCodePath(pkg.codePath); 5912 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5913 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5914 pkg.applicationInfo.setResourcePath(resourcePath); 5915 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5916 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5917 5918 // Note that we invoke the following method only if we are about to unpack an application 5919 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5920 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5921 5922 /* 5923 * If the system app should be overridden by a previously installed 5924 * data, hide the system app now and let the /data/app scan pick it up 5925 * again. 5926 */ 5927 if (shouldHideSystemApp) { 5928 synchronized (mPackages) { 5929 /* 5930 * We have to grant systems permissions before we hide, because 5931 * grantPermissions will assume the package update is trying to 5932 * expand its permissions. 5933 */ 5934 grantPermissionsLPw(pkg, true, pkg.packageName); 5935 mSettings.disableSystemPackageLPw(pkg.packageName); 5936 } 5937 } 5938 5939 return scannedPkg; 5940 } 5941 5942 private static String fixProcessName(String defProcessName, 5943 String processName, int uid) { 5944 if (processName == null) { 5945 return defProcessName; 5946 } 5947 return processName; 5948 } 5949 5950 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5951 throws PackageManagerException { 5952 if (pkgSetting.signatures.mSignatures != null) { 5953 // Already existing package. Make sure signatures match 5954 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5955 == PackageManager.SIGNATURE_MATCH; 5956 if (!match) { 5957 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5958 == PackageManager.SIGNATURE_MATCH; 5959 } 5960 if (!match) { 5961 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5962 == PackageManager.SIGNATURE_MATCH; 5963 } 5964 if (!match) { 5965 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5966 + pkg.packageName + " signatures do not match the " 5967 + "previously installed version; ignoring!"); 5968 } 5969 } 5970 5971 // Check for shared user signatures 5972 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5973 // Already existing package. Make sure signatures match 5974 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5975 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5976 if (!match) { 5977 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5978 == PackageManager.SIGNATURE_MATCH; 5979 } 5980 if (!match) { 5981 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5982 == PackageManager.SIGNATURE_MATCH; 5983 } 5984 if (!match) { 5985 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5986 "Package " + pkg.packageName 5987 + " has no signatures that match those in shared user " 5988 + pkgSetting.sharedUser.name + "; ignoring!"); 5989 } 5990 } 5991 } 5992 5993 /** 5994 * Enforces that only the system UID or root's UID can call a method exposed 5995 * via Binder. 5996 * 5997 * @param message used as message if SecurityException is thrown 5998 * @throws SecurityException if the caller is not system or root 5999 */ 6000 private static final void enforceSystemOrRoot(String message) { 6001 final int uid = Binder.getCallingUid(); 6002 if (uid != Process.SYSTEM_UID && uid != 0) { 6003 throw new SecurityException(message); 6004 } 6005 } 6006 6007 @Override 6008 public void performBootDexOpt() { 6009 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6010 6011 // Before everything else, see whether we need to fstrim. 6012 try { 6013 IMountService ms = PackageHelper.getMountService(); 6014 if (ms != null) { 6015 final boolean isUpgrade = isUpgrade(); 6016 boolean doTrim = isUpgrade; 6017 if (doTrim) { 6018 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6019 } else { 6020 final long interval = android.provider.Settings.Global.getLong( 6021 mContext.getContentResolver(), 6022 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6023 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6024 if (interval > 0) { 6025 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6026 if (timeSinceLast > interval) { 6027 doTrim = true; 6028 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6029 + "; running immediately"); 6030 } 6031 } 6032 } 6033 if (doTrim) { 6034 if (!isFirstBoot()) { 6035 try { 6036 ActivityManagerNative.getDefault().showBootMessage( 6037 mContext.getResources().getString( 6038 R.string.android_upgrading_fstrim), true); 6039 } catch (RemoteException e) { 6040 } 6041 } 6042 ms.runMaintenance(); 6043 } 6044 } else { 6045 Slog.e(TAG, "Mount service unavailable!"); 6046 } 6047 } catch (RemoteException e) { 6048 // Can't happen; MountService is local 6049 } 6050 6051 final ArraySet<PackageParser.Package> pkgs; 6052 synchronized (mPackages) { 6053 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6054 } 6055 6056 if (pkgs != null) { 6057 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6058 // in case the device runs out of space. 6059 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6060 // Give priority to core apps. 6061 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6062 PackageParser.Package pkg = it.next(); 6063 if (pkg.coreApp) { 6064 if (DEBUG_DEXOPT) { 6065 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6066 } 6067 sortedPkgs.add(pkg); 6068 it.remove(); 6069 } 6070 } 6071 // Give priority to system apps that listen for pre boot complete. 6072 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6073 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6074 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6075 PackageParser.Package pkg = it.next(); 6076 if (pkgNames.contains(pkg.packageName)) { 6077 if (DEBUG_DEXOPT) { 6078 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6079 } 6080 sortedPkgs.add(pkg); 6081 it.remove(); 6082 } 6083 } 6084 // Give priority to system apps. 6085 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6086 PackageParser.Package pkg = it.next(); 6087 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6088 if (DEBUG_DEXOPT) { 6089 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6090 } 6091 sortedPkgs.add(pkg); 6092 it.remove(); 6093 } 6094 } 6095 // Give priority to updated system apps. 6096 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6097 PackageParser.Package pkg = it.next(); 6098 if (pkg.isUpdatedSystemApp()) { 6099 if (DEBUG_DEXOPT) { 6100 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6101 } 6102 sortedPkgs.add(pkg); 6103 it.remove(); 6104 } 6105 } 6106 // Give priority to apps that listen for boot complete. 6107 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6108 pkgNames = getPackageNamesForIntent(intent); 6109 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6110 PackageParser.Package pkg = it.next(); 6111 if (pkgNames.contains(pkg.packageName)) { 6112 if (DEBUG_DEXOPT) { 6113 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6114 } 6115 sortedPkgs.add(pkg); 6116 it.remove(); 6117 } 6118 } 6119 // Filter out packages that aren't recently used. 6120 filterRecentlyUsedApps(pkgs); 6121 // Add all remaining apps. 6122 for (PackageParser.Package pkg : pkgs) { 6123 if (DEBUG_DEXOPT) { 6124 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6125 } 6126 sortedPkgs.add(pkg); 6127 } 6128 6129 // If we want to be lazy, filter everything that wasn't recently used. 6130 if (mLazyDexOpt) { 6131 filterRecentlyUsedApps(sortedPkgs); 6132 } 6133 6134 int i = 0; 6135 int total = sortedPkgs.size(); 6136 File dataDir = Environment.getDataDirectory(); 6137 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6138 if (lowThreshold == 0) { 6139 throw new IllegalStateException("Invalid low memory threshold"); 6140 } 6141 for (PackageParser.Package pkg : sortedPkgs) { 6142 long usableSpace = dataDir.getUsableSpace(); 6143 if (usableSpace < lowThreshold) { 6144 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6145 break; 6146 } 6147 performBootDexOpt(pkg, ++i, total); 6148 } 6149 } 6150 } 6151 6152 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6153 // Filter out packages that aren't recently used. 6154 // 6155 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6156 // should do a full dexopt. 6157 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6158 int total = pkgs.size(); 6159 int skipped = 0; 6160 long now = System.currentTimeMillis(); 6161 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6162 PackageParser.Package pkg = i.next(); 6163 long then = pkg.mLastPackageUsageTimeInMills; 6164 if (then + mDexOptLRUThresholdInMills < now) { 6165 if (DEBUG_DEXOPT) { 6166 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6167 ((then == 0) ? "never" : new Date(then))); 6168 } 6169 i.remove(); 6170 skipped++; 6171 } 6172 } 6173 if (DEBUG_DEXOPT) { 6174 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6175 } 6176 } 6177 } 6178 6179 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6180 List<ResolveInfo> ris = null; 6181 try { 6182 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6183 intent, null, 0, UserHandle.USER_OWNER); 6184 } catch (RemoteException e) { 6185 } 6186 ArraySet<String> pkgNames = new ArraySet<String>(); 6187 if (ris != null) { 6188 for (ResolveInfo ri : ris) { 6189 pkgNames.add(ri.activityInfo.packageName); 6190 } 6191 } 6192 return pkgNames; 6193 } 6194 6195 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6196 if (DEBUG_DEXOPT) { 6197 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6198 } 6199 if (!isFirstBoot()) { 6200 try { 6201 ActivityManagerNative.getDefault().showBootMessage( 6202 mContext.getResources().getString(R.string.android_upgrading_apk, 6203 curr, total), true); 6204 } catch (RemoteException e) { 6205 } 6206 } 6207 PackageParser.Package p = pkg; 6208 synchronized (mInstallLock) { 6209 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6210 false /* force dex */, false /* defer */, true /* include dependencies */); 6211 } 6212 } 6213 6214 @Override 6215 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6216 return performDexOpt(packageName, instructionSet, false); 6217 } 6218 6219 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6220 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6221 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6222 if (!dexopt && !updateUsage) { 6223 // We aren't going to dexopt or update usage, so bail early. 6224 return false; 6225 } 6226 PackageParser.Package p; 6227 final String targetInstructionSet; 6228 synchronized (mPackages) { 6229 p = mPackages.get(packageName); 6230 if (p == null) { 6231 return false; 6232 } 6233 if (updateUsage) { 6234 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6235 } 6236 mPackageUsage.write(false); 6237 if (!dexopt) { 6238 // We aren't going to dexopt, so bail early. 6239 return false; 6240 } 6241 6242 targetInstructionSet = instructionSet != null ? instructionSet : 6243 getPrimaryInstructionSet(p.applicationInfo); 6244 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6245 return false; 6246 } 6247 } 6248 long callingId = Binder.clearCallingIdentity(); 6249 try { 6250 synchronized (mInstallLock) { 6251 final String[] instructionSets = new String[] { targetInstructionSet }; 6252 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6253 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6254 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6255 } 6256 } finally { 6257 Binder.restoreCallingIdentity(callingId); 6258 } 6259 } 6260 6261 public ArraySet<String> getPackagesThatNeedDexOpt() { 6262 ArraySet<String> pkgs = null; 6263 synchronized (mPackages) { 6264 for (PackageParser.Package p : mPackages.values()) { 6265 if (DEBUG_DEXOPT) { 6266 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6267 } 6268 if (!p.mDexOptPerformed.isEmpty()) { 6269 continue; 6270 } 6271 if (pkgs == null) { 6272 pkgs = new ArraySet<String>(); 6273 } 6274 pkgs.add(p.packageName); 6275 } 6276 } 6277 return pkgs; 6278 } 6279 6280 public void shutdown() { 6281 mPackageUsage.write(true); 6282 } 6283 6284 @Override 6285 public void forceDexOpt(String packageName) { 6286 enforceSystemOrRoot("forceDexOpt"); 6287 6288 PackageParser.Package pkg; 6289 synchronized (mPackages) { 6290 pkg = mPackages.get(packageName); 6291 if (pkg == null) { 6292 throw new IllegalArgumentException("Missing package: " + packageName); 6293 } 6294 } 6295 6296 synchronized (mInstallLock) { 6297 final String[] instructionSets = new String[] { 6298 getPrimaryInstructionSet(pkg.applicationInfo) }; 6299 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6300 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6301 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6302 throw new IllegalStateException("Failed to dexopt: " + res); 6303 } 6304 } 6305 } 6306 6307 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6308 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6309 Slog.w(TAG, "Unable to update from " + oldPkg.name 6310 + " to " + newPkg.packageName 6311 + ": old package not in system partition"); 6312 return false; 6313 } else if (mPackages.get(oldPkg.name) != null) { 6314 Slog.w(TAG, "Unable to update from " + oldPkg.name 6315 + " to " + newPkg.packageName 6316 + ": old package still exists"); 6317 return false; 6318 } 6319 return true; 6320 } 6321 6322 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6323 int[] users = sUserManager.getUserIds(); 6324 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6325 if (res < 0) { 6326 return res; 6327 } 6328 for (int user : users) { 6329 if (user != 0) { 6330 res = mInstaller.createUserData(volumeUuid, packageName, 6331 UserHandle.getUid(user, uid), user, seinfo); 6332 if (res < 0) { 6333 return res; 6334 } 6335 } 6336 } 6337 return res; 6338 } 6339 6340 private int removeDataDirsLI(String volumeUuid, String packageName) { 6341 int[] users = sUserManager.getUserIds(); 6342 int res = 0; 6343 for (int user : users) { 6344 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6345 if (resInner < 0) { 6346 res = resInner; 6347 } 6348 } 6349 6350 return res; 6351 } 6352 6353 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6354 int[] users = sUserManager.getUserIds(); 6355 int res = 0; 6356 for (int user : users) { 6357 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6358 if (resInner < 0) { 6359 res = resInner; 6360 } 6361 } 6362 return res; 6363 } 6364 6365 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6366 PackageParser.Package changingLib) { 6367 if (file.path != null) { 6368 usesLibraryFiles.add(file.path); 6369 return; 6370 } 6371 PackageParser.Package p = mPackages.get(file.apk); 6372 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6373 // If we are doing this while in the middle of updating a library apk, 6374 // then we need to make sure to use that new apk for determining the 6375 // dependencies here. (We haven't yet finished committing the new apk 6376 // to the package manager state.) 6377 if (p == null || p.packageName.equals(changingLib.packageName)) { 6378 p = changingLib; 6379 } 6380 } 6381 if (p != null) { 6382 usesLibraryFiles.addAll(p.getAllCodePaths()); 6383 } 6384 } 6385 6386 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6387 PackageParser.Package changingLib) throws PackageManagerException { 6388 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6389 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6390 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6391 for (int i=0; i<N; i++) { 6392 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6393 if (file == null) { 6394 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6395 "Package " + pkg.packageName + " requires unavailable shared library " 6396 + pkg.usesLibraries.get(i) + "; failing!"); 6397 } 6398 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6399 } 6400 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6401 for (int i=0; i<N; i++) { 6402 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6403 if (file == null) { 6404 Slog.w(TAG, "Package " + pkg.packageName 6405 + " desires unavailable shared library " 6406 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6407 } else { 6408 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6409 } 6410 } 6411 N = usesLibraryFiles.size(); 6412 if (N > 0) { 6413 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6414 } else { 6415 pkg.usesLibraryFiles = null; 6416 } 6417 } 6418 } 6419 6420 private static boolean hasString(List<String> list, List<String> which) { 6421 if (list == null) { 6422 return false; 6423 } 6424 for (int i=list.size()-1; i>=0; i--) { 6425 for (int j=which.size()-1; j>=0; j--) { 6426 if (which.get(j).equals(list.get(i))) { 6427 return true; 6428 } 6429 } 6430 } 6431 return false; 6432 } 6433 6434 private void updateAllSharedLibrariesLPw() { 6435 for (PackageParser.Package pkg : mPackages.values()) { 6436 try { 6437 updateSharedLibrariesLPw(pkg, null); 6438 } catch (PackageManagerException e) { 6439 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6440 } 6441 } 6442 } 6443 6444 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6445 PackageParser.Package changingPkg) { 6446 ArrayList<PackageParser.Package> res = null; 6447 for (PackageParser.Package pkg : mPackages.values()) { 6448 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6449 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6450 if (res == null) { 6451 res = new ArrayList<PackageParser.Package>(); 6452 } 6453 res.add(pkg); 6454 try { 6455 updateSharedLibrariesLPw(pkg, changingPkg); 6456 } catch (PackageManagerException e) { 6457 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6458 } 6459 } 6460 } 6461 return res; 6462 } 6463 6464 /** 6465 * Derive the value of the {@code cpuAbiOverride} based on the provided 6466 * value and an optional stored value from the package settings. 6467 */ 6468 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6469 String cpuAbiOverride = null; 6470 6471 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6472 cpuAbiOverride = null; 6473 } else if (abiOverride != null) { 6474 cpuAbiOverride = abiOverride; 6475 } else if (settings != null) { 6476 cpuAbiOverride = settings.cpuAbiOverrideString; 6477 } 6478 6479 return cpuAbiOverride; 6480 } 6481 6482 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6483 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6484 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6485 try { 6486 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6487 } finally { 6488 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6489 } 6490 } 6491 6492 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6493 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6494 boolean success = false; 6495 try { 6496 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6497 currentTime, user); 6498 success = true; 6499 return res; 6500 } finally { 6501 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6502 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6503 } 6504 } 6505 } 6506 6507 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6508 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6509 final File scanFile = new File(pkg.codePath); 6510 if (pkg.applicationInfo.getCodePath() == null || 6511 pkg.applicationInfo.getResourcePath() == null) { 6512 // Bail out. The resource and code paths haven't been set. 6513 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6514 "Code and resource paths haven't been set correctly"); 6515 } 6516 6517 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6518 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6519 } else { 6520 // Only allow system apps to be flagged as core apps. 6521 pkg.coreApp = false; 6522 } 6523 6524 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6525 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6526 } 6527 6528 if (mCustomResolverComponentName != null && 6529 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6530 setUpCustomResolverActivity(pkg); 6531 } 6532 6533 if (pkg.packageName.equals("android")) { 6534 synchronized (mPackages) { 6535 if (mAndroidApplication != null) { 6536 Slog.w(TAG, "*************************************************"); 6537 Slog.w(TAG, "Core android package being redefined. Skipping."); 6538 Slog.w(TAG, " file=" + scanFile); 6539 Slog.w(TAG, "*************************************************"); 6540 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6541 "Core android package being redefined. Skipping."); 6542 } 6543 6544 // Set up information for our fall-back user intent resolution activity. 6545 mPlatformPackage = pkg; 6546 pkg.mVersionCode = mSdkVersion; 6547 mAndroidApplication = pkg.applicationInfo; 6548 6549 if (!mResolverReplaced) { 6550 mResolveActivity.applicationInfo = mAndroidApplication; 6551 mResolveActivity.name = ResolverActivity.class.getName(); 6552 mResolveActivity.packageName = mAndroidApplication.packageName; 6553 mResolveActivity.processName = "system:ui"; 6554 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6555 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6556 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6557 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6558 mResolveActivity.exported = true; 6559 mResolveActivity.enabled = true; 6560 mResolveInfo.activityInfo = mResolveActivity; 6561 mResolveInfo.priority = 0; 6562 mResolveInfo.preferredOrder = 0; 6563 mResolveInfo.match = 0; 6564 mResolveComponentName = new ComponentName( 6565 mAndroidApplication.packageName, mResolveActivity.name); 6566 } 6567 } 6568 } 6569 6570 if (DEBUG_PACKAGE_SCANNING) { 6571 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6572 Log.d(TAG, "Scanning package " + pkg.packageName); 6573 } 6574 6575 if (mPackages.containsKey(pkg.packageName) 6576 || mSharedLibraries.containsKey(pkg.packageName)) { 6577 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6578 "Application package " + pkg.packageName 6579 + " already installed. Skipping duplicate."); 6580 } 6581 6582 // If we're only installing presumed-existing packages, require that the 6583 // scanned APK is both already known and at the path previously established 6584 // for it. Previously unknown packages we pick up normally, but if we have an 6585 // a priori expectation about this package's install presence, enforce it. 6586 // With a singular exception for new system packages. When an OTA contains 6587 // a new system package, we allow the codepath to change from a system location 6588 // to the user-installed location. If we don't allow this change, any newer, 6589 // user-installed version of the application will be ignored. 6590 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6591 if (mExpectingBetter.containsKey(pkg.packageName)) { 6592 logCriticalInfo(Log.WARN, 6593 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6594 } else { 6595 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6596 if (known != null) { 6597 if (DEBUG_PACKAGE_SCANNING) { 6598 Log.d(TAG, "Examining " + pkg.codePath 6599 + " and requiring known paths " + known.codePathString 6600 + " & " + known.resourcePathString); 6601 } 6602 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6603 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6604 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6605 "Application package " + pkg.packageName 6606 + " found at " + pkg.applicationInfo.getCodePath() 6607 + " but expected at " + known.codePathString + "; ignoring."); 6608 } 6609 } 6610 } 6611 } 6612 6613 // Initialize package source and resource directories 6614 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6615 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6616 6617 SharedUserSetting suid = null; 6618 PackageSetting pkgSetting = null; 6619 6620 if (!isSystemApp(pkg)) { 6621 // Only system apps can use these features. 6622 pkg.mOriginalPackages = null; 6623 pkg.mRealPackage = null; 6624 pkg.mAdoptPermissions = null; 6625 } 6626 6627 // writer 6628 synchronized (mPackages) { 6629 if (pkg.mSharedUserId != null) { 6630 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6631 if (suid == null) { 6632 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6633 "Creating application package " + pkg.packageName 6634 + " for shared user failed"); 6635 } 6636 if (DEBUG_PACKAGE_SCANNING) { 6637 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6638 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6639 + "): packages=" + suid.packages); 6640 } 6641 } 6642 6643 // Check if we are renaming from an original package name. 6644 PackageSetting origPackage = null; 6645 String realName = null; 6646 if (pkg.mOriginalPackages != null) { 6647 // This package may need to be renamed to a previously 6648 // installed name. Let's check on that... 6649 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6650 if (pkg.mOriginalPackages.contains(renamed)) { 6651 // This package had originally been installed as the 6652 // original name, and we have already taken care of 6653 // transitioning to the new one. Just update the new 6654 // one to continue using the old name. 6655 realName = pkg.mRealPackage; 6656 if (!pkg.packageName.equals(renamed)) { 6657 // Callers into this function may have already taken 6658 // care of renaming the package; only do it here if 6659 // it is not already done. 6660 pkg.setPackageName(renamed); 6661 } 6662 6663 } else { 6664 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6665 if ((origPackage = mSettings.peekPackageLPr( 6666 pkg.mOriginalPackages.get(i))) != null) { 6667 // We do have the package already installed under its 6668 // original name... should we use it? 6669 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6670 // New package is not compatible with original. 6671 origPackage = null; 6672 continue; 6673 } else if (origPackage.sharedUser != null) { 6674 // Make sure uid is compatible between packages. 6675 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6676 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6677 + " to " + pkg.packageName + ": old uid " 6678 + origPackage.sharedUser.name 6679 + " differs from " + pkg.mSharedUserId); 6680 origPackage = null; 6681 continue; 6682 } 6683 } else { 6684 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6685 + pkg.packageName + " to old name " + origPackage.name); 6686 } 6687 break; 6688 } 6689 } 6690 } 6691 } 6692 6693 if (mTransferedPackages.contains(pkg.packageName)) { 6694 Slog.w(TAG, "Package " + pkg.packageName 6695 + " was transferred to another, but its .apk remains"); 6696 } 6697 6698 // Just create the setting, don't add it yet. For already existing packages 6699 // the PkgSetting exists already and doesn't have to be created. 6700 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6701 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6702 pkg.applicationInfo.primaryCpuAbi, 6703 pkg.applicationInfo.secondaryCpuAbi, 6704 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6705 user, false); 6706 if (pkgSetting == null) { 6707 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6708 "Creating application package " + pkg.packageName + " failed"); 6709 } 6710 6711 if (pkgSetting.origPackage != null) { 6712 // If we are first transitioning from an original package, 6713 // fix up the new package's name now. We need to do this after 6714 // looking up the package under its new name, so getPackageLP 6715 // can take care of fiddling things correctly. 6716 pkg.setPackageName(origPackage.name); 6717 6718 // File a report about this. 6719 String msg = "New package " + pkgSetting.realName 6720 + " renamed to replace old package " + pkgSetting.name; 6721 reportSettingsProblem(Log.WARN, msg); 6722 6723 // Make a note of it. 6724 mTransferedPackages.add(origPackage.name); 6725 6726 // No longer need to retain this. 6727 pkgSetting.origPackage = null; 6728 } 6729 6730 if (realName != null) { 6731 // Make a note of it. 6732 mTransferedPackages.add(pkg.packageName); 6733 } 6734 6735 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6736 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6737 } 6738 6739 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6740 // Check all shared libraries and map to their actual file path. 6741 // We only do this here for apps not on a system dir, because those 6742 // are the only ones that can fail an install due to this. We 6743 // will take care of the system apps by updating all of their 6744 // library paths after the scan is done. 6745 updateSharedLibrariesLPw(pkg, null); 6746 } 6747 6748 if (mFoundPolicyFile) { 6749 SELinuxMMAC.assignSeinfoValue(pkg); 6750 } 6751 6752 pkg.applicationInfo.uid = pkgSetting.appId; 6753 pkg.mExtras = pkgSetting; 6754 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6755 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6756 // We just determined the app is signed correctly, so bring 6757 // over the latest parsed certs. 6758 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6759 } else { 6760 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6761 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6762 "Package " + pkg.packageName + " upgrade keys do not match the " 6763 + "previously installed version"); 6764 } else { 6765 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6766 String msg = "System package " + pkg.packageName 6767 + " signature changed; retaining data."; 6768 reportSettingsProblem(Log.WARN, msg); 6769 } 6770 } 6771 } else { 6772 try { 6773 verifySignaturesLP(pkgSetting, pkg); 6774 // We just determined the app is signed correctly, so bring 6775 // over the latest parsed certs. 6776 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6777 } catch (PackageManagerException e) { 6778 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6779 throw e; 6780 } 6781 // The signature has changed, but this package is in the system 6782 // image... let's recover! 6783 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6784 // However... if this package is part of a shared user, but it 6785 // doesn't match the signature of the shared user, let's fail. 6786 // What this means is that you can't change the signatures 6787 // associated with an overall shared user, which doesn't seem all 6788 // that unreasonable. 6789 if (pkgSetting.sharedUser != null) { 6790 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6791 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6792 throw new PackageManagerException( 6793 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6794 "Signature mismatch for shared user : " 6795 + pkgSetting.sharedUser); 6796 } 6797 } 6798 // File a report about this. 6799 String msg = "System package " + pkg.packageName 6800 + " signature changed; retaining data."; 6801 reportSettingsProblem(Log.WARN, msg); 6802 } 6803 } 6804 // Verify that this new package doesn't have any content providers 6805 // that conflict with existing packages. Only do this if the 6806 // package isn't already installed, since we don't want to break 6807 // things that are installed. 6808 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6809 final int N = pkg.providers.size(); 6810 int i; 6811 for (i=0; i<N; i++) { 6812 PackageParser.Provider p = pkg.providers.get(i); 6813 if (p.info.authority != null) { 6814 String names[] = p.info.authority.split(";"); 6815 for (int j = 0; j < names.length; j++) { 6816 if (mProvidersByAuthority.containsKey(names[j])) { 6817 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6818 final String otherPackageName = 6819 ((other != null && other.getComponentName() != null) ? 6820 other.getComponentName().getPackageName() : "?"); 6821 throw new PackageManagerException( 6822 INSTALL_FAILED_CONFLICTING_PROVIDER, 6823 "Can't install because provider name " + names[j] 6824 + " (in package " + pkg.applicationInfo.packageName 6825 + ") is already used by " + otherPackageName); 6826 } 6827 } 6828 } 6829 } 6830 } 6831 6832 if (pkg.mAdoptPermissions != null) { 6833 // This package wants to adopt ownership of permissions from 6834 // another package. 6835 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6836 final String origName = pkg.mAdoptPermissions.get(i); 6837 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6838 if (orig != null) { 6839 if (verifyPackageUpdateLPr(orig, pkg)) { 6840 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6841 + pkg.packageName); 6842 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6843 } 6844 } 6845 } 6846 } 6847 } 6848 6849 final String pkgName = pkg.packageName; 6850 6851 final long scanFileTime = scanFile.lastModified(); 6852 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6853 pkg.applicationInfo.processName = fixProcessName( 6854 pkg.applicationInfo.packageName, 6855 pkg.applicationInfo.processName, 6856 pkg.applicationInfo.uid); 6857 6858 File dataPath; 6859 if (mPlatformPackage == pkg) { 6860 // The system package is special. 6861 dataPath = new File(Environment.getDataDirectory(), "system"); 6862 6863 pkg.applicationInfo.dataDir = dataPath.getPath(); 6864 6865 } else { 6866 // This is a normal package, need to make its data directory. 6867 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6868 UserHandle.USER_OWNER, pkg.packageName); 6869 6870 boolean uidError = false; 6871 if (dataPath.exists()) { 6872 int currentUid = 0; 6873 try { 6874 StructStat stat = Os.stat(dataPath.getPath()); 6875 currentUid = stat.st_uid; 6876 } catch (ErrnoException e) { 6877 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6878 } 6879 6880 // If we have mismatched owners for the data path, we have a problem. 6881 if (currentUid != pkg.applicationInfo.uid) { 6882 boolean recovered = false; 6883 if (currentUid == 0) { 6884 // The directory somehow became owned by root. Wow. 6885 // This is probably because the system was stopped while 6886 // installd was in the middle of messing with its libs 6887 // directory. Ask installd to fix that. 6888 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6889 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6890 if (ret >= 0) { 6891 recovered = true; 6892 String msg = "Package " + pkg.packageName 6893 + " unexpectedly changed to uid 0; recovered to " + 6894 + pkg.applicationInfo.uid; 6895 reportSettingsProblem(Log.WARN, msg); 6896 } 6897 } 6898 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6899 || (scanFlags&SCAN_BOOTING) != 0)) { 6900 // If this is a system app, we can at least delete its 6901 // current data so the application will still work. 6902 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6903 if (ret >= 0) { 6904 // TODO: Kill the processes first 6905 // Old data gone! 6906 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6907 ? "System package " : "Third party package "; 6908 String msg = prefix + pkg.packageName 6909 + " has changed from uid: " 6910 + currentUid + " to " 6911 + pkg.applicationInfo.uid + "; old data erased"; 6912 reportSettingsProblem(Log.WARN, msg); 6913 recovered = true; 6914 6915 // And now re-install the app. 6916 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6917 pkg.applicationInfo.seinfo); 6918 if (ret == -1) { 6919 // Ack should not happen! 6920 msg = prefix + pkg.packageName 6921 + " could not have data directory re-created after delete."; 6922 reportSettingsProblem(Log.WARN, msg); 6923 throw new PackageManagerException( 6924 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6925 } 6926 } 6927 if (!recovered) { 6928 mHasSystemUidErrors = true; 6929 } 6930 } else if (!recovered) { 6931 // If we allow this install to proceed, we will be broken. 6932 // Abort, abort! 6933 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6934 "scanPackageLI"); 6935 } 6936 if (!recovered) { 6937 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6938 + pkg.applicationInfo.uid + "/fs_" 6939 + currentUid; 6940 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6941 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6942 String msg = "Package " + pkg.packageName 6943 + " has mismatched uid: " 6944 + currentUid + " on disk, " 6945 + pkg.applicationInfo.uid + " in settings"; 6946 // writer 6947 synchronized (mPackages) { 6948 mSettings.mReadMessages.append(msg); 6949 mSettings.mReadMessages.append('\n'); 6950 uidError = true; 6951 if (!pkgSetting.uidError) { 6952 reportSettingsProblem(Log.ERROR, msg); 6953 } 6954 } 6955 } 6956 } 6957 pkg.applicationInfo.dataDir = dataPath.getPath(); 6958 if (mShouldRestoreconData) { 6959 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6960 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6961 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6962 } 6963 } else { 6964 if (DEBUG_PACKAGE_SCANNING) { 6965 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6966 Log.v(TAG, "Want this data dir: " + dataPath); 6967 } 6968 //invoke installer to do the actual installation 6969 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6970 pkg.applicationInfo.seinfo); 6971 if (ret < 0) { 6972 // Error from installer 6973 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6974 "Unable to create data dirs [errorCode=" + ret + "]"); 6975 } 6976 6977 if (dataPath.exists()) { 6978 pkg.applicationInfo.dataDir = dataPath.getPath(); 6979 } else { 6980 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6981 pkg.applicationInfo.dataDir = null; 6982 } 6983 } 6984 6985 pkgSetting.uidError = uidError; 6986 } 6987 6988 final String path = scanFile.getPath(); 6989 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6990 6991 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6992 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6993 6994 // Some system apps still use directory structure for native libraries 6995 // in which case we might end up not detecting abi solely based on apk 6996 // structure. Try to detect abi based on directory structure. 6997 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6998 pkg.applicationInfo.primaryCpuAbi == null) { 6999 setBundledAppAbisAndRoots(pkg, pkgSetting); 7000 setNativeLibraryPaths(pkg); 7001 } 7002 7003 } else { 7004 if ((scanFlags & SCAN_MOVE) != 0) { 7005 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7006 // but we already have this packages package info in the PackageSetting. We just 7007 // use that and derive the native library path based on the new codepath. 7008 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7009 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7010 } 7011 7012 // Set native library paths again. For moves, the path will be updated based on the 7013 // ABIs we've determined above. For non-moves, the path will be updated based on the 7014 // ABIs we determined during compilation, but the path will depend on the final 7015 // package path (after the rename away from the stage path). 7016 setNativeLibraryPaths(pkg); 7017 } 7018 7019 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7020 final int[] userIds = sUserManager.getUserIds(); 7021 synchronized (mInstallLock) { 7022 // Make sure all user data directories are ready to roll; we're okay 7023 // if they already exist 7024 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7025 for (int userId : userIds) { 7026 if (userId != 0) { 7027 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7028 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7029 pkg.applicationInfo.seinfo); 7030 } 7031 } 7032 } 7033 7034 // Create a native library symlink only if we have native libraries 7035 // and if the native libraries are 32 bit libraries. We do not provide 7036 // this symlink for 64 bit libraries. 7037 if (pkg.applicationInfo.primaryCpuAbi != null && 7038 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7039 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7040 try { 7041 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7042 for (int userId : userIds) { 7043 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7044 nativeLibPath, userId) < 0) { 7045 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7046 "Failed linking native library dir (user=" + userId + ")"); 7047 } 7048 } 7049 } finally { 7050 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7051 } 7052 } 7053 } 7054 7055 // This is a special case for the "system" package, where the ABI is 7056 // dictated by the zygote configuration (and init.rc). We should keep track 7057 // of this ABI so that we can deal with "normal" applications that run under 7058 // the same UID correctly. 7059 if (mPlatformPackage == pkg) { 7060 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7061 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7062 } 7063 7064 // If there's a mismatch between the abi-override in the package setting 7065 // and the abiOverride specified for the install. Warn about this because we 7066 // would've already compiled the app without taking the package setting into 7067 // account. 7068 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7069 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7070 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7071 " for package: " + pkg.packageName); 7072 } 7073 } 7074 7075 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7076 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7077 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7078 7079 // Copy the derived override back to the parsed package, so that we can 7080 // update the package settings accordingly. 7081 pkg.cpuAbiOverride = cpuAbiOverride; 7082 7083 if (DEBUG_ABI_SELECTION) { 7084 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7085 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7086 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7087 } 7088 7089 // Push the derived path down into PackageSettings so we know what to 7090 // clean up at uninstall time. 7091 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7092 7093 if (DEBUG_ABI_SELECTION) { 7094 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7095 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7096 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7097 } 7098 7099 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7100 // We don't do this here during boot because we can do it all 7101 // at once after scanning all existing packages. 7102 // 7103 // We also do this *before* we perform dexopt on this package, so that 7104 // we can avoid redundant dexopts, and also to make sure we've got the 7105 // code and package path correct. 7106 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7107 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7108 } 7109 7110 if ((scanFlags & SCAN_NO_DEX) == 0) { 7111 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7112 7113 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7114 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7115 7116 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7117 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7118 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7119 } 7120 } 7121 if (mFactoryTest && pkg.requestedPermissions.contains( 7122 android.Manifest.permission.FACTORY_TEST)) { 7123 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7124 } 7125 7126 ArrayList<PackageParser.Package> clientLibPkgs = null; 7127 7128 // writer 7129 synchronized (mPackages) { 7130 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7131 // Only system apps can add new shared libraries. 7132 if (pkg.libraryNames != null) { 7133 for (int i=0; i<pkg.libraryNames.size(); i++) { 7134 String name = pkg.libraryNames.get(i); 7135 boolean allowed = false; 7136 if (pkg.isUpdatedSystemApp()) { 7137 // New library entries can only be added through the 7138 // system image. This is important to get rid of a lot 7139 // of nasty edge cases: for example if we allowed a non- 7140 // system update of the app to add a library, then uninstalling 7141 // the update would make the library go away, and assumptions 7142 // we made such as through app install filtering would now 7143 // have allowed apps on the device which aren't compatible 7144 // with it. Better to just have the restriction here, be 7145 // conservative, and create many fewer cases that can negatively 7146 // impact the user experience. 7147 final PackageSetting sysPs = mSettings 7148 .getDisabledSystemPkgLPr(pkg.packageName); 7149 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7150 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7151 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7152 allowed = true; 7153 allowed = true; 7154 break; 7155 } 7156 } 7157 } 7158 } else { 7159 allowed = true; 7160 } 7161 if (allowed) { 7162 if (!mSharedLibraries.containsKey(name)) { 7163 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7164 } else if (!name.equals(pkg.packageName)) { 7165 Slog.w(TAG, "Package " + pkg.packageName + " library " 7166 + name + " already exists; skipping"); 7167 } 7168 } else { 7169 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7170 + name + " that is not declared on system image; skipping"); 7171 } 7172 } 7173 if ((scanFlags&SCAN_BOOTING) == 0) { 7174 // If we are not booting, we need to update any applications 7175 // that are clients of our shared library. If we are booting, 7176 // this will all be done once the scan is complete. 7177 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7178 } 7179 } 7180 } 7181 } 7182 7183 // We also need to dexopt any apps that are dependent on this library. Note that 7184 // if these fail, we should abort the install since installing the library will 7185 // result in some apps being broken. 7186 if (clientLibPkgs != null) { 7187 if ((scanFlags & SCAN_NO_DEX) == 0) { 7188 for (int i = 0; i < clientLibPkgs.size(); i++) { 7189 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7190 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7191 null /* instruction sets */, forceDex, 7192 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7193 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7194 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7195 "scanPackageLI failed to dexopt clientLibPkgs"); 7196 } 7197 } 7198 } 7199 } 7200 7201 // Request the ActivityManager to kill the process(only for existing packages) 7202 // so that we do not end up in a confused state while the user is still using the older 7203 // version of the application while the new one gets installed. 7204 if ((scanFlags & SCAN_REPLACING) != 0) { 7205 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7206 7207 killApplication(pkg.applicationInfo.packageName, 7208 pkg.applicationInfo.uid, "replace pkg"); 7209 7210 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7211 } 7212 7213 // Also need to kill any apps that are dependent on the library. 7214 if (clientLibPkgs != null) { 7215 for (int i=0; i<clientLibPkgs.size(); i++) { 7216 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7217 killApplication(clientPkg.applicationInfo.packageName, 7218 clientPkg.applicationInfo.uid, "update lib"); 7219 } 7220 } 7221 7222 // Make sure we're not adding any bogus keyset info 7223 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7224 ksms.assertScannedPackageValid(pkg); 7225 7226 // writer 7227 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7228 7229 boolean createIdmapFailed = false; 7230 synchronized (mPackages) { 7231 // We don't expect installation to fail beyond this point 7232 7233 // Add the new setting to mSettings 7234 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7235 // Add the new setting to mPackages 7236 mPackages.put(pkg.applicationInfo.packageName, pkg); 7237 // Make sure we don't accidentally delete its data. 7238 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7239 while (iter.hasNext()) { 7240 PackageCleanItem item = iter.next(); 7241 if (pkgName.equals(item.packageName)) { 7242 iter.remove(); 7243 } 7244 } 7245 7246 // Take care of first install / last update times. 7247 if (currentTime != 0) { 7248 if (pkgSetting.firstInstallTime == 0) { 7249 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7250 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7251 pkgSetting.lastUpdateTime = currentTime; 7252 } 7253 } else if (pkgSetting.firstInstallTime == 0) { 7254 // We need *something*. Take time time stamp of the file. 7255 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7256 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7257 if (scanFileTime != pkgSetting.timeStamp) { 7258 // A package on the system image has changed; consider this 7259 // to be an update. 7260 pkgSetting.lastUpdateTime = scanFileTime; 7261 } 7262 } 7263 7264 // Add the package's KeySets to the global KeySetManagerService 7265 ksms.addScannedPackageLPw(pkg); 7266 7267 int N = pkg.providers.size(); 7268 StringBuilder r = null; 7269 int i; 7270 for (i=0; i<N; i++) { 7271 PackageParser.Provider p = pkg.providers.get(i); 7272 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7273 p.info.processName, pkg.applicationInfo.uid); 7274 mProviders.addProvider(p); 7275 p.syncable = p.info.isSyncable; 7276 if (p.info.authority != null) { 7277 String names[] = p.info.authority.split(";"); 7278 p.info.authority = null; 7279 for (int j = 0; j < names.length; j++) { 7280 if (j == 1 && p.syncable) { 7281 // We only want the first authority for a provider to possibly be 7282 // syncable, so if we already added this provider using a different 7283 // authority clear the syncable flag. We copy the provider before 7284 // changing it because the mProviders object contains a reference 7285 // to a provider that we don't want to change. 7286 // Only do this for the second authority since the resulting provider 7287 // object can be the same for all future authorities for this provider. 7288 p = new PackageParser.Provider(p); 7289 p.syncable = false; 7290 } 7291 if (!mProvidersByAuthority.containsKey(names[j])) { 7292 mProvidersByAuthority.put(names[j], p); 7293 if (p.info.authority == null) { 7294 p.info.authority = names[j]; 7295 } else { 7296 p.info.authority = p.info.authority + ";" + names[j]; 7297 } 7298 if (DEBUG_PACKAGE_SCANNING) { 7299 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7300 Log.d(TAG, "Registered content provider: " + names[j] 7301 + ", className = " + p.info.name + ", isSyncable = " 7302 + p.info.isSyncable); 7303 } 7304 } else { 7305 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7306 Slog.w(TAG, "Skipping provider name " + names[j] + 7307 " (in package " + pkg.applicationInfo.packageName + 7308 "): name already used by " 7309 + ((other != null && other.getComponentName() != null) 7310 ? other.getComponentName().getPackageName() : "?")); 7311 } 7312 } 7313 } 7314 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7315 if (r == null) { 7316 r = new StringBuilder(256); 7317 } else { 7318 r.append(' '); 7319 } 7320 r.append(p.info.name); 7321 } 7322 } 7323 if (r != null) { 7324 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7325 } 7326 7327 N = pkg.services.size(); 7328 r = null; 7329 for (i=0; i<N; i++) { 7330 PackageParser.Service s = pkg.services.get(i); 7331 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7332 s.info.processName, pkg.applicationInfo.uid); 7333 mServices.addService(s); 7334 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7335 if (r == null) { 7336 r = new StringBuilder(256); 7337 } else { 7338 r.append(' '); 7339 } 7340 r.append(s.info.name); 7341 } 7342 } 7343 if (r != null) { 7344 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7345 } 7346 7347 N = pkg.receivers.size(); 7348 r = null; 7349 for (i=0; i<N; i++) { 7350 PackageParser.Activity a = pkg.receivers.get(i); 7351 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7352 a.info.processName, pkg.applicationInfo.uid); 7353 mReceivers.addActivity(a, "receiver"); 7354 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7355 if (r == null) { 7356 r = new StringBuilder(256); 7357 } else { 7358 r.append(' '); 7359 } 7360 r.append(a.info.name); 7361 } 7362 } 7363 if (r != null) { 7364 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7365 } 7366 7367 N = pkg.activities.size(); 7368 r = null; 7369 for (i=0; i<N; i++) { 7370 PackageParser.Activity a = pkg.activities.get(i); 7371 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7372 a.info.processName, pkg.applicationInfo.uid); 7373 mActivities.addActivity(a, "activity"); 7374 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7375 if (r == null) { 7376 r = new StringBuilder(256); 7377 } else { 7378 r.append(' '); 7379 } 7380 r.append(a.info.name); 7381 } 7382 } 7383 if (r != null) { 7384 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7385 } 7386 7387 N = pkg.permissionGroups.size(); 7388 r = null; 7389 for (i=0; i<N; i++) { 7390 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7391 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7392 if (cur == null) { 7393 mPermissionGroups.put(pg.info.name, pg); 7394 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7395 if (r == null) { 7396 r = new StringBuilder(256); 7397 } else { 7398 r.append(' '); 7399 } 7400 r.append(pg.info.name); 7401 } 7402 } else { 7403 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7404 + pg.info.packageName + " ignored: original from " 7405 + cur.info.packageName); 7406 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7407 if (r == null) { 7408 r = new StringBuilder(256); 7409 } else { 7410 r.append(' '); 7411 } 7412 r.append("DUP:"); 7413 r.append(pg.info.name); 7414 } 7415 } 7416 } 7417 if (r != null) { 7418 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7419 } 7420 7421 N = pkg.permissions.size(); 7422 r = null; 7423 for (i=0; i<N; i++) { 7424 PackageParser.Permission p = pkg.permissions.get(i); 7425 7426 // Assume by default that we did not install this permission into the system. 7427 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7428 7429 // Now that permission groups have a special meaning, we ignore permission 7430 // groups for legacy apps to prevent unexpected behavior. In particular, 7431 // permissions for one app being granted to someone just becuase they happen 7432 // to be in a group defined by another app (before this had no implications). 7433 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7434 p.group = mPermissionGroups.get(p.info.group); 7435 // Warn for a permission in an unknown group. 7436 if (p.info.group != null && p.group == null) { 7437 Slog.w(TAG, "Permission " + p.info.name + " from package " 7438 + p.info.packageName + " in an unknown group " + p.info.group); 7439 } 7440 } 7441 7442 ArrayMap<String, BasePermission> permissionMap = 7443 p.tree ? mSettings.mPermissionTrees 7444 : mSettings.mPermissions; 7445 BasePermission bp = permissionMap.get(p.info.name); 7446 7447 // Allow system apps to redefine non-system permissions 7448 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7449 final boolean currentOwnerIsSystem = (bp.perm != null 7450 && isSystemApp(bp.perm.owner)); 7451 if (isSystemApp(p.owner)) { 7452 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7453 // It's a built-in permission and no owner, take ownership now 7454 bp.packageSetting = pkgSetting; 7455 bp.perm = p; 7456 bp.uid = pkg.applicationInfo.uid; 7457 bp.sourcePackage = p.info.packageName; 7458 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7459 } else if (!currentOwnerIsSystem) { 7460 String msg = "New decl " + p.owner + " of permission " 7461 + p.info.name + " is system; overriding " + bp.sourcePackage; 7462 reportSettingsProblem(Log.WARN, msg); 7463 bp = null; 7464 } 7465 } 7466 } 7467 7468 if (bp == null) { 7469 bp = new BasePermission(p.info.name, p.info.packageName, 7470 BasePermission.TYPE_NORMAL); 7471 permissionMap.put(p.info.name, bp); 7472 } 7473 7474 if (bp.perm == null) { 7475 if (bp.sourcePackage == null 7476 || bp.sourcePackage.equals(p.info.packageName)) { 7477 BasePermission tree = findPermissionTreeLP(p.info.name); 7478 if (tree == null 7479 || tree.sourcePackage.equals(p.info.packageName)) { 7480 bp.packageSetting = pkgSetting; 7481 bp.perm = p; 7482 bp.uid = pkg.applicationInfo.uid; 7483 bp.sourcePackage = p.info.packageName; 7484 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7485 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7486 if (r == null) { 7487 r = new StringBuilder(256); 7488 } else { 7489 r.append(' '); 7490 } 7491 r.append(p.info.name); 7492 } 7493 } else { 7494 Slog.w(TAG, "Permission " + p.info.name + " from package " 7495 + p.info.packageName + " ignored: base tree " 7496 + tree.name + " is from package " 7497 + tree.sourcePackage); 7498 } 7499 } else { 7500 Slog.w(TAG, "Permission " + p.info.name + " from package " 7501 + p.info.packageName + " ignored: original from " 7502 + bp.sourcePackage); 7503 } 7504 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7505 if (r == null) { 7506 r = new StringBuilder(256); 7507 } else { 7508 r.append(' '); 7509 } 7510 r.append("DUP:"); 7511 r.append(p.info.name); 7512 } 7513 if (bp.perm == p) { 7514 bp.protectionLevel = p.info.protectionLevel; 7515 } 7516 } 7517 7518 if (r != null) { 7519 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7520 } 7521 7522 N = pkg.instrumentation.size(); 7523 r = null; 7524 for (i=0; i<N; i++) { 7525 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7526 a.info.packageName = pkg.applicationInfo.packageName; 7527 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7528 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7529 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7530 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7531 a.info.dataDir = pkg.applicationInfo.dataDir; 7532 7533 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7534 // need other information about the application, like the ABI and what not ? 7535 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7536 mInstrumentation.put(a.getComponentName(), a); 7537 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7538 if (r == null) { 7539 r = new StringBuilder(256); 7540 } else { 7541 r.append(' '); 7542 } 7543 r.append(a.info.name); 7544 } 7545 } 7546 if (r != null) { 7547 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7548 } 7549 7550 if (pkg.protectedBroadcasts != null) { 7551 N = pkg.protectedBroadcasts.size(); 7552 for (i=0; i<N; i++) { 7553 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7554 } 7555 } 7556 7557 pkgSetting.setTimeStamp(scanFileTime); 7558 7559 // Create idmap files for pairs of (packages, overlay packages). 7560 // Note: "android", ie framework-res.apk, is handled by native layers. 7561 if (pkg.mOverlayTarget != null) { 7562 // This is an overlay package. 7563 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7564 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7565 mOverlays.put(pkg.mOverlayTarget, 7566 new ArrayMap<String, PackageParser.Package>()); 7567 } 7568 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7569 map.put(pkg.packageName, pkg); 7570 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7571 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7572 createIdmapFailed = true; 7573 } 7574 } 7575 } else if (mOverlays.containsKey(pkg.packageName) && 7576 !pkg.packageName.equals("android")) { 7577 // This is a regular package, with one or more known overlay packages. 7578 createIdmapsForPackageLI(pkg); 7579 } 7580 } 7581 7582 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7583 7584 if (createIdmapFailed) { 7585 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7586 "scanPackageLI failed to createIdmap"); 7587 } 7588 return pkg; 7589 } 7590 7591 /** 7592 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7593 * is derived purely on the basis of the contents of {@code scanFile} and 7594 * {@code cpuAbiOverride}. 7595 * 7596 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7597 */ 7598 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7599 String cpuAbiOverride, boolean extractLibs) 7600 throws PackageManagerException { 7601 // TODO: We can probably be smarter about this stuff. For installed apps, 7602 // we can calculate this information at install time once and for all. For 7603 // system apps, we can probably assume that this information doesn't change 7604 // after the first boot scan. As things stand, we do lots of unnecessary work. 7605 7606 // Give ourselves some initial paths; we'll come back for another 7607 // pass once we've determined ABI below. 7608 setNativeLibraryPaths(pkg); 7609 7610 // We would never need to extract libs for forward-locked and external packages, 7611 // since the container service will do it for us. We shouldn't attempt to 7612 // extract libs from system app when it was not updated. 7613 if (pkg.isForwardLocked() || isExternal(pkg) || 7614 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7615 extractLibs = false; 7616 } 7617 7618 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7619 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7620 7621 NativeLibraryHelper.Handle handle = null; 7622 try { 7623 handle = NativeLibraryHelper.Handle.create(pkg); 7624 // TODO(multiArch): This can be null for apps that didn't go through the 7625 // usual installation process. We can calculate it again, like we 7626 // do during install time. 7627 // 7628 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7629 // unnecessary. 7630 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7631 7632 // Null out the abis so that they can be recalculated. 7633 pkg.applicationInfo.primaryCpuAbi = null; 7634 pkg.applicationInfo.secondaryCpuAbi = null; 7635 if (isMultiArch(pkg.applicationInfo)) { 7636 // Warn if we've set an abiOverride for multi-lib packages.. 7637 // By definition, we need to copy both 32 and 64 bit libraries for 7638 // such packages. 7639 if (pkg.cpuAbiOverride != null 7640 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7641 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7642 } 7643 7644 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7645 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7646 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7647 if (extractLibs) { 7648 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7649 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7650 useIsaSpecificSubdirs); 7651 } else { 7652 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7653 } 7654 } 7655 7656 maybeThrowExceptionForMultiArchCopy( 7657 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7658 7659 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7660 if (extractLibs) { 7661 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7662 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7663 useIsaSpecificSubdirs); 7664 } else { 7665 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7666 } 7667 } 7668 7669 maybeThrowExceptionForMultiArchCopy( 7670 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7671 7672 if (abi64 >= 0) { 7673 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7674 } 7675 7676 if (abi32 >= 0) { 7677 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7678 if (abi64 >= 0) { 7679 pkg.applicationInfo.secondaryCpuAbi = abi; 7680 } else { 7681 pkg.applicationInfo.primaryCpuAbi = abi; 7682 } 7683 } 7684 } else { 7685 String[] abiList = (cpuAbiOverride != null) ? 7686 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7687 7688 // Enable gross and lame hacks for apps that are built with old 7689 // SDK tools. We must scan their APKs for renderscript bitcode and 7690 // not launch them if it's present. Don't bother checking on devices 7691 // that don't have 64 bit support. 7692 boolean needsRenderScriptOverride = false; 7693 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7694 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7695 abiList = Build.SUPPORTED_32_BIT_ABIS; 7696 needsRenderScriptOverride = true; 7697 } 7698 7699 final int copyRet; 7700 if (extractLibs) { 7701 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7702 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7703 } else { 7704 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7705 } 7706 7707 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7708 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7709 "Error unpackaging native libs for app, errorCode=" + copyRet); 7710 } 7711 7712 if (copyRet >= 0) { 7713 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7714 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7715 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7716 } else if (needsRenderScriptOverride) { 7717 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7718 } 7719 } 7720 } catch (IOException ioe) { 7721 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7722 } finally { 7723 IoUtils.closeQuietly(handle); 7724 } 7725 7726 // Now that we've calculated the ABIs and determined if it's an internal app, 7727 // we will go ahead and populate the nativeLibraryPath. 7728 setNativeLibraryPaths(pkg); 7729 } 7730 7731 /** 7732 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7733 * i.e, so that all packages can be run inside a single process if required. 7734 * 7735 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7736 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7737 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7738 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7739 * updating a package that belongs to a shared user. 7740 * 7741 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7742 * adds unnecessary complexity. 7743 */ 7744 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7745 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7746 String requiredInstructionSet = null; 7747 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7748 requiredInstructionSet = VMRuntime.getInstructionSet( 7749 scannedPackage.applicationInfo.primaryCpuAbi); 7750 } 7751 7752 PackageSetting requirer = null; 7753 for (PackageSetting ps : packagesForUser) { 7754 // If packagesForUser contains scannedPackage, we skip it. This will happen 7755 // when scannedPackage is an update of an existing package. Without this check, 7756 // we will never be able to change the ABI of any package belonging to a shared 7757 // user, even if it's compatible with other packages. 7758 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7759 if (ps.primaryCpuAbiString == null) { 7760 continue; 7761 } 7762 7763 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7764 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7765 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7766 // this but there's not much we can do. 7767 String errorMessage = "Instruction set mismatch, " 7768 + ((requirer == null) ? "[caller]" : requirer) 7769 + " requires " + requiredInstructionSet + " whereas " + ps 7770 + " requires " + instructionSet; 7771 Slog.w(TAG, errorMessage); 7772 } 7773 7774 if (requiredInstructionSet == null) { 7775 requiredInstructionSet = instructionSet; 7776 requirer = ps; 7777 } 7778 } 7779 } 7780 7781 if (requiredInstructionSet != null) { 7782 String adjustedAbi; 7783 if (requirer != null) { 7784 // requirer != null implies that either scannedPackage was null or that scannedPackage 7785 // did not require an ABI, in which case we have to adjust scannedPackage to match 7786 // the ABI of the set (which is the same as requirer's ABI) 7787 adjustedAbi = requirer.primaryCpuAbiString; 7788 if (scannedPackage != null) { 7789 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7790 } 7791 } else { 7792 // requirer == null implies that we're updating all ABIs in the set to 7793 // match scannedPackage. 7794 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7795 } 7796 7797 for (PackageSetting ps : packagesForUser) { 7798 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7799 if (ps.primaryCpuAbiString != null) { 7800 continue; 7801 } 7802 7803 ps.primaryCpuAbiString = adjustedAbi; 7804 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7805 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7806 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7807 7808 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7809 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7810 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7811 ps.primaryCpuAbiString = null; 7812 ps.pkg.applicationInfo.primaryCpuAbi = null; 7813 return; 7814 } else { 7815 mInstaller.rmdex(ps.codePathString, 7816 getDexCodeInstructionSet(getPreferredInstructionSet())); 7817 } 7818 } 7819 } 7820 } 7821 } 7822 } 7823 7824 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7825 synchronized (mPackages) { 7826 mResolverReplaced = true; 7827 // Set up information for custom user intent resolution activity. 7828 mResolveActivity.applicationInfo = pkg.applicationInfo; 7829 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7830 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7831 mResolveActivity.processName = pkg.applicationInfo.packageName; 7832 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7833 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7834 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7835 mResolveActivity.theme = 0; 7836 mResolveActivity.exported = true; 7837 mResolveActivity.enabled = true; 7838 mResolveInfo.activityInfo = mResolveActivity; 7839 mResolveInfo.priority = 0; 7840 mResolveInfo.preferredOrder = 0; 7841 mResolveInfo.match = 0; 7842 mResolveComponentName = mCustomResolverComponentName; 7843 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7844 mResolveComponentName); 7845 } 7846 } 7847 7848 private static String calculateBundledApkRoot(final String codePathString) { 7849 final File codePath = new File(codePathString); 7850 final File codeRoot; 7851 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7852 codeRoot = Environment.getRootDirectory(); 7853 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7854 codeRoot = Environment.getOemDirectory(); 7855 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7856 codeRoot = Environment.getVendorDirectory(); 7857 } else { 7858 // Unrecognized code path; take its top real segment as the apk root: 7859 // e.g. /something/app/blah.apk => /something 7860 try { 7861 File f = codePath.getCanonicalFile(); 7862 File parent = f.getParentFile(); // non-null because codePath is a file 7863 File tmp; 7864 while ((tmp = parent.getParentFile()) != null) { 7865 f = parent; 7866 parent = tmp; 7867 } 7868 codeRoot = f; 7869 Slog.w(TAG, "Unrecognized code path " 7870 + codePath + " - using " + codeRoot); 7871 } catch (IOException e) { 7872 // Can't canonicalize the code path -- shenanigans? 7873 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7874 return Environment.getRootDirectory().getPath(); 7875 } 7876 } 7877 return codeRoot.getPath(); 7878 } 7879 7880 /** 7881 * Derive and set the location of native libraries for the given package, 7882 * which varies depending on where and how the package was installed. 7883 */ 7884 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7885 final ApplicationInfo info = pkg.applicationInfo; 7886 final String codePath = pkg.codePath; 7887 final File codeFile = new File(codePath); 7888 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7889 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7890 7891 info.nativeLibraryRootDir = null; 7892 info.nativeLibraryRootRequiresIsa = false; 7893 info.nativeLibraryDir = null; 7894 info.secondaryNativeLibraryDir = null; 7895 7896 if (isApkFile(codeFile)) { 7897 // Monolithic install 7898 if (bundledApp) { 7899 // If "/system/lib64/apkname" exists, assume that is the per-package 7900 // native library directory to use; otherwise use "/system/lib/apkname". 7901 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7902 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7903 getPrimaryInstructionSet(info)); 7904 7905 // This is a bundled system app so choose the path based on the ABI. 7906 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7907 // is just the default path. 7908 final String apkName = deriveCodePathName(codePath); 7909 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7910 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7911 apkName).getAbsolutePath(); 7912 7913 if (info.secondaryCpuAbi != null) { 7914 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7915 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7916 secondaryLibDir, apkName).getAbsolutePath(); 7917 } 7918 } else if (asecApp) { 7919 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7920 .getAbsolutePath(); 7921 } else { 7922 final String apkName = deriveCodePathName(codePath); 7923 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7924 .getAbsolutePath(); 7925 } 7926 7927 info.nativeLibraryRootRequiresIsa = false; 7928 info.nativeLibraryDir = info.nativeLibraryRootDir; 7929 } else { 7930 // Cluster install 7931 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7932 info.nativeLibraryRootRequiresIsa = true; 7933 7934 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7935 getPrimaryInstructionSet(info)).getAbsolutePath(); 7936 7937 if (info.secondaryCpuAbi != null) { 7938 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7939 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7940 } 7941 } 7942 } 7943 7944 /** 7945 * Calculate the abis and roots for a bundled app. These can uniquely 7946 * be determined from the contents of the system partition, i.e whether 7947 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7948 * of this information, and instead assume that the system was built 7949 * sensibly. 7950 */ 7951 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7952 PackageSetting pkgSetting) { 7953 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7954 7955 // If "/system/lib64/apkname" exists, assume that is the per-package 7956 // native library directory to use; otherwise use "/system/lib/apkname". 7957 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7958 setBundledAppAbi(pkg, apkRoot, apkName); 7959 // pkgSetting might be null during rescan following uninstall of updates 7960 // to a bundled app, so accommodate that possibility. The settings in 7961 // that case will be established later from the parsed package. 7962 // 7963 // If the settings aren't null, sync them up with what we've just derived. 7964 // note that apkRoot isn't stored in the package settings. 7965 if (pkgSetting != null) { 7966 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7967 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7968 } 7969 } 7970 7971 /** 7972 * Deduces the ABI of a bundled app and sets the relevant fields on the 7973 * parsed pkg object. 7974 * 7975 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7976 * under which system libraries are installed. 7977 * @param apkName the name of the installed package. 7978 */ 7979 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7980 final File codeFile = new File(pkg.codePath); 7981 7982 final boolean has64BitLibs; 7983 final boolean has32BitLibs; 7984 if (isApkFile(codeFile)) { 7985 // Monolithic install 7986 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7987 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7988 } else { 7989 // Cluster install 7990 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7991 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7992 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7993 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7994 has64BitLibs = (new File(rootDir, isa)).exists(); 7995 } else { 7996 has64BitLibs = false; 7997 } 7998 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7999 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8000 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8001 has32BitLibs = (new File(rootDir, isa)).exists(); 8002 } else { 8003 has32BitLibs = false; 8004 } 8005 } 8006 8007 if (has64BitLibs && !has32BitLibs) { 8008 // The package has 64 bit libs, but not 32 bit libs. Its primary 8009 // ABI should be 64 bit. We can safely assume here that the bundled 8010 // native libraries correspond to the most preferred ABI in the list. 8011 8012 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8013 pkg.applicationInfo.secondaryCpuAbi = null; 8014 } else if (has32BitLibs && !has64BitLibs) { 8015 // The package has 32 bit libs but not 64 bit libs. Its primary 8016 // ABI should be 32 bit. 8017 8018 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8019 pkg.applicationInfo.secondaryCpuAbi = null; 8020 } else if (has32BitLibs && has64BitLibs) { 8021 // The application has both 64 and 32 bit bundled libraries. We check 8022 // here that the app declares multiArch support, and warn if it doesn't. 8023 // 8024 // We will be lenient here and record both ABIs. The primary will be the 8025 // ABI that's higher on the list, i.e, a device that's configured to prefer 8026 // 64 bit apps will see a 64 bit primary ABI, 8027 8028 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8029 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8030 } 8031 8032 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8033 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8034 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8035 } else { 8036 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8037 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8038 } 8039 } else { 8040 pkg.applicationInfo.primaryCpuAbi = null; 8041 pkg.applicationInfo.secondaryCpuAbi = null; 8042 } 8043 } 8044 8045 private void killApplication(String pkgName, int appId, String reason) { 8046 // Request the ActivityManager to kill the process(only for existing packages) 8047 // so that we do not end up in a confused state while the user is still using the older 8048 // version of the application while the new one gets installed. 8049 IActivityManager am = ActivityManagerNative.getDefault(); 8050 if (am != null) { 8051 try { 8052 am.killApplicationWithAppId(pkgName, appId, reason); 8053 } catch (RemoteException e) { 8054 } 8055 } 8056 } 8057 8058 void removePackageLI(PackageSetting ps, boolean chatty) { 8059 if (DEBUG_INSTALL) { 8060 if (chatty) 8061 Log.d(TAG, "Removing package " + ps.name); 8062 } 8063 8064 // writer 8065 synchronized (mPackages) { 8066 mPackages.remove(ps.name); 8067 final PackageParser.Package pkg = ps.pkg; 8068 if (pkg != null) { 8069 cleanPackageDataStructuresLILPw(pkg, chatty); 8070 } 8071 } 8072 } 8073 8074 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8075 if (DEBUG_INSTALL) { 8076 if (chatty) 8077 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8078 } 8079 8080 // writer 8081 synchronized (mPackages) { 8082 mPackages.remove(pkg.applicationInfo.packageName); 8083 cleanPackageDataStructuresLILPw(pkg, chatty); 8084 } 8085 } 8086 8087 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8088 int N = pkg.providers.size(); 8089 StringBuilder r = null; 8090 int i; 8091 for (i=0; i<N; i++) { 8092 PackageParser.Provider p = pkg.providers.get(i); 8093 mProviders.removeProvider(p); 8094 if (p.info.authority == null) { 8095 8096 /* There was another ContentProvider with this authority when 8097 * this app was installed so this authority is null, 8098 * Ignore it as we don't have to unregister the provider. 8099 */ 8100 continue; 8101 } 8102 String names[] = p.info.authority.split(";"); 8103 for (int j = 0; j < names.length; j++) { 8104 if (mProvidersByAuthority.get(names[j]) == p) { 8105 mProvidersByAuthority.remove(names[j]); 8106 if (DEBUG_REMOVE) { 8107 if (chatty) 8108 Log.d(TAG, "Unregistered content provider: " + names[j] 8109 + ", className = " + p.info.name + ", isSyncable = " 8110 + p.info.isSyncable); 8111 } 8112 } 8113 } 8114 if (DEBUG_REMOVE && chatty) { 8115 if (r == null) { 8116 r = new StringBuilder(256); 8117 } else { 8118 r.append(' '); 8119 } 8120 r.append(p.info.name); 8121 } 8122 } 8123 if (r != null) { 8124 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8125 } 8126 8127 N = pkg.services.size(); 8128 r = null; 8129 for (i=0; i<N; i++) { 8130 PackageParser.Service s = pkg.services.get(i); 8131 mServices.removeService(s); 8132 if (chatty) { 8133 if (r == null) { 8134 r = new StringBuilder(256); 8135 } else { 8136 r.append(' '); 8137 } 8138 r.append(s.info.name); 8139 } 8140 } 8141 if (r != null) { 8142 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8143 } 8144 8145 N = pkg.receivers.size(); 8146 r = null; 8147 for (i=0; i<N; i++) { 8148 PackageParser.Activity a = pkg.receivers.get(i); 8149 mReceivers.removeActivity(a, "receiver"); 8150 if (DEBUG_REMOVE && chatty) { 8151 if (r == null) { 8152 r = new StringBuilder(256); 8153 } else { 8154 r.append(' '); 8155 } 8156 r.append(a.info.name); 8157 } 8158 } 8159 if (r != null) { 8160 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8161 } 8162 8163 N = pkg.activities.size(); 8164 r = null; 8165 for (i=0; i<N; i++) { 8166 PackageParser.Activity a = pkg.activities.get(i); 8167 mActivities.removeActivity(a, "activity"); 8168 if (DEBUG_REMOVE && chatty) { 8169 if (r == null) { 8170 r = new StringBuilder(256); 8171 } else { 8172 r.append(' '); 8173 } 8174 r.append(a.info.name); 8175 } 8176 } 8177 if (r != null) { 8178 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8179 } 8180 8181 N = pkg.permissions.size(); 8182 r = null; 8183 for (i=0; i<N; i++) { 8184 PackageParser.Permission p = pkg.permissions.get(i); 8185 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8186 if (bp == null) { 8187 bp = mSettings.mPermissionTrees.get(p.info.name); 8188 } 8189 if (bp != null && bp.perm == p) { 8190 bp.perm = null; 8191 if (DEBUG_REMOVE && chatty) { 8192 if (r == null) { 8193 r = new StringBuilder(256); 8194 } else { 8195 r.append(' '); 8196 } 8197 r.append(p.info.name); 8198 } 8199 } 8200 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8201 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8202 if (appOpPerms != null) { 8203 appOpPerms.remove(pkg.packageName); 8204 } 8205 } 8206 } 8207 if (r != null) { 8208 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8209 } 8210 8211 N = pkg.requestedPermissions.size(); 8212 r = null; 8213 for (i=0; i<N; i++) { 8214 String perm = pkg.requestedPermissions.get(i); 8215 BasePermission bp = mSettings.mPermissions.get(perm); 8216 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8217 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8218 if (appOpPerms != null) { 8219 appOpPerms.remove(pkg.packageName); 8220 if (appOpPerms.isEmpty()) { 8221 mAppOpPermissionPackages.remove(perm); 8222 } 8223 } 8224 } 8225 } 8226 if (r != null) { 8227 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8228 } 8229 8230 N = pkg.instrumentation.size(); 8231 r = null; 8232 for (i=0; i<N; i++) { 8233 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8234 mInstrumentation.remove(a.getComponentName()); 8235 if (DEBUG_REMOVE && chatty) { 8236 if (r == null) { 8237 r = new StringBuilder(256); 8238 } else { 8239 r.append(' '); 8240 } 8241 r.append(a.info.name); 8242 } 8243 } 8244 if (r != null) { 8245 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8246 } 8247 8248 r = null; 8249 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8250 // Only system apps can hold shared libraries. 8251 if (pkg.libraryNames != null) { 8252 for (i=0; i<pkg.libraryNames.size(); i++) { 8253 String name = pkg.libraryNames.get(i); 8254 SharedLibraryEntry cur = mSharedLibraries.get(name); 8255 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8256 mSharedLibraries.remove(name); 8257 if (DEBUG_REMOVE && chatty) { 8258 if (r == null) { 8259 r = new StringBuilder(256); 8260 } else { 8261 r.append(' '); 8262 } 8263 r.append(name); 8264 } 8265 } 8266 } 8267 } 8268 } 8269 if (r != null) { 8270 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8271 } 8272 } 8273 8274 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8275 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8276 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8277 return true; 8278 } 8279 } 8280 return false; 8281 } 8282 8283 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8284 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8285 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8286 8287 private void updatePermissionsLPw(String changingPkg, 8288 PackageParser.Package pkgInfo, int flags) { 8289 // Make sure there are no dangling permission trees. 8290 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8291 while (it.hasNext()) { 8292 final BasePermission bp = it.next(); 8293 if (bp.packageSetting == null) { 8294 // We may not yet have parsed the package, so just see if 8295 // we still know about its settings. 8296 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8297 } 8298 if (bp.packageSetting == null) { 8299 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8300 + " from package " + bp.sourcePackage); 8301 it.remove(); 8302 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8303 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8304 Slog.i(TAG, "Removing old permission tree: " + bp.name 8305 + " from package " + bp.sourcePackage); 8306 flags |= UPDATE_PERMISSIONS_ALL; 8307 it.remove(); 8308 } 8309 } 8310 } 8311 8312 // Make sure all dynamic permissions have been assigned to a package, 8313 // and make sure there are no dangling permissions. 8314 it = mSettings.mPermissions.values().iterator(); 8315 while (it.hasNext()) { 8316 final BasePermission bp = it.next(); 8317 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8318 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8319 + bp.name + " pkg=" + bp.sourcePackage 8320 + " info=" + bp.pendingInfo); 8321 if (bp.packageSetting == null && bp.pendingInfo != null) { 8322 final BasePermission tree = findPermissionTreeLP(bp.name); 8323 if (tree != null && tree.perm != null) { 8324 bp.packageSetting = tree.packageSetting; 8325 bp.perm = new PackageParser.Permission(tree.perm.owner, 8326 new PermissionInfo(bp.pendingInfo)); 8327 bp.perm.info.packageName = tree.perm.info.packageName; 8328 bp.perm.info.name = bp.name; 8329 bp.uid = tree.uid; 8330 } 8331 } 8332 } 8333 if (bp.packageSetting == null) { 8334 // We may not yet have parsed the package, so just see if 8335 // we still know about its settings. 8336 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8337 } 8338 if (bp.packageSetting == null) { 8339 Slog.w(TAG, "Removing dangling permission: " + bp.name 8340 + " from package " + bp.sourcePackage); 8341 it.remove(); 8342 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8343 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8344 Slog.i(TAG, "Removing old permission: " + bp.name 8345 + " from package " + bp.sourcePackage); 8346 flags |= UPDATE_PERMISSIONS_ALL; 8347 it.remove(); 8348 } 8349 } 8350 } 8351 8352 // Now update the permissions for all packages, in particular 8353 // replace the granted permissions of the system packages. 8354 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8355 for (PackageParser.Package pkg : mPackages.values()) { 8356 if (pkg != pkgInfo) { 8357 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8358 changingPkg); 8359 } 8360 } 8361 } 8362 8363 if (pkgInfo != null) { 8364 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8365 } 8366 } 8367 8368 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8369 String packageOfInterest) { 8370 // IMPORTANT: There are two types of permissions: install and runtime. 8371 // Install time permissions are granted when the app is installed to 8372 // all device users and users added in the future. Runtime permissions 8373 // are granted at runtime explicitly to specific users. Normal and signature 8374 // protected permissions are install time permissions. Dangerous permissions 8375 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8376 // otherwise they are runtime permissions. This function does not manage 8377 // runtime permissions except for the case an app targeting Lollipop MR1 8378 // being upgraded to target a newer SDK, in which case dangerous permissions 8379 // are transformed from install time to runtime ones. 8380 8381 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8382 if (ps == null) { 8383 return; 8384 } 8385 8386 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8387 8388 PermissionsState permissionsState = ps.getPermissionsState(); 8389 PermissionsState origPermissions = permissionsState; 8390 8391 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8392 8393 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8394 8395 boolean changedInstallPermission = false; 8396 8397 if (replace) { 8398 ps.installPermissionsFixed = false; 8399 if (!ps.isSharedUser()) { 8400 origPermissions = new PermissionsState(permissionsState); 8401 permissionsState.reset(); 8402 } 8403 } 8404 8405 permissionsState.setGlobalGids(mGlobalGids); 8406 8407 final int N = pkg.requestedPermissions.size(); 8408 for (int i=0; i<N; i++) { 8409 final String name = pkg.requestedPermissions.get(i); 8410 final BasePermission bp = mSettings.mPermissions.get(name); 8411 8412 if (DEBUG_INSTALL) { 8413 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8414 } 8415 8416 if (bp == null || bp.packageSetting == null) { 8417 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8418 Slog.w(TAG, "Unknown permission " + name 8419 + " in package " + pkg.packageName); 8420 } 8421 continue; 8422 } 8423 8424 final String perm = bp.name; 8425 boolean allowedSig = false; 8426 int grant = GRANT_DENIED; 8427 8428 // Keep track of app op permissions. 8429 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8430 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8431 if (pkgs == null) { 8432 pkgs = new ArraySet<>(); 8433 mAppOpPermissionPackages.put(bp.name, pkgs); 8434 } 8435 pkgs.add(pkg.packageName); 8436 } 8437 8438 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8439 switch (level) { 8440 case PermissionInfo.PROTECTION_NORMAL: { 8441 // For all apps normal permissions are install time ones. 8442 grant = GRANT_INSTALL; 8443 } break; 8444 8445 case PermissionInfo.PROTECTION_DANGEROUS: { 8446 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8447 // For legacy apps dangerous permissions are install time ones. 8448 grant = GRANT_INSTALL_LEGACY; 8449 } else if (origPermissions.hasInstallPermission(bp.name)) { 8450 // For legacy apps that became modern, install becomes runtime. 8451 grant = GRANT_UPGRADE; 8452 } else if (mPromoteSystemApps 8453 && isSystemApp(ps) 8454 && mExistingSystemPackages.contains(ps.name)) { 8455 // For legacy system apps, install becomes runtime. 8456 // We cannot check hasInstallPermission() for system apps since those 8457 // permissions were granted implicitly and not persisted pre-M. 8458 grant = GRANT_UPGRADE; 8459 } else { 8460 // For modern apps keep runtime permissions unchanged. 8461 grant = GRANT_RUNTIME; 8462 } 8463 } break; 8464 8465 case PermissionInfo.PROTECTION_SIGNATURE: { 8466 // For all apps signature permissions are install time ones. 8467 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8468 if (allowedSig) { 8469 grant = GRANT_INSTALL; 8470 } 8471 } break; 8472 } 8473 8474 if (DEBUG_INSTALL) { 8475 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8476 } 8477 8478 if (grant != GRANT_DENIED) { 8479 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8480 // If this is an existing, non-system package, then 8481 // we can't add any new permissions to it. 8482 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8483 // Except... if this is a permission that was added 8484 // to the platform (note: need to only do this when 8485 // updating the platform). 8486 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8487 grant = GRANT_DENIED; 8488 } 8489 } 8490 } 8491 8492 switch (grant) { 8493 case GRANT_INSTALL: { 8494 // Revoke this as runtime permission to handle the case of 8495 // a runtime permission being downgraded to an install one. 8496 for (int userId : UserManagerService.getInstance().getUserIds()) { 8497 if (origPermissions.getRuntimePermissionState( 8498 bp.name, userId) != null) { 8499 // Revoke the runtime permission and clear the flags. 8500 origPermissions.revokeRuntimePermission(bp, userId); 8501 origPermissions.updatePermissionFlags(bp, userId, 8502 PackageManager.MASK_PERMISSION_FLAGS, 0); 8503 // If we revoked a permission permission, we have to write. 8504 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8505 changedRuntimePermissionUserIds, userId); 8506 } 8507 } 8508 // Grant an install permission. 8509 if (permissionsState.grantInstallPermission(bp) != 8510 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8511 changedInstallPermission = true; 8512 } 8513 } break; 8514 8515 case GRANT_INSTALL_LEGACY: { 8516 // Grant an install permission. 8517 if (permissionsState.grantInstallPermission(bp) != 8518 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8519 changedInstallPermission = true; 8520 } 8521 } break; 8522 8523 case GRANT_RUNTIME: { 8524 // Grant previously granted runtime permissions. 8525 for (int userId : UserManagerService.getInstance().getUserIds()) { 8526 PermissionState permissionState = origPermissions 8527 .getRuntimePermissionState(bp.name, userId); 8528 final int flags = permissionState != null 8529 ? permissionState.getFlags() : 0; 8530 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8531 if (permissionsState.grantRuntimePermission(bp, userId) == 8532 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8533 // If we cannot put the permission as it was, we have to write. 8534 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8535 changedRuntimePermissionUserIds, userId); 8536 } 8537 } 8538 // Propagate the permission flags. 8539 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8540 } 8541 } break; 8542 8543 case GRANT_UPGRADE: { 8544 // Grant runtime permissions for a previously held install permission. 8545 PermissionState permissionState = origPermissions 8546 .getInstallPermissionState(bp.name); 8547 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8548 8549 if (origPermissions.revokeInstallPermission(bp) 8550 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8551 // We will be transferring the permission flags, so clear them. 8552 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8553 PackageManager.MASK_PERMISSION_FLAGS, 0); 8554 changedInstallPermission = true; 8555 } 8556 8557 // If the permission is not to be promoted to runtime we ignore it and 8558 // also its other flags as they are not applicable to install permissions. 8559 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8560 for (int userId : currentUserIds) { 8561 if (permissionsState.grantRuntimePermission(bp, userId) != 8562 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8563 // Transfer the permission flags. 8564 permissionsState.updatePermissionFlags(bp, userId, 8565 flags, flags); 8566 // If we granted the permission, we have to write. 8567 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8568 changedRuntimePermissionUserIds, userId); 8569 } 8570 } 8571 } 8572 } break; 8573 8574 default: { 8575 if (packageOfInterest == null 8576 || packageOfInterest.equals(pkg.packageName)) { 8577 Slog.w(TAG, "Not granting permission " + perm 8578 + " to package " + pkg.packageName 8579 + " because it was previously installed without"); 8580 } 8581 } break; 8582 } 8583 } else { 8584 if (permissionsState.revokeInstallPermission(bp) != 8585 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8586 // Also drop the permission flags. 8587 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8588 PackageManager.MASK_PERMISSION_FLAGS, 0); 8589 changedInstallPermission = true; 8590 Slog.i(TAG, "Un-granting permission " + perm 8591 + " from package " + pkg.packageName 8592 + " (protectionLevel=" + bp.protectionLevel 8593 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8594 + ")"); 8595 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8596 // Don't print warning for app op permissions, since it is fine for them 8597 // not to be granted, there is a UI for the user to decide. 8598 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8599 Slog.w(TAG, "Not granting permission " + perm 8600 + " to package " + pkg.packageName 8601 + " (protectionLevel=" + bp.protectionLevel 8602 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8603 + ")"); 8604 } 8605 } 8606 } 8607 } 8608 8609 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8610 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8611 // This is the first that we have heard about this package, so the 8612 // permissions we have now selected are fixed until explicitly 8613 // changed. 8614 ps.installPermissionsFixed = true; 8615 } 8616 8617 // Persist the runtime permissions state for users with changes. 8618 for (int userId : changedRuntimePermissionUserIds) { 8619 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8620 } 8621 8622 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8623 } 8624 8625 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8626 boolean allowed = false; 8627 final int NP = PackageParser.NEW_PERMISSIONS.length; 8628 for (int ip=0; ip<NP; ip++) { 8629 final PackageParser.NewPermissionInfo npi 8630 = PackageParser.NEW_PERMISSIONS[ip]; 8631 if (npi.name.equals(perm) 8632 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8633 allowed = true; 8634 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8635 + pkg.packageName); 8636 break; 8637 } 8638 } 8639 return allowed; 8640 } 8641 8642 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8643 BasePermission bp, PermissionsState origPermissions) { 8644 boolean allowed; 8645 allowed = (compareSignatures( 8646 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8647 == PackageManager.SIGNATURE_MATCH) 8648 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8649 == PackageManager.SIGNATURE_MATCH); 8650 if (!allowed && (bp.protectionLevel 8651 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8652 if (isSystemApp(pkg)) { 8653 // For updated system applications, a system permission 8654 // is granted only if it had been defined by the original application. 8655 if (pkg.isUpdatedSystemApp()) { 8656 final PackageSetting sysPs = mSettings 8657 .getDisabledSystemPkgLPr(pkg.packageName); 8658 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8659 // If the original was granted this permission, we take 8660 // that grant decision as read and propagate it to the 8661 // update. 8662 if (sysPs.isPrivileged()) { 8663 allowed = true; 8664 } 8665 } else { 8666 // The system apk may have been updated with an older 8667 // version of the one on the data partition, but which 8668 // granted a new system permission that it didn't have 8669 // before. In this case we do want to allow the app to 8670 // now get the new permission if the ancestral apk is 8671 // privileged to get it. 8672 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8673 for (int j=0; 8674 j<sysPs.pkg.requestedPermissions.size(); j++) { 8675 if (perm.equals( 8676 sysPs.pkg.requestedPermissions.get(j))) { 8677 allowed = true; 8678 break; 8679 } 8680 } 8681 } 8682 } 8683 } else { 8684 allowed = isPrivilegedApp(pkg); 8685 } 8686 } 8687 } 8688 if (!allowed) { 8689 if (!allowed && (bp.protectionLevel 8690 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8691 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8692 // If this was a previously normal/dangerous permission that got moved 8693 // to a system permission as part of the runtime permission redesign, then 8694 // we still want to blindly grant it to old apps. 8695 allowed = true; 8696 } 8697 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8698 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8699 // If this permission is to be granted to the system installer and 8700 // this app is an installer, then it gets the permission. 8701 allowed = true; 8702 } 8703 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8704 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8705 // If this permission is to be granted to the system verifier and 8706 // this app is a verifier, then it gets the permission. 8707 allowed = true; 8708 } 8709 if (!allowed && (bp.protectionLevel 8710 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8711 && isSystemApp(pkg)) { 8712 // Any pre-installed system app is allowed to get this permission. 8713 allowed = true; 8714 } 8715 if (!allowed && (bp.protectionLevel 8716 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8717 // For development permissions, a development permission 8718 // is granted only if it was already granted. 8719 allowed = origPermissions.hasInstallPermission(perm); 8720 } 8721 } 8722 return allowed; 8723 } 8724 8725 final class ActivityIntentResolver 8726 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8727 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8728 boolean defaultOnly, int userId) { 8729 if (!sUserManager.exists(userId)) return null; 8730 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8731 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8732 } 8733 8734 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8735 int userId) { 8736 if (!sUserManager.exists(userId)) return null; 8737 mFlags = flags; 8738 return super.queryIntent(intent, resolvedType, 8739 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8740 } 8741 8742 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8743 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8744 if (!sUserManager.exists(userId)) return null; 8745 if (packageActivities == null) { 8746 return null; 8747 } 8748 mFlags = flags; 8749 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8750 final int N = packageActivities.size(); 8751 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8752 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8753 8754 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8755 for (int i = 0; i < N; ++i) { 8756 intentFilters = packageActivities.get(i).intents; 8757 if (intentFilters != null && intentFilters.size() > 0) { 8758 PackageParser.ActivityIntentInfo[] array = 8759 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8760 intentFilters.toArray(array); 8761 listCut.add(array); 8762 } 8763 } 8764 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8765 } 8766 8767 public final void addActivity(PackageParser.Activity a, String type) { 8768 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8769 mActivities.put(a.getComponentName(), a); 8770 if (DEBUG_SHOW_INFO) 8771 Log.v( 8772 TAG, " " + type + " " + 8773 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8774 if (DEBUG_SHOW_INFO) 8775 Log.v(TAG, " Class=" + a.info.name); 8776 final int NI = a.intents.size(); 8777 for (int j=0; j<NI; j++) { 8778 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8779 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8780 intent.setPriority(0); 8781 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8782 + a.className + " with priority > 0, forcing to 0"); 8783 } 8784 if (DEBUG_SHOW_INFO) { 8785 Log.v(TAG, " IntentFilter:"); 8786 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8787 } 8788 if (!intent.debugCheck()) { 8789 Log.w(TAG, "==> For Activity " + a.info.name); 8790 } 8791 addFilter(intent); 8792 } 8793 } 8794 8795 public final void removeActivity(PackageParser.Activity a, String type) { 8796 mActivities.remove(a.getComponentName()); 8797 if (DEBUG_SHOW_INFO) { 8798 Log.v(TAG, " " + type + " " 8799 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8800 : a.info.name) + ":"); 8801 Log.v(TAG, " Class=" + a.info.name); 8802 } 8803 final int NI = a.intents.size(); 8804 for (int j=0; j<NI; j++) { 8805 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8806 if (DEBUG_SHOW_INFO) { 8807 Log.v(TAG, " IntentFilter:"); 8808 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8809 } 8810 removeFilter(intent); 8811 } 8812 } 8813 8814 @Override 8815 protected boolean allowFilterResult( 8816 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8817 ActivityInfo filterAi = filter.activity.info; 8818 for (int i=dest.size()-1; i>=0; i--) { 8819 ActivityInfo destAi = dest.get(i).activityInfo; 8820 if (destAi.name == filterAi.name 8821 && destAi.packageName == filterAi.packageName) { 8822 return false; 8823 } 8824 } 8825 return true; 8826 } 8827 8828 @Override 8829 protected ActivityIntentInfo[] newArray(int size) { 8830 return new ActivityIntentInfo[size]; 8831 } 8832 8833 @Override 8834 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8835 if (!sUserManager.exists(userId)) return true; 8836 PackageParser.Package p = filter.activity.owner; 8837 if (p != null) { 8838 PackageSetting ps = (PackageSetting)p.mExtras; 8839 if (ps != null) { 8840 // System apps are never considered stopped for purposes of 8841 // filtering, because there may be no way for the user to 8842 // actually re-launch them. 8843 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8844 && ps.getStopped(userId); 8845 } 8846 } 8847 return false; 8848 } 8849 8850 @Override 8851 protected boolean isPackageForFilter(String packageName, 8852 PackageParser.ActivityIntentInfo info) { 8853 return packageName.equals(info.activity.owner.packageName); 8854 } 8855 8856 @Override 8857 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8858 int match, int userId) { 8859 if (!sUserManager.exists(userId)) return null; 8860 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8861 return null; 8862 } 8863 final PackageParser.Activity activity = info.activity; 8864 if (mSafeMode && (activity.info.applicationInfo.flags 8865 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8866 return null; 8867 } 8868 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8869 if (ps == null) { 8870 return null; 8871 } 8872 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8873 ps.readUserState(userId), userId); 8874 if (ai == null) { 8875 return null; 8876 } 8877 final ResolveInfo res = new ResolveInfo(); 8878 res.activityInfo = ai; 8879 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8880 res.filter = info; 8881 } 8882 if (info != null) { 8883 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8884 } 8885 res.priority = info.getPriority(); 8886 res.preferredOrder = activity.owner.mPreferredOrder; 8887 //System.out.println("Result: " + res.activityInfo.className + 8888 // " = " + res.priority); 8889 res.match = match; 8890 res.isDefault = info.hasDefault; 8891 res.labelRes = info.labelRes; 8892 res.nonLocalizedLabel = info.nonLocalizedLabel; 8893 if (userNeedsBadging(userId)) { 8894 res.noResourceId = true; 8895 } else { 8896 res.icon = info.icon; 8897 } 8898 res.iconResourceId = info.icon; 8899 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8900 return res; 8901 } 8902 8903 @Override 8904 protected void sortResults(List<ResolveInfo> results) { 8905 Collections.sort(results, mResolvePrioritySorter); 8906 } 8907 8908 @Override 8909 protected void dumpFilter(PrintWriter out, String prefix, 8910 PackageParser.ActivityIntentInfo filter) { 8911 out.print(prefix); out.print( 8912 Integer.toHexString(System.identityHashCode(filter.activity))); 8913 out.print(' '); 8914 filter.activity.printComponentShortName(out); 8915 out.print(" filter "); 8916 out.println(Integer.toHexString(System.identityHashCode(filter))); 8917 } 8918 8919 @Override 8920 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8921 return filter.activity; 8922 } 8923 8924 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8925 PackageParser.Activity activity = (PackageParser.Activity)label; 8926 out.print(prefix); out.print( 8927 Integer.toHexString(System.identityHashCode(activity))); 8928 out.print(' '); 8929 activity.printComponentShortName(out); 8930 if (count > 1) { 8931 out.print(" ("); out.print(count); out.print(" filters)"); 8932 } 8933 out.println(); 8934 } 8935 8936// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8937// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8938// final List<ResolveInfo> retList = Lists.newArrayList(); 8939// while (i.hasNext()) { 8940// final ResolveInfo resolveInfo = i.next(); 8941// if (isEnabledLP(resolveInfo.activityInfo)) { 8942// retList.add(resolveInfo); 8943// } 8944// } 8945// return retList; 8946// } 8947 8948 // Keys are String (activity class name), values are Activity. 8949 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8950 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8951 private int mFlags; 8952 } 8953 8954 private final class ServiceIntentResolver 8955 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8956 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8957 boolean defaultOnly, int userId) { 8958 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8959 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8960 } 8961 8962 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8963 int userId) { 8964 if (!sUserManager.exists(userId)) return null; 8965 mFlags = flags; 8966 return super.queryIntent(intent, resolvedType, 8967 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8968 } 8969 8970 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8971 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8972 if (!sUserManager.exists(userId)) return null; 8973 if (packageServices == null) { 8974 return null; 8975 } 8976 mFlags = flags; 8977 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8978 final int N = packageServices.size(); 8979 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8980 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8981 8982 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8983 for (int i = 0; i < N; ++i) { 8984 intentFilters = packageServices.get(i).intents; 8985 if (intentFilters != null && intentFilters.size() > 0) { 8986 PackageParser.ServiceIntentInfo[] array = 8987 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8988 intentFilters.toArray(array); 8989 listCut.add(array); 8990 } 8991 } 8992 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8993 } 8994 8995 public final void addService(PackageParser.Service s) { 8996 mServices.put(s.getComponentName(), s); 8997 if (DEBUG_SHOW_INFO) { 8998 Log.v(TAG, " " 8999 + (s.info.nonLocalizedLabel != null 9000 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9001 Log.v(TAG, " Class=" + s.info.name); 9002 } 9003 final int NI = s.intents.size(); 9004 int j; 9005 for (j=0; j<NI; j++) { 9006 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9007 if (DEBUG_SHOW_INFO) { 9008 Log.v(TAG, " IntentFilter:"); 9009 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9010 } 9011 if (!intent.debugCheck()) { 9012 Log.w(TAG, "==> For Service " + s.info.name); 9013 } 9014 addFilter(intent); 9015 } 9016 } 9017 9018 public final void removeService(PackageParser.Service s) { 9019 mServices.remove(s.getComponentName()); 9020 if (DEBUG_SHOW_INFO) { 9021 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9022 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9023 Log.v(TAG, " Class=" + s.info.name); 9024 } 9025 final int NI = s.intents.size(); 9026 int j; 9027 for (j=0; j<NI; j++) { 9028 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9029 if (DEBUG_SHOW_INFO) { 9030 Log.v(TAG, " IntentFilter:"); 9031 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9032 } 9033 removeFilter(intent); 9034 } 9035 } 9036 9037 @Override 9038 protected boolean allowFilterResult( 9039 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9040 ServiceInfo filterSi = filter.service.info; 9041 for (int i=dest.size()-1; i>=0; i--) { 9042 ServiceInfo destAi = dest.get(i).serviceInfo; 9043 if (destAi.name == filterSi.name 9044 && destAi.packageName == filterSi.packageName) { 9045 return false; 9046 } 9047 } 9048 return true; 9049 } 9050 9051 @Override 9052 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9053 return new PackageParser.ServiceIntentInfo[size]; 9054 } 9055 9056 @Override 9057 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9058 if (!sUserManager.exists(userId)) return true; 9059 PackageParser.Package p = filter.service.owner; 9060 if (p != null) { 9061 PackageSetting ps = (PackageSetting)p.mExtras; 9062 if (ps != null) { 9063 // System apps are never considered stopped for purposes of 9064 // filtering, because there may be no way for the user to 9065 // actually re-launch them. 9066 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9067 && ps.getStopped(userId); 9068 } 9069 } 9070 return false; 9071 } 9072 9073 @Override 9074 protected boolean isPackageForFilter(String packageName, 9075 PackageParser.ServiceIntentInfo info) { 9076 return packageName.equals(info.service.owner.packageName); 9077 } 9078 9079 @Override 9080 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9081 int match, int userId) { 9082 if (!sUserManager.exists(userId)) return null; 9083 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9084 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9085 return null; 9086 } 9087 final PackageParser.Service service = info.service; 9088 if (mSafeMode && (service.info.applicationInfo.flags 9089 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9090 return null; 9091 } 9092 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9093 if (ps == null) { 9094 return null; 9095 } 9096 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9097 ps.readUserState(userId), userId); 9098 if (si == null) { 9099 return null; 9100 } 9101 final ResolveInfo res = new ResolveInfo(); 9102 res.serviceInfo = si; 9103 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9104 res.filter = filter; 9105 } 9106 res.priority = info.getPriority(); 9107 res.preferredOrder = service.owner.mPreferredOrder; 9108 res.match = match; 9109 res.isDefault = info.hasDefault; 9110 res.labelRes = info.labelRes; 9111 res.nonLocalizedLabel = info.nonLocalizedLabel; 9112 res.icon = info.icon; 9113 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9114 return res; 9115 } 9116 9117 @Override 9118 protected void sortResults(List<ResolveInfo> results) { 9119 Collections.sort(results, mResolvePrioritySorter); 9120 } 9121 9122 @Override 9123 protected void dumpFilter(PrintWriter out, String prefix, 9124 PackageParser.ServiceIntentInfo filter) { 9125 out.print(prefix); out.print( 9126 Integer.toHexString(System.identityHashCode(filter.service))); 9127 out.print(' '); 9128 filter.service.printComponentShortName(out); 9129 out.print(" filter "); 9130 out.println(Integer.toHexString(System.identityHashCode(filter))); 9131 } 9132 9133 @Override 9134 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9135 return filter.service; 9136 } 9137 9138 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9139 PackageParser.Service service = (PackageParser.Service)label; 9140 out.print(prefix); out.print( 9141 Integer.toHexString(System.identityHashCode(service))); 9142 out.print(' '); 9143 service.printComponentShortName(out); 9144 if (count > 1) { 9145 out.print(" ("); out.print(count); out.print(" filters)"); 9146 } 9147 out.println(); 9148 } 9149 9150// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9151// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9152// final List<ResolveInfo> retList = Lists.newArrayList(); 9153// while (i.hasNext()) { 9154// final ResolveInfo resolveInfo = (ResolveInfo) i; 9155// if (isEnabledLP(resolveInfo.serviceInfo)) { 9156// retList.add(resolveInfo); 9157// } 9158// } 9159// return retList; 9160// } 9161 9162 // Keys are String (activity class name), values are Activity. 9163 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9164 = new ArrayMap<ComponentName, PackageParser.Service>(); 9165 private int mFlags; 9166 }; 9167 9168 private final class ProviderIntentResolver 9169 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9170 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9171 boolean defaultOnly, int userId) { 9172 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9173 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9174 } 9175 9176 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9177 int userId) { 9178 if (!sUserManager.exists(userId)) 9179 return null; 9180 mFlags = flags; 9181 return super.queryIntent(intent, resolvedType, 9182 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9183 } 9184 9185 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9186 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9187 if (!sUserManager.exists(userId)) 9188 return null; 9189 if (packageProviders == null) { 9190 return null; 9191 } 9192 mFlags = flags; 9193 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9194 final int N = packageProviders.size(); 9195 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9196 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9197 9198 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9199 for (int i = 0; i < N; ++i) { 9200 intentFilters = packageProviders.get(i).intents; 9201 if (intentFilters != null && intentFilters.size() > 0) { 9202 PackageParser.ProviderIntentInfo[] array = 9203 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9204 intentFilters.toArray(array); 9205 listCut.add(array); 9206 } 9207 } 9208 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9209 } 9210 9211 public final void addProvider(PackageParser.Provider p) { 9212 if (mProviders.containsKey(p.getComponentName())) { 9213 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9214 return; 9215 } 9216 9217 mProviders.put(p.getComponentName(), p); 9218 if (DEBUG_SHOW_INFO) { 9219 Log.v(TAG, " " 9220 + (p.info.nonLocalizedLabel != null 9221 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9222 Log.v(TAG, " Class=" + p.info.name); 9223 } 9224 final int NI = p.intents.size(); 9225 int j; 9226 for (j = 0; j < NI; j++) { 9227 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9228 if (DEBUG_SHOW_INFO) { 9229 Log.v(TAG, " IntentFilter:"); 9230 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9231 } 9232 if (!intent.debugCheck()) { 9233 Log.w(TAG, "==> For Provider " + p.info.name); 9234 } 9235 addFilter(intent); 9236 } 9237 } 9238 9239 public final void removeProvider(PackageParser.Provider p) { 9240 mProviders.remove(p.getComponentName()); 9241 if (DEBUG_SHOW_INFO) { 9242 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9243 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9244 Log.v(TAG, " Class=" + p.info.name); 9245 } 9246 final int NI = p.intents.size(); 9247 int j; 9248 for (j = 0; j < NI; j++) { 9249 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9250 if (DEBUG_SHOW_INFO) { 9251 Log.v(TAG, " IntentFilter:"); 9252 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9253 } 9254 removeFilter(intent); 9255 } 9256 } 9257 9258 @Override 9259 protected boolean allowFilterResult( 9260 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9261 ProviderInfo filterPi = filter.provider.info; 9262 for (int i = dest.size() - 1; i >= 0; i--) { 9263 ProviderInfo destPi = dest.get(i).providerInfo; 9264 if (destPi.name == filterPi.name 9265 && destPi.packageName == filterPi.packageName) { 9266 return false; 9267 } 9268 } 9269 return true; 9270 } 9271 9272 @Override 9273 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9274 return new PackageParser.ProviderIntentInfo[size]; 9275 } 9276 9277 @Override 9278 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9279 if (!sUserManager.exists(userId)) 9280 return true; 9281 PackageParser.Package p = filter.provider.owner; 9282 if (p != null) { 9283 PackageSetting ps = (PackageSetting) p.mExtras; 9284 if (ps != null) { 9285 // System apps are never considered stopped for purposes of 9286 // filtering, because there may be no way for the user to 9287 // actually re-launch them. 9288 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9289 && ps.getStopped(userId); 9290 } 9291 } 9292 return false; 9293 } 9294 9295 @Override 9296 protected boolean isPackageForFilter(String packageName, 9297 PackageParser.ProviderIntentInfo info) { 9298 return packageName.equals(info.provider.owner.packageName); 9299 } 9300 9301 @Override 9302 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9303 int match, int userId) { 9304 if (!sUserManager.exists(userId)) 9305 return null; 9306 final PackageParser.ProviderIntentInfo info = filter; 9307 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9308 return null; 9309 } 9310 final PackageParser.Provider provider = info.provider; 9311 if (mSafeMode && (provider.info.applicationInfo.flags 9312 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9313 return null; 9314 } 9315 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9316 if (ps == null) { 9317 return null; 9318 } 9319 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9320 ps.readUserState(userId), userId); 9321 if (pi == null) { 9322 return null; 9323 } 9324 final ResolveInfo res = new ResolveInfo(); 9325 res.providerInfo = pi; 9326 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9327 res.filter = filter; 9328 } 9329 res.priority = info.getPriority(); 9330 res.preferredOrder = provider.owner.mPreferredOrder; 9331 res.match = match; 9332 res.isDefault = info.hasDefault; 9333 res.labelRes = info.labelRes; 9334 res.nonLocalizedLabel = info.nonLocalizedLabel; 9335 res.icon = info.icon; 9336 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9337 return res; 9338 } 9339 9340 @Override 9341 protected void sortResults(List<ResolveInfo> results) { 9342 Collections.sort(results, mResolvePrioritySorter); 9343 } 9344 9345 @Override 9346 protected void dumpFilter(PrintWriter out, String prefix, 9347 PackageParser.ProviderIntentInfo filter) { 9348 out.print(prefix); 9349 out.print( 9350 Integer.toHexString(System.identityHashCode(filter.provider))); 9351 out.print(' '); 9352 filter.provider.printComponentShortName(out); 9353 out.print(" filter "); 9354 out.println(Integer.toHexString(System.identityHashCode(filter))); 9355 } 9356 9357 @Override 9358 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9359 return filter.provider; 9360 } 9361 9362 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9363 PackageParser.Provider provider = (PackageParser.Provider)label; 9364 out.print(prefix); out.print( 9365 Integer.toHexString(System.identityHashCode(provider))); 9366 out.print(' '); 9367 provider.printComponentShortName(out); 9368 if (count > 1) { 9369 out.print(" ("); out.print(count); out.print(" filters)"); 9370 } 9371 out.println(); 9372 } 9373 9374 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9375 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9376 private int mFlags; 9377 }; 9378 9379 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9380 new Comparator<ResolveInfo>() { 9381 public int compare(ResolveInfo r1, ResolveInfo r2) { 9382 int v1 = r1.priority; 9383 int v2 = r2.priority; 9384 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9385 if (v1 != v2) { 9386 return (v1 > v2) ? -1 : 1; 9387 } 9388 v1 = r1.preferredOrder; 9389 v2 = r2.preferredOrder; 9390 if (v1 != v2) { 9391 return (v1 > v2) ? -1 : 1; 9392 } 9393 if (r1.isDefault != r2.isDefault) { 9394 return r1.isDefault ? -1 : 1; 9395 } 9396 v1 = r1.match; 9397 v2 = r2.match; 9398 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9399 if (v1 != v2) { 9400 return (v1 > v2) ? -1 : 1; 9401 } 9402 if (r1.system != r2.system) { 9403 return r1.system ? -1 : 1; 9404 } 9405 return 0; 9406 } 9407 }; 9408 9409 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9410 new Comparator<ProviderInfo>() { 9411 public int compare(ProviderInfo p1, ProviderInfo p2) { 9412 final int v1 = p1.initOrder; 9413 final int v2 = p2.initOrder; 9414 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9415 } 9416 }; 9417 9418 final void sendPackageBroadcast(final String action, final String pkg, 9419 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9420 final int[] userIds) { 9421 mHandler.post(new Runnable() { 9422 @Override 9423 public void run() { 9424 try { 9425 final IActivityManager am = ActivityManagerNative.getDefault(); 9426 if (am == null) return; 9427 final int[] resolvedUserIds; 9428 if (userIds == null) { 9429 resolvedUserIds = am.getRunningUserIds(); 9430 } else { 9431 resolvedUserIds = userIds; 9432 } 9433 for (int id : resolvedUserIds) { 9434 final Intent intent = new Intent(action, 9435 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9436 if (extras != null) { 9437 intent.putExtras(extras); 9438 } 9439 if (targetPkg != null) { 9440 intent.setPackage(targetPkg); 9441 } 9442 // Modify the UID when posting to other users 9443 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9444 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9445 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9446 intent.putExtra(Intent.EXTRA_UID, uid); 9447 } 9448 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9449 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9450 if (DEBUG_BROADCASTS) { 9451 RuntimeException here = new RuntimeException("here"); 9452 here.fillInStackTrace(); 9453 Slog.d(TAG, "Sending to user " + id + ": " 9454 + intent.toShortString(false, true, false, false) 9455 + " " + intent.getExtras(), here); 9456 } 9457 am.broadcastIntent(null, intent, null, finishedReceiver, 9458 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9459 null, finishedReceiver != null, false, id); 9460 } 9461 } catch (RemoteException ex) { 9462 } 9463 } 9464 }); 9465 } 9466 9467 /** 9468 * Check if the external storage media is available. This is true if there 9469 * is a mounted external storage medium or if the external storage is 9470 * emulated. 9471 */ 9472 private boolean isExternalMediaAvailable() { 9473 return mMediaMounted || Environment.isExternalStorageEmulated(); 9474 } 9475 9476 @Override 9477 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9478 // writer 9479 synchronized (mPackages) { 9480 if (!isExternalMediaAvailable()) { 9481 // If the external storage is no longer mounted at this point, 9482 // the caller may not have been able to delete all of this 9483 // packages files and can not delete any more. Bail. 9484 return null; 9485 } 9486 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9487 if (lastPackage != null) { 9488 pkgs.remove(lastPackage); 9489 } 9490 if (pkgs.size() > 0) { 9491 return pkgs.get(0); 9492 } 9493 } 9494 return null; 9495 } 9496 9497 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9498 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9499 userId, andCode ? 1 : 0, packageName); 9500 if (mSystemReady) { 9501 msg.sendToTarget(); 9502 } else { 9503 if (mPostSystemReadyMessages == null) { 9504 mPostSystemReadyMessages = new ArrayList<>(); 9505 } 9506 mPostSystemReadyMessages.add(msg); 9507 } 9508 } 9509 9510 void startCleaningPackages() { 9511 // reader 9512 synchronized (mPackages) { 9513 if (!isExternalMediaAvailable()) { 9514 return; 9515 } 9516 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9517 return; 9518 } 9519 } 9520 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9521 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9522 IActivityManager am = ActivityManagerNative.getDefault(); 9523 if (am != null) { 9524 try { 9525 am.startService(null, intent, null, mContext.getOpPackageName(), 9526 UserHandle.USER_OWNER); 9527 } catch (RemoteException e) { 9528 } 9529 } 9530 } 9531 9532 @Override 9533 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9534 int installFlags, String installerPackageName, VerificationParams verificationParams, 9535 String packageAbiOverride) { 9536 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9537 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9538 } 9539 9540 @Override 9541 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9542 int installFlags, String installerPackageName, VerificationParams verificationParams, 9543 String packageAbiOverride, int userId) { 9544 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9545 9546 final int callingUid = Binder.getCallingUid(); 9547 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9548 9549 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9550 try { 9551 if (observer != null) { 9552 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9553 } 9554 } catch (RemoteException re) { 9555 } 9556 return; 9557 } 9558 9559 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9560 installFlags |= PackageManager.INSTALL_FROM_ADB; 9561 9562 } else { 9563 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9564 // about installerPackageName. 9565 9566 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9567 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9568 } 9569 9570 UserHandle user; 9571 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9572 user = UserHandle.ALL; 9573 } else { 9574 user = new UserHandle(userId); 9575 } 9576 9577 // Only system components can circumvent runtime permissions when installing. 9578 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9579 && mContext.checkCallingOrSelfPermission(Manifest.permission 9580 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9581 throw new SecurityException("You need the " 9582 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9583 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9584 } 9585 9586 verificationParams.setInstallerUid(callingUid); 9587 9588 final File originFile = new File(originPath); 9589 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9590 9591 final Message msg = mHandler.obtainMessage(INIT_COPY); 9592 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9593 null, verificationParams, user, packageAbiOverride, null); 9594 mHandler.sendMessage(msg); 9595 } 9596 9597 void installStage(String packageName, File stagedDir, String stagedCid, 9598 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9599 String installerPackageName, int installerUid, UserHandle user) { 9600 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9601 params.referrerUri, installerUid, null); 9602 verifParams.setInstallerUid(installerUid); 9603 9604 final OriginInfo origin; 9605 if (stagedDir != null) { 9606 origin = OriginInfo.fromStagedFile(stagedDir); 9607 } else { 9608 origin = OriginInfo.fromStagedContainer(stagedCid); 9609 } 9610 9611 final Message msg = mHandler.obtainMessage(INIT_COPY); 9612 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9613 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9614 params.grantedRuntimePermissions); 9615 9616 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9617 System.identityHashCode(msg.obj)); 9618 9619 mHandler.sendMessage(msg); 9620 } 9621 9622 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9623 Bundle extras = new Bundle(1); 9624 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9625 9626 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9627 packageName, extras, null, null, new int[] {userId}); 9628 try { 9629 IActivityManager am = ActivityManagerNative.getDefault(); 9630 final boolean isSystem = 9631 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9632 if (isSystem && am.isUserRunning(userId, false)) { 9633 // The just-installed/enabled app is bundled on the system, so presumed 9634 // to be able to run automatically without needing an explicit launch. 9635 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9636 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9637 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9638 .setPackage(packageName); 9639 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9640 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9641 } 9642 } catch (RemoteException e) { 9643 // shouldn't happen 9644 Slog.w(TAG, "Unable to bootstrap installed package", e); 9645 } 9646 } 9647 9648 @Override 9649 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9650 int userId) { 9651 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9652 PackageSetting pkgSetting; 9653 final int uid = Binder.getCallingUid(); 9654 enforceCrossUserPermission(uid, userId, true, true, 9655 "setApplicationHiddenSetting for user " + userId); 9656 9657 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9658 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9659 return false; 9660 } 9661 9662 long callingId = Binder.clearCallingIdentity(); 9663 try { 9664 boolean sendAdded = false; 9665 boolean sendRemoved = false; 9666 // writer 9667 synchronized (mPackages) { 9668 pkgSetting = mSettings.mPackages.get(packageName); 9669 if (pkgSetting == null) { 9670 return false; 9671 } 9672 if (pkgSetting.getHidden(userId) != hidden) { 9673 pkgSetting.setHidden(hidden, userId); 9674 mSettings.writePackageRestrictionsLPr(userId); 9675 if (hidden) { 9676 sendRemoved = true; 9677 } else { 9678 sendAdded = true; 9679 } 9680 } 9681 } 9682 if (sendAdded) { 9683 sendPackageAddedForUser(packageName, pkgSetting, userId); 9684 return true; 9685 } 9686 if (sendRemoved) { 9687 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9688 "hiding pkg"); 9689 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9690 return true; 9691 } 9692 } finally { 9693 Binder.restoreCallingIdentity(callingId); 9694 } 9695 return false; 9696 } 9697 9698 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9699 int userId) { 9700 final PackageRemovedInfo info = new PackageRemovedInfo(); 9701 info.removedPackage = packageName; 9702 info.removedUsers = new int[] {userId}; 9703 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9704 info.sendBroadcast(false, false, false); 9705 } 9706 9707 /** 9708 * Returns true if application is not found or there was an error. Otherwise it returns 9709 * the hidden state of the package for the given user. 9710 */ 9711 @Override 9712 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9713 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9714 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9715 false, "getApplicationHidden for user " + userId); 9716 PackageSetting pkgSetting; 9717 long callingId = Binder.clearCallingIdentity(); 9718 try { 9719 // writer 9720 synchronized (mPackages) { 9721 pkgSetting = mSettings.mPackages.get(packageName); 9722 if (pkgSetting == null) { 9723 return true; 9724 } 9725 return pkgSetting.getHidden(userId); 9726 } 9727 } finally { 9728 Binder.restoreCallingIdentity(callingId); 9729 } 9730 } 9731 9732 /** 9733 * @hide 9734 */ 9735 @Override 9736 public int installExistingPackageAsUser(String packageName, int userId) { 9737 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9738 null); 9739 PackageSetting pkgSetting; 9740 final int uid = Binder.getCallingUid(); 9741 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9742 + userId); 9743 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9744 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9745 } 9746 9747 long callingId = Binder.clearCallingIdentity(); 9748 try { 9749 boolean sendAdded = false; 9750 9751 // writer 9752 synchronized (mPackages) { 9753 pkgSetting = mSettings.mPackages.get(packageName); 9754 if (pkgSetting == null) { 9755 return PackageManager.INSTALL_FAILED_INVALID_URI; 9756 } 9757 if (!pkgSetting.getInstalled(userId)) { 9758 pkgSetting.setInstalled(true, userId); 9759 pkgSetting.setHidden(false, userId); 9760 mSettings.writePackageRestrictionsLPr(userId); 9761 sendAdded = true; 9762 } 9763 } 9764 9765 if (sendAdded) { 9766 sendPackageAddedForUser(packageName, pkgSetting, userId); 9767 } 9768 } finally { 9769 Binder.restoreCallingIdentity(callingId); 9770 } 9771 9772 return PackageManager.INSTALL_SUCCEEDED; 9773 } 9774 9775 boolean isUserRestricted(int userId, String restrictionKey) { 9776 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9777 if (restrictions.getBoolean(restrictionKey, false)) { 9778 Log.w(TAG, "User is restricted: " + restrictionKey); 9779 return true; 9780 } 9781 return false; 9782 } 9783 9784 @Override 9785 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9786 mContext.enforceCallingOrSelfPermission( 9787 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9788 "Only package verification agents can verify applications"); 9789 9790 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9791 final PackageVerificationResponse response = new PackageVerificationResponse( 9792 verificationCode, Binder.getCallingUid()); 9793 msg.arg1 = id; 9794 msg.obj = response; 9795 mHandler.sendMessage(msg); 9796 } 9797 9798 @Override 9799 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9800 long millisecondsToDelay) { 9801 mContext.enforceCallingOrSelfPermission( 9802 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9803 "Only package verification agents can extend verification timeouts"); 9804 9805 final PackageVerificationState state = mPendingVerification.get(id); 9806 final PackageVerificationResponse response = new PackageVerificationResponse( 9807 verificationCodeAtTimeout, Binder.getCallingUid()); 9808 9809 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9810 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9811 } 9812 if (millisecondsToDelay < 0) { 9813 millisecondsToDelay = 0; 9814 } 9815 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9816 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9817 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9818 } 9819 9820 if ((state != null) && !state.timeoutExtended()) { 9821 state.extendTimeout(); 9822 9823 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9824 msg.arg1 = id; 9825 msg.obj = response; 9826 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9827 } 9828 } 9829 9830 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9831 int verificationCode, UserHandle user) { 9832 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9833 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9834 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9835 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9836 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9837 9838 mContext.sendBroadcastAsUser(intent, user, 9839 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9840 } 9841 9842 private ComponentName matchComponentForVerifier(String packageName, 9843 List<ResolveInfo> receivers) { 9844 ActivityInfo targetReceiver = null; 9845 9846 final int NR = receivers.size(); 9847 for (int i = 0; i < NR; i++) { 9848 final ResolveInfo info = receivers.get(i); 9849 if (info.activityInfo == null) { 9850 continue; 9851 } 9852 9853 if (packageName.equals(info.activityInfo.packageName)) { 9854 targetReceiver = info.activityInfo; 9855 break; 9856 } 9857 } 9858 9859 if (targetReceiver == null) { 9860 return null; 9861 } 9862 9863 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9864 } 9865 9866 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9867 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9868 if (pkgInfo.verifiers.length == 0) { 9869 return null; 9870 } 9871 9872 final int N = pkgInfo.verifiers.length; 9873 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9874 for (int i = 0; i < N; i++) { 9875 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9876 9877 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9878 receivers); 9879 if (comp == null) { 9880 continue; 9881 } 9882 9883 final int verifierUid = getUidForVerifier(verifierInfo); 9884 if (verifierUid == -1) { 9885 continue; 9886 } 9887 9888 if (DEBUG_VERIFY) { 9889 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9890 + " with the correct signature"); 9891 } 9892 sufficientVerifiers.add(comp); 9893 verificationState.addSufficientVerifier(verifierUid); 9894 } 9895 9896 return sufficientVerifiers; 9897 } 9898 9899 private int getUidForVerifier(VerifierInfo verifierInfo) { 9900 synchronized (mPackages) { 9901 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9902 if (pkg == null) { 9903 return -1; 9904 } else if (pkg.mSignatures.length != 1) { 9905 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9906 + " has more than one signature; ignoring"); 9907 return -1; 9908 } 9909 9910 /* 9911 * If the public key of the package's signature does not match 9912 * our expected public key, then this is a different package and 9913 * we should skip. 9914 */ 9915 9916 final byte[] expectedPublicKey; 9917 try { 9918 final Signature verifierSig = pkg.mSignatures[0]; 9919 final PublicKey publicKey = verifierSig.getPublicKey(); 9920 expectedPublicKey = publicKey.getEncoded(); 9921 } catch (CertificateException e) { 9922 return -1; 9923 } 9924 9925 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9926 9927 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9928 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9929 + " does not have the expected public key; ignoring"); 9930 return -1; 9931 } 9932 9933 return pkg.applicationInfo.uid; 9934 } 9935 } 9936 9937 @Override 9938 public void finishPackageInstall(int token) { 9939 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9940 9941 if (DEBUG_INSTALL) { 9942 Slog.v(TAG, "BM finishing package install for " + token); 9943 } 9944 9945 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9946 mHandler.sendMessage(msg); 9947 } 9948 9949 /** 9950 * Get the verification agent timeout. 9951 * 9952 * @return verification timeout in milliseconds 9953 */ 9954 private long getVerificationTimeout() { 9955 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9956 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9957 DEFAULT_VERIFICATION_TIMEOUT); 9958 } 9959 9960 /** 9961 * Get the default verification agent response code. 9962 * 9963 * @return default verification response code 9964 */ 9965 private int getDefaultVerificationResponse() { 9966 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9967 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9968 DEFAULT_VERIFICATION_RESPONSE); 9969 } 9970 9971 /** 9972 * Check whether or not package verification has been enabled. 9973 * 9974 * @return true if verification should be performed 9975 */ 9976 private boolean isVerificationEnabled(int userId, int installFlags) { 9977 if (!DEFAULT_VERIFY_ENABLE) { 9978 return false; 9979 } 9980 9981 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9982 9983 // Check if installing from ADB 9984 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9985 // Do not run verification in a test harness environment 9986 if (ActivityManager.isRunningInTestHarness()) { 9987 return false; 9988 } 9989 if (ensureVerifyAppsEnabled) { 9990 return true; 9991 } 9992 // Check if the developer does not want package verification for ADB installs 9993 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9994 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9995 return false; 9996 } 9997 } 9998 9999 if (ensureVerifyAppsEnabled) { 10000 return true; 10001 } 10002 10003 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10004 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10005 } 10006 10007 @Override 10008 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10009 throws RemoteException { 10010 mContext.enforceCallingOrSelfPermission( 10011 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10012 "Only intentfilter verification agents can verify applications"); 10013 10014 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10015 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10016 Binder.getCallingUid(), verificationCode, failedDomains); 10017 msg.arg1 = id; 10018 msg.obj = response; 10019 mHandler.sendMessage(msg); 10020 } 10021 10022 @Override 10023 public int getIntentVerificationStatus(String packageName, int userId) { 10024 synchronized (mPackages) { 10025 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10026 } 10027 } 10028 10029 @Override 10030 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10031 mContext.enforceCallingOrSelfPermission( 10032 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10033 10034 boolean result = false; 10035 synchronized (mPackages) { 10036 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10037 } 10038 if (result) { 10039 scheduleWritePackageRestrictionsLocked(userId); 10040 } 10041 return result; 10042 } 10043 10044 @Override 10045 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10046 synchronized (mPackages) { 10047 return mSettings.getIntentFilterVerificationsLPr(packageName); 10048 } 10049 } 10050 10051 @Override 10052 public List<IntentFilter> getAllIntentFilters(String packageName) { 10053 if (TextUtils.isEmpty(packageName)) { 10054 return Collections.<IntentFilter>emptyList(); 10055 } 10056 synchronized (mPackages) { 10057 PackageParser.Package pkg = mPackages.get(packageName); 10058 if (pkg == null || pkg.activities == null) { 10059 return Collections.<IntentFilter>emptyList(); 10060 } 10061 final int count = pkg.activities.size(); 10062 ArrayList<IntentFilter> result = new ArrayList<>(); 10063 for (int n=0; n<count; n++) { 10064 PackageParser.Activity activity = pkg.activities.get(n); 10065 if (activity.intents != null || activity.intents.size() > 0) { 10066 result.addAll(activity.intents); 10067 } 10068 } 10069 return result; 10070 } 10071 } 10072 10073 @Override 10074 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10075 mContext.enforceCallingOrSelfPermission( 10076 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10077 10078 synchronized (mPackages) { 10079 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10080 if (packageName != null) { 10081 result |= updateIntentVerificationStatus(packageName, 10082 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10083 userId); 10084 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10085 packageName, userId); 10086 } 10087 return result; 10088 } 10089 } 10090 10091 @Override 10092 public String getDefaultBrowserPackageName(int userId) { 10093 synchronized (mPackages) { 10094 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10095 } 10096 } 10097 10098 /** 10099 * Get the "allow unknown sources" setting. 10100 * 10101 * @return the current "allow unknown sources" setting 10102 */ 10103 private int getUnknownSourcesSettings() { 10104 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10105 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10106 -1); 10107 } 10108 10109 @Override 10110 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10111 final int uid = Binder.getCallingUid(); 10112 // writer 10113 synchronized (mPackages) { 10114 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10115 if (targetPackageSetting == null) { 10116 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10117 } 10118 10119 PackageSetting installerPackageSetting; 10120 if (installerPackageName != null) { 10121 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10122 if (installerPackageSetting == null) { 10123 throw new IllegalArgumentException("Unknown installer package: " 10124 + installerPackageName); 10125 } 10126 } else { 10127 installerPackageSetting = null; 10128 } 10129 10130 Signature[] callerSignature; 10131 Object obj = mSettings.getUserIdLPr(uid); 10132 if (obj != null) { 10133 if (obj instanceof SharedUserSetting) { 10134 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10135 } else if (obj instanceof PackageSetting) { 10136 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10137 } else { 10138 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10139 } 10140 } else { 10141 throw new SecurityException("Unknown calling uid " + uid); 10142 } 10143 10144 // Verify: can't set installerPackageName to a package that is 10145 // not signed with the same cert as the caller. 10146 if (installerPackageSetting != null) { 10147 if (compareSignatures(callerSignature, 10148 installerPackageSetting.signatures.mSignatures) 10149 != PackageManager.SIGNATURE_MATCH) { 10150 throw new SecurityException( 10151 "Caller does not have same cert as new installer package " 10152 + installerPackageName); 10153 } 10154 } 10155 10156 // Verify: if target already has an installer package, it must 10157 // be signed with the same cert as the caller. 10158 if (targetPackageSetting.installerPackageName != null) { 10159 PackageSetting setting = mSettings.mPackages.get( 10160 targetPackageSetting.installerPackageName); 10161 // If the currently set package isn't valid, then it's always 10162 // okay to change it. 10163 if (setting != null) { 10164 if (compareSignatures(callerSignature, 10165 setting.signatures.mSignatures) 10166 != PackageManager.SIGNATURE_MATCH) { 10167 throw new SecurityException( 10168 "Caller does not have same cert as old installer package " 10169 + targetPackageSetting.installerPackageName); 10170 } 10171 } 10172 } 10173 10174 // Okay! 10175 targetPackageSetting.installerPackageName = installerPackageName; 10176 scheduleWriteSettingsLocked(); 10177 } 10178 } 10179 10180 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10181 // Queue up an async operation since the package installation may take a little while. 10182 mHandler.post(new Runnable() { 10183 public void run() { 10184 mHandler.removeCallbacks(this); 10185 // Result object to be returned 10186 PackageInstalledInfo res = new PackageInstalledInfo(); 10187 res.returnCode = currentStatus; 10188 res.uid = -1; 10189 res.pkg = null; 10190 res.removedInfo = new PackageRemovedInfo(); 10191 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10192 args.doPreInstall(res.returnCode); 10193 synchronized (mInstallLock) { 10194 installPackageTracedLI(args, res); 10195 } 10196 args.doPostInstall(res.returnCode, res.uid); 10197 } 10198 10199 // A restore should be performed at this point if (a) the install 10200 // succeeded, (b) the operation is not an update, and (c) the new 10201 // package has not opted out of backup participation. 10202 final boolean update = res.removedInfo.removedPackage != null; 10203 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10204 boolean doRestore = !update 10205 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10206 10207 // Set up the post-install work request bookkeeping. This will be used 10208 // and cleaned up by the post-install event handling regardless of whether 10209 // there's a restore pass performed. Token values are >= 1. 10210 int token; 10211 if (mNextInstallToken < 0) mNextInstallToken = 1; 10212 token = mNextInstallToken++; 10213 10214 PostInstallData data = new PostInstallData(args, res); 10215 mRunningInstalls.put(token, data); 10216 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10217 10218 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10219 // Pass responsibility to the Backup Manager. It will perform a 10220 // restore if appropriate, then pass responsibility back to the 10221 // Package Manager to run the post-install observer callbacks 10222 // and broadcasts. 10223 IBackupManager bm = IBackupManager.Stub.asInterface( 10224 ServiceManager.getService(Context.BACKUP_SERVICE)); 10225 if (bm != null) { 10226 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10227 + " to BM for possible restore"); 10228 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10229 try { 10230 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10231 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10232 } else { 10233 doRestore = false; 10234 } 10235 } catch (RemoteException e) { 10236 // can't happen; the backup manager is local 10237 } catch (Exception e) { 10238 Slog.e(TAG, "Exception trying to enqueue restore", e); 10239 doRestore = false; 10240 } finally { 10241 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10242 } 10243 } else { 10244 Slog.e(TAG, "Backup Manager not found!"); 10245 doRestore = false; 10246 } 10247 } 10248 10249 if (!doRestore) { 10250 // No restore possible, or the Backup Manager was mysteriously not 10251 // available -- just fire the post-install work request directly. 10252 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10253 10254 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10255 10256 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10257 mHandler.sendMessage(msg); 10258 } 10259 } 10260 }); 10261 } 10262 10263 private abstract class HandlerParams { 10264 private static final int MAX_RETRIES = 4; 10265 10266 /** 10267 * Number of times startCopy() has been attempted and had a non-fatal 10268 * error. 10269 */ 10270 private int mRetries = 0; 10271 10272 /** User handle for the user requesting the information or installation. */ 10273 private final UserHandle mUser; 10274 10275 HandlerParams(UserHandle user) { 10276 mUser = user; 10277 } 10278 10279 UserHandle getUser() { 10280 return mUser; 10281 } 10282 10283 final boolean startCopy() { 10284 boolean res; 10285 try { 10286 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10287 10288 if (++mRetries > MAX_RETRIES) { 10289 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10290 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10291 handleServiceError(); 10292 return false; 10293 } else { 10294 handleStartCopy(); 10295 res = true; 10296 } 10297 } catch (RemoteException e) { 10298 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10299 mHandler.sendEmptyMessage(MCS_RECONNECT); 10300 res = false; 10301 } 10302 handleReturnCode(); 10303 return res; 10304 } 10305 10306 final void serviceError() { 10307 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10308 handleServiceError(); 10309 handleReturnCode(); 10310 } 10311 10312 abstract void handleStartCopy() throws RemoteException; 10313 abstract void handleServiceError(); 10314 abstract void handleReturnCode(); 10315 } 10316 10317 class MeasureParams extends HandlerParams { 10318 private final PackageStats mStats; 10319 private boolean mSuccess; 10320 10321 private final IPackageStatsObserver mObserver; 10322 10323 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10324 super(new UserHandle(stats.userHandle)); 10325 mObserver = observer; 10326 mStats = stats; 10327 } 10328 10329 @Override 10330 public String toString() { 10331 return "MeasureParams{" 10332 + Integer.toHexString(System.identityHashCode(this)) 10333 + " " + mStats.packageName + "}"; 10334 } 10335 10336 @Override 10337 void handleStartCopy() throws RemoteException { 10338 synchronized (mInstallLock) { 10339 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10340 } 10341 10342 if (mSuccess) { 10343 final boolean mounted; 10344 if (Environment.isExternalStorageEmulated()) { 10345 mounted = true; 10346 } else { 10347 final String status = Environment.getExternalStorageState(); 10348 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10349 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10350 } 10351 10352 if (mounted) { 10353 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10354 10355 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10356 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10357 10358 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10359 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10360 10361 // Always subtract cache size, since it's a subdirectory 10362 mStats.externalDataSize -= mStats.externalCacheSize; 10363 10364 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10365 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10366 10367 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10368 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10369 } 10370 } 10371 } 10372 10373 @Override 10374 void handleReturnCode() { 10375 if (mObserver != null) { 10376 try { 10377 mObserver.onGetStatsCompleted(mStats, mSuccess); 10378 } catch (RemoteException e) { 10379 Slog.i(TAG, "Observer no longer exists."); 10380 } 10381 } 10382 } 10383 10384 @Override 10385 void handleServiceError() { 10386 Slog.e(TAG, "Could not measure application " + mStats.packageName 10387 + " external storage"); 10388 } 10389 } 10390 10391 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10392 throws RemoteException { 10393 long result = 0; 10394 for (File path : paths) { 10395 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10396 } 10397 return result; 10398 } 10399 10400 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10401 for (File path : paths) { 10402 try { 10403 mcs.clearDirectory(path.getAbsolutePath()); 10404 } catch (RemoteException e) { 10405 } 10406 } 10407 } 10408 10409 static class OriginInfo { 10410 /** 10411 * Location where install is coming from, before it has been 10412 * copied/renamed into place. This could be a single monolithic APK 10413 * file, or a cluster directory. This location may be untrusted. 10414 */ 10415 final File file; 10416 final String cid; 10417 10418 /** 10419 * Flag indicating that {@link #file} or {@link #cid} has already been 10420 * staged, meaning downstream users don't need to defensively copy the 10421 * contents. 10422 */ 10423 final boolean staged; 10424 10425 /** 10426 * Flag indicating that {@link #file} or {@link #cid} is an already 10427 * installed app that is being moved. 10428 */ 10429 final boolean existing; 10430 10431 final String resolvedPath; 10432 final File resolvedFile; 10433 10434 static OriginInfo fromNothing() { 10435 return new OriginInfo(null, null, false, false); 10436 } 10437 10438 static OriginInfo fromUntrustedFile(File file) { 10439 return new OriginInfo(file, null, false, false); 10440 } 10441 10442 static OriginInfo fromExistingFile(File file) { 10443 return new OriginInfo(file, null, false, true); 10444 } 10445 10446 static OriginInfo fromStagedFile(File file) { 10447 return new OriginInfo(file, null, true, false); 10448 } 10449 10450 static OriginInfo fromStagedContainer(String cid) { 10451 return new OriginInfo(null, cid, true, false); 10452 } 10453 10454 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10455 this.file = file; 10456 this.cid = cid; 10457 this.staged = staged; 10458 this.existing = existing; 10459 10460 if (cid != null) { 10461 resolvedPath = PackageHelper.getSdDir(cid); 10462 resolvedFile = new File(resolvedPath); 10463 } else if (file != null) { 10464 resolvedPath = file.getAbsolutePath(); 10465 resolvedFile = file; 10466 } else { 10467 resolvedPath = null; 10468 resolvedFile = null; 10469 } 10470 } 10471 } 10472 10473 class MoveInfo { 10474 final int moveId; 10475 final String fromUuid; 10476 final String toUuid; 10477 final String packageName; 10478 final String dataAppName; 10479 final int appId; 10480 final String seinfo; 10481 10482 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10483 String dataAppName, int appId, String seinfo) { 10484 this.moveId = moveId; 10485 this.fromUuid = fromUuid; 10486 this.toUuid = toUuid; 10487 this.packageName = packageName; 10488 this.dataAppName = dataAppName; 10489 this.appId = appId; 10490 this.seinfo = seinfo; 10491 } 10492 } 10493 10494 class InstallParams extends HandlerParams { 10495 final OriginInfo origin; 10496 final MoveInfo move; 10497 final IPackageInstallObserver2 observer; 10498 int installFlags; 10499 final String installerPackageName; 10500 final String volumeUuid; 10501 final VerificationParams verificationParams; 10502 private InstallArgs mArgs; 10503 private int mRet; 10504 final String packageAbiOverride; 10505 final String[] grantedRuntimePermissions; 10506 10507 10508 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10509 int installFlags, String installerPackageName, String volumeUuid, 10510 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10511 String[] grantedPermissions) { 10512 super(user); 10513 this.origin = origin; 10514 this.move = move; 10515 this.observer = observer; 10516 this.installFlags = installFlags; 10517 this.installerPackageName = installerPackageName; 10518 this.volumeUuid = volumeUuid; 10519 this.verificationParams = verificationParams; 10520 this.packageAbiOverride = packageAbiOverride; 10521 this.grantedRuntimePermissions = grantedPermissions; 10522 } 10523 10524 @Override 10525 public String toString() { 10526 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10527 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10528 } 10529 10530 public ManifestDigest getManifestDigest() { 10531 if (verificationParams == null) { 10532 return null; 10533 } 10534 return verificationParams.getManifestDigest(); 10535 } 10536 10537 private int installLocationPolicy(PackageInfoLite pkgLite) { 10538 String packageName = pkgLite.packageName; 10539 int installLocation = pkgLite.installLocation; 10540 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10541 // reader 10542 synchronized (mPackages) { 10543 PackageParser.Package pkg = mPackages.get(packageName); 10544 if (pkg != null) { 10545 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10546 // Check for downgrading. 10547 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10548 try { 10549 checkDowngrade(pkg, pkgLite); 10550 } catch (PackageManagerException e) { 10551 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10552 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10553 } 10554 } 10555 // Check for updated system application. 10556 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10557 if (onSd) { 10558 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10559 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10560 } 10561 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10562 } else { 10563 if (onSd) { 10564 // Install flag overrides everything. 10565 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10566 } 10567 // If current upgrade specifies particular preference 10568 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10569 // Application explicitly specified internal. 10570 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10571 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10572 // App explictly prefers external. Let policy decide 10573 } else { 10574 // Prefer previous location 10575 if (isExternal(pkg)) { 10576 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10577 } 10578 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10579 } 10580 } 10581 } else { 10582 // Invalid install. Return error code 10583 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10584 } 10585 } 10586 } 10587 // All the special cases have been taken care of. 10588 // Return result based on recommended install location. 10589 if (onSd) { 10590 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10591 } 10592 return pkgLite.recommendedInstallLocation; 10593 } 10594 10595 /* 10596 * Invoke remote method to get package information and install 10597 * location values. Override install location based on default 10598 * policy if needed and then create install arguments based 10599 * on the install location. 10600 */ 10601 public void handleStartCopy() throws RemoteException { 10602 int ret = PackageManager.INSTALL_SUCCEEDED; 10603 10604 // If we're already staged, we've firmly committed to an install location 10605 if (origin.staged) { 10606 if (origin.file != null) { 10607 installFlags |= PackageManager.INSTALL_INTERNAL; 10608 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10609 } else if (origin.cid != null) { 10610 installFlags |= PackageManager.INSTALL_EXTERNAL; 10611 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10612 } else { 10613 throw new IllegalStateException("Invalid stage location"); 10614 } 10615 } 10616 10617 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10618 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10619 PackageInfoLite pkgLite = null; 10620 10621 if (onInt && onSd) { 10622 // Check if both bits are set. 10623 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10624 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10625 } else { 10626 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10627 packageAbiOverride); 10628 10629 /* 10630 * If we have too little free space, try to free cache 10631 * before giving up. 10632 */ 10633 if (!origin.staged && pkgLite.recommendedInstallLocation 10634 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10635 // TODO: focus freeing disk space on the target device 10636 final StorageManager storage = StorageManager.from(mContext); 10637 final long lowThreshold = storage.getStorageLowBytes( 10638 Environment.getDataDirectory()); 10639 10640 final long sizeBytes = mContainerService.calculateInstalledSize( 10641 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10642 10643 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10644 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10645 installFlags, packageAbiOverride); 10646 } 10647 10648 /* 10649 * The cache free must have deleted the file we 10650 * downloaded to install. 10651 * 10652 * TODO: fix the "freeCache" call to not delete 10653 * the file we care about. 10654 */ 10655 if (pkgLite.recommendedInstallLocation 10656 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10657 pkgLite.recommendedInstallLocation 10658 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10659 } 10660 } 10661 } 10662 10663 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10664 int loc = pkgLite.recommendedInstallLocation; 10665 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10666 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10667 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10668 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10669 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10670 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10671 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10672 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10673 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10674 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10675 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10676 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10677 } else { 10678 // Override with defaults if needed. 10679 loc = installLocationPolicy(pkgLite); 10680 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10681 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10682 } else if (!onSd && !onInt) { 10683 // Override install location with flags 10684 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10685 // Set the flag to install on external media. 10686 installFlags |= PackageManager.INSTALL_EXTERNAL; 10687 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10688 } else { 10689 // Make sure the flag for installing on external 10690 // media is unset 10691 installFlags |= PackageManager.INSTALL_INTERNAL; 10692 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10693 } 10694 } 10695 } 10696 } 10697 10698 final InstallArgs args = createInstallArgs(this); 10699 mArgs = args; 10700 10701 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10702 /* 10703 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10704 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10705 */ 10706 int userIdentifier = getUser().getIdentifier(); 10707 if (userIdentifier == UserHandle.USER_ALL 10708 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10709 userIdentifier = UserHandle.USER_OWNER; 10710 } 10711 10712 /* 10713 * Determine if we have any installed package verifiers. If we 10714 * do, then we'll defer to them to verify the packages. 10715 */ 10716 final int requiredUid = mRequiredVerifierPackage == null ? -1 10717 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10718 if (!origin.existing && requiredUid != -1 10719 && isVerificationEnabled(userIdentifier, installFlags)) { 10720 final Intent verification = new Intent( 10721 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10722 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10723 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10724 PACKAGE_MIME_TYPE); 10725 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10726 10727 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10728 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10729 0 /* TODO: Which userId? */); 10730 10731 if (DEBUG_VERIFY) { 10732 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10733 + verification.toString() + " with " + pkgLite.verifiers.length 10734 + " optional verifiers"); 10735 } 10736 10737 final int verificationId = mPendingVerificationToken++; 10738 10739 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10740 10741 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10742 installerPackageName); 10743 10744 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10745 installFlags); 10746 10747 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10748 pkgLite.packageName); 10749 10750 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10751 pkgLite.versionCode); 10752 10753 if (verificationParams != null) { 10754 if (verificationParams.getVerificationURI() != null) { 10755 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10756 verificationParams.getVerificationURI()); 10757 } 10758 if (verificationParams.getOriginatingURI() != null) { 10759 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10760 verificationParams.getOriginatingURI()); 10761 } 10762 if (verificationParams.getReferrer() != null) { 10763 verification.putExtra(Intent.EXTRA_REFERRER, 10764 verificationParams.getReferrer()); 10765 } 10766 if (verificationParams.getOriginatingUid() >= 0) { 10767 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10768 verificationParams.getOriginatingUid()); 10769 } 10770 if (verificationParams.getInstallerUid() >= 0) { 10771 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10772 verificationParams.getInstallerUid()); 10773 } 10774 } 10775 10776 final PackageVerificationState verificationState = new PackageVerificationState( 10777 requiredUid, args); 10778 10779 mPendingVerification.append(verificationId, verificationState); 10780 10781 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10782 receivers, verificationState); 10783 10784 // Apps installed for "all" users use the device owner to verify the app 10785 UserHandle verifierUser = getUser(); 10786 if (verifierUser == UserHandle.ALL) { 10787 verifierUser = UserHandle.OWNER; 10788 } 10789 10790 /* 10791 * If any sufficient verifiers were listed in the package 10792 * manifest, attempt to ask them. 10793 */ 10794 if (sufficientVerifiers != null) { 10795 final int N = sufficientVerifiers.size(); 10796 if (N == 0) { 10797 Slog.i(TAG, "Additional verifiers required, but none installed."); 10798 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10799 } else { 10800 for (int i = 0; i < N; i++) { 10801 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10802 10803 final Intent sufficientIntent = new Intent(verification); 10804 sufficientIntent.setComponent(verifierComponent); 10805 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10806 } 10807 } 10808 } 10809 10810 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10811 mRequiredVerifierPackage, receivers); 10812 if (ret == PackageManager.INSTALL_SUCCEEDED 10813 && mRequiredVerifierPackage != null) { 10814 Trace.asyncTraceBegin( 10815 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 10816 /* 10817 * Send the intent to the required verification agent, 10818 * but only start the verification timeout after the 10819 * target BroadcastReceivers have run. 10820 */ 10821 verification.setComponent(requiredVerifierComponent); 10822 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10823 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10824 new BroadcastReceiver() { 10825 @Override 10826 public void onReceive(Context context, Intent intent) { 10827 final Message msg = mHandler 10828 .obtainMessage(CHECK_PENDING_VERIFICATION); 10829 msg.arg1 = verificationId; 10830 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10831 } 10832 }, null, 0, null, null); 10833 10834 /* 10835 * We don't want the copy to proceed until verification 10836 * succeeds, so null out this field. 10837 */ 10838 mArgs = null; 10839 } 10840 } else { 10841 /* 10842 * No package verification is enabled, so immediately start 10843 * the remote call to initiate copy using temporary file. 10844 */ 10845 ret = args.copyApk(mContainerService, true); 10846 } 10847 } 10848 10849 mRet = ret; 10850 } 10851 10852 @Override 10853 void handleReturnCode() { 10854 // If mArgs is null, then MCS couldn't be reached. When it 10855 // reconnects, it will try again to install. At that point, this 10856 // will succeed. 10857 if (mArgs != null) { 10858 processPendingInstall(mArgs, mRet); 10859 } 10860 } 10861 10862 @Override 10863 void handleServiceError() { 10864 mArgs = createInstallArgs(this); 10865 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10866 } 10867 10868 public boolean isForwardLocked() { 10869 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10870 } 10871 } 10872 10873 /** 10874 * Used during creation of InstallArgs 10875 * 10876 * @param installFlags package installation flags 10877 * @return true if should be installed on external storage 10878 */ 10879 private static boolean installOnExternalAsec(int installFlags) { 10880 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10881 return false; 10882 } 10883 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10884 return true; 10885 } 10886 return false; 10887 } 10888 10889 /** 10890 * Used during creation of InstallArgs 10891 * 10892 * @param installFlags package installation flags 10893 * @return true if should be installed as forward locked 10894 */ 10895 private static boolean installForwardLocked(int installFlags) { 10896 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10897 } 10898 10899 private InstallArgs createInstallArgs(InstallParams params) { 10900 if (params.move != null) { 10901 return new MoveInstallArgs(params); 10902 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10903 return new AsecInstallArgs(params); 10904 } else { 10905 return new FileInstallArgs(params); 10906 } 10907 } 10908 10909 /** 10910 * Create args that describe an existing installed package. Typically used 10911 * when cleaning up old installs, or used as a move source. 10912 */ 10913 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10914 String resourcePath, String[] instructionSets) { 10915 final boolean isInAsec; 10916 if (installOnExternalAsec(installFlags)) { 10917 /* Apps on SD card are always in ASEC containers. */ 10918 isInAsec = true; 10919 } else if (installForwardLocked(installFlags) 10920 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10921 /* 10922 * Forward-locked apps are only in ASEC containers if they're the 10923 * new style 10924 */ 10925 isInAsec = true; 10926 } else { 10927 isInAsec = false; 10928 } 10929 10930 if (isInAsec) { 10931 return new AsecInstallArgs(codePath, instructionSets, 10932 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10933 } else { 10934 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10935 } 10936 } 10937 10938 static abstract class InstallArgs { 10939 /** @see InstallParams#origin */ 10940 final OriginInfo origin; 10941 /** @see InstallParams#move */ 10942 final MoveInfo move; 10943 10944 final IPackageInstallObserver2 observer; 10945 // Always refers to PackageManager flags only 10946 final int installFlags; 10947 final String installerPackageName; 10948 final String volumeUuid; 10949 final ManifestDigest manifestDigest; 10950 final UserHandle user; 10951 final String abiOverride; 10952 final String[] installGrantPermissions; 10953 10954 // The list of instruction sets supported by this app. This is currently 10955 // only used during the rmdex() phase to clean up resources. We can get rid of this 10956 // if we move dex files under the common app path. 10957 /* nullable */ String[] instructionSets; 10958 10959 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10960 int installFlags, String installerPackageName, String volumeUuid, 10961 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10962 String abiOverride, String[] installGrantPermissions) { 10963 this.origin = origin; 10964 this.move = move; 10965 this.installFlags = installFlags; 10966 this.observer = observer; 10967 this.installerPackageName = installerPackageName; 10968 this.volumeUuid = volumeUuid; 10969 this.manifestDigest = manifestDigest; 10970 this.user = user; 10971 this.instructionSets = instructionSets; 10972 this.abiOverride = abiOverride; 10973 this.installGrantPermissions = installGrantPermissions; 10974 } 10975 10976 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10977 abstract int doPreInstall(int status); 10978 10979 /** 10980 * Rename package into final resting place. All paths on the given 10981 * scanned package should be updated to reflect the rename. 10982 */ 10983 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10984 abstract int doPostInstall(int status, int uid); 10985 10986 /** @see PackageSettingBase#codePathString */ 10987 abstract String getCodePath(); 10988 /** @see PackageSettingBase#resourcePathString */ 10989 abstract String getResourcePath(); 10990 10991 // Need installer lock especially for dex file removal. 10992 abstract void cleanUpResourcesLI(); 10993 abstract boolean doPostDeleteLI(boolean delete); 10994 10995 /** 10996 * Called before the source arguments are copied. This is used mostly 10997 * for MoveParams when it needs to read the source file to put it in the 10998 * destination. 10999 */ 11000 int doPreCopy() { 11001 return PackageManager.INSTALL_SUCCEEDED; 11002 } 11003 11004 /** 11005 * Called after the source arguments are copied. This is used mostly for 11006 * MoveParams when it needs to read the source file to put it in the 11007 * destination. 11008 * 11009 * @return 11010 */ 11011 int doPostCopy(int uid) { 11012 return PackageManager.INSTALL_SUCCEEDED; 11013 } 11014 11015 protected boolean isFwdLocked() { 11016 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11017 } 11018 11019 protected boolean isExternalAsec() { 11020 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11021 } 11022 11023 UserHandle getUser() { 11024 return user; 11025 } 11026 } 11027 11028 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11029 if (!allCodePaths.isEmpty()) { 11030 if (instructionSets == null) { 11031 throw new IllegalStateException("instructionSet == null"); 11032 } 11033 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11034 for (String codePath : allCodePaths) { 11035 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11036 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11037 if (retCode < 0) { 11038 Slog.w(TAG, "Couldn't remove dex file for package: " 11039 + " at location " + codePath + ", retcode=" + retCode); 11040 // we don't consider this to be a failure of the core package deletion 11041 } 11042 } 11043 } 11044 } 11045 } 11046 11047 /** 11048 * Logic to handle installation of non-ASEC applications, including copying 11049 * and renaming logic. 11050 */ 11051 class FileInstallArgs extends InstallArgs { 11052 private File codeFile; 11053 private File resourceFile; 11054 11055 // Example topology: 11056 // /data/app/com.example/base.apk 11057 // /data/app/com.example/split_foo.apk 11058 // /data/app/com.example/lib/arm/libfoo.so 11059 // /data/app/com.example/lib/arm64/libfoo.so 11060 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11061 11062 /** New install */ 11063 FileInstallArgs(InstallParams params) { 11064 super(params.origin, params.move, params.observer, params.installFlags, 11065 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11066 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11067 params.grantedRuntimePermissions); 11068 if (isFwdLocked()) { 11069 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11070 } 11071 } 11072 11073 /** Existing install */ 11074 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11075 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11076 null, null); 11077 this.codeFile = (codePath != null) ? new File(codePath) : null; 11078 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11079 } 11080 11081 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11082 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11083 try { 11084 return doCopyApk(imcs, temp); 11085 } finally { 11086 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11087 } 11088 } 11089 11090 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11091 if (origin.staged) { 11092 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11093 codeFile = origin.file; 11094 resourceFile = origin.file; 11095 return PackageManager.INSTALL_SUCCEEDED; 11096 } 11097 11098 try { 11099 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11100 codeFile = tempDir; 11101 resourceFile = tempDir; 11102 } catch (IOException e) { 11103 Slog.w(TAG, "Failed to create copy file: " + e); 11104 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11105 } 11106 11107 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11108 @Override 11109 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11110 if (!FileUtils.isValidExtFilename(name)) { 11111 throw new IllegalArgumentException("Invalid filename: " + name); 11112 } 11113 try { 11114 final File file = new File(codeFile, name); 11115 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11116 O_RDWR | O_CREAT, 0644); 11117 Os.chmod(file.getAbsolutePath(), 0644); 11118 return new ParcelFileDescriptor(fd); 11119 } catch (ErrnoException e) { 11120 throw new RemoteException("Failed to open: " + e.getMessage()); 11121 } 11122 } 11123 }; 11124 11125 int ret = PackageManager.INSTALL_SUCCEEDED; 11126 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11127 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11128 Slog.e(TAG, "Failed to copy package"); 11129 return ret; 11130 } 11131 11132 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11133 NativeLibraryHelper.Handle handle = null; 11134 try { 11135 handle = NativeLibraryHelper.Handle.create(codeFile); 11136 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11137 abiOverride); 11138 } catch (IOException e) { 11139 Slog.e(TAG, "Copying native libraries failed", e); 11140 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11141 } finally { 11142 IoUtils.closeQuietly(handle); 11143 } 11144 11145 return ret; 11146 } 11147 11148 int doPreInstall(int status) { 11149 if (status != PackageManager.INSTALL_SUCCEEDED) { 11150 cleanUp(); 11151 } 11152 return status; 11153 } 11154 11155 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11156 if (status != PackageManager.INSTALL_SUCCEEDED) { 11157 cleanUp(); 11158 return false; 11159 } 11160 11161 final File targetDir = codeFile.getParentFile(); 11162 final File beforeCodeFile = codeFile; 11163 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11164 11165 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11166 try { 11167 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11168 } catch (ErrnoException e) { 11169 Slog.w(TAG, "Failed to rename", e); 11170 return false; 11171 } 11172 11173 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11174 Slog.w(TAG, "Failed to restorecon"); 11175 return false; 11176 } 11177 11178 // Reflect the rename internally 11179 codeFile = afterCodeFile; 11180 resourceFile = afterCodeFile; 11181 11182 // Reflect the rename in scanned details 11183 pkg.codePath = afterCodeFile.getAbsolutePath(); 11184 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11185 pkg.baseCodePath); 11186 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11187 pkg.splitCodePaths); 11188 11189 // Reflect the rename in app info 11190 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11191 pkg.applicationInfo.setCodePath(pkg.codePath); 11192 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11193 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11194 pkg.applicationInfo.setResourcePath(pkg.codePath); 11195 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11196 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11197 11198 return true; 11199 } 11200 11201 int doPostInstall(int status, int uid) { 11202 if (status != PackageManager.INSTALL_SUCCEEDED) { 11203 cleanUp(); 11204 } 11205 return status; 11206 } 11207 11208 @Override 11209 String getCodePath() { 11210 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11211 } 11212 11213 @Override 11214 String getResourcePath() { 11215 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11216 } 11217 11218 private boolean cleanUp() { 11219 if (codeFile == null || !codeFile.exists()) { 11220 return false; 11221 } 11222 11223 if (codeFile.isDirectory()) { 11224 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11225 } else { 11226 codeFile.delete(); 11227 } 11228 11229 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11230 resourceFile.delete(); 11231 } 11232 11233 return true; 11234 } 11235 11236 void cleanUpResourcesLI() { 11237 // Try enumerating all code paths before deleting 11238 List<String> allCodePaths = Collections.EMPTY_LIST; 11239 if (codeFile != null && codeFile.exists()) { 11240 try { 11241 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11242 allCodePaths = pkg.getAllCodePaths(); 11243 } catch (PackageParserException e) { 11244 // Ignored; we tried our best 11245 } 11246 } 11247 11248 cleanUp(); 11249 removeDexFiles(allCodePaths, instructionSets); 11250 } 11251 11252 boolean doPostDeleteLI(boolean delete) { 11253 // XXX err, shouldn't we respect the delete flag? 11254 cleanUpResourcesLI(); 11255 return true; 11256 } 11257 } 11258 11259 private boolean isAsecExternal(String cid) { 11260 final String asecPath = PackageHelper.getSdFilesystem(cid); 11261 return !asecPath.startsWith(mAsecInternalPath); 11262 } 11263 11264 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11265 PackageManagerException { 11266 if (copyRet < 0) { 11267 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11268 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11269 throw new PackageManagerException(copyRet, message); 11270 } 11271 } 11272 } 11273 11274 /** 11275 * Extract the MountService "container ID" from the full code path of an 11276 * .apk. 11277 */ 11278 static String cidFromCodePath(String fullCodePath) { 11279 int eidx = fullCodePath.lastIndexOf("/"); 11280 String subStr1 = fullCodePath.substring(0, eidx); 11281 int sidx = subStr1.lastIndexOf("/"); 11282 return subStr1.substring(sidx+1, eidx); 11283 } 11284 11285 /** 11286 * Logic to handle installation of ASEC applications, including copying and 11287 * renaming logic. 11288 */ 11289 class AsecInstallArgs extends InstallArgs { 11290 static final String RES_FILE_NAME = "pkg.apk"; 11291 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11292 11293 String cid; 11294 String packagePath; 11295 String resourcePath; 11296 11297 /** New install */ 11298 AsecInstallArgs(InstallParams params) { 11299 super(params.origin, params.move, params.observer, params.installFlags, 11300 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11301 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11302 params.grantedRuntimePermissions); 11303 } 11304 11305 /** Existing install */ 11306 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11307 boolean isExternal, boolean isForwardLocked) { 11308 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11309 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11310 instructionSets, null, null); 11311 // Hackily pretend we're still looking at a full code path 11312 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11313 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11314 } 11315 11316 // Extract cid from fullCodePath 11317 int eidx = fullCodePath.lastIndexOf("/"); 11318 String subStr1 = fullCodePath.substring(0, eidx); 11319 int sidx = subStr1.lastIndexOf("/"); 11320 cid = subStr1.substring(sidx+1, eidx); 11321 setMountPath(subStr1); 11322 } 11323 11324 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11325 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11326 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11327 instructionSets, null, null); 11328 this.cid = cid; 11329 setMountPath(PackageHelper.getSdDir(cid)); 11330 } 11331 11332 void createCopyFile() { 11333 cid = mInstallerService.allocateExternalStageCidLegacy(); 11334 } 11335 11336 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11337 if (origin.staged) { 11338 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11339 cid = origin.cid; 11340 setMountPath(PackageHelper.getSdDir(cid)); 11341 return PackageManager.INSTALL_SUCCEEDED; 11342 } 11343 11344 if (temp) { 11345 createCopyFile(); 11346 } else { 11347 /* 11348 * Pre-emptively destroy the container since it's destroyed if 11349 * copying fails due to it existing anyway. 11350 */ 11351 PackageHelper.destroySdDir(cid); 11352 } 11353 11354 final String newMountPath = imcs.copyPackageToContainer( 11355 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11356 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11357 11358 if (newMountPath != null) { 11359 setMountPath(newMountPath); 11360 return PackageManager.INSTALL_SUCCEEDED; 11361 } else { 11362 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11363 } 11364 } 11365 11366 @Override 11367 String getCodePath() { 11368 return packagePath; 11369 } 11370 11371 @Override 11372 String getResourcePath() { 11373 return resourcePath; 11374 } 11375 11376 int doPreInstall(int status) { 11377 if (status != PackageManager.INSTALL_SUCCEEDED) { 11378 // Destroy container 11379 PackageHelper.destroySdDir(cid); 11380 } else { 11381 boolean mounted = PackageHelper.isContainerMounted(cid); 11382 if (!mounted) { 11383 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11384 Process.SYSTEM_UID); 11385 if (newMountPath != null) { 11386 setMountPath(newMountPath); 11387 } else { 11388 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11389 } 11390 } 11391 } 11392 return status; 11393 } 11394 11395 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11396 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11397 String newMountPath = null; 11398 if (PackageHelper.isContainerMounted(cid)) { 11399 // Unmount the container 11400 if (!PackageHelper.unMountSdDir(cid)) { 11401 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11402 return false; 11403 } 11404 } 11405 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11406 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11407 " which might be stale. Will try to clean up."); 11408 // Clean up the stale container and proceed to recreate. 11409 if (!PackageHelper.destroySdDir(newCacheId)) { 11410 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11411 return false; 11412 } 11413 // Successfully cleaned up stale container. Try to rename again. 11414 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11415 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11416 + " inspite of cleaning it up."); 11417 return false; 11418 } 11419 } 11420 if (!PackageHelper.isContainerMounted(newCacheId)) { 11421 Slog.w(TAG, "Mounting container " + newCacheId); 11422 newMountPath = PackageHelper.mountSdDir(newCacheId, 11423 getEncryptKey(), Process.SYSTEM_UID); 11424 } else { 11425 newMountPath = PackageHelper.getSdDir(newCacheId); 11426 } 11427 if (newMountPath == null) { 11428 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11429 return false; 11430 } 11431 Log.i(TAG, "Succesfully renamed " + cid + 11432 " to " + newCacheId + 11433 " at new path: " + newMountPath); 11434 cid = newCacheId; 11435 11436 final File beforeCodeFile = new File(packagePath); 11437 setMountPath(newMountPath); 11438 final File afterCodeFile = new File(packagePath); 11439 11440 // Reflect the rename in scanned details 11441 pkg.codePath = afterCodeFile.getAbsolutePath(); 11442 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11443 pkg.baseCodePath); 11444 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11445 pkg.splitCodePaths); 11446 11447 // Reflect the rename in app info 11448 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11449 pkg.applicationInfo.setCodePath(pkg.codePath); 11450 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11451 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11452 pkg.applicationInfo.setResourcePath(pkg.codePath); 11453 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11454 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11455 11456 return true; 11457 } 11458 11459 private void setMountPath(String mountPath) { 11460 final File mountFile = new File(mountPath); 11461 11462 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11463 if (monolithicFile.exists()) { 11464 packagePath = monolithicFile.getAbsolutePath(); 11465 if (isFwdLocked()) { 11466 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11467 } else { 11468 resourcePath = packagePath; 11469 } 11470 } else { 11471 packagePath = mountFile.getAbsolutePath(); 11472 resourcePath = packagePath; 11473 } 11474 } 11475 11476 int doPostInstall(int status, int uid) { 11477 if (status != PackageManager.INSTALL_SUCCEEDED) { 11478 cleanUp(); 11479 } else { 11480 final int groupOwner; 11481 final String protectedFile; 11482 if (isFwdLocked()) { 11483 groupOwner = UserHandle.getSharedAppGid(uid); 11484 protectedFile = RES_FILE_NAME; 11485 } else { 11486 groupOwner = -1; 11487 protectedFile = null; 11488 } 11489 11490 if (uid < Process.FIRST_APPLICATION_UID 11491 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11492 Slog.e(TAG, "Failed to finalize " + cid); 11493 PackageHelper.destroySdDir(cid); 11494 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11495 } 11496 11497 boolean mounted = PackageHelper.isContainerMounted(cid); 11498 if (!mounted) { 11499 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11500 } 11501 } 11502 return status; 11503 } 11504 11505 private void cleanUp() { 11506 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11507 11508 // Destroy secure container 11509 PackageHelper.destroySdDir(cid); 11510 } 11511 11512 private List<String> getAllCodePaths() { 11513 final File codeFile = new File(getCodePath()); 11514 if (codeFile != null && codeFile.exists()) { 11515 try { 11516 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11517 return pkg.getAllCodePaths(); 11518 } catch (PackageParserException e) { 11519 // Ignored; we tried our best 11520 } 11521 } 11522 return Collections.EMPTY_LIST; 11523 } 11524 11525 void cleanUpResourcesLI() { 11526 // Enumerate all code paths before deleting 11527 cleanUpResourcesLI(getAllCodePaths()); 11528 } 11529 11530 private void cleanUpResourcesLI(List<String> allCodePaths) { 11531 cleanUp(); 11532 removeDexFiles(allCodePaths, instructionSets); 11533 } 11534 11535 String getPackageName() { 11536 return getAsecPackageName(cid); 11537 } 11538 11539 boolean doPostDeleteLI(boolean delete) { 11540 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11541 final List<String> allCodePaths = getAllCodePaths(); 11542 boolean mounted = PackageHelper.isContainerMounted(cid); 11543 if (mounted) { 11544 // Unmount first 11545 if (PackageHelper.unMountSdDir(cid)) { 11546 mounted = false; 11547 } 11548 } 11549 if (!mounted && delete) { 11550 cleanUpResourcesLI(allCodePaths); 11551 } 11552 return !mounted; 11553 } 11554 11555 @Override 11556 int doPreCopy() { 11557 if (isFwdLocked()) { 11558 if (!PackageHelper.fixSdPermissions(cid, 11559 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11560 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11561 } 11562 } 11563 11564 return PackageManager.INSTALL_SUCCEEDED; 11565 } 11566 11567 @Override 11568 int doPostCopy(int uid) { 11569 if (isFwdLocked()) { 11570 if (uid < Process.FIRST_APPLICATION_UID 11571 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11572 RES_FILE_NAME)) { 11573 Slog.e(TAG, "Failed to finalize " + cid); 11574 PackageHelper.destroySdDir(cid); 11575 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11576 } 11577 } 11578 11579 return PackageManager.INSTALL_SUCCEEDED; 11580 } 11581 } 11582 11583 /** 11584 * Logic to handle movement of existing installed applications. 11585 */ 11586 class MoveInstallArgs extends InstallArgs { 11587 private File codeFile; 11588 private File resourceFile; 11589 11590 /** New install */ 11591 MoveInstallArgs(InstallParams params) { 11592 super(params.origin, params.move, params.observer, params.installFlags, 11593 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11594 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11595 params.grantedRuntimePermissions); 11596 } 11597 11598 int copyApk(IMediaContainerService imcs, boolean temp) { 11599 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11600 + move.fromUuid + " to " + move.toUuid); 11601 synchronized (mInstaller) { 11602 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11603 move.dataAppName, move.appId, move.seinfo) != 0) { 11604 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11605 } 11606 } 11607 11608 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11609 resourceFile = codeFile; 11610 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11611 11612 return PackageManager.INSTALL_SUCCEEDED; 11613 } 11614 11615 int doPreInstall(int status) { 11616 if (status != PackageManager.INSTALL_SUCCEEDED) { 11617 cleanUp(move.toUuid); 11618 } 11619 return status; 11620 } 11621 11622 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11623 if (status != PackageManager.INSTALL_SUCCEEDED) { 11624 cleanUp(move.toUuid); 11625 return false; 11626 } 11627 11628 // Reflect the move in app info 11629 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11630 pkg.applicationInfo.setCodePath(pkg.codePath); 11631 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11632 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11633 pkg.applicationInfo.setResourcePath(pkg.codePath); 11634 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11635 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11636 11637 return true; 11638 } 11639 11640 int doPostInstall(int status, int uid) { 11641 if (status == PackageManager.INSTALL_SUCCEEDED) { 11642 cleanUp(move.fromUuid); 11643 } else { 11644 cleanUp(move.toUuid); 11645 } 11646 return status; 11647 } 11648 11649 @Override 11650 String getCodePath() { 11651 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11652 } 11653 11654 @Override 11655 String getResourcePath() { 11656 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11657 } 11658 11659 private boolean cleanUp(String volumeUuid) { 11660 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11661 move.dataAppName); 11662 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11663 synchronized (mInstallLock) { 11664 // Clean up both app data and code 11665 removeDataDirsLI(volumeUuid, move.packageName); 11666 if (codeFile.isDirectory()) { 11667 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11668 } else { 11669 codeFile.delete(); 11670 } 11671 } 11672 return true; 11673 } 11674 11675 void cleanUpResourcesLI() { 11676 throw new UnsupportedOperationException(); 11677 } 11678 11679 boolean doPostDeleteLI(boolean delete) { 11680 throw new UnsupportedOperationException(); 11681 } 11682 } 11683 11684 static String getAsecPackageName(String packageCid) { 11685 int idx = packageCid.lastIndexOf("-"); 11686 if (idx == -1) { 11687 return packageCid; 11688 } 11689 return packageCid.substring(0, idx); 11690 } 11691 11692 // Utility method used to create code paths based on package name and available index. 11693 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11694 String idxStr = ""; 11695 int idx = 1; 11696 // Fall back to default value of idx=1 if prefix is not 11697 // part of oldCodePath 11698 if (oldCodePath != null) { 11699 String subStr = oldCodePath; 11700 // Drop the suffix right away 11701 if (suffix != null && subStr.endsWith(suffix)) { 11702 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11703 } 11704 // If oldCodePath already contains prefix find out the 11705 // ending index to either increment or decrement. 11706 int sidx = subStr.lastIndexOf(prefix); 11707 if (sidx != -1) { 11708 subStr = subStr.substring(sidx + prefix.length()); 11709 if (subStr != null) { 11710 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11711 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11712 } 11713 try { 11714 idx = Integer.parseInt(subStr); 11715 if (idx <= 1) { 11716 idx++; 11717 } else { 11718 idx--; 11719 } 11720 } catch(NumberFormatException e) { 11721 } 11722 } 11723 } 11724 } 11725 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11726 return prefix + idxStr; 11727 } 11728 11729 private File getNextCodePath(File targetDir, String packageName) { 11730 int suffix = 1; 11731 File result; 11732 do { 11733 result = new File(targetDir, packageName + "-" + suffix); 11734 suffix++; 11735 } while (result.exists()); 11736 return result; 11737 } 11738 11739 // Utility method that returns the relative package path with respect 11740 // to the installation directory. Like say for /data/data/com.test-1.apk 11741 // string com.test-1 is returned. 11742 static String deriveCodePathName(String codePath) { 11743 if (codePath == null) { 11744 return null; 11745 } 11746 final File codeFile = new File(codePath); 11747 final String name = codeFile.getName(); 11748 if (codeFile.isDirectory()) { 11749 return name; 11750 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11751 final int lastDot = name.lastIndexOf('.'); 11752 return name.substring(0, lastDot); 11753 } else { 11754 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11755 return null; 11756 } 11757 } 11758 11759 class PackageInstalledInfo { 11760 String name; 11761 int uid; 11762 // The set of users that originally had this package installed. 11763 int[] origUsers; 11764 // The set of users that now have this package installed. 11765 int[] newUsers; 11766 PackageParser.Package pkg; 11767 int returnCode; 11768 String returnMsg; 11769 PackageRemovedInfo removedInfo; 11770 11771 public void setError(int code, String msg) { 11772 returnCode = code; 11773 returnMsg = msg; 11774 Slog.w(TAG, msg); 11775 } 11776 11777 public void setError(String msg, PackageParserException e) { 11778 returnCode = e.error; 11779 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11780 Slog.w(TAG, msg, e); 11781 } 11782 11783 public void setError(String msg, PackageManagerException e) { 11784 returnCode = e.error; 11785 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11786 Slog.w(TAG, msg, e); 11787 } 11788 11789 // In some error cases we want to convey more info back to the observer 11790 String origPackage; 11791 String origPermission; 11792 } 11793 11794 /* 11795 * Install a non-existing package. 11796 */ 11797 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11798 UserHandle user, String installerPackageName, String volumeUuid, 11799 PackageInstalledInfo res) { 11800 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11801 11802 // Remember this for later, in case we need to rollback this install 11803 String pkgName = pkg.packageName; 11804 11805 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11806 final boolean dataDirExists = Environment 11807 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11808 11809 synchronized(mPackages) { 11810 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11811 // A package with the same name is already installed, though 11812 // it has been renamed to an older name. The package we 11813 // are trying to install should be installed as an update to 11814 // the existing one, but that has not been requested, so bail. 11815 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11816 + " without first uninstalling package running as " 11817 + mSettings.mRenamedPackages.get(pkgName)); 11818 return; 11819 } 11820 if (mPackages.containsKey(pkgName)) { 11821 // Don't allow installation over an existing package with the same name. 11822 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11823 + " without first uninstalling."); 11824 return; 11825 } 11826 } 11827 11828 try { 11829 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11830 System.currentTimeMillis(), user); 11831 11832 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11833 // delete the partially installed application. the data directory will have to be 11834 // restored if it was already existing 11835 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11836 // remove package from internal structures. Note that we want deletePackageX to 11837 // delete the package data and cache directories that it created in 11838 // scanPackageLocked, unless those directories existed before we even tried to 11839 // install. 11840 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11841 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11842 res.removedInfo, true); 11843 } 11844 11845 } catch (PackageManagerException e) { 11846 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11847 } 11848 11849 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11850 } 11851 11852 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11853 // Can't rotate keys during boot or if sharedUser. 11854 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11855 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11856 return false; 11857 } 11858 // app is using upgradeKeySets; make sure all are valid 11859 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11860 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11861 for (int i = 0; i < upgradeKeySets.length; i++) { 11862 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11863 Slog.wtf(TAG, "Package " 11864 + (oldPs.name != null ? oldPs.name : "<null>") 11865 + " contains upgrade-key-set reference to unknown key-set: " 11866 + upgradeKeySets[i] 11867 + " reverting to signatures check."); 11868 return false; 11869 } 11870 } 11871 return true; 11872 } 11873 11874 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11875 // Upgrade keysets are being used. Determine if new package has a superset of the 11876 // required keys. 11877 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11878 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11879 for (int i = 0; i < upgradeKeySets.length; i++) { 11880 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11881 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11882 return true; 11883 } 11884 } 11885 return false; 11886 } 11887 11888 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11889 UserHandle user, String installerPackageName, String volumeUuid, 11890 PackageInstalledInfo res) { 11891 final PackageParser.Package oldPackage; 11892 final String pkgName = pkg.packageName; 11893 final int[] allUsers; 11894 final boolean[] perUserInstalled; 11895 11896 // First find the old package info and check signatures 11897 synchronized(mPackages) { 11898 oldPackage = mPackages.get(pkgName); 11899 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11900 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11901 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11902 if(!checkUpgradeKeySetLP(ps, pkg)) { 11903 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11904 "New package not signed by keys specified by upgrade-keysets: " 11905 + pkgName); 11906 return; 11907 } 11908 } else { 11909 // default to original signature matching 11910 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11911 != PackageManager.SIGNATURE_MATCH) { 11912 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11913 "New package has a different signature: " + pkgName); 11914 return; 11915 } 11916 } 11917 11918 // In case of rollback, remember per-user/profile install state 11919 allUsers = sUserManager.getUserIds(); 11920 perUserInstalled = new boolean[allUsers.length]; 11921 for (int i = 0; i < allUsers.length; i++) { 11922 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11923 } 11924 } 11925 11926 boolean sysPkg = (isSystemApp(oldPackage)); 11927 if (sysPkg) { 11928 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11929 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11930 } else { 11931 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11932 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11933 } 11934 } 11935 11936 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11937 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11938 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11939 String volumeUuid, PackageInstalledInfo res) { 11940 String pkgName = deletedPackage.packageName; 11941 boolean deletedPkg = true; 11942 boolean updatedSettings = false; 11943 11944 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11945 + deletedPackage); 11946 long origUpdateTime; 11947 if (pkg.mExtras != null) { 11948 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11949 } else { 11950 origUpdateTime = 0; 11951 } 11952 11953 // First delete the existing package while retaining the data directory 11954 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11955 res.removedInfo, true)) { 11956 // If the existing package wasn't successfully deleted 11957 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11958 deletedPkg = false; 11959 } else { 11960 // Successfully deleted the old package; proceed with replace. 11961 11962 // If deleted package lived in a container, give users a chance to 11963 // relinquish resources before killing. 11964 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11965 if (DEBUG_INSTALL) { 11966 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11967 } 11968 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11969 final ArrayList<String> pkgList = new ArrayList<String>(1); 11970 pkgList.add(deletedPackage.applicationInfo.packageName); 11971 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11972 } 11973 11974 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11975 try { 11976 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 11977 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11978 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11979 perUserInstalled, res, user); 11980 updatedSettings = true; 11981 } catch (PackageManagerException e) { 11982 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11983 } 11984 } 11985 11986 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11987 // remove package from internal structures. Note that we want deletePackageX to 11988 // delete the package data and cache directories that it created in 11989 // scanPackageLocked, unless those directories existed before we even tried to 11990 // install. 11991 if(updatedSettings) { 11992 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11993 deletePackageLI( 11994 pkgName, null, true, allUsers, perUserInstalled, 11995 PackageManager.DELETE_KEEP_DATA, 11996 res.removedInfo, true); 11997 } 11998 // Since we failed to install the new package we need to restore the old 11999 // package that we deleted. 12000 if (deletedPkg) { 12001 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12002 File restoreFile = new File(deletedPackage.codePath); 12003 // Parse old package 12004 boolean oldExternal = isExternal(deletedPackage); 12005 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12006 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12007 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12008 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12009 try { 12010 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 12011 } catch (PackageManagerException e) { 12012 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12013 + e.getMessage()); 12014 return; 12015 } 12016 // Restore of old package succeeded. Update permissions. 12017 // writer 12018 synchronized (mPackages) { 12019 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12020 UPDATE_PERMISSIONS_ALL); 12021 // can downgrade to reader 12022 mSettings.writeLPr(); 12023 } 12024 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12025 } 12026 } 12027 } 12028 12029 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12030 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12031 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12032 String volumeUuid, PackageInstalledInfo res) { 12033 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12034 + ", old=" + deletedPackage); 12035 boolean disabledSystem = false; 12036 boolean updatedSettings = false; 12037 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12038 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12039 != 0) { 12040 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12041 } 12042 String packageName = deletedPackage.packageName; 12043 if (packageName == null) { 12044 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12045 "Attempt to delete null packageName."); 12046 return; 12047 } 12048 PackageParser.Package oldPkg; 12049 PackageSetting oldPkgSetting; 12050 // reader 12051 synchronized (mPackages) { 12052 oldPkg = mPackages.get(packageName); 12053 oldPkgSetting = mSettings.mPackages.get(packageName); 12054 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12055 (oldPkgSetting == null)) { 12056 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12057 "Couldn't find package:" + packageName + " information"); 12058 return; 12059 } 12060 } 12061 12062 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12063 12064 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12065 res.removedInfo.removedPackage = packageName; 12066 // Remove existing system package 12067 removePackageLI(oldPkgSetting, true); 12068 // writer 12069 synchronized (mPackages) { 12070 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12071 if (!disabledSystem && deletedPackage != null) { 12072 // We didn't need to disable the .apk as a current system package, 12073 // which means we are replacing another update that is already 12074 // installed. We need to make sure to delete the older one's .apk. 12075 res.removedInfo.args = createInstallArgsForExisting(0, 12076 deletedPackage.applicationInfo.getCodePath(), 12077 deletedPackage.applicationInfo.getResourcePath(), 12078 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12079 } else { 12080 res.removedInfo.args = null; 12081 } 12082 } 12083 12084 // Successfully disabled the old package. Now proceed with re-installation 12085 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12086 12087 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12088 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12089 12090 PackageParser.Package newPackage = null; 12091 try { 12092 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12093 if (newPackage.mExtras != null) { 12094 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12095 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12096 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12097 12098 // is the update attempting to change shared user? that isn't going to work... 12099 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12100 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12101 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12102 + " to " + newPkgSetting.sharedUser); 12103 updatedSettings = true; 12104 } 12105 } 12106 12107 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12108 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12109 perUserInstalled, res, user); 12110 updatedSettings = true; 12111 } 12112 12113 } catch (PackageManagerException e) { 12114 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12115 } 12116 12117 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12118 // Re installation failed. Restore old information 12119 // Remove new pkg information 12120 if (newPackage != null) { 12121 removeInstalledPackageLI(newPackage, true); 12122 } 12123 // Add back the old system package 12124 try { 12125 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12126 } catch (PackageManagerException e) { 12127 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12128 } 12129 // Restore the old system information in Settings 12130 synchronized (mPackages) { 12131 if (disabledSystem) { 12132 mSettings.enableSystemPackageLPw(packageName); 12133 } 12134 if (updatedSettings) { 12135 mSettings.setInstallerPackageName(packageName, 12136 oldPkgSetting.installerPackageName); 12137 } 12138 mSettings.writeLPr(); 12139 } 12140 } 12141 } 12142 12143 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12144 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12145 UserHandle user) { 12146 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12147 12148 String pkgName = newPackage.packageName; 12149 synchronized (mPackages) { 12150 //write settings. the installStatus will be incomplete at this stage. 12151 //note that the new package setting would have already been 12152 //added to mPackages. It hasn't been persisted yet. 12153 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12154 mSettings.writeLPr(); 12155 } 12156 12157 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12158 synchronized (mPackages) { 12159 updatePermissionsLPw(newPackage.packageName, newPackage, 12160 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12161 ? UPDATE_PERMISSIONS_ALL : 0)); 12162 // For system-bundled packages, we assume that installing an upgraded version 12163 // of the package implies that the user actually wants to run that new code, 12164 // so we enable the package. 12165 PackageSetting ps = mSettings.mPackages.get(pkgName); 12166 if (ps != null) { 12167 if (isSystemApp(newPackage)) { 12168 // NB: implicit assumption that system package upgrades apply to all users 12169 if (DEBUG_INSTALL) { 12170 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12171 } 12172 if (res.origUsers != null) { 12173 for (int userHandle : res.origUsers) { 12174 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12175 userHandle, installerPackageName); 12176 } 12177 } 12178 // Also convey the prior install/uninstall state 12179 if (allUsers != null && perUserInstalled != null) { 12180 for (int i = 0; i < allUsers.length; i++) { 12181 if (DEBUG_INSTALL) { 12182 Slog.d(TAG, " user " + allUsers[i] 12183 + " => " + perUserInstalled[i]); 12184 } 12185 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12186 } 12187 // these install state changes will be persisted in the 12188 // upcoming call to mSettings.writeLPr(). 12189 } 12190 } 12191 // It's implied that when a user requests installation, they want the app to be 12192 // installed and enabled. 12193 int userId = user.getIdentifier(); 12194 if (userId != UserHandle.USER_ALL) { 12195 ps.setInstalled(true, userId); 12196 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12197 } 12198 } 12199 res.name = pkgName; 12200 res.uid = newPackage.applicationInfo.uid; 12201 res.pkg = newPackage; 12202 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12203 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12204 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12205 //to update install status 12206 mSettings.writeLPr(); 12207 } 12208 12209 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12210 } 12211 12212 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12213 try { 12214 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12215 installPackageLI(args, res); 12216 } finally { 12217 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12218 } 12219 } 12220 12221 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12222 final int installFlags = args.installFlags; 12223 final String installerPackageName = args.installerPackageName; 12224 final String volumeUuid = args.volumeUuid; 12225 final File tmpPackageFile = new File(args.getCodePath()); 12226 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12227 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12228 || (args.volumeUuid != null)); 12229 boolean replace = false; 12230 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12231 if (args.move != null) { 12232 // moving a complete application; perfom an initial scan on the new install location 12233 scanFlags |= SCAN_INITIAL; 12234 } 12235 // Result object to be returned 12236 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12237 12238 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12239 12240 // Retrieve PackageSettings and parse package 12241 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12242 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12243 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12244 PackageParser pp = new PackageParser(); 12245 pp.setSeparateProcesses(mSeparateProcesses); 12246 pp.setDisplayMetrics(mMetrics); 12247 12248 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12249 final PackageParser.Package pkg; 12250 try { 12251 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12252 } catch (PackageParserException e) { 12253 res.setError("Failed parse during installPackageLI", e); 12254 return; 12255 } finally { 12256 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12257 } 12258 12259 // Mark that we have an install time CPU ABI override. 12260 pkg.cpuAbiOverride = args.abiOverride; 12261 12262 String pkgName = res.name = pkg.packageName; 12263 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12264 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12265 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12266 return; 12267 } 12268 } 12269 12270 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12271 try { 12272 pp.collectCertificates(pkg, parseFlags); 12273 pp.collectManifestDigest(pkg); 12274 } catch (PackageParserException e) { 12275 res.setError("Failed collect during installPackageLI", e); 12276 return; 12277 } finally { 12278 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12279 } 12280 12281 /* If the installer passed in a manifest digest, compare it now. */ 12282 if (args.manifestDigest != null) { 12283 if (DEBUG_INSTALL) { 12284 final String parsedManifest = pkg.manifestDigest == null ? "null" 12285 : pkg.manifestDigest.toString(); 12286 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12287 + parsedManifest); 12288 } 12289 12290 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12291 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12292 return; 12293 } 12294 } else if (DEBUG_INSTALL) { 12295 final String parsedManifest = pkg.manifestDigest == null 12296 ? "null" : pkg.manifestDigest.toString(); 12297 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12298 } 12299 12300 // Get rid of all references to package scan path via parser. 12301 pp = null; 12302 String oldCodePath = null; 12303 boolean systemApp = false; 12304 synchronized (mPackages) { 12305 // Check if installing already existing package 12306 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12307 String oldName = mSettings.mRenamedPackages.get(pkgName); 12308 if (pkg.mOriginalPackages != null 12309 && pkg.mOriginalPackages.contains(oldName) 12310 && mPackages.containsKey(oldName)) { 12311 // This package is derived from an original package, 12312 // and this device has been updating from that original 12313 // name. We must continue using the original name, so 12314 // rename the new package here. 12315 pkg.setPackageName(oldName); 12316 pkgName = pkg.packageName; 12317 replace = true; 12318 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12319 + oldName + " pkgName=" + pkgName); 12320 } else if (mPackages.containsKey(pkgName)) { 12321 // This package, under its official name, already exists 12322 // on the device; we should replace it. 12323 replace = true; 12324 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12325 } 12326 12327 // Prevent apps opting out from runtime permissions 12328 if (replace) { 12329 PackageParser.Package oldPackage = mPackages.get(pkgName); 12330 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12331 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12332 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12333 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12334 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12335 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12336 + " doesn't support runtime permissions but the old" 12337 + " target SDK " + oldTargetSdk + " does."); 12338 return; 12339 } 12340 } 12341 } 12342 12343 PackageSetting ps = mSettings.mPackages.get(pkgName); 12344 if (ps != null) { 12345 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12346 12347 // Quick sanity check that we're signed correctly if updating; 12348 // we'll check this again later when scanning, but we want to 12349 // bail early here before tripping over redefined permissions. 12350 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12351 if (!checkUpgradeKeySetLP(ps, pkg)) { 12352 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12353 + pkg.packageName + " upgrade keys do not match the " 12354 + "previously installed version"); 12355 return; 12356 } 12357 } else { 12358 try { 12359 verifySignaturesLP(ps, pkg); 12360 } catch (PackageManagerException e) { 12361 res.setError(e.error, e.getMessage()); 12362 return; 12363 } 12364 } 12365 12366 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12367 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12368 systemApp = (ps.pkg.applicationInfo.flags & 12369 ApplicationInfo.FLAG_SYSTEM) != 0; 12370 } 12371 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12372 } 12373 12374 // Check whether the newly-scanned package wants to define an already-defined perm 12375 int N = pkg.permissions.size(); 12376 for (int i = N-1; i >= 0; i--) { 12377 PackageParser.Permission perm = pkg.permissions.get(i); 12378 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12379 if (bp != null) { 12380 // If the defining package is signed with our cert, it's okay. This 12381 // also includes the "updating the same package" case, of course. 12382 // "updating same package" could also involve key-rotation. 12383 final boolean sigsOk; 12384 if (bp.sourcePackage.equals(pkg.packageName) 12385 && (bp.packageSetting instanceof PackageSetting) 12386 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12387 scanFlags))) { 12388 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12389 } else { 12390 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12391 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12392 } 12393 if (!sigsOk) { 12394 // If the owning package is the system itself, we log but allow 12395 // install to proceed; we fail the install on all other permission 12396 // redefinitions. 12397 if (!bp.sourcePackage.equals("android")) { 12398 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12399 + pkg.packageName + " attempting to redeclare permission " 12400 + perm.info.name + " already owned by " + bp.sourcePackage); 12401 res.origPermission = perm.info.name; 12402 res.origPackage = bp.sourcePackage; 12403 return; 12404 } else { 12405 Slog.w(TAG, "Package " + pkg.packageName 12406 + " attempting to redeclare system permission " 12407 + perm.info.name + "; ignoring new declaration"); 12408 pkg.permissions.remove(i); 12409 } 12410 } 12411 } 12412 } 12413 12414 } 12415 12416 if (systemApp && onExternal) { 12417 // Disable updates to system apps on sdcard 12418 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12419 "Cannot install updates to system apps on sdcard"); 12420 return; 12421 } 12422 12423 if (args.move != null) { 12424 // We did an in-place move, so dex is ready to roll 12425 scanFlags |= SCAN_NO_DEX; 12426 scanFlags |= SCAN_MOVE; 12427 12428 synchronized (mPackages) { 12429 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12430 if (ps == null) { 12431 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12432 "Missing settings for moved package " + pkgName); 12433 } 12434 12435 // We moved the entire application as-is, so bring over the 12436 // previously derived ABI information. 12437 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12438 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12439 } 12440 12441 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12442 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12443 scanFlags |= SCAN_NO_DEX; 12444 12445 try { 12446 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12447 true /* extract libs */); 12448 } catch (PackageManagerException pme) { 12449 Slog.e(TAG, "Error deriving application ABI", pme); 12450 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12451 return; 12452 } 12453 12454 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12455 int result = mPackageDexOptimizer 12456 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12457 false /* defer */, false /* inclDependencies */); 12458 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12459 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12460 return; 12461 } 12462 } 12463 12464 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12465 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12466 return; 12467 } 12468 12469 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12470 12471 if (replace) { 12472 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12473 installerPackageName, volumeUuid, res); 12474 } else { 12475 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12476 args.user, installerPackageName, volumeUuid, res); 12477 } 12478 synchronized (mPackages) { 12479 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12480 if (ps != null) { 12481 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12482 } 12483 } 12484 } 12485 12486 private void startIntentFilterVerifications(int userId, boolean replacing, 12487 PackageParser.Package pkg) { 12488 if (mIntentFilterVerifierComponent == null) { 12489 Slog.w(TAG, "No IntentFilter verification will not be done as " 12490 + "there is no IntentFilterVerifier available!"); 12491 return; 12492 } 12493 12494 final int verifierUid = getPackageUid( 12495 mIntentFilterVerifierComponent.getPackageName(), 12496 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12497 12498 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12499 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12500 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12501 mHandler.sendMessage(msg); 12502 } 12503 12504 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12505 PackageParser.Package pkg) { 12506 int size = pkg.activities.size(); 12507 if (size == 0) { 12508 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12509 "No activity, so no need to verify any IntentFilter!"); 12510 return; 12511 } 12512 12513 final boolean hasDomainURLs = hasDomainURLs(pkg); 12514 if (!hasDomainURLs) { 12515 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12516 "No domain URLs, so no need to verify any IntentFilter!"); 12517 return; 12518 } 12519 12520 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12521 + " if any IntentFilter from the " + size 12522 + " Activities needs verification ..."); 12523 12524 int count = 0; 12525 final String packageName = pkg.packageName; 12526 12527 synchronized (mPackages) { 12528 // If this is a new install and we see that we've already run verification for this 12529 // package, we have nothing to do: it means the state was restored from backup. 12530 if (!replacing) { 12531 IntentFilterVerificationInfo ivi = 12532 mSettings.getIntentFilterVerificationLPr(packageName); 12533 if (ivi != null) { 12534 if (DEBUG_DOMAIN_VERIFICATION) { 12535 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12536 + ivi.getStatusString()); 12537 } 12538 return; 12539 } 12540 } 12541 12542 // If any filters need to be verified, then all need to be. 12543 boolean needToVerify = false; 12544 for (PackageParser.Activity a : pkg.activities) { 12545 for (ActivityIntentInfo filter : a.intents) { 12546 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12547 if (DEBUG_DOMAIN_VERIFICATION) { 12548 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12549 } 12550 needToVerify = true; 12551 break; 12552 } 12553 } 12554 } 12555 12556 if (needToVerify) { 12557 final int verificationId = mIntentFilterVerificationToken++; 12558 for (PackageParser.Activity a : pkg.activities) { 12559 for (ActivityIntentInfo filter : a.intents) { 12560 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12561 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12562 "Verification needed for IntentFilter:" + filter.toString()); 12563 mIntentFilterVerifier.addOneIntentFilterVerification( 12564 verifierUid, userId, verificationId, filter, packageName); 12565 count++; 12566 } 12567 } 12568 } 12569 } 12570 } 12571 12572 if (count > 0) { 12573 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12574 + " IntentFilter verification" + (count > 1 ? "s" : "") 12575 + " for userId:" + userId); 12576 mIntentFilterVerifier.startVerifications(userId); 12577 } else { 12578 if (DEBUG_DOMAIN_VERIFICATION) { 12579 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12580 } 12581 } 12582 } 12583 12584 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12585 final ComponentName cn = filter.activity.getComponentName(); 12586 final String packageName = cn.getPackageName(); 12587 12588 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12589 packageName); 12590 if (ivi == null) { 12591 return true; 12592 } 12593 int status = ivi.getStatus(); 12594 switch (status) { 12595 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12596 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12597 return true; 12598 12599 default: 12600 // Nothing to do 12601 return false; 12602 } 12603 } 12604 12605 private static boolean isMultiArch(PackageSetting ps) { 12606 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12607 } 12608 12609 private static boolean isMultiArch(ApplicationInfo info) { 12610 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12611 } 12612 12613 private static boolean isExternal(PackageParser.Package pkg) { 12614 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12615 } 12616 12617 private static boolean isExternal(PackageSetting ps) { 12618 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12619 } 12620 12621 private static boolean isExternal(ApplicationInfo info) { 12622 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12623 } 12624 12625 private static boolean isSystemApp(PackageParser.Package pkg) { 12626 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12627 } 12628 12629 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12630 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12631 } 12632 12633 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12634 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12635 } 12636 12637 private static boolean isSystemApp(PackageSetting ps) { 12638 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12639 } 12640 12641 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12642 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12643 } 12644 12645 private int packageFlagsToInstallFlags(PackageSetting ps) { 12646 int installFlags = 0; 12647 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12648 // This existing package was an external ASEC install when we have 12649 // the external flag without a UUID 12650 installFlags |= PackageManager.INSTALL_EXTERNAL; 12651 } 12652 if (ps.isForwardLocked()) { 12653 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12654 } 12655 return installFlags; 12656 } 12657 12658 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12659 if (isExternal(pkg)) { 12660 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12661 return mSettings.getExternalVersion(); 12662 } else { 12663 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12664 } 12665 } else { 12666 return mSettings.getInternalVersion(); 12667 } 12668 } 12669 12670 private void deleteTempPackageFiles() { 12671 final FilenameFilter filter = new FilenameFilter() { 12672 public boolean accept(File dir, String name) { 12673 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12674 } 12675 }; 12676 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12677 file.delete(); 12678 } 12679 } 12680 12681 @Override 12682 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12683 int flags) { 12684 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12685 flags); 12686 } 12687 12688 @Override 12689 public void deletePackage(final String packageName, 12690 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12691 mContext.enforceCallingOrSelfPermission( 12692 android.Manifest.permission.DELETE_PACKAGES, null); 12693 Preconditions.checkNotNull(packageName); 12694 Preconditions.checkNotNull(observer); 12695 final int uid = Binder.getCallingUid(); 12696 if (UserHandle.getUserId(uid) != userId) { 12697 mContext.enforceCallingPermission( 12698 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12699 "deletePackage for user " + userId); 12700 } 12701 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12702 try { 12703 observer.onPackageDeleted(packageName, 12704 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12705 } catch (RemoteException re) { 12706 } 12707 return; 12708 } 12709 12710 boolean uninstallBlocked = false; 12711 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12712 int[] users = sUserManager.getUserIds(); 12713 for (int i = 0; i < users.length; ++i) { 12714 if (getBlockUninstallForUser(packageName, users[i])) { 12715 uninstallBlocked = true; 12716 break; 12717 } 12718 } 12719 } else { 12720 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12721 } 12722 if (uninstallBlocked) { 12723 try { 12724 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12725 null); 12726 } catch (RemoteException re) { 12727 } 12728 return; 12729 } 12730 12731 if (DEBUG_REMOVE) { 12732 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12733 } 12734 // Queue up an async operation since the package deletion may take a little while. 12735 mHandler.post(new Runnable() { 12736 public void run() { 12737 mHandler.removeCallbacks(this); 12738 final int returnCode = deletePackageX(packageName, userId, flags); 12739 if (observer != null) { 12740 try { 12741 observer.onPackageDeleted(packageName, returnCode, null); 12742 } catch (RemoteException e) { 12743 Log.i(TAG, "Observer no longer exists."); 12744 } //end catch 12745 } //end if 12746 } //end run 12747 }); 12748 } 12749 12750 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12751 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12752 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12753 try { 12754 if (dpm != null) { 12755 if (dpm.isDeviceOwner(packageName)) { 12756 return true; 12757 } 12758 int[] users; 12759 if (userId == UserHandle.USER_ALL) { 12760 users = sUserManager.getUserIds(); 12761 } else { 12762 users = new int[]{userId}; 12763 } 12764 for (int i = 0; i < users.length; ++i) { 12765 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12766 return true; 12767 } 12768 } 12769 } 12770 } catch (RemoteException e) { 12771 } 12772 return false; 12773 } 12774 12775 /** 12776 * This method is an internal method that could be get invoked either 12777 * to delete an installed package or to clean up a failed installation. 12778 * After deleting an installed package, a broadcast is sent to notify any 12779 * listeners that the package has been installed. For cleaning up a failed 12780 * installation, the broadcast is not necessary since the package's 12781 * installation wouldn't have sent the initial broadcast either 12782 * The key steps in deleting a package are 12783 * deleting the package information in internal structures like mPackages, 12784 * deleting the packages base directories through installd 12785 * updating mSettings to reflect current status 12786 * persisting settings for later use 12787 * sending a broadcast if necessary 12788 */ 12789 private int deletePackageX(String packageName, int userId, int flags) { 12790 final PackageRemovedInfo info = new PackageRemovedInfo(); 12791 final boolean res; 12792 12793 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12794 ? UserHandle.ALL : new UserHandle(userId); 12795 12796 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12797 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12798 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12799 } 12800 12801 boolean removedForAllUsers = false; 12802 boolean systemUpdate = false; 12803 12804 // for the uninstall-updates case and restricted profiles, remember the per- 12805 // userhandle installed state 12806 int[] allUsers; 12807 boolean[] perUserInstalled; 12808 synchronized (mPackages) { 12809 PackageSetting ps = mSettings.mPackages.get(packageName); 12810 allUsers = sUserManager.getUserIds(); 12811 perUserInstalled = new boolean[allUsers.length]; 12812 for (int i = 0; i < allUsers.length; i++) { 12813 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12814 } 12815 } 12816 12817 synchronized (mInstallLock) { 12818 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12819 res = deletePackageLI(packageName, removeForUser, 12820 true, allUsers, perUserInstalled, 12821 flags | REMOVE_CHATTY, info, true); 12822 systemUpdate = info.isRemovedPackageSystemUpdate; 12823 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12824 removedForAllUsers = true; 12825 } 12826 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12827 + " removedForAllUsers=" + removedForAllUsers); 12828 } 12829 12830 if (res) { 12831 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12832 12833 // If the removed package was a system update, the old system package 12834 // was re-enabled; we need to broadcast this information 12835 if (systemUpdate) { 12836 Bundle extras = new Bundle(1); 12837 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12838 ? info.removedAppId : info.uid); 12839 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12840 12841 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12842 extras, null, null, null); 12843 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12844 extras, null, null, null); 12845 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12846 null, packageName, null, null); 12847 } 12848 } 12849 // Force a gc here. 12850 Runtime.getRuntime().gc(); 12851 // Delete the resources here after sending the broadcast to let 12852 // other processes clean up before deleting resources. 12853 if (info.args != null) { 12854 synchronized (mInstallLock) { 12855 info.args.doPostDeleteLI(true); 12856 } 12857 } 12858 12859 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12860 } 12861 12862 class PackageRemovedInfo { 12863 String removedPackage; 12864 int uid = -1; 12865 int removedAppId = -1; 12866 int[] removedUsers = null; 12867 boolean isRemovedPackageSystemUpdate = false; 12868 // Clean up resources deleted packages. 12869 InstallArgs args = null; 12870 12871 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12872 Bundle extras = new Bundle(1); 12873 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12874 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12875 if (replacing) { 12876 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12877 } 12878 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12879 if (removedPackage != null) { 12880 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12881 extras, null, null, removedUsers); 12882 if (fullRemove && !replacing) { 12883 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12884 extras, null, null, removedUsers); 12885 } 12886 } 12887 if (removedAppId >= 0) { 12888 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12889 removedUsers); 12890 } 12891 } 12892 } 12893 12894 /* 12895 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12896 * flag is not set, the data directory is removed as well. 12897 * make sure this flag is set for partially installed apps. If not its meaningless to 12898 * delete a partially installed application. 12899 */ 12900 private void removePackageDataLI(PackageSetting ps, 12901 int[] allUserHandles, boolean[] perUserInstalled, 12902 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12903 String packageName = ps.name; 12904 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12905 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12906 // Retrieve object to delete permissions for shared user later on 12907 final PackageSetting deletedPs; 12908 // reader 12909 synchronized (mPackages) { 12910 deletedPs = mSettings.mPackages.get(packageName); 12911 if (outInfo != null) { 12912 outInfo.removedPackage = packageName; 12913 outInfo.removedUsers = deletedPs != null 12914 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12915 : null; 12916 } 12917 } 12918 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12919 removeDataDirsLI(ps.volumeUuid, packageName); 12920 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12921 } 12922 // writer 12923 synchronized (mPackages) { 12924 if (deletedPs != null) { 12925 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12926 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12927 clearDefaultBrowserIfNeeded(packageName); 12928 if (outInfo != null) { 12929 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12930 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12931 } 12932 updatePermissionsLPw(deletedPs.name, null, 0); 12933 if (deletedPs.sharedUser != null) { 12934 // Remove permissions associated with package. Since runtime 12935 // permissions are per user we have to kill the removed package 12936 // or packages running under the shared user of the removed 12937 // package if revoking the permissions requested only by the removed 12938 // package is successful and this causes a change in gids. 12939 for (int userId : UserManagerService.getInstance().getUserIds()) { 12940 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12941 userId); 12942 if (userIdToKill == UserHandle.USER_ALL 12943 || userIdToKill >= UserHandle.USER_OWNER) { 12944 // If gids changed for this user, kill all affected packages. 12945 mHandler.post(new Runnable() { 12946 @Override 12947 public void run() { 12948 // This has to happen with no lock held. 12949 killApplication(deletedPs.name, deletedPs.appId, 12950 KILL_APP_REASON_GIDS_CHANGED); 12951 } 12952 }); 12953 break; 12954 } 12955 } 12956 } 12957 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12958 } 12959 // make sure to preserve per-user disabled state if this removal was just 12960 // a downgrade of a system app to the factory package 12961 if (allUserHandles != null && perUserInstalled != null) { 12962 if (DEBUG_REMOVE) { 12963 Slog.d(TAG, "Propagating install state across downgrade"); 12964 } 12965 for (int i = 0; i < allUserHandles.length; i++) { 12966 if (DEBUG_REMOVE) { 12967 Slog.d(TAG, " user " + allUserHandles[i] 12968 + " => " + perUserInstalled[i]); 12969 } 12970 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12971 } 12972 } 12973 } 12974 // can downgrade to reader 12975 if (writeSettings) { 12976 // Save settings now 12977 mSettings.writeLPr(); 12978 } 12979 } 12980 if (outInfo != null) { 12981 // A user ID was deleted here. Go through all users and remove it 12982 // from KeyStore. 12983 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12984 } 12985 } 12986 12987 static boolean locationIsPrivileged(File path) { 12988 try { 12989 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12990 .getCanonicalPath(); 12991 return path.getCanonicalPath().startsWith(privilegedAppDir); 12992 } catch (IOException e) { 12993 Slog.e(TAG, "Unable to access code path " + path); 12994 } 12995 return false; 12996 } 12997 12998 /* 12999 * Tries to delete system package. 13000 */ 13001 private boolean deleteSystemPackageLI(PackageSetting newPs, 13002 int[] allUserHandles, boolean[] perUserInstalled, 13003 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13004 final boolean applyUserRestrictions 13005 = (allUserHandles != null) && (perUserInstalled != null); 13006 PackageSetting disabledPs = null; 13007 // Confirm if the system package has been updated 13008 // An updated system app can be deleted. This will also have to restore 13009 // the system pkg from system partition 13010 // reader 13011 synchronized (mPackages) { 13012 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13013 } 13014 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13015 + " disabledPs=" + disabledPs); 13016 if (disabledPs == null) { 13017 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13018 return false; 13019 } else if (DEBUG_REMOVE) { 13020 Slog.d(TAG, "Deleting system pkg from data partition"); 13021 } 13022 if (DEBUG_REMOVE) { 13023 if (applyUserRestrictions) { 13024 Slog.d(TAG, "Remembering install states:"); 13025 for (int i = 0; i < allUserHandles.length; i++) { 13026 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13027 } 13028 } 13029 } 13030 // Delete the updated package 13031 outInfo.isRemovedPackageSystemUpdate = true; 13032 if (disabledPs.versionCode < newPs.versionCode) { 13033 // Delete data for downgrades 13034 flags &= ~PackageManager.DELETE_KEEP_DATA; 13035 } else { 13036 // Preserve data by setting flag 13037 flags |= PackageManager.DELETE_KEEP_DATA; 13038 } 13039 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13040 allUserHandles, perUserInstalled, outInfo, writeSettings); 13041 if (!ret) { 13042 return false; 13043 } 13044 // writer 13045 synchronized (mPackages) { 13046 // Reinstate the old system package 13047 mSettings.enableSystemPackageLPw(newPs.name); 13048 // Remove any native libraries from the upgraded package. 13049 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13050 } 13051 // Install the system package 13052 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13053 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13054 if (locationIsPrivileged(disabledPs.codePath)) { 13055 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13056 } 13057 13058 final PackageParser.Package newPkg; 13059 try { 13060 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13061 } catch (PackageManagerException e) { 13062 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13063 return false; 13064 } 13065 13066 // writer 13067 synchronized (mPackages) { 13068 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13069 13070 // Propagate the permissions state as we do not want to drop on the floor 13071 // runtime permissions. The update permissions method below will take 13072 // care of removing obsolete permissions and grant install permissions. 13073 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13074 updatePermissionsLPw(newPkg.packageName, newPkg, 13075 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13076 13077 if (applyUserRestrictions) { 13078 if (DEBUG_REMOVE) { 13079 Slog.d(TAG, "Propagating install state across reinstall"); 13080 } 13081 for (int i = 0; i < allUserHandles.length; i++) { 13082 if (DEBUG_REMOVE) { 13083 Slog.d(TAG, " user " + allUserHandles[i] 13084 + " => " + perUserInstalled[i]); 13085 } 13086 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13087 13088 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13089 } 13090 // Regardless of writeSettings we need to ensure that this restriction 13091 // state propagation is persisted 13092 mSettings.writeAllUsersPackageRestrictionsLPr(); 13093 } 13094 // can downgrade to reader here 13095 if (writeSettings) { 13096 mSettings.writeLPr(); 13097 } 13098 } 13099 return true; 13100 } 13101 13102 private boolean deleteInstalledPackageLI(PackageSetting ps, 13103 boolean deleteCodeAndResources, int flags, 13104 int[] allUserHandles, boolean[] perUserInstalled, 13105 PackageRemovedInfo outInfo, boolean writeSettings) { 13106 if (outInfo != null) { 13107 outInfo.uid = ps.appId; 13108 } 13109 13110 // Delete package data from internal structures and also remove data if flag is set 13111 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13112 13113 // Delete application code and resources 13114 if (deleteCodeAndResources && (outInfo != null)) { 13115 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13116 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13117 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13118 } 13119 return true; 13120 } 13121 13122 @Override 13123 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13124 int userId) { 13125 mContext.enforceCallingOrSelfPermission( 13126 android.Manifest.permission.DELETE_PACKAGES, null); 13127 synchronized (mPackages) { 13128 PackageSetting ps = mSettings.mPackages.get(packageName); 13129 if (ps == null) { 13130 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13131 return false; 13132 } 13133 if (!ps.getInstalled(userId)) { 13134 // Can't block uninstall for an app that is not installed or enabled. 13135 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13136 return false; 13137 } 13138 ps.setBlockUninstall(blockUninstall, userId); 13139 mSettings.writePackageRestrictionsLPr(userId); 13140 } 13141 return true; 13142 } 13143 13144 @Override 13145 public boolean getBlockUninstallForUser(String packageName, int userId) { 13146 synchronized (mPackages) { 13147 PackageSetting ps = mSettings.mPackages.get(packageName); 13148 if (ps == null) { 13149 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13150 return false; 13151 } 13152 return ps.getBlockUninstall(userId); 13153 } 13154 } 13155 13156 /* 13157 * This method handles package deletion in general 13158 */ 13159 private boolean deletePackageLI(String packageName, UserHandle user, 13160 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13161 int flags, PackageRemovedInfo outInfo, 13162 boolean writeSettings) { 13163 if (packageName == null) { 13164 Slog.w(TAG, "Attempt to delete null packageName."); 13165 return false; 13166 } 13167 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13168 PackageSetting ps; 13169 boolean dataOnly = false; 13170 int removeUser = -1; 13171 int appId = -1; 13172 synchronized (mPackages) { 13173 ps = mSettings.mPackages.get(packageName); 13174 if (ps == null) { 13175 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13176 return false; 13177 } 13178 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13179 && user.getIdentifier() != UserHandle.USER_ALL) { 13180 // The caller is asking that the package only be deleted for a single 13181 // user. To do this, we just mark its uninstalled state and delete 13182 // its data. If this is a system app, we only allow this to happen if 13183 // they have set the special DELETE_SYSTEM_APP which requests different 13184 // semantics than normal for uninstalling system apps. 13185 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13186 final int userId = user.getIdentifier(); 13187 ps.setUserState(userId, 13188 COMPONENT_ENABLED_STATE_DEFAULT, 13189 false, //installed 13190 true, //stopped 13191 true, //notLaunched 13192 false, //hidden 13193 null, null, null, 13194 false, // blockUninstall 13195 ps.readUserState(userId).domainVerificationStatus, 0); 13196 if (!isSystemApp(ps)) { 13197 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13198 // Other user still have this package installed, so all 13199 // we need to do is clear this user's data and save that 13200 // it is uninstalled. 13201 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13202 removeUser = user.getIdentifier(); 13203 appId = ps.appId; 13204 scheduleWritePackageRestrictionsLocked(removeUser); 13205 } else { 13206 // We need to set it back to 'installed' so the uninstall 13207 // broadcasts will be sent correctly. 13208 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13209 ps.setInstalled(true, user.getIdentifier()); 13210 } 13211 } else { 13212 // This is a system app, so we assume that the 13213 // other users still have this package installed, so all 13214 // we need to do is clear this user's data and save that 13215 // it is uninstalled. 13216 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13217 removeUser = user.getIdentifier(); 13218 appId = ps.appId; 13219 scheduleWritePackageRestrictionsLocked(removeUser); 13220 } 13221 } 13222 } 13223 13224 if (removeUser >= 0) { 13225 // From above, we determined that we are deleting this only 13226 // for a single user. Continue the work here. 13227 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13228 if (outInfo != null) { 13229 outInfo.removedPackage = packageName; 13230 outInfo.removedAppId = appId; 13231 outInfo.removedUsers = new int[] {removeUser}; 13232 } 13233 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13234 removeKeystoreDataIfNeeded(removeUser, appId); 13235 schedulePackageCleaning(packageName, removeUser, false); 13236 synchronized (mPackages) { 13237 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13238 scheduleWritePackageRestrictionsLocked(removeUser); 13239 } 13240 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13241 } 13242 return true; 13243 } 13244 13245 if (dataOnly) { 13246 // Delete application data first 13247 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13248 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13249 return true; 13250 } 13251 13252 boolean ret = false; 13253 if (isSystemApp(ps)) { 13254 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13255 // When an updated system application is deleted we delete the existing resources as well and 13256 // fall back to existing code in system partition 13257 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13258 flags, outInfo, writeSettings); 13259 } else { 13260 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13261 // Kill application pre-emptively especially for apps on sd. 13262 killApplication(packageName, ps.appId, "uninstall pkg"); 13263 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13264 allUserHandles, perUserInstalled, 13265 outInfo, writeSettings); 13266 } 13267 13268 return ret; 13269 } 13270 13271 private final class ClearStorageConnection implements ServiceConnection { 13272 IMediaContainerService mContainerService; 13273 13274 @Override 13275 public void onServiceConnected(ComponentName name, IBinder service) { 13276 synchronized (this) { 13277 mContainerService = IMediaContainerService.Stub.asInterface(service); 13278 notifyAll(); 13279 } 13280 } 13281 13282 @Override 13283 public void onServiceDisconnected(ComponentName name) { 13284 } 13285 } 13286 13287 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13288 final boolean mounted; 13289 if (Environment.isExternalStorageEmulated()) { 13290 mounted = true; 13291 } else { 13292 final String status = Environment.getExternalStorageState(); 13293 13294 mounted = status.equals(Environment.MEDIA_MOUNTED) 13295 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13296 } 13297 13298 if (!mounted) { 13299 return; 13300 } 13301 13302 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13303 int[] users; 13304 if (userId == UserHandle.USER_ALL) { 13305 users = sUserManager.getUserIds(); 13306 } else { 13307 users = new int[] { userId }; 13308 } 13309 final ClearStorageConnection conn = new ClearStorageConnection(); 13310 if (mContext.bindServiceAsUser( 13311 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13312 try { 13313 for (int curUser : users) { 13314 long timeout = SystemClock.uptimeMillis() + 5000; 13315 synchronized (conn) { 13316 long now = SystemClock.uptimeMillis(); 13317 while (conn.mContainerService == null && now < timeout) { 13318 try { 13319 conn.wait(timeout - now); 13320 } catch (InterruptedException e) { 13321 } 13322 } 13323 } 13324 if (conn.mContainerService == null) { 13325 return; 13326 } 13327 13328 final UserEnvironment userEnv = new UserEnvironment(curUser); 13329 clearDirectory(conn.mContainerService, 13330 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13331 if (allData) { 13332 clearDirectory(conn.mContainerService, 13333 userEnv.buildExternalStorageAppDataDirs(packageName)); 13334 clearDirectory(conn.mContainerService, 13335 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13336 } 13337 } 13338 } finally { 13339 mContext.unbindService(conn); 13340 } 13341 } 13342 } 13343 13344 @Override 13345 public void clearApplicationUserData(final String packageName, 13346 final IPackageDataObserver observer, final int userId) { 13347 mContext.enforceCallingOrSelfPermission( 13348 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13349 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13350 // Queue up an async operation since the package deletion may take a little while. 13351 mHandler.post(new Runnable() { 13352 public void run() { 13353 mHandler.removeCallbacks(this); 13354 final boolean succeeded; 13355 synchronized (mInstallLock) { 13356 succeeded = clearApplicationUserDataLI(packageName, userId); 13357 } 13358 clearExternalStorageDataSync(packageName, userId, true); 13359 if (succeeded) { 13360 // invoke DeviceStorageMonitor's update method to clear any notifications 13361 DeviceStorageMonitorInternal 13362 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13363 if (dsm != null) { 13364 dsm.checkMemory(); 13365 } 13366 } 13367 if(observer != null) { 13368 try { 13369 observer.onRemoveCompleted(packageName, succeeded); 13370 } catch (RemoteException e) { 13371 Log.i(TAG, "Observer no longer exists."); 13372 } 13373 } //end if observer 13374 } //end run 13375 }); 13376 } 13377 13378 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13379 if (packageName == null) { 13380 Slog.w(TAG, "Attempt to delete null packageName."); 13381 return false; 13382 } 13383 13384 // Try finding details about the requested package 13385 PackageParser.Package pkg; 13386 synchronized (mPackages) { 13387 pkg = mPackages.get(packageName); 13388 if (pkg == null) { 13389 final PackageSetting ps = mSettings.mPackages.get(packageName); 13390 if (ps != null) { 13391 pkg = ps.pkg; 13392 } 13393 } 13394 13395 if (pkg == null) { 13396 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13397 return false; 13398 } 13399 13400 PackageSetting ps = (PackageSetting) pkg.mExtras; 13401 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13402 } 13403 13404 // Always delete data directories for package, even if we found no other 13405 // record of app. This helps users recover from UID mismatches without 13406 // resorting to a full data wipe. 13407 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13408 if (retCode < 0) { 13409 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13410 return false; 13411 } 13412 13413 final int appId = pkg.applicationInfo.uid; 13414 removeKeystoreDataIfNeeded(userId, appId); 13415 13416 // Create a native library symlink only if we have native libraries 13417 // and if the native libraries are 32 bit libraries. We do not provide 13418 // this symlink for 64 bit libraries. 13419 if (pkg.applicationInfo.primaryCpuAbi != null && 13420 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13421 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13422 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13423 nativeLibPath, userId) < 0) { 13424 Slog.w(TAG, "Failed linking native library dir"); 13425 return false; 13426 } 13427 } 13428 13429 return true; 13430 } 13431 13432 /** 13433 * Reverts user permission state changes (permissions and flags) in 13434 * all packages for a given user. 13435 * 13436 * @param userId The device user for which to do a reset. 13437 */ 13438 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13439 final int packageCount = mPackages.size(); 13440 for (int i = 0; i < packageCount; i++) { 13441 PackageParser.Package pkg = mPackages.valueAt(i); 13442 PackageSetting ps = (PackageSetting) pkg.mExtras; 13443 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13444 } 13445 } 13446 13447 /** 13448 * Reverts user permission state changes (permissions and flags). 13449 * 13450 * @param ps The package for which to reset. 13451 * @param userId The device user for which to do a reset. 13452 */ 13453 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13454 final PackageSetting ps, final int userId) { 13455 if (ps.pkg == null) { 13456 return; 13457 } 13458 13459 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13460 | FLAG_PERMISSION_USER_FIXED 13461 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13462 13463 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13464 | FLAG_PERMISSION_POLICY_FIXED; 13465 13466 boolean writeInstallPermissions = false; 13467 boolean writeRuntimePermissions = false; 13468 13469 final int permissionCount = ps.pkg.requestedPermissions.size(); 13470 for (int i = 0; i < permissionCount; i++) { 13471 String permission = ps.pkg.requestedPermissions.get(i); 13472 13473 BasePermission bp = mSettings.mPermissions.get(permission); 13474 if (bp == null) { 13475 continue; 13476 } 13477 13478 // If shared user we just reset the state to which only this app contributed. 13479 if (ps.sharedUser != null) { 13480 boolean used = false; 13481 final int packageCount = ps.sharedUser.packages.size(); 13482 for (int j = 0; j < packageCount; j++) { 13483 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13484 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13485 && pkg.pkg.requestedPermissions.contains(permission)) { 13486 used = true; 13487 break; 13488 } 13489 } 13490 if (used) { 13491 continue; 13492 } 13493 } 13494 13495 PermissionsState permissionsState = ps.getPermissionsState(); 13496 13497 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13498 13499 // Always clear the user settable flags. 13500 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13501 bp.name) != null; 13502 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13503 if (hasInstallState) { 13504 writeInstallPermissions = true; 13505 } else { 13506 writeRuntimePermissions = true; 13507 } 13508 } 13509 13510 // Below is only runtime permission handling. 13511 if (!bp.isRuntime()) { 13512 continue; 13513 } 13514 13515 // Never clobber system or policy. 13516 if ((oldFlags & policyOrSystemFlags) != 0) { 13517 continue; 13518 } 13519 13520 // If this permission was granted by default, make sure it is. 13521 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13522 if (permissionsState.grantRuntimePermission(bp, userId) 13523 != PERMISSION_OPERATION_FAILURE) { 13524 writeRuntimePermissions = true; 13525 } 13526 } else { 13527 // Otherwise, reset the permission. 13528 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13529 switch (revokeResult) { 13530 case PERMISSION_OPERATION_SUCCESS: { 13531 writeRuntimePermissions = true; 13532 } break; 13533 13534 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13535 writeRuntimePermissions = true; 13536 final int appId = ps.appId; 13537 mHandler.post(new Runnable() { 13538 @Override 13539 public void run() { 13540 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13541 } 13542 }); 13543 } break; 13544 } 13545 } 13546 } 13547 13548 // Synchronously write as we are taking permissions away. 13549 if (writeRuntimePermissions) { 13550 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13551 } 13552 13553 // Synchronously write as we are taking permissions away. 13554 if (writeInstallPermissions) { 13555 mSettings.writeLPr(); 13556 } 13557 } 13558 13559 /** 13560 * Remove entries from the keystore daemon. Will only remove it if the 13561 * {@code appId} is valid. 13562 */ 13563 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13564 if (appId < 0) { 13565 return; 13566 } 13567 13568 final KeyStore keyStore = KeyStore.getInstance(); 13569 if (keyStore != null) { 13570 if (userId == UserHandle.USER_ALL) { 13571 for (final int individual : sUserManager.getUserIds()) { 13572 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13573 } 13574 } else { 13575 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13576 } 13577 } else { 13578 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13579 } 13580 } 13581 13582 @Override 13583 public void deleteApplicationCacheFiles(final String packageName, 13584 final IPackageDataObserver observer) { 13585 mContext.enforceCallingOrSelfPermission( 13586 android.Manifest.permission.DELETE_CACHE_FILES, null); 13587 // Queue up an async operation since the package deletion may take a little while. 13588 final int userId = UserHandle.getCallingUserId(); 13589 mHandler.post(new Runnable() { 13590 public void run() { 13591 mHandler.removeCallbacks(this); 13592 final boolean succeded; 13593 synchronized (mInstallLock) { 13594 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13595 } 13596 clearExternalStorageDataSync(packageName, userId, false); 13597 if (observer != null) { 13598 try { 13599 observer.onRemoveCompleted(packageName, succeded); 13600 } catch (RemoteException e) { 13601 Log.i(TAG, "Observer no longer exists."); 13602 } 13603 } //end if observer 13604 } //end run 13605 }); 13606 } 13607 13608 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13609 if (packageName == null) { 13610 Slog.w(TAG, "Attempt to delete null packageName."); 13611 return false; 13612 } 13613 PackageParser.Package p; 13614 synchronized (mPackages) { 13615 p = mPackages.get(packageName); 13616 } 13617 if (p == null) { 13618 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13619 return false; 13620 } 13621 final ApplicationInfo applicationInfo = p.applicationInfo; 13622 if (applicationInfo == null) { 13623 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13624 return false; 13625 } 13626 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13627 if (retCode < 0) { 13628 Slog.w(TAG, "Couldn't remove cache files for package: " 13629 + packageName + " u" + userId); 13630 return false; 13631 } 13632 return true; 13633 } 13634 13635 @Override 13636 public void getPackageSizeInfo(final String packageName, int userHandle, 13637 final IPackageStatsObserver observer) { 13638 mContext.enforceCallingOrSelfPermission( 13639 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13640 if (packageName == null) { 13641 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13642 } 13643 13644 PackageStats stats = new PackageStats(packageName, userHandle); 13645 13646 /* 13647 * Queue up an async operation since the package measurement may take a 13648 * little while. 13649 */ 13650 Message msg = mHandler.obtainMessage(INIT_COPY); 13651 msg.obj = new MeasureParams(stats, observer); 13652 mHandler.sendMessage(msg); 13653 } 13654 13655 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13656 PackageStats pStats) { 13657 if (packageName == null) { 13658 Slog.w(TAG, "Attempt to get size of null packageName."); 13659 return false; 13660 } 13661 PackageParser.Package p; 13662 boolean dataOnly = false; 13663 String libDirRoot = null; 13664 String asecPath = null; 13665 PackageSetting ps = null; 13666 synchronized (mPackages) { 13667 p = mPackages.get(packageName); 13668 ps = mSettings.mPackages.get(packageName); 13669 if(p == null) { 13670 dataOnly = true; 13671 if((ps == null) || (ps.pkg == null)) { 13672 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13673 return false; 13674 } 13675 p = ps.pkg; 13676 } 13677 if (ps != null) { 13678 libDirRoot = ps.legacyNativeLibraryPathString; 13679 } 13680 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13681 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13682 if (secureContainerId != null) { 13683 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13684 } 13685 } 13686 } 13687 String publicSrcDir = null; 13688 if(!dataOnly) { 13689 final ApplicationInfo applicationInfo = p.applicationInfo; 13690 if (applicationInfo == null) { 13691 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13692 return false; 13693 } 13694 if (p.isForwardLocked()) { 13695 publicSrcDir = applicationInfo.getBaseResourcePath(); 13696 } 13697 } 13698 // TODO: extend to measure size of split APKs 13699 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13700 // not just the first level. 13701 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13702 // just the primary. 13703 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13704 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13705 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13706 if (res < 0) { 13707 return false; 13708 } 13709 13710 // Fix-up for forward-locked applications in ASEC containers. 13711 if (!isExternal(p)) { 13712 pStats.codeSize += pStats.externalCodeSize; 13713 pStats.externalCodeSize = 0L; 13714 } 13715 13716 return true; 13717 } 13718 13719 13720 @Override 13721 public void addPackageToPreferred(String packageName) { 13722 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13723 } 13724 13725 @Override 13726 public void removePackageFromPreferred(String packageName) { 13727 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13728 } 13729 13730 @Override 13731 public List<PackageInfo> getPreferredPackages(int flags) { 13732 return new ArrayList<PackageInfo>(); 13733 } 13734 13735 private int getUidTargetSdkVersionLockedLPr(int uid) { 13736 Object obj = mSettings.getUserIdLPr(uid); 13737 if (obj instanceof SharedUserSetting) { 13738 final SharedUserSetting sus = (SharedUserSetting) obj; 13739 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13740 final Iterator<PackageSetting> it = sus.packages.iterator(); 13741 while (it.hasNext()) { 13742 final PackageSetting ps = it.next(); 13743 if (ps.pkg != null) { 13744 int v = ps.pkg.applicationInfo.targetSdkVersion; 13745 if (v < vers) vers = v; 13746 } 13747 } 13748 return vers; 13749 } else if (obj instanceof PackageSetting) { 13750 final PackageSetting ps = (PackageSetting) obj; 13751 if (ps.pkg != null) { 13752 return ps.pkg.applicationInfo.targetSdkVersion; 13753 } 13754 } 13755 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13756 } 13757 13758 @Override 13759 public void addPreferredActivity(IntentFilter filter, int match, 13760 ComponentName[] set, ComponentName activity, int userId) { 13761 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13762 "Adding preferred"); 13763 } 13764 13765 private void addPreferredActivityInternal(IntentFilter filter, int match, 13766 ComponentName[] set, ComponentName activity, boolean always, int userId, 13767 String opname) { 13768 // writer 13769 int callingUid = Binder.getCallingUid(); 13770 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13771 if (filter.countActions() == 0) { 13772 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13773 return; 13774 } 13775 synchronized (mPackages) { 13776 if (mContext.checkCallingOrSelfPermission( 13777 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13778 != PackageManager.PERMISSION_GRANTED) { 13779 if (getUidTargetSdkVersionLockedLPr(callingUid) 13780 < Build.VERSION_CODES.FROYO) { 13781 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13782 + callingUid); 13783 return; 13784 } 13785 mContext.enforceCallingOrSelfPermission( 13786 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13787 } 13788 13789 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13790 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13791 + userId + ":"); 13792 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13793 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13794 scheduleWritePackageRestrictionsLocked(userId); 13795 } 13796 } 13797 13798 @Override 13799 public void replacePreferredActivity(IntentFilter filter, int match, 13800 ComponentName[] set, ComponentName activity, int userId) { 13801 if (filter.countActions() != 1) { 13802 throw new IllegalArgumentException( 13803 "replacePreferredActivity expects filter to have only 1 action."); 13804 } 13805 if (filter.countDataAuthorities() != 0 13806 || filter.countDataPaths() != 0 13807 || filter.countDataSchemes() > 1 13808 || filter.countDataTypes() != 0) { 13809 throw new IllegalArgumentException( 13810 "replacePreferredActivity expects filter to have no data authorities, " + 13811 "paths, or types; and at most one scheme."); 13812 } 13813 13814 final int callingUid = Binder.getCallingUid(); 13815 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13816 synchronized (mPackages) { 13817 if (mContext.checkCallingOrSelfPermission( 13818 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13819 != PackageManager.PERMISSION_GRANTED) { 13820 if (getUidTargetSdkVersionLockedLPr(callingUid) 13821 < Build.VERSION_CODES.FROYO) { 13822 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13823 + Binder.getCallingUid()); 13824 return; 13825 } 13826 mContext.enforceCallingOrSelfPermission( 13827 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13828 } 13829 13830 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13831 if (pir != null) { 13832 // Get all of the existing entries that exactly match this filter. 13833 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13834 if (existing != null && existing.size() == 1) { 13835 PreferredActivity cur = existing.get(0); 13836 if (DEBUG_PREFERRED) { 13837 Slog.i(TAG, "Checking replace of preferred:"); 13838 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13839 if (!cur.mPref.mAlways) { 13840 Slog.i(TAG, " -- CUR; not mAlways!"); 13841 } else { 13842 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13843 Slog.i(TAG, " -- CUR: mSet=" 13844 + Arrays.toString(cur.mPref.mSetComponents)); 13845 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13846 Slog.i(TAG, " -- NEW: mMatch=" 13847 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13848 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13849 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13850 } 13851 } 13852 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13853 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13854 && cur.mPref.sameSet(set)) { 13855 // Setting the preferred activity to what it happens to be already 13856 if (DEBUG_PREFERRED) { 13857 Slog.i(TAG, "Replacing with same preferred activity " 13858 + cur.mPref.mShortComponent + " for user " 13859 + userId + ":"); 13860 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13861 } 13862 return; 13863 } 13864 } 13865 13866 if (existing != null) { 13867 if (DEBUG_PREFERRED) { 13868 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13869 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13870 } 13871 for (int i = 0; i < existing.size(); i++) { 13872 PreferredActivity pa = existing.get(i); 13873 if (DEBUG_PREFERRED) { 13874 Slog.i(TAG, "Removing existing preferred activity " 13875 + pa.mPref.mComponent + ":"); 13876 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13877 } 13878 pir.removeFilter(pa); 13879 } 13880 } 13881 } 13882 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13883 "Replacing preferred"); 13884 } 13885 } 13886 13887 @Override 13888 public void clearPackagePreferredActivities(String packageName) { 13889 final int uid = Binder.getCallingUid(); 13890 // writer 13891 synchronized (mPackages) { 13892 PackageParser.Package pkg = mPackages.get(packageName); 13893 if (pkg == null || pkg.applicationInfo.uid != uid) { 13894 if (mContext.checkCallingOrSelfPermission( 13895 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13896 != PackageManager.PERMISSION_GRANTED) { 13897 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13898 < Build.VERSION_CODES.FROYO) { 13899 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13900 + Binder.getCallingUid()); 13901 return; 13902 } 13903 mContext.enforceCallingOrSelfPermission( 13904 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13905 } 13906 } 13907 13908 int user = UserHandle.getCallingUserId(); 13909 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13910 scheduleWritePackageRestrictionsLocked(user); 13911 } 13912 } 13913 } 13914 13915 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13916 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13917 ArrayList<PreferredActivity> removed = null; 13918 boolean changed = false; 13919 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13920 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13921 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13922 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13923 continue; 13924 } 13925 Iterator<PreferredActivity> it = pir.filterIterator(); 13926 while (it.hasNext()) { 13927 PreferredActivity pa = it.next(); 13928 // Mark entry for removal only if it matches the package name 13929 // and the entry is of type "always". 13930 if (packageName == null || 13931 (pa.mPref.mComponent.getPackageName().equals(packageName) 13932 && pa.mPref.mAlways)) { 13933 if (removed == null) { 13934 removed = new ArrayList<PreferredActivity>(); 13935 } 13936 removed.add(pa); 13937 } 13938 } 13939 if (removed != null) { 13940 for (int j=0; j<removed.size(); j++) { 13941 PreferredActivity pa = removed.get(j); 13942 pir.removeFilter(pa); 13943 } 13944 changed = true; 13945 } 13946 } 13947 return changed; 13948 } 13949 13950 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13951 private void clearIntentFilterVerificationsLPw(int userId) { 13952 final int packageCount = mPackages.size(); 13953 for (int i = 0; i < packageCount; i++) { 13954 PackageParser.Package pkg = mPackages.valueAt(i); 13955 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13956 } 13957 } 13958 13959 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13960 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13961 if (userId == UserHandle.USER_ALL) { 13962 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13963 sUserManager.getUserIds())) { 13964 for (int oneUserId : sUserManager.getUserIds()) { 13965 scheduleWritePackageRestrictionsLocked(oneUserId); 13966 } 13967 } 13968 } else { 13969 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13970 scheduleWritePackageRestrictionsLocked(userId); 13971 } 13972 } 13973 } 13974 13975 void clearDefaultBrowserIfNeeded(String packageName) { 13976 for (int oneUserId : sUserManager.getUserIds()) { 13977 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13978 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13979 if (packageName.equals(defaultBrowserPackageName)) { 13980 setDefaultBrowserPackageName(null, oneUserId); 13981 } 13982 } 13983 } 13984 13985 @Override 13986 public void resetApplicationPreferences(int userId) { 13987 mContext.enforceCallingOrSelfPermission( 13988 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13989 // writer 13990 synchronized (mPackages) { 13991 final long identity = Binder.clearCallingIdentity(); 13992 try { 13993 clearPackagePreferredActivitiesLPw(null, userId); 13994 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13995 // TODO: We have to reset the default SMS and Phone. This requires 13996 // significant refactoring to keep all default apps in the package 13997 // manager (cleaner but more work) or have the services provide 13998 // callbacks to the package manager to request a default app reset. 13999 applyFactoryDefaultBrowserLPw(userId); 14000 clearIntentFilterVerificationsLPw(userId); 14001 primeDomainVerificationsLPw(userId); 14002 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14003 scheduleWritePackageRestrictionsLocked(userId); 14004 } finally { 14005 Binder.restoreCallingIdentity(identity); 14006 } 14007 } 14008 } 14009 14010 @Override 14011 public int getPreferredActivities(List<IntentFilter> outFilters, 14012 List<ComponentName> outActivities, String packageName) { 14013 14014 int num = 0; 14015 final int userId = UserHandle.getCallingUserId(); 14016 // reader 14017 synchronized (mPackages) { 14018 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14019 if (pir != null) { 14020 final Iterator<PreferredActivity> it = pir.filterIterator(); 14021 while (it.hasNext()) { 14022 final PreferredActivity pa = it.next(); 14023 if (packageName == null 14024 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14025 && pa.mPref.mAlways)) { 14026 if (outFilters != null) { 14027 outFilters.add(new IntentFilter(pa)); 14028 } 14029 if (outActivities != null) { 14030 outActivities.add(pa.mPref.mComponent); 14031 } 14032 } 14033 } 14034 } 14035 } 14036 14037 return num; 14038 } 14039 14040 @Override 14041 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14042 int userId) { 14043 int callingUid = Binder.getCallingUid(); 14044 if (callingUid != Process.SYSTEM_UID) { 14045 throw new SecurityException( 14046 "addPersistentPreferredActivity can only be run by the system"); 14047 } 14048 if (filter.countActions() == 0) { 14049 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14050 return; 14051 } 14052 synchronized (mPackages) { 14053 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14054 " :"); 14055 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14056 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14057 new PersistentPreferredActivity(filter, activity)); 14058 scheduleWritePackageRestrictionsLocked(userId); 14059 } 14060 } 14061 14062 @Override 14063 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14064 int callingUid = Binder.getCallingUid(); 14065 if (callingUid != Process.SYSTEM_UID) { 14066 throw new SecurityException( 14067 "clearPackagePersistentPreferredActivities can only be run by the system"); 14068 } 14069 ArrayList<PersistentPreferredActivity> removed = null; 14070 boolean changed = false; 14071 synchronized (mPackages) { 14072 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14073 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14074 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14075 .valueAt(i); 14076 if (userId != thisUserId) { 14077 continue; 14078 } 14079 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14080 while (it.hasNext()) { 14081 PersistentPreferredActivity ppa = it.next(); 14082 // Mark entry for removal only if it matches the package name. 14083 if (ppa.mComponent.getPackageName().equals(packageName)) { 14084 if (removed == null) { 14085 removed = new ArrayList<PersistentPreferredActivity>(); 14086 } 14087 removed.add(ppa); 14088 } 14089 } 14090 if (removed != null) { 14091 for (int j=0; j<removed.size(); j++) { 14092 PersistentPreferredActivity ppa = removed.get(j); 14093 ppir.removeFilter(ppa); 14094 } 14095 changed = true; 14096 } 14097 } 14098 14099 if (changed) { 14100 scheduleWritePackageRestrictionsLocked(userId); 14101 } 14102 } 14103 } 14104 14105 /** 14106 * Common machinery for picking apart a restored XML blob and passing 14107 * it to a caller-supplied functor to be applied to the running system. 14108 */ 14109 private void restoreFromXml(XmlPullParser parser, int userId, 14110 String expectedStartTag, BlobXmlRestorer functor) 14111 throws IOException, XmlPullParserException { 14112 int type; 14113 while ((type = parser.next()) != XmlPullParser.START_TAG 14114 && type != XmlPullParser.END_DOCUMENT) { 14115 } 14116 if (type != XmlPullParser.START_TAG) { 14117 // oops didn't find a start tag?! 14118 if (DEBUG_BACKUP) { 14119 Slog.e(TAG, "Didn't find start tag during restore"); 14120 } 14121 return; 14122 } 14123 14124 // this is supposed to be TAG_PREFERRED_BACKUP 14125 if (!expectedStartTag.equals(parser.getName())) { 14126 if (DEBUG_BACKUP) { 14127 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14128 } 14129 return; 14130 } 14131 14132 // skip interfering stuff, then we're aligned with the backing implementation 14133 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14134 functor.apply(parser, userId); 14135 } 14136 14137 private interface BlobXmlRestorer { 14138 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14139 } 14140 14141 /** 14142 * Non-Binder method, support for the backup/restore mechanism: write the 14143 * full set of preferred activities in its canonical XML format. Returns the 14144 * XML output as a byte array, or null if there is none. 14145 */ 14146 @Override 14147 public byte[] getPreferredActivityBackup(int userId) { 14148 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14149 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14150 } 14151 14152 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14153 try { 14154 final XmlSerializer serializer = new FastXmlSerializer(); 14155 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14156 serializer.startDocument(null, true); 14157 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14158 14159 synchronized (mPackages) { 14160 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14161 } 14162 14163 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14164 serializer.endDocument(); 14165 serializer.flush(); 14166 } catch (Exception e) { 14167 if (DEBUG_BACKUP) { 14168 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14169 } 14170 return null; 14171 } 14172 14173 return dataStream.toByteArray(); 14174 } 14175 14176 @Override 14177 public void restorePreferredActivities(byte[] backup, int userId) { 14178 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14179 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14180 } 14181 14182 try { 14183 final XmlPullParser parser = Xml.newPullParser(); 14184 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14185 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14186 new BlobXmlRestorer() { 14187 @Override 14188 public void apply(XmlPullParser parser, int userId) 14189 throws XmlPullParserException, IOException { 14190 synchronized (mPackages) { 14191 mSettings.readPreferredActivitiesLPw(parser, userId); 14192 } 14193 } 14194 } ); 14195 } catch (Exception e) { 14196 if (DEBUG_BACKUP) { 14197 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14198 } 14199 } 14200 } 14201 14202 /** 14203 * Non-Binder method, support for the backup/restore mechanism: write the 14204 * default browser (etc) settings in its canonical XML format. Returns the default 14205 * browser XML representation as a byte array, or null if there is none. 14206 */ 14207 @Override 14208 public byte[] getDefaultAppsBackup(int userId) { 14209 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14210 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14211 } 14212 14213 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14214 try { 14215 final XmlSerializer serializer = new FastXmlSerializer(); 14216 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14217 serializer.startDocument(null, true); 14218 serializer.startTag(null, TAG_DEFAULT_APPS); 14219 14220 synchronized (mPackages) { 14221 mSettings.writeDefaultAppsLPr(serializer, userId); 14222 } 14223 14224 serializer.endTag(null, TAG_DEFAULT_APPS); 14225 serializer.endDocument(); 14226 serializer.flush(); 14227 } catch (Exception e) { 14228 if (DEBUG_BACKUP) { 14229 Slog.e(TAG, "Unable to write default apps for backup", e); 14230 } 14231 return null; 14232 } 14233 14234 return dataStream.toByteArray(); 14235 } 14236 14237 @Override 14238 public void restoreDefaultApps(byte[] backup, int userId) { 14239 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14240 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14241 } 14242 14243 try { 14244 final XmlPullParser parser = Xml.newPullParser(); 14245 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14246 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14247 new BlobXmlRestorer() { 14248 @Override 14249 public void apply(XmlPullParser parser, int userId) 14250 throws XmlPullParserException, IOException { 14251 synchronized (mPackages) { 14252 mSettings.readDefaultAppsLPw(parser, userId); 14253 } 14254 } 14255 } ); 14256 } catch (Exception e) { 14257 if (DEBUG_BACKUP) { 14258 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14259 } 14260 } 14261 } 14262 14263 @Override 14264 public byte[] getIntentFilterVerificationBackup(int userId) { 14265 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14266 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14267 } 14268 14269 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14270 try { 14271 final XmlSerializer serializer = new FastXmlSerializer(); 14272 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14273 serializer.startDocument(null, true); 14274 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14275 14276 synchronized (mPackages) { 14277 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14278 } 14279 14280 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14281 serializer.endDocument(); 14282 serializer.flush(); 14283 } catch (Exception e) { 14284 if (DEBUG_BACKUP) { 14285 Slog.e(TAG, "Unable to write default apps for backup", e); 14286 } 14287 return null; 14288 } 14289 14290 return dataStream.toByteArray(); 14291 } 14292 14293 @Override 14294 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14295 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14296 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14297 } 14298 14299 try { 14300 final XmlPullParser parser = Xml.newPullParser(); 14301 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14302 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14303 new BlobXmlRestorer() { 14304 @Override 14305 public void apply(XmlPullParser parser, int userId) 14306 throws XmlPullParserException, IOException { 14307 synchronized (mPackages) { 14308 mSettings.readAllDomainVerificationsLPr(parser, userId); 14309 mSettings.writeLPr(); 14310 } 14311 } 14312 } ); 14313 } catch (Exception e) { 14314 if (DEBUG_BACKUP) { 14315 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14316 } 14317 } 14318 } 14319 14320 @Override 14321 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14322 int sourceUserId, int targetUserId, int flags) { 14323 mContext.enforceCallingOrSelfPermission( 14324 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14325 int callingUid = Binder.getCallingUid(); 14326 enforceOwnerRights(ownerPackage, callingUid); 14327 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14328 if (intentFilter.countActions() == 0) { 14329 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14330 return; 14331 } 14332 synchronized (mPackages) { 14333 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14334 ownerPackage, targetUserId, flags); 14335 CrossProfileIntentResolver resolver = 14336 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14337 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14338 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14339 if (existing != null) { 14340 int size = existing.size(); 14341 for (int i = 0; i < size; i++) { 14342 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14343 return; 14344 } 14345 } 14346 } 14347 resolver.addFilter(newFilter); 14348 scheduleWritePackageRestrictionsLocked(sourceUserId); 14349 } 14350 } 14351 14352 @Override 14353 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14354 mContext.enforceCallingOrSelfPermission( 14355 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14356 int callingUid = Binder.getCallingUid(); 14357 enforceOwnerRights(ownerPackage, callingUid); 14358 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14359 synchronized (mPackages) { 14360 CrossProfileIntentResolver resolver = 14361 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14362 ArraySet<CrossProfileIntentFilter> set = 14363 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14364 for (CrossProfileIntentFilter filter : set) { 14365 if (filter.getOwnerPackage().equals(ownerPackage)) { 14366 resolver.removeFilter(filter); 14367 } 14368 } 14369 scheduleWritePackageRestrictionsLocked(sourceUserId); 14370 } 14371 } 14372 14373 // Enforcing that callingUid is owning pkg on userId 14374 private void enforceOwnerRights(String pkg, int callingUid) { 14375 // The system owns everything. 14376 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14377 return; 14378 } 14379 int callingUserId = UserHandle.getUserId(callingUid); 14380 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14381 if (pi == null) { 14382 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14383 + callingUserId); 14384 } 14385 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14386 throw new SecurityException("Calling uid " + callingUid 14387 + " does not own package " + pkg); 14388 } 14389 } 14390 14391 @Override 14392 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14393 Intent intent = new Intent(Intent.ACTION_MAIN); 14394 intent.addCategory(Intent.CATEGORY_HOME); 14395 14396 final int callingUserId = UserHandle.getCallingUserId(); 14397 List<ResolveInfo> list = queryIntentActivities(intent, null, 14398 PackageManager.GET_META_DATA, callingUserId); 14399 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14400 true, false, false, callingUserId); 14401 14402 allHomeCandidates.clear(); 14403 if (list != null) { 14404 for (ResolveInfo ri : list) { 14405 allHomeCandidates.add(ri); 14406 } 14407 } 14408 return (preferred == null || preferred.activityInfo == null) 14409 ? null 14410 : new ComponentName(preferred.activityInfo.packageName, 14411 preferred.activityInfo.name); 14412 } 14413 14414 @Override 14415 public void setApplicationEnabledSetting(String appPackageName, 14416 int newState, int flags, int userId, String callingPackage) { 14417 if (!sUserManager.exists(userId)) return; 14418 if (callingPackage == null) { 14419 callingPackage = Integer.toString(Binder.getCallingUid()); 14420 } 14421 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14422 } 14423 14424 @Override 14425 public void setComponentEnabledSetting(ComponentName componentName, 14426 int newState, int flags, int userId) { 14427 if (!sUserManager.exists(userId)) return; 14428 setEnabledSetting(componentName.getPackageName(), 14429 componentName.getClassName(), newState, flags, userId, null); 14430 } 14431 14432 private void setEnabledSetting(final String packageName, String className, int newState, 14433 final int flags, int userId, String callingPackage) { 14434 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14435 || newState == COMPONENT_ENABLED_STATE_ENABLED 14436 || newState == COMPONENT_ENABLED_STATE_DISABLED 14437 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14438 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14439 throw new IllegalArgumentException("Invalid new component state: " 14440 + newState); 14441 } 14442 PackageSetting pkgSetting; 14443 final int uid = Binder.getCallingUid(); 14444 final int permission = mContext.checkCallingOrSelfPermission( 14445 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14446 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14447 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14448 boolean sendNow = false; 14449 boolean isApp = (className == null); 14450 String componentName = isApp ? packageName : className; 14451 int packageUid = -1; 14452 ArrayList<String> components; 14453 14454 // writer 14455 synchronized (mPackages) { 14456 pkgSetting = mSettings.mPackages.get(packageName); 14457 if (pkgSetting == null) { 14458 if (className == null) { 14459 throw new IllegalArgumentException( 14460 "Unknown package: " + packageName); 14461 } 14462 throw new IllegalArgumentException( 14463 "Unknown component: " + packageName 14464 + "/" + className); 14465 } 14466 // Allow root and verify that userId is not being specified by a different user 14467 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14468 throw new SecurityException( 14469 "Permission Denial: attempt to change component state from pid=" 14470 + Binder.getCallingPid() 14471 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14472 } 14473 if (className == null) { 14474 // We're dealing with an application/package level state change 14475 if (pkgSetting.getEnabled(userId) == newState) { 14476 // Nothing to do 14477 return; 14478 } 14479 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14480 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14481 // Don't care about who enables an app. 14482 callingPackage = null; 14483 } 14484 pkgSetting.setEnabled(newState, userId, callingPackage); 14485 // pkgSetting.pkg.mSetEnabled = newState; 14486 } else { 14487 // We're dealing with a component level state change 14488 // First, verify that this is a valid class name. 14489 PackageParser.Package pkg = pkgSetting.pkg; 14490 if (pkg == null || !pkg.hasComponentClassName(className)) { 14491 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14492 throw new IllegalArgumentException("Component class " + className 14493 + " does not exist in " + packageName); 14494 } else { 14495 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14496 + className + " does not exist in " + packageName); 14497 } 14498 } 14499 switch (newState) { 14500 case COMPONENT_ENABLED_STATE_ENABLED: 14501 if (!pkgSetting.enableComponentLPw(className, userId)) { 14502 return; 14503 } 14504 break; 14505 case COMPONENT_ENABLED_STATE_DISABLED: 14506 if (!pkgSetting.disableComponentLPw(className, userId)) { 14507 return; 14508 } 14509 break; 14510 case COMPONENT_ENABLED_STATE_DEFAULT: 14511 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14512 return; 14513 } 14514 break; 14515 default: 14516 Slog.e(TAG, "Invalid new component state: " + newState); 14517 return; 14518 } 14519 } 14520 scheduleWritePackageRestrictionsLocked(userId); 14521 components = mPendingBroadcasts.get(userId, packageName); 14522 final boolean newPackage = components == null; 14523 if (newPackage) { 14524 components = new ArrayList<String>(); 14525 } 14526 if (!components.contains(componentName)) { 14527 components.add(componentName); 14528 } 14529 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14530 sendNow = true; 14531 // Purge entry from pending broadcast list if another one exists already 14532 // since we are sending one right away. 14533 mPendingBroadcasts.remove(userId, packageName); 14534 } else { 14535 if (newPackage) { 14536 mPendingBroadcasts.put(userId, packageName, components); 14537 } 14538 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14539 // Schedule a message 14540 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14541 } 14542 } 14543 } 14544 14545 long callingId = Binder.clearCallingIdentity(); 14546 try { 14547 if (sendNow) { 14548 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14549 sendPackageChangedBroadcast(packageName, 14550 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14551 } 14552 } finally { 14553 Binder.restoreCallingIdentity(callingId); 14554 } 14555 } 14556 14557 private void sendPackageChangedBroadcast(String packageName, 14558 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14559 if (DEBUG_INSTALL) 14560 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14561 + componentNames); 14562 Bundle extras = new Bundle(4); 14563 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14564 String nameList[] = new String[componentNames.size()]; 14565 componentNames.toArray(nameList); 14566 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14567 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14568 extras.putInt(Intent.EXTRA_UID, packageUid); 14569 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14570 new int[] {UserHandle.getUserId(packageUid)}); 14571 } 14572 14573 @Override 14574 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14575 if (!sUserManager.exists(userId)) return; 14576 final int uid = Binder.getCallingUid(); 14577 final int permission = mContext.checkCallingOrSelfPermission( 14578 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14579 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14580 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14581 // writer 14582 synchronized (mPackages) { 14583 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14584 allowedByPermission, uid, userId)) { 14585 scheduleWritePackageRestrictionsLocked(userId); 14586 } 14587 } 14588 } 14589 14590 @Override 14591 public String getInstallerPackageName(String packageName) { 14592 // reader 14593 synchronized (mPackages) { 14594 return mSettings.getInstallerPackageNameLPr(packageName); 14595 } 14596 } 14597 14598 @Override 14599 public int getApplicationEnabledSetting(String packageName, int userId) { 14600 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14601 int uid = Binder.getCallingUid(); 14602 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14603 // reader 14604 synchronized (mPackages) { 14605 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14606 } 14607 } 14608 14609 @Override 14610 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14611 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14612 int uid = Binder.getCallingUid(); 14613 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14614 // reader 14615 synchronized (mPackages) { 14616 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14617 } 14618 } 14619 14620 @Override 14621 public void enterSafeMode() { 14622 enforceSystemOrRoot("Only the system can request entering safe mode"); 14623 14624 if (!mSystemReady) { 14625 mSafeMode = true; 14626 } 14627 } 14628 14629 @Override 14630 public void systemReady() { 14631 mSystemReady = true; 14632 14633 // Read the compatibilty setting when the system is ready. 14634 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14635 mContext.getContentResolver(), 14636 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14637 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14638 if (DEBUG_SETTINGS) { 14639 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14640 } 14641 14642 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14643 14644 synchronized (mPackages) { 14645 // Verify that all of the preferred activity components actually 14646 // exist. It is possible for applications to be updated and at 14647 // that point remove a previously declared activity component that 14648 // had been set as a preferred activity. We try to clean this up 14649 // the next time we encounter that preferred activity, but it is 14650 // possible for the user flow to never be able to return to that 14651 // situation so here we do a sanity check to make sure we haven't 14652 // left any junk around. 14653 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14654 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14655 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14656 removed.clear(); 14657 for (PreferredActivity pa : pir.filterSet()) { 14658 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14659 removed.add(pa); 14660 } 14661 } 14662 if (removed.size() > 0) { 14663 for (int r=0; r<removed.size(); r++) { 14664 PreferredActivity pa = removed.get(r); 14665 Slog.w(TAG, "Removing dangling preferred activity: " 14666 + pa.mPref.mComponent); 14667 pir.removeFilter(pa); 14668 } 14669 mSettings.writePackageRestrictionsLPr( 14670 mSettings.mPreferredActivities.keyAt(i)); 14671 } 14672 } 14673 14674 for (int userId : UserManagerService.getInstance().getUserIds()) { 14675 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14676 grantPermissionsUserIds = ArrayUtils.appendInt( 14677 grantPermissionsUserIds, userId); 14678 } 14679 } 14680 } 14681 sUserManager.systemReady(); 14682 14683 // If we upgraded grant all default permissions before kicking off. 14684 for (int userId : grantPermissionsUserIds) { 14685 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14686 } 14687 14688 // Kick off any messages waiting for system ready 14689 if (mPostSystemReadyMessages != null) { 14690 for (Message msg : mPostSystemReadyMessages) { 14691 msg.sendToTarget(); 14692 } 14693 mPostSystemReadyMessages = null; 14694 } 14695 14696 // Watch for external volumes that come and go over time 14697 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14698 storage.registerListener(mStorageListener); 14699 14700 mInstallerService.systemReady(); 14701 mPackageDexOptimizer.systemReady(); 14702 14703 MountServiceInternal mountServiceInternal = LocalServices.getService( 14704 MountServiceInternal.class); 14705 mountServiceInternal.addExternalStoragePolicy( 14706 new MountServiceInternal.ExternalStorageMountPolicy() { 14707 @Override 14708 public int getMountMode(int uid, String packageName) { 14709 if (Process.isIsolated(uid)) { 14710 return Zygote.MOUNT_EXTERNAL_NONE; 14711 } 14712 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14713 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14714 } 14715 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14716 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14717 } 14718 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14719 return Zygote.MOUNT_EXTERNAL_READ; 14720 } 14721 return Zygote.MOUNT_EXTERNAL_WRITE; 14722 } 14723 14724 @Override 14725 public boolean hasExternalStorage(int uid, String packageName) { 14726 return true; 14727 } 14728 }); 14729 } 14730 14731 @Override 14732 public boolean isSafeMode() { 14733 return mSafeMode; 14734 } 14735 14736 @Override 14737 public boolean hasSystemUidErrors() { 14738 return mHasSystemUidErrors; 14739 } 14740 14741 static String arrayToString(int[] array) { 14742 StringBuffer buf = new StringBuffer(128); 14743 buf.append('['); 14744 if (array != null) { 14745 for (int i=0; i<array.length; i++) { 14746 if (i > 0) buf.append(", "); 14747 buf.append(array[i]); 14748 } 14749 } 14750 buf.append(']'); 14751 return buf.toString(); 14752 } 14753 14754 static class DumpState { 14755 public static final int DUMP_LIBS = 1 << 0; 14756 public static final int DUMP_FEATURES = 1 << 1; 14757 public static final int DUMP_RESOLVERS = 1 << 2; 14758 public static final int DUMP_PERMISSIONS = 1 << 3; 14759 public static final int DUMP_PACKAGES = 1 << 4; 14760 public static final int DUMP_SHARED_USERS = 1 << 5; 14761 public static final int DUMP_MESSAGES = 1 << 6; 14762 public static final int DUMP_PROVIDERS = 1 << 7; 14763 public static final int DUMP_VERIFIERS = 1 << 8; 14764 public static final int DUMP_PREFERRED = 1 << 9; 14765 public static final int DUMP_PREFERRED_XML = 1 << 10; 14766 public static final int DUMP_KEYSETS = 1 << 11; 14767 public static final int DUMP_VERSION = 1 << 12; 14768 public static final int DUMP_INSTALLS = 1 << 13; 14769 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14770 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14771 14772 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14773 14774 private int mTypes; 14775 14776 private int mOptions; 14777 14778 private boolean mTitlePrinted; 14779 14780 private SharedUserSetting mSharedUser; 14781 14782 public boolean isDumping(int type) { 14783 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14784 return true; 14785 } 14786 14787 return (mTypes & type) != 0; 14788 } 14789 14790 public void setDump(int type) { 14791 mTypes |= type; 14792 } 14793 14794 public boolean isOptionEnabled(int option) { 14795 return (mOptions & option) != 0; 14796 } 14797 14798 public void setOptionEnabled(int option) { 14799 mOptions |= option; 14800 } 14801 14802 public boolean onTitlePrinted() { 14803 final boolean printed = mTitlePrinted; 14804 mTitlePrinted = true; 14805 return printed; 14806 } 14807 14808 public boolean getTitlePrinted() { 14809 return mTitlePrinted; 14810 } 14811 14812 public void setTitlePrinted(boolean enabled) { 14813 mTitlePrinted = enabled; 14814 } 14815 14816 public SharedUserSetting getSharedUser() { 14817 return mSharedUser; 14818 } 14819 14820 public void setSharedUser(SharedUserSetting user) { 14821 mSharedUser = user; 14822 } 14823 } 14824 14825 @Override 14826 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14827 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14828 != PackageManager.PERMISSION_GRANTED) { 14829 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14830 + Binder.getCallingPid() 14831 + ", uid=" + Binder.getCallingUid() 14832 + " without permission " 14833 + android.Manifest.permission.DUMP); 14834 return; 14835 } 14836 14837 DumpState dumpState = new DumpState(); 14838 boolean fullPreferred = false; 14839 boolean checkin = false; 14840 14841 String packageName = null; 14842 ArraySet<String> permissionNames = null; 14843 14844 int opti = 0; 14845 while (opti < args.length) { 14846 String opt = args[opti]; 14847 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14848 break; 14849 } 14850 opti++; 14851 14852 if ("-a".equals(opt)) { 14853 // Right now we only know how to print all. 14854 } else if ("-h".equals(opt)) { 14855 pw.println("Package manager dump options:"); 14856 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14857 pw.println(" --checkin: dump for a checkin"); 14858 pw.println(" -f: print details of intent filters"); 14859 pw.println(" -h: print this help"); 14860 pw.println(" cmd may be one of:"); 14861 pw.println(" l[ibraries]: list known shared libraries"); 14862 pw.println(" f[ibraries]: list device features"); 14863 pw.println(" k[eysets]: print known keysets"); 14864 pw.println(" r[esolvers]: dump intent resolvers"); 14865 pw.println(" perm[issions]: dump permissions"); 14866 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14867 pw.println(" pref[erred]: print preferred package settings"); 14868 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14869 pw.println(" prov[iders]: dump content providers"); 14870 pw.println(" p[ackages]: dump installed packages"); 14871 pw.println(" s[hared-users]: dump shared user IDs"); 14872 pw.println(" m[essages]: print collected runtime messages"); 14873 pw.println(" v[erifiers]: print package verifier info"); 14874 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14875 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14876 pw.println(" version: print database version info"); 14877 pw.println(" write: write current settings now"); 14878 pw.println(" installs: details about install sessions"); 14879 pw.println(" <package.name>: info about given package"); 14880 return; 14881 } else if ("--checkin".equals(opt)) { 14882 checkin = true; 14883 } else if ("-f".equals(opt)) { 14884 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14885 } else { 14886 pw.println("Unknown argument: " + opt + "; use -h for help"); 14887 } 14888 } 14889 14890 // Is the caller requesting to dump a particular piece of data? 14891 if (opti < args.length) { 14892 String cmd = args[opti]; 14893 opti++; 14894 // Is this a package name? 14895 if ("android".equals(cmd) || cmd.contains(".")) { 14896 packageName = cmd; 14897 // When dumping a single package, we always dump all of its 14898 // filter information since the amount of data will be reasonable. 14899 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14900 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14901 dumpState.setDump(DumpState.DUMP_LIBS); 14902 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14903 dumpState.setDump(DumpState.DUMP_FEATURES); 14904 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14905 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14906 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14907 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14908 } else if ("permission".equals(cmd)) { 14909 if (opti >= args.length) { 14910 pw.println("Error: permission requires permission name"); 14911 return; 14912 } 14913 permissionNames = new ArraySet<>(); 14914 while (opti < args.length) { 14915 permissionNames.add(args[opti]); 14916 opti++; 14917 } 14918 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14919 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14920 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14921 dumpState.setDump(DumpState.DUMP_PREFERRED); 14922 } else if ("preferred-xml".equals(cmd)) { 14923 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14924 if (opti < args.length && "--full".equals(args[opti])) { 14925 fullPreferred = true; 14926 opti++; 14927 } 14928 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14929 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14930 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14931 dumpState.setDump(DumpState.DUMP_PACKAGES); 14932 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14933 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14934 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14935 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14936 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14937 dumpState.setDump(DumpState.DUMP_MESSAGES); 14938 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14939 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14940 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14941 || "intent-filter-verifiers".equals(cmd)) { 14942 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14943 } else if ("version".equals(cmd)) { 14944 dumpState.setDump(DumpState.DUMP_VERSION); 14945 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14946 dumpState.setDump(DumpState.DUMP_KEYSETS); 14947 } else if ("installs".equals(cmd)) { 14948 dumpState.setDump(DumpState.DUMP_INSTALLS); 14949 } else if ("write".equals(cmd)) { 14950 synchronized (mPackages) { 14951 mSettings.writeLPr(); 14952 pw.println("Settings written."); 14953 return; 14954 } 14955 } 14956 } 14957 14958 if (checkin) { 14959 pw.println("vers,1"); 14960 } 14961 14962 // reader 14963 synchronized (mPackages) { 14964 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14965 if (!checkin) { 14966 if (dumpState.onTitlePrinted()) 14967 pw.println(); 14968 pw.println("Database versions:"); 14969 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14970 } 14971 } 14972 14973 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14974 if (!checkin) { 14975 if (dumpState.onTitlePrinted()) 14976 pw.println(); 14977 pw.println("Verifiers:"); 14978 pw.print(" Required: "); 14979 pw.print(mRequiredVerifierPackage); 14980 pw.print(" (uid="); 14981 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14982 pw.println(")"); 14983 } else if (mRequiredVerifierPackage != null) { 14984 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14985 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14986 } 14987 } 14988 14989 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14990 packageName == null) { 14991 if (mIntentFilterVerifierComponent != null) { 14992 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14993 if (!checkin) { 14994 if (dumpState.onTitlePrinted()) 14995 pw.println(); 14996 pw.println("Intent Filter Verifier:"); 14997 pw.print(" Using: "); 14998 pw.print(verifierPackageName); 14999 pw.print(" (uid="); 15000 pw.print(getPackageUid(verifierPackageName, 0)); 15001 pw.println(")"); 15002 } else if (verifierPackageName != null) { 15003 pw.print("ifv,"); pw.print(verifierPackageName); 15004 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15005 } 15006 } else { 15007 pw.println(); 15008 pw.println("No Intent Filter Verifier available!"); 15009 } 15010 } 15011 15012 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15013 boolean printedHeader = false; 15014 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15015 while (it.hasNext()) { 15016 String name = it.next(); 15017 SharedLibraryEntry ent = mSharedLibraries.get(name); 15018 if (!checkin) { 15019 if (!printedHeader) { 15020 if (dumpState.onTitlePrinted()) 15021 pw.println(); 15022 pw.println("Libraries:"); 15023 printedHeader = true; 15024 } 15025 pw.print(" "); 15026 } else { 15027 pw.print("lib,"); 15028 } 15029 pw.print(name); 15030 if (!checkin) { 15031 pw.print(" -> "); 15032 } 15033 if (ent.path != null) { 15034 if (!checkin) { 15035 pw.print("(jar) "); 15036 pw.print(ent.path); 15037 } else { 15038 pw.print(",jar,"); 15039 pw.print(ent.path); 15040 } 15041 } else { 15042 if (!checkin) { 15043 pw.print("(apk) "); 15044 pw.print(ent.apk); 15045 } else { 15046 pw.print(",apk,"); 15047 pw.print(ent.apk); 15048 } 15049 } 15050 pw.println(); 15051 } 15052 } 15053 15054 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15055 if (dumpState.onTitlePrinted()) 15056 pw.println(); 15057 if (!checkin) { 15058 pw.println("Features:"); 15059 } 15060 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15061 while (it.hasNext()) { 15062 String name = it.next(); 15063 if (!checkin) { 15064 pw.print(" "); 15065 } else { 15066 pw.print("feat,"); 15067 } 15068 pw.println(name); 15069 } 15070 } 15071 15072 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15073 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15074 : "Activity Resolver Table:", " ", packageName, 15075 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15076 dumpState.setTitlePrinted(true); 15077 } 15078 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15079 : "Receiver Resolver Table:", " ", packageName, 15080 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15081 dumpState.setTitlePrinted(true); 15082 } 15083 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15084 : "Service Resolver Table:", " ", packageName, 15085 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15086 dumpState.setTitlePrinted(true); 15087 } 15088 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15089 : "Provider Resolver Table:", " ", packageName, 15090 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15091 dumpState.setTitlePrinted(true); 15092 } 15093 } 15094 15095 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15096 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15097 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15098 int user = mSettings.mPreferredActivities.keyAt(i); 15099 if (pir.dump(pw, 15100 dumpState.getTitlePrinted() 15101 ? "\nPreferred Activities User " + user + ":" 15102 : "Preferred Activities User " + user + ":", " ", 15103 packageName, true, false)) { 15104 dumpState.setTitlePrinted(true); 15105 } 15106 } 15107 } 15108 15109 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15110 pw.flush(); 15111 FileOutputStream fout = new FileOutputStream(fd); 15112 BufferedOutputStream str = new BufferedOutputStream(fout); 15113 XmlSerializer serializer = new FastXmlSerializer(); 15114 try { 15115 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15116 serializer.startDocument(null, true); 15117 serializer.setFeature( 15118 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15119 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15120 serializer.endDocument(); 15121 serializer.flush(); 15122 } catch (IllegalArgumentException e) { 15123 pw.println("Failed writing: " + e); 15124 } catch (IllegalStateException e) { 15125 pw.println("Failed writing: " + e); 15126 } catch (IOException e) { 15127 pw.println("Failed writing: " + e); 15128 } 15129 } 15130 15131 if (!checkin 15132 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15133 && packageName == null) { 15134 pw.println(); 15135 int count = mSettings.mPackages.size(); 15136 if (count == 0) { 15137 pw.println("No applications!"); 15138 pw.println(); 15139 } else { 15140 final String prefix = " "; 15141 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15142 if (allPackageSettings.size() == 0) { 15143 pw.println("No domain preferred apps!"); 15144 pw.println(); 15145 } else { 15146 pw.println("App verification status:"); 15147 pw.println(); 15148 count = 0; 15149 for (PackageSetting ps : allPackageSettings) { 15150 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15151 if (ivi == null || ivi.getPackageName() == null) continue; 15152 pw.println(prefix + "Package: " + ivi.getPackageName()); 15153 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15154 pw.println(prefix + "Status: " + ivi.getStatusString()); 15155 pw.println(); 15156 count++; 15157 } 15158 if (count == 0) { 15159 pw.println(prefix + "No app verification established."); 15160 pw.println(); 15161 } 15162 for (int userId : sUserManager.getUserIds()) { 15163 pw.println("App linkages for user " + userId + ":"); 15164 pw.println(); 15165 count = 0; 15166 for (PackageSetting ps : allPackageSettings) { 15167 final long status = ps.getDomainVerificationStatusForUser(userId); 15168 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15169 continue; 15170 } 15171 pw.println(prefix + "Package: " + ps.name); 15172 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15173 String statusStr = IntentFilterVerificationInfo. 15174 getStatusStringFromValue(status); 15175 pw.println(prefix + "Status: " + statusStr); 15176 pw.println(); 15177 count++; 15178 } 15179 if (count == 0) { 15180 pw.println(prefix + "No configured app linkages."); 15181 pw.println(); 15182 } 15183 } 15184 } 15185 } 15186 } 15187 15188 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15189 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15190 if (packageName == null && permissionNames == null) { 15191 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15192 if (iperm == 0) { 15193 if (dumpState.onTitlePrinted()) 15194 pw.println(); 15195 pw.println("AppOp Permissions:"); 15196 } 15197 pw.print(" AppOp Permission "); 15198 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15199 pw.println(":"); 15200 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15201 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15202 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15203 } 15204 } 15205 } 15206 } 15207 15208 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15209 boolean printedSomething = false; 15210 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15211 if (packageName != null && !packageName.equals(p.info.packageName)) { 15212 continue; 15213 } 15214 if (!printedSomething) { 15215 if (dumpState.onTitlePrinted()) 15216 pw.println(); 15217 pw.println("Registered ContentProviders:"); 15218 printedSomething = true; 15219 } 15220 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15221 pw.print(" "); pw.println(p.toString()); 15222 } 15223 printedSomething = false; 15224 for (Map.Entry<String, PackageParser.Provider> entry : 15225 mProvidersByAuthority.entrySet()) { 15226 PackageParser.Provider p = entry.getValue(); 15227 if (packageName != null && !packageName.equals(p.info.packageName)) { 15228 continue; 15229 } 15230 if (!printedSomething) { 15231 if (dumpState.onTitlePrinted()) 15232 pw.println(); 15233 pw.println("ContentProvider Authorities:"); 15234 printedSomething = true; 15235 } 15236 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15237 pw.print(" "); pw.println(p.toString()); 15238 if (p.info != null && p.info.applicationInfo != null) { 15239 final String appInfo = p.info.applicationInfo.toString(); 15240 pw.print(" applicationInfo="); pw.println(appInfo); 15241 } 15242 } 15243 } 15244 15245 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15246 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15247 } 15248 15249 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15250 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15251 } 15252 15253 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15254 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15255 } 15256 15257 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15258 // XXX should handle packageName != null by dumping only install data that 15259 // the given package is involved with. 15260 if (dumpState.onTitlePrinted()) pw.println(); 15261 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15262 } 15263 15264 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15265 if (dumpState.onTitlePrinted()) pw.println(); 15266 mSettings.dumpReadMessagesLPr(pw, dumpState); 15267 15268 pw.println(); 15269 pw.println("Package warning messages:"); 15270 BufferedReader in = null; 15271 String line = null; 15272 try { 15273 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15274 while ((line = in.readLine()) != null) { 15275 if (line.contains("ignored: updated version")) continue; 15276 pw.println(line); 15277 } 15278 } catch (IOException ignored) { 15279 } finally { 15280 IoUtils.closeQuietly(in); 15281 } 15282 } 15283 15284 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15285 BufferedReader in = null; 15286 String line = null; 15287 try { 15288 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15289 while ((line = in.readLine()) != null) { 15290 if (line.contains("ignored: updated version")) continue; 15291 pw.print("msg,"); 15292 pw.println(line); 15293 } 15294 } catch (IOException ignored) { 15295 } finally { 15296 IoUtils.closeQuietly(in); 15297 } 15298 } 15299 } 15300 } 15301 15302 private String dumpDomainString(String packageName) { 15303 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15304 List<IntentFilter> filters = getAllIntentFilters(packageName); 15305 15306 ArraySet<String> result = new ArraySet<>(); 15307 if (iviList.size() > 0) { 15308 for (IntentFilterVerificationInfo ivi : iviList) { 15309 for (String host : ivi.getDomains()) { 15310 result.add(host); 15311 } 15312 } 15313 } 15314 if (filters != null && filters.size() > 0) { 15315 for (IntentFilter filter : filters) { 15316 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15317 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15318 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15319 result.addAll(filter.getHostsList()); 15320 } 15321 } 15322 } 15323 15324 StringBuilder sb = new StringBuilder(result.size() * 16); 15325 for (String domain : result) { 15326 if (sb.length() > 0) sb.append(" "); 15327 sb.append(domain); 15328 } 15329 return sb.toString(); 15330 } 15331 15332 // ------- apps on sdcard specific code ------- 15333 static final boolean DEBUG_SD_INSTALL = false; 15334 15335 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15336 15337 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15338 15339 private boolean mMediaMounted = false; 15340 15341 static String getEncryptKey() { 15342 try { 15343 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15344 SD_ENCRYPTION_KEYSTORE_NAME); 15345 if (sdEncKey == null) { 15346 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15347 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15348 if (sdEncKey == null) { 15349 Slog.e(TAG, "Failed to create encryption keys"); 15350 return null; 15351 } 15352 } 15353 return sdEncKey; 15354 } catch (NoSuchAlgorithmException nsae) { 15355 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15356 return null; 15357 } catch (IOException ioe) { 15358 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15359 return null; 15360 } 15361 } 15362 15363 /* 15364 * Update media status on PackageManager. 15365 */ 15366 @Override 15367 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15368 int callingUid = Binder.getCallingUid(); 15369 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15370 throw new SecurityException("Media status can only be updated by the system"); 15371 } 15372 // reader; this apparently protects mMediaMounted, but should probably 15373 // be a different lock in that case. 15374 synchronized (mPackages) { 15375 Log.i(TAG, "Updating external media status from " 15376 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15377 + (mediaStatus ? "mounted" : "unmounted")); 15378 if (DEBUG_SD_INSTALL) 15379 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15380 + ", mMediaMounted=" + mMediaMounted); 15381 if (mediaStatus == mMediaMounted) { 15382 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15383 : 0, -1); 15384 mHandler.sendMessage(msg); 15385 return; 15386 } 15387 mMediaMounted = mediaStatus; 15388 } 15389 // Queue up an async operation since the package installation may take a 15390 // little while. 15391 mHandler.post(new Runnable() { 15392 public void run() { 15393 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15394 } 15395 }); 15396 } 15397 15398 /** 15399 * Called by MountService when the initial ASECs to scan are available. 15400 * Should block until all the ASEC containers are finished being scanned. 15401 */ 15402 public void scanAvailableAsecs() { 15403 updateExternalMediaStatusInner(true, false, false); 15404 if (mShouldRestoreconData) { 15405 SELinuxMMAC.setRestoreconDone(); 15406 mShouldRestoreconData = false; 15407 } 15408 } 15409 15410 /* 15411 * Collect information of applications on external media, map them against 15412 * existing containers and update information based on current mount status. 15413 * Please note that we always have to report status if reportStatus has been 15414 * set to true especially when unloading packages. 15415 */ 15416 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15417 boolean externalStorage) { 15418 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15419 int[] uidArr = EmptyArray.INT; 15420 15421 final String[] list = PackageHelper.getSecureContainerList(); 15422 if (ArrayUtils.isEmpty(list)) { 15423 Log.i(TAG, "No secure containers found"); 15424 } else { 15425 // Process list of secure containers and categorize them 15426 // as active or stale based on their package internal state. 15427 15428 // reader 15429 synchronized (mPackages) { 15430 for (String cid : list) { 15431 // Leave stages untouched for now; installer service owns them 15432 if (PackageInstallerService.isStageName(cid)) continue; 15433 15434 if (DEBUG_SD_INSTALL) 15435 Log.i(TAG, "Processing container " + cid); 15436 String pkgName = getAsecPackageName(cid); 15437 if (pkgName == null) { 15438 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15439 continue; 15440 } 15441 if (DEBUG_SD_INSTALL) 15442 Log.i(TAG, "Looking for pkg : " + pkgName); 15443 15444 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15445 if (ps == null) { 15446 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15447 continue; 15448 } 15449 15450 /* 15451 * Skip packages that are not external if we're unmounting 15452 * external storage. 15453 */ 15454 if (externalStorage && !isMounted && !isExternal(ps)) { 15455 continue; 15456 } 15457 15458 final AsecInstallArgs args = new AsecInstallArgs(cid, 15459 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15460 // The package status is changed only if the code path 15461 // matches between settings and the container id. 15462 if (ps.codePathString != null 15463 && ps.codePathString.startsWith(args.getCodePath())) { 15464 if (DEBUG_SD_INSTALL) { 15465 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15466 + " at code path: " + ps.codePathString); 15467 } 15468 15469 // We do have a valid package installed on sdcard 15470 processCids.put(args, ps.codePathString); 15471 final int uid = ps.appId; 15472 if (uid != -1) { 15473 uidArr = ArrayUtils.appendInt(uidArr, uid); 15474 } 15475 } else { 15476 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15477 + ps.codePathString); 15478 } 15479 } 15480 } 15481 15482 Arrays.sort(uidArr); 15483 } 15484 15485 // Process packages with valid entries. 15486 if (isMounted) { 15487 if (DEBUG_SD_INSTALL) 15488 Log.i(TAG, "Loading packages"); 15489 loadMediaPackages(processCids, uidArr); 15490 startCleaningPackages(); 15491 mInstallerService.onSecureContainersAvailable(); 15492 } else { 15493 if (DEBUG_SD_INSTALL) 15494 Log.i(TAG, "Unloading packages"); 15495 unloadMediaPackages(processCids, uidArr, reportStatus); 15496 } 15497 } 15498 15499 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15500 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15501 final int size = infos.size(); 15502 final String[] packageNames = new String[size]; 15503 final int[] packageUids = new int[size]; 15504 for (int i = 0; i < size; i++) { 15505 final ApplicationInfo info = infos.get(i); 15506 packageNames[i] = info.packageName; 15507 packageUids[i] = info.uid; 15508 } 15509 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15510 finishedReceiver); 15511 } 15512 15513 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15514 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15515 sendResourcesChangedBroadcast(mediaStatus, replacing, 15516 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15517 } 15518 15519 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15520 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15521 int size = pkgList.length; 15522 if (size > 0) { 15523 // Send broadcasts here 15524 Bundle extras = new Bundle(); 15525 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15526 if (uidArr != null) { 15527 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15528 } 15529 if (replacing) { 15530 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15531 } 15532 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15533 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15534 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15535 } 15536 } 15537 15538 /* 15539 * Look at potentially valid container ids from processCids If package 15540 * information doesn't match the one on record or package scanning fails, 15541 * the cid is added to list of removeCids. We currently don't delete stale 15542 * containers. 15543 */ 15544 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15545 ArrayList<String> pkgList = new ArrayList<String>(); 15546 Set<AsecInstallArgs> keys = processCids.keySet(); 15547 15548 for (AsecInstallArgs args : keys) { 15549 String codePath = processCids.get(args); 15550 if (DEBUG_SD_INSTALL) 15551 Log.i(TAG, "Loading container : " + args.cid); 15552 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15553 try { 15554 // Make sure there are no container errors first. 15555 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15556 Slog.e(TAG, "Failed to mount cid : " + args.cid 15557 + " when installing from sdcard"); 15558 continue; 15559 } 15560 // Check code path here. 15561 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15562 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15563 + " does not match one in settings " + codePath); 15564 continue; 15565 } 15566 // Parse package 15567 int parseFlags = mDefParseFlags; 15568 if (args.isExternalAsec()) { 15569 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15570 } 15571 if (args.isFwdLocked()) { 15572 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15573 } 15574 15575 synchronized (mInstallLock) { 15576 PackageParser.Package pkg = null; 15577 try { 15578 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15579 } catch (PackageManagerException e) { 15580 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15581 } 15582 // Scan the package 15583 if (pkg != null) { 15584 /* 15585 * TODO why is the lock being held? doPostInstall is 15586 * called in other places without the lock. This needs 15587 * to be straightened out. 15588 */ 15589 // writer 15590 synchronized (mPackages) { 15591 retCode = PackageManager.INSTALL_SUCCEEDED; 15592 pkgList.add(pkg.packageName); 15593 // Post process args 15594 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15595 pkg.applicationInfo.uid); 15596 } 15597 } else { 15598 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15599 } 15600 } 15601 15602 } finally { 15603 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15604 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15605 } 15606 } 15607 } 15608 // writer 15609 synchronized (mPackages) { 15610 // If the platform SDK has changed since the last time we booted, 15611 // we need to re-grant app permission to catch any new ones that 15612 // appear. This is really a hack, and means that apps can in some 15613 // cases get permissions that the user didn't initially explicitly 15614 // allow... it would be nice to have some better way to handle 15615 // this situation. 15616 final VersionInfo ver = mSettings.getExternalVersion(); 15617 15618 int updateFlags = UPDATE_PERMISSIONS_ALL; 15619 if (ver.sdkVersion != mSdkVersion) { 15620 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15621 + mSdkVersion + "; regranting permissions for external"); 15622 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15623 } 15624 updatePermissionsLPw(null, null, updateFlags); 15625 15626 // Yay, everything is now upgraded 15627 ver.forceCurrent(); 15628 15629 // can downgrade to reader 15630 // Persist settings 15631 mSettings.writeLPr(); 15632 } 15633 // Send a broadcast to let everyone know we are done processing 15634 if (pkgList.size() > 0) { 15635 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15636 } 15637 } 15638 15639 /* 15640 * Utility method to unload a list of specified containers 15641 */ 15642 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15643 // Just unmount all valid containers. 15644 for (AsecInstallArgs arg : cidArgs) { 15645 synchronized (mInstallLock) { 15646 arg.doPostDeleteLI(false); 15647 } 15648 } 15649 } 15650 15651 /* 15652 * Unload packages mounted on external media. This involves deleting package 15653 * data from internal structures, sending broadcasts about diabled packages, 15654 * gc'ing to free up references, unmounting all secure containers 15655 * corresponding to packages on external media, and posting a 15656 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15657 * that we always have to post this message if status has been requested no 15658 * matter what. 15659 */ 15660 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15661 final boolean reportStatus) { 15662 if (DEBUG_SD_INSTALL) 15663 Log.i(TAG, "unloading media packages"); 15664 ArrayList<String> pkgList = new ArrayList<String>(); 15665 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15666 final Set<AsecInstallArgs> keys = processCids.keySet(); 15667 for (AsecInstallArgs args : keys) { 15668 String pkgName = args.getPackageName(); 15669 if (DEBUG_SD_INSTALL) 15670 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15671 // Delete package internally 15672 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15673 synchronized (mInstallLock) { 15674 boolean res = deletePackageLI(pkgName, null, false, null, null, 15675 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15676 if (res) { 15677 pkgList.add(pkgName); 15678 } else { 15679 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15680 failedList.add(args); 15681 } 15682 } 15683 } 15684 15685 // reader 15686 synchronized (mPackages) { 15687 // We didn't update the settings after removing each package; 15688 // write them now for all packages. 15689 mSettings.writeLPr(); 15690 } 15691 15692 // We have to absolutely send UPDATED_MEDIA_STATUS only 15693 // after confirming that all the receivers processed the ordered 15694 // broadcast when packages get disabled, force a gc to clean things up. 15695 // and unload all the containers. 15696 if (pkgList.size() > 0) { 15697 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15698 new IIntentReceiver.Stub() { 15699 public void performReceive(Intent intent, int resultCode, String data, 15700 Bundle extras, boolean ordered, boolean sticky, 15701 int sendingUser) throws RemoteException { 15702 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15703 reportStatus ? 1 : 0, 1, keys); 15704 mHandler.sendMessage(msg); 15705 } 15706 }); 15707 } else { 15708 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15709 keys); 15710 mHandler.sendMessage(msg); 15711 } 15712 } 15713 15714 private void loadPrivatePackages(VolumeInfo vol) { 15715 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15716 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15717 synchronized (mInstallLock) { 15718 synchronized (mPackages) { 15719 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15720 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15721 for (PackageSetting ps : packages) { 15722 final PackageParser.Package pkg; 15723 try { 15724 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15725 loaded.add(pkg.applicationInfo); 15726 } catch (PackageManagerException e) { 15727 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15728 } 15729 15730 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15731 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15732 } 15733 } 15734 15735 int updateFlags = UPDATE_PERMISSIONS_ALL; 15736 if (ver.sdkVersion != mSdkVersion) { 15737 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15738 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15739 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15740 } 15741 updatePermissionsLPw(null, null, updateFlags); 15742 15743 // Yay, everything is now upgraded 15744 ver.forceCurrent(); 15745 15746 mSettings.writeLPr(); 15747 } 15748 } 15749 15750 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15751 sendResourcesChangedBroadcast(true, false, loaded, null); 15752 } 15753 15754 private void unloadPrivatePackages(VolumeInfo vol) { 15755 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15756 synchronized (mInstallLock) { 15757 synchronized (mPackages) { 15758 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15759 for (PackageSetting ps : packages) { 15760 if (ps.pkg == null) continue; 15761 15762 final ApplicationInfo info = ps.pkg.applicationInfo; 15763 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15764 if (deletePackageLI(ps.name, null, false, null, null, 15765 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15766 unloaded.add(info); 15767 } else { 15768 Slog.w(TAG, "Failed to unload " + ps.codePath); 15769 } 15770 } 15771 15772 mSettings.writeLPr(); 15773 } 15774 } 15775 15776 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15777 sendResourcesChangedBroadcast(false, false, unloaded, null); 15778 } 15779 15780 /** 15781 * Examine all users present on given mounted volume, and destroy data 15782 * belonging to users that are no longer valid, or whose user ID has been 15783 * recycled. 15784 */ 15785 private void reconcileUsers(String volumeUuid) { 15786 final File[] files = FileUtils 15787 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15788 for (File file : files) { 15789 if (!file.isDirectory()) continue; 15790 15791 final int userId; 15792 final UserInfo info; 15793 try { 15794 userId = Integer.parseInt(file.getName()); 15795 info = sUserManager.getUserInfo(userId); 15796 } catch (NumberFormatException e) { 15797 Slog.w(TAG, "Invalid user directory " + file); 15798 continue; 15799 } 15800 15801 boolean destroyUser = false; 15802 if (info == null) { 15803 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15804 + " because no matching user was found"); 15805 destroyUser = true; 15806 } else { 15807 try { 15808 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15809 } catch (IOException e) { 15810 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15811 + " because we failed to enforce serial number: " + e); 15812 destroyUser = true; 15813 } 15814 } 15815 15816 if (destroyUser) { 15817 synchronized (mInstallLock) { 15818 mInstaller.removeUserDataDirs(volumeUuid, userId); 15819 } 15820 } 15821 } 15822 15823 final UserManager um = mContext.getSystemService(UserManager.class); 15824 for (UserInfo user : um.getUsers()) { 15825 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15826 if (userDir.exists()) continue; 15827 15828 try { 15829 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15830 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15831 } catch (IOException e) { 15832 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15833 } 15834 } 15835 } 15836 15837 /** 15838 * Examine all apps present on given mounted volume, and destroy apps that 15839 * aren't expected, either due to uninstallation or reinstallation on 15840 * another volume. 15841 */ 15842 private void reconcileApps(String volumeUuid) { 15843 final File[] files = FileUtils 15844 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15845 for (File file : files) { 15846 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15847 && !PackageInstallerService.isStageName(file.getName()); 15848 if (!isPackage) { 15849 // Ignore entries which are not packages 15850 continue; 15851 } 15852 15853 boolean destroyApp = false; 15854 String packageName = null; 15855 try { 15856 final PackageLite pkg = PackageParser.parsePackageLite(file, 15857 PackageParser.PARSE_MUST_BE_APK); 15858 packageName = pkg.packageName; 15859 15860 synchronized (mPackages) { 15861 final PackageSetting ps = mSettings.mPackages.get(packageName); 15862 if (ps == null) { 15863 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15864 + volumeUuid + " because we found no install record"); 15865 destroyApp = true; 15866 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15867 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15868 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15869 destroyApp = true; 15870 } 15871 } 15872 15873 } catch (PackageParserException e) { 15874 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15875 destroyApp = true; 15876 } 15877 15878 if (destroyApp) { 15879 synchronized (mInstallLock) { 15880 if (packageName != null) { 15881 removeDataDirsLI(volumeUuid, packageName); 15882 } 15883 if (file.isDirectory()) { 15884 mInstaller.rmPackageDir(file.getAbsolutePath()); 15885 } else { 15886 file.delete(); 15887 } 15888 } 15889 } 15890 } 15891 } 15892 15893 private void unfreezePackage(String packageName) { 15894 synchronized (mPackages) { 15895 final PackageSetting ps = mSettings.mPackages.get(packageName); 15896 if (ps != null) { 15897 ps.frozen = false; 15898 } 15899 } 15900 } 15901 15902 @Override 15903 public int movePackage(final String packageName, final String volumeUuid) { 15904 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15905 15906 final int moveId = mNextMoveId.getAndIncrement(); 15907 try { 15908 movePackageInternal(packageName, volumeUuid, moveId); 15909 } catch (PackageManagerException e) { 15910 Slog.w(TAG, "Failed to move " + packageName, e); 15911 mMoveCallbacks.notifyStatusChanged(moveId, 15912 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15913 } 15914 return moveId; 15915 } 15916 15917 private void movePackageInternal(final String packageName, final String volumeUuid, 15918 final int moveId) throws PackageManagerException { 15919 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15920 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15921 final PackageManager pm = mContext.getPackageManager(); 15922 15923 final boolean currentAsec; 15924 final String currentVolumeUuid; 15925 final File codeFile; 15926 final String installerPackageName; 15927 final String packageAbiOverride; 15928 final int appId; 15929 final String seinfo; 15930 final String label; 15931 15932 // reader 15933 synchronized (mPackages) { 15934 final PackageParser.Package pkg = mPackages.get(packageName); 15935 final PackageSetting ps = mSettings.mPackages.get(packageName); 15936 if (pkg == null || ps == null) { 15937 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15938 } 15939 15940 if (pkg.applicationInfo.isSystemApp()) { 15941 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15942 "Cannot move system application"); 15943 } 15944 15945 if (pkg.applicationInfo.isExternalAsec()) { 15946 currentAsec = true; 15947 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 15948 } else if (pkg.applicationInfo.isForwardLocked()) { 15949 currentAsec = true; 15950 currentVolumeUuid = "forward_locked"; 15951 } else { 15952 currentAsec = false; 15953 currentVolumeUuid = ps.volumeUuid; 15954 15955 final File probe = new File(pkg.codePath); 15956 final File probeOat = new File(probe, "oat"); 15957 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15958 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15959 "Move only supported for modern cluster style installs"); 15960 } 15961 } 15962 15963 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 15964 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15965 "Package already moved to " + volumeUuid); 15966 } 15967 15968 if (ps.frozen) { 15969 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15970 "Failed to move already frozen package"); 15971 } 15972 ps.frozen = true; 15973 15974 codeFile = new File(pkg.codePath); 15975 installerPackageName = ps.installerPackageName; 15976 packageAbiOverride = ps.cpuAbiOverrideString; 15977 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15978 seinfo = pkg.applicationInfo.seinfo; 15979 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15980 } 15981 15982 // Now that we're guarded by frozen state, kill app during move 15983 final long token = Binder.clearCallingIdentity(); 15984 try { 15985 killApplication(packageName, appId, "move pkg"); 15986 } finally { 15987 Binder.restoreCallingIdentity(token); 15988 } 15989 15990 final Bundle extras = new Bundle(); 15991 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15992 extras.putString(Intent.EXTRA_TITLE, label); 15993 mMoveCallbacks.notifyCreated(moveId, extras); 15994 15995 int installFlags; 15996 final boolean moveCompleteApp; 15997 final File measurePath; 15998 15999 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16000 installFlags = INSTALL_INTERNAL; 16001 moveCompleteApp = !currentAsec; 16002 measurePath = Environment.getDataAppDirectory(volumeUuid); 16003 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16004 installFlags = INSTALL_EXTERNAL; 16005 moveCompleteApp = false; 16006 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16007 } else { 16008 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16009 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16010 || !volume.isMountedWritable()) { 16011 unfreezePackage(packageName); 16012 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16013 "Move location not mounted private volume"); 16014 } 16015 16016 Preconditions.checkState(!currentAsec); 16017 16018 installFlags = INSTALL_INTERNAL; 16019 moveCompleteApp = true; 16020 measurePath = Environment.getDataAppDirectory(volumeUuid); 16021 } 16022 16023 final PackageStats stats = new PackageStats(null, -1); 16024 synchronized (mInstaller) { 16025 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16026 unfreezePackage(packageName); 16027 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16028 "Failed to measure package size"); 16029 } 16030 } 16031 16032 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16033 + stats.dataSize); 16034 16035 final long startFreeBytes = measurePath.getFreeSpace(); 16036 final long sizeBytes; 16037 if (moveCompleteApp) { 16038 sizeBytes = stats.codeSize + stats.dataSize; 16039 } else { 16040 sizeBytes = stats.codeSize; 16041 } 16042 16043 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16044 unfreezePackage(packageName); 16045 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16046 "Not enough free space to move"); 16047 } 16048 16049 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16050 16051 final CountDownLatch installedLatch = new CountDownLatch(1); 16052 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16053 @Override 16054 public void onUserActionRequired(Intent intent) throws RemoteException { 16055 throw new IllegalStateException(); 16056 } 16057 16058 @Override 16059 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16060 Bundle extras) throws RemoteException { 16061 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16062 + PackageManager.installStatusToString(returnCode, msg)); 16063 16064 installedLatch.countDown(); 16065 16066 // Regardless of success or failure of the move operation, 16067 // always unfreeze the package 16068 unfreezePackage(packageName); 16069 16070 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16071 switch (status) { 16072 case PackageInstaller.STATUS_SUCCESS: 16073 mMoveCallbacks.notifyStatusChanged(moveId, 16074 PackageManager.MOVE_SUCCEEDED); 16075 break; 16076 case PackageInstaller.STATUS_FAILURE_STORAGE: 16077 mMoveCallbacks.notifyStatusChanged(moveId, 16078 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16079 break; 16080 default: 16081 mMoveCallbacks.notifyStatusChanged(moveId, 16082 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16083 break; 16084 } 16085 } 16086 }; 16087 16088 final MoveInfo move; 16089 if (moveCompleteApp) { 16090 // Kick off a thread to report progress estimates 16091 new Thread() { 16092 @Override 16093 public void run() { 16094 while (true) { 16095 try { 16096 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16097 break; 16098 } 16099 } catch (InterruptedException ignored) { 16100 } 16101 16102 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16103 final int progress = 10 + (int) MathUtils.constrain( 16104 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16105 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16106 } 16107 } 16108 }.start(); 16109 16110 final String dataAppName = codeFile.getName(); 16111 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16112 dataAppName, appId, seinfo); 16113 } else { 16114 move = null; 16115 } 16116 16117 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16118 16119 final Message msg = mHandler.obtainMessage(INIT_COPY); 16120 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16121 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16122 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16123 mHandler.sendMessage(msg); 16124 } 16125 16126 @Override 16127 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16128 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16129 16130 final int realMoveId = mNextMoveId.getAndIncrement(); 16131 final Bundle extras = new Bundle(); 16132 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16133 mMoveCallbacks.notifyCreated(realMoveId, extras); 16134 16135 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16136 @Override 16137 public void onCreated(int moveId, Bundle extras) { 16138 // Ignored 16139 } 16140 16141 @Override 16142 public void onStatusChanged(int moveId, int status, long estMillis) { 16143 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16144 } 16145 }; 16146 16147 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16148 storage.setPrimaryStorageUuid(volumeUuid, callback); 16149 return realMoveId; 16150 } 16151 16152 @Override 16153 public int getMoveStatus(int moveId) { 16154 mContext.enforceCallingOrSelfPermission( 16155 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16156 return mMoveCallbacks.mLastStatus.get(moveId); 16157 } 16158 16159 @Override 16160 public void registerMoveCallback(IPackageMoveObserver callback) { 16161 mContext.enforceCallingOrSelfPermission( 16162 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16163 mMoveCallbacks.register(callback); 16164 } 16165 16166 @Override 16167 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16168 mContext.enforceCallingOrSelfPermission( 16169 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16170 mMoveCallbacks.unregister(callback); 16171 } 16172 16173 @Override 16174 public boolean setInstallLocation(int loc) { 16175 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16176 null); 16177 if (getInstallLocation() == loc) { 16178 return true; 16179 } 16180 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16181 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16182 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16183 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16184 return true; 16185 } 16186 return false; 16187 } 16188 16189 @Override 16190 public int getInstallLocation() { 16191 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16192 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16193 PackageHelper.APP_INSTALL_AUTO); 16194 } 16195 16196 /** Called by UserManagerService */ 16197 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16198 mDirtyUsers.remove(userHandle); 16199 mSettings.removeUserLPw(userHandle); 16200 mPendingBroadcasts.remove(userHandle); 16201 if (mInstaller != null) { 16202 // Technically, we shouldn't be doing this with the package lock 16203 // held. However, this is very rare, and there is already so much 16204 // other disk I/O going on, that we'll let it slide for now. 16205 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16206 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16207 final String volumeUuid = vol.getFsUuid(); 16208 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16209 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16210 } 16211 } 16212 mUserNeedsBadging.delete(userHandle); 16213 removeUnusedPackagesLILPw(userManager, userHandle); 16214 } 16215 16216 /** 16217 * We're removing userHandle and would like to remove any downloaded packages 16218 * that are no longer in use by any other user. 16219 * @param userHandle the user being removed 16220 */ 16221 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16222 final boolean DEBUG_CLEAN_APKS = false; 16223 int [] users = userManager.getUserIdsLPr(); 16224 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16225 while (psit.hasNext()) { 16226 PackageSetting ps = psit.next(); 16227 if (ps.pkg == null) { 16228 continue; 16229 } 16230 final String packageName = ps.pkg.packageName; 16231 // Skip over if system app 16232 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16233 continue; 16234 } 16235 if (DEBUG_CLEAN_APKS) { 16236 Slog.i(TAG, "Checking package " + packageName); 16237 } 16238 boolean keep = false; 16239 for (int i = 0; i < users.length; i++) { 16240 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16241 keep = true; 16242 if (DEBUG_CLEAN_APKS) { 16243 Slog.i(TAG, " Keeping package " + packageName + " for user " 16244 + users[i]); 16245 } 16246 break; 16247 } 16248 } 16249 if (!keep) { 16250 if (DEBUG_CLEAN_APKS) { 16251 Slog.i(TAG, " Removing package " + packageName); 16252 } 16253 mHandler.post(new Runnable() { 16254 public void run() { 16255 deletePackageX(packageName, userHandle, 0); 16256 } //end run 16257 }); 16258 } 16259 } 16260 } 16261 16262 /** Called by UserManagerService */ 16263 void createNewUserLILPw(int userHandle) { 16264 if (mInstaller != null) { 16265 mInstaller.createUserConfig(userHandle); 16266 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16267 applyFactoryDefaultBrowserLPw(userHandle); 16268 primeDomainVerificationsLPw(userHandle); 16269 } 16270 } 16271 16272 void newUserCreated(final int userHandle) { 16273 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16274 } 16275 16276 @Override 16277 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16278 mContext.enforceCallingOrSelfPermission( 16279 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16280 "Only package verification agents can read the verifier device identity"); 16281 16282 synchronized (mPackages) { 16283 return mSettings.getVerifierDeviceIdentityLPw(); 16284 } 16285 } 16286 16287 @Override 16288 public void setPermissionEnforced(String permission, boolean enforced) { 16289 // TODO: Now that we no longer change GID for storage, this should to away. 16290 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16291 "setPermissionEnforced"); 16292 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16293 synchronized (mPackages) { 16294 if (mSettings.mReadExternalStorageEnforced == null 16295 || mSettings.mReadExternalStorageEnforced != enforced) { 16296 mSettings.mReadExternalStorageEnforced = enforced; 16297 mSettings.writeLPr(); 16298 } 16299 } 16300 // kill any non-foreground processes so we restart them and 16301 // grant/revoke the GID. 16302 final IActivityManager am = ActivityManagerNative.getDefault(); 16303 if (am != null) { 16304 final long token = Binder.clearCallingIdentity(); 16305 try { 16306 am.killProcessesBelowForeground("setPermissionEnforcement"); 16307 } catch (RemoteException e) { 16308 } finally { 16309 Binder.restoreCallingIdentity(token); 16310 } 16311 } 16312 } else { 16313 throw new IllegalArgumentException("No selective enforcement for " + permission); 16314 } 16315 } 16316 16317 @Override 16318 @Deprecated 16319 public boolean isPermissionEnforced(String permission) { 16320 return true; 16321 } 16322 16323 @Override 16324 public boolean isStorageLow() { 16325 final long token = Binder.clearCallingIdentity(); 16326 try { 16327 final DeviceStorageMonitorInternal 16328 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16329 if (dsm != null) { 16330 return dsm.isMemoryLow(); 16331 } else { 16332 return false; 16333 } 16334 } finally { 16335 Binder.restoreCallingIdentity(token); 16336 } 16337 } 16338 16339 @Override 16340 public IPackageInstaller getPackageInstaller() { 16341 return mInstallerService; 16342 } 16343 16344 private boolean userNeedsBadging(int userId) { 16345 int index = mUserNeedsBadging.indexOfKey(userId); 16346 if (index < 0) { 16347 final UserInfo userInfo; 16348 final long token = Binder.clearCallingIdentity(); 16349 try { 16350 userInfo = sUserManager.getUserInfo(userId); 16351 } finally { 16352 Binder.restoreCallingIdentity(token); 16353 } 16354 final boolean b; 16355 if (userInfo != null && userInfo.isManagedProfile()) { 16356 b = true; 16357 } else { 16358 b = false; 16359 } 16360 mUserNeedsBadging.put(userId, b); 16361 return b; 16362 } 16363 return mUserNeedsBadging.valueAt(index); 16364 } 16365 16366 @Override 16367 public KeySet getKeySetByAlias(String packageName, String alias) { 16368 if (packageName == null || alias == null) { 16369 return null; 16370 } 16371 synchronized(mPackages) { 16372 final PackageParser.Package pkg = mPackages.get(packageName); 16373 if (pkg == null) { 16374 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16375 throw new IllegalArgumentException("Unknown package: " + packageName); 16376 } 16377 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16378 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16379 } 16380 } 16381 16382 @Override 16383 public KeySet getSigningKeySet(String packageName) { 16384 if (packageName == null) { 16385 return null; 16386 } 16387 synchronized(mPackages) { 16388 final PackageParser.Package pkg = mPackages.get(packageName); 16389 if (pkg == null) { 16390 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16391 throw new IllegalArgumentException("Unknown package: " + packageName); 16392 } 16393 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16394 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16395 throw new SecurityException("May not access signing KeySet of other apps."); 16396 } 16397 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16398 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16399 } 16400 } 16401 16402 @Override 16403 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16404 if (packageName == null || ks == null) { 16405 return false; 16406 } 16407 synchronized(mPackages) { 16408 final PackageParser.Package pkg = mPackages.get(packageName); 16409 if (pkg == null) { 16410 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16411 throw new IllegalArgumentException("Unknown package: " + packageName); 16412 } 16413 IBinder ksh = ks.getToken(); 16414 if (ksh instanceof KeySetHandle) { 16415 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16416 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16417 } 16418 return false; 16419 } 16420 } 16421 16422 @Override 16423 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16424 if (packageName == null || ks == null) { 16425 return false; 16426 } 16427 synchronized(mPackages) { 16428 final PackageParser.Package pkg = mPackages.get(packageName); 16429 if (pkg == null) { 16430 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16431 throw new IllegalArgumentException("Unknown package: " + packageName); 16432 } 16433 IBinder ksh = ks.getToken(); 16434 if (ksh instanceof KeySetHandle) { 16435 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16436 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16437 } 16438 return false; 16439 } 16440 } 16441 16442 public void getUsageStatsIfNoPackageUsageInfo() { 16443 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16444 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16445 if (usm == null) { 16446 throw new IllegalStateException("UsageStatsManager must be initialized"); 16447 } 16448 long now = System.currentTimeMillis(); 16449 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16450 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16451 String packageName = entry.getKey(); 16452 PackageParser.Package pkg = mPackages.get(packageName); 16453 if (pkg == null) { 16454 continue; 16455 } 16456 UsageStats usage = entry.getValue(); 16457 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16458 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16459 } 16460 } 16461 } 16462 16463 /** 16464 * Check and throw if the given before/after packages would be considered a 16465 * downgrade. 16466 */ 16467 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16468 throws PackageManagerException { 16469 if (after.versionCode < before.mVersionCode) { 16470 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16471 "Update version code " + after.versionCode + " is older than current " 16472 + before.mVersionCode); 16473 } else if (after.versionCode == before.mVersionCode) { 16474 if (after.baseRevisionCode < before.baseRevisionCode) { 16475 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16476 "Update base revision code " + after.baseRevisionCode 16477 + " is older than current " + before.baseRevisionCode); 16478 } 16479 16480 if (!ArrayUtils.isEmpty(after.splitNames)) { 16481 for (int i = 0; i < after.splitNames.length; i++) { 16482 final String splitName = after.splitNames[i]; 16483 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16484 if (j != -1) { 16485 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16486 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16487 "Update split " + splitName + " revision code " 16488 + after.splitRevisionCodes[i] + " is older than current " 16489 + before.splitRevisionCodes[j]); 16490 } 16491 } 16492 } 16493 } 16494 } 16495 } 16496 16497 private static class MoveCallbacks extends Handler { 16498 private static final int MSG_CREATED = 1; 16499 private static final int MSG_STATUS_CHANGED = 2; 16500 16501 private final RemoteCallbackList<IPackageMoveObserver> 16502 mCallbacks = new RemoteCallbackList<>(); 16503 16504 private final SparseIntArray mLastStatus = new SparseIntArray(); 16505 16506 public MoveCallbacks(Looper looper) { 16507 super(looper); 16508 } 16509 16510 public void register(IPackageMoveObserver callback) { 16511 mCallbacks.register(callback); 16512 } 16513 16514 public void unregister(IPackageMoveObserver callback) { 16515 mCallbacks.unregister(callback); 16516 } 16517 16518 @Override 16519 public void handleMessage(Message msg) { 16520 final SomeArgs args = (SomeArgs) msg.obj; 16521 final int n = mCallbacks.beginBroadcast(); 16522 for (int i = 0; i < n; i++) { 16523 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16524 try { 16525 invokeCallback(callback, msg.what, args); 16526 } catch (RemoteException ignored) { 16527 } 16528 } 16529 mCallbacks.finishBroadcast(); 16530 args.recycle(); 16531 } 16532 16533 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16534 throws RemoteException { 16535 switch (what) { 16536 case MSG_CREATED: { 16537 callback.onCreated(args.argi1, (Bundle) args.arg2); 16538 break; 16539 } 16540 case MSG_STATUS_CHANGED: { 16541 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16542 break; 16543 } 16544 } 16545 } 16546 16547 private void notifyCreated(int moveId, Bundle extras) { 16548 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16549 16550 final SomeArgs args = SomeArgs.obtain(); 16551 args.argi1 = moveId; 16552 args.arg2 = extras; 16553 obtainMessage(MSG_CREATED, args).sendToTarget(); 16554 } 16555 16556 private void notifyStatusChanged(int moveId, int status) { 16557 notifyStatusChanged(moveId, status, -1); 16558 } 16559 16560 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16561 Slog.v(TAG, "Move " + moveId + " status " + status); 16562 16563 final SomeArgs args = SomeArgs.obtain(); 16564 args.argi1 = moveId; 16565 args.argi2 = status; 16566 args.arg3 = estMillis; 16567 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16568 16569 synchronized (mLastStatus) { 16570 mLastStatus.put(moveId, status); 16571 } 16572 } 16573 } 16574 16575 private final class OnPermissionChangeListeners extends Handler { 16576 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16577 16578 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16579 new RemoteCallbackList<>(); 16580 16581 public OnPermissionChangeListeners(Looper looper) { 16582 super(looper); 16583 } 16584 16585 @Override 16586 public void handleMessage(Message msg) { 16587 switch (msg.what) { 16588 case MSG_ON_PERMISSIONS_CHANGED: { 16589 final int uid = msg.arg1; 16590 handleOnPermissionsChanged(uid); 16591 } break; 16592 } 16593 } 16594 16595 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16596 mPermissionListeners.register(listener); 16597 16598 } 16599 16600 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16601 mPermissionListeners.unregister(listener); 16602 } 16603 16604 public void onPermissionsChanged(int uid) { 16605 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16606 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16607 } 16608 } 16609 16610 private void handleOnPermissionsChanged(int uid) { 16611 final int count = mPermissionListeners.beginBroadcast(); 16612 try { 16613 for (int i = 0; i < count; i++) { 16614 IOnPermissionsChangeListener callback = mPermissionListeners 16615 .getBroadcastItem(i); 16616 try { 16617 callback.onPermissionsChanged(uid); 16618 } catch (RemoteException e) { 16619 Log.e(TAG, "Permission listener is dead", e); 16620 } 16621 } 16622 } finally { 16623 mPermissionListeners.finishBroadcast(); 16624 } 16625 } 16626 } 16627 16628 private class PackageManagerInternalImpl extends PackageManagerInternal { 16629 @Override 16630 public void setLocationPackagesProvider(PackagesProvider provider) { 16631 synchronized (mPackages) { 16632 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16633 } 16634 } 16635 16636 @Override 16637 public void setImePackagesProvider(PackagesProvider provider) { 16638 synchronized (mPackages) { 16639 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16640 } 16641 } 16642 16643 @Override 16644 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16645 synchronized (mPackages) { 16646 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16647 } 16648 } 16649 16650 @Override 16651 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16652 synchronized (mPackages) { 16653 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16654 } 16655 } 16656 16657 @Override 16658 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16659 synchronized (mPackages) { 16660 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16661 } 16662 } 16663 16664 @Override 16665 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16666 synchronized (mPackages) { 16667 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16668 } 16669 } 16670 16671 @Override 16672 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16673 synchronized (mPackages) { 16674 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16675 } 16676 } 16677 16678 @Override 16679 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16680 synchronized (mPackages) { 16681 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16682 packageName, userId); 16683 } 16684 } 16685 16686 @Override 16687 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16688 synchronized (mPackages) { 16689 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16690 packageName, userId); 16691 } 16692 } 16693 @Override 16694 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16695 synchronized (mPackages) { 16696 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16697 packageName, userId); 16698 } 16699 } 16700 } 16701 16702 @Override 16703 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16704 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16705 synchronized (mPackages) { 16706 final long identity = Binder.clearCallingIdentity(); 16707 try { 16708 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16709 packageNames, userId); 16710 } finally { 16711 Binder.restoreCallingIdentity(identity); 16712 } 16713 } 16714 } 16715 16716 private static void enforceSystemOrPhoneCaller(String tag) { 16717 int callingUid = Binder.getCallingUid(); 16718 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16719 throw new SecurityException( 16720 "Cannot call " + tag + " from UID " + callingUid); 16721 } 16722 } 16723} 16724