PackageManagerService.java revision 9f5b0a27350df984fb4a98b9658e89390ed60573
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.system.OsConstants.O_CREAT; 70import static android.system.OsConstants.O_RDWR; 71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 75import static com.android.internal.util.ArrayUtils.appendInt; 76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 84 85import android.Manifest; 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.AppGlobals; 89import android.app.IActivityManager; 90import android.app.admin.IDevicePolicyManager; 91import android.app.backup.IBackupManager; 92import android.app.usage.UsageStats; 93import android.app.usage.UsageStatsManager; 94import android.content.BroadcastReceiver; 95import android.content.ComponentName; 96import android.content.Context; 97import android.content.IIntentReceiver; 98import android.content.Intent; 99import android.content.IntentFilter; 100import android.content.IntentSender; 101import android.content.IntentSender.SendIntentException; 102import android.content.ServiceConnection; 103import android.content.pm.ActivityInfo; 104import android.content.pm.ApplicationInfo; 105import android.content.pm.FeatureInfo; 106import android.content.pm.IOnPermissionsChangeListener; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.IntentFilterVerificationInfo; 117import android.content.pm.KeySet; 118import android.content.pm.ManifestDigest; 119import android.content.pm.PackageCleanItem; 120import android.content.pm.PackageInfo; 121import android.content.pm.PackageInfoLite; 122import android.content.pm.PackageInstaller; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 125import android.content.pm.PackageManagerInternal; 126import android.content.pm.PackageParser; 127import android.content.pm.PackageParser.ActivityIntentInfo; 128import android.content.pm.PackageParser.PackageLite; 129import android.content.pm.PackageParser.PackageParserException; 130import android.content.pm.PackageStats; 131import android.content.pm.PackageUserState; 132import android.content.pm.ParceledListSlice; 133import android.content.pm.PermissionGroupInfo; 134import android.content.pm.PermissionInfo; 135import android.content.pm.ProviderInfo; 136import android.content.pm.ResolveInfo; 137import android.content.pm.ServiceInfo; 138import android.content.pm.Signature; 139import android.content.pm.UserInfo; 140import android.content.pm.VerificationParams; 141import android.content.pm.VerifierDeviceIdentity; 142import android.content.pm.VerifierInfo; 143import android.content.res.Resources; 144import android.hardware.display.DisplayManager; 145import android.net.Uri; 146import android.os.Debug; 147import android.os.Binder; 148import android.os.Build; 149import android.os.Bundle; 150import android.os.Environment; 151import android.os.Environment.UserEnvironment; 152import android.os.FileUtils; 153import android.os.Handler; 154import android.os.IBinder; 155import android.os.Looper; 156import android.os.Message; 157import android.os.Parcel; 158import android.os.ParcelFileDescriptor; 159import android.os.Process; 160import android.os.RemoteCallbackList; 161import android.os.RemoteException; 162import android.os.SELinux; 163import android.os.ServiceManager; 164import android.os.SystemClock; 165import android.os.SystemProperties; 166import android.os.UserHandle; 167import android.os.UserManager; 168import android.os.storage.IMountService; 169import android.os.storage.MountServiceInternal; 170import android.os.storage.StorageEventListener; 171import android.os.storage.StorageManager; 172import android.os.storage.VolumeInfo; 173import android.os.storage.VolumeRecord; 174import android.security.KeyStore; 175import android.security.SystemKeyStore; 176import android.system.ErrnoException; 177import android.system.Os; 178import android.system.StructStat; 179import android.text.TextUtils; 180import android.text.format.DateUtils; 181import android.util.ArrayMap; 182import android.util.ArraySet; 183import android.util.AtomicFile; 184import android.util.DisplayMetrics; 185import android.util.EventLog; 186import android.util.ExceptionUtils; 187import android.util.Log; 188import android.util.LogPrinter; 189import android.util.MathUtils; 190import android.util.PrintStreamPrinter; 191import android.util.Slog; 192import android.util.SparseArray; 193import android.util.SparseBooleanArray; 194import android.util.SparseIntArray; 195import android.util.Xml; 196import android.view.Display; 197 198import dalvik.system.DexFile; 199import dalvik.system.VMRuntime; 200 201import libcore.io.IoUtils; 202import libcore.util.EmptyArray; 203 204import com.android.internal.R; 205import com.android.internal.annotations.GuardedBy; 206import com.android.internal.app.IMediaContainerService; 207import com.android.internal.app.ResolverActivity; 208import com.android.internal.content.NativeLibraryHelper; 209import com.android.internal.content.PackageHelper; 210import com.android.internal.os.IParcelFileDescriptorFactory; 211import com.android.internal.os.SomeArgs; 212import com.android.internal.os.Zygote; 213import com.android.internal.util.ArrayUtils; 214import com.android.internal.util.FastPrintWriter; 215import com.android.internal.util.FastXmlSerializer; 216import com.android.internal.util.IndentingPrintWriter; 217import com.android.internal.util.Preconditions; 218import com.android.server.EventLogTags; 219import com.android.server.FgThread; 220import com.android.server.IntentResolver; 221import com.android.server.LocalServices; 222import com.android.server.ServiceThread; 223import com.android.server.SystemConfig; 224import com.android.server.Watchdog; 225import com.android.server.pm.PermissionsState.PermissionState; 226import com.android.server.pm.Settings.DatabaseVersion; 227import com.android.server.pm.Settings.VersionInfo; 228import com.android.server.storage.DeviceStorageMonitorInternal; 229 230import org.xmlpull.v1.XmlPullParser; 231import org.xmlpull.v1.XmlPullParserException; 232import org.xmlpull.v1.XmlSerializer; 233 234import java.io.BufferedInputStream; 235import java.io.BufferedOutputStream; 236import java.io.BufferedReader; 237import java.io.ByteArrayInputStream; 238import java.io.ByteArrayOutputStream; 239import java.io.File; 240import java.io.FileDescriptor; 241import java.io.FileNotFoundException; 242import java.io.FileOutputStream; 243import java.io.FileReader; 244import java.io.FilenameFilter; 245import java.io.IOException; 246import java.io.InputStream; 247import java.io.PrintWriter; 248import java.nio.charset.StandardCharsets; 249import java.security.NoSuchAlgorithmException; 250import java.security.PublicKey; 251import java.security.cert.CertificateEncodingException; 252import java.security.cert.CertificateException; 253import java.text.SimpleDateFormat; 254import java.util.ArrayList; 255import java.util.Arrays; 256import java.util.Collection; 257import java.util.Collections; 258import java.util.Comparator; 259import java.util.Date; 260import java.util.Iterator; 261import java.util.List; 262import java.util.Map; 263import java.util.Objects; 264import java.util.Set; 265import java.util.concurrent.CountDownLatch; 266import java.util.concurrent.TimeUnit; 267import java.util.concurrent.atomic.AtomicBoolean; 268import java.util.concurrent.atomic.AtomicInteger; 269import java.util.concurrent.atomic.AtomicLong; 270 271/** 272 * Keep track of all those .apks everywhere. 273 * 274 * This is very central to the platform's security; please run the unit 275 * tests whenever making modifications here: 276 * 277mmm frameworks/base/tests/AndroidTests 278adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 279adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 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 // If this is the only one pending we might 1149 // have to bind to the service again. 1150 if (!connectToService()) { 1151 Slog.e(TAG, "Failed to bind to media container service"); 1152 params.serviceError(); 1153 return; 1154 } else { 1155 // Once we bind to the service, the first 1156 // pending request will be processed. 1157 mPendingInstalls.add(idx, params); 1158 } 1159 } else { 1160 mPendingInstalls.add(idx, params); 1161 // Already bound to the service. Just make 1162 // sure we trigger off processing the first request. 1163 if (idx == 0) { 1164 mHandler.sendEmptyMessage(MCS_BOUND); 1165 } 1166 } 1167 break; 1168 } 1169 case MCS_BOUND: { 1170 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1171 if (msg.obj != null) { 1172 mContainerService = (IMediaContainerService) msg.obj; 1173 } 1174 if (mContainerService == null) { 1175 if (!mBound) { 1176 // Something seriously wrong since we are not bound and we are not 1177 // waiting for connection. Bail out. 1178 Slog.e(TAG, "Cannot bind to media container service"); 1179 for (HandlerParams params : mPendingInstalls) { 1180 // Indicate service bind error 1181 params.serviceError(); 1182 } 1183 mPendingInstalls.clear(); 1184 } else { 1185 Slog.w(TAG, "Waiting to connect to media container service"); 1186 } 1187 } else if (mPendingInstalls.size() > 0) { 1188 HandlerParams params = mPendingInstalls.get(0); 1189 if (params != null) { 1190 if (params.startCopy()) { 1191 // We are done... look for more work or to 1192 // go idle. 1193 if (DEBUG_SD_INSTALL) Log.i(TAG, 1194 "Checking for more work or unbind..."); 1195 // Delete pending install 1196 if (mPendingInstalls.size() > 0) { 1197 mPendingInstalls.remove(0); 1198 } 1199 if (mPendingInstalls.size() == 0) { 1200 if (mBound) { 1201 if (DEBUG_SD_INSTALL) Log.i(TAG, 1202 "Posting delayed MCS_UNBIND"); 1203 removeMessages(MCS_UNBIND); 1204 Message ubmsg = obtainMessage(MCS_UNBIND); 1205 // Unbind after a little delay, to avoid 1206 // continual thrashing. 1207 sendMessageDelayed(ubmsg, 10000); 1208 } 1209 } else { 1210 // There are more pending requests in queue. 1211 // Just post MCS_BOUND message to trigger processing 1212 // of next pending install. 1213 if (DEBUG_SD_INSTALL) Log.i(TAG, 1214 "Posting MCS_BOUND for next work"); 1215 mHandler.sendEmptyMessage(MCS_BOUND); 1216 } 1217 } 1218 } 1219 } else { 1220 // Should never happen ideally. 1221 Slog.w(TAG, "Empty queue"); 1222 } 1223 break; 1224 } 1225 case MCS_RECONNECT: { 1226 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1227 if (mPendingInstalls.size() > 0) { 1228 if (mBound) { 1229 disconnectService(); 1230 } 1231 if (!connectToService()) { 1232 Slog.e(TAG, "Failed to bind to media container service"); 1233 for (HandlerParams params : mPendingInstalls) { 1234 // Indicate service bind error 1235 params.serviceError(); 1236 } 1237 mPendingInstalls.clear(); 1238 } 1239 } 1240 break; 1241 } 1242 case MCS_UNBIND: { 1243 // If there is no actual work left, then time to unbind. 1244 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1245 1246 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1247 if (mBound) { 1248 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1249 1250 disconnectService(); 1251 } 1252 } else if (mPendingInstalls.size() > 0) { 1253 // There are more pending requests in queue. 1254 // Just post MCS_BOUND message to trigger processing 1255 // of next pending install. 1256 mHandler.sendEmptyMessage(MCS_BOUND); 1257 } 1258 1259 break; 1260 } 1261 case MCS_GIVE_UP: { 1262 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1263 mPendingInstalls.remove(0); 1264 break; 1265 } 1266 case SEND_PENDING_BROADCAST: { 1267 String packages[]; 1268 ArrayList<String> components[]; 1269 int size = 0; 1270 int uids[]; 1271 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1272 synchronized (mPackages) { 1273 if (mPendingBroadcasts == null) { 1274 return; 1275 } 1276 size = mPendingBroadcasts.size(); 1277 if (size <= 0) { 1278 // Nothing to be done. Just return 1279 return; 1280 } 1281 packages = new String[size]; 1282 components = new ArrayList[size]; 1283 uids = new int[size]; 1284 int i = 0; // filling out the above arrays 1285 1286 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1287 int packageUserId = mPendingBroadcasts.userIdAt(n); 1288 Iterator<Map.Entry<String, ArrayList<String>>> it 1289 = mPendingBroadcasts.packagesForUserId(packageUserId) 1290 .entrySet().iterator(); 1291 while (it.hasNext() && i < size) { 1292 Map.Entry<String, ArrayList<String>> ent = it.next(); 1293 packages[i] = ent.getKey(); 1294 components[i] = ent.getValue(); 1295 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1296 uids[i] = (ps != null) 1297 ? UserHandle.getUid(packageUserId, ps.appId) 1298 : -1; 1299 i++; 1300 } 1301 } 1302 size = i; 1303 mPendingBroadcasts.clear(); 1304 } 1305 // Send broadcasts 1306 for (int i = 0; i < size; i++) { 1307 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1308 } 1309 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1310 break; 1311 } 1312 case START_CLEANING_PACKAGE: { 1313 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1314 final String packageName = (String)msg.obj; 1315 final int userId = msg.arg1; 1316 final boolean andCode = msg.arg2 != 0; 1317 synchronized (mPackages) { 1318 if (userId == UserHandle.USER_ALL) { 1319 int[] users = sUserManager.getUserIds(); 1320 for (int user : users) { 1321 mSettings.addPackageToCleanLPw( 1322 new PackageCleanItem(user, packageName, andCode)); 1323 } 1324 } else { 1325 mSettings.addPackageToCleanLPw( 1326 new PackageCleanItem(userId, packageName, andCode)); 1327 } 1328 } 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1330 startCleaningPackages(); 1331 } break; 1332 case POST_INSTALL: { 1333 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1334 PostInstallData data = mRunningInstalls.get(msg.arg1); 1335 mRunningInstalls.delete(msg.arg1); 1336 boolean deleteOld = false; 1337 1338 if (data != null) { 1339 InstallArgs args = data.args; 1340 PackageInstalledInfo res = data.res; 1341 1342 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1343 final String packageName = res.pkg.applicationInfo.packageName; 1344 res.removedInfo.sendBroadcast(false, true, false); 1345 Bundle extras = new Bundle(1); 1346 extras.putInt(Intent.EXTRA_UID, res.uid); 1347 1348 // Now that we successfully installed the package, grant runtime 1349 // permissions if requested before broadcasting the install. 1350 if ((args.installFlags 1351 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1352 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1353 args.installGrantPermissions); 1354 } 1355 1356 // Determine the set of users who are adding this 1357 // package for the first time vs. those who are seeing 1358 // an update. 1359 int[] firstUsers; 1360 int[] updateUsers = new int[0]; 1361 if (res.origUsers == null || res.origUsers.length == 0) { 1362 firstUsers = res.newUsers; 1363 } else { 1364 firstUsers = new int[0]; 1365 for (int i=0; i<res.newUsers.length; i++) { 1366 int user = res.newUsers[i]; 1367 boolean isNew = true; 1368 for (int j=0; j<res.origUsers.length; j++) { 1369 if (res.origUsers[j] == user) { 1370 isNew = false; 1371 break; 1372 } 1373 } 1374 if (isNew) { 1375 int[] newFirst = new int[firstUsers.length+1]; 1376 System.arraycopy(firstUsers, 0, newFirst, 0, 1377 firstUsers.length); 1378 newFirst[firstUsers.length] = user; 1379 firstUsers = newFirst; 1380 } else { 1381 int[] newUpdate = new int[updateUsers.length+1]; 1382 System.arraycopy(updateUsers, 0, newUpdate, 0, 1383 updateUsers.length); 1384 newUpdate[updateUsers.length] = user; 1385 updateUsers = newUpdate; 1386 } 1387 } 1388 } 1389 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1390 packageName, extras, null, null, firstUsers); 1391 final boolean update = res.removedInfo.removedPackage != null; 1392 if (update) { 1393 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1394 } 1395 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1396 packageName, extras, null, null, updateUsers); 1397 if (update) { 1398 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1399 packageName, extras, null, null, updateUsers); 1400 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1401 null, null, packageName, null, updateUsers); 1402 1403 // treat asec-hosted packages like removable media on upgrade 1404 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1405 if (DEBUG_INSTALL) { 1406 Slog.i(TAG, "upgrading pkg " + res.pkg 1407 + " is ASEC-hosted -> AVAILABLE"); 1408 } 1409 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1410 ArrayList<String> pkgList = new ArrayList<String>(1); 1411 pkgList.add(packageName); 1412 sendResourcesChangedBroadcast(true, true, 1413 pkgList,uidArray, null); 1414 } 1415 } 1416 if (res.removedInfo.args != null) { 1417 // Remove the replaced package's older resources safely now 1418 deleteOld = true; 1419 } 1420 1421 // If this app is a browser and it's newly-installed for some 1422 // users, clear any default-browser state in those users 1423 if (firstUsers.length > 0) { 1424 // the app's nature doesn't depend on the user, so we can just 1425 // check its browser nature in any user and generalize. 1426 if (packageIsBrowser(packageName, firstUsers[0])) { 1427 synchronized (mPackages) { 1428 for (int userId : firstUsers) { 1429 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1430 } 1431 } 1432 } 1433 } 1434 // Log current value of "unknown sources" setting 1435 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1436 getUnknownSourcesSettings()); 1437 } 1438 // Force a gc to clear up things 1439 Runtime.getRuntime().gc(); 1440 // We delete after a gc for applications on sdcard. 1441 if (deleteOld) { 1442 synchronized (mInstallLock) { 1443 res.removedInfo.args.doPostDeleteLI(true); 1444 } 1445 } 1446 if (args.observer != null) { 1447 try { 1448 Bundle extras = extrasForInstallResult(res); 1449 args.observer.onPackageInstalled(res.name, res.returnCode, 1450 res.returnMsg, extras); 1451 } catch (RemoteException e) { 1452 Slog.i(TAG, "Observer no longer exists."); 1453 } 1454 } 1455 } else { 1456 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1457 } 1458 } break; 1459 case UPDATED_MEDIA_STATUS: { 1460 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1461 boolean reportStatus = msg.arg1 == 1; 1462 boolean doGc = msg.arg2 == 1; 1463 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1464 if (doGc) { 1465 // Force a gc to clear up stale containers. 1466 Runtime.getRuntime().gc(); 1467 } 1468 if (msg.obj != null) { 1469 @SuppressWarnings("unchecked") 1470 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1471 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1472 // Unload containers 1473 unloadAllContainers(args); 1474 } 1475 if (reportStatus) { 1476 try { 1477 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1478 PackageHelper.getMountService().finishMediaUpdate(); 1479 } catch (RemoteException e) { 1480 Log.e(TAG, "MountService not running?"); 1481 } 1482 } 1483 } break; 1484 case WRITE_SETTINGS: { 1485 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1486 synchronized (mPackages) { 1487 removeMessages(WRITE_SETTINGS); 1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1489 mSettings.writeLPr(); 1490 mDirtyUsers.clear(); 1491 } 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1493 } break; 1494 case WRITE_PACKAGE_RESTRICTIONS: { 1495 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1496 synchronized (mPackages) { 1497 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1498 for (int userId : mDirtyUsers) { 1499 mSettings.writePackageRestrictionsLPr(userId); 1500 } 1501 mDirtyUsers.clear(); 1502 } 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1504 } break; 1505 case CHECK_PENDING_VERIFICATION: { 1506 final int verificationId = msg.arg1; 1507 final PackageVerificationState state = mPendingVerification.get(verificationId); 1508 1509 if ((state != null) && !state.timeoutExtended()) { 1510 final InstallArgs args = state.getInstallArgs(); 1511 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1512 1513 Slog.i(TAG, "Verification timed out for " + originUri); 1514 mPendingVerification.remove(verificationId); 1515 1516 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1517 1518 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1519 Slog.i(TAG, "Continuing with installation of " + originUri); 1520 state.setVerifierResponse(Binder.getCallingUid(), 1521 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1522 broadcastPackageVerified(verificationId, originUri, 1523 PackageManager.VERIFICATION_ALLOW, 1524 state.getInstallArgs().getUser()); 1525 try { 1526 ret = args.copyApk(mContainerService, true); 1527 } catch (RemoteException e) { 1528 Slog.e(TAG, "Could not contact the ContainerService"); 1529 } 1530 } else { 1531 broadcastPackageVerified(verificationId, originUri, 1532 PackageManager.VERIFICATION_REJECT, 1533 state.getInstallArgs().getUser()); 1534 } 1535 1536 processPendingInstall(args, ret); 1537 mHandler.sendEmptyMessage(MCS_UNBIND); 1538 } 1539 break; 1540 } 1541 case PACKAGE_VERIFIED: { 1542 final int verificationId = msg.arg1; 1543 1544 final PackageVerificationState state = mPendingVerification.get(verificationId); 1545 if (state == null) { 1546 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1547 break; 1548 } 1549 1550 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1551 1552 state.setVerifierResponse(response.callerUid, response.code); 1553 1554 if (state.isVerificationComplete()) { 1555 mPendingVerification.remove(verificationId); 1556 1557 final InstallArgs args = state.getInstallArgs(); 1558 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1559 1560 int ret; 1561 if (state.isInstallAllowed()) { 1562 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1563 broadcastPackageVerified(verificationId, originUri, 1564 response.code, state.getInstallArgs().getUser()); 1565 try { 1566 ret = args.copyApk(mContainerService, true); 1567 } catch (RemoteException e) { 1568 Slog.e(TAG, "Could not contact the ContainerService"); 1569 } 1570 } else { 1571 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1572 } 1573 1574 processPendingInstall(args, ret); 1575 1576 mHandler.sendEmptyMessage(MCS_UNBIND); 1577 } 1578 1579 break; 1580 } 1581 case START_INTENT_FILTER_VERIFICATIONS: { 1582 IFVerificationParams params = (IFVerificationParams) msg.obj; 1583 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1584 params.replacing, params.pkg); 1585 break; 1586 } 1587 case INTENT_FILTER_VERIFIED: { 1588 final int verificationId = msg.arg1; 1589 1590 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1591 verificationId); 1592 if (state == null) { 1593 Slog.w(TAG, "Invalid IntentFilter verification token " 1594 + verificationId + " received"); 1595 break; 1596 } 1597 1598 final int userId = state.getUserId(); 1599 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1601 "Processing IntentFilter verification with token:" 1602 + verificationId + " and userId:" + userId); 1603 1604 final IntentFilterVerificationResponse response = 1605 (IntentFilterVerificationResponse) msg.obj; 1606 1607 state.setVerifierResponse(response.callerUid, response.code); 1608 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1610 "IntentFilter verification with token:" + verificationId 1611 + " and userId:" + userId 1612 + " is settings verifier response with response code:" 1613 + response.code); 1614 1615 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1616 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1617 + response.getFailedDomainsString()); 1618 } 1619 1620 if (state.isVerificationComplete()) { 1621 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1622 } else { 1623 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1624 "IntentFilter verification with token:" + verificationId 1625 + " was not said to be complete"); 1626 } 1627 1628 break; 1629 } 1630 } 1631 } 1632 } 1633 1634 private StorageEventListener mStorageListener = new StorageEventListener() { 1635 @Override 1636 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1637 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1638 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1639 final String volumeUuid = vol.getFsUuid(); 1640 1641 // Clean up any users or apps that were removed or recreated 1642 // while this volume was missing 1643 reconcileUsers(volumeUuid); 1644 reconcileApps(volumeUuid); 1645 1646 // Clean up any install sessions that expired or were 1647 // cancelled while this volume was missing 1648 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1649 1650 loadPrivatePackages(vol); 1651 1652 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1653 unloadPrivatePackages(vol); 1654 } 1655 } 1656 1657 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1658 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1659 updateExternalMediaStatus(true, false); 1660 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1661 updateExternalMediaStatus(false, false); 1662 } 1663 } 1664 } 1665 1666 @Override 1667 public void onVolumeForgotten(String fsUuid) { 1668 if (TextUtils.isEmpty(fsUuid)) { 1669 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1670 return; 1671 } 1672 1673 // Remove any apps installed on the forgotten volume 1674 synchronized (mPackages) { 1675 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1676 for (PackageSetting ps : packages) { 1677 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1678 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1679 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1680 } 1681 1682 mSettings.onVolumeForgotten(fsUuid); 1683 mSettings.writeLPr(); 1684 } 1685 } 1686 }; 1687 1688 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1689 String[] grantedPermissions) { 1690 if (userId >= UserHandle.USER_OWNER) { 1691 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1692 } else if (userId == UserHandle.USER_ALL) { 1693 final int[] userIds; 1694 synchronized (mPackages) { 1695 userIds = UserManagerService.getInstance().getUserIds(); 1696 } 1697 for (int someUserId : userIds) { 1698 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1699 } 1700 } 1701 1702 // We could have touched GID membership, so flush out packages.list 1703 synchronized (mPackages) { 1704 mSettings.writePackageListLPr(); 1705 } 1706 } 1707 1708 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1709 String[] grantedPermissions) { 1710 SettingBase sb = (SettingBase) pkg.mExtras; 1711 if (sb == null) { 1712 return; 1713 } 1714 1715 PermissionsState permissionsState = sb.getPermissionsState(); 1716 1717 for (String permission : pkg.requestedPermissions) { 1718 BasePermission bp = mSettings.mPermissions.get(permission); 1719 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1720 || ArrayUtils.contains(grantedPermissions, permission))) { 1721 permissionsState.grantRuntimePermission(bp, userId); 1722 } 1723 } 1724 } 1725 1726 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1727 Bundle extras = null; 1728 switch (res.returnCode) { 1729 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1730 extras = new Bundle(); 1731 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1732 res.origPermission); 1733 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1734 res.origPackage); 1735 break; 1736 } 1737 case PackageManager.INSTALL_SUCCEEDED: { 1738 extras = new Bundle(); 1739 extras.putBoolean(Intent.EXTRA_REPLACING, 1740 res.removedInfo != null && res.removedInfo.removedPackage != null); 1741 break; 1742 } 1743 } 1744 return extras; 1745 } 1746 1747 void scheduleWriteSettingsLocked() { 1748 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1749 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1750 } 1751 } 1752 1753 void scheduleWritePackageRestrictionsLocked(int userId) { 1754 if (!sUserManager.exists(userId)) return; 1755 mDirtyUsers.add(userId); 1756 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1757 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1758 } 1759 } 1760 1761 public static PackageManagerService main(Context context, Installer installer, 1762 boolean factoryTest, boolean onlyCore) { 1763 PackageManagerService m = new PackageManagerService(context, installer, 1764 factoryTest, onlyCore); 1765 ServiceManager.addService("package", m); 1766 return m; 1767 } 1768 1769 static String[] splitString(String str, char sep) { 1770 int count = 1; 1771 int i = 0; 1772 while ((i=str.indexOf(sep, i)) >= 0) { 1773 count++; 1774 i++; 1775 } 1776 1777 String[] res = new String[count]; 1778 i=0; 1779 count = 0; 1780 int lastI=0; 1781 while ((i=str.indexOf(sep, i)) >= 0) { 1782 res[count] = str.substring(lastI, i); 1783 count++; 1784 i++; 1785 lastI = i; 1786 } 1787 res[count] = str.substring(lastI, str.length()); 1788 return res; 1789 } 1790 1791 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1792 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1793 Context.DISPLAY_SERVICE); 1794 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1795 } 1796 1797 public PackageManagerService(Context context, Installer installer, 1798 boolean factoryTest, boolean onlyCore) { 1799 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1800 SystemClock.uptimeMillis()); 1801 1802 if (mSdkVersion <= 0) { 1803 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1804 } 1805 1806 mContext = context; 1807 mFactoryTest = factoryTest; 1808 mOnlyCore = onlyCore; 1809 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1810 mMetrics = new DisplayMetrics(); 1811 mSettings = new Settings(mPackages); 1812 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1813 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1814 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1815 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1816 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1817 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1818 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1819 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1820 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1821 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1822 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1823 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1824 1825 // TODO: add a property to control this? 1826 long dexOptLRUThresholdInMinutes; 1827 if (mLazyDexOpt) { 1828 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1829 } else { 1830 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1831 } 1832 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1833 1834 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1835 if (separateProcesses != null && separateProcesses.length() > 0) { 1836 if ("*".equals(separateProcesses)) { 1837 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1838 mSeparateProcesses = null; 1839 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1840 } else { 1841 mDefParseFlags = 0; 1842 mSeparateProcesses = separateProcesses.split(","); 1843 Slog.w(TAG, "Running with debug.separate_processes: " 1844 + separateProcesses); 1845 } 1846 } else { 1847 mDefParseFlags = 0; 1848 mSeparateProcesses = null; 1849 } 1850 1851 mInstaller = installer; 1852 mPackageDexOptimizer = new PackageDexOptimizer(this); 1853 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1854 1855 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1856 FgThread.get().getLooper()); 1857 1858 getDefaultDisplayMetrics(context, mMetrics); 1859 1860 SystemConfig systemConfig = SystemConfig.getInstance(); 1861 mGlobalGids = systemConfig.getGlobalGids(); 1862 mSystemPermissions = systemConfig.getSystemPermissions(); 1863 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1864 1865 synchronized (mInstallLock) { 1866 // writer 1867 synchronized (mPackages) { 1868 mHandlerThread = new ServiceThread(TAG, 1869 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1870 mHandlerThread.start(); 1871 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1872 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1873 1874 File dataDir = Environment.getDataDirectory(); 1875 mAppDataDir = new File(dataDir, "data"); 1876 mAppInstallDir = new File(dataDir, "app"); 1877 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1878 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1879 mUserAppDataDir = new File(dataDir, "user"); 1880 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1881 1882 sUserManager = new UserManagerService(context, this, 1883 mInstallLock, mPackages); 1884 1885 // Propagate permission configuration in to package manager. 1886 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1887 = systemConfig.getPermissions(); 1888 for (int i=0; i<permConfig.size(); i++) { 1889 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1890 BasePermission bp = mSettings.mPermissions.get(perm.name); 1891 if (bp == null) { 1892 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1893 mSettings.mPermissions.put(perm.name, bp); 1894 } 1895 if (perm.gids != null) { 1896 bp.setGids(perm.gids, perm.perUser); 1897 } 1898 } 1899 1900 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1901 for (int i=0; i<libConfig.size(); i++) { 1902 mSharedLibraries.put(libConfig.keyAt(i), 1903 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1904 } 1905 1906 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1907 1908 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1909 mSdkVersion, mOnlyCore); 1910 1911 String customResolverActivity = Resources.getSystem().getString( 1912 R.string.config_customResolverActivity); 1913 if (TextUtils.isEmpty(customResolverActivity)) { 1914 customResolverActivity = null; 1915 } else { 1916 mCustomResolverComponentName = ComponentName.unflattenFromString( 1917 customResolverActivity); 1918 } 1919 1920 long startTime = SystemClock.uptimeMillis(); 1921 1922 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1923 startTime); 1924 1925 // Set flag to monitor and not change apk file paths when 1926 // scanning install directories. 1927 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1928 1929 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1930 1931 /** 1932 * Add everything in the in the boot class path to the 1933 * list of process files because dexopt will have been run 1934 * if necessary during zygote startup. 1935 */ 1936 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1937 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1938 1939 if (bootClassPath != null) { 1940 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1941 for (String element : bootClassPathElements) { 1942 alreadyDexOpted.add(element); 1943 } 1944 } else { 1945 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1946 } 1947 1948 if (systemServerClassPath != null) { 1949 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1950 for (String element : systemServerClassPathElements) { 1951 alreadyDexOpted.add(element); 1952 } 1953 } else { 1954 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1955 } 1956 1957 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1958 final String[] dexCodeInstructionSets = 1959 getDexCodeInstructionSets( 1960 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1961 1962 /** 1963 * Ensure all external libraries have had dexopt run on them. 1964 */ 1965 if (mSharedLibraries.size() > 0) { 1966 // NOTE: For now, we're compiling these system "shared libraries" 1967 // (and framework jars) into all available architectures. It's possible 1968 // to compile them only when we come across an app that uses them (there's 1969 // already logic for that in scanPackageLI) but that adds some complexity. 1970 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1971 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1972 final String lib = libEntry.path; 1973 if (lib == null) { 1974 continue; 1975 } 1976 1977 try { 1978 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1979 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1980 alreadyDexOpted.add(lib); 1981 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1982 } 1983 } catch (FileNotFoundException e) { 1984 Slog.w(TAG, "Library not found: " + lib); 1985 } catch (IOException e) { 1986 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1987 + e.getMessage()); 1988 } 1989 } 1990 } 1991 } 1992 1993 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1994 1995 // Gross hack for now: we know this file doesn't contain any 1996 // code, so don't dexopt it to avoid the resulting log spew. 1997 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1998 1999 // Gross hack for now: we know this file is only part of 2000 // the boot class path for art, so don't dexopt it to 2001 // avoid the resulting log spew. 2002 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2003 2004 /** 2005 * There are a number of commands implemented in Java, which 2006 * we currently need to do the dexopt on so that they can be 2007 * run from a non-root shell. 2008 */ 2009 String[] frameworkFiles = frameworkDir.list(); 2010 if (frameworkFiles != null) { 2011 // TODO: We could compile these only for the most preferred ABI. We should 2012 // first double check that the dex files for these commands are not referenced 2013 // by other system apps. 2014 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2015 for (int i=0; i<frameworkFiles.length; i++) { 2016 File libPath = new File(frameworkDir, frameworkFiles[i]); 2017 String path = libPath.getPath(); 2018 // Skip the file if we already did it. 2019 if (alreadyDexOpted.contains(path)) { 2020 continue; 2021 } 2022 // Skip the file if it is not a type we want to dexopt. 2023 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2024 continue; 2025 } 2026 try { 2027 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2028 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2029 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2030 } 2031 } catch (FileNotFoundException e) { 2032 Slog.w(TAG, "Jar not found: " + path); 2033 } catch (IOException e) { 2034 Slog.w(TAG, "Exception reading jar: " + path, e); 2035 } 2036 } 2037 } 2038 } 2039 2040 final VersionInfo ver = mSettings.getInternalVersion(); 2041 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2042 // when upgrading from pre-M, promote system app permissions from install to runtime 2043 mPromoteSystemApps = 2044 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2045 2046 // save off the names of pre-existing system packages prior to scanning; we don't 2047 // want to automatically grant runtime permissions for new system apps 2048 if (mPromoteSystemApps) { 2049 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2050 while (pkgSettingIter.hasNext()) { 2051 PackageSetting ps = pkgSettingIter.next(); 2052 if (isSystemApp(ps)) { 2053 mExistingSystemPackages.add(ps.name); 2054 } 2055 } 2056 } 2057 2058 // Collect vendor overlay packages. 2059 // (Do this before scanning any apps.) 2060 // For security and version matching reason, only consider 2061 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2062 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2063 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2064 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2065 2066 // Find base frameworks (resource packages without code). 2067 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2068 | PackageParser.PARSE_IS_SYSTEM_DIR 2069 | PackageParser.PARSE_IS_PRIVILEGED, 2070 scanFlags | SCAN_NO_DEX, 0); 2071 2072 // Collected privileged system packages. 2073 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2074 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2075 | PackageParser.PARSE_IS_SYSTEM_DIR 2076 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2077 2078 // Collect ordinary system packages. 2079 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2080 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2081 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2082 2083 // Collect all vendor packages. 2084 File vendorAppDir = new File("/vendor/app"); 2085 try { 2086 vendorAppDir = vendorAppDir.getCanonicalFile(); 2087 } catch (IOException e) { 2088 // failed to look up canonical path, continue with original one 2089 } 2090 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2091 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2092 2093 // Collect all OEM packages. 2094 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2095 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2096 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2097 2098 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2099 mInstaller.moveFiles(); 2100 2101 // Prune any system packages that no longer exist. 2102 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2103 if (!mOnlyCore) { 2104 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2105 while (psit.hasNext()) { 2106 PackageSetting ps = psit.next(); 2107 2108 /* 2109 * If this is not a system app, it can't be a 2110 * disable system app. 2111 */ 2112 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2113 continue; 2114 } 2115 2116 /* 2117 * If the package is scanned, it's not erased. 2118 */ 2119 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2120 if (scannedPkg != null) { 2121 /* 2122 * If the system app is both scanned and in the 2123 * disabled packages list, then it must have been 2124 * added via OTA. Remove it from the currently 2125 * scanned package so the previously user-installed 2126 * application can be scanned. 2127 */ 2128 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2129 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2130 + ps.name + "; removing system app. Last known codePath=" 2131 + ps.codePathString + ", installStatus=" + ps.installStatus 2132 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2133 + scannedPkg.mVersionCode); 2134 removePackageLI(ps, true); 2135 mExpectingBetter.put(ps.name, ps.codePath); 2136 } 2137 2138 continue; 2139 } 2140 2141 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2142 psit.remove(); 2143 logCriticalInfo(Log.WARN, "System package " + ps.name 2144 + " no longer exists; wiping its data"); 2145 removeDataDirsLI(null, ps.name); 2146 } else { 2147 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2148 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2149 possiblyDeletedUpdatedSystemApps.add(ps.name); 2150 } 2151 } 2152 } 2153 } 2154 2155 //look for any incomplete package installations 2156 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2157 //clean up list 2158 for(int i = 0; i < deletePkgsList.size(); i++) { 2159 //clean up here 2160 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2161 } 2162 //delete tmp files 2163 deleteTempPackageFiles(); 2164 2165 // Remove any shared userIDs that have no associated packages 2166 mSettings.pruneSharedUsersLPw(); 2167 2168 if (!mOnlyCore) { 2169 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2170 SystemClock.uptimeMillis()); 2171 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2172 2173 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2174 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2175 2176 /** 2177 * Remove disable package settings for any updated system 2178 * apps that were removed via an OTA. If they're not a 2179 * previously-updated app, remove them completely. 2180 * Otherwise, just revoke their system-level permissions. 2181 */ 2182 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2183 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2184 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2185 2186 String msg; 2187 if (deletedPkg == null) { 2188 msg = "Updated system package " + deletedAppName 2189 + " no longer exists; wiping its data"; 2190 removeDataDirsLI(null, deletedAppName); 2191 } else { 2192 msg = "Updated system app + " + deletedAppName 2193 + " no longer present; removing system privileges for " 2194 + deletedAppName; 2195 2196 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2197 2198 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2199 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2200 } 2201 logCriticalInfo(Log.WARN, msg); 2202 } 2203 2204 /** 2205 * Make sure all system apps that we expected to appear on 2206 * the userdata partition actually showed up. If they never 2207 * appeared, crawl back and revive the system version. 2208 */ 2209 for (int i = 0; i < mExpectingBetter.size(); i++) { 2210 final String packageName = mExpectingBetter.keyAt(i); 2211 if (!mPackages.containsKey(packageName)) { 2212 final File scanFile = mExpectingBetter.valueAt(i); 2213 2214 logCriticalInfo(Log.WARN, "Expected better " + packageName 2215 + " but never showed up; reverting to system"); 2216 2217 final int reparseFlags; 2218 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2219 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2220 | PackageParser.PARSE_IS_SYSTEM_DIR 2221 | PackageParser.PARSE_IS_PRIVILEGED; 2222 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2223 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2224 | PackageParser.PARSE_IS_SYSTEM_DIR; 2225 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2226 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2227 | PackageParser.PARSE_IS_SYSTEM_DIR; 2228 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2229 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2230 | PackageParser.PARSE_IS_SYSTEM_DIR; 2231 } else { 2232 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2233 continue; 2234 } 2235 2236 mSettings.enableSystemPackageLPw(packageName); 2237 2238 try { 2239 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2240 } catch (PackageManagerException e) { 2241 Slog.e(TAG, "Failed to parse original system package: " 2242 + e.getMessage()); 2243 } 2244 } 2245 } 2246 } 2247 mExpectingBetter.clear(); 2248 2249 // Now that we know all of the shared libraries, update all clients to have 2250 // the correct library paths. 2251 updateAllSharedLibrariesLPw(); 2252 2253 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2254 // NOTE: We ignore potential failures here during a system scan (like 2255 // the rest of the commands above) because there's precious little we 2256 // can do about it. A settings error is reported, though. 2257 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2258 false /* force dexopt */, false /* defer dexopt */); 2259 } 2260 2261 // Now that we know all the packages we are keeping, 2262 // read and update their last usage times. 2263 mPackageUsage.readLP(); 2264 2265 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2266 SystemClock.uptimeMillis()); 2267 Slog.i(TAG, "Time to scan packages: " 2268 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2269 + " seconds"); 2270 2271 // If the platform SDK has changed since the last time we booted, 2272 // we need to re-grant app permission to catch any new ones that 2273 // appear. This is really a hack, and means that apps can in some 2274 // cases get permissions that the user didn't initially explicitly 2275 // allow... it would be nice to have some better way to handle 2276 // this situation. 2277 int updateFlags = UPDATE_PERMISSIONS_ALL; 2278 if (ver.sdkVersion != mSdkVersion) { 2279 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2280 + mSdkVersion + "; regranting permissions for internal storage"); 2281 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2282 } 2283 updatePermissionsLPw(null, null, updateFlags); 2284 ver.sdkVersion = mSdkVersion; 2285 // clear only after permissions have been updated 2286 mExistingSystemPackages.clear(); 2287 mPromoteSystemApps = false; 2288 2289 // If this is the first boot, and it is a normal boot, then 2290 // we need to initialize the default preferred apps. 2291 if (!mRestoredSettings && !onlyCore) { 2292 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2293 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2294 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2295 } 2296 2297 // If this is first boot after an OTA, and a normal boot, then 2298 // we need to clear code cache directories. 2299 if (mIsUpgrade && !onlyCore) { 2300 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2301 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2302 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2303 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2304 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2305 } 2306 } 2307 ver.fingerprint = Build.FINGERPRINT; 2308 } 2309 2310 checkDefaultBrowser(); 2311 2312 // All the changes are done during package scanning. 2313 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2314 2315 // can downgrade to reader 2316 mSettings.writeLPr(); 2317 2318 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2319 SystemClock.uptimeMillis()); 2320 2321 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2322 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2323 2324 mInstallerService = new PackageInstallerService(context, this); 2325 2326 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2327 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2328 mIntentFilterVerifierComponent); 2329 2330 } // synchronized (mPackages) 2331 } // synchronized (mInstallLock) 2332 2333 // Now after opening every single application zip, make sure they 2334 // are all flushed. Not really needed, but keeps things nice and 2335 // tidy. 2336 Runtime.getRuntime().gc(); 2337 2338 // Expose private service for system components to use. 2339 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2340 } 2341 2342 @Override 2343 public boolean isFirstBoot() { 2344 return !mRestoredSettings; 2345 } 2346 2347 @Override 2348 public boolean isOnlyCoreApps() { 2349 return mOnlyCore; 2350 } 2351 2352 @Override 2353 public boolean isUpgrade() { 2354 return mIsUpgrade; 2355 } 2356 2357 private String getRequiredVerifierLPr() { 2358 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2359 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2360 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2361 2362 String requiredVerifier = null; 2363 2364 final int N = receivers.size(); 2365 for (int i = 0; i < N; i++) { 2366 final ResolveInfo info = receivers.get(i); 2367 2368 if (info.activityInfo == null) { 2369 continue; 2370 } 2371 2372 final String packageName = info.activityInfo.packageName; 2373 2374 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2375 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2376 continue; 2377 } 2378 2379 if (requiredVerifier != null) { 2380 throw new RuntimeException("There can be only one required verifier"); 2381 } 2382 2383 requiredVerifier = packageName; 2384 } 2385 2386 return requiredVerifier; 2387 } 2388 2389 private String getRequiredInstallerLPr() { 2390 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2391 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2392 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2393 2394 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2395 PACKAGE_MIME_TYPE, 0, 0); 2396 2397 String requiredInstaller = null; 2398 2399 final int N = installers.size(); 2400 for (int i = 0; i < N; i++) { 2401 final ResolveInfo info = installers.get(i); 2402 final String packageName = info.activityInfo.packageName; 2403 2404 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2405 continue; 2406 } 2407 2408 if (requiredInstaller != null) { 2409 throw new RuntimeException("There must be one required installer"); 2410 } 2411 2412 requiredInstaller = packageName; 2413 } 2414 2415 if (requiredInstaller == null) { 2416 throw new RuntimeException("There must be one required installer"); 2417 } 2418 2419 return requiredInstaller; 2420 } 2421 2422 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2423 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2424 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2425 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2426 2427 ComponentName verifierComponentName = null; 2428 2429 int priority = -1000; 2430 final int N = receivers.size(); 2431 for (int i = 0; i < N; i++) { 2432 final ResolveInfo info = receivers.get(i); 2433 2434 if (info.activityInfo == null) { 2435 continue; 2436 } 2437 2438 final String packageName = info.activityInfo.packageName; 2439 2440 final PackageSetting ps = mSettings.mPackages.get(packageName); 2441 if (ps == null) { 2442 continue; 2443 } 2444 2445 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2446 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2447 continue; 2448 } 2449 2450 // Select the IntentFilterVerifier with the highest priority 2451 if (priority < info.priority) { 2452 priority = info.priority; 2453 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2454 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2455 + verifierComponentName + " with priority: " + info.priority); 2456 } 2457 } 2458 2459 return verifierComponentName; 2460 } 2461 2462 private void primeDomainVerificationsLPw(int userId) { 2463 if (DEBUG_DOMAIN_VERIFICATION) { 2464 Slog.d(TAG, "Priming domain verifications in user " + userId); 2465 } 2466 2467 SystemConfig systemConfig = SystemConfig.getInstance(); 2468 ArraySet<String> packages = systemConfig.getLinkedApps(); 2469 ArraySet<String> domains = new ArraySet<String>(); 2470 2471 for (String packageName : packages) { 2472 PackageParser.Package pkg = mPackages.get(packageName); 2473 if (pkg != null) { 2474 if (!pkg.isSystemApp()) { 2475 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2476 continue; 2477 } 2478 2479 domains.clear(); 2480 for (PackageParser.Activity a : pkg.activities) { 2481 for (ActivityIntentInfo filter : a.intents) { 2482 if (hasValidDomains(filter)) { 2483 domains.addAll(filter.getHostsList()); 2484 } 2485 } 2486 } 2487 2488 if (domains.size() > 0) { 2489 if (DEBUG_DOMAIN_VERIFICATION) { 2490 Slog.v(TAG, " + " + packageName); 2491 } 2492 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2493 // state w.r.t. the formal app-linkage "no verification attempted" state; 2494 // and then 'always' in the per-user state actually used for intent resolution. 2495 final IntentFilterVerificationInfo ivi; 2496 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2497 new ArrayList<String>(domains)); 2498 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2499 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2500 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2501 } else { 2502 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2503 + "' does not handle web links"); 2504 } 2505 } else { 2506 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2507 } 2508 } 2509 2510 scheduleWritePackageRestrictionsLocked(userId); 2511 scheduleWriteSettingsLocked(); 2512 } 2513 2514 private void applyFactoryDefaultBrowserLPw(int userId) { 2515 // The default browser app's package name is stored in a string resource, 2516 // with a product-specific overlay used for vendor customization. 2517 String browserPkg = mContext.getResources().getString( 2518 com.android.internal.R.string.default_browser); 2519 if (!TextUtils.isEmpty(browserPkg)) { 2520 // non-empty string => required to be a known package 2521 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2522 if (ps == null) { 2523 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2524 browserPkg = null; 2525 } else { 2526 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2527 } 2528 } 2529 2530 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2531 // default. If there's more than one, just leave everything alone. 2532 if (browserPkg == null) { 2533 calculateDefaultBrowserLPw(userId); 2534 } 2535 } 2536 2537 private void calculateDefaultBrowserLPw(int userId) { 2538 List<String> allBrowsers = resolveAllBrowserApps(userId); 2539 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2540 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2541 } 2542 2543 private List<String> resolveAllBrowserApps(int userId) { 2544 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2545 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2546 PackageManager.MATCH_ALL, userId); 2547 2548 final int count = list.size(); 2549 List<String> result = new ArrayList<String>(count); 2550 for (int i=0; i<count; i++) { 2551 ResolveInfo info = list.get(i); 2552 if (info.activityInfo == null 2553 || !info.handleAllWebDataURI 2554 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2555 || result.contains(info.activityInfo.packageName)) { 2556 continue; 2557 } 2558 result.add(info.activityInfo.packageName); 2559 } 2560 2561 return result; 2562 } 2563 2564 private boolean packageIsBrowser(String packageName, int userId) { 2565 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2566 PackageManager.MATCH_ALL, userId); 2567 final int N = list.size(); 2568 for (int i = 0; i < N; i++) { 2569 ResolveInfo info = list.get(i); 2570 if (packageName.equals(info.activityInfo.packageName)) { 2571 return true; 2572 } 2573 } 2574 return false; 2575 } 2576 2577 private void checkDefaultBrowser() { 2578 final int myUserId = UserHandle.myUserId(); 2579 final String packageName = getDefaultBrowserPackageName(myUserId); 2580 if (packageName != null) { 2581 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2582 if (info == null) { 2583 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2584 synchronized (mPackages) { 2585 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2586 } 2587 } 2588 } 2589 } 2590 2591 @Override 2592 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2593 throws RemoteException { 2594 try { 2595 return super.onTransact(code, data, reply, flags); 2596 } catch (RuntimeException e) { 2597 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2598 Slog.wtf(TAG, "Package Manager Crash", e); 2599 } 2600 throw e; 2601 } 2602 } 2603 2604 void cleanupInstallFailedPackage(PackageSetting ps) { 2605 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2606 2607 removeDataDirsLI(ps.volumeUuid, ps.name); 2608 if (ps.codePath != null) { 2609 if (ps.codePath.isDirectory()) { 2610 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2611 } else { 2612 ps.codePath.delete(); 2613 } 2614 } 2615 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2616 if (ps.resourcePath.isDirectory()) { 2617 FileUtils.deleteContents(ps.resourcePath); 2618 } 2619 ps.resourcePath.delete(); 2620 } 2621 mSettings.removePackageLPw(ps.name); 2622 } 2623 2624 static int[] appendInts(int[] cur, int[] add) { 2625 if (add == null) return cur; 2626 if (cur == null) return add; 2627 final int N = add.length; 2628 for (int i=0; i<N; i++) { 2629 cur = appendInt(cur, add[i]); 2630 } 2631 return cur; 2632 } 2633 2634 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2635 if (!sUserManager.exists(userId)) return null; 2636 final PackageSetting ps = (PackageSetting) p.mExtras; 2637 if (ps == null) { 2638 return null; 2639 } 2640 2641 final PermissionsState permissionsState = ps.getPermissionsState(); 2642 2643 final int[] gids = permissionsState.computeGids(userId); 2644 final Set<String> permissions = permissionsState.getPermissions(userId); 2645 final PackageUserState state = ps.readUserState(userId); 2646 2647 return PackageParser.generatePackageInfo(p, gids, flags, 2648 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2649 } 2650 2651 @Override 2652 public boolean isPackageFrozen(String packageName) { 2653 synchronized (mPackages) { 2654 final PackageSetting ps = mSettings.mPackages.get(packageName); 2655 if (ps != null) { 2656 return ps.frozen; 2657 } 2658 } 2659 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2660 return true; 2661 } 2662 2663 @Override 2664 public boolean isPackageAvailable(String packageName, int userId) { 2665 if (!sUserManager.exists(userId)) return false; 2666 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2667 synchronized (mPackages) { 2668 PackageParser.Package p = mPackages.get(packageName); 2669 if (p != null) { 2670 final PackageSetting ps = (PackageSetting) p.mExtras; 2671 if (ps != null) { 2672 final PackageUserState state = ps.readUserState(userId); 2673 if (state != null) { 2674 return PackageParser.isAvailable(state); 2675 } 2676 } 2677 } 2678 } 2679 return false; 2680 } 2681 2682 @Override 2683 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2684 if (!sUserManager.exists(userId)) return null; 2685 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2686 // reader 2687 synchronized (mPackages) { 2688 PackageParser.Package p = mPackages.get(packageName); 2689 if (DEBUG_PACKAGE_INFO) 2690 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2691 if (p != null) { 2692 return generatePackageInfo(p, flags, userId); 2693 } 2694 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2695 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2696 } 2697 } 2698 return null; 2699 } 2700 2701 @Override 2702 public String[] currentToCanonicalPackageNames(String[] names) { 2703 String[] out = new String[names.length]; 2704 // reader 2705 synchronized (mPackages) { 2706 for (int i=names.length-1; i>=0; i--) { 2707 PackageSetting ps = mSettings.mPackages.get(names[i]); 2708 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2709 } 2710 } 2711 return out; 2712 } 2713 2714 @Override 2715 public String[] canonicalToCurrentPackageNames(String[] names) { 2716 String[] out = new String[names.length]; 2717 // reader 2718 synchronized (mPackages) { 2719 for (int i=names.length-1; i>=0; i--) { 2720 String cur = mSettings.mRenamedPackages.get(names[i]); 2721 out[i] = cur != null ? cur : names[i]; 2722 } 2723 } 2724 return out; 2725 } 2726 2727 @Override 2728 public int getPackageUid(String packageName, int userId) { 2729 if (!sUserManager.exists(userId)) return -1; 2730 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2731 2732 // reader 2733 synchronized (mPackages) { 2734 PackageParser.Package p = mPackages.get(packageName); 2735 if(p != null) { 2736 return UserHandle.getUid(userId, p.applicationInfo.uid); 2737 } 2738 PackageSetting ps = mSettings.mPackages.get(packageName); 2739 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2740 return -1; 2741 } 2742 p = ps.pkg; 2743 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2744 } 2745 } 2746 2747 @Override 2748 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2749 if (!sUserManager.exists(userId)) { 2750 return null; 2751 } 2752 2753 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2754 "getPackageGids"); 2755 2756 // reader 2757 synchronized (mPackages) { 2758 PackageParser.Package p = mPackages.get(packageName); 2759 if (DEBUG_PACKAGE_INFO) { 2760 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2761 } 2762 if (p != null) { 2763 PackageSetting ps = (PackageSetting) p.mExtras; 2764 return ps.getPermissionsState().computeGids(userId); 2765 } 2766 } 2767 2768 return null; 2769 } 2770 2771 static PermissionInfo generatePermissionInfo( 2772 BasePermission bp, int flags) { 2773 if (bp.perm != null) { 2774 return PackageParser.generatePermissionInfo(bp.perm, flags); 2775 } 2776 PermissionInfo pi = new PermissionInfo(); 2777 pi.name = bp.name; 2778 pi.packageName = bp.sourcePackage; 2779 pi.nonLocalizedLabel = bp.name; 2780 pi.protectionLevel = bp.protectionLevel; 2781 return pi; 2782 } 2783 2784 @Override 2785 public PermissionInfo getPermissionInfo(String name, int flags) { 2786 // reader 2787 synchronized (mPackages) { 2788 final BasePermission p = mSettings.mPermissions.get(name); 2789 if (p != null) { 2790 return generatePermissionInfo(p, flags); 2791 } 2792 return null; 2793 } 2794 } 2795 2796 @Override 2797 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2798 // reader 2799 synchronized (mPackages) { 2800 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2801 for (BasePermission p : mSettings.mPermissions.values()) { 2802 if (group == null) { 2803 if (p.perm == null || p.perm.info.group == null) { 2804 out.add(generatePermissionInfo(p, flags)); 2805 } 2806 } else { 2807 if (p.perm != null && group.equals(p.perm.info.group)) { 2808 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2809 } 2810 } 2811 } 2812 2813 if (out.size() > 0) { 2814 return out; 2815 } 2816 return mPermissionGroups.containsKey(group) ? out : null; 2817 } 2818 } 2819 2820 @Override 2821 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2822 // reader 2823 synchronized (mPackages) { 2824 return PackageParser.generatePermissionGroupInfo( 2825 mPermissionGroups.get(name), flags); 2826 } 2827 } 2828 2829 @Override 2830 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2831 // reader 2832 synchronized (mPackages) { 2833 final int N = mPermissionGroups.size(); 2834 ArrayList<PermissionGroupInfo> out 2835 = new ArrayList<PermissionGroupInfo>(N); 2836 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2837 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2838 } 2839 return out; 2840 } 2841 } 2842 2843 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2844 int userId) { 2845 if (!sUserManager.exists(userId)) return null; 2846 PackageSetting ps = mSettings.mPackages.get(packageName); 2847 if (ps != null) { 2848 if (ps.pkg == null) { 2849 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2850 flags, userId); 2851 if (pInfo != null) { 2852 return pInfo.applicationInfo; 2853 } 2854 return null; 2855 } 2856 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2857 ps.readUserState(userId), userId); 2858 } 2859 return null; 2860 } 2861 2862 private PackageInfo generatePackageInfoFromSettingsLPw(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 PackageParser.Package pkg = ps.pkg; 2868 if (pkg == null) { 2869 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2870 return null; 2871 } 2872 // Only data remains, so we aren't worried about code paths 2873 pkg = new PackageParser.Package(packageName); 2874 pkg.applicationInfo.packageName = packageName; 2875 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2876 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2877 pkg.applicationInfo.dataDir = Environment 2878 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2879 .getAbsolutePath(); 2880 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2881 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2882 } 2883 return generatePackageInfo(pkg, flags, userId); 2884 } 2885 return null; 2886 } 2887 2888 @Override 2889 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2892 // writer 2893 synchronized (mPackages) { 2894 PackageParser.Package p = mPackages.get(packageName); 2895 if (DEBUG_PACKAGE_INFO) Log.v( 2896 TAG, "getApplicationInfo " + packageName 2897 + ": " + p); 2898 if (p != null) { 2899 PackageSetting ps = mSettings.mPackages.get(packageName); 2900 if (ps == null) return null; 2901 // Note: isEnabledLP() does not apply here - always return info 2902 return PackageParser.generateApplicationInfo( 2903 p, flags, ps.readUserState(userId), userId); 2904 } 2905 if ("android".equals(packageName)||"system".equals(packageName)) { 2906 return mAndroidApplication; 2907 } 2908 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2909 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2910 } 2911 } 2912 return null; 2913 } 2914 2915 @Override 2916 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2917 final IPackageDataObserver observer) { 2918 mContext.enforceCallingOrSelfPermission( 2919 android.Manifest.permission.CLEAR_APP_CACHE, null); 2920 // Queue up an async operation since clearing cache may take a little while. 2921 mHandler.post(new Runnable() { 2922 public void run() { 2923 mHandler.removeCallbacks(this); 2924 int retCode = -1; 2925 synchronized (mInstallLock) { 2926 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2927 if (retCode < 0) { 2928 Slog.w(TAG, "Couldn't clear application caches"); 2929 } 2930 } 2931 if (observer != null) { 2932 try { 2933 observer.onRemoveCompleted(null, (retCode >= 0)); 2934 } catch (RemoteException e) { 2935 Slog.w(TAG, "RemoveException when invoking call back"); 2936 } 2937 } 2938 } 2939 }); 2940 } 2941 2942 @Override 2943 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2944 final IntentSender pi) { 2945 mContext.enforceCallingOrSelfPermission( 2946 android.Manifest.permission.CLEAR_APP_CACHE, null); 2947 // Queue up an async operation since clearing cache may take a little while. 2948 mHandler.post(new Runnable() { 2949 public void run() { 2950 mHandler.removeCallbacks(this); 2951 int retCode = -1; 2952 synchronized (mInstallLock) { 2953 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2954 if (retCode < 0) { 2955 Slog.w(TAG, "Couldn't clear application caches"); 2956 } 2957 } 2958 if(pi != null) { 2959 try { 2960 // Callback via pending intent 2961 int code = (retCode >= 0) ? 1 : 0; 2962 pi.sendIntent(null, code, null, 2963 null, null); 2964 } catch (SendIntentException e1) { 2965 Slog.i(TAG, "Failed to send pending intent"); 2966 } 2967 } 2968 } 2969 }); 2970 } 2971 2972 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2973 synchronized (mInstallLock) { 2974 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2975 throw new IOException("Failed to free enough space"); 2976 } 2977 } 2978 } 2979 2980 @Override 2981 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2982 if (!sUserManager.exists(userId)) return null; 2983 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2984 synchronized (mPackages) { 2985 PackageParser.Activity a = mActivities.mActivities.get(component); 2986 2987 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2988 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2989 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2990 if (ps == null) return null; 2991 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2992 userId); 2993 } 2994 if (mResolveComponentName.equals(component)) { 2995 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2996 new PackageUserState(), userId); 2997 } 2998 } 2999 return null; 3000 } 3001 3002 @Override 3003 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3004 String resolvedType) { 3005 synchronized (mPackages) { 3006 if (component.equals(mResolveComponentName)) { 3007 // The resolver supports EVERYTHING! 3008 return true; 3009 } 3010 PackageParser.Activity a = mActivities.mActivities.get(component); 3011 if (a == null) { 3012 return false; 3013 } 3014 for (int i=0; i<a.intents.size(); i++) { 3015 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3016 intent.getData(), intent.getCategories(), TAG) >= 0) { 3017 return true; 3018 } 3019 } 3020 return false; 3021 } 3022 } 3023 3024 @Override 3025 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3026 if (!sUserManager.exists(userId)) return null; 3027 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3028 synchronized (mPackages) { 3029 PackageParser.Activity a = mReceivers.mActivities.get(component); 3030 if (DEBUG_PACKAGE_INFO) Log.v( 3031 TAG, "getReceiverInfo " + component + ": " + a); 3032 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3033 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3034 if (ps == null) return null; 3035 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3036 userId); 3037 } 3038 } 3039 return null; 3040 } 3041 3042 @Override 3043 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3044 if (!sUserManager.exists(userId)) return null; 3045 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3046 synchronized (mPackages) { 3047 PackageParser.Service s = mServices.mServices.get(component); 3048 if (DEBUG_PACKAGE_INFO) Log.v( 3049 TAG, "getServiceInfo " + component + ": " + s); 3050 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3051 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3052 if (ps == null) return null; 3053 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3054 userId); 3055 } 3056 } 3057 return null; 3058 } 3059 3060 @Override 3061 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3062 if (!sUserManager.exists(userId)) return null; 3063 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3064 synchronized (mPackages) { 3065 PackageParser.Provider p = mProviders.mProviders.get(component); 3066 if (DEBUG_PACKAGE_INFO) Log.v( 3067 TAG, "getProviderInfo " + component + ": " + p); 3068 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3069 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3070 if (ps == null) return null; 3071 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3072 userId); 3073 } 3074 } 3075 return null; 3076 } 3077 3078 @Override 3079 public String[] getSystemSharedLibraryNames() { 3080 Set<String> libSet; 3081 synchronized (mPackages) { 3082 libSet = mSharedLibraries.keySet(); 3083 int size = libSet.size(); 3084 if (size > 0) { 3085 String[] libs = new String[size]; 3086 libSet.toArray(libs); 3087 return libs; 3088 } 3089 } 3090 return null; 3091 } 3092 3093 /** 3094 * @hide 3095 */ 3096 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3097 synchronized (mPackages) { 3098 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3099 if (lib != null && lib.apk != null) { 3100 return mPackages.get(lib.apk); 3101 } 3102 } 3103 return null; 3104 } 3105 3106 @Override 3107 public FeatureInfo[] getSystemAvailableFeatures() { 3108 Collection<FeatureInfo> featSet; 3109 synchronized (mPackages) { 3110 featSet = mAvailableFeatures.values(); 3111 int size = featSet.size(); 3112 if (size > 0) { 3113 FeatureInfo[] features = new FeatureInfo[size+1]; 3114 featSet.toArray(features); 3115 FeatureInfo fi = new FeatureInfo(); 3116 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3117 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3118 features[size] = fi; 3119 return features; 3120 } 3121 } 3122 return null; 3123 } 3124 3125 @Override 3126 public boolean hasSystemFeature(String name) { 3127 synchronized (mPackages) { 3128 return mAvailableFeatures.containsKey(name); 3129 } 3130 } 3131 3132 private void checkValidCaller(int uid, int userId) { 3133 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3134 return; 3135 3136 throw new SecurityException("Caller uid=" + uid 3137 + " is not privileged to communicate with user=" + userId); 3138 } 3139 3140 @Override 3141 public int checkPermission(String permName, String pkgName, int userId) { 3142 if (!sUserManager.exists(userId)) { 3143 return PackageManager.PERMISSION_DENIED; 3144 } 3145 3146 synchronized (mPackages) { 3147 final PackageParser.Package p = mPackages.get(pkgName); 3148 if (p != null && p.mExtras != null) { 3149 final PackageSetting ps = (PackageSetting) p.mExtras; 3150 final PermissionsState permissionsState = ps.getPermissionsState(); 3151 if (permissionsState.hasPermission(permName, userId)) { 3152 return PackageManager.PERMISSION_GRANTED; 3153 } 3154 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3155 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3156 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3157 return PackageManager.PERMISSION_GRANTED; 3158 } 3159 } 3160 } 3161 3162 return PackageManager.PERMISSION_DENIED; 3163 } 3164 3165 @Override 3166 public int checkUidPermission(String permName, int uid) { 3167 final int userId = UserHandle.getUserId(uid); 3168 3169 if (!sUserManager.exists(userId)) { 3170 return PackageManager.PERMISSION_DENIED; 3171 } 3172 3173 synchronized (mPackages) { 3174 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3175 if (obj != null) { 3176 final SettingBase ps = (SettingBase) obj; 3177 final PermissionsState permissionsState = ps.getPermissionsState(); 3178 if (permissionsState.hasPermission(permName, userId)) { 3179 return PackageManager.PERMISSION_GRANTED; 3180 } 3181 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3182 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3183 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3184 return PackageManager.PERMISSION_GRANTED; 3185 } 3186 } else { 3187 ArraySet<String> perms = mSystemPermissions.get(uid); 3188 if (perms != null) { 3189 if (perms.contains(permName)) { 3190 return PackageManager.PERMISSION_GRANTED; 3191 } 3192 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3193 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3194 return PackageManager.PERMISSION_GRANTED; 3195 } 3196 } 3197 } 3198 } 3199 3200 return PackageManager.PERMISSION_DENIED; 3201 } 3202 3203 @Override 3204 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3205 if (UserHandle.getCallingUserId() != userId) { 3206 mContext.enforceCallingPermission( 3207 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3208 "isPermissionRevokedByPolicy for user " + userId); 3209 } 3210 3211 if (checkPermission(permission, packageName, userId) 3212 == PackageManager.PERMISSION_GRANTED) { 3213 return false; 3214 } 3215 3216 final long identity = Binder.clearCallingIdentity(); 3217 try { 3218 final int flags = getPermissionFlags(permission, packageName, userId); 3219 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3220 } finally { 3221 Binder.restoreCallingIdentity(identity); 3222 } 3223 } 3224 3225 @Override 3226 public String getPermissionControllerPackageName() { 3227 synchronized (mPackages) { 3228 return mRequiredInstallerPackage; 3229 } 3230 } 3231 3232 /** 3233 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3234 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3235 * @param checkShell TODO(yamasani): 3236 * @param message the message to log on security exception 3237 */ 3238 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3239 boolean checkShell, String message) { 3240 if (userId < 0) { 3241 throw new IllegalArgumentException("Invalid userId " + userId); 3242 } 3243 if (checkShell) { 3244 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3245 } 3246 if (userId == UserHandle.getUserId(callingUid)) return; 3247 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3248 if (requireFullPermission) { 3249 mContext.enforceCallingOrSelfPermission( 3250 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3251 } else { 3252 try { 3253 mContext.enforceCallingOrSelfPermission( 3254 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3255 } catch (SecurityException se) { 3256 mContext.enforceCallingOrSelfPermission( 3257 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3258 } 3259 } 3260 } 3261 } 3262 3263 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3264 if (callingUid == Process.SHELL_UID) { 3265 if (userHandle >= 0 3266 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3267 throw new SecurityException("Shell does not have permission to access user " 3268 + userHandle); 3269 } else if (userHandle < 0) { 3270 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3271 + Debug.getCallers(3)); 3272 } 3273 } 3274 } 3275 3276 private BasePermission findPermissionTreeLP(String permName) { 3277 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3278 if (permName.startsWith(bp.name) && 3279 permName.length() > bp.name.length() && 3280 permName.charAt(bp.name.length()) == '.') { 3281 return bp; 3282 } 3283 } 3284 return null; 3285 } 3286 3287 private BasePermission checkPermissionTreeLP(String permName) { 3288 if (permName != null) { 3289 BasePermission bp = findPermissionTreeLP(permName); 3290 if (bp != null) { 3291 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3292 return bp; 3293 } 3294 throw new SecurityException("Calling uid " 3295 + Binder.getCallingUid() 3296 + " is not allowed to add to permission tree " 3297 + bp.name + " owned by uid " + bp.uid); 3298 } 3299 } 3300 throw new SecurityException("No permission tree found for " + permName); 3301 } 3302 3303 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3304 if (s1 == null) { 3305 return s2 == null; 3306 } 3307 if (s2 == null) { 3308 return false; 3309 } 3310 if (s1.getClass() != s2.getClass()) { 3311 return false; 3312 } 3313 return s1.equals(s2); 3314 } 3315 3316 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3317 if (pi1.icon != pi2.icon) return false; 3318 if (pi1.logo != pi2.logo) return false; 3319 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3320 if (!compareStrings(pi1.name, pi2.name)) return false; 3321 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3322 // We'll take care of setting this one. 3323 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3324 // These are not currently stored in settings. 3325 //if (!compareStrings(pi1.group, pi2.group)) return false; 3326 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3327 //if (pi1.labelRes != pi2.labelRes) return false; 3328 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3329 return true; 3330 } 3331 3332 int permissionInfoFootprint(PermissionInfo info) { 3333 int size = info.name.length(); 3334 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3335 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3336 return size; 3337 } 3338 3339 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3340 int size = 0; 3341 for (BasePermission perm : mSettings.mPermissions.values()) { 3342 if (perm.uid == tree.uid) { 3343 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3344 } 3345 } 3346 return size; 3347 } 3348 3349 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3350 // We calculate the max size of permissions defined by this uid and throw 3351 // if that plus the size of 'info' would exceed our stated maximum. 3352 if (tree.uid != Process.SYSTEM_UID) { 3353 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3354 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3355 throw new SecurityException("Permission tree size cap exceeded"); 3356 } 3357 } 3358 } 3359 3360 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3361 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3362 throw new SecurityException("Label must be specified in permission"); 3363 } 3364 BasePermission tree = checkPermissionTreeLP(info.name); 3365 BasePermission bp = mSettings.mPermissions.get(info.name); 3366 boolean added = bp == null; 3367 boolean changed = true; 3368 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3369 if (added) { 3370 enforcePermissionCapLocked(info, tree); 3371 bp = new BasePermission(info.name, tree.sourcePackage, 3372 BasePermission.TYPE_DYNAMIC); 3373 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3374 throw new SecurityException( 3375 "Not allowed to modify non-dynamic permission " 3376 + info.name); 3377 } else { 3378 if (bp.protectionLevel == fixedLevel 3379 && bp.perm.owner.equals(tree.perm.owner) 3380 && bp.uid == tree.uid 3381 && comparePermissionInfos(bp.perm.info, info)) { 3382 changed = false; 3383 } 3384 } 3385 bp.protectionLevel = fixedLevel; 3386 info = new PermissionInfo(info); 3387 info.protectionLevel = fixedLevel; 3388 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3389 bp.perm.info.packageName = tree.perm.info.packageName; 3390 bp.uid = tree.uid; 3391 if (added) { 3392 mSettings.mPermissions.put(info.name, bp); 3393 } 3394 if (changed) { 3395 if (!async) { 3396 mSettings.writeLPr(); 3397 } else { 3398 scheduleWriteSettingsLocked(); 3399 } 3400 } 3401 return added; 3402 } 3403 3404 @Override 3405 public boolean addPermission(PermissionInfo info) { 3406 synchronized (mPackages) { 3407 return addPermissionLocked(info, false); 3408 } 3409 } 3410 3411 @Override 3412 public boolean addPermissionAsync(PermissionInfo info) { 3413 synchronized (mPackages) { 3414 return addPermissionLocked(info, true); 3415 } 3416 } 3417 3418 @Override 3419 public void removePermission(String name) { 3420 synchronized (mPackages) { 3421 checkPermissionTreeLP(name); 3422 BasePermission bp = mSettings.mPermissions.get(name); 3423 if (bp != null) { 3424 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3425 throw new SecurityException( 3426 "Not allowed to modify non-dynamic permission " 3427 + name); 3428 } 3429 mSettings.mPermissions.remove(name); 3430 mSettings.writeLPr(); 3431 } 3432 } 3433 } 3434 3435 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3436 BasePermission bp) { 3437 int index = pkg.requestedPermissions.indexOf(bp.name); 3438 if (index == -1) { 3439 throw new SecurityException("Package " + pkg.packageName 3440 + " has not requested permission " + bp.name); 3441 } 3442 if (!bp.isRuntime() && !bp.isDevelopment()) { 3443 throw new SecurityException("Permission " + bp.name 3444 + " is not a changeable permission type"); 3445 } 3446 } 3447 3448 @Override 3449 public void grantRuntimePermission(String packageName, String name, final int userId) { 3450 if (!sUserManager.exists(userId)) { 3451 Log.e(TAG, "No such user:" + userId); 3452 return; 3453 } 3454 3455 mContext.enforceCallingOrSelfPermission( 3456 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3457 "grantRuntimePermission"); 3458 3459 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3460 "grantRuntimePermission"); 3461 3462 final int uid; 3463 final SettingBase sb; 3464 3465 synchronized (mPackages) { 3466 final PackageParser.Package pkg = mPackages.get(packageName); 3467 if (pkg == null) { 3468 throw new IllegalArgumentException("Unknown package: " + packageName); 3469 } 3470 3471 final BasePermission bp = mSettings.mPermissions.get(name); 3472 if (bp == null) { 3473 throw new IllegalArgumentException("Unknown permission: " + name); 3474 } 3475 3476 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3477 3478 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3479 sb = (SettingBase) pkg.mExtras; 3480 if (sb == null) { 3481 throw new IllegalArgumentException("Unknown package: " + packageName); 3482 } 3483 3484 final PermissionsState permissionsState = sb.getPermissionsState(); 3485 3486 final int flags = permissionsState.getPermissionFlags(name, userId); 3487 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3488 throw new SecurityException("Cannot grant system fixed permission: " 3489 + name + " for package: " + packageName); 3490 } 3491 3492 if (bp.isDevelopment()) { 3493 // Development permissions must be handled specially, since they are not 3494 // normal runtime permissions. For now they apply to all users. 3495 if (permissionsState.grantInstallPermission(bp) != 3496 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3497 scheduleWriteSettingsLocked(); 3498 } 3499 return; 3500 } 3501 3502 final int result = permissionsState.grantRuntimePermission(bp, userId); 3503 switch (result) { 3504 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3505 return; 3506 } 3507 3508 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3509 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3510 mHandler.post(new Runnable() { 3511 @Override 3512 public void run() { 3513 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3514 } 3515 }); 3516 } break; 3517 } 3518 3519 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3520 3521 // Not critical if that is lost - app has to request again. 3522 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3523 } 3524 3525 // Only need to do this if user is initialized. Otherwise it's a new user 3526 // and there are no processes running as the user yet and there's no need 3527 // to make an expensive call to remount processes for the changed permissions. 3528 if (READ_EXTERNAL_STORAGE.equals(name) 3529 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3530 final long token = Binder.clearCallingIdentity(); 3531 try { 3532 if (sUserManager.isInitialized(userId)) { 3533 MountServiceInternal mountServiceInternal = LocalServices.getService( 3534 MountServiceInternal.class); 3535 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3536 } 3537 } finally { 3538 Binder.restoreCallingIdentity(token); 3539 } 3540 } 3541 } 3542 3543 @Override 3544 public void revokeRuntimePermission(String packageName, String name, int userId) { 3545 if (!sUserManager.exists(userId)) { 3546 Log.e(TAG, "No such user:" + userId); 3547 return; 3548 } 3549 3550 mContext.enforceCallingOrSelfPermission( 3551 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3552 "revokeRuntimePermission"); 3553 3554 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3555 "revokeRuntimePermission"); 3556 3557 final int appId; 3558 3559 synchronized (mPackages) { 3560 final PackageParser.Package pkg = mPackages.get(packageName); 3561 if (pkg == null) { 3562 throw new IllegalArgumentException("Unknown package: " + packageName); 3563 } 3564 3565 final BasePermission bp = mSettings.mPermissions.get(name); 3566 if (bp == null) { 3567 throw new IllegalArgumentException("Unknown permission: " + name); 3568 } 3569 3570 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3571 3572 SettingBase sb = (SettingBase) pkg.mExtras; 3573 if (sb == null) { 3574 throw new IllegalArgumentException("Unknown package: " + packageName); 3575 } 3576 3577 final PermissionsState permissionsState = sb.getPermissionsState(); 3578 3579 final int flags = permissionsState.getPermissionFlags(name, userId); 3580 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3581 throw new SecurityException("Cannot revoke system fixed permission: " 3582 + name + " for package: " + packageName); 3583 } 3584 3585 if (bp.isDevelopment()) { 3586 // Development permissions must be handled specially, since they are not 3587 // normal runtime permissions. For now they apply to all users. 3588 if (permissionsState.revokeInstallPermission(bp) != 3589 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3590 scheduleWriteSettingsLocked(); 3591 } 3592 return; 3593 } 3594 3595 if (permissionsState.revokeRuntimePermission(bp, userId) == 3596 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3597 return; 3598 } 3599 3600 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3601 3602 // Critical, after this call app should never have the permission. 3603 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3604 3605 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3606 } 3607 3608 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3609 } 3610 3611 @Override 3612 public void resetRuntimePermissions() { 3613 mContext.enforceCallingOrSelfPermission( 3614 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3615 "revokeRuntimePermission"); 3616 3617 int callingUid = Binder.getCallingUid(); 3618 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3619 mContext.enforceCallingOrSelfPermission( 3620 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3621 "resetRuntimePermissions"); 3622 } 3623 3624 synchronized (mPackages) { 3625 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3626 for (int userId : UserManagerService.getInstance().getUserIds()) { 3627 final int packageCount = mPackages.size(); 3628 for (int i = 0; i < packageCount; i++) { 3629 PackageParser.Package pkg = mPackages.valueAt(i); 3630 if (!(pkg.mExtras instanceof PackageSetting)) { 3631 continue; 3632 } 3633 PackageSetting ps = (PackageSetting) pkg.mExtras; 3634 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3635 } 3636 } 3637 } 3638 } 3639 3640 @Override 3641 public int getPermissionFlags(String name, String packageName, int userId) { 3642 if (!sUserManager.exists(userId)) { 3643 return 0; 3644 } 3645 3646 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3647 3648 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3649 "getPermissionFlags"); 3650 3651 synchronized (mPackages) { 3652 final PackageParser.Package pkg = mPackages.get(packageName); 3653 if (pkg == null) { 3654 throw new IllegalArgumentException("Unknown package: " + packageName); 3655 } 3656 3657 final BasePermission bp = mSettings.mPermissions.get(name); 3658 if (bp == null) { 3659 throw new IllegalArgumentException("Unknown permission: " + name); 3660 } 3661 3662 SettingBase sb = (SettingBase) pkg.mExtras; 3663 if (sb == null) { 3664 throw new IllegalArgumentException("Unknown package: " + packageName); 3665 } 3666 3667 PermissionsState permissionsState = sb.getPermissionsState(); 3668 return permissionsState.getPermissionFlags(name, userId); 3669 } 3670 } 3671 3672 @Override 3673 public void updatePermissionFlags(String name, String packageName, int flagMask, 3674 int flagValues, int userId) { 3675 if (!sUserManager.exists(userId)) { 3676 return; 3677 } 3678 3679 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3680 3681 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3682 "updatePermissionFlags"); 3683 3684 // Only the system can change these flags and nothing else. 3685 if (getCallingUid() != Process.SYSTEM_UID) { 3686 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3687 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3688 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3689 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3690 } 3691 3692 synchronized (mPackages) { 3693 final PackageParser.Package pkg = mPackages.get(packageName); 3694 if (pkg == null) { 3695 throw new IllegalArgumentException("Unknown package: " + packageName); 3696 } 3697 3698 final BasePermission bp = mSettings.mPermissions.get(name); 3699 if (bp == null) { 3700 throw new IllegalArgumentException("Unknown permission: " + name); 3701 } 3702 3703 SettingBase sb = (SettingBase) pkg.mExtras; 3704 if (sb == null) { 3705 throw new IllegalArgumentException("Unknown package: " + packageName); 3706 } 3707 3708 PermissionsState permissionsState = sb.getPermissionsState(); 3709 3710 // Only the package manager can change flags for system component permissions. 3711 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3712 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3713 return; 3714 } 3715 3716 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3717 3718 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3719 // Install and runtime permissions are stored in different places, 3720 // so figure out what permission changed and persist the change. 3721 if (permissionsState.getInstallPermissionState(name) != null) { 3722 scheduleWriteSettingsLocked(); 3723 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3724 || hadState) { 3725 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3726 } 3727 } 3728 } 3729 } 3730 3731 /** 3732 * Update the permission flags for all packages and runtime permissions of a user in order 3733 * to allow device or profile owner to remove POLICY_FIXED. 3734 */ 3735 @Override 3736 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3737 if (!sUserManager.exists(userId)) { 3738 return; 3739 } 3740 3741 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3742 3743 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3744 "updatePermissionFlagsForAllApps"); 3745 3746 // Only the system can change system fixed flags. 3747 if (getCallingUid() != Process.SYSTEM_UID) { 3748 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3749 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3750 } 3751 3752 synchronized (mPackages) { 3753 boolean changed = false; 3754 final int packageCount = mPackages.size(); 3755 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3756 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3757 SettingBase sb = (SettingBase) pkg.mExtras; 3758 if (sb == null) { 3759 continue; 3760 } 3761 PermissionsState permissionsState = sb.getPermissionsState(); 3762 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3763 userId, flagMask, flagValues); 3764 } 3765 if (changed) { 3766 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3767 } 3768 } 3769 } 3770 3771 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3772 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3773 != PackageManager.PERMISSION_GRANTED 3774 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3775 != PackageManager.PERMISSION_GRANTED) { 3776 throw new SecurityException(message + " requires " 3777 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3778 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3779 } 3780 } 3781 3782 @Override 3783 public boolean shouldShowRequestPermissionRationale(String permissionName, 3784 String packageName, int userId) { 3785 if (UserHandle.getCallingUserId() != userId) { 3786 mContext.enforceCallingPermission( 3787 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3788 "canShowRequestPermissionRationale for user " + userId); 3789 } 3790 3791 final int uid = getPackageUid(packageName, userId); 3792 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3793 return false; 3794 } 3795 3796 if (checkPermission(permissionName, packageName, userId) 3797 == PackageManager.PERMISSION_GRANTED) { 3798 return false; 3799 } 3800 3801 final int flags; 3802 3803 final long identity = Binder.clearCallingIdentity(); 3804 try { 3805 flags = getPermissionFlags(permissionName, 3806 packageName, userId); 3807 } finally { 3808 Binder.restoreCallingIdentity(identity); 3809 } 3810 3811 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3812 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3813 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3814 3815 if ((flags & fixedFlags) != 0) { 3816 return false; 3817 } 3818 3819 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3820 } 3821 3822 @Override 3823 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3824 mContext.enforceCallingOrSelfPermission( 3825 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3826 "addOnPermissionsChangeListener"); 3827 3828 synchronized (mPackages) { 3829 mOnPermissionChangeListeners.addListenerLocked(listener); 3830 } 3831 } 3832 3833 @Override 3834 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3835 synchronized (mPackages) { 3836 mOnPermissionChangeListeners.removeListenerLocked(listener); 3837 } 3838 } 3839 3840 @Override 3841 public boolean isProtectedBroadcast(String actionName) { 3842 synchronized (mPackages) { 3843 return mProtectedBroadcasts.contains(actionName); 3844 } 3845 } 3846 3847 @Override 3848 public int checkSignatures(String pkg1, String pkg2) { 3849 synchronized (mPackages) { 3850 final PackageParser.Package p1 = mPackages.get(pkg1); 3851 final PackageParser.Package p2 = mPackages.get(pkg2); 3852 if (p1 == null || p1.mExtras == null 3853 || p2 == null || p2.mExtras == null) { 3854 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3855 } 3856 return compareSignatures(p1.mSignatures, p2.mSignatures); 3857 } 3858 } 3859 3860 @Override 3861 public int checkUidSignatures(int uid1, int uid2) { 3862 // Map to base uids. 3863 uid1 = UserHandle.getAppId(uid1); 3864 uid2 = UserHandle.getAppId(uid2); 3865 // reader 3866 synchronized (mPackages) { 3867 Signature[] s1; 3868 Signature[] s2; 3869 Object obj = mSettings.getUserIdLPr(uid1); 3870 if (obj != null) { 3871 if (obj instanceof SharedUserSetting) { 3872 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3873 } else if (obj instanceof PackageSetting) { 3874 s1 = ((PackageSetting)obj).signatures.mSignatures; 3875 } else { 3876 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3877 } 3878 } else { 3879 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3880 } 3881 obj = mSettings.getUserIdLPr(uid2); 3882 if (obj != null) { 3883 if (obj instanceof SharedUserSetting) { 3884 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3885 } else if (obj instanceof PackageSetting) { 3886 s2 = ((PackageSetting)obj).signatures.mSignatures; 3887 } else { 3888 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3889 } 3890 } else { 3891 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3892 } 3893 return compareSignatures(s1, s2); 3894 } 3895 } 3896 3897 private void killUid(int appId, int userId, String reason) { 3898 final long identity = Binder.clearCallingIdentity(); 3899 try { 3900 IActivityManager am = ActivityManagerNative.getDefault(); 3901 if (am != null) { 3902 try { 3903 am.killUid(appId, userId, reason); 3904 } catch (RemoteException e) { 3905 /* ignore - same process */ 3906 } 3907 } 3908 } finally { 3909 Binder.restoreCallingIdentity(identity); 3910 } 3911 } 3912 3913 /** 3914 * Compares two sets of signatures. Returns: 3915 * <br /> 3916 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3917 * <br /> 3918 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3919 * <br /> 3920 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3921 * <br /> 3922 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3923 * <br /> 3924 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3925 */ 3926 static int compareSignatures(Signature[] s1, Signature[] s2) { 3927 if (s1 == null) { 3928 return s2 == null 3929 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3930 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3931 } 3932 3933 if (s2 == null) { 3934 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3935 } 3936 3937 if (s1.length != s2.length) { 3938 return PackageManager.SIGNATURE_NO_MATCH; 3939 } 3940 3941 // Since both signature sets are of size 1, we can compare without HashSets. 3942 if (s1.length == 1) { 3943 return s1[0].equals(s2[0]) ? 3944 PackageManager.SIGNATURE_MATCH : 3945 PackageManager.SIGNATURE_NO_MATCH; 3946 } 3947 3948 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3949 for (Signature sig : s1) { 3950 set1.add(sig); 3951 } 3952 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3953 for (Signature sig : s2) { 3954 set2.add(sig); 3955 } 3956 // Make sure s2 contains all signatures in s1. 3957 if (set1.equals(set2)) { 3958 return PackageManager.SIGNATURE_MATCH; 3959 } 3960 return PackageManager.SIGNATURE_NO_MATCH; 3961 } 3962 3963 /** 3964 * If the database version for this type of package (internal storage or 3965 * external storage) is less than the version where package signatures 3966 * were updated, return true. 3967 */ 3968 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3969 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3970 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3971 } 3972 3973 /** 3974 * Used for backward compatibility to make sure any packages with 3975 * certificate chains get upgraded to the new style. {@code existingSigs} 3976 * will be in the old format (since they were stored on disk from before the 3977 * system upgrade) and {@code scannedSigs} will be in the newer format. 3978 */ 3979 private int compareSignaturesCompat(PackageSignatures existingSigs, 3980 PackageParser.Package scannedPkg) { 3981 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3982 return PackageManager.SIGNATURE_NO_MATCH; 3983 } 3984 3985 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3986 for (Signature sig : existingSigs.mSignatures) { 3987 existingSet.add(sig); 3988 } 3989 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3990 for (Signature sig : scannedPkg.mSignatures) { 3991 try { 3992 Signature[] chainSignatures = sig.getChainSignatures(); 3993 for (Signature chainSig : chainSignatures) { 3994 scannedCompatSet.add(chainSig); 3995 } 3996 } catch (CertificateEncodingException e) { 3997 scannedCompatSet.add(sig); 3998 } 3999 } 4000 /* 4001 * Make sure the expanded scanned set contains all signatures in the 4002 * existing one. 4003 */ 4004 if (scannedCompatSet.equals(existingSet)) { 4005 // Migrate the old signatures to the new scheme. 4006 existingSigs.assignSignatures(scannedPkg.mSignatures); 4007 // The new KeySets will be re-added later in the scanning process. 4008 synchronized (mPackages) { 4009 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4010 } 4011 return PackageManager.SIGNATURE_MATCH; 4012 } 4013 return PackageManager.SIGNATURE_NO_MATCH; 4014 } 4015 4016 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4017 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4018 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4019 } 4020 4021 private int compareSignaturesRecover(PackageSignatures existingSigs, 4022 PackageParser.Package scannedPkg) { 4023 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4024 return PackageManager.SIGNATURE_NO_MATCH; 4025 } 4026 4027 String msg = null; 4028 try { 4029 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4030 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4031 + scannedPkg.packageName); 4032 return PackageManager.SIGNATURE_MATCH; 4033 } 4034 } catch (CertificateException e) { 4035 msg = e.getMessage(); 4036 } 4037 4038 logCriticalInfo(Log.INFO, 4039 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4040 return PackageManager.SIGNATURE_NO_MATCH; 4041 } 4042 4043 @Override 4044 public String[] getPackagesForUid(int uid) { 4045 uid = UserHandle.getAppId(uid); 4046 // reader 4047 synchronized (mPackages) { 4048 Object obj = mSettings.getUserIdLPr(uid); 4049 if (obj instanceof SharedUserSetting) { 4050 final SharedUserSetting sus = (SharedUserSetting) obj; 4051 final int N = sus.packages.size(); 4052 final String[] res = new String[N]; 4053 final Iterator<PackageSetting> it = sus.packages.iterator(); 4054 int i = 0; 4055 while (it.hasNext()) { 4056 res[i++] = it.next().name; 4057 } 4058 return res; 4059 } else if (obj instanceof PackageSetting) { 4060 final PackageSetting ps = (PackageSetting) obj; 4061 return new String[] { ps.name }; 4062 } 4063 } 4064 return null; 4065 } 4066 4067 @Override 4068 public String getNameForUid(int uid) { 4069 // reader 4070 synchronized (mPackages) { 4071 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4072 if (obj instanceof SharedUserSetting) { 4073 final SharedUserSetting sus = (SharedUserSetting) obj; 4074 return sus.name + ":" + sus.userId; 4075 } else if (obj instanceof PackageSetting) { 4076 final PackageSetting ps = (PackageSetting) obj; 4077 return ps.name; 4078 } 4079 } 4080 return null; 4081 } 4082 4083 @Override 4084 public int getUidForSharedUser(String sharedUserName) { 4085 if(sharedUserName == null) { 4086 return -1; 4087 } 4088 // reader 4089 synchronized (mPackages) { 4090 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4091 if (suid == null) { 4092 return -1; 4093 } 4094 return suid.userId; 4095 } 4096 } 4097 4098 @Override 4099 public int getFlagsForUid(int uid) { 4100 synchronized (mPackages) { 4101 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4102 if (obj instanceof SharedUserSetting) { 4103 final SharedUserSetting sus = (SharedUserSetting) obj; 4104 return sus.pkgFlags; 4105 } else if (obj instanceof PackageSetting) { 4106 final PackageSetting ps = (PackageSetting) obj; 4107 return ps.pkgFlags; 4108 } 4109 } 4110 return 0; 4111 } 4112 4113 @Override 4114 public int getPrivateFlagsForUid(int uid) { 4115 synchronized (mPackages) { 4116 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4117 if (obj instanceof SharedUserSetting) { 4118 final SharedUserSetting sus = (SharedUserSetting) obj; 4119 return sus.pkgPrivateFlags; 4120 } else if (obj instanceof PackageSetting) { 4121 final PackageSetting ps = (PackageSetting) obj; 4122 return ps.pkgPrivateFlags; 4123 } 4124 } 4125 return 0; 4126 } 4127 4128 @Override 4129 public boolean isUidPrivileged(int uid) { 4130 uid = UserHandle.getAppId(uid); 4131 // reader 4132 synchronized (mPackages) { 4133 Object obj = mSettings.getUserIdLPr(uid); 4134 if (obj instanceof SharedUserSetting) { 4135 final SharedUserSetting sus = (SharedUserSetting) obj; 4136 final Iterator<PackageSetting> it = sus.packages.iterator(); 4137 while (it.hasNext()) { 4138 if (it.next().isPrivileged()) { 4139 return true; 4140 } 4141 } 4142 } else if (obj instanceof PackageSetting) { 4143 final PackageSetting ps = (PackageSetting) obj; 4144 return ps.isPrivileged(); 4145 } 4146 } 4147 return false; 4148 } 4149 4150 @Override 4151 public String[] getAppOpPermissionPackages(String permissionName) { 4152 synchronized (mPackages) { 4153 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4154 if (pkgs == null) { 4155 return null; 4156 } 4157 return pkgs.toArray(new String[pkgs.size()]); 4158 } 4159 } 4160 4161 @Override 4162 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4163 int flags, int userId) { 4164 if (!sUserManager.exists(userId)) return null; 4165 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4166 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4167 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4168 } 4169 4170 @Override 4171 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4172 IntentFilter filter, int match, ComponentName activity) { 4173 final int userId = UserHandle.getCallingUserId(); 4174 if (DEBUG_PREFERRED) { 4175 Log.v(TAG, "setLastChosenActivity intent=" + intent 4176 + " resolvedType=" + resolvedType 4177 + " flags=" + flags 4178 + " filter=" + filter 4179 + " match=" + match 4180 + " activity=" + activity); 4181 filter.dump(new PrintStreamPrinter(System.out), " "); 4182 } 4183 intent.setComponent(null); 4184 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4185 // Find any earlier preferred or last chosen entries and nuke them 4186 findPreferredActivity(intent, resolvedType, 4187 flags, query, 0, false, true, false, userId); 4188 // Add the new activity as the last chosen for this filter 4189 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4190 "Setting last chosen"); 4191 } 4192 4193 @Override 4194 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4195 final int userId = UserHandle.getCallingUserId(); 4196 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4197 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4198 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4199 false, false, false, userId); 4200 } 4201 4202 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4203 int flags, List<ResolveInfo> query, int userId) { 4204 if (query != null) { 4205 final int N = query.size(); 4206 if (N == 1) { 4207 return query.get(0); 4208 } else if (N > 1) { 4209 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4210 // If there is more than one activity with the same priority, 4211 // then let the user decide between them. 4212 ResolveInfo r0 = query.get(0); 4213 ResolveInfo r1 = query.get(1); 4214 if (DEBUG_INTENT_MATCHING || debug) { 4215 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4216 + r1.activityInfo.name + "=" + r1.priority); 4217 } 4218 // If the first activity has a higher priority, or a different 4219 // default, then it is always desireable to pick it. 4220 if (r0.priority != r1.priority 4221 || r0.preferredOrder != r1.preferredOrder 4222 || r0.isDefault != r1.isDefault) { 4223 return query.get(0); 4224 } 4225 // If we have saved a preference for a preferred activity for 4226 // this Intent, use that. 4227 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4228 flags, query, r0.priority, true, false, debug, userId); 4229 if (ri != null) { 4230 return ri; 4231 } 4232 if (userId != 0) { 4233 ri = new ResolveInfo(mResolveInfo); 4234 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4235 ri.activityInfo.applicationInfo = new ApplicationInfo( 4236 ri.activityInfo.applicationInfo); 4237 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4238 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4239 return ri; 4240 } 4241 return mResolveInfo; 4242 } 4243 } 4244 return null; 4245 } 4246 4247 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4248 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4249 final int N = query.size(); 4250 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4251 .get(userId); 4252 // Get the list of persistent preferred activities that handle the intent 4253 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4254 List<PersistentPreferredActivity> pprefs = ppir != null 4255 ? ppir.queryIntent(intent, resolvedType, 4256 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4257 : null; 4258 if (pprefs != null && pprefs.size() > 0) { 4259 final int M = pprefs.size(); 4260 for (int i=0; i<M; i++) { 4261 final PersistentPreferredActivity ppa = pprefs.get(i); 4262 if (DEBUG_PREFERRED || debug) { 4263 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4264 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4265 + "\n component=" + ppa.mComponent); 4266 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4267 } 4268 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4269 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4270 if (DEBUG_PREFERRED || debug) { 4271 Slog.v(TAG, "Found persistent preferred activity:"); 4272 if (ai != null) { 4273 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4274 } else { 4275 Slog.v(TAG, " null"); 4276 } 4277 } 4278 if (ai == null) { 4279 // This previously registered persistent preferred activity 4280 // component is no longer known. Ignore it and do NOT remove it. 4281 continue; 4282 } 4283 for (int j=0; j<N; j++) { 4284 final ResolveInfo ri = query.get(j); 4285 if (!ri.activityInfo.applicationInfo.packageName 4286 .equals(ai.applicationInfo.packageName)) { 4287 continue; 4288 } 4289 if (!ri.activityInfo.name.equals(ai.name)) { 4290 continue; 4291 } 4292 // Found a persistent preference that can handle the intent. 4293 if (DEBUG_PREFERRED || debug) { 4294 Slog.v(TAG, "Returning persistent preferred activity: " + 4295 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4296 } 4297 return ri; 4298 } 4299 } 4300 } 4301 return null; 4302 } 4303 4304 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4305 List<ResolveInfo> query, int priority, boolean always, 4306 boolean removeMatches, boolean debug, int userId) { 4307 if (!sUserManager.exists(userId)) return null; 4308 // writer 4309 synchronized (mPackages) { 4310 if (intent.getSelector() != null) { 4311 intent = intent.getSelector(); 4312 } 4313 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4314 4315 // Try to find a matching persistent preferred activity. 4316 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4317 debug, userId); 4318 4319 // If a persistent preferred activity matched, use it. 4320 if (pri != null) { 4321 return pri; 4322 } 4323 4324 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4325 // Get the list of preferred activities that handle the intent 4326 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4327 List<PreferredActivity> prefs = pir != null 4328 ? pir.queryIntent(intent, resolvedType, 4329 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4330 : null; 4331 if (prefs != null && prefs.size() > 0) { 4332 boolean changed = false; 4333 try { 4334 // First figure out how good the original match set is. 4335 // We will only allow preferred activities that came 4336 // from the same match quality. 4337 int match = 0; 4338 4339 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4340 4341 final int N = query.size(); 4342 for (int j=0; j<N; j++) { 4343 final ResolveInfo ri = query.get(j); 4344 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4345 + ": 0x" + Integer.toHexString(match)); 4346 if (ri.match > match) { 4347 match = ri.match; 4348 } 4349 } 4350 4351 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4352 + Integer.toHexString(match)); 4353 4354 match &= IntentFilter.MATCH_CATEGORY_MASK; 4355 final int M = prefs.size(); 4356 for (int i=0; i<M; i++) { 4357 final PreferredActivity pa = prefs.get(i); 4358 if (DEBUG_PREFERRED || debug) { 4359 Slog.v(TAG, "Checking PreferredActivity ds=" 4360 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4361 + "\n component=" + pa.mPref.mComponent); 4362 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4363 } 4364 if (pa.mPref.mMatch != match) { 4365 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4366 + Integer.toHexString(pa.mPref.mMatch)); 4367 continue; 4368 } 4369 // If it's not an "always" type preferred activity and that's what we're 4370 // looking for, skip it. 4371 if (always && !pa.mPref.mAlways) { 4372 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4373 continue; 4374 } 4375 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4376 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4377 if (DEBUG_PREFERRED || debug) { 4378 Slog.v(TAG, "Found preferred activity:"); 4379 if (ai != null) { 4380 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4381 } else { 4382 Slog.v(TAG, " null"); 4383 } 4384 } 4385 if (ai == null) { 4386 // This previously registered preferred activity 4387 // component is no longer known. Most likely an update 4388 // to the app was installed and in the new version this 4389 // component no longer exists. Clean it up by removing 4390 // it from the preferred activities list, and skip it. 4391 Slog.w(TAG, "Removing dangling preferred activity: " 4392 + pa.mPref.mComponent); 4393 pir.removeFilter(pa); 4394 changed = true; 4395 continue; 4396 } 4397 for (int j=0; j<N; j++) { 4398 final ResolveInfo ri = query.get(j); 4399 if (!ri.activityInfo.applicationInfo.packageName 4400 .equals(ai.applicationInfo.packageName)) { 4401 continue; 4402 } 4403 if (!ri.activityInfo.name.equals(ai.name)) { 4404 continue; 4405 } 4406 4407 if (removeMatches) { 4408 pir.removeFilter(pa); 4409 changed = true; 4410 if (DEBUG_PREFERRED) { 4411 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4412 } 4413 break; 4414 } 4415 4416 // Okay we found a previously set preferred or last chosen app. 4417 // If the result set is different from when this 4418 // was created, we need to clear it and re-ask the 4419 // user their preference, if we're looking for an "always" type entry. 4420 if (always && !pa.mPref.sameSet(query)) { 4421 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4422 + intent + " type " + resolvedType); 4423 if (DEBUG_PREFERRED) { 4424 Slog.v(TAG, "Removing preferred activity since set changed " 4425 + pa.mPref.mComponent); 4426 } 4427 pir.removeFilter(pa); 4428 // Re-add the filter as a "last chosen" entry (!always) 4429 PreferredActivity lastChosen = new PreferredActivity( 4430 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4431 pir.addFilter(lastChosen); 4432 changed = true; 4433 return null; 4434 } 4435 4436 // Yay! Either the set matched or we're looking for the last chosen 4437 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4438 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4439 return ri; 4440 } 4441 } 4442 } finally { 4443 if (changed) { 4444 if (DEBUG_PREFERRED) { 4445 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4446 } 4447 scheduleWritePackageRestrictionsLocked(userId); 4448 } 4449 } 4450 } 4451 } 4452 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4453 return null; 4454 } 4455 4456 /* 4457 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4458 */ 4459 @Override 4460 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4461 int targetUserId) { 4462 mContext.enforceCallingOrSelfPermission( 4463 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4464 List<CrossProfileIntentFilter> matches = 4465 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4466 if (matches != null) { 4467 int size = matches.size(); 4468 for (int i = 0; i < size; i++) { 4469 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4470 } 4471 } 4472 if (hasWebURI(intent)) { 4473 // cross-profile app linking works only towards the parent. 4474 final UserInfo parent = getProfileParent(sourceUserId); 4475 synchronized(mPackages) { 4476 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4477 intent, resolvedType, 0, sourceUserId, parent.id); 4478 return xpDomainInfo != null; 4479 } 4480 } 4481 return false; 4482 } 4483 4484 private UserInfo getProfileParent(int userId) { 4485 final long identity = Binder.clearCallingIdentity(); 4486 try { 4487 return sUserManager.getProfileParent(userId); 4488 } finally { 4489 Binder.restoreCallingIdentity(identity); 4490 } 4491 } 4492 4493 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4494 String resolvedType, int userId) { 4495 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4496 if (resolver != null) { 4497 return resolver.queryIntent(intent, resolvedType, false, userId); 4498 } 4499 return null; 4500 } 4501 4502 @Override 4503 public List<ResolveInfo> queryIntentActivities(Intent intent, 4504 String resolvedType, int flags, int userId) { 4505 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4506 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4507 ComponentName comp = intent.getComponent(); 4508 if (comp == null) { 4509 if (intent.getSelector() != null) { 4510 intent = intent.getSelector(); 4511 comp = intent.getComponent(); 4512 } 4513 } 4514 4515 if (comp != null) { 4516 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4517 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4518 if (ai != null) { 4519 final ResolveInfo ri = new ResolveInfo(); 4520 ri.activityInfo = ai; 4521 list.add(ri); 4522 } 4523 return list; 4524 } 4525 4526 // reader 4527 synchronized (mPackages) { 4528 final String pkgName = intent.getPackage(); 4529 if (pkgName == null) { 4530 List<CrossProfileIntentFilter> matchingFilters = 4531 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4532 // Check for results that need to skip the current profile. 4533 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4534 resolvedType, flags, userId); 4535 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4536 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4537 result.add(xpResolveInfo); 4538 return filterIfNotPrimaryUser(result, userId); 4539 } 4540 4541 // Check for results in the current profile. 4542 List<ResolveInfo> result = mActivities.queryIntent( 4543 intent, resolvedType, flags, userId); 4544 4545 // Check for cross profile results. 4546 xpResolveInfo = queryCrossProfileIntents( 4547 matchingFilters, intent, resolvedType, flags, userId); 4548 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4549 result.add(xpResolveInfo); 4550 Collections.sort(result, mResolvePrioritySorter); 4551 } 4552 result = filterIfNotPrimaryUser(result, userId); 4553 if (hasWebURI(intent)) { 4554 CrossProfileDomainInfo xpDomainInfo = null; 4555 final UserInfo parent = getProfileParent(userId); 4556 if (parent != null) { 4557 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4558 flags, userId, parent.id); 4559 } 4560 if (xpDomainInfo != null) { 4561 if (xpResolveInfo != null) { 4562 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4563 // in the result. 4564 result.remove(xpResolveInfo); 4565 } 4566 if (result.size() == 0) { 4567 result.add(xpDomainInfo.resolveInfo); 4568 return result; 4569 } 4570 } else if (result.size() <= 1) { 4571 return result; 4572 } 4573 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4574 xpDomainInfo, userId); 4575 Collections.sort(result, mResolvePrioritySorter); 4576 } 4577 return result; 4578 } 4579 final PackageParser.Package pkg = mPackages.get(pkgName); 4580 if (pkg != null) { 4581 return filterIfNotPrimaryUser( 4582 mActivities.queryIntentForPackage( 4583 intent, resolvedType, flags, pkg.activities, userId), 4584 userId); 4585 } 4586 return new ArrayList<ResolveInfo>(); 4587 } 4588 } 4589 4590 private static class CrossProfileDomainInfo { 4591 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4592 ResolveInfo resolveInfo; 4593 /* Best domain verification status of the activities found in the other profile */ 4594 int bestDomainVerificationStatus; 4595 } 4596 4597 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4598 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4599 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4600 sourceUserId)) { 4601 return null; 4602 } 4603 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4604 resolvedType, flags, parentUserId); 4605 4606 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4607 return null; 4608 } 4609 CrossProfileDomainInfo result = null; 4610 int size = resultTargetUser.size(); 4611 for (int i = 0; i < size; i++) { 4612 ResolveInfo riTargetUser = resultTargetUser.get(i); 4613 // Intent filter verification is only for filters that specify a host. So don't return 4614 // those that handle all web uris. 4615 if (riTargetUser.handleAllWebDataURI) { 4616 continue; 4617 } 4618 String packageName = riTargetUser.activityInfo.packageName; 4619 PackageSetting ps = mSettings.mPackages.get(packageName); 4620 if (ps == null) { 4621 continue; 4622 } 4623 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4624 int status = (int)(verificationState >> 32); 4625 if (result == null) { 4626 result = new CrossProfileDomainInfo(); 4627 result.resolveInfo = 4628 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4629 result.bestDomainVerificationStatus = status; 4630 } else { 4631 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4632 result.bestDomainVerificationStatus); 4633 } 4634 } 4635 // Don't consider matches with status NEVER across profiles. 4636 if (result != null && result.bestDomainVerificationStatus 4637 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4638 return null; 4639 } 4640 return result; 4641 } 4642 4643 /** 4644 * Verification statuses are ordered from the worse to the best, except for 4645 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4646 */ 4647 private int bestDomainVerificationStatus(int status1, int status2) { 4648 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4649 return status2; 4650 } 4651 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4652 return status1; 4653 } 4654 return (int) MathUtils.max(status1, status2); 4655 } 4656 4657 private boolean isUserEnabled(int userId) { 4658 long callingId = Binder.clearCallingIdentity(); 4659 try { 4660 UserInfo userInfo = sUserManager.getUserInfo(userId); 4661 return userInfo != null && userInfo.isEnabled(); 4662 } finally { 4663 Binder.restoreCallingIdentity(callingId); 4664 } 4665 } 4666 4667 /** 4668 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4669 * 4670 * @return filtered list 4671 */ 4672 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4673 if (userId == UserHandle.USER_OWNER) { 4674 return resolveInfos; 4675 } 4676 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4677 ResolveInfo info = resolveInfos.get(i); 4678 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4679 resolveInfos.remove(i); 4680 } 4681 } 4682 return resolveInfos; 4683 } 4684 4685 private static boolean hasWebURI(Intent intent) { 4686 if (intent.getData() == null) { 4687 return false; 4688 } 4689 final String scheme = intent.getScheme(); 4690 if (TextUtils.isEmpty(scheme)) { 4691 return false; 4692 } 4693 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4694 } 4695 4696 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4697 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4698 int userId) { 4699 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4700 4701 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4702 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4703 candidates.size()); 4704 } 4705 4706 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4707 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4708 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4709 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4710 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4711 4712 synchronized (mPackages) { 4713 final int count = candidates.size(); 4714 // First, try to use linked apps. Partition the candidates into four lists: 4715 // one for the final results, one for the "do not use ever", one for "undefined status" 4716 // and finally one for "browser app type". 4717 for (int n=0; n<count; n++) { 4718 ResolveInfo info = candidates.get(n); 4719 String packageName = info.activityInfo.packageName; 4720 PackageSetting ps = mSettings.mPackages.get(packageName); 4721 if (ps != null) { 4722 // Add to the special match all list (Browser use case) 4723 if (info.handleAllWebDataURI) { 4724 matchAllList.add(info); 4725 continue; 4726 } 4727 // Try to get the status from User settings first 4728 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4729 int status = (int)(packedStatus >> 32); 4730 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4731 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4732 if (DEBUG_DOMAIN_VERIFICATION) { 4733 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4734 + " : linkgen=" + linkGeneration); 4735 } 4736 // Use link-enabled generation as preferredOrder, i.e. 4737 // prefer newly-enabled over earlier-enabled. 4738 info.preferredOrder = linkGeneration; 4739 alwaysList.add(info); 4740 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4741 if (DEBUG_DOMAIN_VERIFICATION) { 4742 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4743 } 4744 neverList.add(info); 4745 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4746 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4747 if (DEBUG_DOMAIN_VERIFICATION) { 4748 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4749 } 4750 undefinedList.add(info); 4751 } 4752 } 4753 } 4754 // First try to add the "always" resolution(s) for the current user, if any 4755 if (alwaysList.size() > 0) { 4756 result.addAll(alwaysList); 4757 // if there is an "always" for the parent user, add it. 4758 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4759 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4760 result.add(xpDomainInfo.resolveInfo); 4761 } else { 4762 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4763 result.addAll(undefinedList); 4764 if (xpDomainInfo != null && ( 4765 xpDomainInfo.bestDomainVerificationStatus 4766 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4767 || xpDomainInfo.bestDomainVerificationStatus 4768 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4769 result.add(xpDomainInfo.resolveInfo); 4770 } 4771 // Also add Browsers (all of them or only the default one) 4772 if ((matchFlags & MATCH_ALL) != 0) { 4773 result.addAll(matchAllList); 4774 } else { 4775 // Browser/generic handling case. If there's a default browser, go straight 4776 // to that (but only if there is no other higher-priority match). 4777 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4778 int maxMatchPrio = 0; 4779 ResolveInfo defaultBrowserMatch = null; 4780 final int numCandidates = matchAllList.size(); 4781 for (int n = 0; n < numCandidates; n++) { 4782 ResolveInfo info = matchAllList.get(n); 4783 // track the highest overall match priority... 4784 if (info.priority > maxMatchPrio) { 4785 maxMatchPrio = info.priority; 4786 } 4787 // ...and the highest-priority default browser match 4788 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4789 if (defaultBrowserMatch == null 4790 || (defaultBrowserMatch.priority < info.priority)) { 4791 if (debug) { 4792 Slog.v(TAG, "Considering default browser match " + info); 4793 } 4794 defaultBrowserMatch = info; 4795 } 4796 } 4797 } 4798 if (defaultBrowserMatch != null 4799 && defaultBrowserMatch.priority >= maxMatchPrio 4800 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4801 { 4802 if (debug) { 4803 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4804 } 4805 result.add(defaultBrowserMatch); 4806 } else { 4807 result.addAll(matchAllList); 4808 } 4809 } 4810 4811 // If there is nothing selected, add all candidates and remove the ones that the user 4812 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4813 if (result.size() == 0) { 4814 result.addAll(candidates); 4815 result.removeAll(neverList); 4816 } 4817 } 4818 } 4819 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4820 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4821 result.size()); 4822 for (ResolveInfo info : result) { 4823 Slog.v(TAG, " + " + info.activityInfo); 4824 } 4825 } 4826 return result; 4827 } 4828 4829 // Returns a packed value as a long: 4830 // 4831 // high 'int'-sized word: link status: undefined/ask/never/always. 4832 // low 'int'-sized word: relative priority among 'always' results. 4833 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4834 long result = ps.getDomainVerificationStatusForUser(userId); 4835 // if none available, get the master status 4836 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4837 if (ps.getIntentFilterVerificationInfo() != null) { 4838 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4839 } 4840 } 4841 return result; 4842 } 4843 4844 private ResolveInfo querySkipCurrentProfileIntents( 4845 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4846 int flags, int sourceUserId) { 4847 if (matchingFilters != null) { 4848 int size = matchingFilters.size(); 4849 for (int i = 0; i < size; i ++) { 4850 CrossProfileIntentFilter filter = matchingFilters.get(i); 4851 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4852 // Checking if there are activities in the target user that can handle the 4853 // intent. 4854 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4855 flags, sourceUserId); 4856 if (resolveInfo != null) { 4857 return resolveInfo; 4858 } 4859 } 4860 } 4861 } 4862 return null; 4863 } 4864 4865 // Return matching ResolveInfo if any for skip current profile intent filters. 4866 private ResolveInfo queryCrossProfileIntents( 4867 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4868 int flags, int sourceUserId) { 4869 if (matchingFilters != null) { 4870 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4871 // match the same intent. For performance reasons, it is better not to 4872 // run queryIntent twice for the same userId 4873 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4874 int size = matchingFilters.size(); 4875 for (int i = 0; i < size; i++) { 4876 CrossProfileIntentFilter filter = matchingFilters.get(i); 4877 int targetUserId = filter.getTargetUserId(); 4878 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4879 && !alreadyTriedUserIds.get(targetUserId)) { 4880 // Checking if there are activities in the target user that can handle the 4881 // intent. 4882 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4883 flags, sourceUserId); 4884 if (resolveInfo != null) return resolveInfo; 4885 alreadyTriedUserIds.put(targetUserId, true); 4886 } 4887 } 4888 } 4889 return null; 4890 } 4891 4892 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4893 String resolvedType, int flags, int sourceUserId) { 4894 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4895 resolvedType, flags, filter.getTargetUserId()); 4896 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4897 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4898 } 4899 return null; 4900 } 4901 4902 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4903 int sourceUserId, int targetUserId) { 4904 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4905 String className; 4906 if (targetUserId == UserHandle.USER_OWNER) { 4907 className = FORWARD_INTENT_TO_USER_OWNER; 4908 } else { 4909 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4910 } 4911 ComponentName forwardingActivityComponentName = new ComponentName( 4912 mAndroidApplication.packageName, className); 4913 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4914 sourceUserId); 4915 if (targetUserId == UserHandle.USER_OWNER) { 4916 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4917 forwardingResolveInfo.noResourceId = true; 4918 } 4919 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4920 forwardingResolveInfo.priority = 0; 4921 forwardingResolveInfo.preferredOrder = 0; 4922 forwardingResolveInfo.match = 0; 4923 forwardingResolveInfo.isDefault = true; 4924 forwardingResolveInfo.filter = filter; 4925 forwardingResolveInfo.targetUserId = targetUserId; 4926 return forwardingResolveInfo; 4927 } 4928 4929 @Override 4930 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4931 Intent[] specifics, String[] specificTypes, Intent intent, 4932 String resolvedType, int flags, int userId) { 4933 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4934 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4935 false, "query intent activity options"); 4936 final String resultsAction = intent.getAction(); 4937 4938 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4939 | PackageManager.GET_RESOLVED_FILTER, userId); 4940 4941 if (DEBUG_INTENT_MATCHING) { 4942 Log.v(TAG, "Query " + intent + ": " + results); 4943 } 4944 4945 int specificsPos = 0; 4946 int N; 4947 4948 // todo: note that the algorithm used here is O(N^2). This 4949 // isn't a problem in our current environment, but if we start running 4950 // into situations where we have more than 5 or 10 matches then this 4951 // should probably be changed to something smarter... 4952 4953 // First we go through and resolve each of the specific items 4954 // that were supplied, taking care of removing any corresponding 4955 // duplicate items in the generic resolve list. 4956 if (specifics != null) { 4957 for (int i=0; i<specifics.length; i++) { 4958 final Intent sintent = specifics[i]; 4959 if (sintent == null) { 4960 continue; 4961 } 4962 4963 if (DEBUG_INTENT_MATCHING) { 4964 Log.v(TAG, "Specific #" + i + ": " + sintent); 4965 } 4966 4967 String action = sintent.getAction(); 4968 if (resultsAction != null && resultsAction.equals(action)) { 4969 // If this action was explicitly requested, then don't 4970 // remove things that have it. 4971 action = null; 4972 } 4973 4974 ResolveInfo ri = null; 4975 ActivityInfo ai = null; 4976 4977 ComponentName comp = sintent.getComponent(); 4978 if (comp == null) { 4979 ri = resolveIntent( 4980 sintent, 4981 specificTypes != null ? specificTypes[i] : null, 4982 flags, userId); 4983 if (ri == null) { 4984 continue; 4985 } 4986 if (ri == mResolveInfo) { 4987 // ACK! Must do something better with this. 4988 } 4989 ai = ri.activityInfo; 4990 comp = new ComponentName(ai.applicationInfo.packageName, 4991 ai.name); 4992 } else { 4993 ai = getActivityInfo(comp, flags, userId); 4994 if (ai == null) { 4995 continue; 4996 } 4997 } 4998 4999 // Look for any generic query activities that are duplicates 5000 // of this specific one, and remove them from the results. 5001 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5002 N = results.size(); 5003 int j; 5004 for (j=specificsPos; j<N; j++) { 5005 ResolveInfo sri = results.get(j); 5006 if ((sri.activityInfo.name.equals(comp.getClassName()) 5007 && sri.activityInfo.applicationInfo.packageName.equals( 5008 comp.getPackageName())) 5009 || (action != null && sri.filter.matchAction(action))) { 5010 results.remove(j); 5011 if (DEBUG_INTENT_MATCHING) Log.v( 5012 TAG, "Removing duplicate item from " + j 5013 + " due to specific " + specificsPos); 5014 if (ri == null) { 5015 ri = sri; 5016 } 5017 j--; 5018 N--; 5019 } 5020 } 5021 5022 // Add this specific item to its proper place. 5023 if (ri == null) { 5024 ri = new ResolveInfo(); 5025 ri.activityInfo = ai; 5026 } 5027 results.add(specificsPos, ri); 5028 ri.specificIndex = i; 5029 specificsPos++; 5030 } 5031 } 5032 5033 // Now we go through the remaining generic results and remove any 5034 // duplicate actions that are found here. 5035 N = results.size(); 5036 for (int i=specificsPos; i<N-1; i++) { 5037 final ResolveInfo rii = results.get(i); 5038 if (rii.filter == null) { 5039 continue; 5040 } 5041 5042 // Iterate over all of the actions of this result's intent 5043 // filter... typically this should be just one. 5044 final Iterator<String> it = rii.filter.actionsIterator(); 5045 if (it == null) { 5046 continue; 5047 } 5048 while (it.hasNext()) { 5049 final String action = it.next(); 5050 if (resultsAction != null && resultsAction.equals(action)) { 5051 // If this action was explicitly requested, then don't 5052 // remove things that have it. 5053 continue; 5054 } 5055 for (int j=i+1; j<N; j++) { 5056 final ResolveInfo rij = results.get(j); 5057 if (rij.filter != null && rij.filter.hasAction(action)) { 5058 results.remove(j); 5059 if (DEBUG_INTENT_MATCHING) Log.v( 5060 TAG, "Removing duplicate item from " + j 5061 + " due to action " + action + " at " + i); 5062 j--; 5063 N--; 5064 } 5065 } 5066 } 5067 5068 // If the caller didn't request filter information, drop it now 5069 // so we don't have to marshall/unmarshall it. 5070 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5071 rii.filter = null; 5072 } 5073 } 5074 5075 // Filter out the caller activity if so requested. 5076 if (caller != null) { 5077 N = results.size(); 5078 for (int i=0; i<N; i++) { 5079 ActivityInfo ainfo = results.get(i).activityInfo; 5080 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5081 && caller.getClassName().equals(ainfo.name)) { 5082 results.remove(i); 5083 break; 5084 } 5085 } 5086 } 5087 5088 // If the caller didn't request filter information, 5089 // drop them now so we don't have to 5090 // marshall/unmarshall it. 5091 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5092 N = results.size(); 5093 for (int i=0; i<N; i++) { 5094 results.get(i).filter = null; 5095 } 5096 } 5097 5098 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5099 return results; 5100 } 5101 5102 @Override 5103 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5104 int userId) { 5105 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5106 ComponentName comp = intent.getComponent(); 5107 if (comp == null) { 5108 if (intent.getSelector() != null) { 5109 intent = intent.getSelector(); 5110 comp = intent.getComponent(); 5111 } 5112 } 5113 if (comp != null) { 5114 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5115 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5116 if (ai != null) { 5117 ResolveInfo ri = new ResolveInfo(); 5118 ri.activityInfo = ai; 5119 list.add(ri); 5120 } 5121 return list; 5122 } 5123 5124 // reader 5125 synchronized (mPackages) { 5126 String pkgName = intent.getPackage(); 5127 if (pkgName == null) { 5128 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5129 } 5130 final PackageParser.Package pkg = mPackages.get(pkgName); 5131 if (pkg != null) { 5132 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5133 userId); 5134 } 5135 return null; 5136 } 5137 } 5138 5139 @Override 5140 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5141 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5142 if (!sUserManager.exists(userId)) return null; 5143 if (query != null) { 5144 if (query.size() >= 1) { 5145 // If there is more than one service with the same priority, 5146 // just arbitrarily pick the first one. 5147 return query.get(0); 5148 } 5149 } 5150 return null; 5151 } 5152 5153 @Override 5154 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5155 int userId) { 5156 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5157 ComponentName comp = intent.getComponent(); 5158 if (comp == null) { 5159 if (intent.getSelector() != null) { 5160 intent = intent.getSelector(); 5161 comp = intent.getComponent(); 5162 } 5163 } 5164 if (comp != null) { 5165 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5166 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5167 if (si != null) { 5168 final ResolveInfo ri = new ResolveInfo(); 5169 ri.serviceInfo = si; 5170 list.add(ri); 5171 } 5172 return list; 5173 } 5174 5175 // reader 5176 synchronized (mPackages) { 5177 String pkgName = intent.getPackage(); 5178 if (pkgName == null) { 5179 return mServices.queryIntent(intent, resolvedType, flags, userId); 5180 } 5181 final PackageParser.Package pkg = mPackages.get(pkgName); 5182 if (pkg != null) { 5183 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5184 userId); 5185 } 5186 return null; 5187 } 5188 } 5189 5190 @Override 5191 public List<ResolveInfo> queryIntentContentProviders( 5192 Intent intent, String resolvedType, int flags, int userId) { 5193 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5194 ComponentName comp = intent.getComponent(); 5195 if (comp == null) { 5196 if (intent.getSelector() != null) { 5197 intent = intent.getSelector(); 5198 comp = intent.getComponent(); 5199 } 5200 } 5201 if (comp != null) { 5202 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5203 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5204 if (pi != null) { 5205 final ResolveInfo ri = new ResolveInfo(); 5206 ri.providerInfo = pi; 5207 list.add(ri); 5208 } 5209 return list; 5210 } 5211 5212 // reader 5213 synchronized (mPackages) { 5214 String pkgName = intent.getPackage(); 5215 if (pkgName == null) { 5216 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5217 } 5218 final PackageParser.Package pkg = mPackages.get(pkgName); 5219 if (pkg != null) { 5220 return mProviders.queryIntentForPackage( 5221 intent, resolvedType, flags, pkg.providers, userId); 5222 } 5223 return null; 5224 } 5225 } 5226 5227 @Override 5228 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5229 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5230 5231 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5232 5233 // writer 5234 synchronized (mPackages) { 5235 ArrayList<PackageInfo> list; 5236 if (listUninstalled) { 5237 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5238 for (PackageSetting ps : mSettings.mPackages.values()) { 5239 PackageInfo pi; 5240 if (ps.pkg != null) { 5241 pi = generatePackageInfo(ps.pkg, flags, userId); 5242 } else { 5243 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5244 } 5245 if (pi != null) { 5246 list.add(pi); 5247 } 5248 } 5249 } else { 5250 list = new ArrayList<PackageInfo>(mPackages.size()); 5251 for (PackageParser.Package p : mPackages.values()) { 5252 PackageInfo pi = generatePackageInfo(p, flags, userId); 5253 if (pi != null) { 5254 list.add(pi); 5255 } 5256 } 5257 } 5258 5259 return new ParceledListSlice<PackageInfo>(list); 5260 } 5261 } 5262 5263 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5264 String[] permissions, boolean[] tmp, int flags, int userId) { 5265 int numMatch = 0; 5266 final PermissionsState permissionsState = ps.getPermissionsState(); 5267 for (int i=0; i<permissions.length; i++) { 5268 final String permission = permissions[i]; 5269 if (permissionsState.hasPermission(permission, userId)) { 5270 tmp[i] = true; 5271 numMatch++; 5272 } else { 5273 tmp[i] = false; 5274 } 5275 } 5276 if (numMatch == 0) { 5277 return; 5278 } 5279 PackageInfo pi; 5280 if (ps.pkg != null) { 5281 pi = generatePackageInfo(ps.pkg, flags, userId); 5282 } else { 5283 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5284 } 5285 // The above might return null in cases of uninstalled apps or install-state 5286 // skew across users/profiles. 5287 if (pi != null) { 5288 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5289 if (numMatch == permissions.length) { 5290 pi.requestedPermissions = permissions; 5291 } else { 5292 pi.requestedPermissions = new String[numMatch]; 5293 numMatch = 0; 5294 for (int i=0; i<permissions.length; i++) { 5295 if (tmp[i]) { 5296 pi.requestedPermissions[numMatch] = permissions[i]; 5297 numMatch++; 5298 } 5299 } 5300 } 5301 } 5302 list.add(pi); 5303 } 5304 } 5305 5306 @Override 5307 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5308 String[] permissions, int flags, int userId) { 5309 if (!sUserManager.exists(userId)) return null; 5310 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5311 5312 // writer 5313 synchronized (mPackages) { 5314 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5315 boolean[] tmpBools = new boolean[permissions.length]; 5316 if (listUninstalled) { 5317 for (PackageSetting ps : mSettings.mPackages.values()) { 5318 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5319 } 5320 } else { 5321 for (PackageParser.Package pkg : mPackages.values()) { 5322 PackageSetting ps = (PackageSetting)pkg.mExtras; 5323 if (ps != null) { 5324 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5325 userId); 5326 } 5327 } 5328 } 5329 5330 return new ParceledListSlice<PackageInfo>(list); 5331 } 5332 } 5333 5334 @Override 5335 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5336 if (!sUserManager.exists(userId)) return null; 5337 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5338 5339 // writer 5340 synchronized (mPackages) { 5341 ArrayList<ApplicationInfo> list; 5342 if (listUninstalled) { 5343 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5344 for (PackageSetting ps : mSettings.mPackages.values()) { 5345 ApplicationInfo ai; 5346 if (ps.pkg != null) { 5347 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5348 ps.readUserState(userId), userId); 5349 } else { 5350 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5351 } 5352 if (ai != null) { 5353 list.add(ai); 5354 } 5355 } 5356 } else { 5357 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5358 for (PackageParser.Package p : mPackages.values()) { 5359 if (p.mExtras != null) { 5360 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5361 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5362 if (ai != null) { 5363 list.add(ai); 5364 } 5365 } 5366 } 5367 } 5368 5369 return new ParceledListSlice<ApplicationInfo>(list); 5370 } 5371 } 5372 5373 public List<ApplicationInfo> getPersistentApplications(int flags) { 5374 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5375 5376 // reader 5377 synchronized (mPackages) { 5378 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5379 final int userId = UserHandle.getCallingUserId(); 5380 while (i.hasNext()) { 5381 final PackageParser.Package p = i.next(); 5382 if (p.applicationInfo != null 5383 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5384 && (!mSafeMode || isSystemApp(p))) { 5385 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5386 if (ps != null) { 5387 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5388 ps.readUserState(userId), userId); 5389 if (ai != null) { 5390 finalList.add(ai); 5391 } 5392 } 5393 } 5394 } 5395 } 5396 5397 return finalList; 5398 } 5399 5400 @Override 5401 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5402 if (!sUserManager.exists(userId)) return null; 5403 // reader 5404 synchronized (mPackages) { 5405 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5406 PackageSetting ps = provider != null 5407 ? mSettings.mPackages.get(provider.owner.packageName) 5408 : null; 5409 return ps != null 5410 && mSettings.isEnabledLPr(provider.info, flags, userId) 5411 && (!mSafeMode || (provider.info.applicationInfo.flags 5412 &ApplicationInfo.FLAG_SYSTEM) != 0) 5413 ? PackageParser.generateProviderInfo(provider, flags, 5414 ps.readUserState(userId), userId) 5415 : null; 5416 } 5417 } 5418 5419 /** 5420 * @deprecated 5421 */ 5422 @Deprecated 5423 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5424 // reader 5425 synchronized (mPackages) { 5426 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5427 .entrySet().iterator(); 5428 final int userId = UserHandle.getCallingUserId(); 5429 while (i.hasNext()) { 5430 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5431 PackageParser.Provider p = entry.getValue(); 5432 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5433 5434 if (ps != null && p.syncable 5435 && (!mSafeMode || (p.info.applicationInfo.flags 5436 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5437 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5438 ps.readUserState(userId), userId); 5439 if (info != null) { 5440 outNames.add(entry.getKey()); 5441 outInfo.add(info); 5442 } 5443 } 5444 } 5445 } 5446 } 5447 5448 @Override 5449 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5450 int uid, int flags) { 5451 ArrayList<ProviderInfo> finalList = null; 5452 // reader 5453 synchronized (mPackages) { 5454 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5455 final int userId = processName != null ? 5456 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5457 while (i.hasNext()) { 5458 final PackageParser.Provider p = i.next(); 5459 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5460 if (ps != null && p.info.authority != null 5461 && (processName == null 5462 || (p.info.processName.equals(processName) 5463 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5464 && mSettings.isEnabledLPr(p.info, flags, userId) 5465 && (!mSafeMode 5466 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5467 if (finalList == null) { 5468 finalList = new ArrayList<ProviderInfo>(3); 5469 } 5470 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5471 ps.readUserState(userId), userId); 5472 if (info != null) { 5473 finalList.add(info); 5474 } 5475 } 5476 } 5477 } 5478 5479 if (finalList != null) { 5480 Collections.sort(finalList, mProviderInitOrderSorter); 5481 return new ParceledListSlice<ProviderInfo>(finalList); 5482 } 5483 5484 return null; 5485 } 5486 5487 @Override 5488 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5489 int flags) { 5490 // reader 5491 synchronized (mPackages) { 5492 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5493 return PackageParser.generateInstrumentationInfo(i, flags); 5494 } 5495 } 5496 5497 @Override 5498 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5499 int flags) { 5500 ArrayList<InstrumentationInfo> finalList = 5501 new ArrayList<InstrumentationInfo>(); 5502 5503 // reader 5504 synchronized (mPackages) { 5505 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5506 while (i.hasNext()) { 5507 final PackageParser.Instrumentation p = i.next(); 5508 if (targetPackage == null 5509 || targetPackage.equals(p.info.targetPackage)) { 5510 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5511 flags); 5512 if (ii != null) { 5513 finalList.add(ii); 5514 } 5515 } 5516 } 5517 } 5518 5519 return finalList; 5520 } 5521 5522 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5523 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5524 if (overlays == null) { 5525 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5526 return; 5527 } 5528 for (PackageParser.Package opkg : overlays.values()) { 5529 // Not much to do if idmap fails: we already logged the error 5530 // and we certainly don't want to abort installation of pkg simply 5531 // because an overlay didn't fit properly. For these reasons, 5532 // ignore the return value of createIdmapForPackagePairLI. 5533 createIdmapForPackagePairLI(pkg, opkg); 5534 } 5535 } 5536 5537 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5538 PackageParser.Package opkg) { 5539 if (!opkg.mTrustedOverlay) { 5540 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5541 opkg.baseCodePath + ": overlay not trusted"); 5542 return false; 5543 } 5544 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5545 if (overlaySet == null) { 5546 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5547 opkg.baseCodePath + " but target package has no known overlays"); 5548 return false; 5549 } 5550 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5551 // TODO: generate idmap for split APKs 5552 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5553 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5554 + opkg.baseCodePath); 5555 return false; 5556 } 5557 PackageParser.Package[] overlayArray = 5558 overlaySet.values().toArray(new PackageParser.Package[0]); 5559 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5560 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5561 return p1.mOverlayPriority - p2.mOverlayPriority; 5562 } 5563 }; 5564 Arrays.sort(overlayArray, cmp); 5565 5566 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5567 int i = 0; 5568 for (PackageParser.Package p : overlayArray) { 5569 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5570 } 5571 return true; 5572 } 5573 5574 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5575 final File[] files = dir.listFiles(); 5576 if (ArrayUtils.isEmpty(files)) { 5577 Log.d(TAG, "No files in app dir " + dir); 5578 return; 5579 } 5580 5581 if (DEBUG_PACKAGE_SCANNING) { 5582 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5583 + " flags=0x" + Integer.toHexString(parseFlags)); 5584 } 5585 5586 for (File file : files) { 5587 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5588 && !PackageInstallerService.isStageName(file.getName()); 5589 if (!isPackage) { 5590 // Ignore entries which are not packages 5591 continue; 5592 } 5593 try { 5594 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5595 scanFlags, currentTime, null); 5596 } catch (PackageManagerException e) { 5597 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5598 5599 // Delete invalid userdata apps 5600 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5601 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5602 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5603 if (file.isDirectory()) { 5604 mInstaller.rmPackageDir(file.getAbsolutePath()); 5605 } else { 5606 file.delete(); 5607 } 5608 } 5609 } 5610 } 5611 } 5612 5613 private static File getSettingsProblemFile() { 5614 File dataDir = Environment.getDataDirectory(); 5615 File systemDir = new File(dataDir, "system"); 5616 File fname = new File(systemDir, "uiderrors.txt"); 5617 return fname; 5618 } 5619 5620 static void reportSettingsProblem(int priority, String msg) { 5621 logCriticalInfo(priority, msg); 5622 } 5623 5624 static void logCriticalInfo(int priority, String msg) { 5625 Slog.println(priority, TAG, msg); 5626 EventLogTags.writePmCriticalInfo(msg); 5627 try { 5628 File fname = getSettingsProblemFile(); 5629 FileOutputStream out = new FileOutputStream(fname, true); 5630 PrintWriter pw = new FastPrintWriter(out); 5631 SimpleDateFormat formatter = new SimpleDateFormat(); 5632 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5633 pw.println(dateString + ": " + msg); 5634 pw.close(); 5635 FileUtils.setPermissions( 5636 fname.toString(), 5637 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5638 -1, -1); 5639 } catch (java.io.IOException e) { 5640 } 5641 } 5642 5643 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5644 PackageParser.Package pkg, File srcFile, int parseFlags) 5645 throws PackageManagerException { 5646 if (ps != null 5647 && ps.codePath.equals(srcFile) 5648 && ps.timeStamp == srcFile.lastModified() 5649 && !isCompatSignatureUpdateNeeded(pkg) 5650 && !isRecoverSignatureUpdateNeeded(pkg)) { 5651 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5652 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5653 ArraySet<PublicKey> signingKs; 5654 synchronized (mPackages) { 5655 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5656 } 5657 if (ps.signatures.mSignatures != null 5658 && ps.signatures.mSignatures.length != 0 5659 && signingKs != null) { 5660 // Optimization: reuse the existing cached certificates 5661 // if the package appears to be unchanged. 5662 pkg.mSignatures = ps.signatures.mSignatures; 5663 pkg.mSigningKeys = signingKs; 5664 return; 5665 } 5666 5667 Slog.w(TAG, "PackageSetting for " + ps.name 5668 + " is missing signatures. Collecting certs again to recover them."); 5669 } else { 5670 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5671 } 5672 5673 try { 5674 pp.collectCertificates(pkg, parseFlags); 5675 pp.collectManifestDigest(pkg); 5676 } catch (PackageParserException e) { 5677 throw PackageManagerException.from(e); 5678 } 5679 } 5680 5681 /* 5682 * Scan a package and return the newly parsed package. 5683 * Returns null in case of errors and the error code is stored in mLastScanError 5684 */ 5685 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5686 long currentTime, UserHandle user) throws PackageManagerException { 5687 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5688 parseFlags |= mDefParseFlags; 5689 PackageParser pp = new PackageParser(); 5690 pp.setSeparateProcesses(mSeparateProcesses); 5691 pp.setOnlyCoreApps(mOnlyCore); 5692 pp.setDisplayMetrics(mMetrics); 5693 5694 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5695 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5696 } 5697 5698 final PackageParser.Package pkg; 5699 try { 5700 pkg = pp.parsePackage(scanFile, parseFlags); 5701 } catch (PackageParserException e) { 5702 throw PackageManagerException.from(e); 5703 } 5704 5705 PackageSetting ps = null; 5706 PackageSetting updatedPkg; 5707 // reader 5708 synchronized (mPackages) { 5709 // Look to see if we already know about this package. 5710 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5711 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5712 // This package has been renamed to its original name. Let's 5713 // use that. 5714 ps = mSettings.peekPackageLPr(oldName); 5715 } 5716 // If there was no original package, see one for the real package name. 5717 if (ps == null) { 5718 ps = mSettings.peekPackageLPr(pkg.packageName); 5719 } 5720 // Check to see if this package could be hiding/updating a system 5721 // package. Must look for it either under the original or real 5722 // package name depending on our state. 5723 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5724 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5725 } 5726 boolean updatedPkgBetter = false; 5727 // First check if this is a system package that may involve an update 5728 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5729 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5730 // it needs to drop FLAG_PRIVILEGED. 5731 if (locationIsPrivileged(scanFile)) { 5732 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5733 } else { 5734 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5735 } 5736 5737 if (ps != null && !ps.codePath.equals(scanFile)) { 5738 // The path has changed from what was last scanned... check the 5739 // version of the new path against what we have stored to determine 5740 // what to do. 5741 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5742 if (pkg.mVersionCode <= ps.versionCode) { 5743 // The system package has been updated and the code path does not match 5744 // Ignore entry. Skip it. 5745 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5746 + " ignored: updated version " + ps.versionCode 5747 + " better than this " + pkg.mVersionCode); 5748 if (!updatedPkg.codePath.equals(scanFile)) { 5749 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5750 + ps.name + " changing from " + updatedPkg.codePathString 5751 + " to " + scanFile); 5752 updatedPkg.codePath = scanFile; 5753 updatedPkg.codePathString = scanFile.toString(); 5754 updatedPkg.resourcePath = scanFile; 5755 updatedPkg.resourcePathString = scanFile.toString(); 5756 } 5757 updatedPkg.pkg = pkg; 5758 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5759 "Package " + ps.name + " at " + scanFile 5760 + " ignored: updated version " + ps.versionCode 5761 + " better than this " + pkg.mVersionCode); 5762 } else { 5763 // The current app on the system partition is better than 5764 // what we have updated to on the data partition; switch 5765 // back to the system partition version. 5766 // At this point, its safely assumed that package installation for 5767 // apps in system partition will go through. If not there won't be a working 5768 // version of the app 5769 // writer 5770 synchronized (mPackages) { 5771 // Just remove the loaded entries from package lists. 5772 mPackages.remove(ps.name); 5773 } 5774 5775 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5776 + " reverting from " + ps.codePathString 5777 + ": new version " + pkg.mVersionCode 5778 + " better than installed " + ps.versionCode); 5779 5780 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5781 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5782 synchronized (mInstallLock) { 5783 args.cleanUpResourcesLI(); 5784 } 5785 synchronized (mPackages) { 5786 mSettings.enableSystemPackageLPw(ps.name); 5787 } 5788 updatedPkgBetter = true; 5789 } 5790 } 5791 } 5792 5793 if (updatedPkg != null) { 5794 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5795 // initially 5796 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5797 5798 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5799 // flag set initially 5800 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5801 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5802 } 5803 } 5804 5805 // Verify certificates against what was last scanned 5806 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5807 5808 /* 5809 * A new system app appeared, but we already had a non-system one of the 5810 * same name installed earlier. 5811 */ 5812 boolean shouldHideSystemApp = false; 5813 if (updatedPkg == null && ps != null 5814 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5815 /* 5816 * Check to make sure the signatures match first. If they don't, 5817 * wipe the installed application and its data. 5818 */ 5819 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5820 != PackageManager.SIGNATURE_MATCH) { 5821 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5822 + " signatures don't match existing userdata copy; removing"); 5823 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5824 ps = null; 5825 } else { 5826 /* 5827 * If the newly-added system app is an older version than the 5828 * already installed version, hide it. It will be scanned later 5829 * and re-added like an update. 5830 */ 5831 if (pkg.mVersionCode <= ps.versionCode) { 5832 shouldHideSystemApp = true; 5833 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5834 + " but new version " + pkg.mVersionCode + " better than installed " 5835 + ps.versionCode + "; hiding system"); 5836 } else { 5837 /* 5838 * The newly found system app is a newer version that the 5839 * one previously installed. Simply remove the 5840 * already-installed application and replace it with our own 5841 * while keeping the application data. 5842 */ 5843 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5844 + " reverting from " + ps.codePathString + ": new version " 5845 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5846 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5847 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5848 synchronized (mInstallLock) { 5849 args.cleanUpResourcesLI(); 5850 } 5851 } 5852 } 5853 } 5854 5855 // The apk is forward locked (not public) if its code and resources 5856 // are kept in different files. (except for app in either system or 5857 // vendor path). 5858 // TODO grab this value from PackageSettings 5859 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5860 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5861 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5862 } 5863 } 5864 5865 // TODO: extend to support forward-locked splits 5866 String resourcePath = null; 5867 String baseResourcePath = null; 5868 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5869 if (ps != null && ps.resourcePathString != null) { 5870 resourcePath = ps.resourcePathString; 5871 baseResourcePath = ps.resourcePathString; 5872 } else { 5873 // Should not happen at all. Just log an error. 5874 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5875 } 5876 } else { 5877 resourcePath = pkg.codePath; 5878 baseResourcePath = pkg.baseCodePath; 5879 } 5880 5881 // Set application objects path explicitly. 5882 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5883 pkg.applicationInfo.setCodePath(pkg.codePath); 5884 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5885 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5886 pkg.applicationInfo.setResourcePath(resourcePath); 5887 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5888 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5889 5890 // Note that we invoke the following method only if we are about to unpack an application 5891 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5892 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5893 5894 /* 5895 * If the system app should be overridden by a previously installed 5896 * data, hide the system app now and let the /data/app scan pick it up 5897 * again. 5898 */ 5899 if (shouldHideSystemApp) { 5900 synchronized (mPackages) { 5901 /* 5902 * We have to grant systems permissions before we hide, because 5903 * grantPermissions will assume the package update is trying to 5904 * expand its permissions. 5905 */ 5906 grantPermissionsLPw(pkg, true, pkg.packageName); 5907 mSettings.disableSystemPackageLPw(pkg.packageName); 5908 } 5909 } 5910 5911 return scannedPkg; 5912 } 5913 5914 private static String fixProcessName(String defProcessName, 5915 String processName, int uid) { 5916 if (processName == null) { 5917 return defProcessName; 5918 } 5919 return processName; 5920 } 5921 5922 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5923 throws PackageManagerException { 5924 if (pkgSetting.signatures.mSignatures != null) { 5925 // Already existing package. Make sure signatures match 5926 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5927 == PackageManager.SIGNATURE_MATCH; 5928 if (!match) { 5929 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5930 == PackageManager.SIGNATURE_MATCH; 5931 } 5932 if (!match) { 5933 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5934 == PackageManager.SIGNATURE_MATCH; 5935 } 5936 if (!match) { 5937 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5938 + pkg.packageName + " signatures do not match the " 5939 + "previously installed version; ignoring!"); 5940 } 5941 } 5942 5943 // Check for shared user signatures 5944 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5945 // Already existing package. Make sure signatures match 5946 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5947 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5948 if (!match) { 5949 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5950 == PackageManager.SIGNATURE_MATCH; 5951 } 5952 if (!match) { 5953 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5954 == PackageManager.SIGNATURE_MATCH; 5955 } 5956 if (!match) { 5957 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5958 "Package " + pkg.packageName 5959 + " has no signatures that match those in shared user " 5960 + pkgSetting.sharedUser.name + "; ignoring!"); 5961 } 5962 } 5963 } 5964 5965 /** 5966 * Enforces that only the system UID or root's UID can call a method exposed 5967 * via Binder. 5968 * 5969 * @param message used as message if SecurityException is thrown 5970 * @throws SecurityException if the caller is not system or root 5971 */ 5972 private static final void enforceSystemOrRoot(String message) { 5973 final int uid = Binder.getCallingUid(); 5974 if (uid != Process.SYSTEM_UID && uid != 0) { 5975 throw new SecurityException(message); 5976 } 5977 } 5978 5979 @Override 5980 public void performBootDexOpt() { 5981 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5982 5983 // Before everything else, see whether we need to fstrim. 5984 try { 5985 IMountService ms = PackageHelper.getMountService(); 5986 if (ms != null) { 5987 final boolean isUpgrade = isUpgrade(); 5988 boolean doTrim = isUpgrade; 5989 if (doTrim) { 5990 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5991 } else { 5992 final long interval = android.provider.Settings.Global.getLong( 5993 mContext.getContentResolver(), 5994 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5995 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5996 if (interval > 0) { 5997 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5998 if (timeSinceLast > interval) { 5999 doTrim = true; 6000 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6001 + "; running immediately"); 6002 } 6003 } 6004 } 6005 if (doTrim) { 6006 if (!isFirstBoot()) { 6007 try { 6008 ActivityManagerNative.getDefault().showBootMessage( 6009 mContext.getResources().getString( 6010 R.string.android_upgrading_fstrim), true); 6011 } catch (RemoteException e) { 6012 } 6013 } 6014 ms.runMaintenance(); 6015 } 6016 } else { 6017 Slog.e(TAG, "Mount service unavailable!"); 6018 } 6019 } catch (RemoteException e) { 6020 // Can't happen; MountService is local 6021 } 6022 6023 final ArraySet<PackageParser.Package> pkgs; 6024 synchronized (mPackages) { 6025 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6026 } 6027 6028 if (pkgs != null) { 6029 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6030 // in case the device runs out of space. 6031 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6032 // Give priority to core apps. 6033 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6034 PackageParser.Package pkg = it.next(); 6035 if (pkg.coreApp) { 6036 if (DEBUG_DEXOPT) { 6037 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6038 } 6039 sortedPkgs.add(pkg); 6040 it.remove(); 6041 } 6042 } 6043 // Give priority to system apps that listen for pre boot complete. 6044 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6045 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6046 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6047 PackageParser.Package pkg = it.next(); 6048 if (pkgNames.contains(pkg.packageName)) { 6049 if (DEBUG_DEXOPT) { 6050 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6051 } 6052 sortedPkgs.add(pkg); 6053 it.remove(); 6054 } 6055 } 6056 // Give priority to system apps. 6057 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6058 PackageParser.Package pkg = it.next(); 6059 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6060 if (DEBUG_DEXOPT) { 6061 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6062 } 6063 sortedPkgs.add(pkg); 6064 it.remove(); 6065 } 6066 } 6067 // Give priority to updated system apps. 6068 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6069 PackageParser.Package pkg = it.next(); 6070 if (pkg.isUpdatedSystemApp()) { 6071 if (DEBUG_DEXOPT) { 6072 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6073 } 6074 sortedPkgs.add(pkg); 6075 it.remove(); 6076 } 6077 } 6078 // Give priority to apps that listen for boot complete. 6079 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6080 pkgNames = getPackageNamesForIntent(intent); 6081 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6082 PackageParser.Package pkg = it.next(); 6083 if (pkgNames.contains(pkg.packageName)) { 6084 if (DEBUG_DEXOPT) { 6085 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6086 } 6087 sortedPkgs.add(pkg); 6088 it.remove(); 6089 } 6090 } 6091 // Filter out packages that aren't recently used. 6092 filterRecentlyUsedApps(pkgs); 6093 // Add all remaining apps. 6094 for (PackageParser.Package pkg : pkgs) { 6095 if (DEBUG_DEXOPT) { 6096 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6097 } 6098 sortedPkgs.add(pkg); 6099 } 6100 6101 // If we want to be lazy, filter everything that wasn't recently used. 6102 if (mLazyDexOpt) { 6103 filterRecentlyUsedApps(sortedPkgs); 6104 } 6105 6106 int i = 0; 6107 int total = sortedPkgs.size(); 6108 File dataDir = Environment.getDataDirectory(); 6109 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6110 if (lowThreshold == 0) { 6111 throw new IllegalStateException("Invalid low memory threshold"); 6112 } 6113 for (PackageParser.Package pkg : sortedPkgs) { 6114 long usableSpace = dataDir.getUsableSpace(); 6115 if (usableSpace < lowThreshold) { 6116 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6117 break; 6118 } 6119 performBootDexOpt(pkg, ++i, total); 6120 } 6121 } 6122 } 6123 6124 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6125 // Filter out packages that aren't recently used. 6126 // 6127 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6128 // should do a full dexopt. 6129 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6130 int total = pkgs.size(); 6131 int skipped = 0; 6132 long now = System.currentTimeMillis(); 6133 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6134 PackageParser.Package pkg = i.next(); 6135 long then = pkg.mLastPackageUsageTimeInMills; 6136 if (then + mDexOptLRUThresholdInMills < now) { 6137 if (DEBUG_DEXOPT) { 6138 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6139 ((then == 0) ? "never" : new Date(then))); 6140 } 6141 i.remove(); 6142 skipped++; 6143 } 6144 } 6145 if (DEBUG_DEXOPT) { 6146 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6147 } 6148 } 6149 } 6150 6151 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6152 List<ResolveInfo> ris = null; 6153 try { 6154 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6155 intent, null, 0, UserHandle.USER_OWNER); 6156 } catch (RemoteException e) { 6157 } 6158 ArraySet<String> pkgNames = new ArraySet<String>(); 6159 if (ris != null) { 6160 for (ResolveInfo ri : ris) { 6161 pkgNames.add(ri.activityInfo.packageName); 6162 } 6163 } 6164 return pkgNames; 6165 } 6166 6167 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6168 if (DEBUG_DEXOPT) { 6169 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6170 } 6171 if (!isFirstBoot()) { 6172 try { 6173 ActivityManagerNative.getDefault().showBootMessage( 6174 mContext.getResources().getString(R.string.android_upgrading_apk, 6175 curr, total), true); 6176 } catch (RemoteException e) { 6177 } 6178 } 6179 PackageParser.Package p = pkg; 6180 synchronized (mInstallLock) { 6181 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6182 false /* force dex */, false /* defer */, true /* include dependencies */); 6183 } 6184 } 6185 6186 @Override 6187 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6188 return performDexOpt(packageName, instructionSet, false); 6189 } 6190 6191 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6192 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6193 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6194 if (!dexopt && !updateUsage) { 6195 // We aren't going to dexopt or update usage, so bail early. 6196 return false; 6197 } 6198 PackageParser.Package p; 6199 final String targetInstructionSet; 6200 synchronized (mPackages) { 6201 p = mPackages.get(packageName); 6202 if (p == null) { 6203 return false; 6204 } 6205 if (updateUsage) { 6206 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6207 } 6208 mPackageUsage.write(false); 6209 if (!dexopt) { 6210 // We aren't going to dexopt, so bail early. 6211 return false; 6212 } 6213 6214 targetInstructionSet = instructionSet != null ? instructionSet : 6215 getPrimaryInstructionSet(p.applicationInfo); 6216 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6217 return false; 6218 } 6219 } 6220 long callingId = Binder.clearCallingIdentity(); 6221 try { 6222 synchronized (mInstallLock) { 6223 final String[] instructionSets = new String[] { targetInstructionSet }; 6224 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6225 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6226 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6227 } 6228 } finally { 6229 Binder.restoreCallingIdentity(callingId); 6230 } 6231 } 6232 6233 public ArraySet<String> getPackagesThatNeedDexOpt() { 6234 ArraySet<String> pkgs = null; 6235 synchronized (mPackages) { 6236 for (PackageParser.Package p : mPackages.values()) { 6237 if (DEBUG_DEXOPT) { 6238 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6239 } 6240 if (!p.mDexOptPerformed.isEmpty()) { 6241 continue; 6242 } 6243 if (pkgs == null) { 6244 pkgs = new ArraySet<String>(); 6245 } 6246 pkgs.add(p.packageName); 6247 } 6248 } 6249 return pkgs; 6250 } 6251 6252 public void shutdown() { 6253 mPackageUsage.write(true); 6254 } 6255 6256 @Override 6257 public void forceDexOpt(String packageName) { 6258 enforceSystemOrRoot("forceDexOpt"); 6259 6260 PackageParser.Package pkg; 6261 synchronized (mPackages) { 6262 pkg = mPackages.get(packageName); 6263 if (pkg == null) { 6264 throw new IllegalArgumentException("Missing package: " + packageName); 6265 } 6266 } 6267 6268 synchronized (mInstallLock) { 6269 final String[] instructionSets = new String[] { 6270 getPrimaryInstructionSet(pkg.applicationInfo) }; 6271 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6272 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6273 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6274 throw new IllegalStateException("Failed to dexopt: " + res); 6275 } 6276 } 6277 } 6278 6279 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6280 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6281 Slog.w(TAG, "Unable to update from " + oldPkg.name 6282 + " to " + newPkg.packageName 6283 + ": old package not in system partition"); 6284 return false; 6285 } else if (mPackages.get(oldPkg.name) != null) { 6286 Slog.w(TAG, "Unable to update from " + oldPkg.name 6287 + " to " + newPkg.packageName 6288 + ": old package still exists"); 6289 return false; 6290 } 6291 return true; 6292 } 6293 6294 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6295 int[] users = sUserManager.getUserIds(); 6296 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6297 if (res < 0) { 6298 return res; 6299 } 6300 for (int user : users) { 6301 if (user != 0) { 6302 res = mInstaller.createUserData(volumeUuid, packageName, 6303 UserHandle.getUid(user, uid), user, seinfo); 6304 if (res < 0) { 6305 return res; 6306 } 6307 } 6308 } 6309 return res; 6310 } 6311 6312 private int removeDataDirsLI(String volumeUuid, String packageName) { 6313 int[] users = sUserManager.getUserIds(); 6314 int res = 0; 6315 for (int user : users) { 6316 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6317 if (resInner < 0) { 6318 res = resInner; 6319 } 6320 } 6321 6322 return res; 6323 } 6324 6325 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6326 int[] users = sUserManager.getUserIds(); 6327 int res = 0; 6328 for (int user : users) { 6329 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6330 if (resInner < 0) { 6331 res = resInner; 6332 } 6333 } 6334 return res; 6335 } 6336 6337 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6338 PackageParser.Package changingLib) { 6339 if (file.path != null) { 6340 usesLibraryFiles.add(file.path); 6341 return; 6342 } 6343 PackageParser.Package p = mPackages.get(file.apk); 6344 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6345 // If we are doing this while in the middle of updating a library apk, 6346 // then we need to make sure to use that new apk for determining the 6347 // dependencies here. (We haven't yet finished committing the new apk 6348 // to the package manager state.) 6349 if (p == null || p.packageName.equals(changingLib.packageName)) { 6350 p = changingLib; 6351 } 6352 } 6353 if (p != null) { 6354 usesLibraryFiles.addAll(p.getAllCodePaths()); 6355 } 6356 } 6357 6358 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6359 PackageParser.Package changingLib) throws PackageManagerException { 6360 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6361 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6362 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6363 for (int i=0; i<N; i++) { 6364 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6365 if (file == null) { 6366 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6367 "Package " + pkg.packageName + " requires unavailable shared library " 6368 + pkg.usesLibraries.get(i) + "; failing!"); 6369 } 6370 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6371 } 6372 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6373 for (int i=0; i<N; i++) { 6374 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6375 if (file == null) { 6376 Slog.w(TAG, "Package " + pkg.packageName 6377 + " desires unavailable shared library " 6378 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6379 } else { 6380 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6381 } 6382 } 6383 N = usesLibraryFiles.size(); 6384 if (N > 0) { 6385 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6386 } else { 6387 pkg.usesLibraryFiles = null; 6388 } 6389 } 6390 } 6391 6392 private static boolean hasString(List<String> list, List<String> which) { 6393 if (list == null) { 6394 return false; 6395 } 6396 for (int i=list.size()-1; i>=0; i--) { 6397 for (int j=which.size()-1; j>=0; j--) { 6398 if (which.get(j).equals(list.get(i))) { 6399 return true; 6400 } 6401 } 6402 } 6403 return false; 6404 } 6405 6406 private void updateAllSharedLibrariesLPw() { 6407 for (PackageParser.Package pkg : mPackages.values()) { 6408 try { 6409 updateSharedLibrariesLPw(pkg, null); 6410 } catch (PackageManagerException e) { 6411 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6412 } 6413 } 6414 } 6415 6416 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6417 PackageParser.Package changingPkg) { 6418 ArrayList<PackageParser.Package> res = null; 6419 for (PackageParser.Package pkg : mPackages.values()) { 6420 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6421 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6422 if (res == null) { 6423 res = new ArrayList<PackageParser.Package>(); 6424 } 6425 res.add(pkg); 6426 try { 6427 updateSharedLibrariesLPw(pkg, changingPkg); 6428 } catch (PackageManagerException e) { 6429 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6430 } 6431 } 6432 } 6433 return res; 6434 } 6435 6436 /** 6437 * Derive the value of the {@code cpuAbiOverride} based on the provided 6438 * value and an optional stored value from the package settings. 6439 */ 6440 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6441 String cpuAbiOverride = null; 6442 6443 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6444 cpuAbiOverride = null; 6445 } else if (abiOverride != null) { 6446 cpuAbiOverride = abiOverride; 6447 } else if (settings != null) { 6448 cpuAbiOverride = settings.cpuAbiOverrideString; 6449 } 6450 6451 return cpuAbiOverride; 6452 } 6453 6454 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6455 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6456 boolean success = false; 6457 try { 6458 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6459 currentTime, user); 6460 success = true; 6461 return res; 6462 } finally { 6463 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6464 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6465 } 6466 } 6467 } 6468 6469 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6470 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6471 final File scanFile = new File(pkg.codePath); 6472 if (pkg.applicationInfo.getCodePath() == null || 6473 pkg.applicationInfo.getResourcePath() == null) { 6474 // Bail out. The resource and code paths haven't been set. 6475 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6476 "Code and resource paths haven't been set correctly"); 6477 } 6478 6479 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6480 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6481 } else { 6482 // Only allow system apps to be flagged as core apps. 6483 pkg.coreApp = false; 6484 } 6485 6486 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6487 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6488 } 6489 6490 if (mCustomResolverComponentName != null && 6491 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6492 setUpCustomResolverActivity(pkg); 6493 } 6494 6495 if (pkg.packageName.equals("android")) { 6496 synchronized (mPackages) { 6497 if (mAndroidApplication != null) { 6498 Slog.w(TAG, "*************************************************"); 6499 Slog.w(TAG, "Core android package being redefined. Skipping."); 6500 Slog.w(TAG, " file=" + scanFile); 6501 Slog.w(TAG, "*************************************************"); 6502 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6503 "Core android package being redefined. Skipping."); 6504 } 6505 6506 // Set up information for our fall-back user intent resolution activity. 6507 mPlatformPackage = pkg; 6508 pkg.mVersionCode = mSdkVersion; 6509 mAndroidApplication = pkg.applicationInfo; 6510 6511 if (!mResolverReplaced) { 6512 mResolveActivity.applicationInfo = mAndroidApplication; 6513 mResolveActivity.name = ResolverActivity.class.getName(); 6514 mResolveActivity.packageName = mAndroidApplication.packageName; 6515 mResolveActivity.processName = "system:ui"; 6516 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6517 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6518 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6519 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6520 mResolveActivity.exported = true; 6521 mResolveActivity.enabled = true; 6522 mResolveInfo.activityInfo = mResolveActivity; 6523 mResolveInfo.priority = 0; 6524 mResolveInfo.preferredOrder = 0; 6525 mResolveInfo.match = 0; 6526 mResolveComponentName = new ComponentName( 6527 mAndroidApplication.packageName, mResolveActivity.name); 6528 } 6529 } 6530 } 6531 6532 if (DEBUG_PACKAGE_SCANNING) { 6533 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6534 Log.d(TAG, "Scanning package " + pkg.packageName); 6535 } 6536 6537 if (mPackages.containsKey(pkg.packageName) 6538 || mSharedLibraries.containsKey(pkg.packageName)) { 6539 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6540 "Application package " + pkg.packageName 6541 + " already installed. Skipping duplicate."); 6542 } 6543 6544 // If we're only installing presumed-existing packages, require that the 6545 // scanned APK is both already known and at the path previously established 6546 // for it. Previously unknown packages we pick up normally, but if we have an 6547 // a priori expectation about this package's install presence, enforce it. 6548 // With a singular exception for new system packages. When an OTA contains 6549 // a new system package, we allow the codepath to change from a system location 6550 // to the user-installed location. If we don't allow this change, any newer, 6551 // user-installed version of the application will be ignored. 6552 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6553 if (mExpectingBetter.containsKey(pkg.packageName)) { 6554 logCriticalInfo(Log.WARN, 6555 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6556 } else { 6557 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6558 if (known != null) { 6559 if (DEBUG_PACKAGE_SCANNING) { 6560 Log.d(TAG, "Examining " + pkg.codePath 6561 + " and requiring known paths " + known.codePathString 6562 + " & " + known.resourcePathString); 6563 } 6564 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6565 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6566 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6567 "Application package " + pkg.packageName 6568 + " found at " + pkg.applicationInfo.getCodePath() 6569 + " but expected at " + known.codePathString + "; ignoring."); 6570 } 6571 } 6572 } 6573 } 6574 6575 // Initialize package source and resource directories 6576 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6577 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6578 6579 SharedUserSetting suid = null; 6580 PackageSetting pkgSetting = null; 6581 6582 if (!isSystemApp(pkg)) { 6583 // Only system apps can use these features. 6584 pkg.mOriginalPackages = null; 6585 pkg.mRealPackage = null; 6586 pkg.mAdoptPermissions = null; 6587 } 6588 6589 // writer 6590 synchronized (mPackages) { 6591 if (pkg.mSharedUserId != null) { 6592 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6593 if (suid == null) { 6594 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6595 "Creating application package " + pkg.packageName 6596 + " for shared user failed"); 6597 } 6598 if (DEBUG_PACKAGE_SCANNING) { 6599 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6600 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6601 + "): packages=" + suid.packages); 6602 } 6603 } 6604 6605 // Check if we are renaming from an original package name. 6606 PackageSetting origPackage = null; 6607 String realName = null; 6608 if (pkg.mOriginalPackages != null) { 6609 // This package may need to be renamed to a previously 6610 // installed name. Let's check on that... 6611 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6612 if (pkg.mOriginalPackages.contains(renamed)) { 6613 // This package had originally been installed as the 6614 // original name, and we have already taken care of 6615 // transitioning to the new one. Just update the new 6616 // one to continue using the old name. 6617 realName = pkg.mRealPackage; 6618 if (!pkg.packageName.equals(renamed)) { 6619 // Callers into this function may have already taken 6620 // care of renaming the package; only do it here if 6621 // it is not already done. 6622 pkg.setPackageName(renamed); 6623 } 6624 6625 } else { 6626 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6627 if ((origPackage = mSettings.peekPackageLPr( 6628 pkg.mOriginalPackages.get(i))) != null) { 6629 // We do have the package already installed under its 6630 // original name... should we use it? 6631 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6632 // New package is not compatible with original. 6633 origPackage = null; 6634 continue; 6635 } else if (origPackage.sharedUser != null) { 6636 // Make sure uid is compatible between packages. 6637 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6638 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6639 + " to " + pkg.packageName + ": old uid " 6640 + origPackage.sharedUser.name 6641 + " differs from " + pkg.mSharedUserId); 6642 origPackage = null; 6643 continue; 6644 } 6645 } else { 6646 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6647 + pkg.packageName + " to old name " + origPackage.name); 6648 } 6649 break; 6650 } 6651 } 6652 } 6653 } 6654 6655 if (mTransferedPackages.contains(pkg.packageName)) { 6656 Slog.w(TAG, "Package " + pkg.packageName 6657 + " was transferred to another, but its .apk remains"); 6658 } 6659 6660 // Just create the setting, don't add it yet. For already existing packages 6661 // the PkgSetting exists already and doesn't have to be created. 6662 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6663 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6664 pkg.applicationInfo.primaryCpuAbi, 6665 pkg.applicationInfo.secondaryCpuAbi, 6666 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6667 user, false); 6668 if (pkgSetting == null) { 6669 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6670 "Creating application package " + pkg.packageName + " failed"); 6671 } 6672 6673 if (pkgSetting.origPackage != null) { 6674 // If we are first transitioning from an original package, 6675 // fix up the new package's name now. We need to do this after 6676 // looking up the package under its new name, so getPackageLP 6677 // can take care of fiddling things correctly. 6678 pkg.setPackageName(origPackage.name); 6679 6680 // File a report about this. 6681 String msg = "New package " + pkgSetting.realName 6682 + " renamed to replace old package " + pkgSetting.name; 6683 reportSettingsProblem(Log.WARN, msg); 6684 6685 // Make a note of it. 6686 mTransferedPackages.add(origPackage.name); 6687 6688 // No longer need to retain this. 6689 pkgSetting.origPackage = null; 6690 } 6691 6692 if (realName != null) { 6693 // Make a note of it. 6694 mTransferedPackages.add(pkg.packageName); 6695 } 6696 6697 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6698 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6699 } 6700 6701 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6702 // Check all shared libraries and map to their actual file path. 6703 // We only do this here for apps not on a system dir, because those 6704 // are the only ones that can fail an install due to this. We 6705 // will take care of the system apps by updating all of their 6706 // library paths after the scan is done. 6707 updateSharedLibrariesLPw(pkg, null); 6708 } 6709 6710 if (mFoundPolicyFile) { 6711 SELinuxMMAC.assignSeinfoValue(pkg); 6712 } 6713 6714 pkg.applicationInfo.uid = pkgSetting.appId; 6715 pkg.mExtras = pkgSetting; 6716 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6717 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6718 // We just determined the app is signed correctly, so bring 6719 // over the latest parsed certs. 6720 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6721 } else { 6722 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6723 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6724 "Package " + pkg.packageName + " upgrade keys do not match the " 6725 + "previously installed version"); 6726 } else { 6727 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6728 String msg = "System package " + pkg.packageName 6729 + " signature changed; retaining data."; 6730 reportSettingsProblem(Log.WARN, msg); 6731 } 6732 } 6733 } else { 6734 try { 6735 verifySignaturesLP(pkgSetting, pkg); 6736 // We just determined the app is signed correctly, so bring 6737 // over the latest parsed certs. 6738 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6739 } catch (PackageManagerException e) { 6740 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6741 throw e; 6742 } 6743 // The signature has changed, but this package is in the system 6744 // image... let's recover! 6745 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6746 // However... if this package is part of a shared user, but it 6747 // doesn't match the signature of the shared user, let's fail. 6748 // What this means is that you can't change the signatures 6749 // associated with an overall shared user, which doesn't seem all 6750 // that unreasonable. 6751 if (pkgSetting.sharedUser != null) { 6752 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6753 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6754 throw new PackageManagerException( 6755 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6756 "Signature mismatch for shared user : " 6757 + pkgSetting.sharedUser); 6758 } 6759 } 6760 // File a report about this. 6761 String msg = "System package " + pkg.packageName 6762 + " signature changed; retaining data."; 6763 reportSettingsProblem(Log.WARN, msg); 6764 } 6765 } 6766 // Verify that this new package doesn't have any content providers 6767 // that conflict with existing packages. Only do this if the 6768 // package isn't already installed, since we don't want to break 6769 // things that are installed. 6770 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6771 final int N = pkg.providers.size(); 6772 int i; 6773 for (i=0; i<N; i++) { 6774 PackageParser.Provider p = pkg.providers.get(i); 6775 if (p.info.authority != null) { 6776 String names[] = p.info.authority.split(";"); 6777 for (int j = 0; j < names.length; j++) { 6778 if (mProvidersByAuthority.containsKey(names[j])) { 6779 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6780 final String otherPackageName = 6781 ((other != null && other.getComponentName() != null) ? 6782 other.getComponentName().getPackageName() : "?"); 6783 throw new PackageManagerException( 6784 INSTALL_FAILED_CONFLICTING_PROVIDER, 6785 "Can't install because provider name " + names[j] 6786 + " (in package " + pkg.applicationInfo.packageName 6787 + ") is already used by " + otherPackageName); 6788 } 6789 } 6790 } 6791 } 6792 } 6793 6794 if (pkg.mAdoptPermissions != null) { 6795 // This package wants to adopt ownership of permissions from 6796 // another package. 6797 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6798 final String origName = pkg.mAdoptPermissions.get(i); 6799 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6800 if (orig != null) { 6801 if (verifyPackageUpdateLPr(orig, pkg)) { 6802 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6803 + pkg.packageName); 6804 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6805 } 6806 } 6807 } 6808 } 6809 } 6810 6811 final String pkgName = pkg.packageName; 6812 6813 final long scanFileTime = scanFile.lastModified(); 6814 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6815 pkg.applicationInfo.processName = fixProcessName( 6816 pkg.applicationInfo.packageName, 6817 pkg.applicationInfo.processName, 6818 pkg.applicationInfo.uid); 6819 6820 File dataPath; 6821 if (mPlatformPackage == pkg) { 6822 // The system package is special. 6823 dataPath = new File(Environment.getDataDirectory(), "system"); 6824 6825 pkg.applicationInfo.dataDir = dataPath.getPath(); 6826 6827 } else { 6828 // This is a normal package, need to make its data directory. 6829 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6830 UserHandle.USER_OWNER, pkg.packageName); 6831 6832 boolean uidError = false; 6833 if (dataPath.exists()) { 6834 int currentUid = 0; 6835 try { 6836 StructStat stat = Os.stat(dataPath.getPath()); 6837 currentUid = stat.st_uid; 6838 } catch (ErrnoException e) { 6839 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6840 } 6841 6842 // If we have mismatched owners for the data path, we have a problem. 6843 if (currentUid != pkg.applicationInfo.uid) { 6844 boolean recovered = false; 6845 if (currentUid == 0) { 6846 // The directory somehow became owned by root. Wow. 6847 // This is probably because the system was stopped while 6848 // installd was in the middle of messing with its libs 6849 // directory. Ask installd to fix that. 6850 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6851 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6852 if (ret >= 0) { 6853 recovered = true; 6854 String msg = "Package " + pkg.packageName 6855 + " unexpectedly changed to uid 0; recovered to " + 6856 + pkg.applicationInfo.uid; 6857 reportSettingsProblem(Log.WARN, msg); 6858 } 6859 } 6860 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6861 || (scanFlags&SCAN_BOOTING) != 0)) { 6862 // If this is a system app, we can at least delete its 6863 // current data so the application will still work. 6864 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6865 if (ret >= 0) { 6866 // TODO: Kill the processes first 6867 // Old data gone! 6868 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6869 ? "System package " : "Third party package "; 6870 String msg = prefix + pkg.packageName 6871 + " has changed from uid: " 6872 + currentUid + " to " 6873 + pkg.applicationInfo.uid + "; old data erased"; 6874 reportSettingsProblem(Log.WARN, msg); 6875 recovered = true; 6876 6877 // And now re-install the app. 6878 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6879 pkg.applicationInfo.seinfo); 6880 if (ret == -1) { 6881 // Ack should not happen! 6882 msg = prefix + pkg.packageName 6883 + " could not have data directory re-created after delete."; 6884 reportSettingsProblem(Log.WARN, msg); 6885 throw new PackageManagerException( 6886 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6887 } 6888 } 6889 if (!recovered) { 6890 mHasSystemUidErrors = true; 6891 } 6892 } else if (!recovered) { 6893 // If we allow this install to proceed, we will be broken. 6894 // Abort, abort! 6895 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6896 "scanPackageLI"); 6897 } 6898 if (!recovered) { 6899 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6900 + pkg.applicationInfo.uid + "/fs_" 6901 + currentUid; 6902 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6903 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6904 String msg = "Package " + pkg.packageName 6905 + " has mismatched uid: " 6906 + currentUid + " on disk, " 6907 + pkg.applicationInfo.uid + " in settings"; 6908 // writer 6909 synchronized (mPackages) { 6910 mSettings.mReadMessages.append(msg); 6911 mSettings.mReadMessages.append('\n'); 6912 uidError = true; 6913 if (!pkgSetting.uidError) { 6914 reportSettingsProblem(Log.ERROR, msg); 6915 } 6916 } 6917 } 6918 } 6919 pkg.applicationInfo.dataDir = dataPath.getPath(); 6920 if (mShouldRestoreconData) { 6921 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6922 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6923 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6924 } 6925 } else { 6926 if (DEBUG_PACKAGE_SCANNING) { 6927 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6928 Log.v(TAG, "Want this data dir: " + dataPath); 6929 } 6930 //invoke installer to do the actual installation 6931 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6932 pkg.applicationInfo.seinfo); 6933 if (ret < 0) { 6934 // Error from installer 6935 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6936 "Unable to create data dirs [errorCode=" + ret + "]"); 6937 } 6938 6939 if (dataPath.exists()) { 6940 pkg.applicationInfo.dataDir = dataPath.getPath(); 6941 } else { 6942 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6943 pkg.applicationInfo.dataDir = null; 6944 } 6945 } 6946 6947 pkgSetting.uidError = uidError; 6948 } 6949 6950 final String path = scanFile.getPath(); 6951 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6952 6953 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6954 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6955 6956 // Some system apps still use directory structure for native libraries 6957 // in which case we might end up not detecting abi solely based on apk 6958 // structure. Try to detect abi based on directory structure. 6959 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6960 pkg.applicationInfo.primaryCpuAbi == null) { 6961 setBundledAppAbisAndRoots(pkg, pkgSetting); 6962 setNativeLibraryPaths(pkg); 6963 } 6964 6965 } else { 6966 if ((scanFlags & SCAN_MOVE) != 0) { 6967 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6968 // but we already have this packages package info in the PackageSetting. We just 6969 // use that and derive the native library path based on the new codepath. 6970 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6971 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6972 } 6973 6974 // Set native library paths again. For moves, the path will be updated based on the 6975 // ABIs we've determined above. For non-moves, the path will be updated based on the 6976 // ABIs we determined during compilation, but the path will depend on the final 6977 // package path (after the rename away from the stage path). 6978 setNativeLibraryPaths(pkg); 6979 } 6980 6981 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6982 final int[] userIds = sUserManager.getUserIds(); 6983 synchronized (mInstallLock) { 6984 // Make sure all user data directories are ready to roll; we're okay 6985 // if they already exist 6986 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6987 for (int userId : userIds) { 6988 if (userId != 0) { 6989 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6990 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6991 pkg.applicationInfo.seinfo); 6992 } 6993 } 6994 } 6995 6996 // Create a native library symlink only if we have native libraries 6997 // and if the native libraries are 32 bit libraries. We do not provide 6998 // this symlink for 64 bit libraries. 6999 if (pkg.applicationInfo.primaryCpuAbi != null && 7000 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7001 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7002 for (int userId : userIds) { 7003 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7004 nativeLibPath, userId) < 0) { 7005 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7006 "Failed linking native library dir (user=" + userId + ")"); 7007 } 7008 } 7009 } 7010 } 7011 7012 // This is a special case for the "system" package, where the ABI is 7013 // dictated by the zygote configuration (and init.rc). We should keep track 7014 // of this ABI so that we can deal with "normal" applications that run under 7015 // the same UID correctly. 7016 if (mPlatformPackage == pkg) { 7017 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7018 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7019 } 7020 7021 // If there's a mismatch between the abi-override in the package setting 7022 // and the abiOverride specified for the install. Warn about this because we 7023 // would've already compiled the app without taking the package setting into 7024 // account. 7025 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7026 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7027 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7028 " for package: " + pkg.packageName); 7029 } 7030 } 7031 7032 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7033 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7034 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7035 7036 // Copy the derived override back to the parsed package, so that we can 7037 // update the package settings accordingly. 7038 pkg.cpuAbiOverride = cpuAbiOverride; 7039 7040 if (DEBUG_ABI_SELECTION) { 7041 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7042 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7043 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7044 } 7045 7046 // Push the derived path down into PackageSettings so we know what to 7047 // clean up at uninstall time. 7048 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7049 7050 if (DEBUG_ABI_SELECTION) { 7051 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7052 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7053 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7054 } 7055 7056 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7057 // We don't do this here during boot because we can do it all 7058 // at once after scanning all existing packages. 7059 // 7060 // We also do this *before* we perform dexopt on this package, so that 7061 // we can avoid redundant dexopts, and also to make sure we've got the 7062 // code and package path correct. 7063 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7064 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7065 } 7066 7067 if ((scanFlags & SCAN_NO_DEX) == 0) { 7068 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7069 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7070 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7071 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7072 } 7073 } 7074 if (mFactoryTest && pkg.requestedPermissions.contains( 7075 android.Manifest.permission.FACTORY_TEST)) { 7076 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7077 } 7078 7079 ArrayList<PackageParser.Package> clientLibPkgs = null; 7080 7081 // writer 7082 synchronized (mPackages) { 7083 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7084 // Only system apps can add new shared libraries. 7085 if (pkg.libraryNames != null) { 7086 for (int i=0; i<pkg.libraryNames.size(); i++) { 7087 String name = pkg.libraryNames.get(i); 7088 boolean allowed = false; 7089 if (pkg.isUpdatedSystemApp()) { 7090 // New library entries can only be added through the 7091 // system image. This is important to get rid of a lot 7092 // of nasty edge cases: for example if we allowed a non- 7093 // system update of the app to add a library, then uninstalling 7094 // the update would make the library go away, and assumptions 7095 // we made such as through app install filtering would now 7096 // have allowed apps on the device which aren't compatible 7097 // with it. Better to just have the restriction here, be 7098 // conservative, and create many fewer cases that can negatively 7099 // impact the user experience. 7100 final PackageSetting sysPs = mSettings 7101 .getDisabledSystemPkgLPr(pkg.packageName); 7102 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7103 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7104 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7105 allowed = true; 7106 allowed = true; 7107 break; 7108 } 7109 } 7110 } 7111 } else { 7112 allowed = true; 7113 } 7114 if (allowed) { 7115 if (!mSharedLibraries.containsKey(name)) { 7116 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7117 } else if (!name.equals(pkg.packageName)) { 7118 Slog.w(TAG, "Package " + pkg.packageName + " library " 7119 + name + " already exists; skipping"); 7120 } 7121 } else { 7122 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7123 + name + " that is not declared on system image; skipping"); 7124 } 7125 } 7126 if ((scanFlags&SCAN_BOOTING) == 0) { 7127 // If we are not booting, we need to update any applications 7128 // that are clients of our shared library. If we are booting, 7129 // this will all be done once the scan is complete. 7130 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7131 } 7132 } 7133 } 7134 } 7135 7136 // We also need to dexopt any apps that are dependent on this library. Note that 7137 // if these fail, we should abort the install since installing the library will 7138 // result in some apps being broken. 7139 if (clientLibPkgs != null) { 7140 if ((scanFlags & SCAN_NO_DEX) == 0) { 7141 for (int i = 0; i < clientLibPkgs.size(); i++) { 7142 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7143 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7144 null /* instruction sets */, forceDex, 7145 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7146 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7147 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7148 "scanPackageLI failed to dexopt clientLibPkgs"); 7149 } 7150 } 7151 } 7152 } 7153 7154 // Request the ActivityManager to kill the process(only for existing packages) 7155 // so that we do not end up in a confused state while the user is still using the older 7156 // version of the application while the new one gets installed. 7157 if ((scanFlags & SCAN_REPLACING) != 0) { 7158 killApplication(pkg.applicationInfo.packageName, 7159 pkg.applicationInfo.uid, "replace pkg"); 7160 } 7161 7162 // Also need to kill any apps that are dependent on the library. 7163 if (clientLibPkgs != null) { 7164 for (int i=0; i<clientLibPkgs.size(); i++) { 7165 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7166 killApplication(clientPkg.applicationInfo.packageName, 7167 clientPkg.applicationInfo.uid, "update lib"); 7168 } 7169 } 7170 7171 // Make sure we're not adding any bogus keyset info 7172 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7173 ksms.assertScannedPackageValid(pkg); 7174 7175 // writer 7176 synchronized (mPackages) { 7177 // We don't expect installation to fail beyond this point 7178 7179 // Add the new setting to mSettings 7180 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7181 // Add the new setting to mPackages 7182 mPackages.put(pkg.applicationInfo.packageName, pkg); 7183 // Make sure we don't accidentally delete its data. 7184 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7185 while (iter.hasNext()) { 7186 PackageCleanItem item = iter.next(); 7187 if (pkgName.equals(item.packageName)) { 7188 iter.remove(); 7189 } 7190 } 7191 7192 // Take care of first install / last update times. 7193 if (currentTime != 0) { 7194 if (pkgSetting.firstInstallTime == 0) { 7195 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7196 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7197 pkgSetting.lastUpdateTime = currentTime; 7198 } 7199 } else if (pkgSetting.firstInstallTime == 0) { 7200 // We need *something*. Take time time stamp of the file. 7201 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7202 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7203 if (scanFileTime != pkgSetting.timeStamp) { 7204 // A package on the system image has changed; consider this 7205 // to be an update. 7206 pkgSetting.lastUpdateTime = scanFileTime; 7207 } 7208 } 7209 7210 // Add the package's KeySets to the global KeySetManagerService 7211 ksms.addScannedPackageLPw(pkg); 7212 7213 int N = pkg.providers.size(); 7214 StringBuilder r = null; 7215 int i; 7216 for (i=0; i<N; i++) { 7217 PackageParser.Provider p = pkg.providers.get(i); 7218 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7219 p.info.processName, pkg.applicationInfo.uid); 7220 mProviders.addProvider(p); 7221 p.syncable = p.info.isSyncable; 7222 if (p.info.authority != null) { 7223 String names[] = p.info.authority.split(";"); 7224 p.info.authority = null; 7225 for (int j = 0; j < names.length; j++) { 7226 if (j == 1 && p.syncable) { 7227 // We only want the first authority for a provider to possibly be 7228 // syncable, so if we already added this provider using a different 7229 // authority clear the syncable flag. We copy the provider before 7230 // changing it because the mProviders object contains a reference 7231 // to a provider that we don't want to change. 7232 // Only do this for the second authority since the resulting provider 7233 // object can be the same for all future authorities for this provider. 7234 p = new PackageParser.Provider(p); 7235 p.syncable = false; 7236 } 7237 if (!mProvidersByAuthority.containsKey(names[j])) { 7238 mProvidersByAuthority.put(names[j], p); 7239 if (p.info.authority == null) { 7240 p.info.authority = names[j]; 7241 } else { 7242 p.info.authority = p.info.authority + ";" + names[j]; 7243 } 7244 if (DEBUG_PACKAGE_SCANNING) { 7245 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7246 Log.d(TAG, "Registered content provider: " + names[j] 7247 + ", className = " + p.info.name + ", isSyncable = " 7248 + p.info.isSyncable); 7249 } 7250 } else { 7251 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7252 Slog.w(TAG, "Skipping provider name " + names[j] + 7253 " (in package " + pkg.applicationInfo.packageName + 7254 "): name already used by " 7255 + ((other != null && other.getComponentName() != null) 7256 ? other.getComponentName().getPackageName() : "?")); 7257 } 7258 } 7259 } 7260 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7261 if (r == null) { 7262 r = new StringBuilder(256); 7263 } else { 7264 r.append(' '); 7265 } 7266 r.append(p.info.name); 7267 } 7268 } 7269 if (r != null) { 7270 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7271 } 7272 7273 N = pkg.services.size(); 7274 r = null; 7275 for (i=0; i<N; i++) { 7276 PackageParser.Service s = pkg.services.get(i); 7277 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7278 s.info.processName, pkg.applicationInfo.uid); 7279 mServices.addService(s); 7280 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7281 if (r == null) { 7282 r = new StringBuilder(256); 7283 } else { 7284 r.append(' '); 7285 } 7286 r.append(s.info.name); 7287 } 7288 } 7289 if (r != null) { 7290 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7291 } 7292 7293 N = pkg.receivers.size(); 7294 r = null; 7295 for (i=0; i<N; i++) { 7296 PackageParser.Activity a = pkg.receivers.get(i); 7297 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7298 a.info.processName, pkg.applicationInfo.uid); 7299 mReceivers.addActivity(a, "receiver"); 7300 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7301 if (r == null) { 7302 r = new StringBuilder(256); 7303 } else { 7304 r.append(' '); 7305 } 7306 r.append(a.info.name); 7307 } 7308 } 7309 if (r != null) { 7310 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7311 } 7312 7313 N = pkg.activities.size(); 7314 r = null; 7315 for (i=0; i<N; i++) { 7316 PackageParser.Activity a = pkg.activities.get(i); 7317 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7318 a.info.processName, pkg.applicationInfo.uid); 7319 mActivities.addActivity(a, "activity"); 7320 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7321 if (r == null) { 7322 r = new StringBuilder(256); 7323 } else { 7324 r.append(' '); 7325 } 7326 r.append(a.info.name); 7327 } 7328 } 7329 if (r != null) { 7330 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7331 } 7332 7333 N = pkg.permissionGroups.size(); 7334 r = null; 7335 for (i=0; i<N; i++) { 7336 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7337 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7338 if (cur == null) { 7339 mPermissionGroups.put(pg.info.name, pg); 7340 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7341 if (r == null) { 7342 r = new StringBuilder(256); 7343 } else { 7344 r.append(' '); 7345 } 7346 r.append(pg.info.name); 7347 } 7348 } else { 7349 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7350 + pg.info.packageName + " ignored: original from " 7351 + cur.info.packageName); 7352 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7353 if (r == null) { 7354 r = new StringBuilder(256); 7355 } else { 7356 r.append(' '); 7357 } 7358 r.append("DUP:"); 7359 r.append(pg.info.name); 7360 } 7361 } 7362 } 7363 if (r != null) { 7364 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7365 } 7366 7367 N = pkg.permissions.size(); 7368 r = null; 7369 for (i=0; i<N; i++) { 7370 PackageParser.Permission p = pkg.permissions.get(i); 7371 7372 // Assume by default that we did not install this permission into the system. 7373 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7374 7375 // Now that permission groups have a special meaning, we ignore permission 7376 // groups for legacy apps to prevent unexpected behavior. In particular, 7377 // permissions for one app being granted to someone just becuase they happen 7378 // to be in a group defined by another app (before this had no implications). 7379 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7380 p.group = mPermissionGroups.get(p.info.group); 7381 // Warn for a permission in an unknown group. 7382 if (p.info.group != null && p.group == null) { 7383 Slog.w(TAG, "Permission " + p.info.name + " from package " 7384 + p.info.packageName + " in an unknown group " + p.info.group); 7385 } 7386 } 7387 7388 ArrayMap<String, BasePermission> permissionMap = 7389 p.tree ? mSettings.mPermissionTrees 7390 : mSettings.mPermissions; 7391 BasePermission bp = permissionMap.get(p.info.name); 7392 7393 // Allow system apps to redefine non-system permissions 7394 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7395 final boolean currentOwnerIsSystem = (bp.perm != null 7396 && isSystemApp(bp.perm.owner)); 7397 if (isSystemApp(p.owner)) { 7398 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7399 // It's a built-in permission and no owner, take ownership now 7400 bp.packageSetting = pkgSetting; 7401 bp.perm = p; 7402 bp.uid = pkg.applicationInfo.uid; 7403 bp.sourcePackage = p.info.packageName; 7404 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7405 } else if (!currentOwnerIsSystem) { 7406 String msg = "New decl " + p.owner + " of permission " 7407 + p.info.name + " is system; overriding " + bp.sourcePackage; 7408 reportSettingsProblem(Log.WARN, msg); 7409 bp = null; 7410 } 7411 } 7412 } 7413 7414 if (bp == null) { 7415 bp = new BasePermission(p.info.name, p.info.packageName, 7416 BasePermission.TYPE_NORMAL); 7417 permissionMap.put(p.info.name, bp); 7418 } 7419 7420 if (bp.perm == null) { 7421 if (bp.sourcePackage == null 7422 || bp.sourcePackage.equals(p.info.packageName)) { 7423 BasePermission tree = findPermissionTreeLP(p.info.name); 7424 if (tree == null 7425 || tree.sourcePackage.equals(p.info.packageName)) { 7426 bp.packageSetting = pkgSetting; 7427 bp.perm = p; 7428 bp.uid = pkg.applicationInfo.uid; 7429 bp.sourcePackage = p.info.packageName; 7430 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7431 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7432 if (r == null) { 7433 r = new StringBuilder(256); 7434 } else { 7435 r.append(' '); 7436 } 7437 r.append(p.info.name); 7438 } 7439 } else { 7440 Slog.w(TAG, "Permission " + p.info.name + " from package " 7441 + p.info.packageName + " ignored: base tree " 7442 + tree.name + " is from package " 7443 + tree.sourcePackage); 7444 } 7445 } else { 7446 Slog.w(TAG, "Permission " + p.info.name + " from package " 7447 + p.info.packageName + " ignored: original from " 7448 + bp.sourcePackage); 7449 } 7450 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7451 if (r == null) { 7452 r = new StringBuilder(256); 7453 } else { 7454 r.append(' '); 7455 } 7456 r.append("DUP:"); 7457 r.append(p.info.name); 7458 } 7459 if (bp.perm == p) { 7460 bp.protectionLevel = p.info.protectionLevel; 7461 } 7462 } 7463 7464 if (r != null) { 7465 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7466 } 7467 7468 N = pkg.instrumentation.size(); 7469 r = null; 7470 for (i=0; i<N; i++) { 7471 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7472 a.info.packageName = pkg.applicationInfo.packageName; 7473 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7474 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7475 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7476 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7477 a.info.dataDir = pkg.applicationInfo.dataDir; 7478 7479 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7480 // need other information about the application, like the ABI and what not ? 7481 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7482 mInstrumentation.put(a.getComponentName(), a); 7483 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7484 if (r == null) { 7485 r = new StringBuilder(256); 7486 } else { 7487 r.append(' '); 7488 } 7489 r.append(a.info.name); 7490 } 7491 } 7492 if (r != null) { 7493 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7494 } 7495 7496 if (pkg.protectedBroadcasts != null) { 7497 N = pkg.protectedBroadcasts.size(); 7498 for (i=0; i<N; i++) { 7499 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7500 } 7501 } 7502 7503 pkgSetting.setTimeStamp(scanFileTime); 7504 7505 // Create idmap files for pairs of (packages, overlay packages). 7506 // Note: "android", ie framework-res.apk, is handled by native layers. 7507 if (pkg.mOverlayTarget != null) { 7508 // This is an overlay package. 7509 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7510 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7511 mOverlays.put(pkg.mOverlayTarget, 7512 new ArrayMap<String, PackageParser.Package>()); 7513 } 7514 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7515 map.put(pkg.packageName, pkg); 7516 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7517 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7518 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7519 "scanPackageLI failed to createIdmap"); 7520 } 7521 } 7522 } else if (mOverlays.containsKey(pkg.packageName) && 7523 !pkg.packageName.equals("android")) { 7524 // This is a regular package, with one or more known overlay packages. 7525 createIdmapsForPackageLI(pkg); 7526 } 7527 } 7528 7529 return pkg; 7530 } 7531 7532 /** 7533 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7534 * is derived purely on the basis of the contents of {@code scanFile} and 7535 * {@code cpuAbiOverride}. 7536 * 7537 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7538 */ 7539 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7540 String cpuAbiOverride, boolean extractLibs) 7541 throws PackageManagerException { 7542 // TODO: We can probably be smarter about this stuff. For installed apps, 7543 // we can calculate this information at install time once and for all. For 7544 // system apps, we can probably assume that this information doesn't change 7545 // after the first boot scan. As things stand, we do lots of unnecessary work. 7546 7547 // Give ourselves some initial paths; we'll come back for another 7548 // pass once we've determined ABI below. 7549 setNativeLibraryPaths(pkg); 7550 7551 // We would never need to extract libs for forward-locked and external packages, 7552 // since the container service will do it for us. We shouldn't attempt to 7553 // extract libs from system app when it was not updated. 7554 if (pkg.isForwardLocked() || isExternal(pkg) || 7555 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7556 extractLibs = false; 7557 } 7558 7559 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7560 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7561 7562 NativeLibraryHelper.Handle handle = null; 7563 try { 7564 handle = NativeLibraryHelper.Handle.create(scanFile); 7565 // TODO(multiArch): This can be null for apps that didn't go through the 7566 // usual installation process. We can calculate it again, like we 7567 // do during install time. 7568 // 7569 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7570 // unnecessary. 7571 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7572 7573 // Null out the abis so that they can be recalculated. 7574 pkg.applicationInfo.primaryCpuAbi = null; 7575 pkg.applicationInfo.secondaryCpuAbi = null; 7576 if (isMultiArch(pkg.applicationInfo)) { 7577 // Warn if we've set an abiOverride for multi-lib packages.. 7578 // By definition, we need to copy both 32 and 64 bit libraries for 7579 // such packages. 7580 if (pkg.cpuAbiOverride != null 7581 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7582 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7583 } 7584 7585 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7586 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7587 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7588 if (extractLibs) { 7589 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7590 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7591 useIsaSpecificSubdirs); 7592 } else { 7593 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7594 } 7595 } 7596 7597 maybeThrowExceptionForMultiArchCopy( 7598 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7599 7600 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7601 if (extractLibs) { 7602 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7603 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7604 useIsaSpecificSubdirs); 7605 } else { 7606 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7607 } 7608 } 7609 7610 maybeThrowExceptionForMultiArchCopy( 7611 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7612 7613 if (abi64 >= 0) { 7614 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7615 } 7616 7617 if (abi32 >= 0) { 7618 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7619 if (abi64 >= 0) { 7620 pkg.applicationInfo.secondaryCpuAbi = abi; 7621 } else { 7622 pkg.applicationInfo.primaryCpuAbi = abi; 7623 } 7624 } 7625 } else { 7626 String[] abiList = (cpuAbiOverride != null) ? 7627 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7628 7629 // Enable gross and lame hacks for apps that are built with old 7630 // SDK tools. We must scan their APKs for renderscript bitcode and 7631 // not launch them if it's present. Don't bother checking on devices 7632 // that don't have 64 bit support. 7633 boolean needsRenderScriptOverride = false; 7634 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7635 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7636 abiList = Build.SUPPORTED_32_BIT_ABIS; 7637 needsRenderScriptOverride = true; 7638 } 7639 7640 final int copyRet; 7641 if (extractLibs) { 7642 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7643 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7644 } else { 7645 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7646 } 7647 7648 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7649 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7650 "Error unpackaging native libs for app, errorCode=" + copyRet); 7651 } 7652 7653 if (copyRet >= 0) { 7654 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7655 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7656 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7657 } else if (needsRenderScriptOverride) { 7658 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7659 } 7660 } 7661 } catch (IOException ioe) { 7662 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7663 } finally { 7664 IoUtils.closeQuietly(handle); 7665 } 7666 7667 // Now that we've calculated the ABIs and determined if it's an internal app, 7668 // we will go ahead and populate the nativeLibraryPath. 7669 setNativeLibraryPaths(pkg); 7670 } 7671 7672 /** 7673 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7674 * i.e, so that all packages can be run inside a single process if required. 7675 * 7676 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7677 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7678 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7679 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7680 * updating a package that belongs to a shared user. 7681 * 7682 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7683 * adds unnecessary complexity. 7684 */ 7685 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7686 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7687 String requiredInstructionSet = null; 7688 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7689 requiredInstructionSet = VMRuntime.getInstructionSet( 7690 scannedPackage.applicationInfo.primaryCpuAbi); 7691 } 7692 7693 PackageSetting requirer = null; 7694 for (PackageSetting ps : packagesForUser) { 7695 // If packagesForUser contains scannedPackage, we skip it. This will happen 7696 // when scannedPackage is an update of an existing package. Without this check, 7697 // we will never be able to change the ABI of any package belonging to a shared 7698 // user, even if it's compatible with other packages. 7699 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7700 if (ps.primaryCpuAbiString == null) { 7701 continue; 7702 } 7703 7704 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7705 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7706 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7707 // this but there's not much we can do. 7708 String errorMessage = "Instruction set mismatch, " 7709 + ((requirer == null) ? "[caller]" : requirer) 7710 + " requires " + requiredInstructionSet + " whereas " + ps 7711 + " requires " + instructionSet; 7712 Slog.w(TAG, errorMessage); 7713 } 7714 7715 if (requiredInstructionSet == null) { 7716 requiredInstructionSet = instructionSet; 7717 requirer = ps; 7718 } 7719 } 7720 } 7721 7722 if (requiredInstructionSet != null) { 7723 String adjustedAbi; 7724 if (requirer != null) { 7725 // requirer != null implies that either scannedPackage was null or that scannedPackage 7726 // did not require an ABI, in which case we have to adjust scannedPackage to match 7727 // the ABI of the set (which is the same as requirer's ABI) 7728 adjustedAbi = requirer.primaryCpuAbiString; 7729 if (scannedPackage != null) { 7730 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7731 } 7732 } else { 7733 // requirer == null implies that we're updating all ABIs in the set to 7734 // match scannedPackage. 7735 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7736 } 7737 7738 for (PackageSetting ps : packagesForUser) { 7739 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7740 if (ps.primaryCpuAbiString != null) { 7741 continue; 7742 } 7743 7744 ps.primaryCpuAbiString = adjustedAbi; 7745 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7746 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7747 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7748 7749 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7750 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7751 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7752 ps.primaryCpuAbiString = null; 7753 ps.pkg.applicationInfo.primaryCpuAbi = null; 7754 return; 7755 } else { 7756 mInstaller.rmdex(ps.codePathString, 7757 getDexCodeInstructionSet(getPreferredInstructionSet())); 7758 } 7759 } 7760 } 7761 } 7762 } 7763 } 7764 7765 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7766 synchronized (mPackages) { 7767 mResolverReplaced = true; 7768 // Set up information for custom user intent resolution activity. 7769 mResolveActivity.applicationInfo = pkg.applicationInfo; 7770 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7771 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7772 mResolveActivity.processName = pkg.applicationInfo.packageName; 7773 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7774 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7775 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7776 mResolveActivity.theme = 0; 7777 mResolveActivity.exported = true; 7778 mResolveActivity.enabled = true; 7779 mResolveInfo.activityInfo = mResolveActivity; 7780 mResolveInfo.priority = 0; 7781 mResolveInfo.preferredOrder = 0; 7782 mResolveInfo.match = 0; 7783 mResolveComponentName = mCustomResolverComponentName; 7784 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7785 mResolveComponentName); 7786 } 7787 } 7788 7789 private static String calculateBundledApkRoot(final String codePathString) { 7790 final File codePath = new File(codePathString); 7791 final File codeRoot; 7792 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7793 codeRoot = Environment.getRootDirectory(); 7794 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7795 codeRoot = Environment.getOemDirectory(); 7796 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7797 codeRoot = Environment.getVendorDirectory(); 7798 } else { 7799 // Unrecognized code path; take its top real segment as the apk root: 7800 // e.g. /something/app/blah.apk => /something 7801 try { 7802 File f = codePath.getCanonicalFile(); 7803 File parent = f.getParentFile(); // non-null because codePath is a file 7804 File tmp; 7805 while ((tmp = parent.getParentFile()) != null) { 7806 f = parent; 7807 parent = tmp; 7808 } 7809 codeRoot = f; 7810 Slog.w(TAG, "Unrecognized code path " 7811 + codePath + " - using " + codeRoot); 7812 } catch (IOException e) { 7813 // Can't canonicalize the code path -- shenanigans? 7814 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7815 return Environment.getRootDirectory().getPath(); 7816 } 7817 } 7818 return codeRoot.getPath(); 7819 } 7820 7821 /** 7822 * Derive and set the location of native libraries for the given package, 7823 * which varies depending on where and how the package was installed. 7824 */ 7825 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7826 final ApplicationInfo info = pkg.applicationInfo; 7827 final String codePath = pkg.codePath; 7828 final File codeFile = new File(codePath); 7829 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7830 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7831 7832 info.nativeLibraryRootDir = null; 7833 info.nativeLibraryRootRequiresIsa = false; 7834 info.nativeLibraryDir = null; 7835 info.secondaryNativeLibraryDir = null; 7836 7837 if (isApkFile(codeFile)) { 7838 // Monolithic install 7839 if (bundledApp) { 7840 // If "/system/lib64/apkname" exists, assume that is the per-package 7841 // native library directory to use; otherwise use "/system/lib/apkname". 7842 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7843 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7844 getPrimaryInstructionSet(info)); 7845 7846 // This is a bundled system app so choose the path based on the ABI. 7847 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7848 // is just the default path. 7849 final String apkName = deriveCodePathName(codePath); 7850 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7851 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7852 apkName).getAbsolutePath(); 7853 7854 if (info.secondaryCpuAbi != null) { 7855 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7856 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7857 secondaryLibDir, apkName).getAbsolutePath(); 7858 } 7859 } else if (asecApp) { 7860 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7861 .getAbsolutePath(); 7862 } else { 7863 final String apkName = deriveCodePathName(codePath); 7864 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7865 .getAbsolutePath(); 7866 } 7867 7868 info.nativeLibraryRootRequiresIsa = false; 7869 info.nativeLibraryDir = info.nativeLibraryRootDir; 7870 } else { 7871 // Cluster install 7872 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7873 info.nativeLibraryRootRequiresIsa = true; 7874 7875 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7876 getPrimaryInstructionSet(info)).getAbsolutePath(); 7877 7878 if (info.secondaryCpuAbi != null) { 7879 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7880 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7881 } 7882 } 7883 } 7884 7885 /** 7886 * Calculate the abis and roots for a bundled app. These can uniquely 7887 * be determined from the contents of the system partition, i.e whether 7888 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7889 * of this information, and instead assume that the system was built 7890 * sensibly. 7891 */ 7892 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7893 PackageSetting pkgSetting) { 7894 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7895 7896 // If "/system/lib64/apkname" exists, assume that is the per-package 7897 // native library directory to use; otherwise use "/system/lib/apkname". 7898 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7899 setBundledAppAbi(pkg, apkRoot, apkName); 7900 // pkgSetting might be null during rescan following uninstall of updates 7901 // to a bundled app, so accommodate that possibility. The settings in 7902 // that case will be established later from the parsed package. 7903 // 7904 // If the settings aren't null, sync them up with what we've just derived. 7905 // note that apkRoot isn't stored in the package settings. 7906 if (pkgSetting != null) { 7907 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7908 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7909 } 7910 } 7911 7912 /** 7913 * Deduces the ABI of a bundled app and sets the relevant fields on the 7914 * parsed pkg object. 7915 * 7916 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7917 * under which system libraries are installed. 7918 * @param apkName the name of the installed package. 7919 */ 7920 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7921 final File codeFile = new File(pkg.codePath); 7922 7923 final boolean has64BitLibs; 7924 final boolean has32BitLibs; 7925 if (isApkFile(codeFile)) { 7926 // Monolithic install 7927 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7928 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7929 } else { 7930 // Cluster install 7931 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7932 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7933 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7934 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7935 has64BitLibs = (new File(rootDir, isa)).exists(); 7936 } else { 7937 has64BitLibs = false; 7938 } 7939 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7940 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7941 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7942 has32BitLibs = (new File(rootDir, isa)).exists(); 7943 } else { 7944 has32BitLibs = false; 7945 } 7946 } 7947 7948 if (has64BitLibs && !has32BitLibs) { 7949 // The package has 64 bit libs, but not 32 bit libs. Its primary 7950 // ABI should be 64 bit. We can safely assume here that the bundled 7951 // native libraries correspond to the most preferred ABI in the list. 7952 7953 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7954 pkg.applicationInfo.secondaryCpuAbi = null; 7955 } else if (has32BitLibs && !has64BitLibs) { 7956 // The package has 32 bit libs but not 64 bit libs. Its primary 7957 // ABI should be 32 bit. 7958 7959 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7960 pkg.applicationInfo.secondaryCpuAbi = null; 7961 } else if (has32BitLibs && has64BitLibs) { 7962 // The application has both 64 and 32 bit bundled libraries. We check 7963 // here that the app declares multiArch support, and warn if it doesn't. 7964 // 7965 // We will be lenient here and record both ABIs. The primary will be the 7966 // ABI that's higher on the list, i.e, a device that's configured to prefer 7967 // 64 bit apps will see a 64 bit primary ABI, 7968 7969 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7970 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7971 } 7972 7973 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7974 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7975 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7976 } else { 7977 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7978 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7979 } 7980 } else { 7981 pkg.applicationInfo.primaryCpuAbi = null; 7982 pkg.applicationInfo.secondaryCpuAbi = null; 7983 } 7984 } 7985 7986 private void killApplication(String pkgName, int appId, String reason) { 7987 // Request the ActivityManager to kill the process(only for existing packages) 7988 // so that we do not end up in a confused state while the user is still using the older 7989 // version of the application while the new one gets installed. 7990 IActivityManager am = ActivityManagerNative.getDefault(); 7991 if (am != null) { 7992 try { 7993 am.killApplicationWithAppId(pkgName, appId, reason); 7994 } catch (RemoteException e) { 7995 } 7996 } 7997 } 7998 7999 void removePackageLI(PackageSetting ps, boolean chatty) { 8000 if (DEBUG_INSTALL) { 8001 if (chatty) 8002 Log.d(TAG, "Removing package " + ps.name); 8003 } 8004 8005 // writer 8006 synchronized (mPackages) { 8007 mPackages.remove(ps.name); 8008 final PackageParser.Package pkg = ps.pkg; 8009 if (pkg != null) { 8010 cleanPackageDataStructuresLILPw(pkg, chatty); 8011 } 8012 } 8013 } 8014 8015 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8016 if (DEBUG_INSTALL) { 8017 if (chatty) 8018 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8019 } 8020 8021 // writer 8022 synchronized (mPackages) { 8023 mPackages.remove(pkg.applicationInfo.packageName); 8024 cleanPackageDataStructuresLILPw(pkg, chatty); 8025 } 8026 } 8027 8028 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8029 int N = pkg.providers.size(); 8030 StringBuilder r = null; 8031 int i; 8032 for (i=0; i<N; i++) { 8033 PackageParser.Provider p = pkg.providers.get(i); 8034 mProviders.removeProvider(p); 8035 if (p.info.authority == null) { 8036 8037 /* There was another ContentProvider with this authority when 8038 * this app was installed so this authority is null, 8039 * Ignore it as we don't have to unregister the provider. 8040 */ 8041 continue; 8042 } 8043 String names[] = p.info.authority.split(";"); 8044 for (int j = 0; j < names.length; j++) { 8045 if (mProvidersByAuthority.get(names[j]) == p) { 8046 mProvidersByAuthority.remove(names[j]); 8047 if (DEBUG_REMOVE) { 8048 if (chatty) 8049 Log.d(TAG, "Unregistered content provider: " + names[j] 8050 + ", className = " + p.info.name + ", isSyncable = " 8051 + p.info.isSyncable); 8052 } 8053 } 8054 } 8055 if (DEBUG_REMOVE && chatty) { 8056 if (r == null) { 8057 r = new StringBuilder(256); 8058 } else { 8059 r.append(' '); 8060 } 8061 r.append(p.info.name); 8062 } 8063 } 8064 if (r != null) { 8065 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8066 } 8067 8068 N = pkg.services.size(); 8069 r = null; 8070 for (i=0; i<N; i++) { 8071 PackageParser.Service s = pkg.services.get(i); 8072 mServices.removeService(s); 8073 if (chatty) { 8074 if (r == null) { 8075 r = new StringBuilder(256); 8076 } else { 8077 r.append(' '); 8078 } 8079 r.append(s.info.name); 8080 } 8081 } 8082 if (r != null) { 8083 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8084 } 8085 8086 N = pkg.receivers.size(); 8087 r = null; 8088 for (i=0; i<N; i++) { 8089 PackageParser.Activity a = pkg.receivers.get(i); 8090 mReceivers.removeActivity(a, "receiver"); 8091 if (DEBUG_REMOVE && chatty) { 8092 if (r == null) { 8093 r = new StringBuilder(256); 8094 } else { 8095 r.append(' '); 8096 } 8097 r.append(a.info.name); 8098 } 8099 } 8100 if (r != null) { 8101 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8102 } 8103 8104 N = pkg.activities.size(); 8105 r = null; 8106 for (i=0; i<N; i++) { 8107 PackageParser.Activity a = pkg.activities.get(i); 8108 mActivities.removeActivity(a, "activity"); 8109 if (DEBUG_REMOVE && chatty) { 8110 if (r == null) { 8111 r = new StringBuilder(256); 8112 } else { 8113 r.append(' '); 8114 } 8115 r.append(a.info.name); 8116 } 8117 } 8118 if (r != null) { 8119 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8120 } 8121 8122 N = pkg.permissions.size(); 8123 r = null; 8124 for (i=0; i<N; i++) { 8125 PackageParser.Permission p = pkg.permissions.get(i); 8126 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8127 if (bp == null) { 8128 bp = mSettings.mPermissionTrees.get(p.info.name); 8129 } 8130 if (bp != null && bp.perm == p) { 8131 bp.perm = null; 8132 if (DEBUG_REMOVE && chatty) { 8133 if (r == null) { 8134 r = new StringBuilder(256); 8135 } else { 8136 r.append(' '); 8137 } 8138 r.append(p.info.name); 8139 } 8140 } 8141 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8142 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8143 if (appOpPerms != null) { 8144 appOpPerms.remove(pkg.packageName); 8145 } 8146 } 8147 } 8148 if (r != null) { 8149 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8150 } 8151 8152 N = pkg.requestedPermissions.size(); 8153 r = null; 8154 for (i=0; i<N; i++) { 8155 String perm = pkg.requestedPermissions.get(i); 8156 BasePermission bp = mSettings.mPermissions.get(perm); 8157 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8158 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8159 if (appOpPerms != null) { 8160 appOpPerms.remove(pkg.packageName); 8161 if (appOpPerms.isEmpty()) { 8162 mAppOpPermissionPackages.remove(perm); 8163 } 8164 } 8165 } 8166 } 8167 if (r != null) { 8168 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8169 } 8170 8171 N = pkg.instrumentation.size(); 8172 r = null; 8173 for (i=0; i<N; i++) { 8174 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8175 mInstrumentation.remove(a.getComponentName()); 8176 if (DEBUG_REMOVE && chatty) { 8177 if (r == null) { 8178 r = new StringBuilder(256); 8179 } else { 8180 r.append(' '); 8181 } 8182 r.append(a.info.name); 8183 } 8184 } 8185 if (r != null) { 8186 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8187 } 8188 8189 r = null; 8190 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8191 // Only system apps can hold shared libraries. 8192 if (pkg.libraryNames != null) { 8193 for (i=0; i<pkg.libraryNames.size(); i++) { 8194 String name = pkg.libraryNames.get(i); 8195 SharedLibraryEntry cur = mSharedLibraries.get(name); 8196 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8197 mSharedLibraries.remove(name); 8198 if (DEBUG_REMOVE && chatty) { 8199 if (r == null) { 8200 r = new StringBuilder(256); 8201 } else { 8202 r.append(' '); 8203 } 8204 r.append(name); 8205 } 8206 } 8207 } 8208 } 8209 } 8210 if (r != null) { 8211 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8212 } 8213 } 8214 8215 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8216 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8217 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8218 return true; 8219 } 8220 } 8221 return false; 8222 } 8223 8224 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8225 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8226 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8227 8228 private void updatePermissionsLPw(String changingPkg, 8229 PackageParser.Package pkgInfo, int flags) { 8230 // Make sure there are no dangling permission trees. 8231 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8232 while (it.hasNext()) { 8233 final BasePermission bp = it.next(); 8234 if (bp.packageSetting == null) { 8235 // We may not yet have parsed the package, so just see if 8236 // we still know about its settings. 8237 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8238 } 8239 if (bp.packageSetting == null) { 8240 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8241 + " from package " + bp.sourcePackage); 8242 it.remove(); 8243 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8244 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8245 Slog.i(TAG, "Removing old permission tree: " + bp.name 8246 + " from package " + bp.sourcePackage); 8247 flags |= UPDATE_PERMISSIONS_ALL; 8248 it.remove(); 8249 } 8250 } 8251 } 8252 8253 // Make sure all dynamic permissions have been assigned to a package, 8254 // and make sure there are no dangling permissions. 8255 it = mSettings.mPermissions.values().iterator(); 8256 while (it.hasNext()) { 8257 final BasePermission bp = it.next(); 8258 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8259 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8260 + bp.name + " pkg=" + bp.sourcePackage 8261 + " info=" + bp.pendingInfo); 8262 if (bp.packageSetting == null && bp.pendingInfo != null) { 8263 final BasePermission tree = findPermissionTreeLP(bp.name); 8264 if (tree != null && tree.perm != null) { 8265 bp.packageSetting = tree.packageSetting; 8266 bp.perm = new PackageParser.Permission(tree.perm.owner, 8267 new PermissionInfo(bp.pendingInfo)); 8268 bp.perm.info.packageName = tree.perm.info.packageName; 8269 bp.perm.info.name = bp.name; 8270 bp.uid = tree.uid; 8271 } 8272 } 8273 } 8274 if (bp.packageSetting == null) { 8275 // We may not yet have parsed the package, so just see if 8276 // we still know about its settings. 8277 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8278 } 8279 if (bp.packageSetting == null) { 8280 Slog.w(TAG, "Removing dangling permission: " + bp.name 8281 + " from package " + bp.sourcePackage); 8282 it.remove(); 8283 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8284 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8285 Slog.i(TAG, "Removing old permission: " + bp.name 8286 + " from package " + bp.sourcePackage); 8287 flags |= UPDATE_PERMISSIONS_ALL; 8288 it.remove(); 8289 } 8290 } 8291 } 8292 8293 // Now update the permissions for all packages, in particular 8294 // replace the granted permissions of the system packages. 8295 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8296 for (PackageParser.Package pkg : mPackages.values()) { 8297 if (pkg != pkgInfo) { 8298 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8299 changingPkg); 8300 } 8301 } 8302 } 8303 8304 if (pkgInfo != null) { 8305 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8306 } 8307 } 8308 8309 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8310 String packageOfInterest) { 8311 // IMPORTANT: There are two types of permissions: install and runtime. 8312 // Install time permissions are granted when the app is installed to 8313 // all device users and users added in the future. Runtime permissions 8314 // are granted at runtime explicitly to specific users. Normal and signature 8315 // protected permissions are install time permissions. Dangerous permissions 8316 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8317 // otherwise they are runtime permissions. This function does not manage 8318 // runtime permissions except for the case an app targeting Lollipop MR1 8319 // being upgraded to target a newer SDK, in which case dangerous permissions 8320 // are transformed from install time to runtime ones. 8321 8322 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8323 if (ps == null) { 8324 return; 8325 } 8326 8327 PermissionsState permissionsState = ps.getPermissionsState(); 8328 PermissionsState origPermissions = permissionsState; 8329 8330 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8331 8332 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8333 8334 boolean changedInstallPermission = false; 8335 8336 if (replace) { 8337 ps.installPermissionsFixed = false; 8338 if (!ps.isSharedUser()) { 8339 origPermissions = new PermissionsState(permissionsState); 8340 permissionsState.reset(); 8341 } 8342 } 8343 8344 permissionsState.setGlobalGids(mGlobalGids); 8345 8346 final int N = pkg.requestedPermissions.size(); 8347 for (int i=0; i<N; i++) { 8348 final String name = pkg.requestedPermissions.get(i); 8349 final BasePermission bp = mSettings.mPermissions.get(name); 8350 8351 if (DEBUG_INSTALL) { 8352 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8353 } 8354 8355 if (bp == null || bp.packageSetting == null) { 8356 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8357 Slog.w(TAG, "Unknown permission " + name 8358 + " in package " + pkg.packageName); 8359 } 8360 continue; 8361 } 8362 8363 final String perm = bp.name; 8364 boolean allowedSig = false; 8365 int grant = GRANT_DENIED; 8366 8367 // Keep track of app op permissions. 8368 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8369 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8370 if (pkgs == null) { 8371 pkgs = new ArraySet<>(); 8372 mAppOpPermissionPackages.put(bp.name, pkgs); 8373 } 8374 pkgs.add(pkg.packageName); 8375 } 8376 8377 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8378 switch (level) { 8379 case PermissionInfo.PROTECTION_NORMAL: { 8380 // For all apps normal permissions are install time ones. 8381 grant = GRANT_INSTALL; 8382 } break; 8383 8384 case PermissionInfo.PROTECTION_DANGEROUS: { 8385 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8386 // For legacy apps dangerous permissions are install time ones. 8387 grant = GRANT_INSTALL_LEGACY; 8388 } else if (origPermissions.hasInstallPermission(bp.name)) { 8389 // For legacy apps that became modern, install becomes runtime. 8390 grant = GRANT_UPGRADE; 8391 } else if (mPromoteSystemApps 8392 && isSystemApp(ps) 8393 && mExistingSystemPackages.contains(ps.name)) { 8394 // For legacy system apps, install becomes runtime. 8395 // We cannot check hasInstallPermission() for system apps since those 8396 // permissions were granted implicitly and not persisted pre-M. 8397 grant = GRANT_UPGRADE; 8398 } else { 8399 // For modern apps keep runtime permissions unchanged. 8400 grant = GRANT_RUNTIME; 8401 } 8402 } break; 8403 8404 case PermissionInfo.PROTECTION_SIGNATURE: { 8405 // For all apps signature permissions are install time ones. 8406 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8407 if (allowedSig) { 8408 grant = GRANT_INSTALL; 8409 } 8410 } break; 8411 } 8412 8413 if (DEBUG_INSTALL) { 8414 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8415 } 8416 8417 if (grant != GRANT_DENIED) { 8418 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8419 // If this is an existing, non-system package, then 8420 // we can't add any new permissions to it. 8421 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8422 // Except... if this is a permission that was added 8423 // to the platform (note: need to only do this when 8424 // updating the platform). 8425 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8426 grant = GRANT_DENIED; 8427 } 8428 } 8429 } 8430 8431 switch (grant) { 8432 case GRANT_INSTALL: { 8433 // Revoke this as runtime permission to handle the case of 8434 // a runtime permission being downgraded to an install one. 8435 for (int userId : UserManagerService.getInstance().getUserIds()) { 8436 if (origPermissions.getRuntimePermissionState( 8437 bp.name, userId) != null) { 8438 // Revoke the runtime permission and clear the flags. 8439 origPermissions.revokeRuntimePermission(bp, userId); 8440 origPermissions.updatePermissionFlags(bp, userId, 8441 PackageManager.MASK_PERMISSION_FLAGS, 0); 8442 // If we revoked a permission permission, we have to write. 8443 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8444 changedRuntimePermissionUserIds, userId); 8445 } 8446 } 8447 // Grant an install permission. 8448 if (permissionsState.grantInstallPermission(bp) != 8449 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8450 changedInstallPermission = true; 8451 } 8452 } break; 8453 8454 case GRANT_INSTALL_LEGACY: { 8455 // Grant an install permission. 8456 if (permissionsState.grantInstallPermission(bp) != 8457 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8458 changedInstallPermission = true; 8459 } 8460 } break; 8461 8462 case GRANT_RUNTIME: { 8463 // Grant previously granted runtime permissions. 8464 for (int userId : UserManagerService.getInstance().getUserIds()) { 8465 PermissionState permissionState = origPermissions 8466 .getRuntimePermissionState(bp.name, userId); 8467 final int flags = permissionState != null 8468 ? permissionState.getFlags() : 0; 8469 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8470 if (permissionsState.grantRuntimePermission(bp, userId) == 8471 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8472 // If we cannot put the permission as it was, we have to write. 8473 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8474 changedRuntimePermissionUserIds, userId); 8475 } 8476 } 8477 // Propagate the permission flags. 8478 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8479 } 8480 } break; 8481 8482 case GRANT_UPGRADE: { 8483 // Grant runtime permissions for a previously held install permission. 8484 PermissionState permissionState = origPermissions 8485 .getInstallPermissionState(bp.name); 8486 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8487 8488 if (origPermissions.revokeInstallPermission(bp) 8489 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8490 // We will be transferring the permission flags, so clear them. 8491 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8492 PackageManager.MASK_PERMISSION_FLAGS, 0); 8493 changedInstallPermission = true; 8494 } 8495 8496 // If the permission is not to be promoted to runtime we ignore it and 8497 // also its other flags as they are not applicable to install permissions. 8498 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8499 for (int userId : currentUserIds) { 8500 if (permissionsState.grantRuntimePermission(bp, userId) != 8501 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8502 // Transfer the permission flags. 8503 permissionsState.updatePermissionFlags(bp, userId, 8504 flags, flags); 8505 // If we granted the permission, we have to write. 8506 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8507 changedRuntimePermissionUserIds, userId); 8508 } 8509 } 8510 } 8511 } break; 8512 8513 default: { 8514 if (packageOfInterest == null 8515 || packageOfInterest.equals(pkg.packageName)) { 8516 Slog.w(TAG, "Not granting permission " + perm 8517 + " to package " + pkg.packageName 8518 + " because it was previously installed without"); 8519 } 8520 } break; 8521 } 8522 } else { 8523 if (permissionsState.revokeInstallPermission(bp) != 8524 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8525 // Also drop the permission flags. 8526 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8527 PackageManager.MASK_PERMISSION_FLAGS, 0); 8528 changedInstallPermission = true; 8529 Slog.i(TAG, "Un-granting permission " + perm 8530 + " from package " + pkg.packageName 8531 + " (protectionLevel=" + bp.protectionLevel 8532 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8533 + ")"); 8534 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8535 // Don't print warning for app op permissions, since it is fine for them 8536 // not to be granted, there is a UI for the user to decide. 8537 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8538 Slog.w(TAG, "Not granting permission " + perm 8539 + " to package " + pkg.packageName 8540 + " (protectionLevel=" + bp.protectionLevel 8541 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8542 + ")"); 8543 } 8544 } 8545 } 8546 } 8547 8548 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8549 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8550 // This is the first that we have heard about this package, so the 8551 // permissions we have now selected are fixed until explicitly 8552 // changed. 8553 ps.installPermissionsFixed = true; 8554 } 8555 8556 // Persist the runtime permissions state for users with changes. 8557 for (int userId : changedRuntimePermissionUserIds) { 8558 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8559 } 8560 } 8561 8562 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8563 boolean allowed = false; 8564 final int NP = PackageParser.NEW_PERMISSIONS.length; 8565 for (int ip=0; ip<NP; ip++) { 8566 final PackageParser.NewPermissionInfo npi 8567 = PackageParser.NEW_PERMISSIONS[ip]; 8568 if (npi.name.equals(perm) 8569 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8570 allowed = true; 8571 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8572 + pkg.packageName); 8573 break; 8574 } 8575 } 8576 return allowed; 8577 } 8578 8579 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8580 BasePermission bp, PermissionsState origPermissions) { 8581 boolean allowed; 8582 allowed = (compareSignatures( 8583 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8584 == PackageManager.SIGNATURE_MATCH) 8585 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8586 == PackageManager.SIGNATURE_MATCH); 8587 if (!allowed && (bp.protectionLevel 8588 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8589 if (isSystemApp(pkg)) { 8590 // For updated system applications, a system permission 8591 // is granted only if it had been defined by the original application. 8592 if (pkg.isUpdatedSystemApp()) { 8593 final PackageSetting sysPs = mSettings 8594 .getDisabledSystemPkgLPr(pkg.packageName); 8595 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8596 // If the original was granted this permission, we take 8597 // that grant decision as read and propagate it to the 8598 // update. 8599 if (sysPs.isPrivileged()) { 8600 allowed = true; 8601 } 8602 } else { 8603 // The system apk may have been updated with an older 8604 // version of the one on the data partition, but which 8605 // granted a new system permission that it didn't have 8606 // before. In this case we do want to allow the app to 8607 // now get the new permission if the ancestral apk is 8608 // privileged to get it. 8609 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8610 for (int j=0; 8611 j<sysPs.pkg.requestedPermissions.size(); j++) { 8612 if (perm.equals( 8613 sysPs.pkg.requestedPermissions.get(j))) { 8614 allowed = true; 8615 break; 8616 } 8617 } 8618 } 8619 } 8620 } else { 8621 allowed = isPrivilegedApp(pkg); 8622 } 8623 } 8624 } 8625 if (!allowed) { 8626 if (!allowed && (bp.protectionLevel 8627 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8628 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8629 // If this was a previously normal/dangerous permission that got moved 8630 // to a system permission as part of the runtime permission redesign, then 8631 // we still want to blindly grant it to old apps. 8632 allowed = true; 8633 } 8634 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8635 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8636 // If this permission is to be granted to the system installer and 8637 // this app is an installer, then it gets the permission. 8638 allowed = true; 8639 } 8640 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8641 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8642 // If this permission is to be granted to the system verifier and 8643 // this app is a verifier, then it gets the permission. 8644 allowed = true; 8645 } 8646 if (!allowed && (bp.protectionLevel 8647 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8648 && isSystemApp(pkg)) { 8649 // Any pre-installed system app is allowed to get this permission. 8650 allowed = true; 8651 } 8652 if (!allowed && (bp.protectionLevel 8653 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8654 // For development permissions, a development permission 8655 // is granted only if it was already granted. 8656 allowed = origPermissions.hasInstallPermission(perm); 8657 } 8658 } 8659 return allowed; 8660 } 8661 8662 final class ActivityIntentResolver 8663 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8664 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8665 boolean defaultOnly, int userId) { 8666 if (!sUserManager.exists(userId)) return null; 8667 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8668 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8669 } 8670 8671 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8672 int userId) { 8673 if (!sUserManager.exists(userId)) return null; 8674 mFlags = flags; 8675 return super.queryIntent(intent, resolvedType, 8676 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8677 } 8678 8679 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8680 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8681 if (!sUserManager.exists(userId)) return null; 8682 if (packageActivities == null) { 8683 return null; 8684 } 8685 mFlags = flags; 8686 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8687 final int N = packageActivities.size(); 8688 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8689 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8690 8691 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8692 for (int i = 0; i < N; ++i) { 8693 intentFilters = packageActivities.get(i).intents; 8694 if (intentFilters != null && intentFilters.size() > 0) { 8695 PackageParser.ActivityIntentInfo[] array = 8696 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8697 intentFilters.toArray(array); 8698 listCut.add(array); 8699 } 8700 } 8701 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8702 } 8703 8704 public final void addActivity(PackageParser.Activity a, String type) { 8705 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8706 mActivities.put(a.getComponentName(), a); 8707 if (DEBUG_SHOW_INFO) 8708 Log.v( 8709 TAG, " " + type + " " + 8710 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8711 if (DEBUG_SHOW_INFO) 8712 Log.v(TAG, " Class=" + a.info.name); 8713 final int NI = a.intents.size(); 8714 for (int j=0; j<NI; j++) { 8715 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8716 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8717 intent.setPriority(0); 8718 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8719 + a.className + " with priority > 0, forcing to 0"); 8720 } 8721 if (DEBUG_SHOW_INFO) { 8722 Log.v(TAG, " IntentFilter:"); 8723 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8724 } 8725 if (!intent.debugCheck()) { 8726 Log.w(TAG, "==> For Activity " + a.info.name); 8727 } 8728 addFilter(intent); 8729 } 8730 } 8731 8732 public final void removeActivity(PackageParser.Activity a, String type) { 8733 mActivities.remove(a.getComponentName()); 8734 if (DEBUG_SHOW_INFO) { 8735 Log.v(TAG, " " + type + " " 8736 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8737 : a.info.name) + ":"); 8738 Log.v(TAG, " Class=" + a.info.name); 8739 } 8740 final int NI = a.intents.size(); 8741 for (int j=0; j<NI; j++) { 8742 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8743 if (DEBUG_SHOW_INFO) { 8744 Log.v(TAG, " IntentFilter:"); 8745 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8746 } 8747 removeFilter(intent); 8748 } 8749 } 8750 8751 @Override 8752 protected boolean allowFilterResult( 8753 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8754 ActivityInfo filterAi = filter.activity.info; 8755 for (int i=dest.size()-1; i>=0; i--) { 8756 ActivityInfo destAi = dest.get(i).activityInfo; 8757 if (destAi.name == filterAi.name 8758 && destAi.packageName == filterAi.packageName) { 8759 return false; 8760 } 8761 } 8762 return true; 8763 } 8764 8765 @Override 8766 protected ActivityIntentInfo[] newArray(int size) { 8767 return new ActivityIntentInfo[size]; 8768 } 8769 8770 @Override 8771 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8772 if (!sUserManager.exists(userId)) return true; 8773 PackageParser.Package p = filter.activity.owner; 8774 if (p != null) { 8775 PackageSetting ps = (PackageSetting)p.mExtras; 8776 if (ps != null) { 8777 // System apps are never considered stopped for purposes of 8778 // filtering, because there may be no way for the user to 8779 // actually re-launch them. 8780 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8781 && ps.getStopped(userId); 8782 } 8783 } 8784 return false; 8785 } 8786 8787 @Override 8788 protected boolean isPackageForFilter(String packageName, 8789 PackageParser.ActivityIntentInfo info) { 8790 return packageName.equals(info.activity.owner.packageName); 8791 } 8792 8793 @Override 8794 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8795 int match, int userId) { 8796 if (!sUserManager.exists(userId)) return null; 8797 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8798 return null; 8799 } 8800 final PackageParser.Activity activity = info.activity; 8801 if (mSafeMode && (activity.info.applicationInfo.flags 8802 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8803 return null; 8804 } 8805 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8806 if (ps == null) { 8807 return null; 8808 } 8809 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8810 ps.readUserState(userId), userId); 8811 if (ai == null) { 8812 return null; 8813 } 8814 final ResolveInfo res = new ResolveInfo(); 8815 res.activityInfo = ai; 8816 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8817 res.filter = info; 8818 } 8819 if (info != null) { 8820 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8821 } 8822 res.priority = info.getPriority(); 8823 res.preferredOrder = activity.owner.mPreferredOrder; 8824 //System.out.println("Result: " + res.activityInfo.className + 8825 // " = " + res.priority); 8826 res.match = match; 8827 res.isDefault = info.hasDefault; 8828 res.labelRes = info.labelRes; 8829 res.nonLocalizedLabel = info.nonLocalizedLabel; 8830 if (userNeedsBadging(userId)) { 8831 res.noResourceId = true; 8832 } else { 8833 res.icon = info.icon; 8834 } 8835 res.iconResourceId = info.icon; 8836 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8837 return res; 8838 } 8839 8840 @Override 8841 protected void sortResults(List<ResolveInfo> results) { 8842 Collections.sort(results, mResolvePrioritySorter); 8843 } 8844 8845 @Override 8846 protected void dumpFilter(PrintWriter out, String prefix, 8847 PackageParser.ActivityIntentInfo filter) { 8848 out.print(prefix); out.print( 8849 Integer.toHexString(System.identityHashCode(filter.activity))); 8850 out.print(' '); 8851 filter.activity.printComponentShortName(out); 8852 out.print(" filter "); 8853 out.println(Integer.toHexString(System.identityHashCode(filter))); 8854 } 8855 8856 @Override 8857 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8858 return filter.activity; 8859 } 8860 8861 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8862 PackageParser.Activity activity = (PackageParser.Activity)label; 8863 out.print(prefix); out.print( 8864 Integer.toHexString(System.identityHashCode(activity))); 8865 out.print(' '); 8866 activity.printComponentShortName(out); 8867 if (count > 1) { 8868 out.print(" ("); out.print(count); out.print(" filters)"); 8869 } 8870 out.println(); 8871 } 8872 8873// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8874// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8875// final List<ResolveInfo> retList = Lists.newArrayList(); 8876// while (i.hasNext()) { 8877// final ResolveInfo resolveInfo = i.next(); 8878// if (isEnabledLP(resolveInfo.activityInfo)) { 8879// retList.add(resolveInfo); 8880// } 8881// } 8882// return retList; 8883// } 8884 8885 // Keys are String (activity class name), values are Activity. 8886 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8887 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8888 private int mFlags; 8889 } 8890 8891 private final class ServiceIntentResolver 8892 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8893 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8894 boolean defaultOnly, int userId) { 8895 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8896 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8897 } 8898 8899 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8900 int userId) { 8901 if (!sUserManager.exists(userId)) return null; 8902 mFlags = flags; 8903 return super.queryIntent(intent, resolvedType, 8904 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8905 } 8906 8907 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8908 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8909 if (!sUserManager.exists(userId)) return null; 8910 if (packageServices == null) { 8911 return null; 8912 } 8913 mFlags = flags; 8914 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8915 final int N = packageServices.size(); 8916 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8917 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8918 8919 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8920 for (int i = 0; i < N; ++i) { 8921 intentFilters = packageServices.get(i).intents; 8922 if (intentFilters != null && intentFilters.size() > 0) { 8923 PackageParser.ServiceIntentInfo[] array = 8924 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8925 intentFilters.toArray(array); 8926 listCut.add(array); 8927 } 8928 } 8929 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8930 } 8931 8932 public final void addService(PackageParser.Service s) { 8933 mServices.put(s.getComponentName(), s); 8934 if (DEBUG_SHOW_INFO) { 8935 Log.v(TAG, " " 8936 + (s.info.nonLocalizedLabel != null 8937 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8938 Log.v(TAG, " Class=" + s.info.name); 8939 } 8940 final int NI = s.intents.size(); 8941 int j; 8942 for (j=0; j<NI; j++) { 8943 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8944 if (DEBUG_SHOW_INFO) { 8945 Log.v(TAG, " IntentFilter:"); 8946 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8947 } 8948 if (!intent.debugCheck()) { 8949 Log.w(TAG, "==> For Service " + s.info.name); 8950 } 8951 addFilter(intent); 8952 } 8953 } 8954 8955 public final void removeService(PackageParser.Service s) { 8956 mServices.remove(s.getComponentName()); 8957 if (DEBUG_SHOW_INFO) { 8958 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8959 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8960 Log.v(TAG, " Class=" + s.info.name); 8961 } 8962 final int NI = s.intents.size(); 8963 int j; 8964 for (j=0; j<NI; j++) { 8965 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8966 if (DEBUG_SHOW_INFO) { 8967 Log.v(TAG, " IntentFilter:"); 8968 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8969 } 8970 removeFilter(intent); 8971 } 8972 } 8973 8974 @Override 8975 protected boolean allowFilterResult( 8976 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8977 ServiceInfo filterSi = filter.service.info; 8978 for (int i=dest.size()-1; i>=0; i--) { 8979 ServiceInfo destAi = dest.get(i).serviceInfo; 8980 if (destAi.name == filterSi.name 8981 && destAi.packageName == filterSi.packageName) { 8982 return false; 8983 } 8984 } 8985 return true; 8986 } 8987 8988 @Override 8989 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8990 return new PackageParser.ServiceIntentInfo[size]; 8991 } 8992 8993 @Override 8994 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8995 if (!sUserManager.exists(userId)) return true; 8996 PackageParser.Package p = filter.service.owner; 8997 if (p != null) { 8998 PackageSetting ps = (PackageSetting)p.mExtras; 8999 if (ps != null) { 9000 // System apps are never considered stopped for purposes of 9001 // filtering, because there may be no way for the user to 9002 // actually re-launch them. 9003 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9004 && ps.getStopped(userId); 9005 } 9006 } 9007 return false; 9008 } 9009 9010 @Override 9011 protected boolean isPackageForFilter(String packageName, 9012 PackageParser.ServiceIntentInfo info) { 9013 return packageName.equals(info.service.owner.packageName); 9014 } 9015 9016 @Override 9017 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9018 int match, int userId) { 9019 if (!sUserManager.exists(userId)) return null; 9020 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9021 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9022 return null; 9023 } 9024 final PackageParser.Service service = info.service; 9025 if (mSafeMode && (service.info.applicationInfo.flags 9026 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9027 return null; 9028 } 9029 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9030 if (ps == null) { 9031 return null; 9032 } 9033 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9034 ps.readUserState(userId), userId); 9035 if (si == null) { 9036 return null; 9037 } 9038 final ResolveInfo res = new ResolveInfo(); 9039 res.serviceInfo = si; 9040 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9041 res.filter = filter; 9042 } 9043 res.priority = info.getPriority(); 9044 res.preferredOrder = service.owner.mPreferredOrder; 9045 res.match = match; 9046 res.isDefault = info.hasDefault; 9047 res.labelRes = info.labelRes; 9048 res.nonLocalizedLabel = info.nonLocalizedLabel; 9049 res.icon = info.icon; 9050 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9051 return res; 9052 } 9053 9054 @Override 9055 protected void sortResults(List<ResolveInfo> results) { 9056 Collections.sort(results, mResolvePrioritySorter); 9057 } 9058 9059 @Override 9060 protected void dumpFilter(PrintWriter out, String prefix, 9061 PackageParser.ServiceIntentInfo filter) { 9062 out.print(prefix); out.print( 9063 Integer.toHexString(System.identityHashCode(filter.service))); 9064 out.print(' '); 9065 filter.service.printComponentShortName(out); 9066 out.print(" filter "); 9067 out.println(Integer.toHexString(System.identityHashCode(filter))); 9068 } 9069 9070 @Override 9071 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9072 return filter.service; 9073 } 9074 9075 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9076 PackageParser.Service service = (PackageParser.Service)label; 9077 out.print(prefix); out.print( 9078 Integer.toHexString(System.identityHashCode(service))); 9079 out.print(' '); 9080 service.printComponentShortName(out); 9081 if (count > 1) { 9082 out.print(" ("); out.print(count); out.print(" filters)"); 9083 } 9084 out.println(); 9085 } 9086 9087// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9088// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9089// final List<ResolveInfo> retList = Lists.newArrayList(); 9090// while (i.hasNext()) { 9091// final ResolveInfo resolveInfo = (ResolveInfo) i; 9092// if (isEnabledLP(resolveInfo.serviceInfo)) { 9093// retList.add(resolveInfo); 9094// } 9095// } 9096// return retList; 9097// } 9098 9099 // Keys are String (activity class name), values are Activity. 9100 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9101 = new ArrayMap<ComponentName, PackageParser.Service>(); 9102 private int mFlags; 9103 }; 9104 9105 private final class ProviderIntentResolver 9106 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9107 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9108 boolean defaultOnly, int userId) { 9109 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9110 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9111 } 9112 9113 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9114 int userId) { 9115 if (!sUserManager.exists(userId)) 9116 return null; 9117 mFlags = flags; 9118 return super.queryIntent(intent, resolvedType, 9119 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9120 } 9121 9122 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9123 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9124 if (!sUserManager.exists(userId)) 9125 return null; 9126 if (packageProviders == null) { 9127 return null; 9128 } 9129 mFlags = flags; 9130 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9131 final int N = packageProviders.size(); 9132 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9133 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9134 9135 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9136 for (int i = 0; i < N; ++i) { 9137 intentFilters = packageProviders.get(i).intents; 9138 if (intentFilters != null && intentFilters.size() > 0) { 9139 PackageParser.ProviderIntentInfo[] array = 9140 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9141 intentFilters.toArray(array); 9142 listCut.add(array); 9143 } 9144 } 9145 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9146 } 9147 9148 public final void addProvider(PackageParser.Provider p) { 9149 if (mProviders.containsKey(p.getComponentName())) { 9150 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9151 return; 9152 } 9153 9154 mProviders.put(p.getComponentName(), p); 9155 if (DEBUG_SHOW_INFO) { 9156 Log.v(TAG, " " 9157 + (p.info.nonLocalizedLabel != null 9158 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9159 Log.v(TAG, " Class=" + p.info.name); 9160 } 9161 final int NI = p.intents.size(); 9162 int j; 9163 for (j = 0; j < NI; j++) { 9164 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9165 if (DEBUG_SHOW_INFO) { 9166 Log.v(TAG, " IntentFilter:"); 9167 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9168 } 9169 if (!intent.debugCheck()) { 9170 Log.w(TAG, "==> For Provider " + p.info.name); 9171 } 9172 addFilter(intent); 9173 } 9174 } 9175 9176 public final void removeProvider(PackageParser.Provider p) { 9177 mProviders.remove(p.getComponentName()); 9178 if (DEBUG_SHOW_INFO) { 9179 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9180 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9181 Log.v(TAG, " Class=" + p.info.name); 9182 } 9183 final int NI = p.intents.size(); 9184 int j; 9185 for (j = 0; j < NI; j++) { 9186 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9187 if (DEBUG_SHOW_INFO) { 9188 Log.v(TAG, " IntentFilter:"); 9189 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9190 } 9191 removeFilter(intent); 9192 } 9193 } 9194 9195 @Override 9196 protected boolean allowFilterResult( 9197 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9198 ProviderInfo filterPi = filter.provider.info; 9199 for (int i = dest.size() - 1; i >= 0; i--) { 9200 ProviderInfo destPi = dest.get(i).providerInfo; 9201 if (destPi.name == filterPi.name 9202 && destPi.packageName == filterPi.packageName) { 9203 return false; 9204 } 9205 } 9206 return true; 9207 } 9208 9209 @Override 9210 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9211 return new PackageParser.ProviderIntentInfo[size]; 9212 } 9213 9214 @Override 9215 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9216 if (!sUserManager.exists(userId)) 9217 return true; 9218 PackageParser.Package p = filter.provider.owner; 9219 if (p != null) { 9220 PackageSetting ps = (PackageSetting) p.mExtras; 9221 if (ps != null) { 9222 // System apps are never considered stopped for purposes of 9223 // filtering, because there may be no way for the user to 9224 // actually re-launch them. 9225 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9226 && ps.getStopped(userId); 9227 } 9228 } 9229 return false; 9230 } 9231 9232 @Override 9233 protected boolean isPackageForFilter(String packageName, 9234 PackageParser.ProviderIntentInfo info) { 9235 return packageName.equals(info.provider.owner.packageName); 9236 } 9237 9238 @Override 9239 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9240 int match, int userId) { 9241 if (!sUserManager.exists(userId)) 9242 return null; 9243 final PackageParser.ProviderIntentInfo info = filter; 9244 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9245 return null; 9246 } 9247 final PackageParser.Provider provider = info.provider; 9248 if (mSafeMode && (provider.info.applicationInfo.flags 9249 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9250 return null; 9251 } 9252 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9253 if (ps == null) { 9254 return null; 9255 } 9256 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9257 ps.readUserState(userId), userId); 9258 if (pi == null) { 9259 return null; 9260 } 9261 final ResolveInfo res = new ResolveInfo(); 9262 res.providerInfo = pi; 9263 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9264 res.filter = filter; 9265 } 9266 res.priority = info.getPriority(); 9267 res.preferredOrder = provider.owner.mPreferredOrder; 9268 res.match = match; 9269 res.isDefault = info.hasDefault; 9270 res.labelRes = info.labelRes; 9271 res.nonLocalizedLabel = info.nonLocalizedLabel; 9272 res.icon = info.icon; 9273 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9274 return res; 9275 } 9276 9277 @Override 9278 protected void sortResults(List<ResolveInfo> results) { 9279 Collections.sort(results, mResolvePrioritySorter); 9280 } 9281 9282 @Override 9283 protected void dumpFilter(PrintWriter out, String prefix, 9284 PackageParser.ProviderIntentInfo filter) { 9285 out.print(prefix); 9286 out.print( 9287 Integer.toHexString(System.identityHashCode(filter.provider))); 9288 out.print(' '); 9289 filter.provider.printComponentShortName(out); 9290 out.print(" filter "); 9291 out.println(Integer.toHexString(System.identityHashCode(filter))); 9292 } 9293 9294 @Override 9295 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9296 return filter.provider; 9297 } 9298 9299 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9300 PackageParser.Provider provider = (PackageParser.Provider)label; 9301 out.print(prefix); out.print( 9302 Integer.toHexString(System.identityHashCode(provider))); 9303 out.print(' '); 9304 provider.printComponentShortName(out); 9305 if (count > 1) { 9306 out.print(" ("); out.print(count); out.print(" filters)"); 9307 } 9308 out.println(); 9309 } 9310 9311 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9312 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9313 private int mFlags; 9314 }; 9315 9316 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9317 new Comparator<ResolveInfo>() { 9318 public int compare(ResolveInfo r1, ResolveInfo r2) { 9319 int v1 = r1.priority; 9320 int v2 = r2.priority; 9321 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9322 if (v1 != v2) { 9323 return (v1 > v2) ? -1 : 1; 9324 } 9325 v1 = r1.preferredOrder; 9326 v2 = r2.preferredOrder; 9327 if (v1 != v2) { 9328 return (v1 > v2) ? -1 : 1; 9329 } 9330 if (r1.isDefault != r2.isDefault) { 9331 return r1.isDefault ? -1 : 1; 9332 } 9333 v1 = r1.match; 9334 v2 = r2.match; 9335 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9336 if (v1 != v2) { 9337 return (v1 > v2) ? -1 : 1; 9338 } 9339 if (r1.system != r2.system) { 9340 return r1.system ? -1 : 1; 9341 } 9342 return 0; 9343 } 9344 }; 9345 9346 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9347 new Comparator<ProviderInfo>() { 9348 public int compare(ProviderInfo p1, ProviderInfo p2) { 9349 final int v1 = p1.initOrder; 9350 final int v2 = p2.initOrder; 9351 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9352 } 9353 }; 9354 9355 final void sendPackageBroadcast(final String action, final String pkg, 9356 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9357 final int[] userIds) { 9358 mHandler.post(new Runnable() { 9359 @Override 9360 public void run() { 9361 try { 9362 final IActivityManager am = ActivityManagerNative.getDefault(); 9363 if (am == null) return; 9364 final int[] resolvedUserIds; 9365 if (userIds == null) { 9366 resolvedUserIds = am.getRunningUserIds(); 9367 } else { 9368 resolvedUserIds = userIds; 9369 } 9370 for (int id : resolvedUserIds) { 9371 final Intent intent = new Intent(action, 9372 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9373 if (extras != null) { 9374 intent.putExtras(extras); 9375 } 9376 if (targetPkg != null) { 9377 intent.setPackage(targetPkg); 9378 } 9379 // Modify the UID when posting to other users 9380 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9381 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9382 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9383 intent.putExtra(Intent.EXTRA_UID, uid); 9384 } 9385 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9386 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9387 if (DEBUG_BROADCASTS) { 9388 RuntimeException here = new RuntimeException("here"); 9389 here.fillInStackTrace(); 9390 Slog.d(TAG, "Sending to user " + id + ": " 9391 + intent.toShortString(false, true, false, false) 9392 + " " + intent.getExtras(), here); 9393 } 9394 am.broadcastIntent(null, intent, null, finishedReceiver, 9395 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9396 null, finishedReceiver != null, false, id); 9397 } 9398 } catch (RemoteException ex) { 9399 } 9400 } 9401 }); 9402 } 9403 9404 /** 9405 * Check if the external storage media is available. This is true if there 9406 * is a mounted external storage medium or if the external storage is 9407 * emulated. 9408 */ 9409 private boolean isExternalMediaAvailable() { 9410 return mMediaMounted || Environment.isExternalStorageEmulated(); 9411 } 9412 9413 @Override 9414 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9415 // writer 9416 synchronized (mPackages) { 9417 if (!isExternalMediaAvailable()) { 9418 // If the external storage is no longer mounted at this point, 9419 // the caller may not have been able to delete all of this 9420 // packages files and can not delete any more. Bail. 9421 return null; 9422 } 9423 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9424 if (lastPackage != null) { 9425 pkgs.remove(lastPackage); 9426 } 9427 if (pkgs.size() > 0) { 9428 return pkgs.get(0); 9429 } 9430 } 9431 return null; 9432 } 9433 9434 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9435 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9436 userId, andCode ? 1 : 0, packageName); 9437 if (mSystemReady) { 9438 msg.sendToTarget(); 9439 } else { 9440 if (mPostSystemReadyMessages == null) { 9441 mPostSystemReadyMessages = new ArrayList<>(); 9442 } 9443 mPostSystemReadyMessages.add(msg); 9444 } 9445 } 9446 9447 void startCleaningPackages() { 9448 // reader 9449 synchronized (mPackages) { 9450 if (!isExternalMediaAvailable()) { 9451 return; 9452 } 9453 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9454 return; 9455 } 9456 } 9457 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9458 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9459 IActivityManager am = ActivityManagerNative.getDefault(); 9460 if (am != null) { 9461 try { 9462 am.startService(null, intent, null, mContext.getOpPackageName(), 9463 UserHandle.USER_OWNER); 9464 } catch (RemoteException e) { 9465 } 9466 } 9467 } 9468 9469 @Override 9470 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9471 int installFlags, String installerPackageName, VerificationParams verificationParams, 9472 String packageAbiOverride) { 9473 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9474 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9475 } 9476 9477 @Override 9478 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9479 int installFlags, String installerPackageName, VerificationParams verificationParams, 9480 String packageAbiOverride, int userId) { 9481 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9482 9483 final int callingUid = Binder.getCallingUid(); 9484 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9485 9486 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9487 try { 9488 if (observer != null) { 9489 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9490 } 9491 } catch (RemoteException re) { 9492 } 9493 return; 9494 } 9495 9496 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9497 installFlags |= PackageManager.INSTALL_FROM_ADB; 9498 9499 } else { 9500 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9501 // about installerPackageName. 9502 9503 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9504 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9505 } 9506 9507 UserHandle user; 9508 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9509 user = UserHandle.ALL; 9510 } else { 9511 user = new UserHandle(userId); 9512 } 9513 9514 // Only system components can circumvent runtime permissions when installing. 9515 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9516 && mContext.checkCallingOrSelfPermission(Manifest.permission 9517 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9518 throw new SecurityException("You need the " 9519 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9520 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9521 } 9522 9523 verificationParams.setInstallerUid(callingUid); 9524 9525 final File originFile = new File(originPath); 9526 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9527 9528 final Message msg = mHandler.obtainMessage(INIT_COPY); 9529 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9530 null, verificationParams, user, packageAbiOverride, null); 9531 mHandler.sendMessage(msg); 9532 } 9533 9534 void installStage(String packageName, File stagedDir, String stagedCid, 9535 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9536 String installerPackageName, int installerUid, UserHandle user) { 9537 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9538 params.referrerUri, installerUid, null); 9539 verifParams.setInstallerUid(installerUid); 9540 9541 final OriginInfo origin; 9542 if (stagedDir != null) { 9543 origin = OriginInfo.fromStagedFile(stagedDir); 9544 } else { 9545 origin = OriginInfo.fromStagedContainer(stagedCid); 9546 } 9547 9548 final Message msg = mHandler.obtainMessage(INIT_COPY); 9549 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9550 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9551 params.grantedRuntimePermissions); 9552 mHandler.sendMessage(msg); 9553 } 9554 9555 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9556 Bundle extras = new Bundle(1); 9557 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9558 9559 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9560 packageName, extras, null, null, new int[] {userId}); 9561 try { 9562 IActivityManager am = ActivityManagerNative.getDefault(); 9563 final boolean isSystem = 9564 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9565 if (isSystem && am.isUserRunning(userId, false)) { 9566 // The just-installed/enabled app is bundled on the system, so presumed 9567 // to be able to run automatically without needing an explicit launch. 9568 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9569 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9570 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9571 .setPackage(packageName); 9572 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9573 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9574 } 9575 } catch (RemoteException e) { 9576 // shouldn't happen 9577 Slog.w(TAG, "Unable to bootstrap installed package", e); 9578 } 9579 } 9580 9581 @Override 9582 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9583 int userId) { 9584 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9585 PackageSetting pkgSetting; 9586 final int uid = Binder.getCallingUid(); 9587 enforceCrossUserPermission(uid, userId, true, true, 9588 "setApplicationHiddenSetting for user " + userId); 9589 9590 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9591 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9592 return false; 9593 } 9594 9595 long callingId = Binder.clearCallingIdentity(); 9596 try { 9597 boolean sendAdded = false; 9598 boolean sendRemoved = false; 9599 // writer 9600 synchronized (mPackages) { 9601 pkgSetting = mSettings.mPackages.get(packageName); 9602 if (pkgSetting == null) { 9603 return false; 9604 } 9605 if (pkgSetting.getHidden(userId) != hidden) { 9606 pkgSetting.setHidden(hidden, userId); 9607 mSettings.writePackageRestrictionsLPr(userId); 9608 if (hidden) { 9609 sendRemoved = true; 9610 } else { 9611 sendAdded = true; 9612 } 9613 } 9614 } 9615 if (sendAdded) { 9616 sendPackageAddedForUser(packageName, pkgSetting, userId); 9617 return true; 9618 } 9619 if (sendRemoved) { 9620 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9621 "hiding pkg"); 9622 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9623 return true; 9624 } 9625 } finally { 9626 Binder.restoreCallingIdentity(callingId); 9627 } 9628 return false; 9629 } 9630 9631 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9632 int userId) { 9633 final PackageRemovedInfo info = new PackageRemovedInfo(); 9634 info.removedPackage = packageName; 9635 info.removedUsers = new int[] {userId}; 9636 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9637 info.sendBroadcast(false, false, false); 9638 } 9639 9640 /** 9641 * Returns true if application is not found or there was an error. Otherwise it returns 9642 * the hidden state of the package for the given user. 9643 */ 9644 @Override 9645 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9646 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9647 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9648 false, "getApplicationHidden for user " + userId); 9649 PackageSetting pkgSetting; 9650 long callingId = Binder.clearCallingIdentity(); 9651 try { 9652 // writer 9653 synchronized (mPackages) { 9654 pkgSetting = mSettings.mPackages.get(packageName); 9655 if (pkgSetting == null) { 9656 return true; 9657 } 9658 return pkgSetting.getHidden(userId); 9659 } 9660 } finally { 9661 Binder.restoreCallingIdentity(callingId); 9662 } 9663 } 9664 9665 /** 9666 * @hide 9667 */ 9668 @Override 9669 public int installExistingPackageAsUser(String packageName, int userId) { 9670 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9671 null); 9672 PackageSetting pkgSetting; 9673 final int uid = Binder.getCallingUid(); 9674 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9675 + userId); 9676 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9677 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9678 } 9679 9680 long callingId = Binder.clearCallingIdentity(); 9681 try { 9682 boolean sendAdded = false; 9683 9684 // writer 9685 synchronized (mPackages) { 9686 pkgSetting = mSettings.mPackages.get(packageName); 9687 if (pkgSetting == null) { 9688 return PackageManager.INSTALL_FAILED_INVALID_URI; 9689 } 9690 if (!pkgSetting.getInstalled(userId)) { 9691 pkgSetting.setInstalled(true, userId); 9692 pkgSetting.setHidden(false, userId); 9693 mSettings.writePackageRestrictionsLPr(userId); 9694 sendAdded = true; 9695 } 9696 } 9697 9698 if (sendAdded) { 9699 sendPackageAddedForUser(packageName, pkgSetting, userId); 9700 } 9701 } finally { 9702 Binder.restoreCallingIdentity(callingId); 9703 } 9704 9705 return PackageManager.INSTALL_SUCCEEDED; 9706 } 9707 9708 boolean isUserRestricted(int userId, String restrictionKey) { 9709 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9710 if (restrictions.getBoolean(restrictionKey, false)) { 9711 Log.w(TAG, "User is restricted: " + restrictionKey); 9712 return true; 9713 } 9714 return false; 9715 } 9716 9717 @Override 9718 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9719 mContext.enforceCallingOrSelfPermission( 9720 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9721 "Only package verification agents can verify applications"); 9722 9723 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9724 final PackageVerificationResponse response = new PackageVerificationResponse( 9725 verificationCode, Binder.getCallingUid()); 9726 msg.arg1 = id; 9727 msg.obj = response; 9728 mHandler.sendMessage(msg); 9729 } 9730 9731 @Override 9732 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9733 long millisecondsToDelay) { 9734 mContext.enforceCallingOrSelfPermission( 9735 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9736 "Only package verification agents can extend verification timeouts"); 9737 9738 final PackageVerificationState state = mPendingVerification.get(id); 9739 final PackageVerificationResponse response = new PackageVerificationResponse( 9740 verificationCodeAtTimeout, Binder.getCallingUid()); 9741 9742 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9743 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9744 } 9745 if (millisecondsToDelay < 0) { 9746 millisecondsToDelay = 0; 9747 } 9748 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9749 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9750 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9751 } 9752 9753 if ((state != null) && !state.timeoutExtended()) { 9754 state.extendTimeout(); 9755 9756 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9757 msg.arg1 = id; 9758 msg.obj = response; 9759 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9760 } 9761 } 9762 9763 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9764 int verificationCode, UserHandle user) { 9765 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9766 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9767 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9768 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9769 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9770 9771 mContext.sendBroadcastAsUser(intent, user, 9772 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9773 } 9774 9775 private ComponentName matchComponentForVerifier(String packageName, 9776 List<ResolveInfo> receivers) { 9777 ActivityInfo targetReceiver = null; 9778 9779 final int NR = receivers.size(); 9780 for (int i = 0; i < NR; i++) { 9781 final ResolveInfo info = receivers.get(i); 9782 if (info.activityInfo == null) { 9783 continue; 9784 } 9785 9786 if (packageName.equals(info.activityInfo.packageName)) { 9787 targetReceiver = info.activityInfo; 9788 break; 9789 } 9790 } 9791 9792 if (targetReceiver == null) { 9793 return null; 9794 } 9795 9796 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9797 } 9798 9799 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9800 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9801 if (pkgInfo.verifiers.length == 0) { 9802 return null; 9803 } 9804 9805 final int N = pkgInfo.verifiers.length; 9806 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9807 for (int i = 0; i < N; i++) { 9808 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9809 9810 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9811 receivers); 9812 if (comp == null) { 9813 continue; 9814 } 9815 9816 final int verifierUid = getUidForVerifier(verifierInfo); 9817 if (verifierUid == -1) { 9818 continue; 9819 } 9820 9821 if (DEBUG_VERIFY) { 9822 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9823 + " with the correct signature"); 9824 } 9825 sufficientVerifiers.add(comp); 9826 verificationState.addSufficientVerifier(verifierUid); 9827 } 9828 9829 return sufficientVerifiers; 9830 } 9831 9832 private int getUidForVerifier(VerifierInfo verifierInfo) { 9833 synchronized (mPackages) { 9834 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9835 if (pkg == null) { 9836 return -1; 9837 } else if (pkg.mSignatures.length != 1) { 9838 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9839 + " has more than one signature; ignoring"); 9840 return -1; 9841 } 9842 9843 /* 9844 * If the public key of the package's signature does not match 9845 * our expected public key, then this is a different package and 9846 * we should skip. 9847 */ 9848 9849 final byte[] expectedPublicKey; 9850 try { 9851 final Signature verifierSig = pkg.mSignatures[0]; 9852 final PublicKey publicKey = verifierSig.getPublicKey(); 9853 expectedPublicKey = publicKey.getEncoded(); 9854 } catch (CertificateException e) { 9855 return -1; 9856 } 9857 9858 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9859 9860 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9861 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9862 + " does not have the expected public key; ignoring"); 9863 return -1; 9864 } 9865 9866 return pkg.applicationInfo.uid; 9867 } 9868 } 9869 9870 @Override 9871 public void finishPackageInstall(int token) { 9872 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9873 9874 if (DEBUG_INSTALL) { 9875 Slog.v(TAG, "BM finishing package install for " + token); 9876 } 9877 9878 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9879 mHandler.sendMessage(msg); 9880 } 9881 9882 /** 9883 * Get the verification agent timeout. 9884 * 9885 * @return verification timeout in milliseconds 9886 */ 9887 private long getVerificationTimeout() { 9888 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9889 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9890 DEFAULT_VERIFICATION_TIMEOUT); 9891 } 9892 9893 /** 9894 * Get the default verification agent response code. 9895 * 9896 * @return default verification response code 9897 */ 9898 private int getDefaultVerificationResponse() { 9899 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9900 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9901 DEFAULT_VERIFICATION_RESPONSE); 9902 } 9903 9904 /** 9905 * Check whether or not package verification has been enabled. 9906 * 9907 * @return true if verification should be performed 9908 */ 9909 private boolean isVerificationEnabled(int userId, int installFlags) { 9910 if (!DEFAULT_VERIFY_ENABLE) { 9911 return false; 9912 } 9913 9914 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9915 9916 // Check if installing from ADB 9917 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9918 // Do not run verification in a test harness environment 9919 if (ActivityManager.isRunningInTestHarness()) { 9920 return false; 9921 } 9922 if (ensureVerifyAppsEnabled) { 9923 return true; 9924 } 9925 // Check if the developer does not want package verification for ADB installs 9926 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9927 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9928 return false; 9929 } 9930 } 9931 9932 if (ensureVerifyAppsEnabled) { 9933 return true; 9934 } 9935 9936 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9937 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9938 } 9939 9940 @Override 9941 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9942 throws RemoteException { 9943 mContext.enforceCallingOrSelfPermission( 9944 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9945 "Only intentfilter verification agents can verify applications"); 9946 9947 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9948 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9949 Binder.getCallingUid(), verificationCode, failedDomains); 9950 msg.arg1 = id; 9951 msg.obj = response; 9952 mHandler.sendMessage(msg); 9953 } 9954 9955 @Override 9956 public int getIntentVerificationStatus(String packageName, int userId) { 9957 synchronized (mPackages) { 9958 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9959 } 9960 } 9961 9962 @Override 9963 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9964 mContext.enforceCallingOrSelfPermission( 9965 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9966 9967 boolean result = false; 9968 synchronized (mPackages) { 9969 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9970 } 9971 if (result) { 9972 scheduleWritePackageRestrictionsLocked(userId); 9973 } 9974 return result; 9975 } 9976 9977 @Override 9978 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9979 synchronized (mPackages) { 9980 return mSettings.getIntentFilterVerificationsLPr(packageName); 9981 } 9982 } 9983 9984 @Override 9985 public List<IntentFilter> getAllIntentFilters(String packageName) { 9986 if (TextUtils.isEmpty(packageName)) { 9987 return Collections.<IntentFilter>emptyList(); 9988 } 9989 synchronized (mPackages) { 9990 PackageParser.Package pkg = mPackages.get(packageName); 9991 if (pkg == null || pkg.activities == null) { 9992 return Collections.<IntentFilter>emptyList(); 9993 } 9994 final int count = pkg.activities.size(); 9995 ArrayList<IntentFilter> result = new ArrayList<>(); 9996 for (int n=0; n<count; n++) { 9997 PackageParser.Activity activity = pkg.activities.get(n); 9998 if (activity.intents != null || activity.intents.size() > 0) { 9999 result.addAll(activity.intents); 10000 } 10001 } 10002 return result; 10003 } 10004 } 10005 10006 @Override 10007 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10008 mContext.enforceCallingOrSelfPermission( 10009 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10010 10011 synchronized (mPackages) { 10012 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10013 if (packageName != null) { 10014 result |= updateIntentVerificationStatus(packageName, 10015 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10016 userId); 10017 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10018 packageName, userId); 10019 } 10020 return result; 10021 } 10022 } 10023 10024 @Override 10025 public String getDefaultBrowserPackageName(int userId) { 10026 synchronized (mPackages) { 10027 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10028 } 10029 } 10030 10031 /** 10032 * Get the "allow unknown sources" setting. 10033 * 10034 * @return the current "allow unknown sources" setting 10035 */ 10036 private int getUnknownSourcesSettings() { 10037 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10038 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10039 -1); 10040 } 10041 10042 @Override 10043 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10044 final int uid = Binder.getCallingUid(); 10045 // writer 10046 synchronized (mPackages) { 10047 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10048 if (targetPackageSetting == null) { 10049 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10050 } 10051 10052 PackageSetting installerPackageSetting; 10053 if (installerPackageName != null) { 10054 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10055 if (installerPackageSetting == null) { 10056 throw new IllegalArgumentException("Unknown installer package: " 10057 + installerPackageName); 10058 } 10059 } else { 10060 installerPackageSetting = null; 10061 } 10062 10063 Signature[] callerSignature; 10064 Object obj = mSettings.getUserIdLPr(uid); 10065 if (obj != null) { 10066 if (obj instanceof SharedUserSetting) { 10067 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10068 } else if (obj instanceof PackageSetting) { 10069 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10070 } else { 10071 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10072 } 10073 } else { 10074 throw new SecurityException("Unknown calling uid " + uid); 10075 } 10076 10077 // Verify: can't set installerPackageName to a package that is 10078 // not signed with the same cert as the caller. 10079 if (installerPackageSetting != null) { 10080 if (compareSignatures(callerSignature, 10081 installerPackageSetting.signatures.mSignatures) 10082 != PackageManager.SIGNATURE_MATCH) { 10083 throw new SecurityException( 10084 "Caller does not have same cert as new installer package " 10085 + installerPackageName); 10086 } 10087 } 10088 10089 // Verify: if target already has an installer package, it must 10090 // be signed with the same cert as the caller. 10091 if (targetPackageSetting.installerPackageName != null) { 10092 PackageSetting setting = mSettings.mPackages.get( 10093 targetPackageSetting.installerPackageName); 10094 // If the currently set package isn't valid, then it's always 10095 // okay to change it. 10096 if (setting != null) { 10097 if (compareSignatures(callerSignature, 10098 setting.signatures.mSignatures) 10099 != PackageManager.SIGNATURE_MATCH) { 10100 throw new SecurityException( 10101 "Caller does not have same cert as old installer package " 10102 + targetPackageSetting.installerPackageName); 10103 } 10104 } 10105 } 10106 10107 // Okay! 10108 targetPackageSetting.installerPackageName = installerPackageName; 10109 scheduleWriteSettingsLocked(); 10110 } 10111 } 10112 10113 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10114 // Queue up an async operation since the package installation may take a little while. 10115 mHandler.post(new Runnable() { 10116 public void run() { 10117 mHandler.removeCallbacks(this); 10118 // Result object to be returned 10119 PackageInstalledInfo res = new PackageInstalledInfo(); 10120 res.returnCode = currentStatus; 10121 res.uid = -1; 10122 res.pkg = null; 10123 res.removedInfo = new PackageRemovedInfo(); 10124 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10125 args.doPreInstall(res.returnCode); 10126 synchronized (mInstallLock) { 10127 installPackageLI(args, res); 10128 } 10129 args.doPostInstall(res.returnCode, res.uid); 10130 } 10131 10132 // A restore should be performed at this point if (a) the install 10133 // succeeded, (b) the operation is not an update, and (c) the new 10134 // package has not opted out of backup participation. 10135 final boolean update = res.removedInfo.removedPackage != null; 10136 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10137 boolean doRestore = !update 10138 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10139 10140 // Set up the post-install work request bookkeeping. This will be used 10141 // and cleaned up by the post-install event handling regardless of whether 10142 // there's a restore pass performed. Token values are >= 1. 10143 int token; 10144 if (mNextInstallToken < 0) mNextInstallToken = 1; 10145 token = mNextInstallToken++; 10146 10147 PostInstallData data = new PostInstallData(args, res); 10148 mRunningInstalls.put(token, data); 10149 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10150 10151 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10152 // Pass responsibility to the Backup Manager. It will perform a 10153 // restore if appropriate, then pass responsibility back to the 10154 // Package Manager to run the post-install observer callbacks 10155 // and broadcasts. 10156 IBackupManager bm = IBackupManager.Stub.asInterface( 10157 ServiceManager.getService(Context.BACKUP_SERVICE)); 10158 if (bm != null) { 10159 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10160 + " to BM for possible restore"); 10161 try { 10162 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10163 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10164 } else { 10165 doRestore = false; 10166 } 10167 } catch (RemoteException e) { 10168 // can't happen; the backup manager is local 10169 } catch (Exception e) { 10170 Slog.e(TAG, "Exception trying to enqueue restore", e); 10171 doRestore = false; 10172 } 10173 } else { 10174 Slog.e(TAG, "Backup Manager not found!"); 10175 doRestore = false; 10176 } 10177 } 10178 10179 if (!doRestore) { 10180 // No restore possible, or the Backup Manager was mysteriously not 10181 // available -- just fire the post-install work request directly. 10182 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10183 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10184 mHandler.sendMessage(msg); 10185 } 10186 } 10187 }); 10188 } 10189 10190 private abstract class HandlerParams { 10191 private static final int MAX_RETRIES = 4; 10192 10193 /** 10194 * Number of times startCopy() has been attempted and had a non-fatal 10195 * error. 10196 */ 10197 private int mRetries = 0; 10198 10199 /** User handle for the user requesting the information or installation. */ 10200 private final UserHandle mUser; 10201 10202 HandlerParams(UserHandle user) { 10203 mUser = user; 10204 } 10205 10206 UserHandle getUser() { 10207 return mUser; 10208 } 10209 10210 final boolean startCopy() { 10211 boolean res; 10212 try { 10213 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10214 10215 if (++mRetries > MAX_RETRIES) { 10216 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10217 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10218 handleServiceError(); 10219 return false; 10220 } else { 10221 handleStartCopy(); 10222 res = true; 10223 } 10224 } catch (RemoteException e) { 10225 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10226 mHandler.sendEmptyMessage(MCS_RECONNECT); 10227 res = false; 10228 } 10229 handleReturnCode(); 10230 return res; 10231 } 10232 10233 final void serviceError() { 10234 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10235 handleServiceError(); 10236 handleReturnCode(); 10237 } 10238 10239 abstract void handleStartCopy() throws RemoteException; 10240 abstract void handleServiceError(); 10241 abstract void handleReturnCode(); 10242 } 10243 10244 class MeasureParams extends HandlerParams { 10245 private final PackageStats mStats; 10246 private boolean mSuccess; 10247 10248 private final IPackageStatsObserver mObserver; 10249 10250 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10251 super(new UserHandle(stats.userHandle)); 10252 mObserver = observer; 10253 mStats = stats; 10254 } 10255 10256 @Override 10257 public String toString() { 10258 return "MeasureParams{" 10259 + Integer.toHexString(System.identityHashCode(this)) 10260 + " " + mStats.packageName + "}"; 10261 } 10262 10263 @Override 10264 void handleStartCopy() throws RemoteException { 10265 synchronized (mInstallLock) { 10266 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10267 } 10268 10269 if (mSuccess) { 10270 final boolean mounted; 10271 if (Environment.isExternalStorageEmulated()) { 10272 mounted = true; 10273 } else { 10274 final String status = Environment.getExternalStorageState(); 10275 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10276 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10277 } 10278 10279 if (mounted) { 10280 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10281 10282 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10283 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10284 10285 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10286 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10287 10288 // Always subtract cache size, since it's a subdirectory 10289 mStats.externalDataSize -= mStats.externalCacheSize; 10290 10291 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10292 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10293 10294 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10295 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10296 } 10297 } 10298 } 10299 10300 @Override 10301 void handleReturnCode() { 10302 if (mObserver != null) { 10303 try { 10304 mObserver.onGetStatsCompleted(mStats, mSuccess); 10305 } catch (RemoteException e) { 10306 Slog.i(TAG, "Observer no longer exists."); 10307 } 10308 } 10309 } 10310 10311 @Override 10312 void handleServiceError() { 10313 Slog.e(TAG, "Could not measure application " + mStats.packageName 10314 + " external storage"); 10315 } 10316 } 10317 10318 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10319 throws RemoteException { 10320 long result = 0; 10321 for (File path : paths) { 10322 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10323 } 10324 return result; 10325 } 10326 10327 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10328 for (File path : paths) { 10329 try { 10330 mcs.clearDirectory(path.getAbsolutePath()); 10331 } catch (RemoteException e) { 10332 } 10333 } 10334 } 10335 10336 static class OriginInfo { 10337 /** 10338 * Location where install is coming from, before it has been 10339 * copied/renamed into place. This could be a single monolithic APK 10340 * file, or a cluster directory. This location may be untrusted. 10341 */ 10342 final File file; 10343 final String cid; 10344 10345 /** 10346 * Flag indicating that {@link #file} or {@link #cid} has already been 10347 * staged, meaning downstream users don't need to defensively copy the 10348 * contents. 10349 */ 10350 final boolean staged; 10351 10352 /** 10353 * Flag indicating that {@link #file} or {@link #cid} is an already 10354 * installed app that is being moved. 10355 */ 10356 final boolean existing; 10357 10358 final String resolvedPath; 10359 final File resolvedFile; 10360 10361 static OriginInfo fromNothing() { 10362 return new OriginInfo(null, null, false, false); 10363 } 10364 10365 static OriginInfo fromUntrustedFile(File file) { 10366 return new OriginInfo(file, null, false, false); 10367 } 10368 10369 static OriginInfo fromExistingFile(File file) { 10370 return new OriginInfo(file, null, false, true); 10371 } 10372 10373 static OriginInfo fromStagedFile(File file) { 10374 return new OriginInfo(file, null, true, false); 10375 } 10376 10377 static OriginInfo fromStagedContainer(String cid) { 10378 return new OriginInfo(null, cid, true, false); 10379 } 10380 10381 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10382 this.file = file; 10383 this.cid = cid; 10384 this.staged = staged; 10385 this.existing = existing; 10386 10387 if (cid != null) { 10388 resolvedPath = PackageHelper.getSdDir(cid); 10389 resolvedFile = new File(resolvedPath); 10390 } else if (file != null) { 10391 resolvedPath = file.getAbsolutePath(); 10392 resolvedFile = file; 10393 } else { 10394 resolvedPath = null; 10395 resolvedFile = null; 10396 } 10397 } 10398 } 10399 10400 class MoveInfo { 10401 final int moveId; 10402 final String fromUuid; 10403 final String toUuid; 10404 final String packageName; 10405 final String dataAppName; 10406 final int appId; 10407 final String seinfo; 10408 10409 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10410 String dataAppName, int appId, String seinfo) { 10411 this.moveId = moveId; 10412 this.fromUuid = fromUuid; 10413 this.toUuid = toUuid; 10414 this.packageName = packageName; 10415 this.dataAppName = dataAppName; 10416 this.appId = appId; 10417 this.seinfo = seinfo; 10418 } 10419 } 10420 10421 class InstallParams extends HandlerParams { 10422 final OriginInfo origin; 10423 final MoveInfo move; 10424 final IPackageInstallObserver2 observer; 10425 int installFlags; 10426 final String installerPackageName; 10427 final String volumeUuid; 10428 final VerificationParams verificationParams; 10429 private InstallArgs mArgs; 10430 private int mRet; 10431 final String packageAbiOverride; 10432 final String[] grantedRuntimePermissions; 10433 10434 10435 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10436 int installFlags, String installerPackageName, String volumeUuid, 10437 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10438 String[] grantedPermissions) { 10439 super(user); 10440 this.origin = origin; 10441 this.move = move; 10442 this.observer = observer; 10443 this.installFlags = installFlags; 10444 this.installerPackageName = installerPackageName; 10445 this.volumeUuid = volumeUuid; 10446 this.verificationParams = verificationParams; 10447 this.packageAbiOverride = packageAbiOverride; 10448 this.grantedRuntimePermissions = grantedPermissions; 10449 } 10450 10451 @Override 10452 public String toString() { 10453 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10454 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10455 } 10456 10457 public ManifestDigest getManifestDigest() { 10458 if (verificationParams == null) { 10459 return null; 10460 } 10461 return verificationParams.getManifestDigest(); 10462 } 10463 10464 private int installLocationPolicy(PackageInfoLite pkgLite) { 10465 String packageName = pkgLite.packageName; 10466 int installLocation = pkgLite.installLocation; 10467 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10468 // reader 10469 synchronized (mPackages) { 10470 PackageParser.Package pkg = mPackages.get(packageName); 10471 if (pkg != null) { 10472 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10473 // Check for downgrading. 10474 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10475 try { 10476 checkDowngrade(pkg, pkgLite); 10477 } catch (PackageManagerException e) { 10478 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10479 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10480 } 10481 } 10482 // Check for updated system application. 10483 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10484 if (onSd) { 10485 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10486 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10487 } 10488 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10489 } else { 10490 if (onSd) { 10491 // Install flag overrides everything. 10492 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10493 } 10494 // If current upgrade specifies particular preference 10495 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10496 // Application explicitly specified internal. 10497 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10498 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10499 // App explictly prefers external. Let policy decide 10500 } else { 10501 // Prefer previous location 10502 if (isExternal(pkg)) { 10503 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10504 } 10505 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10506 } 10507 } 10508 } else { 10509 // Invalid install. Return error code 10510 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10511 } 10512 } 10513 } 10514 // All the special cases have been taken care of. 10515 // Return result based on recommended install location. 10516 if (onSd) { 10517 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10518 } 10519 return pkgLite.recommendedInstallLocation; 10520 } 10521 10522 /* 10523 * Invoke remote method to get package information and install 10524 * location values. Override install location based on default 10525 * policy if needed and then create install arguments based 10526 * on the install location. 10527 */ 10528 public void handleStartCopy() throws RemoteException { 10529 int ret = PackageManager.INSTALL_SUCCEEDED; 10530 10531 // If we're already staged, we've firmly committed to an install location 10532 if (origin.staged) { 10533 if (origin.file != null) { 10534 installFlags |= PackageManager.INSTALL_INTERNAL; 10535 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10536 } else if (origin.cid != null) { 10537 installFlags |= PackageManager.INSTALL_EXTERNAL; 10538 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10539 } else { 10540 throw new IllegalStateException("Invalid stage location"); 10541 } 10542 } 10543 10544 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10545 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10546 10547 PackageInfoLite pkgLite = null; 10548 10549 if (onInt && onSd) { 10550 // Check if both bits are set. 10551 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10552 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10553 } else { 10554 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10555 packageAbiOverride); 10556 10557 /* 10558 * If we have too little free space, try to free cache 10559 * before giving up. 10560 */ 10561 if (!origin.staged && pkgLite.recommendedInstallLocation 10562 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10563 // TODO: focus freeing disk space on the target device 10564 final StorageManager storage = StorageManager.from(mContext); 10565 final long lowThreshold = storage.getStorageLowBytes( 10566 Environment.getDataDirectory()); 10567 10568 final long sizeBytes = mContainerService.calculateInstalledSize( 10569 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10570 10571 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10572 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10573 installFlags, packageAbiOverride); 10574 } 10575 10576 /* 10577 * The cache free must have deleted the file we 10578 * downloaded to install. 10579 * 10580 * TODO: fix the "freeCache" call to not delete 10581 * the file we care about. 10582 */ 10583 if (pkgLite.recommendedInstallLocation 10584 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10585 pkgLite.recommendedInstallLocation 10586 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10587 } 10588 } 10589 } 10590 10591 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10592 int loc = pkgLite.recommendedInstallLocation; 10593 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10594 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10595 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10596 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10597 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10598 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10599 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10600 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10601 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10602 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10603 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10604 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10605 } else { 10606 // Override with defaults if needed. 10607 loc = installLocationPolicy(pkgLite); 10608 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10609 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10610 } else if (!onSd && !onInt) { 10611 // Override install location with flags 10612 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10613 // Set the flag to install on external media. 10614 installFlags |= PackageManager.INSTALL_EXTERNAL; 10615 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10616 } else { 10617 // Make sure the flag for installing on external 10618 // media is unset 10619 installFlags |= PackageManager.INSTALL_INTERNAL; 10620 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10621 } 10622 } 10623 } 10624 } 10625 10626 final InstallArgs args = createInstallArgs(this); 10627 mArgs = args; 10628 10629 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10630 /* 10631 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10632 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10633 */ 10634 int userIdentifier = getUser().getIdentifier(); 10635 if (userIdentifier == UserHandle.USER_ALL 10636 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10637 userIdentifier = UserHandle.USER_OWNER; 10638 } 10639 10640 /* 10641 * Determine if we have any installed package verifiers. If we 10642 * do, then we'll defer to them to verify the packages. 10643 */ 10644 final int requiredUid = mRequiredVerifierPackage == null ? -1 10645 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10646 if (!origin.existing && requiredUid != -1 10647 && isVerificationEnabled(userIdentifier, installFlags)) { 10648 final Intent verification = new Intent( 10649 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10650 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10651 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10652 PACKAGE_MIME_TYPE); 10653 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10654 10655 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10656 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10657 0 /* TODO: Which userId? */); 10658 10659 if (DEBUG_VERIFY) { 10660 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10661 + verification.toString() + " with " + pkgLite.verifiers.length 10662 + " optional verifiers"); 10663 } 10664 10665 final int verificationId = mPendingVerificationToken++; 10666 10667 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10668 10669 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10670 installerPackageName); 10671 10672 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10673 installFlags); 10674 10675 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10676 pkgLite.packageName); 10677 10678 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10679 pkgLite.versionCode); 10680 10681 if (verificationParams != null) { 10682 if (verificationParams.getVerificationURI() != null) { 10683 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10684 verificationParams.getVerificationURI()); 10685 } 10686 if (verificationParams.getOriginatingURI() != null) { 10687 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10688 verificationParams.getOriginatingURI()); 10689 } 10690 if (verificationParams.getReferrer() != null) { 10691 verification.putExtra(Intent.EXTRA_REFERRER, 10692 verificationParams.getReferrer()); 10693 } 10694 if (verificationParams.getOriginatingUid() >= 0) { 10695 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10696 verificationParams.getOriginatingUid()); 10697 } 10698 if (verificationParams.getInstallerUid() >= 0) { 10699 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10700 verificationParams.getInstallerUid()); 10701 } 10702 } 10703 10704 final PackageVerificationState verificationState = new PackageVerificationState( 10705 requiredUid, args); 10706 10707 mPendingVerification.append(verificationId, verificationState); 10708 10709 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10710 receivers, verificationState); 10711 10712 // Apps installed for "all" users use the device owner to verify the app 10713 UserHandle verifierUser = getUser(); 10714 if (verifierUser == UserHandle.ALL) { 10715 verifierUser = UserHandle.OWNER; 10716 } 10717 10718 /* 10719 * If any sufficient verifiers were listed in the package 10720 * manifest, attempt to ask them. 10721 */ 10722 if (sufficientVerifiers != null) { 10723 final int N = sufficientVerifiers.size(); 10724 if (N == 0) { 10725 Slog.i(TAG, "Additional verifiers required, but none installed."); 10726 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10727 } else { 10728 for (int i = 0; i < N; i++) { 10729 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10730 10731 final Intent sufficientIntent = new Intent(verification); 10732 sufficientIntent.setComponent(verifierComponent); 10733 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10734 } 10735 } 10736 } 10737 10738 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10739 mRequiredVerifierPackage, receivers); 10740 if (ret == PackageManager.INSTALL_SUCCEEDED 10741 && mRequiredVerifierPackage != null) { 10742 /* 10743 * Send the intent to the required verification agent, 10744 * but only start the verification timeout after the 10745 * target BroadcastReceivers have run. 10746 */ 10747 verification.setComponent(requiredVerifierComponent); 10748 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10749 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10750 new BroadcastReceiver() { 10751 @Override 10752 public void onReceive(Context context, Intent intent) { 10753 final Message msg = mHandler 10754 .obtainMessage(CHECK_PENDING_VERIFICATION); 10755 msg.arg1 = verificationId; 10756 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10757 } 10758 }, null, 0, null, null); 10759 10760 /* 10761 * We don't want the copy to proceed until verification 10762 * succeeds, so null out this field. 10763 */ 10764 mArgs = null; 10765 } 10766 } else { 10767 /* 10768 * No package verification is enabled, so immediately start 10769 * the remote call to initiate copy using temporary file. 10770 */ 10771 ret = args.copyApk(mContainerService, true); 10772 } 10773 } 10774 10775 mRet = ret; 10776 } 10777 10778 @Override 10779 void handleReturnCode() { 10780 // If mArgs is null, then MCS couldn't be reached. When it 10781 // reconnects, it will try again to install. At that point, this 10782 // will succeed. 10783 if (mArgs != null) { 10784 processPendingInstall(mArgs, mRet); 10785 } 10786 } 10787 10788 @Override 10789 void handleServiceError() { 10790 mArgs = createInstallArgs(this); 10791 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10792 } 10793 10794 public boolean isForwardLocked() { 10795 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10796 } 10797 } 10798 10799 /** 10800 * Used during creation of InstallArgs 10801 * 10802 * @param installFlags package installation flags 10803 * @return true if should be installed on external storage 10804 */ 10805 private static boolean installOnExternalAsec(int installFlags) { 10806 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10807 return false; 10808 } 10809 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10810 return true; 10811 } 10812 return false; 10813 } 10814 10815 /** 10816 * Used during creation of InstallArgs 10817 * 10818 * @param installFlags package installation flags 10819 * @return true if should be installed as forward locked 10820 */ 10821 private static boolean installForwardLocked(int installFlags) { 10822 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10823 } 10824 10825 private InstallArgs createInstallArgs(InstallParams params) { 10826 if (params.move != null) { 10827 return new MoveInstallArgs(params); 10828 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10829 return new AsecInstallArgs(params); 10830 } else { 10831 return new FileInstallArgs(params); 10832 } 10833 } 10834 10835 /** 10836 * Create args that describe an existing installed package. Typically used 10837 * when cleaning up old installs, or used as a move source. 10838 */ 10839 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10840 String resourcePath, String[] instructionSets) { 10841 final boolean isInAsec; 10842 if (installOnExternalAsec(installFlags)) { 10843 /* Apps on SD card are always in ASEC containers. */ 10844 isInAsec = true; 10845 } else if (installForwardLocked(installFlags) 10846 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10847 /* 10848 * Forward-locked apps are only in ASEC containers if they're the 10849 * new style 10850 */ 10851 isInAsec = true; 10852 } else { 10853 isInAsec = false; 10854 } 10855 10856 if (isInAsec) { 10857 return new AsecInstallArgs(codePath, instructionSets, 10858 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10859 } else { 10860 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10861 } 10862 } 10863 10864 static abstract class InstallArgs { 10865 /** @see InstallParams#origin */ 10866 final OriginInfo origin; 10867 /** @see InstallParams#move */ 10868 final MoveInfo move; 10869 10870 final IPackageInstallObserver2 observer; 10871 // Always refers to PackageManager flags only 10872 final int installFlags; 10873 final String installerPackageName; 10874 final String volumeUuid; 10875 final ManifestDigest manifestDigest; 10876 final UserHandle user; 10877 final String abiOverride; 10878 final String[] installGrantPermissions; 10879 10880 // The list of instruction sets supported by this app. This is currently 10881 // only used during the rmdex() phase to clean up resources. We can get rid of this 10882 // if we move dex files under the common app path. 10883 /* nullable */ String[] instructionSets; 10884 10885 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10886 int installFlags, String installerPackageName, String volumeUuid, 10887 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10888 String abiOverride, String[] installGrantPermissions) { 10889 this.origin = origin; 10890 this.move = move; 10891 this.installFlags = installFlags; 10892 this.observer = observer; 10893 this.installerPackageName = installerPackageName; 10894 this.volumeUuid = volumeUuid; 10895 this.manifestDigest = manifestDigest; 10896 this.user = user; 10897 this.instructionSets = instructionSets; 10898 this.abiOverride = abiOverride; 10899 this.installGrantPermissions = installGrantPermissions; 10900 } 10901 10902 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10903 abstract int doPreInstall(int status); 10904 10905 /** 10906 * Rename package into final resting place. All paths on the given 10907 * scanned package should be updated to reflect the rename. 10908 */ 10909 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10910 abstract int doPostInstall(int status, int uid); 10911 10912 /** @see PackageSettingBase#codePathString */ 10913 abstract String getCodePath(); 10914 /** @see PackageSettingBase#resourcePathString */ 10915 abstract String getResourcePath(); 10916 10917 // Need installer lock especially for dex file removal. 10918 abstract void cleanUpResourcesLI(); 10919 abstract boolean doPostDeleteLI(boolean delete); 10920 10921 /** 10922 * Called before the source arguments are copied. This is used mostly 10923 * for MoveParams when it needs to read the source file to put it in the 10924 * destination. 10925 */ 10926 int doPreCopy() { 10927 return PackageManager.INSTALL_SUCCEEDED; 10928 } 10929 10930 /** 10931 * Called after the source arguments are copied. This is used mostly for 10932 * MoveParams when it needs to read the source file to put it in the 10933 * destination. 10934 * 10935 * @return 10936 */ 10937 int doPostCopy(int uid) { 10938 return PackageManager.INSTALL_SUCCEEDED; 10939 } 10940 10941 protected boolean isFwdLocked() { 10942 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10943 } 10944 10945 protected boolean isExternalAsec() { 10946 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10947 } 10948 10949 UserHandle getUser() { 10950 return user; 10951 } 10952 } 10953 10954 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10955 if (!allCodePaths.isEmpty()) { 10956 if (instructionSets == null) { 10957 throw new IllegalStateException("instructionSet == null"); 10958 } 10959 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10960 for (String codePath : allCodePaths) { 10961 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10962 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10963 if (retCode < 0) { 10964 Slog.w(TAG, "Couldn't remove dex file for package: " 10965 + " at location " + codePath + ", retcode=" + retCode); 10966 // we don't consider this to be a failure of the core package deletion 10967 } 10968 } 10969 } 10970 } 10971 } 10972 10973 /** 10974 * Logic to handle installation of non-ASEC applications, including copying 10975 * and renaming logic. 10976 */ 10977 class FileInstallArgs extends InstallArgs { 10978 private File codeFile; 10979 private File resourceFile; 10980 10981 // Example topology: 10982 // /data/app/com.example/base.apk 10983 // /data/app/com.example/split_foo.apk 10984 // /data/app/com.example/lib/arm/libfoo.so 10985 // /data/app/com.example/lib/arm64/libfoo.so 10986 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10987 10988 /** New install */ 10989 FileInstallArgs(InstallParams params) { 10990 super(params.origin, params.move, params.observer, params.installFlags, 10991 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10992 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10993 params.grantedRuntimePermissions); 10994 if (isFwdLocked()) { 10995 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10996 } 10997 } 10998 10999 /** Existing install */ 11000 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11001 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11002 null, null); 11003 this.codeFile = (codePath != null) ? new File(codePath) : null; 11004 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11005 } 11006 11007 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11008 if (origin.staged) { 11009 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11010 codeFile = origin.file; 11011 resourceFile = origin.file; 11012 return PackageManager.INSTALL_SUCCEEDED; 11013 } 11014 11015 try { 11016 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11017 codeFile = tempDir; 11018 resourceFile = tempDir; 11019 } catch (IOException e) { 11020 Slog.w(TAG, "Failed to create copy file: " + e); 11021 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11022 } 11023 11024 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11025 @Override 11026 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11027 if (!FileUtils.isValidExtFilename(name)) { 11028 throw new IllegalArgumentException("Invalid filename: " + name); 11029 } 11030 try { 11031 final File file = new File(codeFile, name); 11032 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11033 O_RDWR | O_CREAT, 0644); 11034 Os.chmod(file.getAbsolutePath(), 0644); 11035 return new ParcelFileDescriptor(fd); 11036 } catch (ErrnoException e) { 11037 throw new RemoteException("Failed to open: " + e.getMessage()); 11038 } 11039 } 11040 }; 11041 11042 int ret = PackageManager.INSTALL_SUCCEEDED; 11043 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11044 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11045 Slog.e(TAG, "Failed to copy package"); 11046 return ret; 11047 } 11048 11049 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11050 NativeLibraryHelper.Handle handle = null; 11051 try { 11052 handle = NativeLibraryHelper.Handle.create(codeFile); 11053 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11054 abiOverride); 11055 } catch (IOException e) { 11056 Slog.e(TAG, "Copying native libraries failed", e); 11057 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11058 } finally { 11059 IoUtils.closeQuietly(handle); 11060 } 11061 11062 return ret; 11063 } 11064 11065 int doPreInstall(int status) { 11066 if (status != PackageManager.INSTALL_SUCCEEDED) { 11067 cleanUp(); 11068 } 11069 return status; 11070 } 11071 11072 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11073 if (status != PackageManager.INSTALL_SUCCEEDED) { 11074 cleanUp(); 11075 return false; 11076 } 11077 11078 final File targetDir = codeFile.getParentFile(); 11079 final File beforeCodeFile = codeFile; 11080 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11081 11082 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11083 try { 11084 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11085 } catch (ErrnoException e) { 11086 Slog.w(TAG, "Failed to rename", e); 11087 return false; 11088 } 11089 11090 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11091 Slog.w(TAG, "Failed to restorecon"); 11092 return false; 11093 } 11094 11095 // Reflect the rename internally 11096 codeFile = afterCodeFile; 11097 resourceFile = afterCodeFile; 11098 11099 // Reflect the rename in scanned details 11100 pkg.codePath = afterCodeFile.getAbsolutePath(); 11101 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11102 pkg.baseCodePath); 11103 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11104 pkg.splitCodePaths); 11105 11106 // Reflect the rename in app info 11107 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11108 pkg.applicationInfo.setCodePath(pkg.codePath); 11109 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11110 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11111 pkg.applicationInfo.setResourcePath(pkg.codePath); 11112 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11113 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11114 11115 return true; 11116 } 11117 11118 int doPostInstall(int status, int uid) { 11119 if (status != PackageManager.INSTALL_SUCCEEDED) { 11120 cleanUp(); 11121 } 11122 return status; 11123 } 11124 11125 @Override 11126 String getCodePath() { 11127 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11128 } 11129 11130 @Override 11131 String getResourcePath() { 11132 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11133 } 11134 11135 private boolean cleanUp() { 11136 if (codeFile == null || !codeFile.exists()) { 11137 return false; 11138 } 11139 11140 if (codeFile.isDirectory()) { 11141 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11142 } else { 11143 codeFile.delete(); 11144 } 11145 11146 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11147 resourceFile.delete(); 11148 } 11149 11150 return true; 11151 } 11152 11153 void cleanUpResourcesLI() { 11154 // Try enumerating all code paths before deleting 11155 List<String> allCodePaths = Collections.EMPTY_LIST; 11156 if (codeFile != null && codeFile.exists()) { 11157 try { 11158 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11159 allCodePaths = pkg.getAllCodePaths(); 11160 } catch (PackageParserException e) { 11161 // Ignored; we tried our best 11162 } 11163 } 11164 11165 cleanUp(); 11166 removeDexFiles(allCodePaths, instructionSets); 11167 } 11168 11169 boolean doPostDeleteLI(boolean delete) { 11170 // XXX err, shouldn't we respect the delete flag? 11171 cleanUpResourcesLI(); 11172 return true; 11173 } 11174 } 11175 11176 private boolean isAsecExternal(String cid) { 11177 final String asecPath = PackageHelper.getSdFilesystem(cid); 11178 return !asecPath.startsWith(mAsecInternalPath); 11179 } 11180 11181 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11182 PackageManagerException { 11183 if (copyRet < 0) { 11184 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11185 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11186 throw new PackageManagerException(copyRet, message); 11187 } 11188 } 11189 } 11190 11191 /** 11192 * Extract the MountService "container ID" from the full code path of an 11193 * .apk. 11194 */ 11195 static String cidFromCodePath(String fullCodePath) { 11196 int eidx = fullCodePath.lastIndexOf("/"); 11197 String subStr1 = fullCodePath.substring(0, eidx); 11198 int sidx = subStr1.lastIndexOf("/"); 11199 return subStr1.substring(sidx+1, eidx); 11200 } 11201 11202 /** 11203 * Logic to handle installation of ASEC applications, including copying and 11204 * renaming logic. 11205 */ 11206 class AsecInstallArgs extends InstallArgs { 11207 static final String RES_FILE_NAME = "pkg.apk"; 11208 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11209 11210 String cid; 11211 String packagePath; 11212 String resourcePath; 11213 11214 /** New install */ 11215 AsecInstallArgs(InstallParams params) { 11216 super(params.origin, params.move, params.observer, params.installFlags, 11217 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11218 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11219 params.grantedRuntimePermissions); 11220 } 11221 11222 /** Existing install */ 11223 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11224 boolean isExternal, boolean isForwardLocked) { 11225 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11226 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11227 instructionSets, null, null); 11228 // Hackily pretend we're still looking at a full code path 11229 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11230 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11231 } 11232 11233 // Extract cid from fullCodePath 11234 int eidx = fullCodePath.lastIndexOf("/"); 11235 String subStr1 = fullCodePath.substring(0, eidx); 11236 int sidx = subStr1.lastIndexOf("/"); 11237 cid = subStr1.substring(sidx+1, eidx); 11238 setMountPath(subStr1); 11239 } 11240 11241 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11242 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11243 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11244 instructionSets, null, null); 11245 this.cid = cid; 11246 setMountPath(PackageHelper.getSdDir(cid)); 11247 } 11248 11249 void createCopyFile() { 11250 cid = mInstallerService.allocateExternalStageCidLegacy(); 11251 } 11252 11253 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11254 if (origin.staged) { 11255 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11256 cid = origin.cid; 11257 setMountPath(PackageHelper.getSdDir(cid)); 11258 return PackageManager.INSTALL_SUCCEEDED; 11259 } 11260 11261 if (temp) { 11262 createCopyFile(); 11263 } else { 11264 /* 11265 * Pre-emptively destroy the container since it's destroyed if 11266 * copying fails due to it existing anyway. 11267 */ 11268 PackageHelper.destroySdDir(cid); 11269 } 11270 11271 final String newMountPath = imcs.copyPackageToContainer( 11272 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11273 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11274 11275 if (newMountPath != null) { 11276 setMountPath(newMountPath); 11277 return PackageManager.INSTALL_SUCCEEDED; 11278 } else { 11279 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11280 } 11281 } 11282 11283 @Override 11284 String getCodePath() { 11285 return packagePath; 11286 } 11287 11288 @Override 11289 String getResourcePath() { 11290 return resourcePath; 11291 } 11292 11293 int doPreInstall(int status) { 11294 if (status != PackageManager.INSTALL_SUCCEEDED) { 11295 // Destroy container 11296 PackageHelper.destroySdDir(cid); 11297 } else { 11298 boolean mounted = PackageHelper.isContainerMounted(cid); 11299 if (!mounted) { 11300 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11301 Process.SYSTEM_UID); 11302 if (newMountPath != null) { 11303 setMountPath(newMountPath); 11304 } else { 11305 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11306 } 11307 } 11308 } 11309 return status; 11310 } 11311 11312 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11313 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11314 String newMountPath = null; 11315 if (PackageHelper.isContainerMounted(cid)) { 11316 // Unmount the container 11317 if (!PackageHelper.unMountSdDir(cid)) { 11318 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11319 return false; 11320 } 11321 } 11322 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11323 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11324 " which might be stale. Will try to clean up."); 11325 // Clean up the stale container and proceed to recreate. 11326 if (!PackageHelper.destroySdDir(newCacheId)) { 11327 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11328 return false; 11329 } 11330 // Successfully cleaned up stale container. Try to rename again. 11331 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11332 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11333 + " inspite of cleaning it up."); 11334 return false; 11335 } 11336 } 11337 if (!PackageHelper.isContainerMounted(newCacheId)) { 11338 Slog.w(TAG, "Mounting container " + newCacheId); 11339 newMountPath = PackageHelper.mountSdDir(newCacheId, 11340 getEncryptKey(), Process.SYSTEM_UID); 11341 } else { 11342 newMountPath = PackageHelper.getSdDir(newCacheId); 11343 } 11344 if (newMountPath == null) { 11345 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11346 return false; 11347 } 11348 Log.i(TAG, "Succesfully renamed " + cid + 11349 " to " + newCacheId + 11350 " at new path: " + newMountPath); 11351 cid = newCacheId; 11352 11353 final File beforeCodeFile = new File(packagePath); 11354 setMountPath(newMountPath); 11355 final File afterCodeFile = new File(packagePath); 11356 11357 // Reflect the rename in scanned details 11358 pkg.codePath = afterCodeFile.getAbsolutePath(); 11359 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11360 pkg.baseCodePath); 11361 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11362 pkg.splitCodePaths); 11363 11364 // Reflect the rename in app info 11365 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11366 pkg.applicationInfo.setCodePath(pkg.codePath); 11367 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11368 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11369 pkg.applicationInfo.setResourcePath(pkg.codePath); 11370 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11371 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11372 11373 return true; 11374 } 11375 11376 private void setMountPath(String mountPath) { 11377 final File mountFile = new File(mountPath); 11378 11379 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11380 if (monolithicFile.exists()) { 11381 packagePath = monolithicFile.getAbsolutePath(); 11382 if (isFwdLocked()) { 11383 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11384 } else { 11385 resourcePath = packagePath; 11386 } 11387 } else { 11388 packagePath = mountFile.getAbsolutePath(); 11389 resourcePath = packagePath; 11390 } 11391 } 11392 11393 int doPostInstall(int status, int uid) { 11394 if (status != PackageManager.INSTALL_SUCCEEDED) { 11395 cleanUp(); 11396 } else { 11397 final int groupOwner; 11398 final String protectedFile; 11399 if (isFwdLocked()) { 11400 groupOwner = UserHandle.getSharedAppGid(uid); 11401 protectedFile = RES_FILE_NAME; 11402 } else { 11403 groupOwner = -1; 11404 protectedFile = null; 11405 } 11406 11407 if (uid < Process.FIRST_APPLICATION_UID 11408 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11409 Slog.e(TAG, "Failed to finalize " + cid); 11410 PackageHelper.destroySdDir(cid); 11411 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11412 } 11413 11414 boolean mounted = PackageHelper.isContainerMounted(cid); 11415 if (!mounted) { 11416 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11417 } 11418 } 11419 return status; 11420 } 11421 11422 private void cleanUp() { 11423 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11424 11425 // Destroy secure container 11426 PackageHelper.destroySdDir(cid); 11427 } 11428 11429 private List<String> getAllCodePaths() { 11430 final File codeFile = new File(getCodePath()); 11431 if (codeFile != null && codeFile.exists()) { 11432 try { 11433 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11434 return pkg.getAllCodePaths(); 11435 } catch (PackageParserException e) { 11436 // Ignored; we tried our best 11437 } 11438 } 11439 return Collections.EMPTY_LIST; 11440 } 11441 11442 void cleanUpResourcesLI() { 11443 // Enumerate all code paths before deleting 11444 cleanUpResourcesLI(getAllCodePaths()); 11445 } 11446 11447 private void cleanUpResourcesLI(List<String> allCodePaths) { 11448 cleanUp(); 11449 removeDexFiles(allCodePaths, instructionSets); 11450 } 11451 11452 String getPackageName() { 11453 return getAsecPackageName(cid); 11454 } 11455 11456 boolean doPostDeleteLI(boolean delete) { 11457 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11458 final List<String> allCodePaths = getAllCodePaths(); 11459 boolean mounted = PackageHelper.isContainerMounted(cid); 11460 if (mounted) { 11461 // Unmount first 11462 if (PackageHelper.unMountSdDir(cid)) { 11463 mounted = false; 11464 } 11465 } 11466 if (!mounted && delete) { 11467 cleanUpResourcesLI(allCodePaths); 11468 } 11469 return !mounted; 11470 } 11471 11472 @Override 11473 int doPreCopy() { 11474 if (isFwdLocked()) { 11475 if (!PackageHelper.fixSdPermissions(cid, 11476 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11477 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11478 } 11479 } 11480 11481 return PackageManager.INSTALL_SUCCEEDED; 11482 } 11483 11484 @Override 11485 int doPostCopy(int uid) { 11486 if (isFwdLocked()) { 11487 if (uid < Process.FIRST_APPLICATION_UID 11488 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11489 RES_FILE_NAME)) { 11490 Slog.e(TAG, "Failed to finalize " + cid); 11491 PackageHelper.destroySdDir(cid); 11492 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11493 } 11494 } 11495 11496 return PackageManager.INSTALL_SUCCEEDED; 11497 } 11498 } 11499 11500 /** 11501 * Logic to handle movement of existing installed applications. 11502 */ 11503 class MoveInstallArgs extends InstallArgs { 11504 private File codeFile; 11505 private File resourceFile; 11506 11507 /** New install */ 11508 MoveInstallArgs(InstallParams params) { 11509 super(params.origin, params.move, params.observer, params.installFlags, 11510 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11511 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11512 params.grantedRuntimePermissions); 11513 } 11514 11515 int copyApk(IMediaContainerService imcs, boolean temp) { 11516 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11517 + move.fromUuid + " to " + move.toUuid); 11518 synchronized (mInstaller) { 11519 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11520 move.dataAppName, move.appId, move.seinfo) != 0) { 11521 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11522 } 11523 } 11524 11525 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11526 resourceFile = codeFile; 11527 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11528 11529 return PackageManager.INSTALL_SUCCEEDED; 11530 } 11531 11532 int doPreInstall(int status) { 11533 if (status != PackageManager.INSTALL_SUCCEEDED) { 11534 cleanUp(move.toUuid); 11535 } 11536 return status; 11537 } 11538 11539 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11540 if (status != PackageManager.INSTALL_SUCCEEDED) { 11541 cleanUp(move.toUuid); 11542 return false; 11543 } 11544 11545 // Reflect the move in app info 11546 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11547 pkg.applicationInfo.setCodePath(pkg.codePath); 11548 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11549 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11550 pkg.applicationInfo.setResourcePath(pkg.codePath); 11551 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11552 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11553 11554 return true; 11555 } 11556 11557 int doPostInstall(int status, int uid) { 11558 if (status == PackageManager.INSTALL_SUCCEEDED) { 11559 cleanUp(move.fromUuid); 11560 } else { 11561 cleanUp(move.toUuid); 11562 } 11563 return status; 11564 } 11565 11566 @Override 11567 String getCodePath() { 11568 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11569 } 11570 11571 @Override 11572 String getResourcePath() { 11573 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11574 } 11575 11576 private boolean cleanUp(String volumeUuid) { 11577 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11578 move.dataAppName); 11579 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11580 synchronized (mInstallLock) { 11581 // Clean up both app data and code 11582 removeDataDirsLI(volumeUuid, move.packageName); 11583 if (codeFile.isDirectory()) { 11584 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11585 } else { 11586 codeFile.delete(); 11587 } 11588 } 11589 return true; 11590 } 11591 11592 void cleanUpResourcesLI() { 11593 throw new UnsupportedOperationException(); 11594 } 11595 11596 boolean doPostDeleteLI(boolean delete) { 11597 throw new UnsupportedOperationException(); 11598 } 11599 } 11600 11601 static String getAsecPackageName(String packageCid) { 11602 int idx = packageCid.lastIndexOf("-"); 11603 if (idx == -1) { 11604 return packageCid; 11605 } 11606 return packageCid.substring(0, idx); 11607 } 11608 11609 // Utility method used to create code paths based on package name and available index. 11610 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11611 String idxStr = ""; 11612 int idx = 1; 11613 // Fall back to default value of idx=1 if prefix is not 11614 // part of oldCodePath 11615 if (oldCodePath != null) { 11616 String subStr = oldCodePath; 11617 // Drop the suffix right away 11618 if (suffix != null && subStr.endsWith(suffix)) { 11619 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11620 } 11621 // If oldCodePath already contains prefix find out the 11622 // ending index to either increment or decrement. 11623 int sidx = subStr.lastIndexOf(prefix); 11624 if (sidx != -1) { 11625 subStr = subStr.substring(sidx + prefix.length()); 11626 if (subStr != null) { 11627 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11628 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11629 } 11630 try { 11631 idx = Integer.parseInt(subStr); 11632 if (idx <= 1) { 11633 idx++; 11634 } else { 11635 idx--; 11636 } 11637 } catch(NumberFormatException e) { 11638 } 11639 } 11640 } 11641 } 11642 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11643 return prefix + idxStr; 11644 } 11645 11646 private File getNextCodePath(File targetDir, String packageName) { 11647 int suffix = 1; 11648 File result; 11649 do { 11650 result = new File(targetDir, packageName + "-" + suffix); 11651 suffix++; 11652 } while (result.exists()); 11653 return result; 11654 } 11655 11656 // Utility method that returns the relative package path with respect 11657 // to the installation directory. Like say for /data/data/com.test-1.apk 11658 // string com.test-1 is returned. 11659 static String deriveCodePathName(String codePath) { 11660 if (codePath == null) { 11661 return null; 11662 } 11663 final File codeFile = new File(codePath); 11664 final String name = codeFile.getName(); 11665 if (codeFile.isDirectory()) { 11666 return name; 11667 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11668 final int lastDot = name.lastIndexOf('.'); 11669 return name.substring(0, lastDot); 11670 } else { 11671 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11672 return null; 11673 } 11674 } 11675 11676 class PackageInstalledInfo { 11677 String name; 11678 int uid; 11679 // The set of users that originally had this package installed. 11680 int[] origUsers; 11681 // The set of users that now have this package installed. 11682 int[] newUsers; 11683 PackageParser.Package pkg; 11684 int returnCode; 11685 String returnMsg; 11686 PackageRemovedInfo removedInfo; 11687 11688 public void setError(int code, String msg) { 11689 returnCode = code; 11690 returnMsg = msg; 11691 Slog.w(TAG, msg); 11692 } 11693 11694 public void setError(String msg, PackageParserException e) { 11695 returnCode = e.error; 11696 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11697 Slog.w(TAG, msg, e); 11698 } 11699 11700 public void setError(String msg, PackageManagerException e) { 11701 returnCode = e.error; 11702 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11703 Slog.w(TAG, msg, e); 11704 } 11705 11706 // In some error cases we want to convey more info back to the observer 11707 String origPackage; 11708 String origPermission; 11709 } 11710 11711 /* 11712 * Install a non-existing package. 11713 */ 11714 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11715 UserHandle user, String installerPackageName, String volumeUuid, 11716 PackageInstalledInfo res) { 11717 // Remember this for later, in case we need to rollback this install 11718 String pkgName = pkg.packageName; 11719 11720 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11721 final boolean dataDirExists = Environment 11722 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11723 synchronized(mPackages) { 11724 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11725 // A package with the same name is already installed, though 11726 // it has been renamed to an older name. The package we 11727 // are trying to install should be installed as an update to 11728 // the existing one, but that has not been requested, so bail. 11729 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11730 + " without first uninstalling package running as " 11731 + mSettings.mRenamedPackages.get(pkgName)); 11732 return; 11733 } 11734 if (mPackages.containsKey(pkgName)) { 11735 // Don't allow installation over an existing package with the same name. 11736 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11737 + " without first uninstalling."); 11738 return; 11739 } 11740 } 11741 11742 try { 11743 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11744 System.currentTimeMillis(), user); 11745 11746 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11747 // delete the partially installed application. the data directory will have to be 11748 // restored if it was already existing 11749 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11750 // remove package from internal structures. Note that we want deletePackageX to 11751 // delete the package data and cache directories that it created in 11752 // scanPackageLocked, unless those directories existed before we even tried to 11753 // install. 11754 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11755 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11756 res.removedInfo, true); 11757 } 11758 11759 } catch (PackageManagerException e) { 11760 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11761 } 11762 } 11763 11764 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11765 // Can't rotate keys during boot or if sharedUser. 11766 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11767 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11768 return false; 11769 } 11770 // app is using upgradeKeySets; make sure all are valid 11771 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11772 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11773 for (int i = 0; i < upgradeKeySets.length; i++) { 11774 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11775 Slog.wtf(TAG, "Package " 11776 + (oldPs.name != null ? oldPs.name : "<null>") 11777 + " contains upgrade-key-set reference to unknown key-set: " 11778 + upgradeKeySets[i] 11779 + " reverting to signatures check."); 11780 return false; 11781 } 11782 } 11783 return true; 11784 } 11785 11786 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11787 // Upgrade keysets are being used. Determine if new package has a superset of the 11788 // required keys. 11789 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11790 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11791 for (int i = 0; i < upgradeKeySets.length; i++) { 11792 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11793 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11794 return true; 11795 } 11796 } 11797 return false; 11798 } 11799 11800 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11801 UserHandle user, String installerPackageName, String volumeUuid, 11802 PackageInstalledInfo res) { 11803 final PackageParser.Package oldPackage; 11804 final String pkgName = pkg.packageName; 11805 final int[] allUsers; 11806 final boolean[] perUserInstalled; 11807 11808 // First find the old package info and check signatures 11809 synchronized(mPackages) { 11810 oldPackage = mPackages.get(pkgName); 11811 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11812 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11813 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11814 if(!checkUpgradeKeySetLP(ps, pkg)) { 11815 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11816 "New package not signed by keys specified by upgrade-keysets: " 11817 + pkgName); 11818 return; 11819 } 11820 } else { 11821 // default to original signature matching 11822 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11823 != PackageManager.SIGNATURE_MATCH) { 11824 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11825 "New package has a different signature: " + pkgName); 11826 return; 11827 } 11828 } 11829 11830 // In case of rollback, remember per-user/profile install state 11831 allUsers = sUserManager.getUserIds(); 11832 perUserInstalled = new boolean[allUsers.length]; 11833 for (int i = 0; i < allUsers.length; i++) { 11834 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11835 } 11836 } 11837 11838 boolean sysPkg = (isSystemApp(oldPackage)); 11839 if (sysPkg) { 11840 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11841 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11842 } else { 11843 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11844 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11845 } 11846 } 11847 11848 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11849 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11850 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11851 String volumeUuid, PackageInstalledInfo res) { 11852 String pkgName = deletedPackage.packageName; 11853 boolean deletedPkg = true; 11854 boolean updatedSettings = false; 11855 11856 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11857 + deletedPackage); 11858 long origUpdateTime; 11859 if (pkg.mExtras != null) { 11860 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11861 } else { 11862 origUpdateTime = 0; 11863 } 11864 11865 // First delete the existing package while retaining the data directory 11866 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11867 res.removedInfo, true)) { 11868 // If the existing package wasn't successfully deleted 11869 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11870 deletedPkg = false; 11871 } else { 11872 // Successfully deleted the old package; proceed with replace. 11873 11874 // If deleted package lived in a container, give users a chance to 11875 // relinquish resources before killing. 11876 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11877 if (DEBUG_INSTALL) { 11878 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11879 } 11880 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11881 final ArrayList<String> pkgList = new ArrayList<String>(1); 11882 pkgList.add(deletedPackage.applicationInfo.packageName); 11883 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11884 } 11885 11886 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11887 try { 11888 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11889 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11890 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11891 perUserInstalled, res, user); 11892 updatedSettings = true; 11893 } catch (PackageManagerException e) { 11894 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11895 } 11896 } 11897 11898 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11899 // remove package from internal structures. Note that we want deletePackageX to 11900 // delete the package data and cache directories that it created in 11901 // scanPackageLocked, unless those directories existed before we even tried to 11902 // install. 11903 if(updatedSettings) { 11904 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11905 deletePackageLI( 11906 pkgName, null, true, allUsers, perUserInstalled, 11907 PackageManager.DELETE_KEEP_DATA, 11908 res.removedInfo, true); 11909 } 11910 // Since we failed to install the new package we need to restore the old 11911 // package that we deleted. 11912 if (deletedPkg) { 11913 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11914 File restoreFile = new File(deletedPackage.codePath); 11915 // Parse old package 11916 boolean oldExternal = isExternal(deletedPackage); 11917 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11918 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11919 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11920 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11921 try { 11922 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11923 } catch (PackageManagerException e) { 11924 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11925 + e.getMessage()); 11926 return; 11927 } 11928 // Restore of old package succeeded. Update permissions. 11929 // writer 11930 synchronized (mPackages) { 11931 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11932 UPDATE_PERMISSIONS_ALL); 11933 // can downgrade to reader 11934 mSettings.writeLPr(); 11935 } 11936 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11937 } 11938 } 11939 } 11940 11941 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11942 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11943 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11944 String volumeUuid, PackageInstalledInfo res) { 11945 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11946 + ", old=" + deletedPackage); 11947 boolean disabledSystem = false; 11948 boolean updatedSettings = false; 11949 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11950 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11951 != 0) { 11952 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11953 } 11954 String packageName = deletedPackage.packageName; 11955 if (packageName == null) { 11956 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11957 "Attempt to delete null packageName."); 11958 return; 11959 } 11960 PackageParser.Package oldPkg; 11961 PackageSetting oldPkgSetting; 11962 // reader 11963 synchronized (mPackages) { 11964 oldPkg = mPackages.get(packageName); 11965 oldPkgSetting = mSettings.mPackages.get(packageName); 11966 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11967 (oldPkgSetting == null)) { 11968 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11969 "Couldn't find package:" + packageName + " information"); 11970 return; 11971 } 11972 } 11973 11974 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 11975 11976 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11977 res.removedInfo.removedPackage = packageName; 11978 // Remove existing system package 11979 removePackageLI(oldPkgSetting, true); 11980 // writer 11981 synchronized (mPackages) { 11982 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11983 if (!disabledSystem && deletedPackage != null) { 11984 // We didn't need to disable the .apk as a current system package, 11985 // which means we are replacing another update that is already 11986 // installed. We need to make sure to delete the older one's .apk. 11987 res.removedInfo.args = createInstallArgsForExisting(0, 11988 deletedPackage.applicationInfo.getCodePath(), 11989 deletedPackage.applicationInfo.getResourcePath(), 11990 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11991 } else { 11992 res.removedInfo.args = null; 11993 } 11994 } 11995 11996 // Successfully disabled the old package. Now proceed with re-installation 11997 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11998 11999 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12000 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12001 12002 PackageParser.Package newPackage = null; 12003 try { 12004 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 12005 if (newPackage.mExtras != null) { 12006 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12007 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12008 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12009 12010 // is the update attempting to change shared user? that isn't going to work... 12011 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12012 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12013 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12014 + " to " + newPkgSetting.sharedUser); 12015 updatedSettings = true; 12016 } 12017 } 12018 12019 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12020 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12021 perUserInstalled, res, user); 12022 updatedSettings = true; 12023 } 12024 12025 } catch (PackageManagerException e) { 12026 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12027 } 12028 12029 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12030 // Re installation failed. Restore old information 12031 // Remove new pkg information 12032 if (newPackage != null) { 12033 removeInstalledPackageLI(newPackage, true); 12034 } 12035 // Add back the old system package 12036 try { 12037 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12038 } catch (PackageManagerException e) { 12039 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12040 } 12041 // Restore the old system information in Settings 12042 synchronized (mPackages) { 12043 if (disabledSystem) { 12044 mSettings.enableSystemPackageLPw(packageName); 12045 } 12046 if (updatedSettings) { 12047 mSettings.setInstallerPackageName(packageName, 12048 oldPkgSetting.installerPackageName); 12049 } 12050 mSettings.writeLPr(); 12051 } 12052 } 12053 } 12054 12055 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12056 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12057 UserHandle user) { 12058 String pkgName = newPackage.packageName; 12059 synchronized (mPackages) { 12060 //write settings. the installStatus will be incomplete at this stage. 12061 //note that the new package setting would have already been 12062 //added to mPackages. It hasn't been persisted yet. 12063 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12064 mSettings.writeLPr(); 12065 } 12066 12067 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12068 12069 synchronized (mPackages) { 12070 updatePermissionsLPw(newPackage.packageName, newPackage, 12071 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12072 ? UPDATE_PERMISSIONS_ALL : 0)); 12073 // For system-bundled packages, we assume that installing an upgraded version 12074 // of the package implies that the user actually wants to run that new code, 12075 // so we enable the package. 12076 PackageSetting ps = mSettings.mPackages.get(pkgName); 12077 if (ps != null) { 12078 if (isSystemApp(newPackage)) { 12079 // NB: implicit assumption that system package upgrades apply to all users 12080 if (DEBUG_INSTALL) { 12081 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12082 } 12083 if (res.origUsers != null) { 12084 for (int userHandle : res.origUsers) { 12085 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12086 userHandle, installerPackageName); 12087 } 12088 } 12089 // Also convey the prior install/uninstall state 12090 if (allUsers != null && perUserInstalled != null) { 12091 for (int i = 0; i < allUsers.length; i++) { 12092 if (DEBUG_INSTALL) { 12093 Slog.d(TAG, " user " + allUsers[i] 12094 + " => " + perUserInstalled[i]); 12095 } 12096 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12097 } 12098 // these install state changes will be persisted in the 12099 // upcoming call to mSettings.writeLPr(). 12100 } 12101 } 12102 // It's implied that when a user requests installation, they want the app to be 12103 // installed and enabled. 12104 int userId = user.getIdentifier(); 12105 if (userId != UserHandle.USER_ALL) { 12106 ps.setInstalled(true, userId); 12107 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12108 } 12109 } 12110 res.name = pkgName; 12111 res.uid = newPackage.applicationInfo.uid; 12112 res.pkg = newPackage; 12113 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12114 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12115 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12116 //to update install status 12117 mSettings.writeLPr(); 12118 } 12119 } 12120 12121 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12122 final int installFlags = args.installFlags; 12123 final String installerPackageName = args.installerPackageName; 12124 final String volumeUuid = args.volumeUuid; 12125 final File tmpPackageFile = new File(args.getCodePath()); 12126 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12127 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12128 || (args.volumeUuid != null)); 12129 boolean replace = false; 12130 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12131 if (args.move != null) { 12132 // moving a complete application; perfom an initial scan on the new install location 12133 scanFlags |= SCAN_INITIAL; 12134 } 12135 // Result object to be returned 12136 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12137 12138 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12139 // Retrieve PackageSettings and parse package 12140 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12141 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12142 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12143 PackageParser pp = new PackageParser(); 12144 pp.setSeparateProcesses(mSeparateProcesses); 12145 pp.setDisplayMetrics(mMetrics); 12146 12147 final PackageParser.Package pkg; 12148 try { 12149 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12150 } catch (PackageParserException e) { 12151 res.setError("Failed parse during installPackageLI", e); 12152 return; 12153 } 12154 12155 // Mark that we have an install time CPU ABI override. 12156 pkg.cpuAbiOverride = args.abiOverride; 12157 12158 String pkgName = res.name = pkg.packageName; 12159 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12160 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12161 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12162 return; 12163 } 12164 } 12165 12166 try { 12167 pp.collectCertificates(pkg, parseFlags); 12168 pp.collectManifestDigest(pkg); 12169 } catch (PackageParserException e) { 12170 res.setError("Failed collect during installPackageLI", e); 12171 return; 12172 } 12173 12174 /* If the installer passed in a manifest digest, compare it now. */ 12175 if (args.manifestDigest != null) { 12176 if (DEBUG_INSTALL) { 12177 final String parsedManifest = pkg.manifestDigest == null ? "null" 12178 : pkg.manifestDigest.toString(); 12179 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12180 + parsedManifest); 12181 } 12182 12183 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12184 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12185 return; 12186 } 12187 } else if (DEBUG_INSTALL) { 12188 final String parsedManifest = pkg.manifestDigest == null 12189 ? "null" : pkg.manifestDigest.toString(); 12190 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12191 } 12192 12193 // Get rid of all references to package scan path via parser. 12194 pp = null; 12195 String oldCodePath = null; 12196 boolean systemApp = false; 12197 synchronized (mPackages) { 12198 // Check if installing already existing package 12199 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12200 String oldName = mSettings.mRenamedPackages.get(pkgName); 12201 if (pkg.mOriginalPackages != null 12202 && pkg.mOriginalPackages.contains(oldName) 12203 && mPackages.containsKey(oldName)) { 12204 // This package is derived from an original package, 12205 // and this device has been updating from that original 12206 // name. We must continue using the original name, so 12207 // rename the new package here. 12208 pkg.setPackageName(oldName); 12209 pkgName = pkg.packageName; 12210 replace = true; 12211 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12212 + oldName + " pkgName=" + pkgName); 12213 } else if (mPackages.containsKey(pkgName)) { 12214 // This package, under its official name, already exists 12215 // on the device; we should replace it. 12216 replace = true; 12217 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12218 } 12219 12220 // Prevent apps opting out from runtime permissions 12221 if (replace) { 12222 PackageParser.Package oldPackage = mPackages.get(pkgName); 12223 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12224 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12225 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12226 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12227 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12228 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12229 + " doesn't support runtime permissions but the old" 12230 + " target SDK " + oldTargetSdk + " does."); 12231 return; 12232 } 12233 } 12234 } 12235 12236 PackageSetting ps = mSettings.mPackages.get(pkgName); 12237 if (ps != null) { 12238 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12239 12240 // Quick sanity check that we're signed correctly if updating; 12241 // we'll check this again later when scanning, but we want to 12242 // bail early here before tripping over redefined permissions. 12243 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12244 if (!checkUpgradeKeySetLP(ps, pkg)) { 12245 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12246 + pkg.packageName + " upgrade keys do not match the " 12247 + "previously installed version"); 12248 return; 12249 } 12250 } else { 12251 try { 12252 verifySignaturesLP(ps, pkg); 12253 } catch (PackageManagerException e) { 12254 res.setError(e.error, e.getMessage()); 12255 return; 12256 } 12257 } 12258 12259 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12260 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12261 systemApp = (ps.pkg.applicationInfo.flags & 12262 ApplicationInfo.FLAG_SYSTEM) != 0; 12263 } 12264 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12265 } 12266 12267 // Check whether the newly-scanned package wants to define an already-defined perm 12268 int N = pkg.permissions.size(); 12269 for (int i = N-1; i >= 0; i--) { 12270 PackageParser.Permission perm = pkg.permissions.get(i); 12271 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12272 if (bp != null) { 12273 // If the defining package is signed with our cert, it's okay. This 12274 // also includes the "updating the same package" case, of course. 12275 // "updating same package" could also involve key-rotation. 12276 final boolean sigsOk; 12277 if (bp.sourcePackage.equals(pkg.packageName) 12278 && (bp.packageSetting instanceof PackageSetting) 12279 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12280 scanFlags))) { 12281 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12282 } else { 12283 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12284 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12285 } 12286 if (!sigsOk) { 12287 // If the owning package is the system itself, we log but allow 12288 // install to proceed; we fail the install on all other permission 12289 // redefinitions. 12290 if (!bp.sourcePackage.equals("android")) { 12291 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12292 + pkg.packageName + " attempting to redeclare permission " 12293 + perm.info.name + " already owned by " + bp.sourcePackage); 12294 res.origPermission = perm.info.name; 12295 res.origPackage = bp.sourcePackage; 12296 return; 12297 } else { 12298 Slog.w(TAG, "Package " + pkg.packageName 12299 + " attempting to redeclare system permission " 12300 + perm.info.name + "; ignoring new declaration"); 12301 pkg.permissions.remove(i); 12302 } 12303 } 12304 } 12305 } 12306 12307 } 12308 12309 if (systemApp && onExternal) { 12310 // Disable updates to system apps on sdcard 12311 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12312 "Cannot install updates to system apps on sdcard"); 12313 return; 12314 } 12315 12316 if (args.move != null) { 12317 // We did an in-place move, so dex is ready to roll 12318 scanFlags |= SCAN_NO_DEX; 12319 scanFlags |= SCAN_MOVE; 12320 12321 synchronized (mPackages) { 12322 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12323 if (ps == null) { 12324 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12325 "Missing settings for moved package " + pkgName); 12326 } 12327 12328 // We moved the entire application as-is, so bring over the 12329 // previously derived ABI information. 12330 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12331 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12332 } 12333 12334 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12335 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12336 scanFlags |= SCAN_NO_DEX; 12337 12338 try { 12339 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12340 true /* extract libs */); 12341 } catch (PackageManagerException pme) { 12342 Slog.e(TAG, "Error deriving application ABI", pme); 12343 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12344 return; 12345 } 12346 12347 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12348 int result = mPackageDexOptimizer 12349 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12350 false /* defer */, false /* inclDependencies */); 12351 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12352 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12353 return; 12354 } 12355 } 12356 12357 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12358 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12359 return; 12360 } 12361 12362 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12363 12364 if (replace) { 12365 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12366 installerPackageName, volumeUuid, res); 12367 } else { 12368 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12369 args.user, installerPackageName, volumeUuid, res); 12370 } 12371 synchronized (mPackages) { 12372 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12373 if (ps != null) { 12374 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12375 } 12376 } 12377 } 12378 12379 private void startIntentFilterVerifications(int userId, boolean replacing, 12380 PackageParser.Package pkg) { 12381 if (mIntentFilterVerifierComponent == null) { 12382 Slog.w(TAG, "No IntentFilter verification will not be done as " 12383 + "there is no IntentFilterVerifier available!"); 12384 return; 12385 } 12386 12387 final int verifierUid = getPackageUid( 12388 mIntentFilterVerifierComponent.getPackageName(), 12389 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12390 12391 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12392 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12393 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12394 mHandler.sendMessage(msg); 12395 } 12396 12397 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12398 PackageParser.Package pkg) { 12399 int size = pkg.activities.size(); 12400 if (size == 0) { 12401 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12402 "No activity, so no need to verify any IntentFilter!"); 12403 return; 12404 } 12405 12406 final boolean hasDomainURLs = hasDomainURLs(pkg); 12407 if (!hasDomainURLs) { 12408 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12409 "No domain URLs, so no need to verify any IntentFilter!"); 12410 return; 12411 } 12412 12413 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12414 + " if any IntentFilter from the " + size 12415 + " Activities needs verification ..."); 12416 12417 int count = 0; 12418 final String packageName = pkg.packageName; 12419 12420 synchronized (mPackages) { 12421 // If this is a new install and we see that we've already run verification for this 12422 // package, we have nothing to do: it means the state was restored from backup. 12423 if (!replacing) { 12424 IntentFilterVerificationInfo ivi = 12425 mSettings.getIntentFilterVerificationLPr(packageName); 12426 if (ivi != null) { 12427 if (DEBUG_DOMAIN_VERIFICATION) { 12428 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12429 + ivi.getStatusString()); 12430 } 12431 return; 12432 } 12433 } 12434 12435 // If any filters need to be verified, then all need to be. 12436 boolean needToVerify = false; 12437 for (PackageParser.Activity a : pkg.activities) { 12438 for (ActivityIntentInfo filter : a.intents) { 12439 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12440 if (DEBUG_DOMAIN_VERIFICATION) { 12441 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12442 } 12443 needToVerify = true; 12444 break; 12445 } 12446 } 12447 } 12448 12449 if (needToVerify) { 12450 final int verificationId = mIntentFilterVerificationToken++; 12451 for (PackageParser.Activity a : pkg.activities) { 12452 for (ActivityIntentInfo filter : a.intents) { 12453 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12454 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12455 "Verification needed for IntentFilter:" + filter.toString()); 12456 mIntentFilterVerifier.addOneIntentFilterVerification( 12457 verifierUid, userId, verificationId, filter, packageName); 12458 count++; 12459 } 12460 } 12461 } 12462 } 12463 } 12464 12465 if (count > 0) { 12466 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12467 + " IntentFilter verification" + (count > 1 ? "s" : "") 12468 + " for userId:" + userId); 12469 mIntentFilterVerifier.startVerifications(userId); 12470 } else { 12471 if (DEBUG_DOMAIN_VERIFICATION) { 12472 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12473 } 12474 } 12475 } 12476 12477 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12478 final ComponentName cn = filter.activity.getComponentName(); 12479 final String packageName = cn.getPackageName(); 12480 12481 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12482 packageName); 12483 if (ivi == null) { 12484 return true; 12485 } 12486 int status = ivi.getStatus(); 12487 switch (status) { 12488 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12489 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12490 return true; 12491 12492 default: 12493 // Nothing to do 12494 return false; 12495 } 12496 } 12497 12498 private static boolean isMultiArch(PackageSetting ps) { 12499 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12500 } 12501 12502 private static boolean isMultiArch(ApplicationInfo info) { 12503 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12504 } 12505 12506 private static boolean isExternal(PackageParser.Package pkg) { 12507 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12508 } 12509 12510 private static boolean isExternal(PackageSetting ps) { 12511 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12512 } 12513 12514 private static boolean isExternal(ApplicationInfo info) { 12515 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12516 } 12517 12518 private static boolean isSystemApp(PackageParser.Package pkg) { 12519 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12520 } 12521 12522 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12523 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12524 } 12525 12526 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12527 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12528 } 12529 12530 private static boolean isSystemApp(PackageSetting ps) { 12531 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12532 } 12533 12534 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12535 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12536 } 12537 12538 private int packageFlagsToInstallFlags(PackageSetting ps) { 12539 int installFlags = 0; 12540 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12541 // This existing package was an external ASEC install when we have 12542 // the external flag without a UUID 12543 installFlags |= PackageManager.INSTALL_EXTERNAL; 12544 } 12545 if (ps.isForwardLocked()) { 12546 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12547 } 12548 return installFlags; 12549 } 12550 12551 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12552 if (isExternal(pkg)) { 12553 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12554 return mSettings.getExternalVersion(); 12555 } else { 12556 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12557 } 12558 } else { 12559 return mSettings.getInternalVersion(); 12560 } 12561 } 12562 12563 private void deleteTempPackageFiles() { 12564 final FilenameFilter filter = new FilenameFilter() { 12565 public boolean accept(File dir, String name) { 12566 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12567 } 12568 }; 12569 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12570 file.delete(); 12571 } 12572 } 12573 12574 @Override 12575 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12576 int flags) { 12577 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12578 flags); 12579 } 12580 12581 @Override 12582 public void deletePackage(final String packageName, 12583 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12584 mContext.enforceCallingOrSelfPermission( 12585 android.Manifest.permission.DELETE_PACKAGES, null); 12586 Preconditions.checkNotNull(packageName); 12587 Preconditions.checkNotNull(observer); 12588 final int uid = Binder.getCallingUid(); 12589 if (UserHandle.getUserId(uid) != userId) { 12590 mContext.enforceCallingPermission( 12591 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12592 "deletePackage for user " + userId); 12593 } 12594 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12595 try { 12596 observer.onPackageDeleted(packageName, 12597 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12598 } catch (RemoteException re) { 12599 } 12600 return; 12601 } 12602 12603 boolean uninstallBlocked = false; 12604 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12605 int[] users = sUserManager.getUserIds(); 12606 for (int i = 0; i < users.length; ++i) { 12607 if (getBlockUninstallForUser(packageName, users[i])) { 12608 uninstallBlocked = true; 12609 break; 12610 } 12611 } 12612 } else { 12613 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12614 } 12615 if (uninstallBlocked) { 12616 try { 12617 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12618 null); 12619 } catch (RemoteException re) { 12620 } 12621 return; 12622 } 12623 12624 if (DEBUG_REMOVE) { 12625 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12626 } 12627 // Queue up an async operation since the package deletion may take a little while. 12628 mHandler.post(new Runnable() { 12629 public void run() { 12630 mHandler.removeCallbacks(this); 12631 final int returnCode = deletePackageX(packageName, userId, flags); 12632 if (observer != null) { 12633 try { 12634 observer.onPackageDeleted(packageName, returnCode, null); 12635 } catch (RemoteException e) { 12636 Log.i(TAG, "Observer no longer exists."); 12637 } //end catch 12638 } //end if 12639 } //end run 12640 }); 12641 } 12642 12643 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12644 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12645 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12646 try { 12647 if (dpm != null) { 12648 if (dpm.isDeviceOwner(packageName)) { 12649 return true; 12650 } 12651 int[] users; 12652 if (userId == UserHandle.USER_ALL) { 12653 users = sUserManager.getUserIds(); 12654 } else { 12655 users = new int[]{userId}; 12656 } 12657 for (int i = 0; i < users.length; ++i) { 12658 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12659 return true; 12660 } 12661 } 12662 } 12663 } catch (RemoteException e) { 12664 } 12665 return false; 12666 } 12667 12668 /** 12669 * This method is an internal method that could be get invoked either 12670 * to delete an installed package or to clean up a failed installation. 12671 * After deleting an installed package, a broadcast is sent to notify any 12672 * listeners that the package has been installed. For cleaning up a failed 12673 * installation, the broadcast is not necessary since the package's 12674 * installation wouldn't have sent the initial broadcast either 12675 * The key steps in deleting a package are 12676 * deleting the package information in internal structures like mPackages, 12677 * deleting the packages base directories through installd 12678 * updating mSettings to reflect current status 12679 * persisting settings for later use 12680 * sending a broadcast if necessary 12681 */ 12682 private int deletePackageX(String packageName, int userId, int flags) { 12683 final PackageRemovedInfo info = new PackageRemovedInfo(); 12684 final boolean res; 12685 12686 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12687 ? UserHandle.ALL : new UserHandle(userId); 12688 12689 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12690 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12691 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12692 } 12693 12694 boolean removedForAllUsers = false; 12695 boolean systemUpdate = false; 12696 12697 // for the uninstall-updates case and restricted profiles, remember the per- 12698 // userhandle installed state 12699 int[] allUsers; 12700 boolean[] perUserInstalled; 12701 synchronized (mPackages) { 12702 PackageSetting ps = mSettings.mPackages.get(packageName); 12703 allUsers = sUserManager.getUserIds(); 12704 perUserInstalled = new boolean[allUsers.length]; 12705 for (int i = 0; i < allUsers.length; i++) { 12706 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12707 } 12708 } 12709 12710 synchronized (mInstallLock) { 12711 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12712 res = deletePackageLI(packageName, removeForUser, 12713 true, allUsers, perUserInstalled, 12714 flags | REMOVE_CHATTY, info, true); 12715 systemUpdate = info.isRemovedPackageSystemUpdate; 12716 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12717 removedForAllUsers = true; 12718 } 12719 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12720 + " removedForAllUsers=" + removedForAllUsers); 12721 } 12722 12723 if (res) { 12724 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12725 12726 // If the removed package was a system update, the old system package 12727 // was re-enabled; we need to broadcast this information 12728 if (systemUpdate) { 12729 Bundle extras = new Bundle(1); 12730 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12731 ? info.removedAppId : info.uid); 12732 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12733 12734 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12735 extras, null, null, null); 12736 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12737 extras, null, null, null); 12738 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12739 null, packageName, null, null); 12740 } 12741 } 12742 // Force a gc here. 12743 Runtime.getRuntime().gc(); 12744 // Delete the resources here after sending the broadcast to let 12745 // other processes clean up before deleting resources. 12746 if (info.args != null) { 12747 synchronized (mInstallLock) { 12748 info.args.doPostDeleteLI(true); 12749 } 12750 } 12751 12752 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12753 } 12754 12755 class PackageRemovedInfo { 12756 String removedPackage; 12757 int uid = -1; 12758 int removedAppId = -1; 12759 int[] removedUsers = null; 12760 boolean isRemovedPackageSystemUpdate = false; 12761 // Clean up resources deleted packages. 12762 InstallArgs args = null; 12763 12764 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12765 Bundle extras = new Bundle(1); 12766 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12767 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12768 if (replacing) { 12769 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12770 } 12771 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12772 if (removedPackage != null) { 12773 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12774 extras, null, null, removedUsers); 12775 if (fullRemove && !replacing) { 12776 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12777 extras, null, null, removedUsers); 12778 } 12779 } 12780 if (removedAppId >= 0) { 12781 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12782 removedUsers); 12783 } 12784 } 12785 } 12786 12787 /* 12788 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12789 * flag is not set, the data directory is removed as well. 12790 * make sure this flag is set for partially installed apps. If not its meaningless to 12791 * delete a partially installed application. 12792 */ 12793 private void removePackageDataLI(PackageSetting ps, 12794 int[] allUserHandles, boolean[] perUserInstalled, 12795 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12796 String packageName = ps.name; 12797 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12798 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12799 // Retrieve object to delete permissions for shared user later on 12800 final PackageSetting deletedPs; 12801 // reader 12802 synchronized (mPackages) { 12803 deletedPs = mSettings.mPackages.get(packageName); 12804 if (outInfo != null) { 12805 outInfo.removedPackage = packageName; 12806 outInfo.removedUsers = deletedPs != null 12807 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12808 : null; 12809 } 12810 } 12811 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12812 removeDataDirsLI(ps.volumeUuid, packageName); 12813 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12814 } 12815 // writer 12816 synchronized (mPackages) { 12817 if (deletedPs != null) { 12818 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12819 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12820 clearDefaultBrowserIfNeeded(packageName); 12821 if (outInfo != null) { 12822 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12823 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12824 } 12825 updatePermissionsLPw(deletedPs.name, null, 0); 12826 if (deletedPs.sharedUser != null) { 12827 // Remove permissions associated with package. Since runtime 12828 // permissions are per user we have to kill the removed package 12829 // or packages running under the shared user of the removed 12830 // package if revoking the permissions requested only by the removed 12831 // package is successful and this causes a change in gids. 12832 for (int userId : UserManagerService.getInstance().getUserIds()) { 12833 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12834 userId); 12835 if (userIdToKill == UserHandle.USER_ALL 12836 || userIdToKill >= UserHandle.USER_OWNER) { 12837 // If gids changed for this user, kill all affected packages. 12838 mHandler.post(new Runnable() { 12839 @Override 12840 public void run() { 12841 // This has to happen with no lock held. 12842 killApplication(deletedPs.name, deletedPs.appId, 12843 KILL_APP_REASON_GIDS_CHANGED); 12844 } 12845 }); 12846 break; 12847 } 12848 } 12849 } 12850 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12851 } 12852 // make sure to preserve per-user disabled state if this removal was just 12853 // a downgrade of a system app to the factory package 12854 if (allUserHandles != null && perUserInstalled != null) { 12855 if (DEBUG_REMOVE) { 12856 Slog.d(TAG, "Propagating install state across downgrade"); 12857 } 12858 for (int i = 0; i < allUserHandles.length; i++) { 12859 if (DEBUG_REMOVE) { 12860 Slog.d(TAG, " user " + allUserHandles[i] 12861 + " => " + perUserInstalled[i]); 12862 } 12863 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12864 } 12865 } 12866 } 12867 // can downgrade to reader 12868 if (writeSettings) { 12869 // Save settings now 12870 mSettings.writeLPr(); 12871 } 12872 } 12873 if (outInfo != null) { 12874 // A user ID was deleted here. Go through all users and remove it 12875 // from KeyStore. 12876 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12877 } 12878 } 12879 12880 static boolean locationIsPrivileged(File path) { 12881 try { 12882 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12883 .getCanonicalPath(); 12884 return path.getCanonicalPath().startsWith(privilegedAppDir); 12885 } catch (IOException e) { 12886 Slog.e(TAG, "Unable to access code path " + path); 12887 } 12888 return false; 12889 } 12890 12891 /* 12892 * Tries to delete system package. 12893 */ 12894 private boolean deleteSystemPackageLI(PackageSetting newPs, 12895 int[] allUserHandles, boolean[] perUserInstalled, 12896 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12897 final boolean applyUserRestrictions 12898 = (allUserHandles != null) && (perUserInstalled != null); 12899 PackageSetting disabledPs = null; 12900 // Confirm if the system package has been updated 12901 // An updated system app can be deleted. This will also have to restore 12902 // the system pkg from system partition 12903 // reader 12904 synchronized (mPackages) { 12905 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12906 } 12907 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12908 + " disabledPs=" + disabledPs); 12909 if (disabledPs == null) { 12910 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12911 return false; 12912 } else if (DEBUG_REMOVE) { 12913 Slog.d(TAG, "Deleting system pkg from data partition"); 12914 } 12915 if (DEBUG_REMOVE) { 12916 if (applyUserRestrictions) { 12917 Slog.d(TAG, "Remembering install states:"); 12918 for (int i = 0; i < allUserHandles.length; i++) { 12919 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12920 } 12921 } 12922 } 12923 // Delete the updated package 12924 outInfo.isRemovedPackageSystemUpdate = true; 12925 if (disabledPs.versionCode < newPs.versionCode) { 12926 // Delete data for downgrades 12927 flags &= ~PackageManager.DELETE_KEEP_DATA; 12928 } else { 12929 // Preserve data by setting flag 12930 flags |= PackageManager.DELETE_KEEP_DATA; 12931 } 12932 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12933 allUserHandles, perUserInstalled, outInfo, writeSettings); 12934 if (!ret) { 12935 return false; 12936 } 12937 // writer 12938 synchronized (mPackages) { 12939 // Reinstate the old system package 12940 mSettings.enableSystemPackageLPw(newPs.name); 12941 // Remove any native libraries from the upgraded package. 12942 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12943 } 12944 // Install the system package 12945 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12946 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12947 if (locationIsPrivileged(disabledPs.codePath)) { 12948 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12949 } 12950 12951 final PackageParser.Package newPkg; 12952 try { 12953 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12954 } catch (PackageManagerException e) { 12955 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12956 return false; 12957 } 12958 12959 // writer 12960 synchronized (mPackages) { 12961 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12962 12963 // Propagate the permissions state as we do not want to drop on the floor 12964 // runtime permissions. The update permissions method below will take 12965 // care of removing obsolete permissions and grant install permissions. 12966 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 12967 updatePermissionsLPw(newPkg.packageName, newPkg, 12968 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12969 12970 if (applyUserRestrictions) { 12971 if (DEBUG_REMOVE) { 12972 Slog.d(TAG, "Propagating install state across reinstall"); 12973 } 12974 for (int i = 0; i < allUserHandles.length; i++) { 12975 if (DEBUG_REMOVE) { 12976 Slog.d(TAG, " user " + allUserHandles[i] 12977 + " => " + perUserInstalled[i]); 12978 } 12979 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12980 12981 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 12982 } 12983 // Regardless of writeSettings we need to ensure that this restriction 12984 // state propagation is persisted 12985 mSettings.writeAllUsersPackageRestrictionsLPr(); 12986 } 12987 // can downgrade to reader here 12988 if (writeSettings) { 12989 mSettings.writeLPr(); 12990 } 12991 } 12992 return true; 12993 } 12994 12995 private boolean deleteInstalledPackageLI(PackageSetting ps, 12996 boolean deleteCodeAndResources, int flags, 12997 int[] allUserHandles, boolean[] perUserInstalled, 12998 PackageRemovedInfo outInfo, boolean writeSettings) { 12999 if (outInfo != null) { 13000 outInfo.uid = ps.appId; 13001 } 13002 13003 // Delete package data from internal structures and also remove data if flag is set 13004 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13005 13006 // Delete application code and resources 13007 if (deleteCodeAndResources && (outInfo != null)) { 13008 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13009 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13010 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13011 } 13012 return true; 13013 } 13014 13015 @Override 13016 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13017 int userId) { 13018 mContext.enforceCallingOrSelfPermission( 13019 android.Manifest.permission.DELETE_PACKAGES, null); 13020 synchronized (mPackages) { 13021 PackageSetting ps = mSettings.mPackages.get(packageName); 13022 if (ps == null) { 13023 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13024 return false; 13025 } 13026 if (!ps.getInstalled(userId)) { 13027 // Can't block uninstall for an app that is not installed or enabled. 13028 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13029 return false; 13030 } 13031 ps.setBlockUninstall(blockUninstall, userId); 13032 mSettings.writePackageRestrictionsLPr(userId); 13033 } 13034 return true; 13035 } 13036 13037 @Override 13038 public boolean getBlockUninstallForUser(String packageName, int userId) { 13039 synchronized (mPackages) { 13040 PackageSetting ps = mSettings.mPackages.get(packageName); 13041 if (ps == null) { 13042 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13043 return false; 13044 } 13045 return ps.getBlockUninstall(userId); 13046 } 13047 } 13048 13049 /* 13050 * This method handles package deletion in general 13051 */ 13052 private boolean deletePackageLI(String packageName, UserHandle user, 13053 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13054 int flags, PackageRemovedInfo outInfo, 13055 boolean writeSettings) { 13056 if (packageName == null) { 13057 Slog.w(TAG, "Attempt to delete null packageName."); 13058 return false; 13059 } 13060 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13061 PackageSetting ps; 13062 boolean dataOnly = false; 13063 int removeUser = -1; 13064 int appId = -1; 13065 synchronized (mPackages) { 13066 ps = mSettings.mPackages.get(packageName); 13067 if (ps == null) { 13068 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13069 return false; 13070 } 13071 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13072 && user.getIdentifier() != UserHandle.USER_ALL) { 13073 // The caller is asking that the package only be deleted for a single 13074 // user. To do this, we just mark its uninstalled state and delete 13075 // its data. If this is a system app, we only allow this to happen if 13076 // they have set the special DELETE_SYSTEM_APP which requests different 13077 // semantics than normal for uninstalling system apps. 13078 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13079 final int userId = user.getIdentifier(); 13080 ps.setUserState(userId, 13081 COMPONENT_ENABLED_STATE_DEFAULT, 13082 false, //installed 13083 true, //stopped 13084 true, //notLaunched 13085 false, //hidden 13086 null, null, null, 13087 false, // blockUninstall 13088 ps.readUserState(userId).domainVerificationStatus, 0); 13089 if (!isSystemApp(ps)) { 13090 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13091 // Other user still have this package installed, so all 13092 // we need to do is clear this user's data and save that 13093 // it is uninstalled. 13094 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13095 removeUser = user.getIdentifier(); 13096 appId = ps.appId; 13097 scheduleWritePackageRestrictionsLocked(removeUser); 13098 } else { 13099 // We need to set it back to 'installed' so the uninstall 13100 // broadcasts will be sent correctly. 13101 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13102 ps.setInstalled(true, user.getIdentifier()); 13103 } 13104 } else { 13105 // This is a system app, so we assume that the 13106 // other users still have this package installed, so all 13107 // we need to do is clear this user's data and save that 13108 // it is uninstalled. 13109 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13110 removeUser = user.getIdentifier(); 13111 appId = ps.appId; 13112 scheduleWritePackageRestrictionsLocked(removeUser); 13113 } 13114 } 13115 } 13116 13117 if (removeUser >= 0) { 13118 // From above, we determined that we are deleting this only 13119 // for a single user. Continue the work here. 13120 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13121 if (outInfo != null) { 13122 outInfo.removedPackage = packageName; 13123 outInfo.removedAppId = appId; 13124 outInfo.removedUsers = new int[] {removeUser}; 13125 } 13126 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13127 removeKeystoreDataIfNeeded(removeUser, appId); 13128 schedulePackageCleaning(packageName, removeUser, false); 13129 synchronized (mPackages) { 13130 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13131 scheduleWritePackageRestrictionsLocked(removeUser); 13132 } 13133 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13134 } 13135 return true; 13136 } 13137 13138 if (dataOnly) { 13139 // Delete application data first 13140 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13141 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13142 return true; 13143 } 13144 13145 boolean ret = false; 13146 if (isSystemApp(ps)) { 13147 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13148 // When an updated system application is deleted we delete the existing resources as well and 13149 // fall back to existing code in system partition 13150 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13151 flags, outInfo, writeSettings); 13152 } else { 13153 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13154 // Kill application pre-emptively especially for apps on sd. 13155 killApplication(packageName, ps.appId, "uninstall pkg"); 13156 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13157 allUserHandles, perUserInstalled, 13158 outInfo, writeSettings); 13159 } 13160 13161 return ret; 13162 } 13163 13164 private final class ClearStorageConnection implements ServiceConnection { 13165 IMediaContainerService mContainerService; 13166 13167 @Override 13168 public void onServiceConnected(ComponentName name, IBinder service) { 13169 synchronized (this) { 13170 mContainerService = IMediaContainerService.Stub.asInterface(service); 13171 notifyAll(); 13172 } 13173 } 13174 13175 @Override 13176 public void onServiceDisconnected(ComponentName name) { 13177 } 13178 } 13179 13180 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13181 final boolean mounted; 13182 if (Environment.isExternalStorageEmulated()) { 13183 mounted = true; 13184 } else { 13185 final String status = Environment.getExternalStorageState(); 13186 13187 mounted = status.equals(Environment.MEDIA_MOUNTED) 13188 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13189 } 13190 13191 if (!mounted) { 13192 return; 13193 } 13194 13195 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13196 int[] users; 13197 if (userId == UserHandle.USER_ALL) { 13198 users = sUserManager.getUserIds(); 13199 } else { 13200 users = new int[] { userId }; 13201 } 13202 final ClearStorageConnection conn = new ClearStorageConnection(); 13203 if (mContext.bindServiceAsUser( 13204 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13205 try { 13206 for (int curUser : users) { 13207 long timeout = SystemClock.uptimeMillis() + 5000; 13208 synchronized (conn) { 13209 long now = SystemClock.uptimeMillis(); 13210 while (conn.mContainerService == null && now < timeout) { 13211 try { 13212 conn.wait(timeout - now); 13213 } catch (InterruptedException e) { 13214 } 13215 } 13216 } 13217 if (conn.mContainerService == null) { 13218 return; 13219 } 13220 13221 final UserEnvironment userEnv = new UserEnvironment(curUser); 13222 clearDirectory(conn.mContainerService, 13223 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13224 if (allData) { 13225 clearDirectory(conn.mContainerService, 13226 userEnv.buildExternalStorageAppDataDirs(packageName)); 13227 clearDirectory(conn.mContainerService, 13228 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13229 } 13230 } 13231 } finally { 13232 mContext.unbindService(conn); 13233 } 13234 } 13235 } 13236 13237 @Override 13238 public void clearApplicationUserData(final String packageName, 13239 final IPackageDataObserver observer, final int userId) { 13240 mContext.enforceCallingOrSelfPermission( 13241 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13242 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13243 // Queue up an async operation since the package deletion may take a little while. 13244 mHandler.post(new Runnable() { 13245 public void run() { 13246 mHandler.removeCallbacks(this); 13247 final boolean succeeded; 13248 synchronized (mInstallLock) { 13249 succeeded = clearApplicationUserDataLI(packageName, userId); 13250 } 13251 clearExternalStorageDataSync(packageName, userId, true); 13252 if (succeeded) { 13253 // invoke DeviceStorageMonitor's update method to clear any notifications 13254 DeviceStorageMonitorInternal 13255 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13256 if (dsm != null) { 13257 dsm.checkMemory(); 13258 } 13259 } 13260 if(observer != null) { 13261 try { 13262 observer.onRemoveCompleted(packageName, succeeded); 13263 } catch (RemoteException e) { 13264 Log.i(TAG, "Observer no longer exists."); 13265 } 13266 } //end if observer 13267 } //end run 13268 }); 13269 } 13270 13271 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13272 if (packageName == null) { 13273 Slog.w(TAG, "Attempt to delete null packageName."); 13274 return false; 13275 } 13276 13277 // Try finding details about the requested package 13278 PackageParser.Package pkg; 13279 synchronized (mPackages) { 13280 pkg = mPackages.get(packageName); 13281 if (pkg == null) { 13282 final PackageSetting ps = mSettings.mPackages.get(packageName); 13283 if (ps != null) { 13284 pkg = ps.pkg; 13285 } 13286 } 13287 13288 if (pkg == null) { 13289 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13290 return false; 13291 } 13292 13293 PackageSetting ps = (PackageSetting) pkg.mExtras; 13294 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13295 } 13296 13297 // Always delete data directories for package, even if we found no other 13298 // record of app. This helps users recover from UID mismatches without 13299 // resorting to a full data wipe. 13300 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13301 if (retCode < 0) { 13302 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13303 return false; 13304 } 13305 13306 final int appId = pkg.applicationInfo.uid; 13307 removeKeystoreDataIfNeeded(userId, appId); 13308 13309 // Create a native library symlink only if we have native libraries 13310 // and if the native libraries are 32 bit libraries. We do not provide 13311 // this symlink for 64 bit libraries. 13312 if (pkg.applicationInfo.primaryCpuAbi != null && 13313 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13314 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13315 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13316 nativeLibPath, userId) < 0) { 13317 Slog.w(TAG, "Failed linking native library dir"); 13318 return false; 13319 } 13320 } 13321 13322 return true; 13323 } 13324 13325 /** 13326 * Reverts user permission state changes (permissions and flags) in 13327 * all packages for a given user. 13328 * 13329 * @param userId The device user for which to do a reset. 13330 */ 13331 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13332 final int packageCount = mPackages.size(); 13333 for (int i = 0; i < packageCount; i++) { 13334 PackageParser.Package pkg = mPackages.valueAt(i); 13335 PackageSetting ps = (PackageSetting) pkg.mExtras; 13336 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13337 } 13338 } 13339 13340 /** 13341 * Reverts user permission state changes (permissions and flags). 13342 * 13343 * @param ps The package for which to reset. 13344 * @param userId The device user for which to do a reset. 13345 */ 13346 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13347 final PackageSetting ps, final int userId) { 13348 if (ps.pkg == null) { 13349 return; 13350 } 13351 13352 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13353 | FLAG_PERMISSION_USER_FIXED 13354 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13355 13356 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13357 | FLAG_PERMISSION_POLICY_FIXED; 13358 13359 boolean writeInstallPermissions = false; 13360 boolean writeRuntimePermissions = false; 13361 13362 final int permissionCount = ps.pkg.requestedPermissions.size(); 13363 for (int i = 0; i < permissionCount; i++) { 13364 String permission = ps.pkg.requestedPermissions.get(i); 13365 13366 BasePermission bp = mSettings.mPermissions.get(permission); 13367 if (bp == null) { 13368 continue; 13369 } 13370 13371 // If shared user we just reset the state to which only this app contributed. 13372 if (ps.sharedUser != null) { 13373 boolean used = false; 13374 final int packageCount = ps.sharedUser.packages.size(); 13375 for (int j = 0; j < packageCount; j++) { 13376 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13377 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13378 && pkg.pkg.requestedPermissions.contains(permission)) { 13379 used = true; 13380 break; 13381 } 13382 } 13383 if (used) { 13384 continue; 13385 } 13386 } 13387 13388 PermissionsState permissionsState = ps.getPermissionsState(); 13389 13390 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13391 13392 // Always clear the user settable flags. 13393 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13394 bp.name) != null; 13395 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13396 if (hasInstallState) { 13397 writeInstallPermissions = true; 13398 } else { 13399 writeRuntimePermissions = true; 13400 } 13401 } 13402 13403 // Below is only runtime permission handling. 13404 if (!bp.isRuntime()) { 13405 continue; 13406 } 13407 13408 // Never clobber system or policy. 13409 if ((oldFlags & policyOrSystemFlags) != 0) { 13410 continue; 13411 } 13412 13413 // If this permission was granted by default, make sure it is. 13414 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13415 if (permissionsState.grantRuntimePermission(bp, userId) 13416 != PERMISSION_OPERATION_FAILURE) { 13417 writeRuntimePermissions = true; 13418 } 13419 } else { 13420 // Otherwise, reset the permission. 13421 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13422 switch (revokeResult) { 13423 case PERMISSION_OPERATION_SUCCESS: { 13424 writeRuntimePermissions = true; 13425 } break; 13426 13427 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13428 writeRuntimePermissions = true; 13429 final int appId = ps.appId; 13430 mHandler.post(new Runnable() { 13431 @Override 13432 public void run() { 13433 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13434 } 13435 }); 13436 } break; 13437 } 13438 } 13439 } 13440 13441 // Synchronously write as we are taking permissions away. 13442 if (writeRuntimePermissions) { 13443 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13444 } 13445 13446 // Synchronously write as we are taking permissions away. 13447 if (writeInstallPermissions) { 13448 mSettings.writeLPr(); 13449 } 13450 } 13451 13452 /** 13453 * Remove entries from the keystore daemon. Will only remove it if the 13454 * {@code appId} is valid. 13455 */ 13456 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13457 if (appId < 0) { 13458 return; 13459 } 13460 13461 final KeyStore keyStore = KeyStore.getInstance(); 13462 if (keyStore != null) { 13463 if (userId == UserHandle.USER_ALL) { 13464 for (final int individual : sUserManager.getUserIds()) { 13465 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13466 } 13467 } else { 13468 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13469 } 13470 } else { 13471 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13472 } 13473 } 13474 13475 @Override 13476 public void deleteApplicationCacheFiles(final String packageName, 13477 final IPackageDataObserver observer) { 13478 mContext.enforceCallingOrSelfPermission( 13479 android.Manifest.permission.DELETE_CACHE_FILES, null); 13480 // Queue up an async operation since the package deletion may take a little while. 13481 final int userId = UserHandle.getCallingUserId(); 13482 mHandler.post(new Runnable() { 13483 public void run() { 13484 mHandler.removeCallbacks(this); 13485 final boolean succeded; 13486 synchronized (mInstallLock) { 13487 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13488 } 13489 clearExternalStorageDataSync(packageName, userId, false); 13490 if (observer != null) { 13491 try { 13492 observer.onRemoveCompleted(packageName, succeded); 13493 } catch (RemoteException e) { 13494 Log.i(TAG, "Observer no longer exists."); 13495 } 13496 } //end if observer 13497 } //end run 13498 }); 13499 } 13500 13501 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13502 if (packageName == null) { 13503 Slog.w(TAG, "Attempt to delete null packageName."); 13504 return false; 13505 } 13506 PackageParser.Package p; 13507 synchronized (mPackages) { 13508 p = mPackages.get(packageName); 13509 } 13510 if (p == null) { 13511 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13512 return false; 13513 } 13514 final ApplicationInfo applicationInfo = p.applicationInfo; 13515 if (applicationInfo == null) { 13516 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13517 return false; 13518 } 13519 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13520 if (retCode < 0) { 13521 Slog.w(TAG, "Couldn't remove cache files for package: " 13522 + packageName + " u" + userId); 13523 return false; 13524 } 13525 return true; 13526 } 13527 13528 @Override 13529 public void getPackageSizeInfo(final String packageName, int userHandle, 13530 final IPackageStatsObserver observer) { 13531 mContext.enforceCallingOrSelfPermission( 13532 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13533 if (packageName == null) { 13534 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13535 } 13536 13537 PackageStats stats = new PackageStats(packageName, userHandle); 13538 13539 /* 13540 * Queue up an async operation since the package measurement may take a 13541 * little while. 13542 */ 13543 Message msg = mHandler.obtainMessage(INIT_COPY); 13544 msg.obj = new MeasureParams(stats, observer); 13545 mHandler.sendMessage(msg); 13546 } 13547 13548 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13549 PackageStats pStats) { 13550 if (packageName == null) { 13551 Slog.w(TAG, "Attempt to get size of null packageName."); 13552 return false; 13553 } 13554 PackageParser.Package p; 13555 boolean dataOnly = false; 13556 String libDirRoot = null; 13557 String asecPath = null; 13558 PackageSetting ps = null; 13559 synchronized (mPackages) { 13560 p = mPackages.get(packageName); 13561 ps = mSettings.mPackages.get(packageName); 13562 if(p == null) { 13563 dataOnly = true; 13564 if((ps == null) || (ps.pkg == null)) { 13565 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13566 return false; 13567 } 13568 p = ps.pkg; 13569 } 13570 if (ps != null) { 13571 libDirRoot = ps.legacyNativeLibraryPathString; 13572 } 13573 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13574 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13575 if (secureContainerId != null) { 13576 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13577 } 13578 } 13579 } 13580 String publicSrcDir = null; 13581 if(!dataOnly) { 13582 final ApplicationInfo applicationInfo = p.applicationInfo; 13583 if (applicationInfo == null) { 13584 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13585 return false; 13586 } 13587 if (p.isForwardLocked()) { 13588 publicSrcDir = applicationInfo.getBaseResourcePath(); 13589 } 13590 } 13591 // TODO: extend to measure size of split APKs 13592 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13593 // not just the first level. 13594 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13595 // just the primary. 13596 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13597 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13598 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13599 if (res < 0) { 13600 return false; 13601 } 13602 13603 // Fix-up for forward-locked applications in ASEC containers. 13604 if (!isExternal(p)) { 13605 pStats.codeSize += pStats.externalCodeSize; 13606 pStats.externalCodeSize = 0L; 13607 } 13608 13609 return true; 13610 } 13611 13612 13613 @Override 13614 public void addPackageToPreferred(String packageName) { 13615 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13616 } 13617 13618 @Override 13619 public void removePackageFromPreferred(String packageName) { 13620 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13621 } 13622 13623 @Override 13624 public List<PackageInfo> getPreferredPackages(int flags) { 13625 return new ArrayList<PackageInfo>(); 13626 } 13627 13628 private int getUidTargetSdkVersionLockedLPr(int uid) { 13629 Object obj = mSettings.getUserIdLPr(uid); 13630 if (obj instanceof SharedUserSetting) { 13631 final SharedUserSetting sus = (SharedUserSetting) obj; 13632 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13633 final Iterator<PackageSetting> it = sus.packages.iterator(); 13634 while (it.hasNext()) { 13635 final PackageSetting ps = it.next(); 13636 if (ps.pkg != null) { 13637 int v = ps.pkg.applicationInfo.targetSdkVersion; 13638 if (v < vers) vers = v; 13639 } 13640 } 13641 return vers; 13642 } else if (obj instanceof PackageSetting) { 13643 final PackageSetting ps = (PackageSetting) obj; 13644 if (ps.pkg != null) { 13645 return ps.pkg.applicationInfo.targetSdkVersion; 13646 } 13647 } 13648 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13649 } 13650 13651 @Override 13652 public void addPreferredActivity(IntentFilter filter, int match, 13653 ComponentName[] set, ComponentName activity, int userId) { 13654 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13655 "Adding preferred"); 13656 } 13657 13658 private void addPreferredActivityInternal(IntentFilter filter, int match, 13659 ComponentName[] set, ComponentName activity, boolean always, int userId, 13660 String opname) { 13661 // writer 13662 int callingUid = Binder.getCallingUid(); 13663 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13664 if (filter.countActions() == 0) { 13665 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13666 return; 13667 } 13668 synchronized (mPackages) { 13669 if (mContext.checkCallingOrSelfPermission( 13670 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13671 != PackageManager.PERMISSION_GRANTED) { 13672 if (getUidTargetSdkVersionLockedLPr(callingUid) 13673 < Build.VERSION_CODES.FROYO) { 13674 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13675 + callingUid); 13676 return; 13677 } 13678 mContext.enforceCallingOrSelfPermission( 13679 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13680 } 13681 13682 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13683 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13684 + userId + ":"); 13685 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13686 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13687 scheduleWritePackageRestrictionsLocked(userId); 13688 } 13689 } 13690 13691 @Override 13692 public void replacePreferredActivity(IntentFilter filter, int match, 13693 ComponentName[] set, ComponentName activity, int userId) { 13694 if (filter.countActions() != 1) { 13695 throw new IllegalArgumentException( 13696 "replacePreferredActivity expects filter to have only 1 action."); 13697 } 13698 if (filter.countDataAuthorities() != 0 13699 || filter.countDataPaths() != 0 13700 || filter.countDataSchemes() > 1 13701 || filter.countDataTypes() != 0) { 13702 throw new IllegalArgumentException( 13703 "replacePreferredActivity expects filter to have no data authorities, " + 13704 "paths, or types; and at most one scheme."); 13705 } 13706 13707 final int callingUid = Binder.getCallingUid(); 13708 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13709 synchronized (mPackages) { 13710 if (mContext.checkCallingOrSelfPermission( 13711 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13712 != PackageManager.PERMISSION_GRANTED) { 13713 if (getUidTargetSdkVersionLockedLPr(callingUid) 13714 < Build.VERSION_CODES.FROYO) { 13715 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13716 + Binder.getCallingUid()); 13717 return; 13718 } 13719 mContext.enforceCallingOrSelfPermission( 13720 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13721 } 13722 13723 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13724 if (pir != null) { 13725 // Get all of the existing entries that exactly match this filter. 13726 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13727 if (existing != null && existing.size() == 1) { 13728 PreferredActivity cur = existing.get(0); 13729 if (DEBUG_PREFERRED) { 13730 Slog.i(TAG, "Checking replace of preferred:"); 13731 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13732 if (!cur.mPref.mAlways) { 13733 Slog.i(TAG, " -- CUR; not mAlways!"); 13734 } else { 13735 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13736 Slog.i(TAG, " -- CUR: mSet=" 13737 + Arrays.toString(cur.mPref.mSetComponents)); 13738 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13739 Slog.i(TAG, " -- NEW: mMatch=" 13740 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13741 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13742 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13743 } 13744 } 13745 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13746 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13747 && cur.mPref.sameSet(set)) { 13748 // Setting the preferred activity to what it happens to be already 13749 if (DEBUG_PREFERRED) { 13750 Slog.i(TAG, "Replacing with same preferred activity " 13751 + cur.mPref.mShortComponent + " for user " 13752 + userId + ":"); 13753 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13754 } 13755 return; 13756 } 13757 } 13758 13759 if (existing != null) { 13760 if (DEBUG_PREFERRED) { 13761 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13762 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13763 } 13764 for (int i = 0; i < existing.size(); i++) { 13765 PreferredActivity pa = existing.get(i); 13766 if (DEBUG_PREFERRED) { 13767 Slog.i(TAG, "Removing existing preferred activity " 13768 + pa.mPref.mComponent + ":"); 13769 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13770 } 13771 pir.removeFilter(pa); 13772 } 13773 } 13774 } 13775 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13776 "Replacing preferred"); 13777 } 13778 } 13779 13780 @Override 13781 public void clearPackagePreferredActivities(String packageName) { 13782 final int uid = Binder.getCallingUid(); 13783 // writer 13784 synchronized (mPackages) { 13785 PackageParser.Package pkg = mPackages.get(packageName); 13786 if (pkg == null || pkg.applicationInfo.uid != uid) { 13787 if (mContext.checkCallingOrSelfPermission( 13788 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13789 != PackageManager.PERMISSION_GRANTED) { 13790 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13791 < Build.VERSION_CODES.FROYO) { 13792 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13793 + Binder.getCallingUid()); 13794 return; 13795 } 13796 mContext.enforceCallingOrSelfPermission( 13797 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13798 } 13799 } 13800 13801 int user = UserHandle.getCallingUserId(); 13802 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13803 scheduleWritePackageRestrictionsLocked(user); 13804 } 13805 } 13806 } 13807 13808 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13809 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13810 ArrayList<PreferredActivity> removed = null; 13811 boolean changed = false; 13812 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13813 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13814 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13815 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13816 continue; 13817 } 13818 Iterator<PreferredActivity> it = pir.filterIterator(); 13819 while (it.hasNext()) { 13820 PreferredActivity pa = it.next(); 13821 // Mark entry for removal only if it matches the package name 13822 // and the entry is of type "always". 13823 if (packageName == null || 13824 (pa.mPref.mComponent.getPackageName().equals(packageName) 13825 && pa.mPref.mAlways)) { 13826 if (removed == null) { 13827 removed = new ArrayList<PreferredActivity>(); 13828 } 13829 removed.add(pa); 13830 } 13831 } 13832 if (removed != null) { 13833 for (int j=0; j<removed.size(); j++) { 13834 PreferredActivity pa = removed.get(j); 13835 pir.removeFilter(pa); 13836 } 13837 changed = true; 13838 } 13839 } 13840 return changed; 13841 } 13842 13843 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13844 private void clearIntentFilterVerificationsLPw(int userId) { 13845 final int packageCount = mPackages.size(); 13846 for (int i = 0; i < packageCount; i++) { 13847 PackageParser.Package pkg = mPackages.valueAt(i); 13848 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13849 } 13850 } 13851 13852 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13853 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13854 if (userId == UserHandle.USER_ALL) { 13855 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13856 sUserManager.getUserIds())) { 13857 for (int oneUserId : sUserManager.getUserIds()) { 13858 scheduleWritePackageRestrictionsLocked(oneUserId); 13859 } 13860 } 13861 } else { 13862 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13863 scheduleWritePackageRestrictionsLocked(userId); 13864 } 13865 } 13866 } 13867 13868 void clearDefaultBrowserIfNeeded(String packageName) { 13869 for (int oneUserId : sUserManager.getUserIds()) { 13870 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13871 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13872 if (packageName.equals(defaultBrowserPackageName)) { 13873 setDefaultBrowserPackageName(null, oneUserId); 13874 } 13875 } 13876 } 13877 13878 @Override 13879 public void resetApplicationPreferences(int userId) { 13880 mContext.enforceCallingOrSelfPermission( 13881 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13882 // writer 13883 synchronized (mPackages) { 13884 final long identity = Binder.clearCallingIdentity(); 13885 try { 13886 clearPackagePreferredActivitiesLPw(null, userId); 13887 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13888 // TODO: We have to reset the default SMS and Phone. This requires 13889 // significant refactoring to keep all default apps in the package 13890 // manager (cleaner but more work) or have the services provide 13891 // callbacks to the package manager to request a default app reset. 13892 applyFactoryDefaultBrowserLPw(userId); 13893 clearIntentFilterVerificationsLPw(userId); 13894 primeDomainVerificationsLPw(userId); 13895 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 13896 scheduleWritePackageRestrictionsLocked(userId); 13897 } finally { 13898 Binder.restoreCallingIdentity(identity); 13899 } 13900 } 13901 } 13902 13903 @Override 13904 public int getPreferredActivities(List<IntentFilter> outFilters, 13905 List<ComponentName> outActivities, String packageName) { 13906 13907 int num = 0; 13908 final int userId = UserHandle.getCallingUserId(); 13909 // reader 13910 synchronized (mPackages) { 13911 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13912 if (pir != null) { 13913 final Iterator<PreferredActivity> it = pir.filterIterator(); 13914 while (it.hasNext()) { 13915 final PreferredActivity pa = it.next(); 13916 if (packageName == null 13917 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13918 && pa.mPref.mAlways)) { 13919 if (outFilters != null) { 13920 outFilters.add(new IntentFilter(pa)); 13921 } 13922 if (outActivities != null) { 13923 outActivities.add(pa.mPref.mComponent); 13924 } 13925 } 13926 } 13927 } 13928 } 13929 13930 return num; 13931 } 13932 13933 @Override 13934 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13935 int userId) { 13936 int callingUid = Binder.getCallingUid(); 13937 if (callingUid != Process.SYSTEM_UID) { 13938 throw new SecurityException( 13939 "addPersistentPreferredActivity can only be run by the system"); 13940 } 13941 if (filter.countActions() == 0) { 13942 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13943 return; 13944 } 13945 synchronized (mPackages) { 13946 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13947 " :"); 13948 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13949 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13950 new PersistentPreferredActivity(filter, activity)); 13951 scheduleWritePackageRestrictionsLocked(userId); 13952 } 13953 } 13954 13955 @Override 13956 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13957 int callingUid = Binder.getCallingUid(); 13958 if (callingUid != Process.SYSTEM_UID) { 13959 throw new SecurityException( 13960 "clearPackagePersistentPreferredActivities can only be run by the system"); 13961 } 13962 ArrayList<PersistentPreferredActivity> removed = null; 13963 boolean changed = false; 13964 synchronized (mPackages) { 13965 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13966 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13967 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13968 .valueAt(i); 13969 if (userId != thisUserId) { 13970 continue; 13971 } 13972 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13973 while (it.hasNext()) { 13974 PersistentPreferredActivity ppa = it.next(); 13975 // Mark entry for removal only if it matches the package name. 13976 if (ppa.mComponent.getPackageName().equals(packageName)) { 13977 if (removed == null) { 13978 removed = new ArrayList<PersistentPreferredActivity>(); 13979 } 13980 removed.add(ppa); 13981 } 13982 } 13983 if (removed != null) { 13984 for (int j=0; j<removed.size(); j++) { 13985 PersistentPreferredActivity ppa = removed.get(j); 13986 ppir.removeFilter(ppa); 13987 } 13988 changed = true; 13989 } 13990 } 13991 13992 if (changed) { 13993 scheduleWritePackageRestrictionsLocked(userId); 13994 } 13995 } 13996 } 13997 13998 /** 13999 * Common machinery for picking apart a restored XML blob and passing 14000 * it to a caller-supplied functor to be applied to the running system. 14001 */ 14002 private void restoreFromXml(XmlPullParser parser, int userId, 14003 String expectedStartTag, BlobXmlRestorer functor) 14004 throws IOException, XmlPullParserException { 14005 int type; 14006 while ((type = parser.next()) != XmlPullParser.START_TAG 14007 && type != XmlPullParser.END_DOCUMENT) { 14008 } 14009 if (type != XmlPullParser.START_TAG) { 14010 // oops didn't find a start tag?! 14011 if (DEBUG_BACKUP) { 14012 Slog.e(TAG, "Didn't find start tag during restore"); 14013 } 14014 return; 14015 } 14016 14017 // this is supposed to be TAG_PREFERRED_BACKUP 14018 if (!expectedStartTag.equals(parser.getName())) { 14019 if (DEBUG_BACKUP) { 14020 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14021 } 14022 return; 14023 } 14024 14025 // skip interfering stuff, then we're aligned with the backing implementation 14026 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14027 functor.apply(parser, userId); 14028 } 14029 14030 private interface BlobXmlRestorer { 14031 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14032 } 14033 14034 /** 14035 * Non-Binder method, support for the backup/restore mechanism: write the 14036 * full set of preferred activities in its canonical XML format. Returns the 14037 * XML output as a byte array, or null if there is none. 14038 */ 14039 @Override 14040 public byte[] getPreferredActivityBackup(int userId) { 14041 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14042 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14043 } 14044 14045 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14046 try { 14047 final XmlSerializer serializer = new FastXmlSerializer(); 14048 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14049 serializer.startDocument(null, true); 14050 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14051 14052 synchronized (mPackages) { 14053 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14054 } 14055 14056 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14057 serializer.endDocument(); 14058 serializer.flush(); 14059 } catch (Exception e) { 14060 if (DEBUG_BACKUP) { 14061 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14062 } 14063 return null; 14064 } 14065 14066 return dataStream.toByteArray(); 14067 } 14068 14069 @Override 14070 public void restorePreferredActivities(byte[] backup, int userId) { 14071 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14072 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14073 } 14074 14075 try { 14076 final XmlPullParser parser = Xml.newPullParser(); 14077 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14078 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14079 new BlobXmlRestorer() { 14080 @Override 14081 public void apply(XmlPullParser parser, int userId) 14082 throws XmlPullParserException, IOException { 14083 synchronized (mPackages) { 14084 mSettings.readPreferredActivitiesLPw(parser, userId); 14085 } 14086 } 14087 } ); 14088 } catch (Exception e) { 14089 if (DEBUG_BACKUP) { 14090 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14091 } 14092 } 14093 } 14094 14095 /** 14096 * Non-Binder method, support for the backup/restore mechanism: write the 14097 * default browser (etc) settings in its canonical XML format. Returns the default 14098 * browser XML representation as a byte array, or null if there is none. 14099 */ 14100 @Override 14101 public byte[] getDefaultAppsBackup(int userId) { 14102 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14103 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14104 } 14105 14106 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14107 try { 14108 final XmlSerializer serializer = new FastXmlSerializer(); 14109 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14110 serializer.startDocument(null, true); 14111 serializer.startTag(null, TAG_DEFAULT_APPS); 14112 14113 synchronized (mPackages) { 14114 mSettings.writeDefaultAppsLPr(serializer, userId); 14115 } 14116 14117 serializer.endTag(null, TAG_DEFAULT_APPS); 14118 serializer.endDocument(); 14119 serializer.flush(); 14120 } catch (Exception e) { 14121 if (DEBUG_BACKUP) { 14122 Slog.e(TAG, "Unable to write default apps for backup", e); 14123 } 14124 return null; 14125 } 14126 14127 return dataStream.toByteArray(); 14128 } 14129 14130 @Override 14131 public void restoreDefaultApps(byte[] backup, int userId) { 14132 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14133 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14134 } 14135 14136 try { 14137 final XmlPullParser parser = Xml.newPullParser(); 14138 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14139 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14140 new BlobXmlRestorer() { 14141 @Override 14142 public void apply(XmlPullParser parser, int userId) 14143 throws XmlPullParserException, IOException { 14144 synchronized (mPackages) { 14145 mSettings.readDefaultAppsLPw(parser, userId); 14146 } 14147 } 14148 } ); 14149 } catch (Exception e) { 14150 if (DEBUG_BACKUP) { 14151 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14152 } 14153 } 14154 } 14155 14156 @Override 14157 public byte[] getIntentFilterVerificationBackup(int userId) { 14158 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14159 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14160 } 14161 14162 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14163 try { 14164 final XmlSerializer serializer = new FastXmlSerializer(); 14165 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14166 serializer.startDocument(null, true); 14167 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14168 14169 synchronized (mPackages) { 14170 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14171 } 14172 14173 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14174 serializer.endDocument(); 14175 serializer.flush(); 14176 } catch (Exception e) { 14177 if (DEBUG_BACKUP) { 14178 Slog.e(TAG, "Unable to write default apps for backup", e); 14179 } 14180 return null; 14181 } 14182 14183 return dataStream.toByteArray(); 14184 } 14185 14186 @Override 14187 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14188 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14189 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14190 } 14191 14192 try { 14193 final XmlPullParser parser = Xml.newPullParser(); 14194 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14195 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14196 new BlobXmlRestorer() { 14197 @Override 14198 public void apply(XmlPullParser parser, int userId) 14199 throws XmlPullParserException, IOException { 14200 synchronized (mPackages) { 14201 mSettings.readAllDomainVerificationsLPr(parser, userId); 14202 mSettings.writeLPr(); 14203 } 14204 } 14205 } ); 14206 } catch (Exception e) { 14207 if (DEBUG_BACKUP) { 14208 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14209 } 14210 } 14211 } 14212 14213 @Override 14214 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14215 int sourceUserId, int targetUserId, int flags) { 14216 mContext.enforceCallingOrSelfPermission( 14217 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14218 int callingUid = Binder.getCallingUid(); 14219 enforceOwnerRights(ownerPackage, callingUid); 14220 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14221 if (intentFilter.countActions() == 0) { 14222 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14223 return; 14224 } 14225 synchronized (mPackages) { 14226 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14227 ownerPackage, targetUserId, flags); 14228 CrossProfileIntentResolver resolver = 14229 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14230 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14231 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14232 if (existing != null) { 14233 int size = existing.size(); 14234 for (int i = 0; i < size; i++) { 14235 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14236 return; 14237 } 14238 } 14239 } 14240 resolver.addFilter(newFilter); 14241 scheduleWritePackageRestrictionsLocked(sourceUserId); 14242 } 14243 } 14244 14245 @Override 14246 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14247 mContext.enforceCallingOrSelfPermission( 14248 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14249 int callingUid = Binder.getCallingUid(); 14250 enforceOwnerRights(ownerPackage, callingUid); 14251 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14252 synchronized (mPackages) { 14253 CrossProfileIntentResolver resolver = 14254 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14255 ArraySet<CrossProfileIntentFilter> set = 14256 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14257 for (CrossProfileIntentFilter filter : set) { 14258 if (filter.getOwnerPackage().equals(ownerPackage)) { 14259 resolver.removeFilter(filter); 14260 } 14261 } 14262 scheduleWritePackageRestrictionsLocked(sourceUserId); 14263 } 14264 } 14265 14266 // Enforcing that callingUid is owning pkg on userId 14267 private void enforceOwnerRights(String pkg, int callingUid) { 14268 // The system owns everything. 14269 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14270 return; 14271 } 14272 int callingUserId = UserHandle.getUserId(callingUid); 14273 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14274 if (pi == null) { 14275 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14276 + callingUserId); 14277 } 14278 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14279 throw new SecurityException("Calling uid " + callingUid 14280 + " does not own package " + pkg); 14281 } 14282 } 14283 14284 @Override 14285 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14286 Intent intent = new Intent(Intent.ACTION_MAIN); 14287 intent.addCategory(Intent.CATEGORY_HOME); 14288 14289 final int callingUserId = UserHandle.getCallingUserId(); 14290 List<ResolveInfo> list = queryIntentActivities(intent, null, 14291 PackageManager.GET_META_DATA, callingUserId); 14292 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14293 true, false, false, callingUserId); 14294 14295 allHomeCandidates.clear(); 14296 if (list != null) { 14297 for (ResolveInfo ri : list) { 14298 allHomeCandidates.add(ri); 14299 } 14300 } 14301 return (preferred == null || preferred.activityInfo == null) 14302 ? null 14303 : new ComponentName(preferred.activityInfo.packageName, 14304 preferred.activityInfo.name); 14305 } 14306 14307 @Override 14308 public void setApplicationEnabledSetting(String appPackageName, 14309 int newState, int flags, int userId, String callingPackage) { 14310 if (!sUserManager.exists(userId)) return; 14311 if (callingPackage == null) { 14312 callingPackage = Integer.toString(Binder.getCallingUid()); 14313 } 14314 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14315 } 14316 14317 @Override 14318 public void setComponentEnabledSetting(ComponentName componentName, 14319 int newState, int flags, int userId) { 14320 if (!sUserManager.exists(userId)) return; 14321 setEnabledSetting(componentName.getPackageName(), 14322 componentName.getClassName(), newState, flags, userId, null); 14323 } 14324 14325 private void setEnabledSetting(final String packageName, String className, int newState, 14326 final int flags, int userId, String callingPackage) { 14327 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14328 || newState == COMPONENT_ENABLED_STATE_ENABLED 14329 || newState == COMPONENT_ENABLED_STATE_DISABLED 14330 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14331 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14332 throw new IllegalArgumentException("Invalid new component state: " 14333 + newState); 14334 } 14335 PackageSetting pkgSetting; 14336 final int uid = Binder.getCallingUid(); 14337 final int permission = mContext.checkCallingOrSelfPermission( 14338 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14339 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14340 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14341 boolean sendNow = false; 14342 boolean isApp = (className == null); 14343 String componentName = isApp ? packageName : className; 14344 int packageUid = -1; 14345 ArrayList<String> components; 14346 14347 // writer 14348 synchronized (mPackages) { 14349 pkgSetting = mSettings.mPackages.get(packageName); 14350 if (pkgSetting == null) { 14351 if (className == null) { 14352 throw new IllegalArgumentException( 14353 "Unknown package: " + packageName); 14354 } 14355 throw new IllegalArgumentException( 14356 "Unknown component: " + packageName 14357 + "/" + className); 14358 } 14359 // Allow root and verify that userId is not being specified by a different user 14360 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14361 throw new SecurityException( 14362 "Permission Denial: attempt to change component state from pid=" 14363 + Binder.getCallingPid() 14364 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14365 } 14366 if (className == null) { 14367 // We're dealing with an application/package level state change 14368 if (pkgSetting.getEnabled(userId) == newState) { 14369 // Nothing to do 14370 return; 14371 } 14372 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14373 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14374 // Don't care about who enables an app. 14375 callingPackage = null; 14376 } 14377 pkgSetting.setEnabled(newState, userId, callingPackage); 14378 // pkgSetting.pkg.mSetEnabled = newState; 14379 } else { 14380 // We're dealing with a component level state change 14381 // First, verify that this is a valid class name. 14382 PackageParser.Package pkg = pkgSetting.pkg; 14383 if (pkg == null || !pkg.hasComponentClassName(className)) { 14384 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14385 throw new IllegalArgumentException("Component class " + className 14386 + " does not exist in " + packageName); 14387 } else { 14388 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14389 + className + " does not exist in " + packageName); 14390 } 14391 } 14392 switch (newState) { 14393 case COMPONENT_ENABLED_STATE_ENABLED: 14394 if (!pkgSetting.enableComponentLPw(className, userId)) { 14395 return; 14396 } 14397 break; 14398 case COMPONENT_ENABLED_STATE_DISABLED: 14399 if (!pkgSetting.disableComponentLPw(className, userId)) { 14400 return; 14401 } 14402 break; 14403 case COMPONENT_ENABLED_STATE_DEFAULT: 14404 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14405 return; 14406 } 14407 break; 14408 default: 14409 Slog.e(TAG, "Invalid new component state: " + newState); 14410 return; 14411 } 14412 } 14413 scheduleWritePackageRestrictionsLocked(userId); 14414 components = mPendingBroadcasts.get(userId, packageName); 14415 final boolean newPackage = components == null; 14416 if (newPackage) { 14417 components = new ArrayList<String>(); 14418 } 14419 if (!components.contains(componentName)) { 14420 components.add(componentName); 14421 } 14422 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14423 sendNow = true; 14424 // Purge entry from pending broadcast list if another one exists already 14425 // since we are sending one right away. 14426 mPendingBroadcasts.remove(userId, packageName); 14427 } else { 14428 if (newPackage) { 14429 mPendingBroadcasts.put(userId, packageName, components); 14430 } 14431 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14432 // Schedule a message 14433 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14434 } 14435 } 14436 } 14437 14438 long callingId = Binder.clearCallingIdentity(); 14439 try { 14440 if (sendNow) { 14441 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14442 sendPackageChangedBroadcast(packageName, 14443 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14444 } 14445 } finally { 14446 Binder.restoreCallingIdentity(callingId); 14447 } 14448 } 14449 14450 private void sendPackageChangedBroadcast(String packageName, 14451 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14452 if (DEBUG_INSTALL) 14453 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14454 + componentNames); 14455 Bundle extras = new Bundle(4); 14456 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14457 String nameList[] = new String[componentNames.size()]; 14458 componentNames.toArray(nameList); 14459 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14460 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14461 extras.putInt(Intent.EXTRA_UID, packageUid); 14462 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14463 new int[] {UserHandle.getUserId(packageUid)}); 14464 } 14465 14466 @Override 14467 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14468 if (!sUserManager.exists(userId)) return; 14469 final int uid = Binder.getCallingUid(); 14470 final int permission = mContext.checkCallingOrSelfPermission( 14471 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14472 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14473 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14474 // writer 14475 synchronized (mPackages) { 14476 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14477 allowedByPermission, uid, userId)) { 14478 scheduleWritePackageRestrictionsLocked(userId); 14479 } 14480 } 14481 } 14482 14483 @Override 14484 public String getInstallerPackageName(String packageName) { 14485 // reader 14486 synchronized (mPackages) { 14487 return mSettings.getInstallerPackageNameLPr(packageName); 14488 } 14489 } 14490 14491 @Override 14492 public int getApplicationEnabledSetting(String packageName, int userId) { 14493 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14494 int uid = Binder.getCallingUid(); 14495 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14496 // reader 14497 synchronized (mPackages) { 14498 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14499 } 14500 } 14501 14502 @Override 14503 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14504 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14505 int uid = Binder.getCallingUid(); 14506 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14507 // reader 14508 synchronized (mPackages) { 14509 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14510 } 14511 } 14512 14513 @Override 14514 public void enterSafeMode() { 14515 enforceSystemOrRoot("Only the system can request entering safe mode"); 14516 14517 if (!mSystemReady) { 14518 mSafeMode = true; 14519 } 14520 } 14521 14522 @Override 14523 public void systemReady() { 14524 mSystemReady = true; 14525 14526 // Read the compatibilty setting when the system is ready. 14527 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14528 mContext.getContentResolver(), 14529 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14530 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14531 if (DEBUG_SETTINGS) { 14532 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14533 } 14534 14535 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14536 14537 synchronized (mPackages) { 14538 // Verify that all of the preferred activity components actually 14539 // exist. It is possible for applications to be updated and at 14540 // that point remove a previously declared activity component that 14541 // had been set as a preferred activity. We try to clean this up 14542 // the next time we encounter that preferred activity, but it is 14543 // possible for the user flow to never be able to return to that 14544 // situation so here we do a sanity check to make sure we haven't 14545 // left any junk around. 14546 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14547 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14548 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14549 removed.clear(); 14550 for (PreferredActivity pa : pir.filterSet()) { 14551 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14552 removed.add(pa); 14553 } 14554 } 14555 if (removed.size() > 0) { 14556 for (int r=0; r<removed.size(); r++) { 14557 PreferredActivity pa = removed.get(r); 14558 Slog.w(TAG, "Removing dangling preferred activity: " 14559 + pa.mPref.mComponent); 14560 pir.removeFilter(pa); 14561 } 14562 mSettings.writePackageRestrictionsLPr( 14563 mSettings.mPreferredActivities.keyAt(i)); 14564 } 14565 } 14566 14567 for (int userId : UserManagerService.getInstance().getUserIds()) { 14568 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14569 grantPermissionsUserIds = ArrayUtils.appendInt( 14570 grantPermissionsUserIds, userId); 14571 } 14572 } 14573 } 14574 sUserManager.systemReady(); 14575 14576 // If we upgraded grant all default permissions before kicking off. 14577 for (int userId : grantPermissionsUserIds) { 14578 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14579 } 14580 14581 // Kick off any messages waiting for system ready 14582 if (mPostSystemReadyMessages != null) { 14583 for (Message msg : mPostSystemReadyMessages) { 14584 msg.sendToTarget(); 14585 } 14586 mPostSystemReadyMessages = null; 14587 } 14588 14589 // Watch for external volumes that come and go over time 14590 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14591 storage.registerListener(mStorageListener); 14592 14593 mInstallerService.systemReady(); 14594 mPackageDexOptimizer.systemReady(); 14595 14596 MountServiceInternal mountServiceInternal = LocalServices.getService( 14597 MountServiceInternal.class); 14598 mountServiceInternal.addExternalStoragePolicy( 14599 new MountServiceInternal.ExternalStorageMountPolicy() { 14600 @Override 14601 public int getMountMode(int uid, String packageName) { 14602 if (Process.isIsolated(uid)) { 14603 return Zygote.MOUNT_EXTERNAL_NONE; 14604 } 14605 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14606 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14607 } 14608 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14609 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14610 } 14611 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14612 return Zygote.MOUNT_EXTERNAL_READ; 14613 } 14614 return Zygote.MOUNT_EXTERNAL_WRITE; 14615 } 14616 14617 @Override 14618 public boolean hasExternalStorage(int uid, String packageName) { 14619 return true; 14620 } 14621 }); 14622 } 14623 14624 @Override 14625 public boolean isSafeMode() { 14626 return mSafeMode; 14627 } 14628 14629 @Override 14630 public boolean hasSystemUidErrors() { 14631 return mHasSystemUidErrors; 14632 } 14633 14634 static String arrayToString(int[] array) { 14635 StringBuffer buf = new StringBuffer(128); 14636 buf.append('['); 14637 if (array != null) { 14638 for (int i=0; i<array.length; i++) { 14639 if (i > 0) buf.append(", "); 14640 buf.append(array[i]); 14641 } 14642 } 14643 buf.append(']'); 14644 return buf.toString(); 14645 } 14646 14647 static class DumpState { 14648 public static final int DUMP_LIBS = 1 << 0; 14649 public static final int DUMP_FEATURES = 1 << 1; 14650 public static final int DUMP_RESOLVERS = 1 << 2; 14651 public static final int DUMP_PERMISSIONS = 1 << 3; 14652 public static final int DUMP_PACKAGES = 1 << 4; 14653 public static final int DUMP_SHARED_USERS = 1 << 5; 14654 public static final int DUMP_MESSAGES = 1 << 6; 14655 public static final int DUMP_PROVIDERS = 1 << 7; 14656 public static final int DUMP_VERIFIERS = 1 << 8; 14657 public static final int DUMP_PREFERRED = 1 << 9; 14658 public static final int DUMP_PREFERRED_XML = 1 << 10; 14659 public static final int DUMP_KEYSETS = 1 << 11; 14660 public static final int DUMP_VERSION = 1 << 12; 14661 public static final int DUMP_INSTALLS = 1 << 13; 14662 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14663 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14664 14665 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14666 14667 private int mTypes; 14668 14669 private int mOptions; 14670 14671 private boolean mTitlePrinted; 14672 14673 private SharedUserSetting mSharedUser; 14674 14675 public boolean isDumping(int type) { 14676 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14677 return true; 14678 } 14679 14680 return (mTypes & type) != 0; 14681 } 14682 14683 public void setDump(int type) { 14684 mTypes |= type; 14685 } 14686 14687 public boolean isOptionEnabled(int option) { 14688 return (mOptions & option) != 0; 14689 } 14690 14691 public void setOptionEnabled(int option) { 14692 mOptions |= option; 14693 } 14694 14695 public boolean onTitlePrinted() { 14696 final boolean printed = mTitlePrinted; 14697 mTitlePrinted = true; 14698 return printed; 14699 } 14700 14701 public boolean getTitlePrinted() { 14702 return mTitlePrinted; 14703 } 14704 14705 public void setTitlePrinted(boolean enabled) { 14706 mTitlePrinted = enabled; 14707 } 14708 14709 public SharedUserSetting getSharedUser() { 14710 return mSharedUser; 14711 } 14712 14713 public void setSharedUser(SharedUserSetting user) { 14714 mSharedUser = user; 14715 } 14716 } 14717 14718 @Override 14719 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14720 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14721 != PackageManager.PERMISSION_GRANTED) { 14722 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14723 + Binder.getCallingPid() 14724 + ", uid=" + Binder.getCallingUid() 14725 + " without permission " 14726 + android.Manifest.permission.DUMP); 14727 return; 14728 } 14729 14730 DumpState dumpState = new DumpState(); 14731 boolean fullPreferred = false; 14732 boolean checkin = false; 14733 14734 String packageName = null; 14735 ArraySet<String> permissionNames = null; 14736 14737 int opti = 0; 14738 while (opti < args.length) { 14739 String opt = args[opti]; 14740 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14741 break; 14742 } 14743 opti++; 14744 14745 if ("-a".equals(opt)) { 14746 // Right now we only know how to print all. 14747 } else if ("-h".equals(opt)) { 14748 pw.println("Package manager dump options:"); 14749 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14750 pw.println(" --checkin: dump for a checkin"); 14751 pw.println(" -f: print details of intent filters"); 14752 pw.println(" -h: print this help"); 14753 pw.println(" cmd may be one of:"); 14754 pw.println(" l[ibraries]: list known shared libraries"); 14755 pw.println(" f[ibraries]: list device features"); 14756 pw.println(" k[eysets]: print known keysets"); 14757 pw.println(" r[esolvers]: dump intent resolvers"); 14758 pw.println(" perm[issions]: dump permissions"); 14759 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14760 pw.println(" pref[erred]: print preferred package settings"); 14761 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14762 pw.println(" prov[iders]: dump content providers"); 14763 pw.println(" p[ackages]: dump installed packages"); 14764 pw.println(" s[hared-users]: dump shared user IDs"); 14765 pw.println(" m[essages]: print collected runtime messages"); 14766 pw.println(" v[erifiers]: print package verifier info"); 14767 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14768 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14769 pw.println(" version: print database version info"); 14770 pw.println(" write: write current settings now"); 14771 pw.println(" installs: details about install sessions"); 14772 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14773 pw.println(" <package.name>: info about given package"); 14774 return; 14775 } else if ("--checkin".equals(opt)) { 14776 checkin = true; 14777 } else if ("-f".equals(opt)) { 14778 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14779 } else { 14780 pw.println("Unknown argument: " + opt + "; use -h for help"); 14781 } 14782 } 14783 14784 // Is the caller requesting to dump a particular piece of data? 14785 if (opti < args.length) { 14786 String cmd = args[opti]; 14787 opti++; 14788 // Is this a package name? 14789 if ("android".equals(cmd) || cmd.contains(".")) { 14790 packageName = cmd; 14791 // When dumping a single package, we always dump all of its 14792 // filter information since the amount of data will be reasonable. 14793 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14794 } else if ("check-permission".equals(cmd)) { 14795 if (opti >= args.length) { 14796 pw.println("Error: check-permission missing permission argument"); 14797 return; 14798 } 14799 String perm = args[opti]; 14800 opti++; 14801 if (opti >= args.length) { 14802 pw.println("Error: check-permission missing package argument"); 14803 return; 14804 } 14805 String pkg = args[opti]; 14806 opti++; 14807 int user = UserHandle.getUserId(Binder.getCallingUid()); 14808 if (opti < args.length) { 14809 try { 14810 user = Integer.parseInt(args[opti]); 14811 } catch (NumberFormatException e) { 14812 pw.println("Error: check-permission user argument is not a number: " 14813 + args[opti]); 14814 return; 14815 } 14816 } 14817 pw.println(checkPermission(perm, pkg, user)); 14818 return; 14819 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14820 dumpState.setDump(DumpState.DUMP_LIBS); 14821 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14822 dumpState.setDump(DumpState.DUMP_FEATURES); 14823 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14824 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14825 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14826 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14827 } else if ("permission".equals(cmd)) { 14828 if (opti >= args.length) { 14829 pw.println("Error: permission requires permission name"); 14830 return; 14831 } 14832 permissionNames = new ArraySet<>(); 14833 while (opti < args.length) { 14834 permissionNames.add(args[opti]); 14835 opti++; 14836 } 14837 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14838 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14839 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14840 dumpState.setDump(DumpState.DUMP_PREFERRED); 14841 } else if ("preferred-xml".equals(cmd)) { 14842 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14843 if (opti < args.length && "--full".equals(args[opti])) { 14844 fullPreferred = true; 14845 opti++; 14846 } 14847 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14848 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14849 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14850 dumpState.setDump(DumpState.DUMP_PACKAGES); 14851 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14852 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14853 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14854 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14855 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14856 dumpState.setDump(DumpState.DUMP_MESSAGES); 14857 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14858 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14859 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14860 || "intent-filter-verifiers".equals(cmd)) { 14861 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14862 } else if ("version".equals(cmd)) { 14863 dumpState.setDump(DumpState.DUMP_VERSION); 14864 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14865 dumpState.setDump(DumpState.DUMP_KEYSETS); 14866 } else if ("installs".equals(cmd)) { 14867 dumpState.setDump(DumpState.DUMP_INSTALLS); 14868 } else if ("write".equals(cmd)) { 14869 synchronized (mPackages) { 14870 mSettings.writeLPr(); 14871 pw.println("Settings written."); 14872 return; 14873 } 14874 } 14875 } 14876 14877 if (checkin) { 14878 pw.println("vers,1"); 14879 } 14880 14881 // reader 14882 synchronized (mPackages) { 14883 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14884 if (!checkin) { 14885 if (dumpState.onTitlePrinted()) 14886 pw.println(); 14887 pw.println("Database versions:"); 14888 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14889 } 14890 } 14891 14892 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14893 if (!checkin) { 14894 if (dumpState.onTitlePrinted()) 14895 pw.println(); 14896 pw.println("Verifiers:"); 14897 pw.print(" Required: "); 14898 pw.print(mRequiredVerifierPackage); 14899 pw.print(" (uid="); 14900 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14901 pw.println(")"); 14902 } else if (mRequiredVerifierPackage != null) { 14903 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14904 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14905 } 14906 } 14907 14908 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14909 packageName == null) { 14910 if (mIntentFilterVerifierComponent != null) { 14911 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14912 if (!checkin) { 14913 if (dumpState.onTitlePrinted()) 14914 pw.println(); 14915 pw.println("Intent Filter Verifier:"); 14916 pw.print(" Using: "); 14917 pw.print(verifierPackageName); 14918 pw.print(" (uid="); 14919 pw.print(getPackageUid(verifierPackageName, 0)); 14920 pw.println(")"); 14921 } else if (verifierPackageName != null) { 14922 pw.print("ifv,"); pw.print(verifierPackageName); 14923 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14924 } 14925 } else { 14926 pw.println(); 14927 pw.println("No Intent Filter Verifier available!"); 14928 } 14929 } 14930 14931 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14932 boolean printedHeader = false; 14933 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14934 while (it.hasNext()) { 14935 String name = it.next(); 14936 SharedLibraryEntry ent = mSharedLibraries.get(name); 14937 if (!checkin) { 14938 if (!printedHeader) { 14939 if (dumpState.onTitlePrinted()) 14940 pw.println(); 14941 pw.println("Libraries:"); 14942 printedHeader = true; 14943 } 14944 pw.print(" "); 14945 } else { 14946 pw.print("lib,"); 14947 } 14948 pw.print(name); 14949 if (!checkin) { 14950 pw.print(" -> "); 14951 } 14952 if (ent.path != null) { 14953 if (!checkin) { 14954 pw.print("(jar) "); 14955 pw.print(ent.path); 14956 } else { 14957 pw.print(",jar,"); 14958 pw.print(ent.path); 14959 } 14960 } else { 14961 if (!checkin) { 14962 pw.print("(apk) "); 14963 pw.print(ent.apk); 14964 } else { 14965 pw.print(",apk,"); 14966 pw.print(ent.apk); 14967 } 14968 } 14969 pw.println(); 14970 } 14971 } 14972 14973 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14974 if (dumpState.onTitlePrinted()) 14975 pw.println(); 14976 if (!checkin) { 14977 pw.println("Features:"); 14978 } 14979 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14980 while (it.hasNext()) { 14981 String name = it.next(); 14982 if (!checkin) { 14983 pw.print(" "); 14984 } else { 14985 pw.print("feat,"); 14986 } 14987 pw.println(name); 14988 } 14989 } 14990 14991 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14992 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14993 : "Activity Resolver Table:", " ", packageName, 14994 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14995 dumpState.setTitlePrinted(true); 14996 } 14997 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14998 : "Receiver Resolver Table:", " ", packageName, 14999 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15000 dumpState.setTitlePrinted(true); 15001 } 15002 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15003 : "Service Resolver Table:", " ", packageName, 15004 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15005 dumpState.setTitlePrinted(true); 15006 } 15007 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15008 : "Provider Resolver Table:", " ", packageName, 15009 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15010 dumpState.setTitlePrinted(true); 15011 } 15012 } 15013 15014 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15015 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15016 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15017 int user = mSettings.mPreferredActivities.keyAt(i); 15018 if (pir.dump(pw, 15019 dumpState.getTitlePrinted() 15020 ? "\nPreferred Activities User " + user + ":" 15021 : "Preferred Activities User " + user + ":", " ", 15022 packageName, true, false)) { 15023 dumpState.setTitlePrinted(true); 15024 } 15025 } 15026 } 15027 15028 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15029 pw.flush(); 15030 FileOutputStream fout = new FileOutputStream(fd); 15031 BufferedOutputStream str = new BufferedOutputStream(fout); 15032 XmlSerializer serializer = new FastXmlSerializer(); 15033 try { 15034 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15035 serializer.startDocument(null, true); 15036 serializer.setFeature( 15037 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15038 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15039 serializer.endDocument(); 15040 serializer.flush(); 15041 } catch (IllegalArgumentException e) { 15042 pw.println("Failed writing: " + e); 15043 } catch (IllegalStateException e) { 15044 pw.println("Failed writing: " + e); 15045 } catch (IOException e) { 15046 pw.println("Failed writing: " + e); 15047 } 15048 } 15049 15050 if (!checkin 15051 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15052 && packageName == null) { 15053 pw.println(); 15054 int count = mSettings.mPackages.size(); 15055 if (count == 0) { 15056 pw.println("No applications!"); 15057 pw.println(); 15058 } else { 15059 final String prefix = " "; 15060 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15061 if (allPackageSettings.size() == 0) { 15062 pw.println("No domain preferred apps!"); 15063 pw.println(); 15064 } else { 15065 pw.println("App verification status:"); 15066 pw.println(); 15067 count = 0; 15068 for (PackageSetting ps : allPackageSettings) { 15069 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15070 if (ivi == null || ivi.getPackageName() == null) continue; 15071 pw.println(prefix + "Package: " + ivi.getPackageName()); 15072 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15073 pw.println(prefix + "Status: " + ivi.getStatusString()); 15074 pw.println(); 15075 count++; 15076 } 15077 if (count == 0) { 15078 pw.println(prefix + "No app verification established."); 15079 pw.println(); 15080 } 15081 for (int userId : sUserManager.getUserIds()) { 15082 pw.println("App linkages for user " + userId + ":"); 15083 pw.println(); 15084 count = 0; 15085 for (PackageSetting ps : allPackageSettings) { 15086 final long status = ps.getDomainVerificationStatusForUser(userId); 15087 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15088 continue; 15089 } 15090 pw.println(prefix + "Package: " + ps.name); 15091 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15092 String statusStr = IntentFilterVerificationInfo. 15093 getStatusStringFromValue(status); 15094 pw.println(prefix + "Status: " + statusStr); 15095 pw.println(); 15096 count++; 15097 } 15098 if (count == 0) { 15099 pw.println(prefix + "No configured app linkages."); 15100 pw.println(); 15101 } 15102 } 15103 } 15104 } 15105 } 15106 15107 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15108 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15109 if (packageName == null && permissionNames == null) { 15110 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15111 if (iperm == 0) { 15112 if (dumpState.onTitlePrinted()) 15113 pw.println(); 15114 pw.println("AppOp Permissions:"); 15115 } 15116 pw.print(" AppOp Permission "); 15117 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15118 pw.println(":"); 15119 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15120 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15121 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15122 } 15123 } 15124 } 15125 } 15126 15127 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15128 boolean printedSomething = false; 15129 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15130 if (packageName != null && !packageName.equals(p.info.packageName)) { 15131 continue; 15132 } 15133 if (!printedSomething) { 15134 if (dumpState.onTitlePrinted()) 15135 pw.println(); 15136 pw.println("Registered ContentProviders:"); 15137 printedSomething = true; 15138 } 15139 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15140 pw.print(" "); pw.println(p.toString()); 15141 } 15142 printedSomething = false; 15143 for (Map.Entry<String, PackageParser.Provider> entry : 15144 mProvidersByAuthority.entrySet()) { 15145 PackageParser.Provider p = entry.getValue(); 15146 if (packageName != null && !packageName.equals(p.info.packageName)) { 15147 continue; 15148 } 15149 if (!printedSomething) { 15150 if (dumpState.onTitlePrinted()) 15151 pw.println(); 15152 pw.println("ContentProvider Authorities:"); 15153 printedSomething = true; 15154 } 15155 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15156 pw.print(" "); pw.println(p.toString()); 15157 if (p.info != null && p.info.applicationInfo != null) { 15158 final String appInfo = p.info.applicationInfo.toString(); 15159 pw.print(" applicationInfo="); pw.println(appInfo); 15160 } 15161 } 15162 } 15163 15164 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15165 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15166 } 15167 15168 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15169 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15170 } 15171 15172 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15173 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15174 } 15175 15176 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15177 // XXX should handle packageName != null by dumping only install data that 15178 // the given package is involved with. 15179 if (dumpState.onTitlePrinted()) pw.println(); 15180 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15181 } 15182 15183 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15184 if (dumpState.onTitlePrinted()) pw.println(); 15185 mSettings.dumpReadMessagesLPr(pw, dumpState); 15186 15187 pw.println(); 15188 pw.println("Package warning messages:"); 15189 BufferedReader in = null; 15190 String line = null; 15191 try { 15192 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15193 while ((line = in.readLine()) != null) { 15194 if (line.contains("ignored: updated version")) continue; 15195 pw.println(line); 15196 } 15197 } catch (IOException ignored) { 15198 } finally { 15199 IoUtils.closeQuietly(in); 15200 } 15201 } 15202 15203 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15204 BufferedReader in = null; 15205 String line = null; 15206 try { 15207 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15208 while ((line = in.readLine()) != null) { 15209 if (line.contains("ignored: updated version")) continue; 15210 pw.print("msg,"); 15211 pw.println(line); 15212 } 15213 } catch (IOException ignored) { 15214 } finally { 15215 IoUtils.closeQuietly(in); 15216 } 15217 } 15218 } 15219 } 15220 15221 private String dumpDomainString(String packageName) { 15222 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15223 List<IntentFilter> filters = getAllIntentFilters(packageName); 15224 15225 ArraySet<String> result = new ArraySet<>(); 15226 if (iviList.size() > 0) { 15227 for (IntentFilterVerificationInfo ivi : iviList) { 15228 for (String host : ivi.getDomains()) { 15229 result.add(host); 15230 } 15231 } 15232 } 15233 if (filters != null && filters.size() > 0) { 15234 for (IntentFilter filter : filters) { 15235 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15236 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15237 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15238 result.addAll(filter.getHostsList()); 15239 } 15240 } 15241 } 15242 15243 StringBuilder sb = new StringBuilder(result.size() * 16); 15244 for (String domain : result) { 15245 if (sb.length() > 0) sb.append(" "); 15246 sb.append(domain); 15247 } 15248 return sb.toString(); 15249 } 15250 15251 // ------- apps on sdcard specific code ------- 15252 static final boolean DEBUG_SD_INSTALL = false; 15253 15254 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15255 15256 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15257 15258 private boolean mMediaMounted = false; 15259 15260 static String getEncryptKey() { 15261 try { 15262 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15263 SD_ENCRYPTION_KEYSTORE_NAME); 15264 if (sdEncKey == null) { 15265 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15266 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15267 if (sdEncKey == null) { 15268 Slog.e(TAG, "Failed to create encryption keys"); 15269 return null; 15270 } 15271 } 15272 return sdEncKey; 15273 } catch (NoSuchAlgorithmException nsae) { 15274 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15275 return null; 15276 } catch (IOException ioe) { 15277 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15278 return null; 15279 } 15280 } 15281 15282 /* 15283 * Update media status on PackageManager. 15284 */ 15285 @Override 15286 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15287 int callingUid = Binder.getCallingUid(); 15288 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15289 throw new SecurityException("Media status can only be updated by the system"); 15290 } 15291 // reader; this apparently protects mMediaMounted, but should probably 15292 // be a different lock in that case. 15293 synchronized (mPackages) { 15294 Log.i(TAG, "Updating external media status from " 15295 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15296 + (mediaStatus ? "mounted" : "unmounted")); 15297 if (DEBUG_SD_INSTALL) 15298 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15299 + ", mMediaMounted=" + mMediaMounted); 15300 if (mediaStatus == mMediaMounted) { 15301 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15302 : 0, -1); 15303 mHandler.sendMessage(msg); 15304 return; 15305 } 15306 mMediaMounted = mediaStatus; 15307 } 15308 // Queue up an async operation since the package installation may take a 15309 // little while. 15310 mHandler.post(new Runnable() { 15311 public void run() { 15312 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15313 } 15314 }); 15315 } 15316 15317 /** 15318 * Called by MountService when the initial ASECs to scan are available. 15319 * Should block until all the ASEC containers are finished being scanned. 15320 */ 15321 public void scanAvailableAsecs() { 15322 updateExternalMediaStatusInner(true, false, false); 15323 if (mShouldRestoreconData) { 15324 SELinuxMMAC.setRestoreconDone(); 15325 mShouldRestoreconData = false; 15326 } 15327 } 15328 15329 /* 15330 * Collect information of applications on external media, map them against 15331 * existing containers and update information based on current mount status. 15332 * Please note that we always have to report status if reportStatus has been 15333 * set to true especially when unloading packages. 15334 */ 15335 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15336 boolean externalStorage) { 15337 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15338 int[] uidArr = EmptyArray.INT; 15339 15340 final String[] list = PackageHelper.getSecureContainerList(); 15341 if (ArrayUtils.isEmpty(list)) { 15342 Log.i(TAG, "No secure containers found"); 15343 } else { 15344 // Process list of secure containers and categorize them 15345 // as active or stale based on their package internal state. 15346 15347 // reader 15348 synchronized (mPackages) { 15349 for (String cid : list) { 15350 // Leave stages untouched for now; installer service owns them 15351 if (PackageInstallerService.isStageName(cid)) continue; 15352 15353 if (DEBUG_SD_INSTALL) 15354 Log.i(TAG, "Processing container " + cid); 15355 String pkgName = getAsecPackageName(cid); 15356 if (pkgName == null) { 15357 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15358 continue; 15359 } 15360 if (DEBUG_SD_INSTALL) 15361 Log.i(TAG, "Looking for pkg : " + pkgName); 15362 15363 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15364 if (ps == null) { 15365 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15366 continue; 15367 } 15368 15369 /* 15370 * Skip packages that are not external if we're unmounting 15371 * external storage. 15372 */ 15373 if (externalStorage && !isMounted && !isExternal(ps)) { 15374 continue; 15375 } 15376 15377 final AsecInstallArgs args = new AsecInstallArgs(cid, 15378 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15379 // The package status is changed only if the code path 15380 // matches between settings and the container id. 15381 if (ps.codePathString != null 15382 && ps.codePathString.startsWith(args.getCodePath())) { 15383 if (DEBUG_SD_INSTALL) { 15384 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15385 + " at code path: " + ps.codePathString); 15386 } 15387 15388 // We do have a valid package installed on sdcard 15389 processCids.put(args, ps.codePathString); 15390 final int uid = ps.appId; 15391 if (uid != -1) { 15392 uidArr = ArrayUtils.appendInt(uidArr, uid); 15393 } 15394 } else { 15395 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15396 + ps.codePathString); 15397 } 15398 } 15399 } 15400 15401 Arrays.sort(uidArr); 15402 } 15403 15404 // Process packages with valid entries. 15405 if (isMounted) { 15406 if (DEBUG_SD_INSTALL) 15407 Log.i(TAG, "Loading packages"); 15408 loadMediaPackages(processCids, uidArr); 15409 startCleaningPackages(); 15410 mInstallerService.onSecureContainersAvailable(); 15411 } else { 15412 if (DEBUG_SD_INSTALL) 15413 Log.i(TAG, "Unloading packages"); 15414 unloadMediaPackages(processCids, uidArr, reportStatus); 15415 } 15416 } 15417 15418 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15419 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15420 final int size = infos.size(); 15421 final String[] packageNames = new String[size]; 15422 final int[] packageUids = new int[size]; 15423 for (int i = 0; i < size; i++) { 15424 final ApplicationInfo info = infos.get(i); 15425 packageNames[i] = info.packageName; 15426 packageUids[i] = info.uid; 15427 } 15428 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15429 finishedReceiver); 15430 } 15431 15432 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15433 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15434 sendResourcesChangedBroadcast(mediaStatus, replacing, 15435 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15436 } 15437 15438 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15439 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15440 int size = pkgList.length; 15441 if (size > 0) { 15442 // Send broadcasts here 15443 Bundle extras = new Bundle(); 15444 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15445 if (uidArr != null) { 15446 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15447 } 15448 if (replacing) { 15449 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15450 } 15451 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15452 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15453 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15454 } 15455 } 15456 15457 /* 15458 * Look at potentially valid container ids from processCids If package 15459 * information doesn't match the one on record or package scanning fails, 15460 * the cid is added to list of removeCids. We currently don't delete stale 15461 * containers. 15462 */ 15463 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15464 ArrayList<String> pkgList = new ArrayList<String>(); 15465 Set<AsecInstallArgs> keys = processCids.keySet(); 15466 15467 for (AsecInstallArgs args : keys) { 15468 String codePath = processCids.get(args); 15469 if (DEBUG_SD_INSTALL) 15470 Log.i(TAG, "Loading container : " + args.cid); 15471 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15472 try { 15473 // Make sure there are no container errors first. 15474 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15475 Slog.e(TAG, "Failed to mount cid : " + args.cid 15476 + " when installing from sdcard"); 15477 continue; 15478 } 15479 // Check code path here. 15480 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15481 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15482 + " does not match one in settings " + codePath); 15483 continue; 15484 } 15485 // Parse package 15486 int parseFlags = mDefParseFlags; 15487 if (args.isExternalAsec()) { 15488 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15489 } 15490 if (args.isFwdLocked()) { 15491 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15492 } 15493 15494 synchronized (mInstallLock) { 15495 PackageParser.Package pkg = null; 15496 try { 15497 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15498 } catch (PackageManagerException e) { 15499 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15500 } 15501 // Scan the package 15502 if (pkg != null) { 15503 /* 15504 * TODO why is the lock being held? doPostInstall is 15505 * called in other places without the lock. This needs 15506 * to be straightened out. 15507 */ 15508 // writer 15509 synchronized (mPackages) { 15510 retCode = PackageManager.INSTALL_SUCCEEDED; 15511 pkgList.add(pkg.packageName); 15512 // Post process args 15513 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15514 pkg.applicationInfo.uid); 15515 } 15516 } else { 15517 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15518 } 15519 } 15520 15521 } finally { 15522 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15523 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15524 } 15525 } 15526 } 15527 // writer 15528 synchronized (mPackages) { 15529 // If the platform SDK has changed since the last time we booted, 15530 // we need to re-grant app permission to catch any new ones that 15531 // appear. This is really a hack, and means that apps can in some 15532 // cases get permissions that the user didn't initially explicitly 15533 // allow... it would be nice to have some better way to handle 15534 // this situation. 15535 final VersionInfo ver = mSettings.getExternalVersion(); 15536 15537 int updateFlags = UPDATE_PERMISSIONS_ALL; 15538 if (ver.sdkVersion != mSdkVersion) { 15539 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15540 + mSdkVersion + "; regranting permissions for external"); 15541 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15542 } 15543 updatePermissionsLPw(null, null, updateFlags); 15544 15545 // Yay, everything is now upgraded 15546 ver.forceCurrent(); 15547 15548 // can downgrade to reader 15549 // Persist settings 15550 mSettings.writeLPr(); 15551 } 15552 // Send a broadcast to let everyone know we are done processing 15553 if (pkgList.size() > 0) { 15554 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15555 } 15556 } 15557 15558 /* 15559 * Utility method to unload a list of specified containers 15560 */ 15561 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15562 // Just unmount all valid containers. 15563 for (AsecInstallArgs arg : cidArgs) { 15564 synchronized (mInstallLock) { 15565 arg.doPostDeleteLI(false); 15566 } 15567 } 15568 } 15569 15570 /* 15571 * Unload packages mounted on external media. This involves deleting package 15572 * data from internal structures, sending broadcasts about diabled packages, 15573 * gc'ing to free up references, unmounting all secure containers 15574 * corresponding to packages on external media, and posting a 15575 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15576 * that we always have to post this message if status has been requested no 15577 * matter what. 15578 */ 15579 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15580 final boolean reportStatus) { 15581 if (DEBUG_SD_INSTALL) 15582 Log.i(TAG, "unloading media packages"); 15583 ArrayList<String> pkgList = new ArrayList<String>(); 15584 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15585 final Set<AsecInstallArgs> keys = processCids.keySet(); 15586 for (AsecInstallArgs args : keys) { 15587 String pkgName = args.getPackageName(); 15588 if (DEBUG_SD_INSTALL) 15589 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15590 // Delete package internally 15591 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15592 synchronized (mInstallLock) { 15593 boolean res = deletePackageLI(pkgName, null, false, null, null, 15594 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15595 if (res) { 15596 pkgList.add(pkgName); 15597 } else { 15598 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15599 failedList.add(args); 15600 } 15601 } 15602 } 15603 15604 // reader 15605 synchronized (mPackages) { 15606 // We didn't update the settings after removing each package; 15607 // write them now for all packages. 15608 mSettings.writeLPr(); 15609 } 15610 15611 // We have to absolutely send UPDATED_MEDIA_STATUS only 15612 // after confirming that all the receivers processed the ordered 15613 // broadcast when packages get disabled, force a gc to clean things up. 15614 // and unload all the containers. 15615 if (pkgList.size() > 0) { 15616 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15617 new IIntentReceiver.Stub() { 15618 public void performReceive(Intent intent, int resultCode, String data, 15619 Bundle extras, boolean ordered, boolean sticky, 15620 int sendingUser) throws RemoteException { 15621 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15622 reportStatus ? 1 : 0, 1, keys); 15623 mHandler.sendMessage(msg); 15624 } 15625 }); 15626 } else { 15627 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15628 keys); 15629 mHandler.sendMessage(msg); 15630 } 15631 } 15632 15633 private void loadPrivatePackages(VolumeInfo vol) { 15634 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15635 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15636 synchronized (mInstallLock) { 15637 synchronized (mPackages) { 15638 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15639 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15640 for (PackageSetting ps : packages) { 15641 final PackageParser.Package pkg; 15642 try { 15643 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15644 loaded.add(pkg.applicationInfo); 15645 } catch (PackageManagerException e) { 15646 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15647 } 15648 15649 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15650 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15651 } 15652 } 15653 15654 int updateFlags = UPDATE_PERMISSIONS_ALL; 15655 if (ver.sdkVersion != mSdkVersion) { 15656 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15657 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15658 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15659 } 15660 updatePermissionsLPw(null, null, updateFlags); 15661 15662 // Yay, everything is now upgraded 15663 ver.forceCurrent(); 15664 15665 mSettings.writeLPr(); 15666 } 15667 } 15668 15669 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15670 sendResourcesChangedBroadcast(true, false, loaded, null); 15671 } 15672 15673 private void unloadPrivatePackages(VolumeInfo vol) { 15674 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15675 synchronized (mInstallLock) { 15676 synchronized (mPackages) { 15677 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15678 for (PackageSetting ps : packages) { 15679 if (ps.pkg == null) continue; 15680 15681 final ApplicationInfo info = ps.pkg.applicationInfo; 15682 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15683 if (deletePackageLI(ps.name, null, false, null, null, 15684 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15685 unloaded.add(info); 15686 } else { 15687 Slog.w(TAG, "Failed to unload " + ps.codePath); 15688 } 15689 } 15690 15691 mSettings.writeLPr(); 15692 } 15693 } 15694 15695 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15696 sendResourcesChangedBroadcast(false, false, unloaded, null); 15697 } 15698 15699 /** 15700 * Examine all users present on given mounted volume, and destroy data 15701 * belonging to users that are no longer valid, or whose user ID has been 15702 * recycled. 15703 */ 15704 private void reconcileUsers(String volumeUuid) { 15705 final File[] files = FileUtils 15706 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15707 for (File file : files) { 15708 if (!file.isDirectory()) continue; 15709 15710 final int userId; 15711 final UserInfo info; 15712 try { 15713 userId = Integer.parseInt(file.getName()); 15714 info = sUserManager.getUserInfo(userId); 15715 } catch (NumberFormatException e) { 15716 Slog.w(TAG, "Invalid user directory " + file); 15717 continue; 15718 } 15719 15720 boolean destroyUser = false; 15721 if (info == null) { 15722 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15723 + " because no matching user was found"); 15724 destroyUser = true; 15725 } else { 15726 try { 15727 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15728 } catch (IOException e) { 15729 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15730 + " because we failed to enforce serial number: " + e); 15731 destroyUser = true; 15732 } 15733 } 15734 15735 if (destroyUser) { 15736 synchronized (mInstallLock) { 15737 mInstaller.removeUserDataDirs(volumeUuid, userId); 15738 } 15739 } 15740 } 15741 15742 final UserManager um = mContext.getSystemService(UserManager.class); 15743 for (UserInfo user : um.getUsers()) { 15744 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15745 if (userDir.exists()) continue; 15746 15747 try { 15748 UserManagerService.prepareUserDirectory(userDir); 15749 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15750 } catch (IOException e) { 15751 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15752 } 15753 } 15754 } 15755 15756 /** 15757 * Examine all apps present on given mounted volume, and destroy apps that 15758 * aren't expected, either due to uninstallation or reinstallation on 15759 * another volume. 15760 */ 15761 private void reconcileApps(String volumeUuid) { 15762 final File[] files = FileUtils 15763 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15764 for (File file : files) { 15765 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15766 && !PackageInstallerService.isStageName(file.getName()); 15767 if (!isPackage) { 15768 // Ignore entries which are not packages 15769 continue; 15770 } 15771 15772 boolean destroyApp = false; 15773 String packageName = null; 15774 try { 15775 final PackageLite pkg = PackageParser.parsePackageLite(file, 15776 PackageParser.PARSE_MUST_BE_APK); 15777 packageName = pkg.packageName; 15778 15779 synchronized (mPackages) { 15780 final PackageSetting ps = mSettings.mPackages.get(packageName); 15781 if (ps == null) { 15782 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15783 + volumeUuid + " because we found no install record"); 15784 destroyApp = true; 15785 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15786 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15787 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15788 destroyApp = true; 15789 } 15790 } 15791 15792 } catch (PackageParserException e) { 15793 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15794 destroyApp = true; 15795 } 15796 15797 if (destroyApp) { 15798 synchronized (mInstallLock) { 15799 if (packageName != null) { 15800 removeDataDirsLI(volumeUuid, packageName); 15801 } 15802 if (file.isDirectory()) { 15803 mInstaller.rmPackageDir(file.getAbsolutePath()); 15804 } else { 15805 file.delete(); 15806 } 15807 } 15808 } 15809 } 15810 } 15811 15812 private void unfreezePackage(String packageName) { 15813 synchronized (mPackages) { 15814 final PackageSetting ps = mSettings.mPackages.get(packageName); 15815 if (ps != null) { 15816 ps.frozen = false; 15817 } 15818 } 15819 } 15820 15821 @Override 15822 public int movePackage(final String packageName, final String volumeUuid) { 15823 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15824 15825 final int moveId = mNextMoveId.getAndIncrement(); 15826 try { 15827 movePackageInternal(packageName, volumeUuid, moveId); 15828 } catch (PackageManagerException e) { 15829 Slog.w(TAG, "Failed to move " + packageName, e); 15830 mMoveCallbacks.notifyStatusChanged(moveId, 15831 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15832 } 15833 return moveId; 15834 } 15835 15836 private void movePackageInternal(final String packageName, final String volumeUuid, 15837 final int moveId) throws PackageManagerException { 15838 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15839 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15840 final PackageManager pm = mContext.getPackageManager(); 15841 15842 final boolean currentAsec; 15843 final String currentVolumeUuid; 15844 final File codeFile; 15845 final String installerPackageName; 15846 final String packageAbiOverride; 15847 final int appId; 15848 final String seinfo; 15849 final String label; 15850 15851 // reader 15852 synchronized (mPackages) { 15853 final PackageParser.Package pkg = mPackages.get(packageName); 15854 final PackageSetting ps = mSettings.mPackages.get(packageName); 15855 if (pkg == null || ps == null) { 15856 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15857 } 15858 15859 if (pkg.applicationInfo.isSystemApp()) { 15860 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15861 "Cannot move system application"); 15862 } 15863 15864 if (pkg.applicationInfo.isExternalAsec()) { 15865 currentAsec = true; 15866 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 15867 } else if (pkg.applicationInfo.isForwardLocked()) { 15868 currentAsec = true; 15869 currentVolumeUuid = "forward_locked"; 15870 } else { 15871 currentAsec = false; 15872 currentVolumeUuid = ps.volumeUuid; 15873 15874 final File probe = new File(pkg.codePath); 15875 final File probeOat = new File(probe, "oat"); 15876 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15877 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15878 "Move only supported for modern cluster style installs"); 15879 } 15880 } 15881 15882 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 15883 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15884 "Package already moved to " + volumeUuid); 15885 } 15886 15887 if (ps.frozen) { 15888 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15889 "Failed to move already frozen package"); 15890 } 15891 ps.frozen = true; 15892 15893 codeFile = new File(pkg.codePath); 15894 installerPackageName = ps.installerPackageName; 15895 packageAbiOverride = ps.cpuAbiOverrideString; 15896 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15897 seinfo = pkg.applicationInfo.seinfo; 15898 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15899 } 15900 15901 // Now that we're guarded by frozen state, kill app during move 15902 final long token = Binder.clearCallingIdentity(); 15903 try { 15904 killApplication(packageName, appId, "move pkg"); 15905 } finally { 15906 Binder.restoreCallingIdentity(token); 15907 } 15908 15909 final Bundle extras = new Bundle(); 15910 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15911 extras.putString(Intent.EXTRA_TITLE, label); 15912 mMoveCallbacks.notifyCreated(moveId, extras); 15913 15914 int installFlags; 15915 final boolean moveCompleteApp; 15916 final File measurePath; 15917 15918 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15919 installFlags = INSTALL_INTERNAL; 15920 moveCompleteApp = !currentAsec; 15921 measurePath = Environment.getDataAppDirectory(volumeUuid); 15922 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15923 installFlags = INSTALL_EXTERNAL; 15924 moveCompleteApp = false; 15925 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15926 } else { 15927 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15928 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15929 || !volume.isMountedWritable()) { 15930 unfreezePackage(packageName); 15931 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15932 "Move location not mounted private volume"); 15933 } 15934 15935 Preconditions.checkState(!currentAsec); 15936 15937 installFlags = INSTALL_INTERNAL; 15938 moveCompleteApp = true; 15939 measurePath = Environment.getDataAppDirectory(volumeUuid); 15940 } 15941 15942 final PackageStats stats = new PackageStats(null, -1); 15943 synchronized (mInstaller) { 15944 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15945 unfreezePackage(packageName); 15946 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15947 "Failed to measure package size"); 15948 } 15949 } 15950 15951 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15952 + stats.dataSize); 15953 15954 final long startFreeBytes = measurePath.getFreeSpace(); 15955 final long sizeBytes; 15956 if (moveCompleteApp) { 15957 sizeBytes = stats.codeSize + stats.dataSize; 15958 } else { 15959 sizeBytes = stats.codeSize; 15960 } 15961 15962 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15963 unfreezePackage(packageName); 15964 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15965 "Not enough free space to move"); 15966 } 15967 15968 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15969 15970 final CountDownLatch installedLatch = new CountDownLatch(1); 15971 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15972 @Override 15973 public void onUserActionRequired(Intent intent) throws RemoteException { 15974 throw new IllegalStateException(); 15975 } 15976 15977 @Override 15978 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15979 Bundle extras) throws RemoteException { 15980 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15981 + PackageManager.installStatusToString(returnCode, msg)); 15982 15983 installedLatch.countDown(); 15984 15985 // Regardless of success or failure of the move operation, 15986 // always unfreeze the package 15987 unfreezePackage(packageName); 15988 15989 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15990 switch (status) { 15991 case PackageInstaller.STATUS_SUCCESS: 15992 mMoveCallbacks.notifyStatusChanged(moveId, 15993 PackageManager.MOVE_SUCCEEDED); 15994 break; 15995 case PackageInstaller.STATUS_FAILURE_STORAGE: 15996 mMoveCallbacks.notifyStatusChanged(moveId, 15997 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15998 break; 15999 default: 16000 mMoveCallbacks.notifyStatusChanged(moveId, 16001 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16002 break; 16003 } 16004 } 16005 }; 16006 16007 final MoveInfo move; 16008 if (moveCompleteApp) { 16009 // Kick off a thread to report progress estimates 16010 new Thread() { 16011 @Override 16012 public void run() { 16013 while (true) { 16014 try { 16015 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16016 break; 16017 } 16018 } catch (InterruptedException ignored) { 16019 } 16020 16021 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16022 final int progress = 10 + (int) MathUtils.constrain( 16023 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16024 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16025 } 16026 } 16027 }.start(); 16028 16029 final String dataAppName = codeFile.getName(); 16030 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16031 dataAppName, appId, seinfo); 16032 } else { 16033 move = null; 16034 } 16035 16036 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16037 16038 final Message msg = mHandler.obtainMessage(INIT_COPY); 16039 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16040 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16041 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16042 mHandler.sendMessage(msg); 16043 } 16044 16045 @Override 16046 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16047 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16048 16049 final int realMoveId = mNextMoveId.getAndIncrement(); 16050 final Bundle extras = new Bundle(); 16051 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16052 mMoveCallbacks.notifyCreated(realMoveId, extras); 16053 16054 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16055 @Override 16056 public void onCreated(int moveId, Bundle extras) { 16057 // Ignored 16058 } 16059 16060 @Override 16061 public void onStatusChanged(int moveId, int status, long estMillis) { 16062 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16063 } 16064 }; 16065 16066 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16067 storage.setPrimaryStorageUuid(volumeUuid, callback); 16068 return realMoveId; 16069 } 16070 16071 @Override 16072 public int getMoveStatus(int moveId) { 16073 mContext.enforceCallingOrSelfPermission( 16074 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16075 return mMoveCallbacks.mLastStatus.get(moveId); 16076 } 16077 16078 @Override 16079 public void registerMoveCallback(IPackageMoveObserver callback) { 16080 mContext.enforceCallingOrSelfPermission( 16081 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16082 mMoveCallbacks.register(callback); 16083 } 16084 16085 @Override 16086 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16087 mContext.enforceCallingOrSelfPermission( 16088 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16089 mMoveCallbacks.unregister(callback); 16090 } 16091 16092 @Override 16093 public boolean setInstallLocation(int loc) { 16094 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16095 null); 16096 if (getInstallLocation() == loc) { 16097 return true; 16098 } 16099 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16100 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16101 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16102 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16103 return true; 16104 } 16105 return false; 16106 } 16107 16108 @Override 16109 public int getInstallLocation() { 16110 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16111 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16112 PackageHelper.APP_INSTALL_AUTO); 16113 } 16114 16115 /** Called by UserManagerService */ 16116 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16117 mDirtyUsers.remove(userHandle); 16118 mSettings.removeUserLPw(userHandle); 16119 mPendingBroadcasts.remove(userHandle); 16120 if (mInstaller != null) { 16121 // Technically, we shouldn't be doing this with the package lock 16122 // held. However, this is very rare, and there is already so much 16123 // other disk I/O going on, that we'll let it slide for now. 16124 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16125 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16126 final String volumeUuid = vol.getFsUuid(); 16127 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16128 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16129 } 16130 } 16131 mUserNeedsBadging.delete(userHandle); 16132 removeUnusedPackagesLILPw(userManager, userHandle); 16133 } 16134 16135 /** 16136 * We're removing userHandle and would like to remove any downloaded packages 16137 * that are no longer in use by any other user. 16138 * @param userHandle the user being removed 16139 */ 16140 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16141 final boolean DEBUG_CLEAN_APKS = false; 16142 int [] users = userManager.getUserIdsLPr(); 16143 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16144 while (psit.hasNext()) { 16145 PackageSetting ps = psit.next(); 16146 if (ps.pkg == null) { 16147 continue; 16148 } 16149 final String packageName = ps.pkg.packageName; 16150 // Skip over if system app 16151 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16152 continue; 16153 } 16154 if (DEBUG_CLEAN_APKS) { 16155 Slog.i(TAG, "Checking package " + packageName); 16156 } 16157 boolean keep = false; 16158 for (int i = 0; i < users.length; i++) { 16159 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16160 keep = true; 16161 if (DEBUG_CLEAN_APKS) { 16162 Slog.i(TAG, " Keeping package " + packageName + " for user " 16163 + users[i]); 16164 } 16165 break; 16166 } 16167 } 16168 if (!keep) { 16169 if (DEBUG_CLEAN_APKS) { 16170 Slog.i(TAG, " Removing package " + packageName); 16171 } 16172 mHandler.post(new Runnable() { 16173 public void run() { 16174 deletePackageX(packageName, userHandle, 0); 16175 } //end run 16176 }); 16177 } 16178 } 16179 } 16180 16181 /** Called by UserManagerService */ 16182 void createNewUserLILPw(int userHandle) { 16183 if (mInstaller != null) { 16184 mInstaller.createUserConfig(userHandle); 16185 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16186 applyFactoryDefaultBrowserLPw(userHandle); 16187 primeDomainVerificationsLPw(userHandle); 16188 } 16189 } 16190 16191 void newUserCreated(final int userHandle) { 16192 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16193 } 16194 16195 @Override 16196 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16197 mContext.enforceCallingOrSelfPermission( 16198 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16199 "Only package verification agents can read the verifier device identity"); 16200 16201 synchronized (mPackages) { 16202 return mSettings.getVerifierDeviceIdentityLPw(); 16203 } 16204 } 16205 16206 @Override 16207 public void setPermissionEnforced(String permission, boolean enforced) { 16208 // TODO: Now that we no longer change GID for storage, this should to away. 16209 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16210 "setPermissionEnforced"); 16211 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16212 synchronized (mPackages) { 16213 if (mSettings.mReadExternalStorageEnforced == null 16214 || mSettings.mReadExternalStorageEnforced != enforced) { 16215 mSettings.mReadExternalStorageEnforced = enforced; 16216 mSettings.writeLPr(); 16217 } 16218 } 16219 // kill any non-foreground processes so we restart them and 16220 // grant/revoke the GID. 16221 final IActivityManager am = ActivityManagerNative.getDefault(); 16222 if (am != null) { 16223 final long token = Binder.clearCallingIdentity(); 16224 try { 16225 am.killProcessesBelowForeground("setPermissionEnforcement"); 16226 } catch (RemoteException e) { 16227 } finally { 16228 Binder.restoreCallingIdentity(token); 16229 } 16230 } 16231 } else { 16232 throw new IllegalArgumentException("No selective enforcement for " + permission); 16233 } 16234 } 16235 16236 @Override 16237 @Deprecated 16238 public boolean isPermissionEnforced(String permission) { 16239 return true; 16240 } 16241 16242 @Override 16243 public boolean isStorageLow() { 16244 final long token = Binder.clearCallingIdentity(); 16245 try { 16246 final DeviceStorageMonitorInternal 16247 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16248 if (dsm != null) { 16249 return dsm.isMemoryLow(); 16250 } else { 16251 return false; 16252 } 16253 } finally { 16254 Binder.restoreCallingIdentity(token); 16255 } 16256 } 16257 16258 @Override 16259 public IPackageInstaller getPackageInstaller() { 16260 return mInstallerService; 16261 } 16262 16263 private boolean userNeedsBadging(int userId) { 16264 int index = mUserNeedsBadging.indexOfKey(userId); 16265 if (index < 0) { 16266 final UserInfo userInfo; 16267 final long token = Binder.clearCallingIdentity(); 16268 try { 16269 userInfo = sUserManager.getUserInfo(userId); 16270 } finally { 16271 Binder.restoreCallingIdentity(token); 16272 } 16273 final boolean b; 16274 if (userInfo != null && userInfo.isManagedProfile()) { 16275 b = true; 16276 } else { 16277 b = false; 16278 } 16279 mUserNeedsBadging.put(userId, b); 16280 return b; 16281 } 16282 return mUserNeedsBadging.valueAt(index); 16283 } 16284 16285 @Override 16286 public KeySet getKeySetByAlias(String packageName, String alias) { 16287 if (packageName == null || alias == null) { 16288 return null; 16289 } 16290 synchronized(mPackages) { 16291 final PackageParser.Package pkg = mPackages.get(packageName); 16292 if (pkg == null) { 16293 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16294 throw new IllegalArgumentException("Unknown package: " + packageName); 16295 } 16296 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16297 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16298 } 16299 } 16300 16301 @Override 16302 public KeySet getSigningKeySet(String packageName) { 16303 if (packageName == null) { 16304 return null; 16305 } 16306 synchronized(mPackages) { 16307 final PackageParser.Package pkg = mPackages.get(packageName); 16308 if (pkg == null) { 16309 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16310 throw new IllegalArgumentException("Unknown package: " + packageName); 16311 } 16312 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16313 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16314 throw new SecurityException("May not access signing KeySet of other apps."); 16315 } 16316 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16317 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16318 } 16319 } 16320 16321 @Override 16322 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16323 if (packageName == null || ks == null) { 16324 return false; 16325 } 16326 synchronized(mPackages) { 16327 final PackageParser.Package pkg = mPackages.get(packageName); 16328 if (pkg == null) { 16329 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16330 throw new IllegalArgumentException("Unknown package: " + packageName); 16331 } 16332 IBinder ksh = ks.getToken(); 16333 if (ksh instanceof KeySetHandle) { 16334 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16335 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16336 } 16337 return false; 16338 } 16339 } 16340 16341 @Override 16342 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16343 if (packageName == null || ks == null) { 16344 return false; 16345 } 16346 synchronized(mPackages) { 16347 final PackageParser.Package pkg = mPackages.get(packageName); 16348 if (pkg == null) { 16349 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16350 throw new IllegalArgumentException("Unknown package: " + packageName); 16351 } 16352 IBinder ksh = ks.getToken(); 16353 if (ksh instanceof KeySetHandle) { 16354 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16355 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16356 } 16357 return false; 16358 } 16359 } 16360 16361 public void getUsageStatsIfNoPackageUsageInfo() { 16362 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16363 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16364 if (usm == null) { 16365 throw new IllegalStateException("UsageStatsManager must be initialized"); 16366 } 16367 long now = System.currentTimeMillis(); 16368 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16369 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16370 String packageName = entry.getKey(); 16371 PackageParser.Package pkg = mPackages.get(packageName); 16372 if (pkg == null) { 16373 continue; 16374 } 16375 UsageStats usage = entry.getValue(); 16376 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16377 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16378 } 16379 } 16380 } 16381 16382 /** 16383 * Check and throw if the given before/after packages would be considered a 16384 * downgrade. 16385 */ 16386 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16387 throws PackageManagerException { 16388 if (after.versionCode < before.mVersionCode) { 16389 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16390 "Update version code " + after.versionCode + " is older than current " 16391 + before.mVersionCode); 16392 } else if (after.versionCode == before.mVersionCode) { 16393 if (after.baseRevisionCode < before.baseRevisionCode) { 16394 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16395 "Update base revision code " + after.baseRevisionCode 16396 + " is older than current " + before.baseRevisionCode); 16397 } 16398 16399 if (!ArrayUtils.isEmpty(after.splitNames)) { 16400 for (int i = 0; i < after.splitNames.length; i++) { 16401 final String splitName = after.splitNames[i]; 16402 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16403 if (j != -1) { 16404 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16405 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16406 "Update split " + splitName + " revision code " 16407 + after.splitRevisionCodes[i] + " is older than current " 16408 + before.splitRevisionCodes[j]); 16409 } 16410 } 16411 } 16412 } 16413 } 16414 } 16415 16416 private static class MoveCallbacks extends Handler { 16417 private static final int MSG_CREATED = 1; 16418 private static final int MSG_STATUS_CHANGED = 2; 16419 16420 private final RemoteCallbackList<IPackageMoveObserver> 16421 mCallbacks = new RemoteCallbackList<>(); 16422 16423 private final SparseIntArray mLastStatus = new SparseIntArray(); 16424 16425 public MoveCallbacks(Looper looper) { 16426 super(looper); 16427 } 16428 16429 public void register(IPackageMoveObserver callback) { 16430 mCallbacks.register(callback); 16431 } 16432 16433 public void unregister(IPackageMoveObserver callback) { 16434 mCallbacks.unregister(callback); 16435 } 16436 16437 @Override 16438 public void handleMessage(Message msg) { 16439 final SomeArgs args = (SomeArgs) msg.obj; 16440 final int n = mCallbacks.beginBroadcast(); 16441 for (int i = 0; i < n; i++) { 16442 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16443 try { 16444 invokeCallback(callback, msg.what, args); 16445 } catch (RemoteException ignored) { 16446 } 16447 } 16448 mCallbacks.finishBroadcast(); 16449 args.recycle(); 16450 } 16451 16452 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16453 throws RemoteException { 16454 switch (what) { 16455 case MSG_CREATED: { 16456 callback.onCreated(args.argi1, (Bundle) args.arg2); 16457 break; 16458 } 16459 case MSG_STATUS_CHANGED: { 16460 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16461 break; 16462 } 16463 } 16464 } 16465 16466 private void notifyCreated(int moveId, Bundle extras) { 16467 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16468 16469 final SomeArgs args = SomeArgs.obtain(); 16470 args.argi1 = moveId; 16471 args.arg2 = extras; 16472 obtainMessage(MSG_CREATED, args).sendToTarget(); 16473 } 16474 16475 private void notifyStatusChanged(int moveId, int status) { 16476 notifyStatusChanged(moveId, status, -1); 16477 } 16478 16479 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16480 Slog.v(TAG, "Move " + moveId + " status " + status); 16481 16482 final SomeArgs args = SomeArgs.obtain(); 16483 args.argi1 = moveId; 16484 args.argi2 = status; 16485 args.arg3 = estMillis; 16486 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16487 16488 synchronized (mLastStatus) { 16489 mLastStatus.put(moveId, status); 16490 } 16491 } 16492 } 16493 16494 private final class OnPermissionChangeListeners extends Handler { 16495 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16496 16497 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16498 new RemoteCallbackList<>(); 16499 16500 public OnPermissionChangeListeners(Looper looper) { 16501 super(looper); 16502 } 16503 16504 @Override 16505 public void handleMessage(Message msg) { 16506 switch (msg.what) { 16507 case MSG_ON_PERMISSIONS_CHANGED: { 16508 final int uid = msg.arg1; 16509 handleOnPermissionsChanged(uid); 16510 } break; 16511 } 16512 } 16513 16514 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16515 mPermissionListeners.register(listener); 16516 16517 } 16518 16519 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16520 mPermissionListeners.unregister(listener); 16521 } 16522 16523 public void onPermissionsChanged(int uid) { 16524 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16525 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16526 } 16527 } 16528 16529 private void handleOnPermissionsChanged(int uid) { 16530 final int count = mPermissionListeners.beginBroadcast(); 16531 try { 16532 for (int i = 0; i < count; i++) { 16533 IOnPermissionsChangeListener callback = mPermissionListeners 16534 .getBroadcastItem(i); 16535 try { 16536 callback.onPermissionsChanged(uid); 16537 } catch (RemoteException e) { 16538 Log.e(TAG, "Permission listener is dead", e); 16539 } 16540 } 16541 } finally { 16542 mPermissionListeners.finishBroadcast(); 16543 } 16544 } 16545 } 16546 16547 private class PackageManagerInternalImpl extends PackageManagerInternal { 16548 @Override 16549 public void setLocationPackagesProvider(PackagesProvider provider) { 16550 synchronized (mPackages) { 16551 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16552 } 16553 } 16554 16555 @Override 16556 public void setImePackagesProvider(PackagesProvider provider) { 16557 synchronized (mPackages) { 16558 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16559 } 16560 } 16561 16562 @Override 16563 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16564 synchronized (mPackages) { 16565 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16566 } 16567 } 16568 16569 @Override 16570 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16571 synchronized (mPackages) { 16572 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16573 } 16574 } 16575 16576 @Override 16577 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16578 synchronized (mPackages) { 16579 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16580 } 16581 } 16582 16583 @Override 16584 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16585 synchronized (mPackages) { 16586 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16587 } 16588 } 16589 16590 @Override 16591 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16592 synchronized (mPackages) { 16593 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16594 } 16595 } 16596 16597 @Override 16598 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16599 synchronized (mPackages) { 16600 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16601 packageName, userId); 16602 } 16603 } 16604 16605 @Override 16606 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16607 synchronized (mPackages) { 16608 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16609 packageName, userId); 16610 } 16611 } 16612 @Override 16613 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16614 synchronized (mPackages) { 16615 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16616 packageName, userId); 16617 } 16618 } 16619 } 16620 16621 @Override 16622 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16623 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16624 synchronized (mPackages) { 16625 final long identity = Binder.clearCallingIdentity(); 16626 try { 16627 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16628 packageNames, userId); 16629 } finally { 16630 Binder.restoreCallingIdentity(identity); 16631 } 16632 } 16633 } 16634 16635 private static void enforceSystemOrPhoneCaller(String tag) { 16636 int callingUid = Binder.getCallingUid(); 16637 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16638 throw new SecurityException( 16639 "Cannot call " + tag + " from UID " + callingUid); 16640 } 16641 } 16642} 16643