PackageManagerService.java revision bdc7141f7f7d278922d240f466244e352d758635
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 * 277runtest -c android.content.pm.PackageManagerTests frameworks-core 278 * 279 * {@hide} 280 */ 281public class PackageManagerService extends IPackageManager.Stub { 282 static final String TAG = "PackageManager"; 283 static final boolean DEBUG_SETTINGS = false; 284 static final boolean DEBUG_PREFERRED = false; 285 static final boolean DEBUG_UPGRADE = false; 286 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 287 private static final boolean DEBUG_BACKUP = false; 288 private static final boolean DEBUG_INSTALL = false; 289 private static final boolean DEBUG_REMOVE = false; 290 private static final boolean DEBUG_BROADCASTS = false; 291 private static final boolean DEBUG_SHOW_INFO = false; 292 private static final boolean DEBUG_PACKAGE_INFO = false; 293 private static final boolean DEBUG_INTENT_MATCHING = false; 294 private static final boolean DEBUG_PACKAGE_SCANNING = false; 295 private static final boolean DEBUG_VERIFY = false; 296 private static final boolean DEBUG_DEXOPT = false; 297 private static final boolean DEBUG_ABI_SELECTION = false; 298 299 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 300 301 private static final int RADIO_UID = Process.PHONE_UID; 302 private static final int LOG_UID = Process.LOG_UID; 303 private static final int NFC_UID = Process.NFC_UID; 304 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 305 private static final int SHELL_UID = Process.SHELL_UID; 306 307 // Cap the size of permission trees that 3rd party apps can define 308 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 309 310 // Suffix used during package installation when copying/moving 311 // package apks to install directory. 312 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 313 314 static final int SCAN_NO_DEX = 1<<1; 315 static final int SCAN_FORCE_DEX = 1<<2; 316 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 317 static final int SCAN_NEW_INSTALL = 1<<4; 318 static final int SCAN_NO_PATHS = 1<<5; 319 static final int SCAN_UPDATE_TIME = 1<<6; 320 static final int SCAN_DEFER_DEX = 1<<7; 321 static final int SCAN_BOOTING = 1<<8; 322 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 323 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 324 static final int SCAN_REQUIRE_KNOWN = 1<<12; 325 static final int SCAN_MOVE = 1<<13; 326 static final int SCAN_INITIAL = 1<<14; 327 328 static final int REMOVE_CHATTY = 1<<16; 329 330 private static final int[] EMPTY_INT_ARRAY = new int[0]; 331 332 /** 333 * Timeout (in milliseconds) after which the watchdog should declare that 334 * our handler thread is wedged. The usual default for such things is one 335 * minute but we sometimes do very lengthy I/O operations on this thread, 336 * such as installing multi-gigabyte applications, so ours needs to be longer. 337 */ 338 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 339 340 /** 341 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 342 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 343 * settings entry if available, otherwise we use the hardcoded default. If it's been 344 * more than this long since the last fstrim, we force one during the boot sequence. 345 * 346 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 347 * one gets run at the next available charging+idle time. This final mandatory 348 * no-fstrim check kicks in only of the other scheduling criteria is never met. 349 */ 350 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 351 352 /** 353 * Whether verification is enabled by default. 354 */ 355 private static final boolean DEFAULT_VERIFY_ENABLE = true; 356 357 /** 358 * The default maximum time to wait for the verification agent to return in 359 * milliseconds. 360 */ 361 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 362 363 /** 364 * The default response for package verification timeout. 365 * 366 * This can be either PackageManager.VERIFICATION_ALLOW or 367 * PackageManager.VERIFICATION_REJECT. 368 */ 369 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 370 371 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 372 373 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 374 DEFAULT_CONTAINER_PACKAGE, 375 "com.android.defcontainer.DefaultContainerService"); 376 377 private static final String KILL_APP_REASON_GIDS_CHANGED = 378 "permission grant or revoke changed gids"; 379 380 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 381 "permissions revoked"; 382 383 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 384 385 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 386 387 /** Permission grant: not grant the permission. */ 388 private static final int GRANT_DENIED = 1; 389 390 /** Permission grant: grant the permission as an install permission. */ 391 private static final int GRANT_INSTALL = 2; 392 393 /** Permission grant: grant the permission as an install permission for a legacy app. */ 394 private static final int GRANT_INSTALL_LEGACY = 3; 395 396 /** Permission grant: grant the permission as a runtime one. */ 397 private static final int GRANT_RUNTIME = 4; 398 399 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 400 private static final int GRANT_UPGRADE = 5; 401 402 /** Canonical intent used to identify what counts as a "web browser" app */ 403 private static final Intent sBrowserIntent; 404 static { 405 sBrowserIntent = new Intent(); 406 sBrowserIntent.setAction(Intent.ACTION_VIEW); 407 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 408 sBrowserIntent.setData(Uri.parse("http:")); 409 } 410 411 final ServiceThread mHandlerThread; 412 413 final PackageHandler mHandler; 414 415 /** 416 * Messages for {@link #mHandler} that need to wait for system ready before 417 * being dispatched. 418 */ 419 private ArrayList<Message> mPostSystemReadyMessages; 420 421 final int mSdkVersion = Build.VERSION.SDK_INT; 422 423 final Context mContext; 424 final boolean mFactoryTest; 425 final boolean mOnlyCore; 426 final boolean mLazyDexOpt; 427 final long mDexOptLRUThresholdInMills; 428 final DisplayMetrics mMetrics; 429 final int mDefParseFlags; 430 final String[] mSeparateProcesses; 431 final boolean mIsUpgrade; 432 433 // This is where all application persistent data goes. 434 final File mAppDataDir; 435 436 // This is where all application persistent data goes for secondary users. 437 final File mUserAppDataDir; 438 439 /** The location for ASEC container files on internal storage. */ 440 final String mAsecInternalPath; 441 442 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 443 // LOCK HELD. Can be called with mInstallLock held. 444 @GuardedBy("mInstallLock") 445 final Installer mInstaller; 446 447 /** Directory where installed third-party apps stored */ 448 final File mAppInstallDir; 449 450 /** 451 * Directory to which applications installed internally have their 452 * 32 bit native libraries copied. 453 */ 454 private File mAppLib32InstallDir; 455 456 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 457 // apps. 458 final File mDrmAppPrivateInstallDir; 459 460 // ---------------------------------------------------------------- 461 462 // Lock for state used when installing and doing other long running 463 // operations. Methods that must be called with this lock held have 464 // the suffix "LI". 465 final Object mInstallLock = new Object(); 466 467 // ---------------------------------------------------------------- 468 469 // Keys are String (package name), values are Package. This also serves 470 // as the lock for the global state. Methods that must be called with 471 // this lock held have the prefix "LP". 472 @GuardedBy("mPackages") 473 final ArrayMap<String, PackageParser.Package> mPackages = 474 new ArrayMap<String, PackageParser.Package>(); 475 476 // Tracks available target package names -> overlay package paths. 477 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 478 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 479 480 /** 481 * Tracks new system packages [receiving in an OTA] that we expect to 482 * find updated user-installed versions. Keys are package name, values 483 * are package location. 484 */ 485 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 486 487 final Settings mSettings; 488 boolean mRestoredSettings; 489 490 // System configuration read by SystemConfig. 491 final int[] mGlobalGids; 492 final SparseArray<ArraySet<String>> mSystemPermissions; 493 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 494 495 // If mac_permissions.xml was found for seinfo labeling. 496 boolean mFoundPolicyFile; 497 498 // If a recursive restorecon of /data/data/<pkg> is needed. 499 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 500 501 public static final class SharedLibraryEntry { 502 public final String path; 503 public final String apk; 504 505 SharedLibraryEntry(String _path, String _apk) { 506 path = _path; 507 apk = _apk; 508 } 509 } 510 511 // Currently known shared libraries. 512 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 513 new ArrayMap<String, SharedLibraryEntry>(); 514 515 // All available activities, for your resolving pleasure. 516 final ActivityIntentResolver mActivities = 517 new ActivityIntentResolver(); 518 519 // All available receivers, for your resolving pleasure. 520 final ActivityIntentResolver mReceivers = 521 new ActivityIntentResolver(); 522 523 // All available services, for your resolving pleasure. 524 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 525 526 // All available providers, for your resolving pleasure. 527 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 528 529 // Mapping from provider base names (first directory in content URI codePath) 530 // to the provider information. 531 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 532 new ArrayMap<String, PackageParser.Provider>(); 533 534 // Mapping from instrumentation class names to info about them. 535 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 536 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 537 538 // Mapping from permission names to info about them. 539 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 540 new ArrayMap<String, PackageParser.PermissionGroup>(); 541 542 // Packages whose data we have transfered into another package, thus 543 // should no longer exist. 544 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 545 546 // Broadcast actions that are only available to the system. 547 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 548 549 /** List of packages waiting for verification. */ 550 final SparseArray<PackageVerificationState> mPendingVerification 551 = new SparseArray<PackageVerificationState>(); 552 553 /** Set of packages associated with each app op permission. */ 554 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 555 556 final PackageInstallerService mInstallerService; 557 558 private final PackageDexOptimizer mPackageDexOptimizer; 559 560 private AtomicInteger mNextMoveId = new AtomicInteger(); 561 private final MoveCallbacks mMoveCallbacks; 562 563 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 564 565 // Cache of users who need badging. 566 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 567 568 /** Token for keys in mPendingVerification. */ 569 private int mPendingVerificationToken = 0; 570 571 volatile boolean mSystemReady; 572 volatile boolean mSafeMode; 573 volatile boolean mHasSystemUidErrors; 574 575 ApplicationInfo mAndroidApplication; 576 final ActivityInfo mResolveActivity = new ActivityInfo(); 577 final ResolveInfo mResolveInfo = new ResolveInfo(); 578 ComponentName mResolveComponentName; 579 PackageParser.Package mPlatformPackage; 580 ComponentName mCustomResolverComponentName; 581 582 boolean mResolverReplaced = false; 583 584 private final ComponentName mIntentFilterVerifierComponent; 585 private int mIntentFilterVerificationToken = 0; 586 587 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 588 = new SparseArray<IntentFilterVerificationState>(); 589 590 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 591 new DefaultPermissionGrantPolicy(this); 592 593 private static class IFVerificationParams { 594 PackageParser.Package pkg; 595 boolean replacing; 596 int userId; 597 int verifierUid; 598 599 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 600 int _userId, int _verifierUid) { 601 pkg = _pkg; 602 replacing = _replacing; 603 userId = _userId; 604 replacing = _replacing; 605 verifierUid = _verifierUid; 606 } 607 } 608 609 private interface IntentFilterVerifier<T extends IntentFilter> { 610 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 611 T filter, String packageName); 612 void startVerifications(int userId); 613 void receiveVerificationResponse(int verificationId); 614 } 615 616 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 617 private Context mContext; 618 private ComponentName mIntentFilterVerifierComponent; 619 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 620 621 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 622 mContext = context; 623 mIntentFilterVerifierComponent = verifierComponent; 624 } 625 626 private String getDefaultScheme() { 627 return IntentFilter.SCHEME_HTTPS; 628 } 629 630 @Override 631 public void startVerifications(int userId) { 632 // Launch verifications requests 633 int count = mCurrentIntentFilterVerifications.size(); 634 for (int n=0; n<count; n++) { 635 int verificationId = mCurrentIntentFilterVerifications.get(n); 636 final IntentFilterVerificationState ivs = 637 mIntentFilterVerificationStates.get(verificationId); 638 639 String packageName = ivs.getPackageName(); 640 641 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 642 final int filterCount = filters.size(); 643 ArraySet<String> domainsSet = new ArraySet<>(); 644 for (int m=0; m<filterCount; m++) { 645 PackageParser.ActivityIntentInfo filter = filters.get(m); 646 domainsSet.addAll(filter.getHostsList()); 647 } 648 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 649 synchronized (mPackages) { 650 if (mSettings.createIntentFilterVerificationIfNeededLPw( 651 packageName, domainsList) != null) { 652 scheduleWriteSettingsLocked(); 653 } 654 } 655 sendVerificationRequest(userId, verificationId, ivs); 656 } 657 mCurrentIntentFilterVerifications.clear(); 658 } 659 660 private void sendVerificationRequest(int userId, int verificationId, 661 IntentFilterVerificationState ivs) { 662 663 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 664 verificationIntent.putExtra( 665 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 666 verificationId); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 669 getDefaultScheme()); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 672 ivs.getHostsString()); 673 verificationIntent.putExtra( 674 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 675 ivs.getPackageName()); 676 verificationIntent.setComponent(mIntentFilterVerifierComponent); 677 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 678 679 UserHandle user = new UserHandle(userId); 680 mContext.sendBroadcastAsUser(verificationIntent, user); 681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 682 "Sending IntentFilter verification broadcast"); 683 } 684 685 public void receiveVerificationResponse(int verificationId) { 686 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 687 688 final boolean verified = ivs.isVerified(); 689 690 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 691 final int count = filters.size(); 692 if (DEBUG_DOMAIN_VERIFICATION) { 693 Slog.i(TAG, "Received verification response " + verificationId 694 + " for " + count + " filters, verified=" + verified); 695 } 696 for (int n=0; n<count; n++) { 697 PackageParser.ActivityIntentInfo filter = filters.get(n); 698 filter.setVerified(verified); 699 700 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 701 + " verified with result:" + verified + " and hosts:" 702 + ivs.getHostsString()); 703 } 704 705 mIntentFilterVerificationStates.remove(verificationId); 706 707 final String packageName = ivs.getPackageName(); 708 IntentFilterVerificationInfo ivi = null; 709 710 synchronized (mPackages) { 711 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 712 } 713 if (ivi == null) { 714 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 715 + verificationId + " packageName:" + packageName); 716 return; 717 } 718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 719 "Updating IntentFilterVerificationInfo for package " + packageName 720 +" verificationId:" + verificationId); 721 722 synchronized (mPackages) { 723 if (verified) { 724 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 725 } else { 726 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 727 } 728 scheduleWriteSettingsLocked(); 729 730 final int userId = ivs.getUserId(); 731 if (userId != UserHandle.USER_ALL) { 732 final int userStatus = 733 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 734 735 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 736 boolean needUpdate = false; 737 738 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 739 // already been set by the User thru the Disambiguation dialog 740 switch (userStatus) { 741 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 742 if (verified) { 743 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 744 } else { 745 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 746 } 747 needUpdate = true; 748 break; 749 750 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 751 if (verified) { 752 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 753 needUpdate = true; 754 } 755 break; 756 757 default: 758 // Nothing to do 759 } 760 761 if (needUpdate) { 762 mSettings.updateIntentFilterVerificationStatusLPw( 763 packageName, updatedStatus, userId); 764 scheduleWritePackageRestrictionsLocked(userId); 765 } 766 } 767 } 768 } 769 770 @Override 771 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 772 ActivityIntentInfo filter, String packageName) { 773 if (!hasValidDomains(filter)) { 774 return false; 775 } 776 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 777 if (ivs == null) { 778 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 779 packageName); 780 } 781 if (DEBUG_DOMAIN_VERIFICATION) { 782 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 783 } 784 ivs.addFilter(filter); 785 return true; 786 } 787 788 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 789 int userId, int verificationId, String packageName) { 790 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 791 verifierUid, userId, packageName); 792 ivs.setPendingState(); 793 synchronized (mPackages) { 794 mIntentFilterVerificationStates.append(verificationId, ivs); 795 mCurrentIntentFilterVerifications.add(verificationId); 796 } 797 return ivs; 798 } 799 } 800 801 private static boolean hasValidDomains(ActivityIntentInfo filter) { 802 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 803 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 804 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 805 } 806 807 private IntentFilterVerifier mIntentFilterVerifier; 808 809 // Set of pending broadcasts for aggregating enable/disable of components. 810 static class PendingPackageBroadcasts { 811 // for each user id, a map of <package name -> components within that package> 812 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 813 814 public PendingPackageBroadcasts() { 815 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 816 } 817 818 public ArrayList<String> get(int userId, String packageName) { 819 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 820 return packages.get(packageName); 821 } 822 823 public void put(int userId, String packageName, ArrayList<String> components) { 824 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 825 packages.put(packageName, components); 826 } 827 828 public void remove(int userId, String packageName) { 829 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 830 if (packages != null) { 831 packages.remove(packageName); 832 } 833 } 834 835 public void remove(int userId) { 836 mUidMap.remove(userId); 837 } 838 839 public int userIdCount() { 840 return mUidMap.size(); 841 } 842 843 public int userIdAt(int n) { 844 return mUidMap.keyAt(n); 845 } 846 847 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 848 return mUidMap.get(userId); 849 } 850 851 public int size() { 852 // total number of pending broadcast entries across all userIds 853 int num = 0; 854 for (int i = 0; i< mUidMap.size(); i++) { 855 num += mUidMap.valueAt(i).size(); 856 } 857 return num; 858 } 859 860 public void clear() { 861 mUidMap.clear(); 862 } 863 864 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 865 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 866 if (map == null) { 867 map = new ArrayMap<String, ArrayList<String>>(); 868 mUidMap.put(userId, map); 869 } 870 return map; 871 } 872 } 873 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 874 875 // Service Connection to remote media container service to copy 876 // package uri's from external media onto secure containers 877 // or internal storage. 878 private IMediaContainerService mContainerService = null; 879 880 static final int SEND_PENDING_BROADCAST = 1; 881 static final int MCS_BOUND = 3; 882 static final int END_COPY = 4; 883 static final int INIT_COPY = 5; 884 static final int MCS_UNBIND = 6; 885 static final int START_CLEANING_PACKAGE = 7; 886 static final int FIND_INSTALL_LOC = 8; 887 static final int POST_INSTALL = 9; 888 static final int MCS_RECONNECT = 10; 889 static final int MCS_GIVE_UP = 11; 890 static final int UPDATED_MEDIA_STATUS = 12; 891 static final int WRITE_SETTINGS = 13; 892 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 893 static final int PACKAGE_VERIFIED = 15; 894 static final int CHECK_PENDING_VERIFICATION = 16; 895 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 896 static final int INTENT_FILTER_VERIFIED = 18; 897 898 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 899 900 // Delay time in millisecs 901 static final int BROADCAST_DELAY = 10 * 1000; 902 903 static UserManagerService sUserManager; 904 905 // Stores a list of users whose package restrictions file needs to be updated 906 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 907 908 final private DefaultContainerConnection mDefContainerConn = 909 new DefaultContainerConnection(); 910 class DefaultContainerConnection implements ServiceConnection { 911 public void onServiceConnected(ComponentName name, IBinder service) { 912 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 913 IMediaContainerService imcs = 914 IMediaContainerService.Stub.asInterface(service); 915 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 916 } 917 918 public void onServiceDisconnected(ComponentName name) { 919 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 920 } 921 } 922 923 // Recordkeeping of restore-after-install operations that are currently in flight 924 // between the Package Manager and the Backup Manager 925 class PostInstallData { 926 public InstallArgs args; 927 public PackageInstalledInfo res; 928 929 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 930 args = _a; 931 res = _r; 932 } 933 } 934 935 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 936 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 937 938 // XML tags for backup/restore of various bits of state 939 private static final String TAG_PREFERRED_BACKUP = "pa"; 940 private static final String TAG_DEFAULT_APPS = "da"; 941 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 942 943 final String mRequiredVerifierPackage; 944 final String mRequiredInstallerPackage; 945 946 private final PackageUsage mPackageUsage = new PackageUsage(); 947 948 private class PackageUsage { 949 private static final int WRITE_INTERVAL 950 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 951 952 private final Object mFileLock = new Object(); 953 private final AtomicLong mLastWritten = new AtomicLong(0); 954 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 955 956 private boolean mIsHistoricalPackageUsageAvailable = true; 957 958 boolean isHistoricalPackageUsageAvailable() { 959 return mIsHistoricalPackageUsageAvailable; 960 } 961 962 void write(boolean force) { 963 if (force) { 964 writeInternal(); 965 return; 966 } 967 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 968 && !DEBUG_DEXOPT) { 969 return; 970 } 971 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 972 new Thread("PackageUsage_DiskWriter") { 973 @Override 974 public void run() { 975 try { 976 writeInternal(); 977 } finally { 978 mBackgroundWriteRunning.set(false); 979 } 980 } 981 }.start(); 982 } 983 } 984 985 private void writeInternal() { 986 synchronized (mPackages) { 987 synchronized (mFileLock) { 988 AtomicFile file = getFile(); 989 FileOutputStream f = null; 990 try { 991 f = file.startWrite(); 992 BufferedOutputStream out = new BufferedOutputStream(f); 993 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 994 StringBuilder sb = new StringBuilder(); 995 for (PackageParser.Package pkg : mPackages.values()) { 996 if (pkg.mLastPackageUsageTimeInMills == 0) { 997 continue; 998 } 999 sb.setLength(0); 1000 sb.append(pkg.packageName); 1001 sb.append(' '); 1002 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1003 sb.append('\n'); 1004 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1005 } 1006 out.flush(); 1007 file.finishWrite(f); 1008 } catch (IOException e) { 1009 if (f != null) { 1010 file.failWrite(f); 1011 } 1012 Log.e(TAG, "Failed to write package usage times", e); 1013 } 1014 } 1015 } 1016 mLastWritten.set(SystemClock.elapsedRealtime()); 1017 } 1018 1019 void readLP() { 1020 synchronized (mFileLock) { 1021 AtomicFile file = getFile(); 1022 BufferedInputStream in = null; 1023 try { 1024 in = new BufferedInputStream(file.openRead()); 1025 StringBuffer sb = new StringBuffer(); 1026 while (true) { 1027 String packageName = readToken(in, sb, ' '); 1028 if (packageName == null) { 1029 break; 1030 } 1031 String timeInMillisString = readToken(in, sb, '\n'); 1032 if (timeInMillisString == null) { 1033 throw new IOException("Failed to find last usage time for package " 1034 + packageName); 1035 } 1036 PackageParser.Package pkg = mPackages.get(packageName); 1037 if (pkg == null) { 1038 continue; 1039 } 1040 long timeInMillis; 1041 try { 1042 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1043 } catch (NumberFormatException e) { 1044 throw new IOException("Failed to parse " + timeInMillisString 1045 + " as a long.", e); 1046 } 1047 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1048 } 1049 } catch (FileNotFoundException expected) { 1050 mIsHistoricalPackageUsageAvailable = false; 1051 } catch (IOException e) { 1052 Log.w(TAG, "Failed to read package usage times", e); 1053 } finally { 1054 IoUtils.closeQuietly(in); 1055 } 1056 } 1057 mLastWritten.set(SystemClock.elapsedRealtime()); 1058 } 1059 1060 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1061 throws IOException { 1062 sb.setLength(0); 1063 while (true) { 1064 int ch = in.read(); 1065 if (ch == -1) { 1066 if (sb.length() == 0) { 1067 return null; 1068 } 1069 throw new IOException("Unexpected EOF"); 1070 } 1071 if (ch == endOfToken) { 1072 return sb.toString(); 1073 } 1074 sb.append((char)ch); 1075 } 1076 } 1077 1078 private AtomicFile getFile() { 1079 File dataDir = Environment.getDataDirectory(); 1080 File systemDir = new File(dataDir, "system"); 1081 File fname = new File(systemDir, "package-usage.list"); 1082 return new AtomicFile(fname); 1083 } 1084 } 1085 1086 class PackageHandler extends Handler { 1087 private boolean mBound = false; 1088 final ArrayList<HandlerParams> mPendingInstalls = 1089 new ArrayList<HandlerParams>(); 1090 1091 private boolean connectToService() { 1092 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1093 " DefaultContainerService"); 1094 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1095 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1096 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1097 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1099 mBound = true; 1100 return true; 1101 } 1102 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1103 return false; 1104 } 1105 1106 private void disconnectService() { 1107 mContainerService = null; 1108 mBound = false; 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 mContext.unbindService(mDefContainerConn); 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 } 1113 1114 PackageHandler(Looper looper) { 1115 super(looper); 1116 } 1117 1118 public void handleMessage(Message msg) { 1119 try { 1120 doHandleMessage(msg); 1121 } finally { 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1123 } 1124 } 1125 1126 void doHandleMessage(Message msg) { 1127 switch (msg.what) { 1128 case INIT_COPY: { 1129 HandlerParams params = (HandlerParams) msg.obj; 1130 int idx = mPendingInstalls.size(); 1131 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1132 // If a bind was already initiated we dont really 1133 // need to do anything. The pending install 1134 // will be processed later on. 1135 if (!mBound) { 1136 // If this is the only one pending we might 1137 // have to bind to the service again. 1138 if (!connectToService()) { 1139 Slog.e(TAG, "Failed to bind to media container service"); 1140 params.serviceError(); 1141 return; 1142 } else { 1143 // Once we bind to the service, the first 1144 // pending request will be processed. 1145 mPendingInstalls.add(idx, params); 1146 } 1147 } else { 1148 mPendingInstalls.add(idx, params); 1149 // Already bound to the service. Just make 1150 // sure we trigger off processing the first request. 1151 if (idx == 0) { 1152 mHandler.sendEmptyMessage(MCS_BOUND); 1153 } 1154 } 1155 break; 1156 } 1157 case MCS_BOUND: { 1158 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1159 if (msg.obj != null) { 1160 mContainerService = (IMediaContainerService) msg.obj; 1161 } 1162 if (mContainerService == null) { 1163 if (!mBound) { 1164 // Something seriously wrong since we are not bound and we are not 1165 // waiting for connection. Bail out. 1166 Slog.e(TAG, "Cannot bind to media container service"); 1167 for (HandlerParams params : mPendingInstalls) { 1168 // Indicate service bind error 1169 params.serviceError(); 1170 } 1171 mPendingInstalls.clear(); 1172 } else { 1173 Slog.w(TAG, "Waiting to connect to media container service"); 1174 } 1175 } else if (mPendingInstalls.size() > 0) { 1176 HandlerParams params = mPendingInstalls.get(0); 1177 if (params != null) { 1178 if (params.startCopy()) { 1179 // We are done... look for more work or to 1180 // go idle. 1181 if (DEBUG_SD_INSTALL) Log.i(TAG, 1182 "Checking for more work or unbind..."); 1183 // Delete pending install 1184 if (mPendingInstalls.size() > 0) { 1185 mPendingInstalls.remove(0); 1186 } 1187 if (mPendingInstalls.size() == 0) { 1188 if (mBound) { 1189 if (DEBUG_SD_INSTALL) Log.i(TAG, 1190 "Posting delayed MCS_UNBIND"); 1191 removeMessages(MCS_UNBIND); 1192 Message ubmsg = obtainMessage(MCS_UNBIND); 1193 // Unbind after a little delay, to avoid 1194 // continual thrashing. 1195 sendMessageDelayed(ubmsg, 10000); 1196 } 1197 } else { 1198 // There are more pending requests in queue. 1199 // Just post MCS_BOUND message to trigger processing 1200 // of next pending install. 1201 if (DEBUG_SD_INSTALL) Log.i(TAG, 1202 "Posting MCS_BOUND for next work"); 1203 mHandler.sendEmptyMessage(MCS_BOUND); 1204 } 1205 } 1206 } 1207 } else { 1208 // Should never happen ideally. 1209 Slog.w(TAG, "Empty queue"); 1210 } 1211 break; 1212 } 1213 case MCS_RECONNECT: { 1214 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1215 if (mPendingInstalls.size() > 0) { 1216 if (mBound) { 1217 disconnectService(); 1218 } 1219 if (!connectToService()) { 1220 Slog.e(TAG, "Failed to bind to media container service"); 1221 for (HandlerParams params : mPendingInstalls) { 1222 // Indicate service bind error 1223 params.serviceError(); 1224 } 1225 mPendingInstalls.clear(); 1226 } 1227 } 1228 break; 1229 } 1230 case MCS_UNBIND: { 1231 // If there is no actual work left, then time to unbind. 1232 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1233 1234 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1235 if (mBound) { 1236 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1237 1238 disconnectService(); 1239 } 1240 } else if (mPendingInstalls.size() > 0) { 1241 // There are more pending requests in queue. 1242 // Just post MCS_BOUND message to trigger processing 1243 // of next pending install. 1244 mHandler.sendEmptyMessage(MCS_BOUND); 1245 } 1246 1247 break; 1248 } 1249 case MCS_GIVE_UP: { 1250 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1251 mPendingInstalls.remove(0); 1252 break; 1253 } 1254 case SEND_PENDING_BROADCAST: { 1255 String packages[]; 1256 ArrayList<String> components[]; 1257 int size = 0; 1258 int uids[]; 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1260 synchronized (mPackages) { 1261 if (mPendingBroadcasts == null) { 1262 return; 1263 } 1264 size = mPendingBroadcasts.size(); 1265 if (size <= 0) { 1266 // Nothing to be done. Just return 1267 return; 1268 } 1269 packages = new String[size]; 1270 components = new ArrayList[size]; 1271 uids = new int[size]; 1272 int i = 0; // filling out the above arrays 1273 1274 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1275 int packageUserId = mPendingBroadcasts.userIdAt(n); 1276 Iterator<Map.Entry<String, ArrayList<String>>> it 1277 = mPendingBroadcasts.packagesForUserId(packageUserId) 1278 .entrySet().iterator(); 1279 while (it.hasNext() && i < size) { 1280 Map.Entry<String, ArrayList<String>> ent = it.next(); 1281 packages[i] = ent.getKey(); 1282 components[i] = ent.getValue(); 1283 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1284 uids[i] = (ps != null) 1285 ? UserHandle.getUid(packageUserId, ps.appId) 1286 : -1; 1287 i++; 1288 } 1289 } 1290 size = i; 1291 mPendingBroadcasts.clear(); 1292 } 1293 // Send broadcasts 1294 for (int i = 0; i < size; i++) { 1295 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1296 } 1297 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1298 break; 1299 } 1300 case START_CLEANING_PACKAGE: { 1301 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1302 final String packageName = (String)msg.obj; 1303 final int userId = msg.arg1; 1304 final boolean andCode = msg.arg2 != 0; 1305 synchronized (mPackages) { 1306 if (userId == UserHandle.USER_ALL) { 1307 int[] users = sUserManager.getUserIds(); 1308 for (int user : users) { 1309 mSettings.addPackageToCleanLPw( 1310 new PackageCleanItem(user, packageName, andCode)); 1311 } 1312 } else { 1313 mSettings.addPackageToCleanLPw( 1314 new PackageCleanItem(userId, packageName, andCode)); 1315 } 1316 } 1317 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1318 startCleaningPackages(); 1319 } break; 1320 case POST_INSTALL: { 1321 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1322 PostInstallData data = mRunningInstalls.get(msg.arg1); 1323 mRunningInstalls.delete(msg.arg1); 1324 boolean deleteOld = false; 1325 1326 if (data != null) { 1327 InstallArgs args = data.args; 1328 PackageInstalledInfo res = data.res; 1329 1330 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1331 final String packageName = res.pkg.applicationInfo.packageName; 1332 res.removedInfo.sendBroadcast(false, true, false); 1333 Bundle extras = new Bundle(1); 1334 extras.putInt(Intent.EXTRA_UID, res.uid); 1335 1336 // Now that we successfully installed the package, grant runtime 1337 // permissions if requested before broadcasting the install. 1338 if ((args.installFlags 1339 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1340 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1341 args.installGrantPermissions); 1342 } 1343 1344 // Determine the set of users who are adding this 1345 // package for the first time vs. those who are seeing 1346 // an update. 1347 int[] firstUsers; 1348 int[] updateUsers = new int[0]; 1349 if (res.origUsers == null || res.origUsers.length == 0) { 1350 firstUsers = res.newUsers; 1351 } else { 1352 firstUsers = new int[0]; 1353 for (int i=0; i<res.newUsers.length; i++) { 1354 int user = res.newUsers[i]; 1355 boolean isNew = true; 1356 for (int j=0; j<res.origUsers.length; j++) { 1357 if (res.origUsers[j] == user) { 1358 isNew = false; 1359 break; 1360 } 1361 } 1362 if (isNew) { 1363 int[] newFirst = new int[firstUsers.length+1]; 1364 System.arraycopy(firstUsers, 0, newFirst, 0, 1365 firstUsers.length); 1366 newFirst[firstUsers.length] = user; 1367 firstUsers = newFirst; 1368 } else { 1369 int[] newUpdate = new int[updateUsers.length+1]; 1370 System.arraycopy(updateUsers, 0, newUpdate, 0, 1371 updateUsers.length); 1372 newUpdate[updateUsers.length] = user; 1373 updateUsers = newUpdate; 1374 } 1375 } 1376 } 1377 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1378 packageName, extras, null, null, firstUsers); 1379 final boolean update = res.removedInfo.removedPackage != null; 1380 if (update) { 1381 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1382 } 1383 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1384 packageName, extras, null, null, updateUsers); 1385 if (update) { 1386 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1387 packageName, extras, null, null, updateUsers); 1388 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1389 null, null, packageName, null, updateUsers); 1390 1391 // treat asec-hosted packages like removable media on upgrade 1392 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1393 if (DEBUG_INSTALL) { 1394 Slog.i(TAG, "upgrading pkg " + res.pkg 1395 + " is ASEC-hosted -> AVAILABLE"); 1396 } 1397 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1398 ArrayList<String> pkgList = new ArrayList<String>(1); 1399 pkgList.add(packageName); 1400 sendResourcesChangedBroadcast(true, true, 1401 pkgList,uidArray, null); 1402 } 1403 } 1404 if (res.removedInfo.args != null) { 1405 // Remove the replaced package's older resources safely now 1406 deleteOld = true; 1407 } 1408 1409 // If this app is a browser and it's newly-installed for some 1410 // users, clear any default-browser state in those users 1411 if (firstUsers.length > 0) { 1412 // the app's nature doesn't depend on the user, so we can just 1413 // check its browser nature in any user and generalize. 1414 if (packageIsBrowser(packageName, firstUsers[0])) { 1415 synchronized (mPackages) { 1416 for (int userId : firstUsers) { 1417 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1418 } 1419 } 1420 } 1421 } 1422 // Log current value of "unknown sources" setting 1423 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1424 getUnknownSourcesSettings()); 1425 } 1426 // Force a gc to clear up things 1427 Runtime.getRuntime().gc(); 1428 // We delete after a gc for applications on sdcard. 1429 if (deleteOld) { 1430 synchronized (mInstallLock) { 1431 res.removedInfo.args.doPostDeleteLI(true); 1432 } 1433 } 1434 if (args.observer != null) { 1435 try { 1436 Bundle extras = extrasForInstallResult(res); 1437 args.observer.onPackageInstalled(res.name, res.returnCode, 1438 res.returnMsg, extras); 1439 } catch (RemoteException e) { 1440 Slog.i(TAG, "Observer no longer exists."); 1441 } 1442 } 1443 } else { 1444 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1445 } 1446 } break; 1447 case UPDATED_MEDIA_STATUS: { 1448 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1449 boolean reportStatus = msg.arg1 == 1; 1450 boolean doGc = msg.arg2 == 1; 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1452 if (doGc) { 1453 // Force a gc to clear up stale containers. 1454 Runtime.getRuntime().gc(); 1455 } 1456 if (msg.obj != null) { 1457 @SuppressWarnings("unchecked") 1458 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1459 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1460 // Unload containers 1461 unloadAllContainers(args); 1462 } 1463 if (reportStatus) { 1464 try { 1465 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1466 PackageHelper.getMountService().finishMediaUpdate(); 1467 } catch (RemoteException e) { 1468 Log.e(TAG, "MountService not running?"); 1469 } 1470 } 1471 } break; 1472 case WRITE_SETTINGS: { 1473 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1474 synchronized (mPackages) { 1475 removeMessages(WRITE_SETTINGS); 1476 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1477 mSettings.writeLPr(); 1478 mDirtyUsers.clear(); 1479 } 1480 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1481 } break; 1482 case WRITE_PACKAGE_RESTRICTIONS: { 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1484 synchronized (mPackages) { 1485 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1486 for (int userId : mDirtyUsers) { 1487 mSettings.writePackageRestrictionsLPr(userId); 1488 } 1489 mDirtyUsers.clear(); 1490 } 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1492 } break; 1493 case CHECK_PENDING_VERIFICATION: { 1494 final int verificationId = msg.arg1; 1495 final PackageVerificationState state = mPendingVerification.get(verificationId); 1496 1497 if ((state != null) && !state.timeoutExtended()) { 1498 final InstallArgs args = state.getInstallArgs(); 1499 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1500 1501 Slog.i(TAG, "Verification timed out for " + originUri); 1502 mPendingVerification.remove(verificationId); 1503 1504 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1505 1506 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1507 Slog.i(TAG, "Continuing with installation of " + originUri); 1508 state.setVerifierResponse(Binder.getCallingUid(), 1509 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1510 broadcastPackageVerified(verificationId, originUri, 1511 PackageManager.VERIFICATION_ALLOW, 1512 state.getInstallArgs().getUser()); 1513 try { 1514 ret = args.copyApk(mContainerService, true); 1515 } catch (RemoteException e) { 1516 Slog.e(TAG, "Could not contact the ContainerService"); 1517 } 1518 } else { 1519 broadcastPackageVerified(verificationId, originUri, 1520 PackageManager.VERIFICATION_REJECT, 1521 state.getInstallArgs().getUser()); 1522 } 1523 1524 processPendingInstall(args, ret); 1525 mHandler.sendEmptyMessage(MCS_UNBIND); 1526 } 1527 break; 1528 } 1529 case PACKAGE_VERIFIED: { 1530 final int verificationId = msg.arg1; 1531 1532 final PackageVerificationState state = mPendingVerification.get(verificationId); 1533 if (state == null) { 1534 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1535 break; 1536 } 1537 1538 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1539 1540 state.setVerifierResponse(response.callerUid, response.code); 1541 1542 if (state.isVerificationComplete()) { 1543 mPendingVerification.remove(verificationId); 1544 1545 final InstallArgs args = state.getInstallArgs(); 1546 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1547 1548 int ret; 1549 if (state.isInstallAllowed()) { 1550 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1551 broadcastPackageVerified(verificationId, originUri, 1552 response.code, state.getInstallArgs().getUser()); 1553 try { 1554 ret = args.copyApk(mContainerService, true); 1555 } catch (RemoteException e) { 1556 Slog.e(TAG, "Could not contact the ContainerService"); 1557 } 1558 } else { 1559 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1560 } 1561 1562 processPendingInstall(args, ret); 1563 1564 mHandler.sendEmptyMessage(MCS_UNBIND); 1565 } 1566 1567 break; 1568 } 1569 case START_INTENT_FILTER_VERIFICATIONS: { 1570 IFVerificationParams params = (IFVerificationParams) msg.obj; 1571 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1572 params.replacing, params.pkg); 1573 break; 1574 } 1575 case INTENT_FILTER_VERIFIED: { 1576 final int verificationId = msg.arg1; 1577 1578 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1579 verificationId); 1580 if (state == null) { 1581 Slog.w(TAG, "Invalid IntentFilter verification token " 1582 + verificationId + " received"); 1583 break; 1584 } 1585 1586 final int userId = state.getUserId(); 1587 1588 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1589 "Processing IntentFilter verification with token:" 1590 + verificationId + " and userId:" + userId); 1591 1592 final IntentFilterVerificationResponse response = 1593 (IntentFilterVerificationResponse) msg.obj; 1594 1595 state.setVerifierResponse(response.callerUid, response.code); 1596 1597 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1598 "IntentFilter verification with token:" + verificationId 1599 + " and userId:" + userId 1600 + " is settings verifier response with response code:" 1601 + response.code); 1602 1603 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1604 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1605 + response.getFailedDomainsString()); 1606 } 1607 1608 if (state.isVerificationComplete()) { 1609 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1610 } else { 1611 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1612 "IntentFilter verification with token:" + verificationId 1613 + " was not said to be complete"); 1614 } 1615 1616 break; 1617 } 1618 } 1619 } 1620 } 1621 1622 private StorageEventListener mStorageListener = new StorageEventListener() { 1623 @Override 1624 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1625 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1626 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1627 final String volumeUuid = vol.getFsUuid(); 1628 1629 // Clean up any users or apps that were removed or recreated 1630 // while this volume was missing 1631 reconcileUsers(volumeUuid); 1632 reconcileApps(volumeUuid); 1633 1634 // Clean up any install sessions that expired or were 1635 // cancelled while this volume was missing 1636 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1637 1638 loadPrivatePackages(vol); 1639 1640 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1641 unloadPrivatePackages(vol); 1642 } 1643 } 1644 1645 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1646 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1647 updateExternalMediaStatus(true, false); 1648 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1649 updateExternalMediaStatus(false, false); 1650 } 1651 } 1652 } 1653 1654 @Override 1655 public void onVolumeForgotten(String fsUuid) { 1656 if (TextUtils.isEmpty(fsUuid)) { 1657 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1658 return; 1659 } 1660 1661 // Remove any apps installed on the forgotten volume 1662 synchronized (mPackages) { 1663 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1664 for (PackageSetting ps : packages) { 1665 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1666 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1667 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1668 } 1669 1670 mSettings.onVolumeForgotten(fsUuid); 1671 mSettings.writeLPr(); 1672 } 1673 } 1674 }; 1675 1676 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1677 String[] grantedPermissions) { 1678 if (userId >= UserHandle.USER_OWNER) { 1679 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1680 } else if (userId == UserHandle.USER_ALL) { 1681 final int[] userIds; 1682 synchronized (mPackages) { 1683 userIds = UserManagerService.getInstance().getUserIds(); 1684 } 1685 for (int someUserId : userIds) { 1686 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1687 } 1688 } 1689 1690 // We could have touched GID membership, so flush out packages.list 1691 synchronized (mPackages) { 1692 mSettings.writePackageListLPr(); 1693 } 1694 } 1695 1696 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1697 String[] grantedPermissions) { 1698 SettingBase sb = (SettingBase) pkg.mExtras; 1699 if (sb == null) { 1700 return; 1701 } 1702 1703 PermissionsState permissionsState = sb.getPermissionsState(); 1704 1705 for (String permission : pkg.requestedPermissions) { 1706 BasePermission bp = mSettings.mPermissions.get(permission); 1707 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1708 || ArrayUtils.contains(grantedPermissions, permission))) { 1709 permissionsState.grantRuntimePermission(bp, userId); 1710 } 1711 } 1712 } 1713 1714 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1715 Bundle extras = null; 1716 switch (res.returnCode) { 1717 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1718 extras = new Bundle(); 1719 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1720 res.origPermission); 1721 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1722 res.origPackage); 1723 break; 1724 } 1725 case PackageManager.INSTALL_SUCCEEDED: { 1726 extras = new Bundle(); 1727 extras.putBoolean(Intent.EXTRA_REPLACING, 1728 res.removedInfo != null && res.removedInfo.removedPackage != null); 1729 break; 1730 } 1731 } 1732 return extras; 1733 } 1734 1735 void scheduleWriteSettingsLocked() { 1736 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1737 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1738 } 1739 } 1740 1741 void scheduleWritePackageRestrictionsLocked(int userId) { 1742 if (!sUserManager.exists(userId)) return; 1743 mDirtyUsers.add(userId); 1744 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1745 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1746 } 1747 } 1748 1749 public static PackageManagerService main(Context context, Installer installer, 1750 boolean factoryTest, boolean onlyCore) { 1751 PackageManagerService m = new PackageManagerService(context, installer, 1752 factoryTest, onlyCore); 1753 ServiceManager.addService("package", m); 1754 return m; 1755 } 1756 1757 static String[] splitString(String str, char sep) { 1758 int count = 1; 1759 int i = 0; 1760 while ((i=str.indexOf(sep, i)) >= 0) { 1761 count++; 1762 i++; 1763 } 1764 1765 String[] res = new String[count]; 1766 i=0; 1767 count = 0; 1768 int lastI=0; 1769 while ((i=str.indexOf(sep, i)) >= 0) { 1770 res[count] = str.substring(lastI, i); 1771 count++; 1772 i++; 1773 lastI = i; 1774 } 1775 res[count] = str.substring(lastI, str.length()); 1776 return res; 1777 } 1778 1779 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1780 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1781 Context.DISPLAY_SERVICE); 1782 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1783 } 1784 1785 public PackageManagerService(Context context, Installer installer, 1786 boolean factoryTest, boolean onlyCore) { 1787 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1788 SystemClock.uptimeMillis()); 1789 1790 if (mSdkVersion <= 0) { 1791 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1792 } 1793 1794 mContext = context; 1795 mFactoryTest = factoryTest; 1796 mOnlyCore = onlyCore; 1797 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1798 mMetrics = new DisplayMetrics(); 1799 mSettings = new Settings(mPackages); 1800 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1801 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1802 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1803 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1804 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1805 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1806 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1807 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1808 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1809 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1810 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1811 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1812 1813 // TODO: add a property to control this? 1814 long dexOptLRUThresholdInMinutes; 1815 if (mLazyDexOpt) { 1816 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1817 } else { 1818 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1819 } 1820 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1821 1822 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1823 if (separateProcesses != null && separateProcesses.length() > 0) { 1824 if ("*".equals(separateProcesses)) { 1825 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1826 mSeparateProcesses = null; 1827 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1828 } else { 1829 mDefParseFlags = 0; 1830 mSeparateProcesses = separateProcesses.split(","); 1831 Slog.w(TAG, "Running with debug.separate_processes: " 1832 + separateProcesses); 1833 } 1834 } else { 1835 mDefParseFlags = 0; 1836 mSeparateProcesses = null; 1837 } 1838 1839 mInstaller = installer; 1840 mPackageDexOptimizer = new PackageDexOptimizer(this); 1841 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1842 1843 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1844 FgThread.get().getLooper()); 1845 1846 getDefaultDisplayMetrics(context, mMetrics); 1847 1848 SystemConfig systemConfig = SystemConfig.getInstance(); 1849 mGlobalGids = systemConfig.getGlobalGids(); 1850 mSystemPermissions = systemConfig.getSystemPermissions(); 1851 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1852 1853 synchronized (mInstallLock) { 1854 // writer 1855 synchronized (mPackages) { 1856 mHandlerThread = new ServiceThread(TAG, 1857 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1858 mHandlerThread.start(); 1859 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1860 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1861 1862 File dataDir = Environment.getDataDirectory(); 1863 mAppDataDir = new File(dataDir, "data"); 1864 mAppInstallDir = new File(dataDir, "app"); 1865 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1866 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1867 mUserAppDataDir = new File(dataDir, "user"); 1868 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1869 1870 sUserManager = new UserManagerService(context, this, 1871 mInstallLock, mPackages); 1872 1873 // Propagate permission configuration in to package manager. 1874 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1875 = systemConfig.getPermissions(); 1876 for (int i=0; i<permConfig.size(); i++) { 1877 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1878 BasePermission bp = mSettings.mPermissions.get(perm.name); 1879 if (bp == null) { 1880 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1881 mSettings.mPermissions.put(perm.name, bp); 1882 } 1883 if (perm.gids != null) { 1884 bp.setGids(perm.gids, perm.perUser); 1885 } 1886 } 1887 1888 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1889 for (int i=0; i<libConfig.size(); i++) { 1890 mSharedLibraries.put(libConfig.keyAt(i), 1891 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1892 } 1893 1894 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1895 1896 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1897 mSdkVersion, mOnlyCore); 1898 1899 String customResolverActivity = Resources.getSystem().getString( 1900 R.string.config_customResolverActivity); 1901 if (TextUtils.isEmpty(customResolverActivity)) { 1902 customResolverActivity = null; 1903 } else { 1904 mCustomResolverComponentName = ComponentName.unflattenFromString( 1905 customResolverActivity); 1906 } 1907 1908 long startTime = SystemClock.uptimeMillis(); 1909 1910 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1911 startTime); 1912 1913 // Set flag to monitor and not change apk file paths when 1914 // scanning install directories. 1915 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1916 1917 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1918 1919 /** 1920 * Add everything in the in the boot class path to the 1921 * list of process files because dexopt will have been run 1922 * if necessary during zygote startup. 1923 */ 1924 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1925 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1926 1927 if (bootClassPath != null) { 1928 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1929 for (String element : bootClassPathElements) { 1930 alreadyDexOpted.add(element); 1931 } 1932 } else { 1933 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1934 } 1935 1936 if (systemServerClassPath != null) { 1937 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1938 for (String element : systemServerClassPathElements) { 1939 alreadyDexOpted.add(element); 1940 } 1941 } else { 1942 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1943 } 1944 1945 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1946 final String[] dexCodeInstructionSets = 1947 getDexCodeInstructionSets( 1948 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1949 1950 /** 1951 * Ensure all external libraries have had dexopt run on them. 1952 */ 1953 if (mSharedLibraries.size() > 0) { 1954 // NOTE: For now, we're compiling these system "shared libraries" 1955 // (and framework jars) into all available architectures. It's possible 1956 // to compile them only when we come across an app that uses them (there's 1957 // already logic for that in scanPackageLI) but that adds some complexity. 1958 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1959 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1960 final String lib = libEntry.path; 1961 if (lib == null) { 1962 continue; 1963 } 1964 1965 try { 1966 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1967 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1968 alreadyDexOpted.add(lib); 1969 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1970 } 1971 } catch (FileNotFoundException e) { 1972 Slog.w(TAG, "Library not found: " + lib); 1973 } catch (IOException e) { 1974 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1975 + e.getMessage()); 1976 } 1977 } 1978 } 1979 } 1980 1981 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1982 1983 // Gross hack for now: we know this file doesn't contain any 1984 // code, so don't dexopt it to avoid the resulting log spew. 1985 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1986 1987 // Gross hack for now: we know this file is only part of 1988 // the boot class path for art, so don't dexopt it to 1989 // avoid the resulting log spew. 1990 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1991 1992 /** 1993 * There are a number of commands implemented in Java, which 1994 * we currently need to do the dexopt on so that they can be 1995 * run from a non-root shell. 1996 */ 1997 String[] frameworkFiles = frameworkDir.list(); 1998 if (frameworkFiles != null) { 1999 // TODO: We could compile these only for the most preferred ABI. We should 2000 // first double check that the dex files for these commands are not referenced 2001 // by other system apps. 2002 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2003 for (int i=0; i<frameworkFiles.length; i++) { 2004 File libPath = new File(frameworkDir, frameworkFiles[i]); 2005 String path = libPath.getPath(); 2006 // Skip the file if we already did it. 2007 if (alreadyDexOpted.contains(path)) { 2008 continue; 2009 } 2010 // Skip the file if it is not a type we want to dexopt. 2011 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2012 continue; 2013 } 2014 try { 2015 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2016 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2017 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2018 } 2019 } catch (FileNotFoundException e) { 2020 Slog.w(TAG, "Jar not found: " + path); 2021 } catch (IOException e) { 2022 Slog.w(TAG, "Exception reading jar: " + path, e); 2023 } 2024 } 2025 } 2026 } 2027 2028 // Collect vendor overlay packages. 2029 // (Do this before scanning any apps.) 2030 // For security and version matching reason, only consider 2031 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2032 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2033 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2034 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2035 2036 // Find base frameworks (resource packages without code). 2037 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2038 | PackageParser.PARSE_IS_SYSTEM_DIR 2039 | PackageParser.PARSE_IS_PRIVILEGED, 2040 scanFlags | SCAN_NO_DEX, 0); 2041 2042 // Collected privileged system packages. 2043 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2044 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2045 | PackageParser.PARSE_IS_SYSTEM_DIR 2046 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2047 2048 // Collect ordinary system packages. 2049 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2050 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2051 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2052 2053 // Collect all vendor packages. 2054 File vendorAppDir = new File("/vendor/app"); 2055 try { 2056 vendorAppDir = vendorAppDir.getCanonicalFile(); 2057 } catch (IOException e) { 2058 // failed to look up canonical path, continue with original one 2059 } 2060 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2061 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2062 2063 // Collect all OEM packages. 2064 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2065 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2066 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2067 2068 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2069 mInstaller.moveFiles(); 2070 2071 // Prune any system packages that no longer exist. 2072 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2073 if (!mOnlyCore) { 2074 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2075 while (psit.hasNext()) { 2076 PackageSetting ps = psit.next(); 2077 2078 /* 2079 * If this is not a system app, it can't be a 2080 * disable system app. 2081 */ 2082 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2083 continue; 2084 } 2085 2086 /* 2087 * If the package is scanned, it's not erased. 2088 */ 2089 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2090 if (scannedPkg != null) { 2091 /* 2092 * If the system app is both scanned and in the 2093 * disabled packages list, then it must have been 2094 * added via OTA. Remove it from the currently 2095 * scanned package so the previously user-installed 2096 * application can be scanned. 2097 */ 2098 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2099 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2100 + ps.name + "; removing system app. Last known codePath=" 2101 + ps.codePathString + ", installStatus=" + ps.installStatus 2102 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2103 + scannedPkg.mVersionCode); 2104 removePackageLI(ps, true); 2105 mExpectingBetter.put(ps.name, ps.codePath); 2106 } 2107 2108 continue; 2109 } 2110 2111 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2112 psit.remove(); 2113 logCriticalInfo(Log.WARN, "System package " + ps.name 2114 + " no longer exists; wiping its data"); 2115 removeDataDirsLI(null, ps.name); 2116 } else { 2117 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2118 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2119 possiblyDeletedUpdatedSystemApps.add(ps.name); 2120 } 2121 } 2122 } 2123 } 2124 2125 //look for any incomplete package installations 2126 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2127 //clean up list 2128 for(int i = 0; i < deletePkgsList.size(); i++) { 2129 //clean up here 2130 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2131 } 2132 //delete tmp files 2133 deleteTempPackageFiles(); 2134 2135 // Remove any shared userIDs that have no associated packages 2136 mSettings.pruneSharedUsersLPw(); 2137 2138 if (!mOnlyCore) { 2139 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2140 SystemClock.uptimeMillis()); 2141 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2142 2143 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2144 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2145 2146 /** 2147 * Remove disable package settings for any updated system 2148 * apps that were removed via an OTA. If they're not a 2149 * previously-updated app, remove them completely. 2150 * Otherwise, just revoke their system-level permissions. 2151 */ 2152 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2153 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2154 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2155 2156 String msg; 2157 if (deletedPkg == null) { 2158 msg = "Updated system package " + deletedAppName 2159 + " no longer exists; wiping its data"; 2160 removeDataDirsLI(null, deletedAppName); 2161 } else { 2162 msg = "Updated system app + " + deletedAppName 2163 + " no longer present; removing system privileges for " 2164 + deletedAppName; 2165 2166 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2167 2168 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2169 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2170 } 2171 logCriticalInfo(Log.WARN, msg); 2172 } 2173 2174 /** 2175 * Make sure all system apps that we expected to appear on 2176 * the userdata partition actually showed up. If they never 2177 * appeared, crawl back and revive the system version. 2178 */ 2179 for (int i = 0; i < mExpectingBetter.size(); i++) { 2180 final String packageName = mExpectingBetter.keyAt(i); 2181 if (!mPackages.containsKey(packageName)) { 2182 final File scanFile = mExpectingBetter.valueAt(i); 2183 2184 logCriticalInfo(Log.WARN, "Expected better " + packageName 2185 + " but never showed up; reverting to system"); 2186 2187 final int reparseFlags; 2188 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2189 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2190 | PackageParser.PARSE_IS_SYSTEM_DIR 2191 | PackageParser.PARSE_IS_PRIVILEGED; 2192 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2193 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2194 | PackageParser.PARSE_IS_SYSTEM_DIR; 2195 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2196 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2197 | PackageParser.PARSE_IS_SYSTEM_DIR; 2198 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2199 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2200 | PackageParser.PARSE_IS_SYSTEM_DIR; 2201 } else { 2202 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2203 continue; 2204 } 2205 2206 mSettings.enableSystemPackageLPw(packageName); 2207 2208 try { 2209 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2210 } catch (PackageManagerException e) { 2211 Slog.e(TAG, "Failed to parse original system package: " 2212 + e.getMessage()); 2213 } 2214 } 2215 } 2216 } 2217 mExpectingBetter.clear(); 2218 2219 // Now that we know all of the shared libraries, update all clients to have 2220 // the correct library paths. 2221 updateAllSharedLibrariesLPw(); 2222 2223 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2224 // NOTE: We ignore potential failures here during a system scan (like 2225 // the rest of the commands above) because there's precious little we 2226 // can do about it. A settings error is reported, though. 2227 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2228 false /* force dexopt */, false /* defer dexopt */); 2229 } 2230 2231 // Now that we know all the packages we are keeping, 2232 // read and update their last usage times. 2233 mPackageUsage.readLP(); 2234 2235 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2236 SystemClock.uptimeMillis()); 2237 Slog.i(TAG, "Time to scan packages: " 2238 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2239 + " seconds"); 2240 2241 // If the platform SDK has changed since the last time we booted, 2242 // we need to re-grant app permission to catch any new ones that 2243 // appear. This is really a hack, and means that apps can in some 2244 // cases get permissions that the user didn't initially explicitly 2245 // allow... it would be nice to have some better way to handle 2246 // this situation. 2247 final VersionInfo ver = mSettings.getInternalVersion(); 2248 2249 int updateFlags = UPDATE_PERMISSIONS_ALL; 2250 if (ver.sdkVersion != mSdkVersion) { 2251 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2252 + mSdkVersion + "; regranting permissions for internal storage"); 2253 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2254 } 2255 updatePermissionsLPw(null, null, updateFlags); 2256 ver.sdkVersion = mSdkVersion; 2257 2258 // If this is the first boot, and it is a normal boot, then 2259 // we need to initialize the default preferred apps. 2260 if (!mRestoredSettings && !onlyCore) { 2261 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2262 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2263 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2264 } 2265 2266 // If this is first boot after an OTA, and a normal boot, then 2267 // we need to clear code cache directories. 2268 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2269 if (mIsUpgrade && !onlyCore) { 2270 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2271 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2272 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2273 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2274 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2275 } 2276 } 2277 ver.fingerprint = Build.FINGERPRINT; 2278 } 2279 2280 checkDefaultBrowser(); 2281 2282 // All the changes are done during package scanning. 2283 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2284 2285 // can downgrade to reader 2286 mSettings.writeLPr(); 2287 2288 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2289 SystemClock.uptimeMillis()); 2290 2291 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2292 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2293 2294 mInstallerService = new PackageInstallerService(context, this); 2295 2296 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2297 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2298 mIntentFilterVerifierComponent); 2299 2300 } // synchronized (mPackages) 2301 } // synchronized (mInstallLock) 2302 2303 // Now after opening every single application zip, make sure they 2304 // are all flushed. Not really needed, but keeps things nice and 2305 // tidy. 2306 Runtime.getRuntime().gc(); 2307 2308 // Expose private service for system components to use. 2309 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2310 } 2311 2312 @Override 2313 public boolean isFirstBoot() { 2314 return !mRestoredSettings; 2315 } 2316 2317 @Override 2318 public boolean isOnlyCoreApps() { 2319 return mOnlyCore; 2320 } 2321 2322 @Override 2323 public boolean isUpgrade() { 2324 return mIsUpgrade; 2325 } 2326 2327 private String getRequiredVerifierLPr() { 2328 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2329 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2330 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2331 2332 String requiredVerifier = null; 2333 2334 final int N = receivers.size(); 2335 for (int i = 0; i < N; i++) { 2336 final ResolveInfo info = receivers.get(i); 2337 2338 if (info.activityInfo == null) { 2339 continue; 2340 } 2341 2342 final String packageName = info.activityInfo.packageName; 2343 2344 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2345 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2346 continue; 2347 } 2348 2349 if (requiredVerifier != null) { 2350 throw new RuntimeException("There can be only one required verifier"); 2351 } 2352 2353 requiredVerifier = packageName; 2354 } 2355 2356 return requiredVerifier; 2357 } 2358 2359 private String getRequiredInstallerLPr() { 2360 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2361 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2362 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2363 2364 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2365 PACKAGE_MIME_TYPE, 0, 0); 2366 2367 String requiredInstaller = null; 2368 2369 final int N = installers.size(); 2370 for (int i = 0; i < N; i++) { 2371 final ResolveInfo info = installers.get(i); 2372 final String packageName = info.activityInfo.packageName; 2373 2374 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2375 continue; 2376 } 2377 2378 if (requiredInstaller != null) { 2379 throw new RuntimeException("There must be one required installer"); 2380 } 2381 2382 requiredInstaller = packageName; 2383 } 2384 2385 if (requiredInstaller == null) { 2386 throw new RuntimeException("There must be one required installer"); 2387 } 2388 2389 return requiredInstaller; 2390 } 2391 2392 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2393 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2394 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2395 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2396 2397 ComponentName verifierComponentName = null; 2398 2399 int priority = -1000; 2400 final int N = receivers.size(); 2401 for (int i = 0; i < N; i++) { 2402 final ResolveInfo info = receivers.get(i); 2403 2404 if (info.activityInfo == null) { 2405 continue; 2406 } 2407 2408 final String packageName = info.activityInfo.packageName; 2409 2410 final PackageSetting ps = mSettings.mPackages.get(packageName); 2411 if (ps == null) { 2412 continue; 2413 } 2414 2415 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2416 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2417 continue; 2418 } 2419 2420 // Select the IntentFilterVerifier with the highest priority 2421 if (priority < info.priority) { 2422 priority = info.priority; 2423 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2424 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2425 + verifierComponentName + " with priority: " + info.priority); 2426 } 2427 } 2428 2429 return verifierComponentName; 2430 } 2431 2432 private void primeDomainVerificationsLPw(int userId) { 2433 if (DEBUG_DOMAIN_VERIFICATION) { 2434 Slog.d(TAG, "Priming domain verifications in user " + userId); 2435 } 2436 2437 SystemConfig systemConfig = SystemConfig.getInstance(); 2438 ArraySet<String> packages = systemConfig.getLinkedApps(); 2439 ArraySet<String> domains = new ArraySet<String>(); 2440 2441 for (String packageName : packages) { 2442 PackageParser.Package pkg = mPackages.get(packageName); 2443 if (pkg != null) { 2444 if (!pkg.isSystemApp()) { 2445 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2446 continue; 2447 } 2448 2449 domains.clear(); 2450 for (PackageParser.Activity a : pkg.activities) { 2451 for (ActivityIntentInfo filter : a.intents) { 2452 if (hasValidDomains(filter)) { 2453 domains.addAll(filter.getHostsList()); 2454 } 2455 } 2456 } 2457 2458 if (domains.size() > 0) { 2459 if (DEBUG_DOMAIN_VERIFICATION) { 2460 Slog.v(TAG, " + " + packageName); 2461 } 2462 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2463 // state w.r.t. the formal app-linkage "no verification attempted" state; 2464 // and then 'always' in the per-user state actually used for intent resolution. 2465 final IntentFilterVerificationInfo ivi; 2466 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2467 new ArrayList<String>(domains)); 2468 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2469 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2470 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2471 } else { 2472 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2473 + "' does not handle web links"); 2474 } 2475 } else { 2476 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2477 } 2478 } 2479 2480 scheduleWritePackageRestrictionsLocked(userId); 2481 scheduleWriteSettingsLocked(); 2482 } 2483 2484 private void applyFactoryDefaultBrowserLPw(int userId) { 2485 // The default browser app's package name is stored in a string resource, 2486 // with a product-specific overlay used for vendor customization. 2487 String browserPkg = mContext.getResources().getString( 2488 com.android.internal.R.string.default_browser); 2489 if (!TextUtils.isEmpty(browserPkg)) { 2490 // non-empty string => required to be a known package 2491 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2492 if (ps == null) { 2493 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2494 browserPkg = null; 2495 } else { 2496 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2497 } 2498 } 2499 2500 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2501 // default. If there's more than one, just leave everything alone. 2502 if (browserPkg == null) { 2503 calculateDefaultBrowserLPw(userId); 2504 } 2505 } 2506 2507 private void calculateDefaultBrowserLPw(int userId) { 2508 List<String> allBrowsers = resolveAllBrowserApps(userId); 2509 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2510 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2511 } 2512 2513 private List<String> resolveAllBrowserApps(int userId) { 2514 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2515 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2516 PackageManager.MATCH_ALL, userId); 2517 2518 final int count = list.size(); 2519 List<String> result = new ArrayList<String>(count); 2520 for (int i=0; i<count; i++) { 2521 ResolveInfo info = list.get(i); 2522 if (info.activityInfo == null 2523 || !info.handleAllWebDataURI 2524 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2525 || result.contains(info.activityInfo.packageName)) { 2526 continue; 2527 } 2528 result.add(info.activityInfo.packageName); 2529 } 2530 2531 return result; 2532 } 2533 2534 private boolean packageIsBrowser(String packageName, int userId) { 2535 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2536 PackageManager.MATCH_ALL, userId); 2537 final int N = list.size(); 2538 for (int i = 0; i < N; i++) { 2539 ResolveInfo info = list.get(i); 2540 if (packageName.equals(info.activityInfo.packageName)) { 2541 return true; 2542 } 2543 } 2544 return false; 2545 } 2546 2547 private void checkDefaultBrowser() { 2548 final int myUserId = UserHandle.myUserId(); 2549 final String packageName = getDefaultBrowserPackageName(myUserId); 2550 if (packageName != null) { 2551 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2552 if (info == null) { 2553 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2554 synchronized (mPackages) { 2555 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2556 } 2557 } 2558 } 2559 } 2560 2561 @Override 2562 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2563 throws RemoteException { 2564 try { 2565 return super.onTransact(code, data, reply, flags); 2566 } catch (RuntimeException e) { 2567 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2568 Slog.wtf(TAG, "Package Manager Crash", e); 2569 } 2570 throw e; 2571 } 2572 } 2573 2574 void cleanupInstallFailedPackage(PackageSetting ps) { 2575 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2576 2577 removeDataDirsLI(ps.volumeUuid, ps.name); 2578 if (ps.codePath != null) { 2579 if (ps.codePath.isDirectory()) { 2580 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2581 } else { 2582 ps.codePath.delete(); 2583 } 2584 } 2585 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2586 if (ps.resourcePath.isDirectory()) { 2587 FileUtils.deleteContents(ps.resourcePath); 2588 } 2589 ps.resourcePath.delete(); 2590 } 2591 mSettings.removePackageLPw(ps.name); 2592 } 2593 2594 static int[] appendInts(int[] cur, int[] add) { 2595 if (add == null) return cur; 2596 if (cur == null) return add; 2597 final int N = add.length; 2598 for (int i=0; i<N; i++) { 2599 cur = appendInt(cur, add[i]); 2600 } 2601 return cur; 2602 } 2603 2604 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2605 if (!sUserManager.exists(userId)) return null; 2606 final PackageSetting ps = (PackageSetting) p.mExtras; 2607 if (ps == null) { 2608 return null; 2609 } 2610 2611 final PermissionsState permissionsState = ps.getPermissionsState(); 2612 2613 final int[] gids = permissionsState.computeGids(userId); 2614 final Set<String> permissions = permissionsState.getPermissions(userId); 2615 final PackageUserState state = ps.readUserState(userId); 2616 2617 return PackageParser.generatePackageInfo(p, gids, flags, 2618 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2619 } 2620 2621 @Override 2622 public boolean isPackageFrozen(String packageName) { 2623 synchronized (mPackages) { 2624 final PackageSetting ps = mSettings.mPackages.get(packageName); 2625 if (ps != null) { 2626 return ps.frozen; 2627 } 2628 } 2629 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2630 return true; 2631 } 2632 2633 @Override 2634 public boolean isPackageAvailable(String packageName, int userId) { 2635 if (!sUserManager.exists(userId)) return false; 2636 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2637 synchronized (mPackages) { 2638 PackageParser.Package p = mPackages.get(packageName); 2639 if (p != null) { 2640 final PackageSetting ps = (PackageSetting) p.mExtras; 2641 if (ps != null) { 2642 final PackageUserState state = ps.readUserState(userId); 2643 if (state != null) { 2644 return PackageParser.isAvailable(state); 2645 } 2646 } 2647 } 2648 } 2649 return false; 2650 } 2651 2652 @Override 2653 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2654 if (!sUserManager.exists(userId)) return null; 2655 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2656 // reader 2657 synchronized (mPackages) { 2658 PackageParser.Package p = mPackages.get(packageName); 2659 if (DEBUG_PACKAGE_INFO) 2660 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2661 if (p != null) { 2662 return generatePackageInfo(p, flags, userId); 2663 } 2664 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2665 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2666 } 2667 } 2668 return null; 2669 } 2670 2671 @Override 2672 public String[] currentToCanonicalPackageNames(String[] names) { 2673 String[] out = new String[names.length]; 2674 // reader 2675 synchronized (mPackages) { 2676 for (int i=names.length-1; i>=0; i--) { 2677 PackageSetting ps = mSettings.mPackages.get(names[i]); 2678 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2679 } 2680 } 2681 return out; 2682 } 2683 2684 @Override 2685 public String[] canonicalToCurrentPackageNames(String[] names) { 2686 String[] out = new String[names.length]; 2687 // reader 2688 synchronized (mPackages) { 2689 for (int i=names.length-1; i>=0; i--) { 2690 String cur = mSettings.mRenamedPackages.get(names[i]); 2691 out[i] = cur != null ? cur : names[i]; 2692 } 2693 } 2694 return out; 2695 } 2696 2697 @Override 2698 public int getPackageUid(String packageName, int userId) { 2699 if (!sUserManager.exists(userId)) return -1; 2700 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2701 2702 // reader 2703 synchronized (mPackages) { 2704 PackageParser.Package p = mPackages.get(packageName); 2705 if(p != null) { 2706 return UserHandle.getUid(userId, p.applicationInfo.uid); 2707 } 2708 PackageSetting ps = mSettings.mPackages.get(packageName); 2709 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2710 return -1; 2711 } 2712 p = ps.pkg; 2713 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2714 } 2715 } 2716 2717 @Override 2718 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2719 if (!sUserManager.exists(userId)) { 2720 return null; 2721 } 2722 2723 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2724 "getPackageGids"); 2725 2726 // reader 2727 synchronized (mPackages) { 2728 PackageParser.Package p = mPackages.get(packageName); 2729 if (DEBUG_PACKAGE_INFO) { 2730 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2731 } 2732 if (p != null) { 2733 PackageSetting ps = (PackageSetting) p.mExtras; 2734 return ps.getPermissionsState().computeGids(userId); 2735 } 2736 } 2737 2738 return null; 2739 } 2740 2741 static PermissionInfo generatePermissionInfo( 2742 BasePermission bp, int flags) { 2743 if (bp.perm != null) { 2744 return PackageParser.generatePermissionInfo(bp.perm, flags); 2745 } 2746 PermissionInfo pi = new PermissionInfo(); 2747 pi.name = bp.name; 2748 pi.packageName = bp.sourcePackage; 2749 pi.nonLocalizedLabel = bp.name; 2750 pi.protectionLevel = bp.protectionLevel; 2751 return pi; 2752 } 2753 2754 @Override 2755 public PermissionInfo getPermissionInfo(String name, int flags) { 2756 // reader 2757 synchronized (mPackages) { 2758 final BasePermission p = mSettings.mPermissions.get(name); 2759 if (p != null) { 2760 return generatePermissionInfo(p, flags); 2761 } 2762 return null; 2763 } 2764 } 2765 2766 @Override 2767 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2768 // reader 2769 synchronized (mPackages) { 2770 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2771 for (BasePermission p : mSettings.mPermissions.values()) { 2772 if (group == null) { 2773 if (p.perm == null || p.perm.info.group == null) { 2774 out.add(generatePermissionInfo(p, flags)); 2775 } 2776 } else { 2777 if (p.perm != null && group.equals(p.perm.info.group)) { 2778 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2779 } 2780 } 2781 } 2782 2783 if (out.size() > 0) { 2784 return out; 2785 } 2786 return mPermissionGroups.containsKey(group) ? out : null; 2787 } 2788 } 2789 2790 @Override 2791 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2792 // reader 2793 synchronized (mPackages) { 2794 return PackageParser.generatePermissionGroupInfo( 2795 mPermissionGroups.get(name), flags); 2796 } 2797 } 2798 2799 @Override 2800 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2801 // reader 2802 synchronized (mPackages) { 2803 final int N = mPermissionGroups.size(); 2804 ArrayList<PermissionGroupInfo> out 2805 = new ArrayList<PermissionGroupInfo>(N); 2806 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2807 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2808 } 2809 return out; 2810 } 2811 } 2812 2813 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2814 int userId) { 2815 if (!sUserManager.exists(userId)) return null; 2816 PackageSetting ps = mSettings.mPackages.get(packageName); 2817 if (ps != null) { 2818 if (ps.pkg == null) { 2819 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2820 flags, userId); 2821 if (pInfo != null) { 2822 return pInfo.applicationInfo; 2823 } 2824 return null; 2825 } 2826 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2827 ps.readUserState(userId), userId); 2828 } 2829 return null; 2830 } 2831 2832 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2833 int userId) { 2834 if (!sUserManager.exists(userId)) return null; 2835 PackageSetting ps = mSettings.mPackages.get(packageName); 2836 if (ps != null) { 2837 PackageParser.Package pkg = ps.pkg; 2838 if (pkg == null) { 2839 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2840 return null; 2841 } 2842 // Only data remains, so we aren't worried about code paths 2843 pkg = new PackageParser.Package(packageName); 2844 pkg.applicationInfo.packageName = packageName; 2845 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2846 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2847 pkg.applicationInfo.dataDir = Environment 2848 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2849 .getAbsolutePath(); 2850 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2851 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2852 } 2853 return generatePackageInfo(pkg, flags, userId); 2854 } 2855 return null; 2856 } 2857 2858 @Override 2859 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2860 if (!sUserManager.exists(userId)) return null; 2861 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2862 // writer 2863 synchronized (mPackages) { 2864 PackageParser.Package p = mPackages.get(packageName); 2865 if (DEBUG_PACKAGE_INFO) Log.v( 2866 TAG, "getApplicationInfo " + packageName 2867 + ": " + p); 2868 if (p != null) { 2869 PackageSetting ps = mSettings.mPackages.get(packageName); 2870 if (ps == null) return null; 2871 // Note: isEnabledLP() does not apply here - always return info 2872 return PackageParser.generateApplicationInfo( 2873 p, flags, ps.readUserState(userId), userId); 2874 } 2875 if ("android".equals(packageName)||"system".equals(packageName)) { 2876 return mAndroidApplication; 2877 } 2878 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2879 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2880 } 2881 } 2882 return null; 2883 } 2884 2885 @Override 2886 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2887 final IPackageDataObserver observer) { 2888 mContext.enforceCallingOrSelfPermission( 2889 android.Manifest.permission.CLEAR_APP_CACHE, null); 2890 // Queue up an async operation since clearing cache may take a little while. 2891 mHandler.post(new Runnable() { 2892 public void run() { 2893 mHandler.removeCallbacks(this); 2894 int retCode = -1; 2895 synchronized (mInstallLock) { 2896 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2897 if (retCode < 0) { 2898 Slog.w(TAG, "Couldn't clear application caches"); 2899 } 2900 } 2901 if (observer != null) { 2902 try { 2903 observer.onRemoveCompleted(null, (retCode >= 0)); 2904 } catch (RemoteException e) { 2905 Slog.w(TAG, "RemoveException when invoking call back"); 2906 } 2907 } 2908 } 2909 }); 2910 } 2911 2912 @Override 2913 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2914 final IntentSender pi) { 2915 mContext.enforceCallingOrSelfPermission( 2916 android.Manifest.permission.CLEAR_APP_CACHE, null); 2917 // Queue up an async operation since clearing cache may take a little while. 2918 mHandler.post(new Runnable() { 2919 public void run() { 2920 mHandler.removeCallbacks(this); 2921 int retCode = -1; 2922 synchronized (mInstallLock) { 2923 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2924 if (retCode < 0) { 2925 Slog.w(TAG, "Couldn't clear application caches"); 2926 } 2927 } 2928 if(pi != null) { 2929 try { 2930 // Callback via pending intent 2931 int code = (retCode >= 0) ? 1 : 0; 2932 pi.sendIntent(null, code, null, 2933 null, null); 2934 } catch (SendIntentException e1) { 2935 Slog.i(TAG, "Failed to send pending intent"); 2936 } 2937 } 2938 } 2939 }); 2940 } 2941 2942 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2943 synchronized (mInstallLock) { 2944 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2945 throw new IOException("Failed to free enough space"); 2946 } 2947 } 2948 } 2949 2950 @Override 2951 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2952 if (!sUserManager.exists(userId)) return null; 2953 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2954 synchronized (mPackages) { 2955 PackageParser.Activity a = mActivities.mActivities.get(component); 2956 2957 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2958 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2959 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2960 if (ps == null) return null; 2961 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2962 userId); 2963 } 2964 if (mResolveComponentName.equals(component)) { 2965 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2966 new PackageUserState(), userId); 2967 } 2968 } 2969 return null; 2970 } 2971 2972 @Override 2973 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2974 String resolvedType) { 2975 synchronized (mPackages) { 2976 if (component.equals(mResolveComponentName)) { 2977 // The resolver supports EVERYTHING! 2978 return true; 2979 } 2980 PackageParser.Activity a = mActivities.mActivities.get(component); 2981 if (a == null) { 2982 return false; 2983 } 2984 for (int i=0; i<a.intents.size(); i++) { 2985 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2986 intent.getData(), intent.getCategories(), TAG) >= 0) { 2987 return true; 2988 } 2989 } 2990 return false; 2991 } 2992 } 2993 2994 @Override 2995 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2996 if (!sUserManager.exists(userId)) return null; 2997 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2998 synchronized (mPackages) { 2999 PackageParser.Activity a = mReceivers.mActivities.get(component); 3000 if (DEBUG_PACKAGE_INFO) Log.v( 3001 TAG, "getReceiverInfo " + component + ": " + a); 3002 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3003 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3004 if (ps == null) return null; 3005 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3006 userId); 3007 } 3008 } 3009 return null; 3010 } 3011 3012 @Override 3013 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3014 if (!sUserManager.exists(userId)) return null; 3015 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3016 synchronized (mPackages) { 3017 PackageParser.Service s = mServices.mServices.get(component); 3018 if (DEBUG_PACKAGE_INFO) Log.v( 3019 TAG, "getServiceInfo " + component + ": " + s); 3020 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3021 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3022 if (ps == null) return null; 3023 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3024 userId); 3025 } 3026 } 3027 return null; 3028 } 3029 3030 @Override 3031 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3032 if (!sUserManager.exists(userId)) return null; 3033 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3034 synchronized (mPackages) { 3035 PackageParser.Provider p = mProviders.mProviders.get(component); 3036 if (DEBUG_PACKAGE_INFO) Log.v( 3037 TAG, "getProviderInfo " + component + ": " + p); 3038 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3039 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3040 if (ps == null) return null; 3041 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3042 userId); 3043 } 3044 } 3045 return null; 3046 } 3047 3048 @Override 3049 public String[] getSystemSharedLibraryNames() { 3050 Set<String> libSet; 3051 synchronized (mPackages) { 3052 libSet = mSharedLibraries.keySet(); 3053 int size = libSet.size(); 3054 if (size > 0) { 3055 String[] libs = new String[size]; 3056 libSet.toArray(libs); 3057 return libs; 3058 } 3059 } 3060 return null; 3061 } 3062 3063 /** 3064 * @hide 3065 */ 3066 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3067 synchronized (mPackages) { 3068 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3069 if (lib != null && lib.apk != null) { 3070 return mPackages.get(lib.apk); 3071 } 3072 } 3073 return null; 3074 } 3075 3076 @Override 3077 public FeatureInfo[] getSystemAvailableFeatures() { 3078 Collection<FeatureInfo> featSet; 3079 synchronized (mPackages) { 3080 featSet = mAvailableFeatures.values(); 3081 int size = featSet.size(); 3082 if (size > 0) { 3083 FeatureInfo[] features = new FeatureInfo[size+1]; 3084 featSet.toArray(features); 3085 FeatureInfo fi = new FeatureInfo(); 3086 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3087 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3088 features[size] = fi; 3089 return features; 3090 } 3091 } 3092 return null; 3093 } 3094 3095 @Override 3096 public boolean hasSystemFeature(String name) { 3097 synchronized (mPackages) { 3098 return mAvailableFeatures.containsKey(name); 3099 } 3100 } 3101 3102 private void checkValidCaller(int uid, int userId) { 3103 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3104 return; 3105 3106 throw new SecurityException("Caller uid=" + uid 3107 + " is not privileged to communicate with user=" + userId); 3108 } 3109 3110 @Override 3111 public int checkPermission(String permName, String pkgName, int userId) { 3112 if (!sUserManager.exists(userId)) { 3113 return PackageManager.PERMISSION_DENIED; 3114 } 3115 3116 synchronized (mPackages) { 3117 final PackageParser.Package p = mPackages.get(pkgName); 3118 if (p != null && p.mExtras != null) { 3119 final PackageSetting ps = (PackageSetting) p.mExtras; 3120 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3121 return PackageManager.PERMISSION_GRANTED; 3122 } 3123 } 3124 } 3125 3126 return PackageManager.PERMISSION_DENIED; 3127 } 3128 3129 @Override 3130 public int checkUidPermission(String permName, int uid) { 3131 final int userId = UserHandle.getUserId(uid); 3132 3133 if (!sUserManager.exists(userId)) { 3134 return PackageManager.PERMISSION_DENIED; 3135 } 3136 3137 synchronized (mPackages) { 3138 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3139 if (obj != null) { 3140 final SettingBase ps = (SettingBase) obj; 3141 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3142 return PackageManager.PERMISSION_GRANTED; 3143 } 3144 } else { 3145 ArraySet<String> perms = mSystemPermissions.get(uid); 3146 if (perms != null && perms.contains(permName)) { 3147 return PackageManager.PERMISSION_GRANTED; 3148 } 3149 } 3150 } 3151 3152 return PackageManager.PERMISSION_DENIED; 3153 } 3154 3155 @Override 3156 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3157 if (UserHandle.getCallingUserId() != userId) { 3158 mContext.enforceCallingPermission( 3159 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3160 "isPermissionRevokedByPolicy for user " + userId); 3161 } 3162 3163 if (checkPermission(permission, packageName, userId) 3164 == PackageManager.PERMISSION_GRANTED) { 3165 return false; 3166 } 3167 3168 final long identity = Binder.clearCallingIdentity(); 3169 try { 3170 final int flags = getPermissionFlags(permission, packageName, userId); 3171 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3172 } finally { 3173 Binder.restoreCallingIdentity(identity); 3174 } 3175 } 3176 3177 /** 3178 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3179 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3180 * @param checkShell TODO(yamasani): 3181 * @param message the message to log on security exception 3182 */ 3183 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3184 boolean checkShell, String message) { 3185 if (userId < 0) { 3186 throw new IllegalArgumentException("Invalid userId " + userId); 3187 } 3188 if (checkShell) { 3189 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3190 } 3191 if (userId == UserHandle.getUserId(callingUid)) return; 3192 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3193 if (requireFullPermission) { 3194 mContext.enforceCallingOrSelfPermission( 3195 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3196 } else { 3197 try { 3198 mContext.enforceCallingOrSelfPermission( 3199 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3200 } catch (SecurityException se) { 3201 mContext.enforceCallingOrSelfPermission( 3202 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3203 } 3204 } 3205 } 3206 } 3207 3208 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3209 if (callingUid == Process.SHELL_UID) { 3210 if (userHandle >= 0 3211 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3212 throw new SecurityException("Shell does not have permission to access user " 3213 + userHandle); 3214 } else if (userHandle < 0) { 3215 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3216 + Debug.getCallers(3)); 3217 } 3218 } 3219 } 3220 3221 private BasePermission findPermissionTreeLP(String permName) { 3222 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3223 if (permName.startsWith(bp.name) && 3224 permName.length() > bp.name.length() && 3225 permName.charAt(bp.name.length()) == '.') { 3226 return bp; 3227 } 3228 } 3229 return null; 3230 } 3231 3232 private BasePermission checkPermissionTreeLP(String permName) { 3233 if (permName != null) { 3234 BasePermission bp = findPermissionTreeLP(permName); 3235 if (bp != null) { 3236 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3237 return bp; 3238 } 3239 throw new SecurityException("Calling uid " 3240 + Binder.getCallingUid() 3241 + " is not allowed to add to permission tree " 3242 + bp.name + " owned by uid " + bp.uid); 3243 } 3244 } 3245 throw new SecurityException("No permission tree found for " + permName); 3246 } 3247 3248 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3249 if (s1 == null) { 3250 return s2 == null; 3251 } 3252 if (s2 == null) { 3253 return false; 3254 } 3255 if (s1.getClass() != s2.getClass()) { 3256 return false; 3257 } 3258 return s1.equals(s2); 3259 } 3260 3261 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3262 if (pi1.icon != pi2.icon) return false; 3263 if (pi1.logo != pi2.logo) return false; 3264 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3265 if (!compareStrings(pi1.name, pi2.name)) return false; 3266 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3267 // We'll take care of setting this one. 3268 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3269 // These are not currently stored in settings. 3270 //if (!compareStrings(pi1.group, pi2.group)) return false; 3271 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3272 //if (pi1.labelRes != pi2.labelRes) return false; 3273 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3274 return true; 3275 } 3276 3277 int permissionInfoFootprint(PermissionInfo info) { 3278 int size = info.name.length(); 3279 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3280 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3281 return size; 3282 } 3283 3284 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3285 int size = 0; 3286 for (BasePermission perm : mSettings.mPermissions.values()) { 3287 if (perm.uid == tree.uid) { 3288 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3289 } 3290 } 3291 return size; 3292 } 3293 3294 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3295 // We calculate the max size of permissions defined by this uid and throw 3296 // if that plus the size of 'info' would exceed our stated maximum. 3297 if (tree.uid != Process.SYSTEM_UID) { 3298 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3299 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3300 throw new SecurityException("Permission tree size cap exceeded"); 3301 } 3302 } 3303 } 3304 3305 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3306 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3307 throw new SecurityException("Label must be specified in permission"); 3308 } 3309 BasePermission tree = checkPermissionTreeLP(info.name); 3310 BasePermission bp = mSettings.mPermissions.get(info.name); 3311 boolean added = bp == null; 3312 boolean changed = true; 3313 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3314 if (added) { 3315 enforcePermissionCapLocked(info, tree); 3316 bp = new BasePermission(info.name, tree.sourcePackage, 3317 BasePermission.TYPE_DYNAMIC); 3318 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3319 throw new SecurityException( 3320 "Not allowed to modify non-dynamic permission " 3321 + info.name); 3322 } else { 3323 if (bp.protectionLevel == fixedLevel 3324 && bp.perm.owner.equals(tree.perm.owner) 3325 && bp.uid == tree.uid 3326 && comparePermissionInfos(bp.perm.info, info)) { 3327 changed = false; 3328 } 3329 } 3330 bp.protectionLevel = fixedLevel; 3331 info = new PermissionInfo(info); 3332 info.protectionLevel = fixedLevel; 3333 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3334 bp.perm.info.packageName = tree.perm.info.packageName; 3335 bp.uid = tree.uid; 3336 if (added) { 3337 mSettings.mPermissions.put(info.name, bp); 3338 } 3339 if (changed) { 3340 if (!async) { 3341 mSettings.writeLPr(); 3342 } else { 3343 scheduleWriteSettingsLocked(); 3344 } 3345 } 3346 return added; 3347 } 3348 3349 @Override 3350 public boolean addPermission(PermissionInfo info) { 3351 synchronized (mPackages) { 3352 return addPermissionLocked(info, false); 3353 } 3354 } 3355 3356 @Override 3357 public boolean addPermissionAsync(PermissionInfo info) { 3358 synchronized (mPackages) { 3359 return addPermissionLocked(info, true); 3360 } 3361 } 3362 3363 @Override 3364 public void removePermission(String name) { 3365 synchronized (mPackages) { 3366 checkPermissionTreeLP(name); 3367 BasePermission bp = mSettings.mPermissions.get(name); 3368 if (bp != null) { 3369 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3370 throw new SecurityException( 3371 "Not allowed to modify non-dynamic permission " 3372 + name); 3373 } 3374 mSettings.mPermissions.remove(name); 3375 mSettings.writeLPr(); 3376 } 3377 } 3378 } 3379 3380 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3381 BasePermission bp) { 3382 int index = pkg.requestedPermissions.indexOf(bp.name); 3383 if (index == -1) { 3384 throw new SecurityException("Package " + pkg.packageName 3385 + " has not requested permission " + bp.name); 3386 } 3387 if (!bp.isRuntime()) { 3388 throw new SecurityException("Permission " + bp.name 3389 + " is not a changeable permission type"); 3390 } 3391 } 3392 3393 @Override 3394 public void grantRuntimePermission(String packageName, String name, final int userId) { 3395 if (!sUserManager.exists(userId)) { 3396 Log.e(TAG, "No such user:" + userId); 3397 return; 3398 } 3399 3400 mContext.enforceCallingOrSelfPermission( 3401 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3402 "grantRuntimePermission"); 3403 3404 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3405 "grantRuntimePermission"); 3406 3407 final int uid; 3408 final SettingBase sb; 3409 3410 synchronized (mPackages) { 3411 final PackageParser.Package pkg = mPackages.get(packageName); 3412 if (pkg == null) { 3413 throw new IllegalArgumentException("Unknown package: " + packageName); 3414 } 3415 3416 final BasePermission bp = mSettings.mPermissions.get(name); 3417 if (bp == null) { 3418 throw new IllegalArgumentException("Unknown permission: " + name); 3419 } 3420 3421 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3422 3423 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3424 sb = (SettingBase) pkg.mExtras; 3425 if (sb == null) { 3426 throw new IllegalArgumentException("Unknown package: " + packageName); 3427 } 3428 3429 final PermissionsState permissionsState = sb.getPermissionsState(); 3430 3431 final int flags = permissionsState.getPermissionFlags(name, userId); 3432 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3433 throw new SecurityException("Cannot grant system fixed permission: " 3434 + name + " for package: " + packageName); 3435 } 3436 3437 final int result = permissionsState.grantRuntimePermission(bp, userId); 3438 switch (result) { 3439 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3440 return; 3441 } 3442 3443 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3444 mHandler.post(new Runnable() { 3445 @Override 3446 public void run() { 3447 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3448 } 3449 }); 3450 } break; 3451 } 3452 3453 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3454 3455 // Not critical if that is lost - app has to request again. 3456 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3457 } 3458 3459 // Only need to do this if user is initialized. Otherwise it's a new user 3460 // and there are no processes running as the user yet and there's no need 3461 // to make an expensive call to remount processes for the changed permissions. 3462 if (READ_EXTERNAL_STORAGE.equals(name) 3463 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3464 final long token = Binder.clearCallingIdentity(); 3465 try { 3466 if (sUserManager.isInitialized(userId)) { 3467 MountServiceInternal mountServiceInternal = LocalServices.getService( 3468 MountServiceInternal.class); 3469 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3470 } 3471 } finally { 3472 Binder.restoreCallingIdentity(token); 3473 } 3474 } 3475 } 3476 3477 @Override 3478 public void revokeRuntimePermission(String packageName, String name, int userId) { 3479 if (!sUserManager.exists(userId)) { 3480 Log.e(TAG, "No such user:" + userId); 3481 return; 3482 } 3483 3484 mContext.enforceCallingOrSelfPermission( 3485 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3486 "revokeRuntimePermission"); 3487 3488 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3489 "revokeRuntimePermission"); 3490 3491 final SettingBase sb; 3492 3493 synchronized (mPackages) { 3494 final PackageParser.Package pkg = mPackages.get(packageName); 3495 if (pkg == null) { 3496 throw new IllegalArgumentException("Unknown package: " + packageName); 3497 } 3498 3499 final BasePermission bp = mSettings.mPermissions.get(name); 3500 if (bp == null) { 3501 throw new IllegalArgumentException("Unknown permission: " + name); 3502 } 3503 3504 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3505 3506 sb = (SettingBase) pkg.mExtras; 3507 if (sb == null) { 3508 throw new IllegalArgumentException("Unknown package: " + packageName); 3509 } 3510 3511 final PermissionsState permissionsState = sb.getPermissionsState(); 3512 3513 final int flags = permissionsState.getPermissionFlags(name, userId); 3514 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3515 throw new SecurityException("Cannot revoke system fixed permission: " 3516 + name + " for package: " + packageName); 3517 } 3518 3519 if (permissionsState.revokeRuntimePermission(bp, userId) == 3520 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3521 return; 3522 } 3523 3524 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3525 3526 // Critical, after this call app should never have the permission. 3527 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3528 } 3529 3530 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3531 } 3532 3533 @Override 3534 public void resetRuntimePermissions() { 3535 mContext.enforceCallingOrSelfPermission( 3536 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3537 "revokeRuntimePermission"); 3538 3539 int callingUid = Binder.getCallingUid(); 3540 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3541 mContext.enforceCallingOrSelfPermission( 3542 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3543 "resetRuntimePermissions"); 3544 } 3545 3546 synchronized (mPackages) { 3547 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3548 for (int userId : UserManagerService.getInstance().getUserIds()) { 3549 final int packageCount = mPackages.size(); 3550 for (int i = 0; i < packageCount; i++) { 3551 PackageParser.Package pkg = mPackages.valueAt(i); 3552 if (!(pkg.mExtras instanceof PackageSetting)) { 3553 continue; 3554 } 3555 PackageSetting ps = (PackageSetting) pkg.mExtras; 3556 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 3557 } 3558 } 3559 } 3560 } 3561 3562 @Override 3563 public int getPermissionFlags(String name, String packageName, int userId) { 3564 if (!sUserManager.exists(userId)) { 3565 return 0; 3566 } 3567 3568 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3569 3570 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3571 "getPermissionFlags"); 3572 3573 synchronized (mPackages) { 3574 final PackageParser.Package pkg = mPackages.get(packageName); 3575 if (pkg == null) { 3576 throw new IllegalArgumentException("Unknown package: " + packageName); 3577 } 3578 3579 final BasePermission bp = mSettings.mPermissions.get(name); 3580 if (bp == null) { 3581 throw new IllegalArgumentException("Unknown permission: " + name); 3582 } 3583 3584 SettingBase sb = (SettingBase) pkg.mExtras; 3585 if (sb == null) { 3586 throw new IllegalArgumentException("Unknown package: " + packageName); 3587 } 3588 3589 PermissionsState permissionsState = sb.getPermissionsState(); 3590 return permissionsState.getPermissionFlags(name, userId); 3591 } 3592 } 3593 3594 @Override 3595 public void updatePermissionFlags(String name, String packageName, int flagMask, 3596 int flagValues, int userId) { 3597 if (!sUserManager.exists(userId)) { 3598 return; 3599 } 3600 3601 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3602 3603 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3604 "updatePermissionFlags"); 3605 3606 // Only the system can change system fixed flags. 3607 if (getCallingUid() != Process.SYSTEM_UID) { 3608 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3609 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3610 } 3611 3612 synchronized (mPackages) { 3613 final PackageParser.Package pkg = mPackages.get(packageName); 3614 if (pkg == null) { 3615 throw new IllegalArgumentException("Unknown package: " + packageName); 3616 } 3617 3618 final BasePermission bp = mSettings.mPermissions.get(name); 3619 if (bp == null) { 3620 throw new IllegalArgumentException("Unknown permission: " + name); 3621 } 3622 3623 SettingBase sb = (SettingBase) pkg.mExtras; 3624 if (sb == null) { 3625 throw new IllegalArgumentException("Unknown package: " + packageName); 3626 } 3627 3628 PermissionsState permissionsState = sb.getPermissionsState(); 3629 3630 // Only the package manager can change flags for system component permissions. 3631 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3632 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3633 return; 3634 } 3635 3636 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3637 3638 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3639 // Install and runtime permissions are stored in different places, 3640 // so figure out what permission changed and persist the change. 3641 if (permissionsState.getInstallPermissionState(name) != null) { 3642 scheduleWriteSettingsLocked(); 3643 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3644 || hadState) { 3645 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3646 } 3647 } 3648 } 3649 } 3650 3651 /** 3652 * Update the permission flags for all packages and runtime permissions of a user in order 3653 * to allow device or profile owner to remove POLICY_FIXED. 3654 */ 3655 @Override 3656 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3657 if (!sUserManager.exists(userId)) { 3658 return; 3659 } 3660 3661 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3662 3663 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3664 "updatePermissionFlagsForAllApps"); 3665 3666 // Only the system can change system fixed flags. 3667 if (getCallingUid() != Process.SYSTEM_UID) { 3668 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3669 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3670 } 3671 3672 synchronized (mPackages) { 3673 boolean changed = false; 3674 final int packageCount = mPackages.size(); 3675 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3676 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3677 SettingBase sb = (SettingBase) pkg.mExtras; 3678 if (sb == null) { 3679 continue; 3680 } 3681 PermissionsState permissionsState = sb.getPermissionsState(); 3682 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3683 userId, flagMask, flagValues); 3684 } 3685 if (changed) { 3686 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3687 } 3688 } 3689 } 3690 3691 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3692 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3693 != PackageManager.PERMISSION_GRANTED 3694 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3695 != PackageManager.PERMISSION_GRANTED) { 3696 throw new SecurityException(message + " requires " 3697 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3698 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3699 } 3700 } 3701 3702 @Override 3703 public boolean shouldShowRequestPermissionRationale(String permissionName, 3704 String packageName, int userId) { 3705 if (UserHandle.getCallingUserId() != userId) { 3706 mContext.enforceCallingPermission( 3707 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3708 "canShowRequestPermissionRationale for user " + userId); 3709 } 3710 3711 final int uid = getPackageUid(packageName, userId); 3712 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3713 return false; 3714 } 3715 3716 if (checkPermission(permissionName, packageName, userId) 3717 == PackageManager.PERMISSION_GRANTED) { 3718 return false; 3719 } 3720 3721 final int flags; 3722 3723 final long identity = Binder.clearCallingIdentity(); 3724 try { 3725 flags = getPermissionFlags(permissionName, 3726 packageName, userId); 3727 } finally { 3728 Binder.restoreCallingIdentity(identity); 3729 } 3730 3731 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3732 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3733 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3734 3735 if ((flags & fixedFlags) != 0) { 3736 return false; 3737 } 3738 3739 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3740 } 3741 3742 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3743 BasePermission bp = mSettings.mPermissions.get(permission); 3744 if (bp == null) { 3745 throw new SecurityException("Missing " + permission + " permission"); 3746 } 3747 3748 SettingBase sb = (SettingBase) pkg.mExtras; 3749 PermissionsState permissionsState = sb.getPermissionsState(); 3750 3751 if (permissionsState.grantInstallPermission(bp) != 3752 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3753 scheduleWriteSettingsLocked(); 3754 } 3755 } 3756 3757 @Override 3758 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3759 mContext.enforceCallingOrSelfPermission( 3760 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3761 "addOnPermissionsChangeListener"); 3762 3763 synchronized (mPackages) { 3764 mOnPermissionChangeListeners.addListenerLocked(listener); 3765 } 3766 } 3767 3768 @Override 3769 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3770 synchronized (mPackages) { 3771 mOnPermissionChangeListeners.removeListenerLocked(listener); 3772 } 3773 } 3774 3775 @Override 3776 public boolean isProtectedBroadcast(String actionName) { 3777 synchronized (mPackages) { 3778 return mProtectedBroadcasts.contains(actionName); 3779 } 3780 } 3781 3782 @Override 3783 public int checkSignatures(String pkg1, String pkg2) { 3784 synchronized (mPackages) { 3785 final PackageParser.Package p1 = mPackages.get(pkg1); 3786 final PackageParser.Package p2 = mPackages.get(pkg2); 3787 if (p1 == null || p1.mExtras == null 3788 || p2 == null || p2.mExtras == null) { 3789 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3790 } 3791 return compareSignatures(p1.mSignatures, p2.mSignatures); 3792 } 3793 } 3794 3795 @Override 3796 public int checkUidSignatures(int uid1, int uid2) { 3797 // Map to base uids. 3798 uid1 = UserHandle.getAppId(uid1); 3799 uid2 = UserHandle.getAppId(uid2); 3800 // reader 3801 synchronized (mPackages) { 3802 Signature[] s1; 3803 Signature[] s2; 3804 Object obj = mSettings.getUserIdLPr(uid1); 3805 if (obj != null) { 3806 if (obj instanceof SharedUserSetting) { 3807 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3808 } else if (obj instanceof PackageSetting) { 3809 s1 = ((PackageSetting)obj).signatures.mSignatures; 3810 } else { 3811 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3812 } 3813 } else { 3814 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3815 } 3816 obj = mSettings.getUserIdLPr(uid2); 3817 if (obj != null) { 3818 if (obj instanceof SharedUserSetting) { 3819 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3820 } else if (obj instanceof PackageSetting) { 3821 s2 = ((PackageSetting)obj).signatures.mSignatures; 3822 } else { 3823 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3824 } 3825 } else { 3826 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3827 } 3828 return compareSignatures(s1, s2); 3829 } 3830 } 3831 3832 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3833 final long identity = Binder.clearCallingIdentity(); 3834 try { 3835 if (sb instanceof SharedUserSetting) { 3836 SharedUserSetting sus = (SharedUserSetting) sb; 3837 final int packageCount = sus.packages.size(); 3838 for (int i = 0; i < packageCount; i++) { 3839 PackageSetting susPs = sus.packages.valueAt(i); 3840 if (userId == UserHandle.USER_ALL) { 3841 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3842 } else { 3843 final int uid = UserHandle.getUid(userId, susPs.appId); 3844 killUid(uid, reason); 3845 } 3846 } 3847 } else if (sb instanceof PackageSetting) { 3848 PackageSetting ps = (PackageSetting) sb; 3849 if (userId == UserHandle.USER_ALL) { 3850 killApplication(ps.pkg.packageName, ps.appId, reason); 3851 } else { 3852 final int uid = UserHandle.getUid(userId, ps.appId); 3853 killUid(uid, reason); 3854 } 3855 } 3856 } finally { 3857 Binder.restoreCallingIdentity(identity); 3858 } 3859 } 3860 3861 private static void killUid(int uid, String reason) { 3862 IActivityManager am = ActivityManagerNative.getDefault(); 3863 if (am != null) { 3864 try { 3865 am.killUid(uid, reason); 3866 } catch (RemoteException e) { 3867 /* ignore - same process */ 3868 } 3869 } 3870 } 3871 3872 /** 3873 * Compares two sets of signatures. Returns: 3874 * <br /> 3875 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3876 * <br /> 3877 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3878 * <br /> 3879 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3880 * <br /> 3881 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3882 * <br /> 3883 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3884 */ 3885 static int compareSignatures(Signature[] s1, Signature[] s2) { 3886 if (s1 == null) { 3887 return s2 == null 3888 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3889 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3890 } 3891 3892 if (s2 == null) { 3893 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3894 } 3895 3896 if (s1.length != s2.length) { 3897 return PackageManager.SIGNATURE_NO_MATCH; 3898 } 3899 3900 // Since both signature sets are of size 1, we can compare without HashSets. 3901 if (s1.length == 1) { 3902 return s1[0].equals(s2[0]) ? 3903 PackageManager.SIGNATURE_MATCH : 3904 PackageManager.SIGNATURE_NO_MATCH; 3905 } 3906 3907 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3908 for (Signature sig : s1) { 3909 set1.add(sig); 3910 } 3911 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3912 for (Signature sig : s2) { 3913 set2.add(sig); 3914 } 3915 // Make sure s2 contains all signatures in s1. 3916 if (set1.equals(set2)) { 3917 return PackageManager.SIGNATURE_MATCH; 3918 } 3919 return PackageManager.SIGNATURE_NO_MATCH; 3920 } 3921 3922 /** 3923 * If the database version for this type of package (internal storage or 3924 * external storage) is less than the version where package signatures 3925 * were updated, return true. 3926 */ 3927 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3928 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3929 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3930 } 3931 3932 /** 3933 * Used for backward compatibility to make sure any packages with 3934 * certificate chains get upgraded to the new style. {@code existingSigs} 3935 * will be in the old format (since they were stored on disk from before the 3936 * system upgrade) and {@code scannedSigs} will be in the newer format. 3937 */ 3938 private int compareSignaturesCompat(PackageSignatures existingSigs, 3939 PackageParser.Package scannedPkg) { 3940 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3941 return PackageManager.SIGNATURE_NO_MATCH; 3942 } 3943 3944 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3945 for (Signature sig : existingSigs.mSignatures) { 3946 existingSet.add(sig); 3947 } 3948 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3949 for (Signature sig : scannedPkg.mSignatures) { 3950 try { 3951 Signature[] chainSignatures = sig.getChainSignatures(); 3952 for (Signature chainSig : chainSignatures) { 3953 scannedCompatSet.add(chainSig); 3954 } 3955 } catch (CertificateEncodingException e) { 3956 scannedCompatSet.add(sig); 3957 } 3958 } 3959 /* 3960 * Make sure the expanded scanned set contains all signatures in the 3961 * existing one. 3962 */ 3963 if (scannedCompatSet.equals(existingSet)) { 3964 // Migrate the old signatures to the new scheme. 3965 existingSigs.assignSignatures(scannedPkg.mSignatures); 3966 // The new KeySets will be re-added later in the scanning process. 3967 synchronized (mPackages) { 3968 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3969 } 3970 return PackageManager.SIGNATURE_MATCH; 3971 } 3972 return PackageManager.SIGNATURE_NO_MATCH; 3973 } 3974 3975 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3976 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3977 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 3978 } 3979 3980 private int compareSignaturesRecover(PackageSignatures existingSigs, 3981 PackageParser.Package scannedPkg) { 3982 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3983 return PackageManager.SIGNATURE_NO_MATCH; 3984 } 3985 3986 String msg = null; 3987 try { 3988 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3989 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3990 + scannedPkg.packageName); 3991 return PackageManager.SIGNATURE_MATCH; 3992 } 3993 } catch (CertificateException e) { 3994 msg = e.getMessage(); 3995 } 3996 3997 logCriticalInfo(Log.INFO, 3998 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3999 return PackageManager.SIGNATURE_NO_MATCH; 4000 } 4001 4002 @Override 4003 public String[] getPackagesForUid(int uid) { 4004 uid = UserHandle.getAppId(uid); 4005 // reader 4006 synchronized (mPackages) { 4007 Object obj = mSettings.getUserIdLPr(uid); 4008 if (obj instanceof SharedUserSetting) { 4009 final SharedUserSetting sus = (SharedUserSetting) obj; 4010 final int N = sus.packages.size(); 4011 final String[] res = new String[N]; 4012 final Iterator<PackageSetting> it = sus.packages.iterator(); 4013 int i = 0; 4014 while (it.hasNext()) { 4015 res[i++] = it.next().name; 4016 } 4017 return res; 4018 } else if (obj instanceof PackageSetting) { 4019 final PackageSetting ps = (PackageSetting) obj; 4020 return new String[] { ps.name }; 4021 } 4022 } 4023 return null; 4024 } 4025 4026 @Override 4027 public String getNameForUid(int uid) { 4028 // reader 4029 synchronized (mPackages) { 4030 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4031 if (obj instanceof SharedUserSetting) { 4032 final SharedUserSetting sus = (SharedUserSetting) obj; 4033 return sus.name + ":" + sus.userId; 4034 } else if (obj instanceof PackageSetting) { 4035 final PackageSetting ps = (PackageSetting) obj; 4036 return ps.name; 4037 } 4038 } 4039 return null; 4040 } 4041 4042 @Override 4043 public int getUidForSharedUser(String sharedUserName) { 4044 if(sharedUserName == null) { 4045 return -1; 4046 } 4047 // reader 4048 synchronized (mPackages) { 4049 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4050 if (suid == null) { 4051 return -1; 4052 } 4053 return suid.userId; 4054 } 4055 } 4056 4057 @Override 4058 public int getFlagsForUid(int uid) { 4059 synchronized (mPackages) { 4060 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4061 if (obj instanceof SharedUserSetting) { 4062 final SharedUserSetting sus = (SharedUserSetting) obj; 4063 return sus.pkgFlags; 4064 } else if (obj instanceof PackageSetting) { 4065 final PackageSetting ps = (PackageSetting) obj; 4066 return ps.pkgFlags; 4067 } 4068 } 4069 return 0; 4070 } 4071 4072 @Override 4073 public int getPrivateFlagsForUid(int uid) { 4074 synchronized (mPackages) { 4075 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4076 if (obj instanceof SharedUserSetting) { 4077 final SharedUserSetting sus = (SharedUserSetting) obj; 4078 return sus.pkgPrivateFlags; 4079 } else if (obj instanceof PackageSetting) { 4080 final PackageSetting ps = (PackageSetting) obj; 4081 return ps.pkgPrivateFlags; 4082 } 4083 } 4084 return 0; 4085 } 4086 4087 @Override 4088 public boolean isUidPrivileged(int uid) { 4089 uid = UserHandle.getAppId(uid); 4090 // reader 4091 synchronized (mPackages) { 4092 Object obj = mSettings.getUserIdLPr(uid); 4093 if (obj instanceof SharedUserSetting) { 4094 final SharedUserSetting sus = (SharedUserSetting) obj; 4095 final Iterator<PackageSetting> it = sus.packages.iterator(); 4096 while (it.hasNext()) { 4097 if (it.next().isPrivileged()) { 4098 return true; 4099 } 4100 } 4101 } else if (obj instanceof PackageSetting) { 4102 final PackageSetting ps = (PackageSetting) obj; 4103 return ps.isPrivileged(); 4104 } 4105 } 4106 return false; 4107 } 4108 4109 @Override 4110 public String[] getAppOpPermissionPackages(String permissionName) { 4111 synchronized (mPackages) { 4112 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4113 if (pkgs == null) { 4114 return null; 4115 } 4116 return pkgs.toArray(new String[pkgs.size()]); 4117 } 4118 } 4119 4120 @Override 4121 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4122 int flags, int userId) { 4123 if (!sUserManager.exists(userId)) return null; 4124 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4125 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4126 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4127 } 4128 4129 @Override 4130 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4131 IntentFilter filter, int match, ComponentName activity) { 4132 final int userId = UserHandle.getCallingUserId(); 4133 if (DEBUG_PREFERRED) { 4134 Log.v(TAG, "setLastChosenActivity intent=" + intent 4135 + " resolvedType=" + resolvedType 4136 + " flags=" + flags 4137 + " filter=" + filter 4138 + " match=" + match 4139 + " activity=" + activity); 4140 filter.dump(new PrintStreamPrinter(System.out), " "); 4141 } 4142 intent.setComponent(null); 4143 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4144 // Find any earlier preferred or last chosen entries and nuke them 4145 findPreferredActivity(intent, resolvedType, 4146 flags, query, 0, false, true, false, userId); 4147 // Add the new activity as the last chosen for this filter 4148 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4149 "Setting last chosen"); 4150 } 4151 4152 @Override 4153 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4154 final int userId = UserHandle.getCallingUserId(); 4155 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4156 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4157 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4158 false, false, false, userId); 4159 } 4160 4161 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4162 int flags, List<ResolveInfo> query, int userId) { 4163 if (query != null) { 4164 final int N = query.size(); 4165 if (N == 1) { 4166 return query.get(0); 4167 } else if (N > 1) { 4168 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4169 // If there is more than one activity with the same priority, 4170 // then let the user decide between them. 4171 ResolveInfo r0 = query.get(0); 4172 ResolveInfo r1 = query.get(1); 4173 if (DEBUG_INTENT_MATCHING || debug) { 4174 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4175 + r1.activityInfo.name + "=" + r1.priority); 4176 } 4177 // If the first activity has a higher priority, or a different 4178 // default, then it is always desireable to pick it. 4179 if (r0.priority != r1.priority 4180 || r0.preferredOrder != r1.preferredOrder 4181 || r0.isDefault != r1.isDefault) { 4182 return query.get(0); 4183 } 4184 // If we have saved a preference for a preferred activity for 4185 // this Intent, use that. 4186 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4187 flags, query, r0.priority, true, false, debug, userId); 4188 if (ri != null) { 4189 return ri; 4190 } 4191 if (userId != 0) { 4192 ri = new ResolveInfo(mResolveInfo); 4193 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4194 ri.activityInfo.applicationInfo = new ApplicationInfo( 4195 ri.activityInfo.applicationInfo); 4196 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4197 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4198 return ri; 4199 } 4200 return mResolveInfo; 4201 } 4202 } 4203 return null; 4204 } 4205 4206 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4207 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4208 final int N = query.size(); 4209 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4210 .get(userId); 4211 // Get the list of persistent preferred activities that handle the intent 4212 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4213 List<PersistentPreferredActivity> pprefs = ppir != null 4214 ? ppir.queryIntent(intent, resolvedType, 4215 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4216 : null; 4217 if (pprefs != null && pprefs.size() > 0) { 4218 final int M = pprefs.size(); 4219 for (int i=0; i<M; i++) { 4220 final PersistentPreferredActivity ppa = pprefs.get(i); 4221 if (DEBUG_PREFERRED || debug) { 4222 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4223 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4224 + "\n component=" + ppa.mComponent); 4225 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4226 } 4227 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4228 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4229 if (DEBUG_PREFERRED || debug) { 4230 Slog.v(TAG, "Found persistent preferred activity:"); 4231 if (ai != null) { 4232 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4233 } else { 4234 Slog.v(TAG, " null"); 4235 } 4236 } 4237 if (ai == null) { 4238 // This previously registered persistent preferred activity 4239 // component is no longer known. Ignore it and do NOT remove it. 4240 continue; 4241 } 4242 for (int j=0; j<N; j++) { 4243 final ResolveInfo ri = query.get(j); 4244 if (!ri.activityInfo.applicationInfo.packageName 4245 .equals(ai.applicationInfo.packageName)) { 4246 continue; 4247 } 4248 if (!ri.activityInfo.name.equals(ai.name)) { 4249 continue; 4250 } 4251 // Found a persistent preference that can handle the intent. 4252 if (DEBUG_PREFERRED || debug) { 4253 Slog.v(TAG, "Returning persistent preferred activity: " + 4254 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4255 } 4256 return ri; 4257 } 4258 } 4259 } 4260 return null; 4261 } 4262 4263 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4264 List<ResolveInfo> query, int priority, boolean always, 4265 boolean removeMatches, boolean debug, int userId) { 4266 if (!sUserManager.exists(userId)) return null; 4267 // writer 4268 synchronized (mPackages) { 4269 if (intent.getSelector() != null) { 4270 intent = intent.getSelector(); 4271 } 4272 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4273 4274 // Try to find a matching persistent preferred activity. 4275 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4276 debug, userId); 4277 4278 // If a persistent preferred activity matched, use it. 4279 if (pri != null) { 4280 return pri; 4281 } 4282 4283 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4284 // Get the list of preferred activities that handle the intent 4285 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4286 List<PreferredActivity> prefs = pir != null 4287 ? pir.queryIntent(intent, resolvedType, 4288 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4289 : null; 4290 if (prefs != null && prefs.size() > 0) { 4291 boolean changed = false; 4292 try { 4293 // First figure out how good the original match set is. 4294 // We will only allow preferred activities that came 4295 // from the same match quality. 4296 int match = 0; 4297 4298 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4299 4300 final int N = query.size(); 4301 for (int j=0; j<N; j++) { 4302 final ResolveInfo ri = query.get(j); 4303 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4304 + ": 0x" + Integer.toHexString(match)); 4305 if (ri.match > match) { 4306 match = ri.match; 4307 } 4308 } 4309 4310 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4311 + Integer.toHexString(match)); 4312 4313 match &= IntentFilter.MATCH_CATEGORY_MASK; 4314 final int M = prefs.size(); 4315 for (int i=0; i<M; i++) { 4316 final PreferredActivity pa = prefs.get(i); 4317 if (DEBUG_PREFERRED || debug) { 4318 Slog.v(TAG, "Checking PreferredActivity ds=" 4319 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4320 + "\n component=" + pa.mPref.mComponent); 4321 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4322 } 4323 if (pa.mPref.mMatch != match) { 4324 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4325 + Integer.toHexString(pa.mPref.mMatch)); 4326 continue; 4327 } 4328 // If it's not an "always" type preferred activity and that's what we're 4329 // looking for, skip it. 4330 if (always && !pa.mPref.mAlways) { 4331 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4332 continue; 4333 } 4334 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4335 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4336 if (DEBUG_PREFERRED || debug) { 4337 Slog.v(TAG, "Found preferred activity:"); 4338 if (ai != null) { 4339 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4340 } else { 4341 Slog.v(TAG, " null"); 4342 } 4343 } 4344 if (ai == null) { 4345 // This previously registered preferred activity 4346 // component is no longer known. Most likely an update 4347 // to the app was installed and in the new version this 4348 // component no longer exists. Clean it up by removing 4349 // it from the preferred activities list, and skip it. 4350 Slog.w(TAG, "Removing dangling preferred activity: " 4351 + pa.mPref.mComponent); 4352 pir.removeFilter(pa); 4353 changed = true; 4354 continue; 4355 } 4356 for (int j=0; j<N; j++) { 4357 final ResolveInfo ri = query.get(j); 4358 if (!ri.activityInfo.applicationInfo.packageName 4359 .equals(ai.applicationInfo.packageName)) { 4360 continue; 4361 } 4362 if (!ri.activityInfo.name.equals(ai.name)) { 4363 continue; 4364 } 4365 4366 if (removeMatches) { 4367 pir.removeFilter(pa); 4368 changed = true; 4369 if (DEBUG_PREFERRED) { 4370 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4371 } 4372 break; 4373 } 4374 4375 // Okay we found a previously set preferred or last chosen app. 4376 // If the result set is different from when this 4377 // was created, we need to clear it and re-ask the 4378 // user their preference, if we're looking for an "always" type entry. 4379 if (always && !pa.mPref.sameSet(query)) { 4380 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4381 + intent + " type " + resolvedType); 4382 if (DEBUG_PREFERRED) { 4383 Slog.v(TAG, "Removing preferred activity since set changed " 4384 + pa.mPref.mComponent); 4385 } 4386 pir.removeFilter(pa); 4387 // Re-add the filter as a "last chosen" entry (!always) 4388 PreferredActivity lastChosen = new PreferredActivity( 4389 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4390 pir.addFilter(lastChosen); 4391 changed = true; 4392 return null; 4393 } 4394 4395 // Yay! Either the set matched or we're looking for the last chosen 4396 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4397 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4398 return ri; 4399 } 4400 } 4401 } finally { 4402 if (changed) { 4403 if (DEBUG_PREFERRED) { 4404 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4405 } 4406 scheduleWritePackageRestrictionsLocked(userId); 4407 } 4408 } 4409 } 4410 } 4411 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4412 return null; 4413 } 4414 4415 /* 4416 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4417 */ 4418 @Override 4419 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4420 int targetUserId) { 4421 mContext.enforceCallingOrSelfPermission( 4422 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4423 List<CrossProfileIntentFilter> matches = 4424 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4425 if (matches != null) { 4426 int size = matches.size(); 4427 for (int i = 0; i < size; i++) { 4428 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4429 } 4430 } 4431 if (hasWebURI(intent)) { 4432 // cross-profile app linking works only towards the parent. 4433 final UserInfo parent = getProfileParent(sourceUserId); 4434 synchronized(mPackages) { 4435 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4436 intent, resolvedType, 0, sourceUserId, parent.id); 4437 return xpDomainInfo != null; 4438 } 4439 } 4440 return false; 4441 } 4442 4443 private UserInfo getProfileParent(int userId) { 4444 final long identity = Binder.clearCallingIdentity(); 4445 try { 4446 return sUserManager.getProfileParent(userId); 4447 } finally { 4448 Binder.restoreCallingIdentity(identity); 4449 } 4450 } 4451 4452 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4453 String resolvedType, int userId) { 4454 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4455 if (resolver != null) { 4456 return resolver.queryIntent(intent, resolvedType, false, userId); 4457 } 4458 return null; 4459 } 4460 4461 @Override 4462 public List<ResolveInfo> queryIntentActivities(Intent intent, 4463 String resolvedType, int flags, int userId) { 4464 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4465 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4466 ComponentName comp = intent.getComponent(); 4467 if (comp == null) { 4468 if (intent.getSelector() != null) { 4469 intent = intent.getSelector(); 4470 comp = intent.getComponent(); 4471 } 4472 } 4473 4474 if (comp != null) { 4475 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4476 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4477 if (ai != null) { 4478 final ResolveInfo ri = new ResolveInfo(); 4479 ri.activityInfo = ai; 4480 list.add(ri); 4481 } 4482 return list; 4483 } 4484 4485 // reader 4486 synchronized (mPackages) { 4487 final String pkgName = intent.getPackage(); 4488 if (pkgName == null) { 4489 List<CrossProfileIntentFilter> matchingFilters = 4490 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4491 // Check for results that need to skip the current profile. 4492 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4493 resolvedType, flags, userId); 4494 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4495 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4496 result.add(xpResolveInfo); 4497 return filterIfNotPrimaryUser(result, userId); 4498 } 4499 4500 // Check for results in the current profile. 4501 List<ResolveInfo> result = mActivities.queryIntent( 4502 intent, resolvedType, flags, userId); 4503 4504 // Check for cross profile results. 4505 xpResolveInfo = queryCrossProfileIntents( 4506 matchingFilters, intent, resolvedType, flags, userId); 4507 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4508 result.add(xpResolveInfo); 4509 Collections.sort(result, mResolvePrioritySorter); 4510 } 4511 result = filterIfNotPrimaryUser(result, userId); 4512 if (hasWebURI(intent)) { 4513 CrossProfileDomainInfo xpDomainInfo = null; 4514 final UserInfo parent = getProfileParent(userId); 4515 if (parent != null) { 4516 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4517 flags, userId, parent.id); 4518 } 4519 if (xpDomainInfo != null) { 4520 if (xpResolveInfo != null) { 4521 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4522 // in the result. 4523 result.remove(xpResolveInfo); 4524 } 4525 if (result.size() == 0) { 4526 result.add(xpDomainInfo.resolveInfo); 4527 return result; 4528 } 4529 } else if (result.size() <= 1) { 4530 return result; 4531 } 4532 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4533 xpDomainInfo, userId); 4534 Collections.sort(result, mResolvePrioritySorter); 4535 } 4536 return result; 4537 } 4538 final PackageParser.Package pkg = mPackages.get(pkgName); 4539 if (pkg != null) { 4540 return filterIfNotPrimaryUser( 4541 mActivities.queryIntentForPackage( 4542 intent, resolvedType, flags, pkg.activities, userId), 4543 userId); 4544 } 4545 return new ArrayList<ResolveInfo>(); 4546 } 4547 } 4548 4549 private static class CrossProfileDomainInfo { 4550 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4551 ResolveInfo resolveInfo; 4552 /* Best domain verification status of the activities found in the other profile */ 4553 int bestDomainVerificationStatus; 4554 } 4555 4556 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4557 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4558 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4559 sourceUserId)) { 4560 return null; 4561 } 4562 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4563 resolvedType, flags, parentUserId); 4564 4565 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4566 return null; 4567 } 4568 CrossProfileDomainInfo result = null; 4569 int size = resultTargetUser.size(); 4570 for (int i = 0; i < size; i++) { 4571 ResolveInfo riTargetUser = resultTargetUser.get(i); 4572 // Intent filter verification is only for filters that specify a host. So don't return 4573 // those that handle all web uris. 4574 if (riTargetUser.handleAllWebDataURI) { 4575 continue; 4576 } 4577 String packageName = riTargetUser.activityInfo.packageName; 4578 PackageSetting ps = mSettings.mPackages.get(packageName); 4579 if (ps == null) { 4580 continue; 4581 } 4582 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4583 int status = (int)(verificationState >> 32); 4584 if (result == null) { 4585 result = new CrossProfileDomainInfo(); 4586 result.resolveInfo = 4587 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4588 result.bestDomainVerificationStatus = status; 4589 } else { 4590 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4591 result.bestDomainVerificationStatus); 4592 } 4593 } 4594 // Don't consider matches with status NEVER across profiles. 4595 if (result != null && result.bestDomainVerificationStatus 4596 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4597 return null; 4598 } 4599 return result; 4600 } 4601 4602 /** 4603 * Verification statuses are ordered from the worse to the best, except for 4604 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4605 */ 4606 private int bestDomainVerificationStatus(int status1, int status2) { 4607 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4608 return status2; 4609 } 4610 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4611 return status1; 4612 } 4613 return (int) MathUtils.max(status1, status2); 4614 } 4615 4616 private boolean isUserEnabled(int userId) { 4617 long callingId = Binder.clearCallingIdentity(); 4618 try { 4619 UserInfo userInfo = sUserManager.getUserInfo(userId); 4620 return userInfo != null && userInfo.isEnabled(); 4621 } finally { 4622 Binder.restoreCallingIdentity(callingId); 4623 } 4624 } 4625 4626 /** 4627 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4628 * 4629 * @return filtered list 4630 */ 4631 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4632 if (userId == UserHandle.USER_OWNER) { 4633 return resolveInfos; 4634 } 4635 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4636 ResolveInfo info = resolveInfos.get(i); 4637 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4638 resolveInfos.remove(i); 4639 } 4640 } 4641 return resolveInfos; 4642 } 4643 4644 private static boolean hasWebURI(Intent intent) { 4645 if (intent.getData() == null) { 4646 return false; 4647 } 4648 final String scheme = intent.getScheme(); 4649 if (TextUtils.isEmpty(scheme)) { 4650 return false; 4651 } 4652 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4653 } 4654 4655 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4656 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4657 int userId) { 4658 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4659 4660 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4661 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4662 candidates.size()); 4663 } 4664 4665 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4666 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4667 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4668 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4669 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4670 4671 synchronized (mPackages) { 4672 final int count = candidates.size(); 4673 // First, try to use linked apps. Partition the candidates into four lists: 4674 // one for the final results, one for the "do not use ever", one for "undefined status" 4675 // and finally one for "browser app type". 4676 for (int n=0; n<count; n++) { 4677 ResolveInfo info = candidates.get(n); 4678 String packageName = info.activityInfo.packageName; 4679 PackageSetting ps = mSettings.mPackages.get(packageName); 4680 if (ps != null) { 4681 // Add to the special match all list (Browser use case) 4682 if (info.handleAllWebDataURI) { 4683 matchAllList.add(info); 4684 continue; 4685 } 4686 // Try to get the status from User settings first 4687 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4688 int status = (int)(packedStatus >> 32); 4689 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4690 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4691 if (DEBUG_DOMAIN_VERIFICATION) { 4692 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4693 + " : linkgen=" + linkGeneration); 4694 } 4695 // Use link-enabled generation as preferredOrder, i.e. 4696 // prefer newly-enabled over earlier-enabled. 4697 info.preferredOrder = linkGeneration; 4698 alwaysList.add(info); 4699 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4700 if (DEBUG_DOMAIN_VERIFICATION) { 4701 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4702 } 4703 neverList.add(info); 4704 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4705 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4706 if (DEBUG_DOMAIN_VERIFICATION) { 4707 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4708 } 4709 undefinedList.add(info); 4710 } 4711 } 4712 } 4713 // First try to add the "always" resolution(s) for the current user, if any 4714 if (alwaysList.size() > 0) { 4715 result.addAll(alwaysList); 4716 // if there is an "always" for the parent user, add it. 4717 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4718 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4719 result.add(xpDomainInfo.resolveInfo); 4720 } else { 4721 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4722 result.addAll(undefinedList); 4723 if (xpDomainInfo != null && ( 4724 xpDomainInfo.bestDomainVerificationStatus 4725 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4726 || xpDomainInfo.bestDomainVerificationStatus 4727 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4728 result.add(xpDomainInfo.resolveInfo); 4729 } 4730 // Also add Browsers (all of them or only the default one) 4731 if ((matchFlags & MATCH_ALL) != 0) { 4732 result.addAll(matchAllList); 4733 } else { 4734 // Browser/generic handling case. If there's a default browser, go straight 4735 // to that (but only if there is no other higher-priority match). 4736 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4737 int maxMatchPrio = 0; 4738 ResolveInfo defaultBrowserMatch = null; 4739 final int numCandidates = matchAllList.size(); 4740 for (int n = 0; n < numCandidates; n++) { 4741 ResolveInfo info = matchAllList.get(n); 4742 // track the highest overall match priority... 4743 if (info.priority > maxMatchPrio) { 4744 maxMatchPrio = info.priority; 4745 } 4746 // ...and the highest-priority default browser match 4747 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4748 if (defaultBrowserMatch == null 4749 || (defaultBrowserMatch.priority < info.priority)) { 4750 if (debug) { 4751 Slog.v(TAG, "Considering default browser match " + info); 4752 } 4753 defaultBrowserMatch = info; 4754 } 4755 } 4756 } 4757 if (defaultBrowserMatch != null 4758 && defaultBrowserMatch.priority >= maxMatchPrio 4759 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4760 { 4761 if (debug) { 4762 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4763 } 4764 result.add(defaultBrowserMatch); 4765 } else { 4766 result.addAll(matchAllList); 4767 } 4768 } 4769 4770 // If there is nothing selected, add all candidates and remove the ones that the user 4771 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4772 if (result.size() == 0) { 4773 result.addAll(candidates); 4774 result.removeAll(neverList); 4775 } 4776 } 4777 } 4778 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4779 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4780 result.size()); 4781 for (ResolveInfo info : result) { 4782 Slog.v(TAG, " + " + info.activityInfo); 4783 } 4784 } 4785 return result; 4786 } 4787 4788 // Returns a packed value as a long: 4789 // 4790 // high 'int'-sized word: link status: undefined/ask/never/always. 4791 // low 'int'-sized word: relative priority among 'always' results. 4792 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4793 long result = ps.getDomainVerificationStatusForUser(userId); 4794 // if none available, get the master status 4795 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4796 if (ps.getIntentFilterVerificationInfo() != null) { 4797 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4798 } 4799 } 4800 return result; 4801 } 4802 4803 private ResolveInfo querySkipCurrentProfileIntents( 4804 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4805 int flags, int sourceUserId) { 4806 if (matchingFilters != null) { 4807 int size = matchingFilters.size(); 4808 for (int i = 0; i < size; i ++) { 4809 CrossProfileIntentFilter filter = matchingFilters.get(i); 4810 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4811 // Checking if there are activities in the target user that can handle the 4812 // intent. 4813 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4814 flags, sourceUserId); 4815 if (resolveInfo != null) { 4816 return resolveInfo; 4817 } 4818 } 4819 } 4820 } 4821 return null; 4822 } 4823 4824 // Return matching ResolveInfo if any for skip current profile intent filters. 4825 private ResolveInfo queryCrossProfileIntents( 4826 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4827 int flags, int sourceUserId) { 4828 if (matchingFilters != null) { 4829 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4830 // match the same intent. For performance reasons, it is better not to 4831 // run queryIntent twice for the same userId 4832 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4833 int size = matchingFilters.size(); 4834 for (int i = 0; i < size; i++) { 4835 CrossProfileIntentFilter filter = matchingFilters.get(i); 4836 int targetUserId = filter.getTargetUserId(); 4837 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4838 && !alreadyTriedUserIds.get(targetUserId)) { 4839 // Checking if there are activities in the target user that can handle the 4840 // intent. 4841 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4842 flags, sourceUserId); 4843 if (resolveInfo != null) return resolveInfo; 4844 alreadyTriedUserIds.put(targetUserId, true); 4845 } 4846 } 4847 } 4848 return null; 4849 } 4850 4851 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4852 String resolvedType, int flags, int sourceUserId) { 4853 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4854 resolvedType, flags, filter.getTargetUserId()); 4855 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4856 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4857 } 4858 return null; 4859 } 4860 4861 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4862 int sourceUserId, int targetUserId) { 4863 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4864 String className; 4865 if (targetUserId == UserHandle.USER_OWNER) { 4866 className = FORWARD_INTENT_TO_USER_OWNER; 4867 } else { 4868 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4869 } 4870 ComponentName forwardingActivityComponentName = new ComponentName( 4871 mAndroidApplication.packageName, className); 4872 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4873 sourceUserId); 4874 if (targetUserId == UserHandle.USER_OWNER) { 4875 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4876 forwardingResolveInfo.noResourceId = true; 4877 } 4878 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4879 forwardingResolveInfo.priority = 0; 4880 forwardingResolveInfo.preferredOrder = 0; 4881 forwardingResolveInfo.match = 0; 4882 forwardingResolveInfo.isDefault = true; 4883 forwardingResolveInfo.filter = filter; 4884 forwardingResolveInfo.targetUserId = targetUserId; 4885 return forwardingResolveInfo; 4886 } 4887 4888 @Override 4889 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4890 Intent[] specifics, String[] specificTypes, Intent intent, 4891 String resolvedType, int flags, int userId) { 4892 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4893 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4894 false, "query intent activity options"); 4895 final String resultsAction = intent.getAction(); 4896 4897 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4898 | PackageManager.GET_RESOLVED_FILTER, userId); 4899 4900 if (DEBUG_INTENT_MATCHING) { 4901 Log.v(TAG, "Query " + intent + ": " + results); 4902 } 4903 4904 int specificsPos = 0; 4905 int N; 4906 4907 // todo: note that the algorithm used here is O(N^2). This 4908 // isn't a problem in our current environment, but if we start running 4909 // into situations where we have more than 5 or 10 matches then this 4910 // should probably be changed to something smarter... 4911 4912 // First we go through and resolve each of the specific items 4913 // that were supplied, taking care of removing any corresponding 4914 // duplicate items in the generic resolve list. 4915 if (specifics != null) { 4916 for (int i=0; i<specifics.length; i++) { 4917 final Intent sintent = specifics[i]; 4918 if (sintent == null) { 4919 continue; 4920 } 4921 4922 if (DEBUG_INTENT_MATCHING) { 4923 Log.v(TAG, "Specific #" + i + ": " + sintent); 4924 } 4925 4926 String action = sintent.getAction(); 4927 if (resultsAction != null && resultsAction.equals(action)) { 4928 // If this action was explicitly requested, then don't 4929 // remove things that have it. 4930 action = null; 4931 } 4932 4933 ResolveInfo ri = null; 4934 ActivityInfo ai = null; 4935 4936 ComponentName comp = sintent.getComponent(); 4937 if (comp == null) { 4938 ri = resolveIntent( 4939 sintent, 4940 specificTypes != null ? specificTypes[i] : null, 4941 flags, userId); 4942 if (ri == null) { 4943 continue; 4944 } 4945 if (ri == mResolveInfo) { 4946 // ACK! Must do something better with this. 4947 } 4948 ai = ri.activityInfo; 4949 comp = new ComponentName(ai.applicationInfo.packageName, 4950 ai.name); 4951 } else { 4952 ai = getActivityInfo(comp, flags, userId); 4953 if (ai == null) { 4954 continue; 4955 } 4956 } 4957 4958 // Look for any generic query activities that are duplicates 4959 // of this specific one, and remove them from the results. 4960 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4961 N = results.size(); 4962 int j; 4963 for (j=specificsPos; j<N; j++) { 4964 ResolveInfo sri = results.get(j); 4965 if ((sri.activityInfo.name.equals(comp.getClassName()) 4966 && sri.activityInfo.applicationInfo.packageName.equals( 4967 comp.getPackageName())) 4968 || (action != null && sri.filter.matchAction(action))) { 4969 results.remove(j); 4970 if (DEBUG_INTENT_MATCHING) Log.v( 4971 TAG, "Removing duplicate item from " + j 4972 + " due to specific " + specificsPos); 4973 if (ri == null) { 4974 ri = sri; 4975 } 4976 j--; 4977 N--; 4978 } 4979 } 4980 4981 // Add this specific item to its proper place. 4982 if (ri == null) { 4983 ri = new ResolveInfo(); 4984 ri.activityInfo = ai; 4985 } 4986 results.add(specificsPos, ri); 4987 ri.specificIndex = i; 4988 specificsPos++; 4989 } 4990 } 4991 4992 // Now we go through the remaining generic results and remove any 4993 // duplicate actions that are found here. 4994 N = results.size(); 4995 for (int i=specificsPos; i<N-1; i++) { 4996 final ResolveInfo rii = results.get(i); 4997 if (rii.filter == null) { 4998 continue; 4999 } 5000 5001 // Iterate over all of the actions of this result's intent 5002 // filter... typically this should be just one. 5003 final Iterator<String> it = rii.filter.actionsIterator(); 5004 if (it == null) { 5005 continue; 5006 } 5007 while (it.hasNext()) { 5008 final String action = it.next(); 5009 if (resultsAction != null && resultsAction.equals(action)) { 5010 // If this action was explicitly requested, then don't 5011 // remove things that have it. 5012 continue; 5013 } 5014 for (int j=i+1; j<N; j++) { 5015 final ResolveInfo rij = results.get(j); 5016 if (rij.filter != null && rij.filter.hasAction(action)) { 5017 results.remove(j); 5018 if (DEBUG_INTENT_MATCHING) Log.v( 5019 TAG, "Removing duplicate item from " + j 5020 + " due to action " + action + " at " + i); 5021 j--; 5022 N--; 5023 } 5024 } 5025 } 5026 5027 // If the caller didn't request filter information, drop it now 5028 // so we don't have to marshall/unmarshall it. 5029 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5030 rii.filter = null; 5031 } 5032 } 5033 5034 // Filter out the caller activity if so requested. 5035 if (caller != null) { 5036 N = results.size(); 5037 for (int i=0; i<N; i++) { 5038 ActivityInfo ainfo = results.get(i).activityInfo; 5039 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5040 && caller.getClassName().equals(ainfo.name)) { 5041 results.remove(i); 5042 break; 5043 } 5044 } 5045 } 5046 5047 // If the caller didn't request filter information, 5048 // drop them now so we don't have to 5049 // marshall/unmarshall it. 5050 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5051 N = results.size(); 5052 for (int i=0; i<N; i++) { 5053 results.get(i).filter = null; 5054 } 5055 } 5056 5057 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5058 return results; 5059 } 5060 5061 @Override 5062 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5063 int userId) { 5064 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5065 ComponentName comp = intent.getComponent(); 5066 if (comp == null) { 5067 if (intent.getSelector() != null) { 5068 intent = intent.getSelector(); 5069 comp = intent.getComponent(); 5070 } 5071 } 5072 if (comp != null) { 5073 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5074 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5075 if (ai != null) { 5076 ResolveInfo ri = new ResolveInfo(); 5077 ri.activityInfo = ai; 5078 list.add(ri); 5079 } 5080 return list; 5081 } 5082 5083 // reader 5084 synchronized (mPackages) { 5085 String pkgName = intent.getPackage(); 5086 if (pkgName == null) { 5087 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5088 } 5089 final PackageParser.Package pkg = mPackages.get(pkgName); 5090 if (pkg != null) { 5091 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5092 userId); 5093 } 5094 return null; 5095 } 5096 } 5097 5098 @Override 5099 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5100 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5101 if (!sUserManager.exists(userId)) return null; 5102 if (query != null) { 5103 if (query.size() >= 1) { 5104 // If there is more than one service with the same priority, 5105 // just arbitrarily pick the first one. 5106 return query.get(0); 5107 } 5108 } 5109 return null; 5110 } 5111 5112 @Override 5113 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5114 int userId) { 5115 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5116 ComponentName comp = intent.getComponent(); 5117 if (comp == null) { 5118 if (intent.getSelector() != null) { 5119 intent = intent.getSelector(); 5120 comp = intent.getComponent(); 5121 } 5122 } 5123 if (comp != null) { 5124 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5125 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5126 if (si != null) { 5127 final ResolveInfo ri = new ResolveInfo(); 5128 ri.serviceInfo = si; 5129 list.add(ri); 5130 } 5131 return list; 5132 } 5133 5134 // reader 5135 synchronized (mPackages) { 5136 String pkgName = intent.getPackage(); 5137 if (pkgName == null) { 5138 return mServices.queryIntent(intent, resolvedType, flags, userId); 5139 } 5140 final PackageParser.Package pkg = mPackages.get(pkgName); 5141 if (pkg != null) { 5142 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5143 userId); 5144 } 5145 return null; 5146 } 5147 } 5148 5149 @Override 5150 public List<ResolveInfo> queryIntentContentProviders( 5151 Intent intent, String resolvedType, int flags, int userId) { 5152 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5153 ComponentName comp = intent.getComponent(); 5154 if (comp == null) { 5155 if (intent.getSelector() != null) { 5156 intent = intent.getSelector(); 5157 comp = intent.getComponent(); 5158 } 5159 } 5160 if (comp != null) { 5161 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5162 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5163 if (pi != null) { 5164 final ResolveInfo ri = new ResolveInfo(); 5165 ri.providerInfo = pi; 5166 list.add(ri); 5167 } 5168 return list; 5169 } 5170 5171 // reader 5172 synchronized (mPackages) { 5173 String pkgName = intent.getPackage(); 5174 if (pkgName == null) { 5175 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5176 } 5177 final PackageParser.Package pkg = mPackages.get(pkgName); 5178 if (pkg != null) { 5179 return mProviders.queryIntentForPackage( 5180 intent, resolvedType, flags, pkg.providers, userId); 5181 } 5182 return null; 5183 } 5184 } 5185 5186 @Override 5187 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5188 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5189 5190 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5191 5192 // writer 5193 synchronized (mPackages) { 5194 ArrayList<PackageInfo> list; 5195 if (listUninstalled) { 5196 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5197 for (PackageSetting ps : mSettings.mPackages.values()) { 5198 PackageInfo pi; 5199 if (ps.pkg != null) { 5200 pi = generatePackageInfo(ps.pkg, flags, userId); 5201 } else { 5202 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5203 } 5204 if (pi != null) { 5205 list.add(pi); 5206 } 5207 } 5208 } else { 5209 list = new ArrayList<PackageInfo>(mPackages.size()); 5210 for (PackageParser.Package p : mPackages.values()) { 5211 PackageInfo pi = generatePackageInfo(p, flags, userId); 5212 if (pi != null) { 5213 list.add(pi); 5214 } 5215 } 5216 } 5217 5218 return new ParceledListSlice<PackageInfo>(list); 5219 } 5220 } 5221 5222 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5223 String[] permissions, boolean[] tmp, int flags, int userId) { 5224 int numMatch = 0; 5225 final PermissionsState permissionsState = ps.getPermissionsState(); 5226 for (int i=0; i<permissions.length; i++) { 5227 final String permission = permissions[i]; 5228 if (permissionsState.hasPermission(permission, userId)) { 5229 tmp[i] = true; 5230 numMatch++; 5231 } else { 5232 tmp[i] = false; 5233 } 5234 } 5235 if (numMatch == 0) { 5236 return; 5237 } 5238 PackageInfo pi; 5239 if (ps.pkg != null) { 5240 pi = generatePackageInfo(ps.pkg, flags, userId); 5241 } else { 5242 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5243 } 5244 // The above might return null in cases of uninstalled apps or install-state 5245 // skew across users/profiles. 5246 if (pi != null) { 5247 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5248 if (numMatch == permissions.length) { 5249 pi.requestedPermissions = permissions; 5250 } else { 5251 pi.requestedPermissions = new String[numMatch]; 5252 numMatch = 0; 5253 for (int i=0; i<permissions.length; i++) { 5254 if (tmp[i]) { 5255 pi.requestedPermissions[numMatch] = permissions[i]; 5256 numMatch++; 5257 } 5258 } 5259 } 5260 } 5261 list.add(pi); 5262 } 5263 } 5264 5265 @Override 5266 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5267 String[] permissions, int flags, int userId) { 5268 if (!sUserManager.exists(userId)) return null; 5269 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5270 5271 // writer 5272 synchronized (mPackages) { 5273 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5274 boolean[] tmpBools = new boolean[permissions.length]; 5275 if (listUninstalled) { 5276 for (PackageSetting ps : mSettings.mPackages.values()) { 5277 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5278 } 5279 } else { 5280 for (PackageParser.Package pkg : mPackages.values()) { 5281 PackageSetting ps = (PackageSetting)pkg.mExtras; 5282 if (ps != null) { 5283 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5284 userId); 5285 } 5286 } 5287 } 5288 5289 return new ParceledListSlice<PackageInfo>(list); 5290 } 5291 } 5292 5293 @Override 5294 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5295 if (!sUserManager.exists(userId)) return null; 5296 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5297 5298 // writer 5299 synchronized (mPackages) { 5300 ArrayList<ApplicationInfo> list; 5301 if (listUninstalled) { 5302 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5303 for (PackageSetting ps : mSettings.mPackages.values()) { 5304 ApplicationInfo ai; 5305 if (ps.pkg != null) { 5306 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5307 ps.readUserState(userId), userId); 5308 } else { 5309 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5310 } 5311 if (ai != null) { 5312 list.add(ai); 5313 } 5314 } 5315 } else { 5316 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5317 for (PackageParser.Package p : mPackages.values()) { 5318 if (p.mExtras != null) { 5319 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5320 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5321 if (ai != null) { 5322 list.add(ai); 5323 } 5324 } 5325 } 5326 } 5327 5328 return new ParceledListSlice<ApplicationInfo>(list); 5329 } 5330 } 5331 5332 public List<ApplicationInfo> getPersistentApplications(int flags) { 5333 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5334 5335 // reader 5336 synchronized (mPackages) { 5337 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5338 final int userId = UserHandle.getCallingUserId(); 5339 while (i.hasNext()) { 5340 final PackageParser.Package p = i.next(); 5341 if (p.applicationInfo != null 5342 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5343 && (!mSafeMode || isSystemApp(p))) { 5344 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5345 if (ps != null) { 5346 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5347 ps.readUserState(userId), userId); 5348 if (ai != null) { 5349 finalList.add(ai); 5350 } 5351 } 5352 } 5353 } 5354 } 5355 5356 return finalList; 5357 } 5358 5359 @Override 5360 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5361 if (!sUserManager.exists(userId)) return null; 5362 // reader 5363 synchronized (mPackages) { 5364 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5365 PackageSetting ps = provider != null 5366 ? mSettings.mPackages.get(provider.owner.packageName) 5367 : null; 5368 return ps != null 5369 && mSettings.isEnabledLPr(provider.info, flags, userId) 5370 && (!mSafeMode || (provider.info.applicationInfo.flags 5371 &ApplicationInfo.FLAG_SYSTEM) != 0) 5372 ? PackageParser.generateProviderInfo(provider, flags, 5373 ps.readUserState(userId), userId) 5374 : null; 5375 } 5376 } 5377 5378 /** 5379 * @deprecated 5380 */ 5381 @Deprecated 5382 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5383 // reader 5384 synchronized (mPackages) { 5385 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5386 .entrySet().iterator(); 5387 final int userId = UserHandle.getCallingUserId(); 5388 while (i.hasNext()) { 5389 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5390 PackageParser.Provider p = entry.getValue(); 5391 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5392 5393 if (ps != null && p.syncable 5394 && (!mSafeMode || (p.info.applicationInfo.flags 5395 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5396 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5397 ps.readUserState(userId), userId); 5398 if (info != null) { 5399 outNames.add(entry.getKey()); 5400 outInfo.add(info); 5401 } 5402 } 5403 } 5404 } 5405 } 5406 5407 @Override 5408 public List<ProviderInfo> queryContentProviders(String processName, 5409 int uid, int flags) { 5410 ArrayList<ProviderInfo> finalList = null; 5411 // reader 5412 synchronized (mPackages) { 5413 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5414 final int userId = processName != null ? 5415 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5416 while (i.hasNext()) { 5417 final PackageParser.Provider p = i.next(); 5418 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5419 if (ps != null && p.info.authority != null 5420 && (processName == null 5421 || (p.info.processName.equals(processName) 5422 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5423 && mSettings.isEnabledLPr(p.info, flags, userId) 5424 && (!mSafeMode 5425 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5426 if (finalList == null) { 5427 finalList = new ArrayList<ProviderInfo>(3); 5428 } 5429 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5430 ps.readUserState(userId), userId); 5431 if (info != null) { 5432 finalList.add(info); 5433 } 5434 } 5435 } 5436 } 5437 5438 if (finalList != null) { 5439 Collections.sort(finalList, mProviderInitOrderSorter); 5440 } 5441 5442 return finalList; 5443 } 5444 5445 @Override 5446 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5447 int flags) { 5448 // reader 5449 synchronized (mPackages) { 5450 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5451 return PackageParser.generateInstrumentationInfo(i, flags); 5452 } 5453 } 5454 5455 @Override 5456 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5457 int flags) { 5458 ArrayList<InstrumentationInfo> finalList = 5459 new ArrayList<InstrumentationInfo>(); 5460 5461 // reader 5462 synchronized (mPackages) { 5463 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5464 while (i.hasNext()) { 5465 final PackageParser.Instrumentation p = i.next(); 5466 if (targetPackage == null 5467 || targetPackage.equals(p.info.targetPackage)) { 5468 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5469 flags); 5470 if (ii != null) { 5471 finalList.add(ii); 5472 } 5473 } 5474 } 5475 } 5476 5477 return finalList; 5478 } 5479 5480 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5481 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5482 if (overlays == null) { 5483 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5484 return; 5485 } 5486 for (PackageParser.Package opkg : overlays.values()) { 5487 // Not much to do if idmap fails: we already logged the error 5488 // and we certainly don't want to abort installation of pkg simply 5489 // because an overlay didn't fit properly. For these reasons, 5490 // ignore the return value of createIdmapForPackagePairLI. 5491 createIdmapForPackagePairLI(pkg, opkg); 5492 } 5493 } 5494 5495 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5496 PackageParser.Package opkg) { 5497 if (!opkg.mTrustedOverlay) { 5498 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5499 opkg.baseCodePath + ": overlay not trusted"); 5500 return false; 5501 } 5502 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5503 if (overlaySet == null) { 5504 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5505 opkg.baseCodePath + " but target package has no known overlays"); 5506 return false; 5507 } 5508 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5509 // TODO: generate idmap for split APKs 5510 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5511 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5512 + opkg.baseCodePath); 5513 return false; 5514 } 5515 PackageParser.Package[] overlayArray = 5516 overlaySet.values().toArray(new PackageParser.Package[0]); 5517 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5518 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5519 return p1.mOverlayPriority - p2.mOverlayPriority; 5520 } 5521 }; 5522 Arrays.sort(overlayArray, cmp); 5523 5524 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5525 int i = 0; 5526 for (PackageParser.Package p : overlayArray) { 5527 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5528 } 5529 return true; 5530 } 5531 5532 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5533 final File[] files = dir.listFiles(); 5534 if (ArrayUtils.isEmpty(files)) { 5535 Log.d(TAG, "No files in app dir " + dir); 5536 return; 5537 } 5538 5539 if (DEBUG_PACKAGE_SCANNING) { 5540 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5541 + " flags=0x" + Integer.toHexString(parseFlags)); 5542 } 5543 5544 for (File file : files) { 5545 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5546 && !PackageInstallerService.isStageName(file.getName()); 5547 if (!isPackage) { 5548 // Ignore entries which are not packages 5549 continue; 5550 } 5551 try { 5552 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5553 scanFlags, currentTime, null); 5554 } catch (PackageManagerException e) { 5555 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5556 5557 // Delete invalid userdata apps 5558 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5559 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5560 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5561 if (file.isDirectory()) { 5562 mInstaller.rmPackageDir(file.getAbsolutePath()); 5563 } else { 5564 file.delete(); 5565 } 5566 } 5567 } 5568 } 5569 } 5570 5571 private static File getSettingsProblemFile() { 5572 File dataDir = Environment.getDataDirectory(); 5573 File systemDir = new File(dataDir, "system"); 5574 File fname = new File(systemDir, "uiderrors.txt"); 5575 return fname; 5576 } 5577 5578 static void reportSettingsProblem(int priority, String msg) { 5579 logCriticalInfo(priority, msg); 5580 } 5581 5582 static void logCriticalInfo(int priority, String msg) { 5583 Slog.println(priority, TAG, msg); 5584 EventLogTags.writePmCriticalInfo(msg); 5585 try { 5586 File fname = getSettingsProblemFile(); 5587 FileOutputStream out = new FileOutputStream(fname, true); 5588 PrintWriter pw = new FastPrintWriter(out); 5589 SimpleDateFormat formatter = new SimpleDateFormat(); 5590 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5591 pw.println(dateString + ": " + msg); 5592 pw.close(); 5593 FileUtils.setPermissions( 5594 fname.toString(), 5595 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5596 -1, -1); 5597 } catch (java.io.IOException e) { 5598 } 5599 } 5600 5601 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5602 PackageParser.Package pkg, File srcFile, int parseFlags) 5603 throws PackageManagerException { 5604 if (ps != null 5605 && ps.codePath.equals(srcFile) 5606 && ps.timeStamp == srcFile.lastModified() 5607 && !isCompatSignatureUpdateNeeded(pkg) 5608 && !isRecoverSignatureUpdateNeeded(pkg)) { 5609 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5610 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5611 ArraySet<PublicKey> signingKs; 5612 synchronized (mPackages) { 5613 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5614 } 5615 if (ps.signatures.mSignatures != null 5616 && ps.signatures.mSignatures.length != 0 5617 && signingKs != null) { 5618 // Optimization: reuse the existing cached certificates 5619 // if the package appears to be unchanged. 5620 pkg.mSignatures = ps.signatures.mSignatures; 5621 pkg.mSigningKeys = signingKs; 5622 return; 5623 } 5624 5625 Slog.w(TAG, "PackageSetting for " + ps.name 5626 + " is missing signatures. Collecting certs again to recover them."); 5627 } else { 5628 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5629 } 5630 5631 try { 5632 pp.collectCertificates(pkg, parseFlags); 5633 pp.collectManifestDigest(pkg); 5634 } catch (PackageParserException e) { 5635 throw PackageManagerException.from(e); 5636 } 5637 } 5638 5639 /* 5640 * Scan a package and return the newly parsed package. 5641 * Returns null in case of errors and the error code is stored in mLastScanError 5642 */ 5643 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5644 long currentTime, UserHandle user) throws PackageManagerException { 5645 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5646 parseFlags |= mDefParseFlags; 5647 PackageParser pp = new PackageParser(); 5648 pp.setSeparateProcesses(mSeparateProcesses); 5649 pp.setOnlyCoreApps(mOnlyCore); 5650 pp.setDisplayMetrics(mMetrics); 5651 5652 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5653 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5654 } 5655 5656 final PackageParser.Package pkg; 5657 try { 5658 pkg = pp.parsePackage(scanFile, parseFlags); 5659 } catch (PackageParserException e) { 5660 throw PackageManagerException.from(e); 5661 } 5662 5663 PackageSetting ps = null; 5664 PackageSetting updatedPkg; 5665 // reader 5666 synchronized (mPackages) { 5667 // Look to see if we already know about this package. 5668 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5669 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5670 // This package has been renamed to its original name. Let's 5671 // use that. 5672 ps = mSettings.peekPackageLPr(oldName); 5673 } 5674 // If there was no original package, see one for the real package name. 5675 if (ps == null) { 5676 ps = mSettings.peekPackageLPr(pkg.packageName); 5677 } 5678 // Check to see if this package could be hiding/updating a system 5679 // package. Must look for it either under the original or real 5680 // package name depending on our state. 5681 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5682 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5683 } 5684 boolean updatedPkgBetter = false; 5685 // First check if this is a system package that may involve an update 5686 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5687 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5688 // it needs to drop FLAG_PRIVILEGED. 5689 if (locationIsPrivileged(scanFile)) { 5690 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5691 } else { 5692 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5693 } 5694 5695 if (ps != null && !ps.codePath.equals(scanFile)) { 5696 // The path has changed from what was last scanned... check the 5697 // version of the new path against what we have stored to determine 5698 // what to do. 5699 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5700 if (pkg.mVersionCode <= ps.versionCode) { 5701 // The system package has been updated and the code path does not match 5702 // Ignore entry. Skip it. 5703 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5704 + " ignored: updated version " + ps.versionCode 5705 + " better than this " + pkg.mVersionCode); 5706 if (!updatedPkg.codePath.equals(scanFile)) { 5707 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5708 + ps.name + " changing from " + updatedPkg.codePathString 5709 + " to " + scanFile); 5710 updatedPkg.codePath = scanFile; 5711 updatedPkg.codePathString = scanFile.toString(); 5712 updatedPkg.resourcePath = scanFile; 5713 updatedPkg.resourcePathString = scanFile.toString(); 5714 } 5715 updatedPkg.pkg = pkg; 5716 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5717 "Package " + ps.name + " at " + scanFile 5718 + " ignored: updated version " + ps.versionCode 5719 + " better than this " + pkg.mVersionCode); 5720 } else { 5721 // The current app on the system partition is better than 5722 // what we have updated to on the data partition; switch 5723 // back to the system partition version. 5724 // At this point, its safely assumed that package installation for 5725 // apps in system partition will go through. If not there won't be a working 5726 // version of the app 5727 // writer 5728 synchronized (mPackages) { 5729 // Just remove the loaded entries from package lists. 5730 mPackages.remove(ps.name); 5731 } 5732 5733 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5734 + " reverting from " + ps.codePathString 5735 + ": new version " + pkg.mVersionCode 5736 + " better than installed " + ps.versionCode); 5737 5738 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5739 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5740 synchronized (mInstallLock) { 5741 args.cleanUpResourcesLI(); 5742 } 5743 synchronized (mPackages) { 5744 mSettings.enableSystemPackageLPw(ps.name); 5745 } 5746 updatedPkgBetter = true; 5747 } 5748 } 5749 } 5750 5751 if (updatedPkg != null) { 5752 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5753 // initially 5754 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5755 5756 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5757 // flag set initially 5758 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5759 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5760 } 5761 } 5762 5763 // Verify certificates against what was last scanned 5764 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5765 5766 /* 5767 * A new system app appeared, but we already had a non-system one of the 5768 * same name installed earlier. 5769 */ 5770 boolean shouldHideSystemApp = false; 5771 if (updatedPkg == null && ps != null 5772 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5773 /* 5774 * Check to make sure the signatures match first. If they don't, 5775 * wipe the installed application and its data. 5776 */ 5777 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5778 != PackageManager.SIGNATURE_MATCH) { 5779 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5780 + " signatures don't match existing userdata copy; removing"); 5781 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5782 ps = null; 5783 } else { 5784 /* 5785 * If the newly-added system app is an older version than the 5786 * already installed version, hide it. It will be scanned later 5787 * and re-added like an update. 5788 */ 5789 if (pkg.mVersionCode <= ps.versionCode) { 5790 shouldHideSystemApp = true; 5791 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5792 + " but new version " + pkg.mVersionCode + " better than installed " 5793 + ps.versionCode + "; hiding system"); 5794 } else { 5795 /* 5796 * The newly found system app is a newer version that the 5797 * one previously installed. Simply remove the 5798 * already-installed application and replace it with our own 5799 * while keeping the application data. 5800 */ 5801 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5802 + " reverting from " + ps.codePathString + ": new version " 5803 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5804 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5805 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5806 synchronized (mInstallLock) { 5807 args.cleanUpResourcesLI(); 5808 } 5809 } 5810 } 5811 } 5812 5813 // The apk is forward locked (not public) if its code and resources 5814 // are kept in different files. (except for app in either system or 5815 // vendor path). 5816 // TODO grab this value from PackageSettings 5817 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5818 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5819 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5820 } 5821 } 5822 5823 // TODO: extend to support forward-locked splits 5824 String resourcePath = null; 5825 String baseResourcePath = null; 5826 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5827 if (ps != null && ps.resourcePathString != null) { 5828 resourcePath = ps.resourcePathString; 5829 baseResourcePath = ps.resourcePathString; 5830 } else { 5831 // Should not happen at all. Just log an error. 5832 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5833 } 5834 } else { 5835 resourcePath = pkg.codePath; 5836 baseResourcePath = pkg.baseCodePath; 5837 } 5838 5839 // Set application objects path explicitly. 5840 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5841 pkg.applicationInfo.setCodePath(pkg.codePath); 5842 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5843 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5844 pkg.applicationInfo.setResourcePath(resourcePath); 5845 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5846 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5847 5848 // Note that we invoke the following method only if we are about to unpack an application 5849 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5850 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5851 5852 /* 5853 * If the system app should be overridden by a previously installed 5854 * data, hide the system app now and let the /data/app scan pick it up 5855 * again. 5856 */ 5857 if (shouldHideSystemApp) { 5858 synchronized (mPackages) { 5859 /* 5860 * We have to grant systems permissions before we hide, because 5861 * grantPermissions will assume the package update is trying to 5862 * expand its permissions. 5863 */ 5864 grantPermissionsLPw(pkg, true, pkg.packageName); 5865 mSettings.disableSystemPackageLPw(pkg.packageName); 5866 } 5867 } 5868 5869 return scannedPkg; 5870 } 5871 5872 private static String fixProcessName(String defProcessName, 5873 String processName, int uid) { 5874 if (processName == null) { 5875 return defProcessName; 5876 } 5877 return processName; 5878 } 5879 5880 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5881 throws PackageManagerException { 5882 if (pkgSetting.signatures.mSignatures != null) { 5883 // Already existing package. Make sure signatures match 5884 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5885 == PackageManager.SIGNATURE_MATCH; 5886 if (!match) { 5887 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5888 == PackageManager.SIGNATURE_MATCH; 5889 } 5890 if (!match) { 5891 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5892 == PackageManager.SIGNATURE_MATCH; 5893 } 5894 if (!match) { 5895 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5896 + pkg.packageName + " signatures do not match the " 5897 + "previously installed version; ignoring!"); 5898 } 5899 } 5900 5901 // Check for shared user signatures 5902 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5903 // Already existing package. Make sure signatures match 5904 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5905 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5906 if (!match) { 5907 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5908 == PackageManager.SIGNATURE_MATCH; 5909 } 5910 if (!match) { 5911 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5912 == PackageManager.SIGNATURE_MATCH; 5913 } 5914 if (!match) { 5915 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5916 "Package " + pkg.packageName 5917 + " has no signatures that match those in shared user " 5918 + pkgSetting.sharedUser.name + "; ignoring!"); 5919 } 5920 } 5921 } 5922 5923 /** 5924 * Enforces that only the system UID or root's UID can call a method exposed 5925 * via Binder. 5926 * 5927 * @param message used as message if SecurityException is thrown 5928 * @throws SecurityException if the caller is not system or root 5929 */ 5930 private static final void enforceSystemOrRoot(String message) { 5931 final int uid = Binder.getCallingUid(); 5932 if (uid != Process.SYSTEM_UID && uid != 0) { 5933 throw new SecurityException(message); 5934 } 5935 } 5936 5937 @Override 5938 public void performBootDexOpt() { 5939 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5940 5941 // Before everything else, see whether we need to fstrim. 5942 try { 5943 IMountService ms = PackageHelper.getMountService(); 5944 if (ms != null) { 5945 final boolean isUpgrade = isUpgrade(); 5946 boolean doTrim = isUpgrade; 5947 if (doTrim) { 5948 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5949 } else { 5950 final long interval = android.provider.Settings.Global.getLong( 5951 mContext.getContentResolver(), 5952 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5953 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5954 if (interval > 0) { 5955 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5956 if (timeSinceLast > interval) { 5957 doTrim = true; 5958 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5959 + "; running immediately"); 5960 } 5961 } 5962 } 5963 if (doTrim) { 5964 if (!isFirstBoot()) { 5965 try { 5966 ActivityManagerNative.getDefault().showBootMessage( 5967 mContext.getResources().getString( 5968 R.string.android_upgrading_fstrim), true); 5969 } catch (RemoteException e) { 5970 } 5971 } 5972 ms.runMaintenance(); 5973 } 5974 } else { 5975 Slog.e(TAG, "Mount service unavailable!"); 5976 } 5977 } catch (RemoteException e) { 5978 // Can't happen; MountService is local 5979 } 5980 5981 final ArraySet<PackageParser.Package> pkgs; 5982 synchronized (mPackages) { 5983 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5984 } 5985 5986 if (pkgs != null) { 5987 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5988 // in case the device runs out of space. 5989 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5990 // Give priority to core apps. 5991 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5992 PackageParser.Package pkg = it.next(); 5993 if (pkg.coreApp) { 5994 if (DEBUG_DEXOPT) { 5995 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5996 } 5997 sortedPkgs.add(pkg); 5998 it.remove(); 5999 } 6000 } 6001 // Give priority to system apps that listen for pre boot complete. 6002 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6003 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6004 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6005 PackageParser.Package pkg = it.next(); 6006 if (pkgNames.contains(pkg.packageName)) { 6007 if (DEBUG_DEXOPT) { 6008 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6009 } 6010 sortedPkgs.add(pkg); 6011 it.remove(); 6012 } 6013 } 6014 // Give priority to system apps. 6015 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6016 PackageParser.Package pkg = it.next(); 6017 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6018 if (DEBUG_DEXOPT) { 6019 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6020 } 6021 sortedPkgs.add(pkg); 6022 it.remove(); 6023 } 6024 } 6025 // Give priority to updated system apps. 6026 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6027 PackageParser.Package pkg = it.next(); 6028 if (pkg.isUpdatedSystemApp()) { 6029 if (DEBUG_DEXOPT) { 6030 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6031 } 6032 sortedPkgs.add(pkg); 6033 it.remove(); 6034 } 6035 } 6036 // Give priority to apps that listen for boot complete. 6037 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6038 pkgNames = getPackageNamesForIntent(intent); 6039 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6040 PackageParser.Package pkg = it.next(); 6041 if (pkgNames.contains(pkg.packageName)) { 6042 if (DEBUG_DEXOPT) { 6043 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6044 } 6045 sortedPkgs.add(pkg); 6046 it.remove(); 6047 } 6048 } 6049 // Filter out packages that aren't recently used. 6050 filterRecentlyUsedApps(pkgs); 6051 // Add all remaining apps. 6052 for (PackageParser.Package pkg : pkgs) { 6053 if (DEBUG_DEXOPT) { 6054 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6055 } 6056 sortedPkgs.add(pkg); 6057 } 6058 6059 // If we want to be lazy, filter everything that wasn't recently used. 6060 if (mLazyDexOpt) { 6061 filterRecentlyUsedApps(sortedPkgs); 6062 } 6063 6064 int i = 0; 6065 int total = sortedPkgs.size(); 6066 File dataDir = Environment.getDataDirectory(); 6067 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6068 if (lowThreshold == 0) { 6069 throw new IllegalStateException("Invalid low memory threshold"); 6070 } 6071 for (PackageParser.Package pkg : sortedPkgs) { 6072 long usableSpace = dataDir.getUsableSpace(); 6073 if (usableSpace < lowThreshold) { 6074 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6075 break; 6076 } 6077 performBootDexOpt(pkg, ++i, total); 6078 } 6079 } 6080 } 6081 6082 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6083 // Filter out packages that aren't recently used. 6084 // 6085 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6086 // should do a full dexopt. 6087 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6088 int total = pkgs.size(); 6089 int skipped = 0; 6090 long now = System.currentTimeMillis(); 6091 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6092 PackageParser.Package pkg = i.next(); 6093 long then = pkg.mLastPackageUsageTimeInMills; 6094 if (then + mDexOptLRUThresholdInMills < now) { 6095 if (DEBUG_DEXOPT) { 6096 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6097 ((then == 0) ? "never" : new Date(then))); 6098 } 6099 i.remove(); 6100 skipped++; 6101 } 6102 } 6103 if (DEBUG_DEXOPT) { 6104 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6105 } 6106 } 6107 } 6108 6109 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6110 List<ResolveInfo> ris = null; 6111 try { 6112 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6113 intent, null, 0, UserHandle.USER_OWNER); 6114 } catch (RemoteException e) { 6115 } 6116 ArraySet<String> pkgNames = new ArraySet<String>(); 6117 if (ris != null) { 6118 for (ResolveInfo ri : ris) { 6119 pkgNames.add(ri.activityInfo.packageName); 6120 } 6121 } 6122 return pkgNames; 6123 } 6124 6125 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6126 if (DEBUG_DEXOPT) { 6127 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6128 } 6129 if (!isFirstBoot()) { 6130 try { 6131 ActivityManagerNative.getDefault().showBootMessage( 6132 mContext.getResources().getString(R.string.android_upgrading_apk, 6133 curr, total), true); 6134 } catch (RemoteException e) { 6135 } 6136 } 6137 PackageParser.Package p = pkg; 6138 synchronized (mInstallLock) { 6139 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6140 false /* force dex */, false /* defer */, true /* include dependencies */); 6141 } 6142 } 6143 6144 @Override 6145 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6146 return performDexOpt(packageName, instructionSet, false); 6147 } 6148 6149 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6150 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6151 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6152 if (!dexopt && !updateUsage) { 6153 // We aren't going to dexopt or update usage, so bail early. 6154 return false; 6155 } 6156 PackageParser.Package p; 6157 final String targetInstructionSet; 6158 synchronized (mPackages) { 6159 p = mPackages.get(packageName); 6160 if (p == null) { 6161 return false; 6162 } 6163 if (updateUsage) { 6164 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6165 } 6166 mPackageUsage.write(false); 6167 if (!dexopt) { 6168 // We aren't going to dexopt, so bail early. 6169 return false; 6170 } 6171 6172 targetInstructionSet = instructionSet != null ? instructionSet : 6173 getPrimaryInstructionSet(p.applicationInfo); 6174 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6175 return false; 6176 } 6177 } 6178 long callingId = Binder.clearCallingIdentity(); 6179 try { 6180 synchronized (mInstallLock) { 6181 final String[] instructionSets = new String[] { targetInstructionSet }; 6182 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6183 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6184 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6185 } 6186 } finally { 6187 Binder.restoreCallingIdentity(callingId); 6188 } 6189 } 6190 6191 public ArraySet<String> getPackagesThatNeedDexOpt() { 6192 ArraySet<String> pkgs = null; 6193 synchronized (mPackages) { 6194 for (PackageParser.Package p : mPackages.values()) { 6195 if (DEBUG_DEXOPT) { 6196 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6197 } 6198 if (!p.mDexOptPerformed.isEmpty()) { 6199 continue; 6200 } 6201 if (pkgs == null) { 6202 pkgs = new ArraySet<String>(); 6203 } 6204 pkgs.add(p.packageName); 6205 } 6206 } 6207 return pkgs; 6208 } 6209 6210 public void shutdown() { 6211 mPackageUsage.write(true); 6212 } 6213 6214 @Override 6215 public void forceDexOpt(String packageName) { 6216 enforceSystemOrRoot("forceDexOpt"); 6217 6218 PackageParser.Package pkg; 6219 synchronized (mPackages) { 6220 pkg = mPackages.get(packageName); 6221 if (pkg == null) { 6222 throw new IllegalArgumentException("Missing package: " + packageName); 6223 } 6224 } 6225 6226 synchronized (mInstallLock) { 6227 final String[] instructionSets = new String[] { 6228 getPrimaryInstructionSet(pkg.applicationInfo) }; 6229 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6230 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6231 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6232 throw new IllegalStateException("Failed to dexopt: " + res); 6233 } 6234 } 6235 } 6236 6237 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6238 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6239 Slog.w(TAG, "Unable to update from " + oldPkg.name 6240 + " to " + newPkg.packageName 6241 + ": old package not in system partition"); 6242 return false; 6243 } else if (mPackages.get(oldPkg.name) != null) { 6244 Slog.w(TAG, "Unable to update from " + oldPkg.name 6245 + " to " + newPkg.packageName 6246 + ": old package still exists"); 6247 return false; 6248 } 6249 return true; 6250 } 6251 6252 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6253 int[] users = sUserManager.getUserIds(); 6254 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6255 if (res < 0) { 6256 return res; 6257 } 6258 for (int user : users) { 6259 if (user != 0) { 6260 res = mInstaller.createUserData(volumeUuid, packageName, 6261 UserHandle.getUid(user, uid), user, seinfo); 6262 if (res < 0) { 6263 return res; 6264 } 6265 } 6266 } 6267 return res; 6268 } 6269 6270 private int removeDataDirsLI(String volumeUuid, String packageName) { 6271 int[] users = sUserManager.getUserIds(); 6272 int res = 0; 6273 for (int user : users) { 6274 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6275 if (resInner < 0) { 6276 res = resInner; 6277 } 6278 } 6279 6280 return res; 6281 } 6282 6283 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6284 int[] users = sUserManager.getUserIds(); 6285 int res = 0; 6286 for (int user : users) { 6287 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6288 if (resInner < 0) { 6289 res = resInner; 6290 } 6291 } 6292 return res; 6293 } 6294 6295 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6296 PackageParser.Package changingLib) { 6297 if (file.path != null) { 6298 usesLibraryFiles.add(file.path); 6299 return; 6300 } 6301 PackageParser.Package p = mPackages.get(file.apk); 6302 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6303 // If we are doing this while in the middle of updating a library apk, 6304 // then we need to make sure to use that new apk for determining the 6305 // dependencies here. (We haven't yet finished committing the new apk 6306 // to the package manager state.) 6307 if (p == null || p.packageName.equals(changingLib.packageName)) { 6308 p = changingLib; 6309 } 6310 } 6311 if (p != null) { 6312 usesLibraryFiles.addAll(p.getAllCodePaths()); 6313 } 6314 } 6315 6316 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6317 PackageParser.Package changingLib) throws PackageManagerException { 6318 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6319 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6320 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6321 for (int i=0; i<N; i++) { 6322 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6323 if (file == null) { 6324 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6325 "Package " + pkg.packageName + " requires unavailable shared library " 6326 + pkg.usesLibraries.get(i) + "; failing!"); 6327 } 6328 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6329 } 6330 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6331 for (int i=0; i<N; i++) { 6332 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6333 if (file == null) { 6334 Slog.w(TAG, "Package " + pkg.packageName 6335 + " desires unavailable shared library " 6336 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6337 } else { 6338 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6339 } 6340 } 6341 N = usesLibraryFiles.size(); 6342 if (N > 0) { 6343 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6344 } else { 6345 pkg.usesLibraryFiles = null; 6346 } 6347 } 6348 } 6349 6350 private static boolean hasString(List<String> list, List<String> which) { 6351 if (list == null) { 6352 return false; 6353 } 6354 for (int i=list.size()-1; i>=0; i--) { 6355 for (int j=which.size()-1; j>=0; j--) { 6356 if (which.get(j).equals(list.get(i))) { 6357 return true; 6358 } 6359 } 6360 } 6361 return false; 6362 } 6363 6364 private void updateAllSharedLibrariesLPw() { 6365 for (PackageParser.Package pkg : mPackages.values()) { 6366 try { 6367 updateSharedLibrariesLPw(pkg, null); 6368 } catch (PackageManagerException e) { 6369 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6370 } 6371 } 6372 } 6373 6374 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6375 PackageParser.Package changingPkg) { 6376 ArrayList<PackageParser.Package> res = null; 6377 for (PackageParser.Package pkg : mPackages.values()) { 6378 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6379 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6380 if (res == null) { 6381 res = new ArrayList<PackageParser.Package>(); 6382 } 6383 res.add(pkg); 6384 try { 6385 updateSharedLibrariesLPw(pkg, changingPkg); 6386 } catch (PackageManagerException e) { 6387 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6388 } 6389 } 6390 } 6391 return res; 6392 } 6393 6394 /** 6395 * Derive the value of the {@code cpuAbiOverride} based on the provided 6396 * value and an optional stored value from the package settings. 6397 */ 6398 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6399 String cpuAbiOverride = null; 6400 6401 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6402 cpuAbiOverride = null; 6403 } else if (abiOverride != null) { 6404 cpuAbiOverride = abiOverride; 6405 } else if (settings != null) { 6406 cpuAbiOverride = settings.cpuAbiOverrideString; 6407 } 6408 6409 return cpuAbiOverride; 6410 } 6411 6412 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6413 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6414 boolean success = false; 6415 try { 6416 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6417 currentTime, user); 6418 success = true; 6419 return res; 6420 } finally { 6421 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6422 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6423 } 6424 } 6425 } 6426 6427 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6428 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6429 final File scanFile = new File(pkg.codePath); 6430 if (pkg.applicationInfo.getCodePath() == null || 6431 pkg.applicationInfo.getResourcePath() == null) { 6432 // Bail out. The resource and code paths haven't been set. 6433 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6434 "Code and resource paths haven't been set correctly"); 6435 } 6436 6437 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6438 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6439 } else { 6440 // Only allow system apps to be flagged as core apps. 6441 pkg.coreApp = false; 6442 } 6443 6444 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6445 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6446 } 6447 6448 if (mCustomResolverComponentName != null && 6449 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6450 setUpCustomResolverActivity(pkg); 6451 } 6452 6453 if (pkg.packageName.equals("android")) { 6454 synchronized (mPackages) { 6455 if (mAndroidApplication != null) { 6456 Slog.w(TAG, "*************************************************"); 6457 Slog.w(TAG, "Core android package being redefined. Skipping."); 6458 Slog.w(TAG, " file=" + scanFile); 6459 Slog.w(TAG, "*************************************************"); 6460 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6461 "Core android package being redefined. Skipping."); 6462 } 6463 6464 // Set up information for our fall-back user intent resolution activity. 6465 mPlatformPackage = pkg; 6466 pkg.mVersionCode = mSdkVersion; 6467 mAndroidApplication = pkg.applicationInfo; 6468 6469 if (!mResolverReplaced) { 6470 mResolveActivity.applicationInfo = mAndroidApplication; 6471 mResolveActivity.name = ResolverActivity.class.getName(); 6472 mResolveActivity.packageName = mAndroidApplication.packageName; 6473 mResolveActivity.processName = "system:ui"; 6474 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6475 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6476 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6477 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6478 mResolveActivity.exported = true; 6479 mResolveActivity.enabled = true; 6480 mResolveInfo.activityInfo = mResolveActivity; 6481 mResolveInfo.priority = 0; 6482 mResolveInfo.preferredOrder = 0; 6483 mResolveInfo.match = 0; 6484 mResolveComponentName = new ComponentName( 6485 mAndroidApplication.packageName, mResolveActivity.name); 6486 } 6487 } 6488 } 6489 6490 if (DEBUG_PACKAGE_SCANNING) { 6491 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6492 Log.d(TAG, "Scanning package " + pkg.packageName); 6493 } 6494 6495 if (mPackages.containsKey(pkg.packageName) 6496 || mSharedLibraries.containsKey(pkg.packageName)) { 6497 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6498 "Application package " + pkg.packageName 6499 + " already installed. Skipping duplicate."); 6500 } 6501 6502 // If we're only installing presumed-existing packages, require that the 6503 // scanned APK is both already known and at the path previously established 6504 // for it. Previously unknown packages we pick up normally, but if we have an 6505 // a priori expectation about this package's install presence, enforce it. 6506 // With a singular exception for new system packages. When an OTA contains 6507 // a new system package, we allow the codepath to change from a system location 6508 // to the user-installed location. If we don't allow this change, any newer, 6509 // user-installed version of the application will be ignored. 6510 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6511 if (mExpectingBetter.containsKey(pkg.packageName)) { 6512 logCriticalInfo(Log.WARN, 6513 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6514 } else { 6515 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6516 if (known != null) { 6517 if (DEBUG_PACKAGE_SCANNING) { 6518 Log.d(TAG, "Examining " + pkg.codePath 6519 + " and requiring known paths " + known.codePathString 6520 + " & " + known.resourcePathString); 6521 } 6522 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6523 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6524 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6525 "Application package " + pkg.packageName 6526 + " found at " + pkg.applicationInfo.getCodePath() 6527 + " but expected at " + known.codePathString + "; ignoring."); 6528 } 6529 } 6530 } 6531 } 6532 6533 // Initialize package source and resource directories 6534 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6535 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6536 6537 SharedUserSetting suid = null; 6538 PackageSetting pkgSetting = null; 6539 6540 if (!isSystemApp(pkg)) { 6541 // Only system apps can use these features. 6542 pkg.mOriginalPackages = null; 6543 pkg.mRealPackage = null; 6544 pkg.mAdoptPermissions = null; 6545 } 6546 6547 // writer 6548 synchronized (mPackages) { 6549 if (pkg.mSharedUserId != null) { 6550 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6551 if (suid == null) { 6552 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6553 "Creating application package " + pkg.packageName 6554 + " for shared user failed"); 6555 } 6556 if (DEBUG_PACKAGE_SCANNING) { 6557 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6558 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6559 + "): packages=" + suid.packages); 6560 } 6561 } 6562 6563 // Check if we are renaming from an original package name. 6564 PackageSetting origPackage = null; 6565 String realName = null; 6566 if (pkg.mOriginalPackages != null) { 6567 // This package may need to be renamed to a previously 6568 // installed name. Let's check on that... 6569 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6570 if (pkg.mOriginalPackages.contains(renamed)) { 6571 // This package had originally been installed as the 6572 // original name, and we have already taken care of 6573 // transitioning to the new one. Just update the new 6574 // one to continue using the old name. 6575 realName = pkg.mRealPackage; 6576 if (!pkg.packageName.equals(renamed)) { 6577 // Callers into this function may have already taken 6578 // care of renaming the package; only do it here if 6579 // it is not already done. 6580 pkg.setPackageName(renamed); 6581 } 6582 6583 } else { 6584 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6585 if ((origPackage = mSettings.peekPackageLPr( 6586 pkg.mOriginalPackages.get(i))) != null) { 6587 // We do have the package already installed under its 6588 // original name... should we use it? 6589 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6590 // New package is not compatible with original. 6591 origPackage = null; 6592 continue; 6593 } else if (origPackage.sharedUser != null) { 6594 // Make sure uid is compatible between packages. 6595 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6596 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6597 + " to " + pkg.packageName + ": old uid " 6598 + origPackage.sharedUser.name 6599 + " differs from " + pkg.mSharedUserId); 6600 origPackage = null; 6601 continue; 6602 } 6603 } else { 6604 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6605 + pkg.packageName + " to old name " + origPackage.name); 6606 } 6607 break; 6608 } 6609 } 6610 } 6611 } 6612 6613 if (mTransferedPackages.contains(pkg.packageName)) { 6614 Slog.w(TAG, "Package " + pkg.packageName 6615 + " was transferred to another, but its .apk remains"); 6616 } 6617 6618 // Just create the setting, don't add it yet. For already existing packages 6619 // the PkgSetting exists already and doesn't have to be created. 6620 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6621 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6622 pkg.applicationInfo.primaryCpuAbi, 6623 pkg.applicationInfo.secondaryCpuAbi, 6624 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6625 user, false); 6626 if (pkgSetting == null) { 6627 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6628 "Creating application package " + pkg.packageName + " failed"); 6629 } 6630 6631 if (pkgSetting.origPackage != null) { 6632 // If we are first transitioning from an original package, 6633 // fix up the new package's name now. We need to do this after 6634 // looking up the package under its new name, so getPackageLP 6635 // can take care of fiddling things correctly. 6636 pkg.setPackageName(origPackage.name); 6637 6638 // File a report about this. 6639 String msg = "New package " + pkgSetting.realName 6640 + " renamed to replace old package " + pkgSetting.name; 6641 reportSettingsProblem(Log.WARN, msg); 6642 6643 // Make a note of it. 6644 mTransferedPackages.add(origPackage.name); 6645 6646 // No longer need to retain this. 6647 pkgSetting.origPackage = null; 6648 } 6649 6650 if (realName != null) { 6651 // Make a note of it. 6652 mTransferedPackages.add(pkg.packageName); 6653 } 6654 6655 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6656 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6657 } 6658 6659 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6660 // Check all shared libraries and map to their actual file path. 6661 // We only do this here for apps not on a system dir, because those 6662 // are the only ones that can fail an install due to this. We 6663 // will take care of the system apps by updating all of their 6664 // library paths after the scan is done. 6665 updateSharedLibrariesLPw(pkg, null); 6666 } 6667 6668 if (mFoundPolicyFile) { 6669 SELinuxMMAC.assignSeinfoValue(pkg); 6670 } 6671 6672 pkg.applicationInfo.uid = pkgSetting.appId; 6673 pkg.mExtras = pkgSetting; 6674 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6675 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6676 // We just determined the app is signed correctly, so bring 6677 // over the latest parsed certs. 6678 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6679 } else { 6680 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6681 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6682 "Package " + pkg.packageName + " upgrade keys do not match the " 6683 + "previously installed version"); 6684 } else { 6685 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6686 String msg = "System package " + pkg.packageName 6687 + " signature changed; retaining data."; 6688 reportSettingsProblem(Log.WARN, msg); 6689 } 6690 } 6691 } else { 6692 try { 6693 verifySignaturesLP(pkgSetting, pkg); 6694 // We just determined the app is signed correctly, so bring 6695 // over the latest parsed certs. 6696 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6697 } catch (PackageManagerException e) { 6698 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6699 throw e; 6700 } 6701 // The signature has changed, but this package is in the system 6702 // image... let's recover! 6703 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6704 // However... if this package is part of a shared user, but it 6705 // doesn't match the signature of the shared user, let's fail. 6706 // What this means is that you can't change the signatures 6707 // associated with an overall shared user, which doesn't seem all 6708 // that unreasonable. 6709 if (pkgSetting.sharedUser != null) { 6710 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6711 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6712 throw new PackageManagerException( 6713 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6714 "Signature mismatch for shared user : " 6715 + pkgSetting.sharedUser); 6716 } 6717 } 6718 // File a report about this. 6719 String msg = "System package " + pkg.packageName 6720 + " signature changed; retaining data."; 6721 reportSettingsProblem(Log.WARN, msg); 6722 } 6723 } 6724 // Verify that this new package doesn't have any content providers 6725 // that conflict with existing packages. Only do this if the 6726 // package isn't already installed, since we don't want to break 6727 // things that are installed. 6728 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6729 final int N = pkg.providers.size(); 6730 int i; 6731 for (i=0; i<N; i++) { 6732 PackageParser.Provider p = pkg.providers.get(i); 6733 if (p.info.authority != null) { 6734 String names[] = p.info.authority.split(";"); 6735 for (int j = 0; j < names.length; j++) { 6736 if (mProvidersByAuthority.containsKey(names[j])) { 6737 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6738 final String otherPackageName = 6739 ((other != null && other.getComponentName() != null) ? 6740 other.getComponentName().getPackageName() : "?"); 6741 throw new PackageManagerException( 6742 INSTALL_FAILED_CONFLICTING_PROVIDER, 6743 "Can't install because provider name " + names[j] 6744 + " (in package " + pkg.applicationInfo.packageName 6745 + ") is already used by " + otherPackageName); 6746 } 6747 } 6748 } 6749 } 6750 } 6751 6752 if (pkg.mAdoptPermissions != null) { 6753 // This package wants to adopt ownership of permissions from 6754 // another package. 6755 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6756 final String origName = pkg.mAdoptPermissions.get(i); 6757 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6758 if (orig != null) { 6759 if (verifyPackageUpdateLPr(orig, pkg)) { 6760 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6761 + pkg.packageName); 6762 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6763 } 6764 } 6765 } 6766 } 6767 } 6768 6769 final String pkgName = pkg.packageName; 6770 6771 final long scanFileTime = scanFile.lastModified(); 6772 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6773 pkg.applicationInfo.processName = fixProcessName( 6774 pkg.applicationInfo.packageName, 6775 pkg.applicationInfo.processName, 6776 pkg.applicationInfo.uid); 6777 6778 File dataPath; 6779 if (mPlatformPackage == pkg) { 6780 // The system package is special. 6781 dataPath = new File(Environment.getDataDirectory(), "system"); 6782 6783 pkg.applicationInfo.dataDir = dataPath.getPath(); 6784 6785 } else { 6786 // This is a normal package, need to make its data directory. 6787 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6788 UserHandle.USER_OWNER, pkg.packageName); 6789 6790 boolean uidError = false; 6791 if (dataPath.exists()) { 6792 int currentUid = 0; 6793 try { 6794 StructStat stat = Os.stat(dataPath.getPath()); 6795 currentUid = stat.st_uid; 6796 } catch (ErrnoException e) { 6797 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6798 } 6799 6800 // If we have mismatched owners for the data path, we have a problem. 6801 if (currentUid != pkg.applicationInfo.uid) { 6802 boolean recovered = false; 6803 if (currentUid == 0) { 6804 // The directory somehow became owned by root. Wow. 6805 // This is probably because the system was stopped while 6806 // installd was in the middle of messing with its libs 6807 // directory. Ask installd to fix that. 6808 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6809 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6810 if (ret >= 0) { 6811 recovered = true; 6812 String msg = "Package " + pkg.packageName 6813 + " unexpectedly changed to uid 0; recovered to " + 6814 + pkg.applicationInfo.uid; 6815 reportSettingsProblem(Log.WARN, msg); 6816 } 6817 } 6818 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6819 || (scanFlags&SCAN_BOOTING) != 0)) { 6820 // If this is a system app, we can at least delete its 6821 // current data so the application will still work. 6822 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6823 if (ret >= 0) { 6824 // TODO: Kill the processes first 6825 // Old data gone! 6826 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6827 ? "System package " : "Third party package "; 6828 String msg = prefix + pkg.packageName 6829 + " has changed from uid: " 6830 + currentUid + " to " 6831 + pkg.applicationInfo.uid + "; old data erased"; 6832 reportSettingsProblem(Log.WARN, msg); 6833 recovered = true; 6834 6835 // And now re-install the app. 6836 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6837 pkg.applicationInfo.seinfo); 6838 if (ret == -1) { 6839 // Ack should not happen! 6840 msg = prefix + pkg.packageName 6841 + " could not have data directory re-created after delete."; 6842 reportSettingsProblem(Log.WARN, msg); 6843 throw new PackageManagerException( 6844 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6845 } 6846 } 6847 if (!recovered) { 6848 mHasSystemUidErrors = true; 6849 } 6850 } else if (!recovered) { 6851 // If we allow this install to proceed, we will be broken. 6852 // Abort, abort! 6853 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6854 "scanPackageLI"); 6855 } 6856 if (!recovered) { 6857 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6858 + pkg.applicationInfo.uid + "/fs_" 6859 + currentUid; 6860 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6861 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6862 String msg = "Package " + pkg.packageName 6863 + " has mismatched uid: " 6864 + currentUid + " on disk, " 6865 + pkg.applicationInfo.uid + " in settings"; 6866 // writer 6867 synchronized (mPackages) { 6868 mSettings.mReadMessages.append(msg); 6869 mSettings.mReadMessages.append('\n'); 6870 uidError = true; 6871 if (!pkgSetting.uidError) { 6872 reportSettingsProblem(Log.ERROR, msg); 6873 } 6874 } 6875 } 6876 } 6877 pkg.applicationInfo.dataDir = dataPath.getPath(); 6878 if (mShouldRestoreconData) { 6879 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6880 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6881 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6882 } 6883 } else { 6884 if (DEBUG_PACKAGE_SCANNING) { 6885 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6886 Log.v(TAG, "Want this data dir: " + dataPath); 6887 } 6888 //invoke installer to do the actual installation 6889 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6890 pkg.applicationInfo.seinfo); 6891 if (ret < 0) { 6892 // Error from installer 6893 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6894 "Unable to create data dirs [errorCode=" + ret + "]"); 6895 } 6896 6897 if (dataPath.exists()) { 6898 pkg.applicationInfo.dataDir = dataPath.getPath(); 6899 } else { 6900 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6901 pkg.applicationInfo.dataDir = null; 6902 } 6903 } 6904 6905 pkgSetting.uidError = uidError; 6906 } 6907 6908 final String path = scanFile.getPath(); 6909 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6910 6911 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6912 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6913 6914 // Some system apps still use directory structure for native libraries 6915 // in which case we might end up not detecting abi solely based on apk 6916 // structure. Try to detect abi based on directory structure. 6917 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6918 pkg.applicationInfo.primaryCpuAbi == null) { 6919 setBundledAppAbisAndRoots(pkg, pkgSetting); 6920 setNativeLibraryPaths(pkg); 6921 } 6922 6923 } else { 6924 if ((scanFlags & SCAN_MOVE) != 0) { 6925 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6926 // but we already have this packages package info in the PackageSetting. We just 6927 // use that and derive the native library path based on the new codepath. 6928 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6929 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6930 } 6931 6932 // Set native library paths again. For moves, the path will be updated based on the 6933 // ABIs we've determined above. For non-moves, the path will be updated based on the 6934 // ABIs we determined during compilation, but the path will depend on the final 6935 // package path (after the rename away from the stage path). 6936 setNativeLibraryPaths(pkg); 6937 } 6938 6939 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6940 final int[] userIds = sUserManager.getUserIds(); 6941 synchronized (mInstallLock) { 6942 // Make sure all user data directories are ready to roll; we're okay 6943 // if they already exist 6944 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6945 for (int userId : userIds) { 6946 if (userId != 0) { 6947 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6948 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6949 pkg.applicationInfo.seinfo); 6950 } 6951 } 6952 } 6953 6954 // Create a native library symlink only if we have native libraries 6955 // and if the native libraries are 32 bit libraries. We do not provide 6956 // this symlink for 64 bit libraries. 6957 if (pkg.applicationInfo.primaryCpuAbi != null && 6958 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6959 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6960 for (int userId : userIds) { 6961 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6962 nativeLibPath, userId) < 0) { 6963 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6964 "Failed linking native library dir (user=" + userId + ")"); 6965 } 6966 } 6967 } 6968 } 6969 6970 // This is a special case for the "system" package, where the ABI is 6971 // dictated by the zygote configuration (and init.rc). We should keep track 6972 // of this ABI so that we can deal with "normal" applications that run under 6973 // the same UID correctly. 6974 if (mPlatformPackage == pkg) { 6975 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6976 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6977 } 6978 6979 // If there's a mismatch between the abi-override in the package setting 6980 // and the abiOverride specified for the install. Warn about this because we 6981 // would've already compiled the app without taking the package setting into 6982 // account. 6983 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6984 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6985 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6986 " for package: " + pkg.packageName); 6987 } 6988 } 6989 6990 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6991 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6992 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6993 6994 // Copy the derived override back to the parsed package, so that we can 6995 // update the package settings accordingly. 6996 pkg.cpuAbiOverride = cpuAbiOverride; 6997 6998 if (DEBUG_ABI_SELECTION) { 6999 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7000 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7001 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7002 } 7003 7004 // Push the derived path down into PackageSettings so we know what to 7005 // clean up at uninstall time. 7006 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7007 7008 if (DEBUG_ABI_SELECTION) { 7009 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7010 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7011 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7012 } 7013 7014 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7015 // We don't do this here during boot because we can do it all 7016 // at once after scanning all existing packages. 7017 // 7018 // We also do this *before* we perform dexopt on this package, so that 7019 // we can avoid redundant dexopts, and also to make sure we've got the 7020 // code and package path correct. 7021 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7022 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7023 } 7024 7025 if ((scanFlags & SCAN_NO_DEX) == 0) { 7026 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7027 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7028 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7029 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7030 } 7031 } 7032 if (mFactoryTest && pkg.requestedPermissions.contains( 7033 android.Manifest.permission.FACTORY_TEST)) { 7034 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7035 } 7036 7037 ArrayList<PackageParser.Package> clientLibPkgs = null; 7038 7039 // writer 7040 synchronized (mPackages) { 7041 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7042 // Only system apps can add new shared libraries. 7043 if (pkg.libraryNames != null) { 7044 for (int i=0; i<pkg.libraryNames.size(); i++) { 7045 String name = pkg.libraryNames.get(i); 7046 boolean allowed = false; 7047 if (pkg.isUpdatedSystemApp()) { 7048 // New library entries can only be added through the 7049 // system image. This is important to get rid of a lot 7050 // of nasty edge cases: for example if we allowed a non- 7051 // system update of the app to add a library, then uninstalling 7052 // the update would make the library go away, and assumptions 7053 // we made such as through app install filtering would now 7054 // have allowed apps on the device which aren't compatible 7055 // with it. Better to just have the restriction here, be 7056 // conservative, and create many fewer cases that can negatively 7057 // impact the user experience. 7058 final PackageSetting sysPs = mSettings 7059 .getDisabledSystemPkgLPr(pkg.packageName); 7060 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7061 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7062 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7063 allowed = true; 7064 allowed = true; 7065 break; 7066 } 7067 } 7068 } 7069 } else { 7070 allowed = true; 7071 } 7072 if (allowed) { 7073 if (!mSharedLibraries.containsKey(name)) { 7074 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7075 } else if (!name.equals(pkg.packageName)) { 7076 Slog.w(TAG, "Package " + pkg.packageName + " library " 7077 + name + " already exists; skipping"); 7078 } 7079 } else { 7080 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7081 + name + " that is not declared on system image; skipping"); 7082 } 7083 } 7084 if ((scanFlags&SCAN_BOOTING) == 0) { 7085 // If we are not booting, we need to update any applications 7086 // that are clients of our shared library. If we are booting, 7087 // this will all be done once the scan is complete. 7088 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7089 } 7090 } 7091 } 7092 } 7093 7094 // We also need to dexopt any apps that are dependent on this library. Note that 7095 // if these fail, we should abort the install since installing the library will 7096 // result in some apps being broken. 7097 if (clientLibPkgs != null) { 7098 if ((scanFlags & SCAN_NO_DEX) == 0) { 7099 for (int i = 0; i < clientLibPkgs.size(); i++) { 7100 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7101 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7102 null /* instruction sets */, forceDex, 7103 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7104 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7105 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7106 "scanPackageLI failed to dexopt clientLibPkgs"); 7107 } 7108 } 7109 } 7110 } 7111 7112 // Also need to kill any apps that are dependent on the library. 7113 if (clientLibPkgs != null) { 7114 for (int i=0; i<clientLibPkgs.size(); i++) { 7115 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7116 killApplication(clientPkg.applicationInfo.packageName, 7117 clientPkg.applicationInfo.uid, "update lib"); 7118 } 7119 } 7120 7121 // Make sure we're not adding any bogus keyset info 7122 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7123 ksms.assertScannedPackageValid(pkg); 7124 7125 // writer 7126 synchronized (mPackages) { 7127 // We don't expect installation to fail beyond this point 7128 7129 // Add the new setting to mSettings 7130 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7131 // Add the new setting to mPackages 7132 mPackages.put(pkg.applicationInfo.packageName, pkg); 7133 // Make sure we don't accidentally delete its data. 7134 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7135 while (iter.hasNext()) { 7136 PackageCleanItem item = iter.next(); 7137 if (pkgName.equals(item.packageName)) { 7138 iter.remove(); 7139 } 7140 } 7141 7142 // Take care of first install / last update times. 7143 if (currentTime != 0) { 7144 if (pkgSetting.firstInstallTime == 0) { 7145 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7146 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7147 pkgSetting.lastUpdateTime = currentTime; 7148 } 7149 } else if (pkgSetting.firstInstallTime == 0) { 7150 // We need *something*. Take time time stamp of the file. 7151 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7152 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7153 if (scanFileTime != pkgSetting.timeStamp) { 7154 // A package on the system image has changed; consider this 7155 // to be an update. 7156 pkgSetting.lastUpdateTime = scanFileTime; 7157 } 7158 } 7159 7160 // Add the package's KeySets to the global KeySetManagerService 7161 ksms.addScannedPackageLPw(pkg); 7162 7163 int N = pkg.providers.size(); 7164 StringBuilder r = null; 7165 int i; 7166 for (i=0; i<N; i++) { 7167 PackageParser.Provider p = pkg.providers.get(i); 7168 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7169 p.info.processName, pkg.applicationInfo.uid); 7170 mProviders.addProvider(p); 7171 p.syncable = p.info.isSyncable; 7172 if (p.info.authority != null) { 7173 String names[] = p.info.authority.split(";"); 7174 p.info.authority = null; 7175 for (int j = 0; j < names.length; j++) { 7176 if (j == 1 && p.syncable) { 7177 // We only want the first authority for a provider to possibly be 7178 // syncable, so if we already added this provider using a different 7179 // authority clear the syncable flag. We copy the provider before 7180 // changing it because the mProviders object contains a reference 7181 // to a provider that we don't want to change. 7182 // Only do this for the second authority since the resulting provider 7183 // object can be the same for all future authorities for this provider. 7184 p = new PackageParser.Provider(p); 7185 p.syncable = false; 7186 } 7187 if (!mProvidersByAuthority.containsKey(names[j])) { 7188 mProvidersByAuthority.put(names[j], p); 7189 if (p.info.authority == null) { 7190 p.info.authority = names[j]; 7191 } else { 7192 p.info.authority = p.info.authority + ";" + names[j]; 7193 } 7194 if (DEBUG_PACKAGE_SCANNING) { 7195 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7196 Log.d(TAG, "Registered content provider: " + names[j] 7197 + ", className = " + p.info.name + ", isSyncable = " 7198 + p.info.isSyncable); 7199 } 7200 } else { 7201 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7202 Slog.w(TAG, "Skipping provider name " + names[j] + 7203 " (in package " + pkg.applicationInfo.packageName + 7204 "): name already used by " 7205 + ((other != null && other.getComponentName() != null) 7206 ? other.getComponentName().getPackageName() : "?")); 7207 } 7208 } 7209 } 7210 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7211 if (r == null) { 7212 r = new StringBuilder(256); 7213 } else { 7214 r.append(' '); 7215 } 7216 r.append(p.info.name); 7217 } 7218 } 7219 if (r != null) { 7220 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7221 } 7222 7223 N = pkg.services.size(); 7224 r = null; 7225 for (i=0; i<N; i++) { 7226 PackageParser.Service s = pkg.services.get(i); 7227 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7228 s.info.processName, pkg.applicationInfo.uid); 7229 mServices.addService(s); 7230 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7231 if (r == null) { 7232 r = new StringBuilder(256); 7233 } else { 7234 r.append(' '); 7235 } 7236 r.append(s.info.name); 7237 } 7238 } 7239 if (r != null) { 7240 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7241 } 7242 7243 N = pkg.receivers.size(); 7244 r = null; 7245 for (i=0; i<N; i++) { 7246 PackageParser.Activity a = pkg.receivers.get(i); 7247 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7248 a.info.processName, pkg.applicationInfo.uid); 7249 mReceivers.addActivity(a, "receiver"); 7250 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7251 if (r == null) { 7252 r = new StringBuilder(256); 7253 } else { 7254 r.append(' '); 7255 } 7256 r.append(a.info.name); 7257 } 7258 } 7259 if (r != null) { 7260 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7261 } 7262 7263 N = pkg.activities.size(); 7264 r = null; 7265 for (i=0; i<N; i++) { 7266 PackageParser.Activity a = pkg.activities.get(i); 7267 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7268 a.info.processName, pkg.applicationInfo.uid); 7269 mActivities.addActivity(a, "activity"); 7270 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7271 if (r == null) { 7272 r = new StringBuilder(256); 7273 } else { 7274 r.append(' '); 7275 } 7276 r.append(a.info.name); 7277 } 7278 } 7279 if (r != null) { 7280 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7281 } 7282 7283 N = pkg.permissionGroups.size(); 7284 r = null; 7285 for (i=0; i<N; i++) { 7286 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7287 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7288 if (cur == null) { 7289 mPermissionGroups.put(pg.info.name, pg); 7290 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7291 if (r == null) { 7292 r = new StringBuilder(256); 7293 } else { 7294 r.append(' '); 7295 } 7296 r.append(pg.info.name); 7297 } 7298 } else { 7299 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7300 + pg.info.packageName + " ignored: original from " 7301 + cur.info.packageName); 7302 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7303 if (r == null) { 7304 r = new StringBuilder(256); 7305 } else { 7306 r.append(' '); 7307 } 7308 r.append("DUP:"); 7309 r.append(pg.info.name); 7310 } 7311 } 7312 } 7313 if (r != null) { 7314 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7315 } 7316 7317 N = pkg.permissions.size(); 7318 r = null; 7319 for (i=0; i<N; i++) { 7320 PackageParser.Permission p = pkg.permissions.get(i); 7321 7322 // Now that permission groups have a special meaning, we ignore permission 7323 // groups for legacy apps to prevent unexpected behavior. In particular, 7324 // permissions for one app being granted to someone just becuase they happen 7325 // to be in a group defined by another app (before this had no implications). 7326 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7327 p.group = mPermissionGroups.get(p.info.group); 7328 // Warn for a permission in an unknown group. 7329 if (p.info.group != null && p.group == null) { 7330 Slog.w(TAG, "Permission " + p.info.name + " from package " 7331 + p.info.packageName + " in an unknown group " + p.info.group); 7332 } 7333 } 7334 7335 ArrayMap<String, BasePermission> permissionMap = 7336 p.tree ? mSettings.mPermissionTrees 7337 : mSettings.mPermissions; 7338 BasePermission bp = permissionMap.get(p.info.name); 7339 7340 // Allow system apps to redefine non-system permissions 7341 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7342 final boolean currentOwnerIsSystem = (bp.perm != null 7343 && isSystemApp(bp.perm.owner)); 7344 if (isSystemApp(p.owner)) { 7345 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7346 // It's a built-in permission and no owner, take ownership now 7347 bp.packageSetting = pkgSetting; 7348 bp.perm = p; 7349 bp.uid = pkg.applicationInfo.uid; 7350 bp.sourcePackage = p.info.packageName; 7351 } else if (!currentOwnerIsSystem) { 7352 String msg = "New decl " + p.owner + " of permission " 7353 + p.info.name + " is system; overriding " + bp.sourcePackage; 7354 reportSettingsProblem(Log.WARN, msg); 7355 bp = null; 7356 } 7357 } 7358 } 7359 7360 if (bp == null) { 7361 bp = new BasePermission(p.info.name, p.info.packageName, 7362 BasePermission.TYPE_NORMAL); 7363 permissionMap.put(p.info.name, bp); 7364 } 7365 7366 if (bp.perm == null) { 7367 if (bp.sourcePackage == null 7368 || bp.sourcePackage.equals(p.info.packageName)) { 7369 BasePermission tree = findPermissionTreeLP(p.info.name); 7370 if (tree == null 7371 || tree.sourcePackage.equals(p.info.packageName)) { 7372 bp.packageSetting = pkgSetting; 7373 bp.perm = p; 7374 bp.uid = pkg.applicationInfo.uid; 7375 bp.sourcePackage = p.info.packageName; 7376 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7377 if (r == null) { 7378 r = new StringBuilder(256); 7379 } else { 7380 r.append(' '); 7381 } 7382 r.append(p.info.name); 7383 } 7384 } else { 7385 Slog.w(TAG, "Permission " + p.info.name + " from package " 7386 + p.info.packageName + " ignored: base tree " 7387 + tree.name + " is from package " 7388 + tree.sourcePackage); 7389 } 7390 } else { 7391 Slog.w(TAG, "Permission " + p.info.name + " from package " 7392 + p.info.packageName + " ignored: original from " 7393 + bp.sourcePackage); 7394 } 7395 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7396 if (r == null) { 7397 r = new StringBuilder(256); 7398 } else { 7399 r.append(' '); 7400 } 7401 r.append("DUP:"); 7402 r.append(p.info.name); 7403 } 7404 if (bp.perm == p) { 7405 bp.protectionLevel = p.info.protectionLevel; 7406 } 7407 } 7408 7409 if (r != null) { 7410 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7411 } 7412 7413 N = pkg.instrumentation.size(); 7414 r = null; 7415 for (i=0; i<N; i++) { 7416 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7417 a.info.packageName = pkg.applicationInfo.packageName; 7418 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7419 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7420 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7421 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7422 a.info.dataDir = pkg.applicationInfo.dataDir; 7423 7424 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7425 // need other information about the application, like the ABI and what not ? 7426 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7427 mInstrumentation.put(a.getComponentName(), a); 7428 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7429 if (r == null) { 7430 r = new StringBuilder(256); 7431 } else { 7432 r.append(' '); 7433 } 7434 r.append(a.info.name); 7435 } 7436 } 7437 if (r != null) { 7438 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7439 } 7440 7441 if (pkg.protectedBroadcasts != null) { 7442 N = pkg.protectedBroadcasts.size(); 7443 for (i=0; i<N; i++) { 7444 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7445 } 7446 } 7447 7448 pkgSetting.setTimeStamp(scanFileTime); 7449 7450 // Create idmap files for pairs of (packages, overlay packages). 7451 // Note: "android", ie framework-res.apk, is handled by native layers. 7452 if (pkg.mOverlayTarget != null) { 7453 // This is an overlay package. 7454 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7455 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7456 mOverlays.put(pkg.mOverlayTarget, 7457 new ArrayMap<String, PackageParser.Package>()); 7458 } 7459 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7460 map.put(pkg.packageName, pkg); 7461 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7462 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7463 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7464 "scanPackageLI failed to createIdmap"); 7465 } 7466 } 7467 } else if (mOverlays.containsKey(pkg.packageName) && 7468 !pkg.packageName.equals("android")) { 7469 // This is a regular package, with one or more known overlay packages. 7470 createIdmapsForPackageLI(pkg); 7471 } 7472 } 7473 7474 return pkg; 7475 } 7476 7477 /** 7478 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7479 * is derived purely on the basis of the contents of {@code scanFile} and 7480 * {@code cpuAbiOverride}. 7481 * 7482 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7483 */ 7484 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7485 String cpuAbiOverride, boolean extractLibs) 7486 throws PackageManagerException { 7487 // TODO: We can probably be smarter about this stuff. For installed apps, 7488 // we can calculate this information at install time once and for all. For 7489 // system apps, we can probably assume that this information doesn't change 7490 // after the first boot scan. As things stand, we do lots of unnecessary work. 7491 7492 // Give ourselves some initial paths; we'll come back for another 7493 // pass once we've determined ABI below. 7494 setNativeLibraryPaths(pkg); 7495 7496 // We would never need to extract libs for forward-locked and external packages, 7497 // since the container service will do it for us. We shouldn't attempt to 7498 // extract libs from system app when it was not updated. 7499 if (pkg.isForwardLocked() || isExternal(pkg) || 7500 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7501 extractLibs = false; 7502 } 7503 7504 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7505 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7506 7507 NativeLibraryHelper.Handle handle = null; 7508 try { 7509 handle = NativeLibraryHelper.Handle.create(pkg); 7510 // TODO(multiArch): This can be null for apps that didn't go through the 7511 // usual installation process. We can calculate it again, like we 7512 // do during install time. 7513 // 7514 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7515 // unnecessary. 7516 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7517 7518 // Null out the abis so that they can be recalculated. 7519 pkg.applicationInfo.primaryCpuAbi = null; 7520 pkg.applicationInfo.secondaryCpuAbi = null; 7521 if (isMultiArch(pkg.applicationInfo)) { 7522 // Warn if we've set an abiOverride for multi-lib packages.. 7523 // By definition, we need to copy both 32 and 64 bit libraries for 7524 // such packages. 7525 if (pkg.cpuAbiOverride != null 7526 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7527 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7528 } 7529 7530 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7531 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7532 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7533 if (extractLibs) { 7534 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7535 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7536 useIsaSpecificSubdirs); 7537 } else { 7538 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7539 } 7540 } 7541 7542 maybeThrowExceptionForMultiArchCopy( 7543 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7544 7545 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7546 if (extractLibs) { 7547 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7548 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7549 useIsaSpecificSubdirs); 7550 } else { 7551 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7552 } 7553 } 7554 7555 maybeThrowExceptionForMultiArchCopy( 7556 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7557 7558 if (abi64 >= 0) { 7559 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7560 } 7561 7562 if (abi32 >= 0) { 7563 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7564 if (abi64 >= 0) { 7565 pkg.applicationInfo.secondaryCpuAbi = abi; 7566 } else { 7567 pkg.applicationInfo.primaryCpuAbi = abi; 7568 } 7569 } 7570 } else { 7571 String[] abiList = (cpuAbiOverride != null) ? 7572 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7573 7574 // Enable gross and lame hacks for apps that are built with old 7575 // SDK tools. We must scan their APKs for renderscript bitcode and 7576 // not launch them if it's present. Don't bother checking on devices 7577 // that don't have 64 bit support. 7578 boolean needsRenderScriptOverride = false; 7579 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7580 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7581 abiList = Build.SUPPORTED_32_BIT_ABIS; 7582 needsRenderScriptOverride = true; 7583 } 7584 7585 final int copyRet; 7586 if (extractLibs) { 7587 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7588 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7589 } else { 7590 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7591 } 7592 7593 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7594 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7595 "Error unpackaging native libs for app, errorCode=" + copyRet); 7596 } 7597 7598 if (copyRet >= 0) { 7599 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7600 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7601 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7602 } else if (needsRenderScriptOverride) { 7603 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7604 } 7605 } 7606 } catch (IOException ioe) { 7607 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7608 } finally { 7609 IoUtils.closeQuietly(handle); 7610 } 7611 7612 // Now that we've calculated the ABIs and determined if it's an internal app, 7613 // we will go ahead and populate the nativeLibraryPath. 7614 setNativeLibraryPaths(pkg); 7615 } 7616 7617 /** 7618 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7619 * i.e, so that all packages can be run inside a single process if required. 7620 * 7621 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7622 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7623 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7624 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7625 * updating a package that belongs to a shared user. 7626 * 7627 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7628 * adds unnecessary complexity. 7629 */ 7630 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7631 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7632 String requiredInstructionSet = null; 7633 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7634 requiredInstructionSet = VMRuntime.getInstructionSet( 7635 scannedPackage.applicationInfo.primaryCpuAbi); 7636 } 7637 7638 PackageSetting requirer = null; 7639 for (PackageSetting ps : packagesForUser) { 7640 // If packagesForUser contains scannedPackage, we skip it. This will happen 7641 // when scannedPackage is an update of an existing package. Without this check, 7642 // we will never be able to change the ABI of any package belonging to a shared 7643 // user, even if it's compatible with other packages. 7644 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7645 if (ps.primaryCpuAbiString == null) { 7646 continue; 7647 } 7648 7649 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7650 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7651 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7652 // this but there's not much we can do. 7653 String errorMessage = "Instruction set mismatch, " 7654 + ((requirer == null) ? "[caller]" : requirer) 7655 + " requires " + requiredInstructionSet + " whereas " + ps 7656 + " requires " + instructionSet; 7657 Slog.w(TAG, errorMessage); 7658 } 7659 7660 if (requiredInstructionSet == null) { 7661 requiredInstructionSet = instructionSet; 7662 requirer = ps; 7663 } 7664 } 7665 } 7666 7667 if (requiredInstructionSet != null) { 7668 String adjustedAbi; 7669 if (requirer != null) { 7670 // requirer != null implies that either scannedPackage was null or that scannedPackage 7671 // did not require an ABI, in which case we have to adjust scannedPackage to match 7672 // the ABI of the set (which is the same as requirer's ABI) 7673 adjustedAbi = requirer.primaryCpuAbiString; 7674 if (scannedPackage != null) { 7675 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7676 } 7677 } else { 7678 // requirer == null implies that we're updating all ABIs in the set to 7679 // match scannedPackage. 7680 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7681 } 7682 7683 for (PackageSetting ps : packagesForUser) { 7684 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7685 if (ps.primaryCpuAbiString != null) { 7686 continue; 7687 } 7688 7689 ps.primaryCpuAbiString = adjustedAbi; 7690 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7691 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7692 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7693 7694 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7695 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7696 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7697 ps.primaryCpuAbiString = null; 7698 ps.pkg.applicationInfo.primaryCpuAbi = null; 7699 return; 7700 } else { 7701 mInstaller.rmdex(ps.codePathString, 7702 getDexCodeInstructionSet(getPreferredInstructionSet())); 7703 } 7704 } 7705 } 7706 } 7707 } 7708 } 7709 7710 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7711 synchronized (mPackages) { 7712 mResolverReplaced = true; 7713 // Set up information for custom user intent resolution activity. 7714 mResolveActivity.applicationInfo = pkg.applicationInfo; 7715 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7716 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7717 mResolveActivity.processName = pkg.applicationInfo.packageName; 7718 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7719 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7720 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7721 mResolveActivity.theme = 0; 7722 mResolveActivity.exported = true; 7723 mResolveActivity.enabled = true; 7724 mResolveInfo.activityInfo = mResolveActivity; 7725 mResolveInfo.priority = 0; 7726 mResolveInfo.preferredOrder = 0; 7727 mResolveInfo.match = 0; 7728 mResolveComponentName = mCustomResolverComponentName; 7729 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7730 mResolveComponentName); 7731 } 7732 } 7733 7734 private static String calculateBundledApkRoot(final String codePathString) { 7735 final File codePath = new File(codePathString); 7736 final File codeRoot; 7737 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7738 codeRoot = Environment.getRootDirectory(); 7739 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7740 codeRoot = Environment.getOemDirectory(); 7741 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7742 codeRoot = Environment.getVendorDirectory(); 7743 } else { 7744 // Unrecognized code path; take its top real segment as the apk root: 7745 // e.g. /something/app/blah.apk => /something 7746 try { 7747 File f = codePath.getCanonicalFile(); 7748 File parent = f.getParentFile(); // non-null because codePath is a file 7749 File tmp; 7750 while ((tmp = parent.getParentFile()) != null) { 7751 f = parent; 7752 parent = tmp; 7753 } 7754 codeRoot = f; 7755 Slog.w(TAG, "Unrecognized code path " 7756 + codePath + " - using " + codeRoot); 7757 } catch (IOException e) { 7758 // Can't canonicalize the code path -- shenanigans? 7759 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7760 return Environment.getRootDirectory().getPath(); 7761 } 7762 } 7763 return codeRoot.getPath(); 7764 } 7765 7766 /** 7767 * Derive and set the location of native libraries for the given package, 7768 * which varies depending on where and how the package was installed. 7769 */ 7770 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7771 final ApplicationInfo info = pkg.applicationInfo; 7772 final String codePath = pkg.codePath; 7773 final File codeFile = new File(codePath); 7774 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7775 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7776 7777 info.nativeLibraryRootDir = null; 7778 info.nativeLibraryRootRequiresIsa = false; 7779 info.nativeLibraryDir = null; 7780 info.secondaryNativeLibraryDir = null; 7781 7782 if (isApkFile(codeFile)) { 7783 // Monolithic install 7784 if (bundledApp) { 7785 // If "/system/lib64/apkname" exists, assume that is the per-package 7786 // native library directory to use; otherwise use "/system/lib/apkname". 7787 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7788 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7789 getPrimaryInstructionSet(info)); 7790 7791 // This is a bundled system app so choose the path based on the ABI. 7792 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7793 // is just the default path. 7794 final String apkName = deriveCodePathName(codePath); 7795 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7796 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7797 apkName).getAbsolutePath(); 7798 7799 if (info.secondaryCpuAbi != null) { 7800 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7801 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7802 secondaryLibDir, apkName).getAbsolutePath(); 7803 } 7804 } else if (asecApp) { 7805 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7806 .getAbsolutePath(); 7807 } else { 7808 final String apkName = deriveCodePathName(codePath); 7809 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7810 .getAbsolutePath(); 7811 } 7812 7813 info.nativeLibraryRootRequiresIsa = false; 7814 info.nativeLibraryDir = info.nativeLibraryRootDir; 7815 } else { 7816 // Cluster install 7817 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7818 info.nativeLibraryRootRequiresIsa = true; 7819 7820 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7821 getPrimaryInstructionSet(info)).getAbsolutePath(); 7822 7823 if (info.secondaryCpuAbi != null) { 7824 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7825 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7826 } 7827 } 7828 } 7829 7830 /** 7831 * Calculate the abis and roots for a bundled app. These can uniquely 7832 * be determined from the contents of the system partition, i.e whether 7833 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7834 * of this information, and instead assume that the system was built 7835 * sensibly. 7836 */ 7837 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7838 PackageSetting pkgSetting) { 7839 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7840 7841 // If "/system/lib64/apkname" exists, assume that is the per-package 7842 // native library directory to use; otherwise use "/system/lib/apkname". 7843 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7844 setBundledAppAbi(pkg, apkRoot, apkName); 7845 // pkgSetting might be null during rescan following uninstall of updates 7846 // to a bundled app, so accommodate that possibility. The settings in 7847 // that case will be established later from the parsed package. 7848 // 7849 // If the settings aren't null, sync them up with what we've just derived. 7850 // note that apkRoot isn't stored in the package settings. 7851 if (pkgSetting != null) { 7852 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7853 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7854 } 7855 } 7856 7857 /** 7858 * Deduces the ABI of a bundled app and sets the relevant fields on the 7859 * parsed pkg object. 7860 * 7861 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7862 * under which system libraries are installed. 7863 * @param apkName the name of the installed package. 7864 */ 7865 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7866 final File codeFile = new File(pkg.codePath); 7867 7868 final boolean has64BitLibs; 7869 final boolean has32BitLibs; 7870 if (isApkFile(codeFile)) { 7871 // Monolithic install 7872 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7873 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7874 } else { 7875 // Cluster install 7876 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7877 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7878 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7879 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7880 has64BitLibs = (new File(rootDir, isa)).exists(); 7881 } else { 7882 has64BitLibs = false; 7883 } 7884 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7885 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7886 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7887 has32BitLibs = (new File(rootDir, isa)).exists(); 7888 } else { 7889 has32BitLibs = false; 7890 } 7891 } 7892 7893 if (has64BitLibs && !has32BitLibs) { 7894 // The package has 64 bit libs, but not 32 bit libs. Its primary 7895 // ABI should be 64 bit. We can safely assume here that the bundled 7896 // native libraries correspond to the most preferred ABI in the list. 7897 7898 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7899 pkg.applicationInfo.secondaryCpuAbi = null; 7900 } else if (has32BitLibs && !has64BitLibs) { 7901 // The package has 32 bit libs but not 64 bit libs. Its primary 7902 // ABI should be 32 bit. 7903 7904 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7905 pkg.applicationInfo.secondaryCpuAbi = null; 7906 } else if (has32BitLibs && has64BitLibs) { 7907 // The application has both 64 and 32 bit bundled libraries. We check 7908 // here that the app declares multiArch support, and warn if it doesn't. 7909 // 7910 // We will be lenient here and record both ABIs. The primary will be the 7911 // ABI that's higher on the list, i.e, a device that's configured to prefer 7912 // 64 bit apps will see a 64 bit primary ABI, 7913 7914 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7915 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7916 } 7917 7918 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7919 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7920 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7921 } else { 7922 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7923 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7924 } 7925 } else { 7926 pkg.applicationInfo.primaryCpuAbi = null; 7927 pkg.applicationInfo.secondaryCpuAbi = null; 7928 } 7929 } 7930 7931 private void killApplication(String pkgName, int appId, String reason) { 7932 // Request the ActivityManager to kill the process(only for existing packages) 7933 // so that we do not end up in a confused state while the user is still using the older 7934 // version of the application while the new one gets installed. 7935 IActivityManager am = ActivityManagerNative.getDefault(); 7936 if (am != null) { 7937 try { 7938 am.killApplicationWithAppId(pkgName, appId, reason); 7939 } catch (RemoteException e) { 7940 } 7941 } 7942 } 7943 7944 void removePackageLI(PackageSetting ps, boolean chatty) { 7945 if (DEBUG_INSTALL) { 7946 if (chatty) 7947 Log.d(TAG, "Removing package " + ps.name); 7948 } 7949 7950 // writer 7951 synchronized (mPackages) { 7952 mPackages.remove(ps.name); 7953 final PackageParser.Package pkg = ps.pkg; 7954 if (pkg != null) { 7955 cleanPackageDataStructuresLILPw(pkg, chatty); 7956 } 7957 } 7958 } 7959 7960 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7961 if (DEBUG_INSTALL) { 7962 if (chatty) 7963 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7964 } 7965 7966 // writer 7967 synchronized (mPackages) { 7968 mPackages.remove(pkg.applicationInfo.packageName); 7969 cleanPackageDataStructuresLILPw(pkg, chatty); 7970 } 7971 } 7972 7973 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7974 int N = pkg.providers.size(); 7975 StringBuilder r = null; 7976 int i; 7977 for (i=0; i<N; i++) { 7978 PackageParser.Provider p = pkg.providers.get(i); 7979 mProviders.removeProvider(p); 7980 if (p.info.authority == null) { 7981 7982 /* There was another ContentProvider with this authority when 7983 * this app was installed so this authority is null, 7984 * Ignore it as we don't have to unregister the provider. 7985 */ 7986 continue; 7987 } 7988 String names[] = p.info.authority.split(";"); 7989 for (int j = 0; j < names.length; j++) { 7990 if (mProvidersByAuthority.get(names[j]) == p) { 7991 mProvidersByAuthority.remove(names[j]); 7992 if (DEBUG_REMOVE) { 7993 if (chatty) 7994 Log.d(TAG, "Unregistered content provider: " + names[j] 7995 + ", className = " + p.info.name + ", isSyncable = " 7996 + p.info.isSyncable); 7997 } 7998 } 7999 } 8000 if (DEBUG_REMOVE && chatty) { 8001 if (r == null) { 8002 r = new StringBuilder(256); 8003 } else { 8004 r.append(' '); 8005 } 8006 r.append(p.info.name); 8007 } 8008 } 8009 if (r != null) { 8010 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8011 } 8012 8013 N = pkg.services.size(); 8014 r = null; 8015 for (i=0; i<N; i++) { 8016 PackageParser.Service s = pkg.services.get(i); 8017 mServices.removeService(s); 8018 if (chatty) { 8019 if (r == null) { 8020 r = new StringBuilder(256); 8021 } else { 8022 r.append(' '); 8023 } 8024 r.append(s.info.name); 8025 } 8026 } 8027 if (r != null) { 8028 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8029 } 8030 8031 N = pkg.receivers.size(); 8032 r = null; 8033 for (i=0; i<N; i++) { 8034 PackageParser.Activity a = pkg.receivers.get(i); 8035 mReceivers.removeActivity(a, "receiver"); 8036 if (DEBUG_REMOVE && chatty) { 8037 if (r == null) { 8038 r = new StringBuilder(256); 8039 } else { 8040 r.append(' '); 8041 } 8042 r.append(a.info.name); 8043 } 8044 } 8045 if (r != null) { 8046 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8047 } 8048 8049 N = pkg.activities.size(); 8050 r = null; 8051 for (i=0; i<N; i++) { 8052 PackageParser.Activity a = pkg.activities.get(i); 8053 mActivities.removeActivity(a, "activity"); 8054 if (DEBUG_REMOVE && chatty) { 8055 if (r == null) { 8056 r = new StringBuilder(256); 8057 } else { 8058 r.append(' '); 8059 } 8060 r.append(a.info.name); 8061 } 8062 } 8063 if (r != null) { 8064 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8065 } 8066 8067 N = pkg.permissions.size(); 8068 r = null; 8069 for (i=0; i<N; i++) { 8070 PackageParser.Permission p = pkg.permissions.get(i); 8071 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8072 if (bp == null) { 8073 bp = mSettings.mPermissionTrees.get(p.info.name); 8074 } 8075 if (bp != null && bp.perm == p) { 8076 bp.perm = null; 8077 if (DEBUG_REMOVE && chatty) { 8078 if (r == null) { 8079 r = new StringBuilder(256); 8080 } else { 8081 r.append(' '); 8082 } 8083 r.append(p.info.name); 8084 } 8085 } 8086 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8087 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8088 if (appOpPerms != null) { 8089 appOpPerms.remove(pkg.packageName); 8090 } 8091 } 8092 } 8093 if (r != null) { 8094 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8095 } 8096 8097 N = pkg.requestedPermissions.size(); 8098 r = null; 8099 for (i=0; i<N; i++) { 8100 String perm = pkg.requestedPermissions.get(i); 8101 BasePermission bp = mSettings.mPermissions.get(perm); 8102 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8103 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8104 if (appOpPerms != null) { 8105 appOpPerms.remove(pkg.packageName); 8106 if (appOpPerms.isEmpty()) { 8107 mAppOpPermissionPackages.remove(perm); 8108 } 8109 } 8110 } 8111 } 8112 if (r != null) { 8113 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8114 } 8115 8116 N = pkg.instrumentation.size(); 8117 r = null; 8118 for (i=0; i<N; i++) { 8119 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8120 mInstrumentation.remove(a.getComponentName()); 8121 if (DEBUG_REMOVE && chatty) { 8122 if (r == null) { 8123 r = new StringBuilder(256); 8124 } else { 8125 r.append(' '); 8126 } 8127 r.append(a.info.name); 8128 } 8129 } 8130 if (r != null) { 8131 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8132 } 8133 8134 r = null; 8135 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8136 // Only system apps can hold shared libraries. 8137 if (pkg.libraryNames != null) { 8138 for (i=0; i<pkg.libraryNames.size(); i++) { 8139 String name = pkg.libraryNames.get(i); 8140 SharedLibraryEntry cur = mSharedLibraries.get(name); 8141 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8142 mSharedLibraries.remove(name); 8143 if (DEBUG_REMOVE && chatty) { 8144 if (r == null) { 8145 r = new StringBuilder(256); 8146 } else { 8147 r.append(' '); 8148 } 8149 r.append(name); 8150 } 8151 } 8152 } 8153 } 8154 } 8155 if (r != null) { 8156 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8157 } 8158 } 8159 8160 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8161 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8162 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8163 return true; 8164 } 8165 } 8166 return false; 8167 } 8168 8169 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8170 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8171 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8172 8173 private void updatePermissionsLPw(String changingPkg, 8174 PackageParser.Package pkgInfo, int flags) { 8175 // Make sure there are no dangling permission trees. 8176 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8177 while (it.hasNext()) { 8178 final BasePermission bp = it.next(); 8179 if (bp.packageSetting == null) { 8180 // We may not yet have parsed the package, so just see if 8181 // we still know about its settings. 8182 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8183 } 8184 if (bp.packageSetting == null) { 8185 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8186 + " from package " + bp.sourcePackage); 8187 it.remove(); 8188 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8189 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8190 Slog.i(TAG, "Removing old permission tree: " + bp.name 8191 + " from package " + bp.sourcePackage); 8192 flags |= UPDATE_PERMISSIONS_ALL; 8193 it.remove(); 8194 } 8195 } 8196 } 8197 8198 // Make sure all dynamic permissions have been assigned to a package, 8199 // and make sure there are no dangling permissions. 8200 it = mSettings.mPermissions.values().iterator(); 8201 while (it.hasNext()) { 8202 final BasePermission bp = it.next(); 8203 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8204 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8205 + bp.name + " pkg=" + bp.sourcePackage 8206 + " info=" + bp.pendingInfo); 8207 if (bp.packageSetting == null && bp.pendingInfo != null) { 8208 final BasePermission tree = findPermissionTreeLP(bp.name); 8209 if (tree != null && tree.perm != null) { 8210 bp.packageSetting = tree.packageSetting; 8211 bp.perm = new PackageParser.Permission(tree.perm.owner, 8212 new PermissionInfo(bp.pendingInfo)); 8213 bp.perm.info.packageName = tree.perm.info.packageName; 8214 bp.perm.info.name = bp.name; 8215 bp.uid = tree.uid; 8216 } 8217 } 8218 } 8219 if (bp.packageSetting == null) { 8220 // We may not yet have parsed the package, so just see if 8221 // we still know about its settings. 8222 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8223 } 8224 if (bp.packageSetting == null) { 8225 Slog.w(TAG, "Removing dangling permission: " + bp.name 8226 + " from package " + bp.sourcePackage); 8227 it.remove(); 8228 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8229 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8230 Slog.i(TAG, "Removing old permission: " + bp.name 8231 + " from package " + bp.sourcePackage); 8232 flags |= UPDATE_PERMISSIONS_ALL; 8233 it.remove(); 8234 } 8235 } 8236 } 8237 8238 // Now update the permissions for all packages, in particular 8239 // replace the granted permissions of the system packages. 8240 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8241 for (PackageParser.Package pkg : mPackages.values()) { 8242 if (pkg != pkgInfo) { 8243 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8244 changingPkg); 8245 } 8246 } 8247 } 8248 8249 if (pkgInfo != null) { 8250 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8251 } 8252 } 8253 8254 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8255 String packageOfInterest) { 8256 // IMPORTANT: There are two types of permissions: install and runtime. 8257 // Install time permissions are granted when the app is installed to 8258 // all device users and users added in the future. Runtime permissions 8259 // are granted at runtime explicitly to specific users. Normal and signature 8260 // protected permissions are install time permissions. Dangerous permissions 8261 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8262 // otherwise they are runtime permissions. This function does not manage 8263 // runtime permissions except for the case an app targeting Lollipop MR1 8264 // being upgraded to target a newer SDK, in which case dangerous permissions 8265 // are transformed from install time to runtime ones. 8266 8267 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8268 if (ps == null) { 8269 return; 8270 } 8271 8272 PermissionsState permissionsState = ps.getPermissionsState(); 8273 PermissionsState origPermissions = permissionsState; 8274 8275 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8276 8277 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8278 8279 boolean changedInstallPermission = false; 8280 8281 if (replace) { 8282 ps.installPermissionsFixed = false; 8283 if (!ps.isSharedUser()) { 8284 origPermissions = new PermissionsState(permissionsState); 8285 permissionsState.reset(); 8286 } 8287 } 8288 8289 permissionsState.setGlobalGids(mGlobalGids); 8290 8291 final int N = pkg.requestedPermissions.size(); 8292 for (int i=0; i<N; i++) { 8293 final String name = pkg.requestedPermissions.get(i); 8294 final BasePermission bp = mSettings.mPermissions.get(name); 8295 8296 if (DEBUG_INSTALL) { 8297 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8298 } 8299 8300 if (bp == null || bp.packageSetting == null) { 8301 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8302 Slog.w(TAG, "Unknown permission " + name 8303 + " in package " + pkg.packageName); 8304 } 8305 continue; 8306 } 8307 8308 final String perm = bp.name; 8309 boolean allowedSig = false; 8310 int grant = GRANT_DENIED; 8311 8312 // Keep track of app op permissions. 8313 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8314 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8315 if (pkgs == null) { 8316 pkgs = new ArraySet<>(); 8317 mAppOpPermissionPackages.put(bp.name, pkgs); 8318 } 8319 pkgs.add(pkg.packageName); 8320 } 8321 8322 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8323 switch (level) { 8324 case PermissionInfo.PROTECTION_NORMAL: { 8325 // For all apps normal permissions are install time ones. 8326 grant = GRANT_INSTALL; 8327 } break; 8328 8329 case PermissionInfo.PROTECTION_DANGEROUS: { 8330 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8331 // For legacy apps dangerous permissions are install time ones. 8332 grant = GRANT_INSTALL_LEGACY; 8333 } else if (origPermissions.hasInstallPermission(bp.name)) { 8334 // For legacy apps that became modern, install becomes runtime. 8335 grant = GRANT_UPGRADE; 8336 } else { 8337 // For modern apps keep runtime permissions unchanged. 8338 grant = GRANT_RUNTIME; 8339 } 8340 } break; 8341 8342 case PermissionInfo.PROTECTION_SIGNATURE: { 8343 // For all apps signature permissions are install time ones. 8344 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8345 if (allowedSig) { 8346 grant = GRANT_INSTALL; 8347 } 8348 } break; 8349 } 8350 8351 if (DEBUG_INSTALL) { 8352 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8353 } 8354 8355 if (grant != GRANT_DENIED) { 8356 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8357 // If this is an existing, non-system package, then 8358 // we can't add any new permissions to it. 8359 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8360 // Except... if this is a permission that was added 8361 // to the platform (note: need to only do this when 8362 // updating the platform). 8363 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8364 grant = GRANT_DENIED; 8365 } 8366 } 8367 } 8368 8369 switch (grant) { 8370 case GRANT_INSTALL: { 8371 // Revoke this as runtime permission to handle the case of 8372 // a runtime permission being downgraded to an install one. 8373 for (int userId : UserManagerService.getInstance().getUserIds()) { 8374 if (origPermissions.getRuntimePermissionState( 8375 bp.name, userId) != null) { 8376 // Revoke the runtime permission and clear the flags. 8377 origPermissions.revokeRuntimePermission(bp, userId); 8378 origPermissions.updatePermissionFlags(bp, userId, 8379 PackageManager.MASK_PERMISSION_FLAGS, 0); 8380 // If we revoked a permission permission, we have to write. 8381 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8382 changedRuntimePermissionUserIds, userId); 8383 } 8384 } 8385 // Grant an install permission. 8386 if (permissionsState.grantInstallPermission(bp) != 8387 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8388 changedInstallPermission = true; 8389 } 8390 } break; 8391 8392 case GRANT_INSTALL_LEGACY: { 8393 // Grant an install permission. 8394 if (permissionsState.grantInstallPermission(bp) != 8395 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8396 changedInstallPermission = true; 8397 } 8398 } break; 8399 8400 case GRANT_RUNTIME: { 8401 // Grant previously granted runtime permissions. 8402 for (int userId : UserManagerService.getInstance().getUserIds()) { 8403 PermissionState permissionState = origPermissions 8404 .getRuntimePermissionState(bp.name, userId); 8405 final int flags = permissionState != null 8406 ? permissionState.getFlags() : 0; 8407 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8408 if (permissionsState.grantRuntimePermission(bp, userId) == 8409 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8410 // If we cannot put the permission as it was, we have to write. 8411 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8412 changedRuntimePermissionUserIds, userId); 8413 } 8414 } 8415 // Propagate the permission flags. 8416 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8417 } 8418 } break; 8419 8420 case GRANT_UPGRADE: { 8421 // Grant runtime permissions for a previously held install permission. 8422 PermissionState permissionState = origPermissions 8423 .getInstallPermissionState(bp.name); 8424 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8425 8426 if (origPermissions.revokeInstallPermission(bp) 8427 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8428 // We will be transferring the permission flags, so clear them. 8429 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8430 PackageManager.MASK_PERMISSION_FLAGS, 0); 8431 changedInstallPermission = true; 8432 } 8433 8434 // If the permission is not to be promoted to runtime we ignore it and 8435 // also its other flags as they are not applicable to install permissions. 8436 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8437 for (int userId : currentUserIds) { 8438 if (permissionsState.grantRuntimePermission(bp, userId) != 8439 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8440 // Transfer the permission flags. 8441 permissionsState.updatePermissionFlags(bp, userId, 8442 flags, flags); 8443 // If we granted the permission, we have to write. 8444 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8445 changedRuntimePermissionUserIds, userId); 8446 } 8447 } 8448 } 8449 } break; 8450 8451 default: { 8452 if (packageOfInterest == null 8453 || packageOfInterest.equals(pkg.packageName)) { 8454 Slog.w(TAG, "Not granting permission " + perm 8455 + " to package " + pkg.packageName 8456 + " because it was previously installed without"); 8457 } 8458 } break; 8459 } 8460 } else { 8461 if (permissionsState.revokeInstallPermission(bp) != 8462 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8463 // Also drop the permission flags. 8464 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8465 PackageManager.MASK_PERMISSION_FLAGS, 0); 8466 changedInstallPermission = true; 8467 Slog.i(TAG, "Un-granting permission " + perm 8468 + " from package " + pkg.packageName 8469 + " (protectionLevel=" + bp.protectionLevel 8470 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8471 + ")"); 8472 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8473 // Don't print warning for app op permissions, since it is fine for them 8474 // not to be granted, there is a UI for the user to decide. 8475 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8476 Slog.w(TAG, "Not granting permission " + perm 8477 + " to package " + pkg.packageName 8478 + " (protectionLevel=" + bp.protectionLevel 8479 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8480 + ")"); 8481 } 8482 } 8483 } 8484 } 8485 8486 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8487 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8488 // This is the first that we have heard about this package, so the 8489 // permissions we have now selected are fixed until explicitly 8490 // changed. 8491 ps.installPermissionsFixed = true; 8492 } 8493 8494 // Persist the runtime permissions state for users with changes. 8495 for (int userId : changedRuntimePermissionUserIds) { 8496 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8497 } 8498 } 8499 8500 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8501 boolean allowed = false; 8502 final int NP = PackageParser.NEW_PERMISSIONS.length; 8503 for (int ip=0; ip<NP; ip++) { 8504 final PackageParser.NewPermissionInfo npi 8505 = PackageParser.NEW_PERMISSIONS[ip]; 8506 if (npi.name.equals(perm) 8507 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8508 allowed = true; 8509 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8510 + pkg.packageName); 8511 break; 8512 } 8513 } 8514 return allowed; 8515 } 8516 8517 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8518 BasePermission bp, PermissionsState origPermissions) { 8519 boolean allowed; 8520 allowed = (compareSignatures( 8521 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8522 == PackageManager.SIGNATURE_MATCH) 8523 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8524 == PackageManager.SIGNATURE_MATCH); 8525 if (!allowed && (bp.protectionLevel 8526 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8527 if (isSystemApp(pkg)) { 8528 // For updated system applications, a system permission 8529 // is granted only if it had been defined by the original application. 8530 if (pkg.isUpdatedSystemApp()) { 8531 final PackageSetting sysPs = mSettings 8532 .getDisabledSystemPkgLPr(pkg.packageName); 8533 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8534 // If the original was granted this permission, we take 8535 // that grant decision as read and propagate it to the 8536 // update. 8537 if (sysPs.isPrivileged()) { 8538 allowed = true; 8539 } 8540 } else { 8541 // The system apk may have been updated with an older 8542 // version of the one on the data partition, but which 8543 // granted a new system permission that it didn't have 8544 // before. In this case we do want to allow the app to 8545 // now get the new permission if the ancestral apk is 8546 // privileged to get it. 8547 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8548 for (int j=0; 8549 j<sysPs.pkg.requestedPermissions.size(); j++) { 8550 if (perm.equals( 8551 sysPs.pkg.requestedPermissions.get(j))) { 8552 allowed = true; 8553 break; 8554 } 8555 } 8556 } 8557 } 8558 } else { 8559 allowed = isPrivilegedApp(pkg); 8560 } 8561 } 8562 } 8563 if (!allowed) { 8564 if (!allowed && (bp.protectionLevel 8565 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8566 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8567 // If this was a previously normal/dangerous permission that got moved 8568 // to a system permission as part of the runtime permission redesign, then 8569 // we still want to blindly grant it to old apps. 8570 allowed = true; 8571 } 8572 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8573 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8574 // If this permission is to be granted to the system installer and 8575 // this app is an installer, then it gets the permission. 8576 allowed = true; 8577 } 8578 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8579 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8580 // If this permission is to be granted to the system verifier and 8581 // this app is a verifier, then it gets the permission. 8582 allowed = true; 8583 } 8584 if (!allowed && (bp.protectionLevel 8585 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8586 && isSystemApp(pkg)) { 8587 // Any pre-installed system app is allowed to get this permission. 8588 allowed = true; 8589 } 8590 if (!allowed && (bp.protectionLevel 8591 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8592 // For development permissions, a development permission 8593 // is granted only if it was already granted. 8594 allowed = origPermissions.hasInstallPermission(perm); 8595 } 8596 } 8597 return allowed; 8598 } 8599 8600 final class ActivityIntentResolver 8601 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8602 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8603 boolean defaultOnly, int userId) { 8604 if (!sUserManager.exists(userId)) return null; 8605 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8606 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8607 } 8608 8609 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8610 int userId) { 8611 if (!sUserManager.exists(userId)) return null; 8612 mFlags = flags; 8613 return super.queryIntent(intent, resolvedType, 8614 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8615 } 8616 8617 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8618 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8619 if (!sUserManager.exists(userId)) return null; 8620 if (packageActivities == null) { 8621 return null; 8622 } 8623 mFlags = flags; 8624 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8625 final int N = packageActivities.size(); 8626 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8627 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8628 8629 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8630 for (int i = 0; i < N; ++i) { 8631 intentFilters = packageActivities.get(i).intents; 8632 if (intentFilters != null && intentFilters.size() > 0) { 8633 PackageParser.ActivityIntentInfo[] array = 8634 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8635 intentFilters.toArray(array); 8636 listCut.add(array); 8637 } 8638 } 8639 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8640 } 8641 8642 public final void addActivity(PackageParser.Activity a, String type) { 8643 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8644 mActivities.put(a.getComponentName(), a); 8645 if (DEBUG_SHOW_INFO) 8646 Log.v( 8647 TAG, " " + type + " " + 8648 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8649 if (DEBUG_SHOW_INFO) 8650 Log.v(TAG, " Class=" + a.info.name); 8651 final int NI = a.intents.size(); 8652 for (int j=0; j<NI; j++) { 8653 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8654 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8655 intent.setPriority(0); 8656 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8657 + a.className + " with priority > 0, forcing to 0"); 8658 } 8659 if (DEBUG_SHOW_INFO) { 8660 Log.v(TAG, " IntentFilter:"); 8661 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8662 } 8663 if (!intent.debugCheck()) { 8664 Log.w(TAG, "==> For Activity " + a.info.name); 8665 } 8666 addFilter(intent); 8667 } 8668 } 8669 8670 public final void removeActivity(PackageParser.Activity a, String type) { 8671 mActivities.remove(a.getComponentName()); 8672 if (DEBUG_SHOW_INFO) { 8673 Log.v(TAG, " " + type + " " 8674 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8675 : a.info.name) + ":"); 8676 Log.v(TAG, " Class=" + a.info.name); 8677 } 8678 final int NI = a.intents.size(); 8679 for (int j=0; j<NI; j++) { 8680 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8681 if (DEBUG_SHOW_INFO) { 8682 Log.v(TAG, " IntentFilter:"); 8683 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8684 } 8685 removeFilter(intent); 8686 } 8687 } 8688 8689 @Override 8690 protected boolean allowFilterResult( 8691 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8692 ActivityInfo filterAi = filter.activity.info; 8693 for (int i=dest.size()-1; i>=0; i--) { 8694 ActivityInfo destAi = dest.get(i).activityInfo; 8695 if (destAi.name == filterAi.name 8696 && destAi.packageName == filterAi.packageName) { 8697 return false; 8698 } 8699 } 8700 return true; 8701 } 8702 8703 @Override 8704 protected ActivityIntentInfo[] newArray(int size) { 8705 return new ActivityIntentInfo[size]; 8706 } 8707 8708 @Override 8709 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8710 if (!sUserManager.exists(userId)) return true; 8711 PackageParser.Package p = filter.activity.owner; 8712 if (p != null) { 8713 PackageSetting ps = (PackageSetting)p.mExtras; 8714 if (ps != null) { 8715 // System apps are never considered stopped for purposes of 8716 // filtering, because there may be no way for the user to 8717 // actually re-launch them. 8718 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8719 && ps.getStopped(userId); 8720 } 8721 } 8722 return false; 8723 } 8724 8725 @Override 8726 protected boolean isPackageForFilter(String packageName, 8727 PackageParser.ActivityIntentInfo info) { 8728 return packageName.equals(info.activity.owner.packageName); 8729 } 8730 8731 @Override 8732 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8733 int match, int userId) { 8734 if (!sUserManager.exists(userId)) return null; 8735 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8736 return null; 8737 } 8738 final PackageParser.Activity activity = info.activity; 8739 if (mSafeMode && (activity.info.applicationInfo.flags 8740 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8741 return null; 8742 } 8743 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8744 if (ps == null) { 8745 return null; 8746 } 8747 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8748 ps.readUserState(userId), userId); 8749 if (ai == null) { 8750 return null; 8751 } 8752 final ResolveInfo res = new ResolveInfo(); 8753 res.activityInfo = ai; 8754 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8755 res.filter = info; 8756 } 8757 if (info != null) { 8758 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8759 } 8760 res.priority = info.getPriority(); 8761 res.preferredOrder = activity.owner.mPreferredOrder; 8762 //System.out.println("Result: " + res.activityInfo.className + 8763 // " = " + res.priority); 8764 res.match = match; 8765 res.isDefault = info.hasDefault; 8766 res.labelRes = info.labelRes; 8767 res.nonLocalizedLabel = info.nonLocalizedLabel; 8768 if (userNeedsBadging(userId)) { 8769 res.noResourceId = true; 8770 } else { 8771 res.icon = info.icon; 8772 } 8773 res.iconResourceId = info.icon; 8774 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8775 return res; 8776 } 8777 8778 @Override 8779 protected void sortResults(List<ResolveInfo> results) { 8780 Collections.sort(results, mResolvePrioritySorter); 8781 } 8782 8783 @Override 8784 protected void dumpFilter(PrintWriter out, String prefix, 8785 PackageParser.ActivityIntentInfo filter) { 8786 out.print(prefix); out.print( 8787 Integer.toHexString(System.identityHashCode(filter.activity))); 8788 out.print(' '); 8789 filter.activity.printComponentShortName(out); 8790 out.print(" filter "); 8791 out.println(Integer.toHexString(System.identityHashCode(filter))); 8792 } 8793 8794 @Override 8795 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8796 return filter.activity; 8797 } 8798 8799 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8800 PackageParser.Activity activity = (PackageParser.Activity)label; 8801 out.print(prefix); out.print( 8802 Integer.toHexString(System.identityHashCode(activity))); 8803 out.print(' '); 8804 activity.printComponentShortName(out); 8805 if (count > 1) { 8806 out.print(" ("); out.print(count); out.print(" filters)"); 8807 } 8808 out.println(); 8809 } 8810 8811// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8812// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8813// final List<ResolveInfo> retList = Lists.newArrayList(); 8814// while (i.hasNext()) { 8815// final ResolveInfo resolveInfo = i.next(); 8816// if (isEnabledLP(resolveInfo.activityInfo)) { 8817// retList.add(resolveInfo); 8818// } 8819// } 8820// return retList; 8821// } 8822 8823 // Keys are String (activity class name), values are Activity. 8824 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8825 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8826 private int mFlags; 8827 } 8828 8829 private final class ServiceIntentResolver 8830 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8831 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8832 boolean defaultOnly, int userId) { 8833 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8834 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8835 } 8836 8837 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8838 int userId) { 8839 if (!sUserManager.exists(userId)) return null; 8840 mFlags = flags; 8841 return super.queryIntent(intent, resolvedType, 8842 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8843 } 8844 8845 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8846 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8847 if (!sUserManager.exists(userId)) return null; 8848 if (packageServices == null) { 8849 return null; 8850 } 8851 mFlags = flags; 8852 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8853 final int N = packageServices.size(); 8854 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8855 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8856 8857 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8858 for (int i = 0; i < N; ++i) { 8859 intentFilters = packageServices.get(i).intents; 8860 if (intentFilters != null && intentFilters.size() > 0) { 8861 PackageParser.ServiceIntentInfo[] array = 8862 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8863 intentFilters.toArray(array); 8864 listCut.add(array); 8865 } 8866 } 8867 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8868 } 8869 8870 public final void addService(PackageParser.Service s) { 8871 mServices.put(s.getComponentName(), s); 8872 if (DEBUG_SHOW_INFO) { 8873 Log.v(TAG, " " 8874 + (s.info.nonLocalizedLabel != null 8875 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8876 Log.v(TAG, " Class=" + s.info.name); 8877 } 8878 final int NI = s.intents.size(); 8879 int j; 8880 for (j=0; j<NI; j++) { 8881 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8882 if (DEBUG_SHOW_INFO) { 8883 Log.v(TAG, " IntentFilter:"); 8884 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8885 } 8886 if (!intent.debugCheck()) { 8887 Log.w(TAG, "==> For Service " + s.info.name); 8888 } 8889 addFilter(intent); 8890 } 8891 } 8892 8893 public final void removeService(PackageParser.Service s) { 8894 mServices.remove(s.getComponentName()); 8895 if (DEBUG_SHOW_INFO) { 8896 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8897 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8898 Log.v(TAG, " Class=" + s.info.name); 8899 } 8900 final int NI = s.intents.size(); 8901 int j; 8902 for (j=0; j<NI; j++) { 8903 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8904 if (DEBUG_SHOW_INFO) { 8905 Log.v(TAG, " IntentFilter:"); 8906 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8907 } 8908 removeFilter(intent); 8909 } 8910 } 8911 8912 @Override 8913 protected boolean allowFilterResult( 8914 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8915 ServiceInfo filterSi = filter.service.info; 8916 for (int i=dest.size()-1; i>=0; i--) { 8917 ServiceInfo destAi = dest.get(i).serviceInfo; 8918 if (destAi.name == filterSi.name 8919 && destAi.packageName == filterSi.packageName) { 8920 return false; 8921 } 8922 } 8923 return true; 8924 } 8925 8926 @Override 8927 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8928 return new PackageParser.ServiceIntentInfo[size]; 8929 } 8930 8931 @Override 8932 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8933 if (!sUserManager.exists(userId)) return true; 8934 PackageParser.Package p = filter.service.owner; 8935 if (p != null) { 8936 PackageSetting ps = (PackageSetting)p.mExtras; 8937 if (ps != null) { 8938 // System apps are never considered stopped for purposes of 8939 // filtering, because there may be no way for the user to 8940 // actually re-launch them. 8941 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8942 && ps.getStopped(userId); 8943 } 8944 } 8945 return false; 8946 } 8947 8948 @Override 8949 protected boolean isPackageForFilter(String packageName, 8950 PackageParser.ServiceIntentInfo info) { 8951 return packageName.equals(info.service.owner.packageName); 8952 } 8953 8954 @Override 8955 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8956 int match, int userId) { 8957 if (!sUserManager.exists(userId)) return null; 8958 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8959 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8960 return null; 8961 } 8962 final PackageParser.Service service = info.service; 8963 if (mSafeMode && (service.info.applicationInfo.flags 8964 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8965 return null; 8966 } 8967 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8968 if (ps == null) { 8969 return null; 8970 } 8971 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8972 ps.readUserState(userId), userId); 8973 if (si == null) { 8974 return null; 8975 } 8976 final ResolveInfo res = new ResolveInfo(); 8977 res.serviceInfo = si; 8978 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8979 res.filter = filter; 8980 } 8981 res.priority = info.getPriority(); 8982 res.preferredOrder = service.owner.mPreferredOrder; 8983 res.match = match; 8984 res.isDefault = info.hasDefault; 8985 res.labelRes = info.labelRes; 8986 res.nonLocalizedLabel = info.nonLocalizedLabel; 8987 res.icon = info.icon; 8988 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8989 return res; 8990 } 8991 8992 @Override 8993 protected void sortResults(List<ResolveInfo> results) { 8994 Collections.sort(results, mResolvePrioritySorter); 8995 } 8996 8997 @Override 8998 protected void dumpFilter(PrintWriter out, String prefix, 8999 PackageParser.ServiceIntentInfo filter) { 9000 out.print(prefix); out.print( 9001 Integer.toHexString(System.identityHashCode(filter.service))); 9002 out.print(' '); 9003 filter.service.printComponentShortName(out); 9004 out.print(" filter "); 9005 out.println(Integer.toHexString(System.identityHashCode(filter))); 9006 } 9007 9008 @Override 9009 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9010 return filter.service; 9011 } 9012 9013 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9014 PackageParser.Service service = (PackageParser.Service)label; 9015 out.print(prefix); out.print( 9016 Integer.toHexString(System.identityHashCode(service))); 9017 out.print(' '); 9018 service.printComponentShortName(out); 9019 if (count > 1) { 9020 out.print(" ("); out.print(count); out.print(" filters)"); 9021 } 9022 out.println(); 9023 } 9024 9025// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9026// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9027// final List<ResolveInfo> retList = Lists.newArrayList(); 9028// while (i.hasNext()) { 9029// final ResolveInfo resolveInfo = (ResolveInfo) i; 9030// if (isEnabledLP(resolveInfo.serviceInfo)) { 9031// retList.add(resolveInfo); 9032// } 9033// } 9034// return retList; 9035// } 9036 9037 // Keys are String (activity class name), values are Activity. 9038 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9039 = new ArrayMap<ComponentName, PackageParser.Service>(); 9040 private int mFlags; 9041 }; 9042 9043 private final class ProviderIntentResolver 9044 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9045 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9046 boolean defaultOnly, int userId) { 9047 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9048 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9049 } 9050 9051 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9052 int userId) { 9053 if (!sUserManager.exists(userId)) 9054 return null; 9055 mFlags = flags; 9056 return super.queryIntent(intent, resolvedType, 9057 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9058 } 9059 9060 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9061 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9062 if (!sUserManager.exists(userId)) 9063 return null; 9064 if (packageProviders == null) { 9065 return null; 9066 } 9067 mFlags = flags; 9068 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9069 final int N = packageProviders.size(); 9070 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9071 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9072 9073 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9074 for (int i = 0; i < N; ++i) { 9075 intentFilters = packageProviders.get(i).intents; 9076 if (intentFilters != null && intentFilters.size() > 0) { 9077 PackageParser.ProviderIntentInfo[] array = 9078 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9079 intentFilters.toArray(array); 9080 listCut.add(array); 9081 } 9082 } 9083 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9084 } 9085 9086 public final void addProvider(PackageParser.Provider p) { 9087 if (mProviders.containsKey(p.getComponentName())) { 9088 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9089 return; 9090 } 9091 9092 mProviders.put(p.getComponentName(), p); 9093 if (DEBUG_SHOW_INFO) { 9094 Log.v(TAG, " " 9095 + (p.info.nonLocalizedLabel != null 9096 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9097 Log.v(TAG, " Class=" + p.info.name); 9098 } 9099 final int NI = p.intents.size(); 9100 int j; 9101 for (j = 0; j < NI; j++) { 9102 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9103 if (DEBUG_SHOW_INFO) { 9104 Log.v(TAG, " IntentFilter:"); 9105 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9106 } 9107 if (!intent.debugCheck()) { 9108 Log.w(TAG, "==> For Provider " + p.info.name); 9109 } 9110 addFilter(intent); 9111 } 9112 } 9113 9114 public final void removeProvider(PackageParser.Provider p) { 9115 mProviders.remove(p.getComponentName()); 9116 if (DEBUG_SHOW_INFO) { 9117 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9118 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9119 Log.v(TAG, " Class=" + p.info.name); 9120 } 9121 final int NI = p.intents.size(); 9122 int j; 9123 for (j = 0; j < NI; j++) { 9124 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9125 if (DEBUG_SHOW_INFO) { 9126 Log.v(TAG, " IntentFilter:"); 9127 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9128 } 9129 removeFilter(intent); 9130 } 9131 } 9132 9133 @Override 9134 protected boolean allowFilterResult( 9135 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9136 ProviderInfo filterPi = filter.provider.info; 9137 for (int i = dest.size() - 1; i >= 0; i--) { 9138 ProviderInfo destPi = dest.get(i).providerInfo; 9139 if (destPi.name == filterPi.name 9140 && destPi.packageName == filterPi.packageName) { 9141 return false; 9142 } 9143 } 9144 return true; 9145 } 9146 9147 @Override 9148 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9149 return new PackageParser.ProviderIntentInfo[size]; 9150 } 9151 9152 @Override 9153 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9154 if (!sUserManager.exists(userId)) 9155 return true; 9156 PackageParser.Package p = filter.provider.owner; 9157 if (p != null) { 9158 PackageSetting ps = (PackageSetting) p.mExtras; 9159 if (ps != null) { 9160 // System apps are never considered stopped for purposes of 9161 // filtering, because there may be no way for the user to 9162 // actually re-launch them. 9163 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9164 && ps.getStopped(userId); 9165 } 9166 } 9167 return false; 9168 } 9169 9170 @Override 9171 protected boolean isPackageForFilter(String packageName, 9172 PackageParser.ProviderIntentInfo info) { 9173 return packageName.equals(info.provider.owner.packageName); 9174 } 9175 9176 @Override 9177 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9178 int match, int userId) { 9179 if (!sUserManager.exists(userId)) 9180 return null; 9181 final PackageParser.ProviderIntentInfo info = filter; 9182 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9183 return null; 9184 } 9185 final PackageParser.Provider provider = info.provider; 9186 if (mSafeMode && (provider.info.applicationInfo.flags 9187 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9188 return null; 9189 } 9190 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9191 if (ps == null) { 9192 return null; 9193 } 9194 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9195 ps.readUserState(userId), userId); 9196 if (pi == null) { 9197 return null; 9198 } 9199 final ResolveInfo res = new ResolveInfo(); 9200 res.providerInfo = pi; 9201 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9202 res.filter = filter; 9203 } 9204 res.priority = info.getPriority(); 9205 res.preferredOrder = provider.owner.mPreferredOrder; 9206 res.match = match; 9207 res.isDefault = info.hasDefault; 9208 res.labelRes = info.labelRes; 9209 res.nonLocalizedLabel = info.nonLocalizedLabel; 9210 res.icon = info.icon; 9211 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9212 return res; 9213 } 9214 9215 @Override 9216 protected void sortResults(List<ResolveInfo> results) { 9217 Collections.sort(results, mResolvePrioritySorter); 9218 } 9219 9220 @Override 9221 protected void dumpFilter(PrintWriter out, String prefix, 9222 PackageParser.ProviderIntentInfo filter) { 9223 out.print(prefix); 9224 out.print( 9225 Integer.toHexString(System.identityHashCode(filter.provider))); 9226 out.print(' '); 9227 filter.provider.printComponentShortName(out); 9228 out.print(" filter "); 9229 out.println(Integer.toHexString(System.identityHashCode(filter))); 9230 } 9231 9232 @Override 9233 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9234 return filter.provider; 9235 } 9236 9237 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9238 PackageParser.Provider provider = (PackageParser.Provider)label; 9239 out.print(prefix); out.print( 9240 Integer.toHexString(System.identityHashCode(provider))); 9241 out.print(' '); 9242 provider.printComponentShortName(out); 9243 if (count > 1) { 9244 out.print(" ("); out.print(count); out.print(" filters)"); 9245 } 9246 out.println(); 9247 } 9248 9249 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9250 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9251 private int mFlags; 9252 }; 9253 9254 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9255 new Comparator<ResolveInfo>() { 9256 public int compare(ResolveInfo r1, ResolveInfo r2) { 9257 int v1 = r1.priority; 9258 int v2 = r2.priority; 9259 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9260 if (v1 != v2) { 9261 return (v1 > v2) ? -1 : 1; 9262 } 9263 v1 = r1.preferredOrder; 9264 v2 = r2.preferredOrder; 9265 if (v1 != v2) { 9266 return (v1 > v2) ? -1 : 1; 9267 } 9268 if (r1.isDefault != r2.isDefault) { 9269 return r1.isDefault ? -1 : 1; 9270 } 9271 v1 = r1.match; 9272 v2 = r2.match; 9273 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9274 if (v1 != v2) { 9275 return (v1 > v2) ? -1 : 1; 9276 } 9277 if (r1.system != r2.system) { 9278 return r1.system ? -1 : 1; 9279 } 9280 return 0; 9281 } 9282 }; 9283 9284 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9285 new Comparator<ProviderInfo>() { 9286 public int compare(ProviderInfo p1, ProviderInfo p2) { 9287 final int v1 = p1.initOrder; 9288 final int v2 = p2.initOrder; 9289 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9290 } 9291 }; 9292 9293 final void sendPackageBroadcast(final String action, final String pkg, 9294 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9295 final int[] userIds) { 9296 mHandler.post(new Runnable() { 9297 @Override 9298 public void run() { 9299 try { 9300 final IActivityManager am = ActivityManagerNative.getDefault(); 9301 if (am == null) return; 9302 final int[] resolvedUserIds; 9303 if (userIds == null) { 9304 resolvedUserIds = am.getRunningUserIds(); 9305 } else { 9306 resolvedUserIds = userIds; 9307 } 9308 for (int id : resolvedUserIds) { 9309 final Intent intent = new Intent(action, 9310 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9311 if (extras != null) { 9312 intent.putExtras(extras); 9313 } 9314 if (targetPkg != null) { 9315 intent.setPackage(targetPkg); 9316 } 9317 // Modify the UID when posting to other users 9318 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9319 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9320 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9321 intent.putExtra(Intent.EXTRA_UID, uid); 9322 } 9323 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9324 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9325 if (DEBUG_BROADCASTS) { 9326 RuntimeException here = new RuntimeException("here"); 9327 here.fillInStackTrace(); 9328 Slog.d(TAG, "Sending to user " + id + ": " 9329 + intent.toShortString(false, true, false, false) 9330 + " " + intent.getExtras(), here); 9331 } 9332 am.broadcastIntent(null, intent, null, finishedReceiver, 9333 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9334 null, finishedReceiver != null, false, id); 9335 } 9336 } catch (RemoteException ex) { 9337 } 9338 } 9339 }); 9340 } 9341 9342 /** 9343 * Check if the external storage media is available. This is true if there 9344 * is a mounted external storage medium or if the external storage is 9345 * emulated. 9346 */ 9347 private boolean isExternalMediaAvailable() { 9348 return mMediaMounted || Environment.isExternalStorageEmulated(); 9349 } 9350 9351 @Override 9352 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9353 // writer 9354 synchronized (mPackages) { 9355 if (!isExternalMediaAvailable()) { 9356 // If the external storage is no longer mounted at this point, 9357 // the caller may not have been able to delete all of this 9358 // packages files and can not delete any more. Bail. 9359 return null; 9360 } 9361 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9362 if (lastPackage != null) { 9363 pkgs.remove(lastPackage); 9364 } 9365 if (pkgs.size() > 0) { 9366 return pkgs.get(0); 9367 } 9368 } 9369 return null; 9370 } 9371 9372 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9373 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9374 userId, andCode ? 1 : 0, packageName); 9375 if (mSystemReady) { 9376 msg.sendToTarget(); 9377 } else { 9378 if (mPostSystemReadyMessages == null) { 9379 mPostSystemReadyMessages = new ArrayList<>(); 9380 } 9381 mPostSystemReadyMessages.add(msg); 9382 } 9383 } 9384 9385 void startCleaningPackages() { 9386 // reader 9387 synchronized (mPackages) { 9388 if (!isExternalMediaAvailable()) { 9389 return; 9390 } 9391 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9392 return; 9393 } 9394 } 9395 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9396 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9397 IActivityManager am = ActivityManagerNative.getDefault(); 9398 if (am != null) { 9399 try { 9400 am.startService(null, intent, null, mContext.getOpPackageName(), 9401 UserHandle.USER_OWNER); 9402 } catch (RemoteException e) { 9403 } 9404 } 9405 } 9406 9407 @Override 9408 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9409 int installFlags, String installerPackageName, VerificationParams verificationParams, 9410 String packageAbiOverride) { 9411 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9412 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9413 } 9414 9415 @Override 9416 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9417 int installFlags, String installerPackageName, VerificationParams verificationParams, 9418 String packageAbiOverride, int userId) { 9419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9420 9421 final int callingUid = Binder.getCallingUid(); 9422 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9423 9424 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9425 try { 9426 if (observer != null) { 9427 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9428 } 9429 } catch (RemoteException re) { 9430 } 9431 return; 9432 } 9433 9434 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9435 installFlags |= PackageManager.INSTALL_FROM_ADB; 9436 9437 } else { 9438 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9439 // about installerPackageName. 9440 9441 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9442 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9443 } 9444 9445 UserHandle user; 9446 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9447 user = UserHandle.ALL; 9448 } else { 9449 user = new UserHandle(userId); 9450 } 9451 9452 // Only system components can circumvent runtime permissions when installing. 9453 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9454 && mContext.checkCallingOrSelfPermission(Manifest.permission 9455 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9456 throw new SecurityException("You need the " 9457 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9458 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9459 } 9460 9461 verificationParams.setInstallerUid(callingUid); 9462 9463 final File originFile = new File(originPath); 9464 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9465 9466 final Message msg = mHandler.obtainMessage(INIT_COPY); 9467 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9468 null, verificationParams, user, packageAbiOverride, null); 9469 mHandler.sendMessage(msg); 9470 } 9471 9472 void installStage(String packageName, File stagedDir, String stagedCid, 9473 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9474 String installerPackageName, int installerUid, UserHandle user) { 9475 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9476 params.referrerUri, installerUid, null); 9477 verifParams.setInstallerUid(installerUid); 9478 9479 final OriginInfo origin; 9480 if (stagedDir != null) { 9481 origin = OriginInfo.fromStagedFile(stagedDir); 9482 } else { 9483 origin = OriginInfo.fromStagedContainer(stagedCid); 9484 } 9485 9486 final Message msg = mHandler.obtainMessage(INIT_COPY); 9487 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9488 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9489 params.grantedRuntimePermissions); 9490 mHandler.sendMessage(msg); 9491 } 9492 9493 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9494 Bundle extras = new Bundle(1); 9495 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9496 9497 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9498 packageName, extras, null, null, new int[] {userId}); 9499 try { 9500 IActivityManager am = ActivityManagerNative.getDefault(); 9501 final boolean isSystem = 9502 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9503 if (isSystem && am.isUserRunning(userId, false)) { 9504 // The just-installed/enabled app is bundled on the system, so presumed 9505 // to be able to run automatically without needing an explicit launch. 9506 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9507 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9508 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9509 .setPackage(packageName); 9510 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9511 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9512 } 9513 } catch (RemoteException e) { 9514 // shouldn't happen 9515 Slog.w(TAG, "Unable to bootstrap installed package", e); 9516 } 9517 } 9518 9519 @Override 9520 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9521 int userId) { 9522 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9523 PackageSetting pkgSetting; 9524 final int uid = Binder.getCallingUid(); 9525 enforceCrossUserPermission(uid, userId, true, true, 9526 "setApplicationHiddenSetting for user " + userId); 9527 9528 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9529 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9530 return false; 9531 } 9532 9533 long callingId = Binder.clearCallingIdentity(); 9534 try { 9535 boolean sendAdded = false; 9536 boolean sendRemoved = false; 9537 // writer 9538 synchronized (mPackages) { 9539 pkgSetting = mSettings.mPackages.get(packageName); 9540 if (pkgSetting == null) { 9541 return false; 9542 } 9543 if (pkgSetting.getHidden(userId) != hidden) { 9544 pkgSetting.setHidden(hidden, userId); 9545 mSettings.writePackageRestrictionsLPr(userId); 9546 if (hidden) { 9547 sendRemoved = true; 9548 } else { 9549 sendAdded = true; 9550 } 9551 } 9552 } 9553 if (sendAdded) { 9554 sendPackageAddedForUser(packageName, pkgSetting, userId); 9555 return true; 9556 } 9557 if (sendRemoved) { 9558 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9559 "hiding pkg"); 9560 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9561 } 9562 } finally { 9563 Binder.restoreCallingIdentity(callingId); 9564 } 9565 return false; 9566 } 9567 9568 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9569 int userId) { 9570 final PackageRemovedInfo info = new PackageRemovedInfo(); 9571 info.removedPackage = packageName; 9572 info.removedUsers = new int[] {userId}; 9573 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9574 info.sendBroadcast(false, false, false); 9575 } 9576 9577 /** 9578 * Returns true if application is not found or there was an error. Otherwise it returns 9579 * the hidden state of the package for the given user. 9580 */ 9581 @Override 9582 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9583 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9584 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9585 false, "getApplicationHidden for user " + userId); 9586 PackageSetting pkgSetting; 9587 long callingId = Binder.clearCallingIdentity(); 9588 try { 9589 // writer 9590 synchronized (mPackages) { 9591 pkgSetting = mSettings.mPackages.get(packageName); 9592 if (pkgSetting == null) { 9593 return true; 9594 } 9595 return pkgSetting.getHidden(userId); 9596 } 9597 } finally { 9598 Binder.restoreCallingIdentity(callingId); 9599 } 9600 } 9601 9602 /** 9603 * @hide 9604 */ 9605 @Override 9606 public int installExistingPackageAsUser(String packageName, int userId) { 9607 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9608 null); 9609 PackageSetting pkgSetting; 9610 final int uid = Binder.getCallingUid(); 9611 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9612 + userId); 9613 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9614 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9615 } 9616 9617 long callingId = Binder.clearCallingIdentity(); 9618 try { 9619 boolean sendAdded = false; 9620 9621 // writer 9622 synchronized (mPackages) { 9623 pkgSetting = mSettings.mPackages.get(packageName); 9624 if (pkgSetting == null) { 9625 return PackageManager.INSTALL_FAILED_INVALID_URI; 9626 } 9627 if (!pkgSetting.getInstalled(userId)) { 9628 pkgSetting.setInstalled(true, userId); 9629 pkgSetting.setHidden(false, userId); 9630 mSettings.writePackageRestrictionsLPr(userId); 9631 sendAdded = true; 9632 } 9633 } 9634 9635 if (sendAdded) { 9636 sendPackageAddedForUser(packageName, pkgSetting, userId); 9637 } 9638 } finally { 9639 Binder.restoreCallingIdentity(callingId); 9640 } 9641 9642 return PackageManager.INSTALL_SUCCEEDED; 9643 } 9644 9645 boolean isUserRestricted(int userId, String restrictionKey) { 9646 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9647 if (restrictions.getBoolean(restrictionKey, false)) { 9648 Log.w(TAG, "User is restricted: " + restrictionKey); 9649 return true; 9650 } 9651 return false; 9652 } 9653 9654 @Override 9655 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9656 mContext.enforceCallingOrSelfPermission( 9657 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9658 "Only package verification agents can verify applications"); 9659 9660 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9661 final PackageVerificationResponse response = new PackageVerificationResponse( 9662 verificationCode, Binder.getCallingUid()); 9663 msg.arg1 = id; 9664 msg.obj = response; 9665 mHandler.sendMessage(msg); 9666 } 9667 9668 @Override 9669 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9670 long millisecondsToDelay) { 9671 mContext.enforceCallingOrSelfPermission( 9672 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9673 "Only package verification agents can extend verification timeouts"); 9674 9675 final PackageVerificationState state = mPendingVerification.get(id); 9676 final PackageVerificationResponse response = new PackageVerificationResponse( 9677 verificationCodeAtTimeout, Binder.getCallingUid()); 9678 9679 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9680 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9681 } 9682 if (millisecondsToDelay < 0) { 9683 millisecondsToDelay = 0; 9684 } 9685 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9686 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9687 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9688 } 9689 9690 if ((state != null) && !state.timeoutExtended()) { 9691 state.extendTimeout(); 9692 9693 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9694 msg.arg1 = id; 9695 msg.obj = response; 9696 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9697 } 9698 } 9699 9700 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9701 int verificationCode, UserHandle user) { 9702 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9703 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9704 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9705 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9706 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9707 9708 mContext.sendBroadcastAsUser(intent, user, 9709 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9710 } 9711 9712 private ComponentName matchComponentForVerifier(String packageName, 9713 List<ResolveInfo> receivers) { 9714 ActivityInfo targetReceiver = null; 9715 9716 final int NR = receivers.size(); 9717 for (int i = 0; i < NR; i++) { 9718 final ResolveInfo info = receivers.get(i); 9719 if (info.activityInfo == null) { 9720 continue; 9721 } 9722 9723 if (packageName.equals(info.activityInfo.packageName)) { 9724 targetReceiver = info.activityInfo; 9725 break; 9726 } 9727 } 9728 9729 if (targetReceiver == null) { 9730 return null; 9731 } 9732 9733 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9734 } 9735 9736 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9737 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9738 if (pkgInfo.verifiers.length == 0) { 9739 return null; 9740 } 9741 9742 final int N = pkgInfo.verifiers.length; 9743 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9744 for (int i = 0; i < N; i++) { 9745 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9746 9747 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9748 receivers); 9749 if (comp == null) { 9750 continue; 9751 } 9752 9753 final int verifierUid = getUidForVerifier(verifierInfo); 9754 if (verifierUid == -1) { 9755 continue; 9756 } 9757 9758 if (DEBUG_VERIFY) { 9759 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9760 + " with the correct signature"); 9761 } 9762 sufficientVerifiers.add(comp); 9763 verificationState.addSufficientVerifier(verifierUid); 9764 } 9765 9766 return sufficientVerifiers; 9767 } 9768 9769 private int getUidForVerifier(VerifierInfo verifierInfo) { 9770 synchronized (mPackages) { 9771 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9772 if (pkg == null) { 9773 return -1; 9774 } else if (pkg.mSignatures.length != 1) { 9775 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9776 + " has more than one signature; ignoring"); 9777 return -1; 9778 } 9779 9780 /* 9781 * If the public key of the package's signature does not match 9782 * our expected public key, then this is a different package and 9783 * we should skip. 9784 */ 9785 9786 final byte[] expectedPublicKey; 9787 try { 9788 final Signature verifierSig = pkg.mSignatures[0]; 9789 final PublicKey publicKey = verifierSig.getPublicKey(); 9790 expectedPublicKey = publicKey.getEncoded(); 9791 } catch (CertificateException e) { 9792 return -1; 9793 } 9794 9795 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9796 9797 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9798 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9799 + " does not have the expected public key; ignoring"); 9800 return -1; 9801 } 9802 9803 return pkg.applicationInfo.uid; 9804 } 9805 } 9806 9807 @Override 9808 public void finishPackageInstall(int token) { 9809 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9810 9811 if (DEBUG_INSTALL) { 9812 Slog.v(TAG, "BM finishing package install for " + token); 9813 } 9814 9815 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9816 mHandler.sendMessage(msg); 9817 } 9818 9819 /** 9820 * Get the verification agent timeout. 9821 * 9822 * @return verification timeout in milliseconds 9823 */ 9824 private long getVerificationTimeout() { 9825 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9826 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9827 DEFAULT_VERIFICATION_TIMEOUT); 9828 } 9829 9830 /** 9831 * Get the default verification agent response code. 9832 * 9833 * @return default verification response code 9834 */ 9835 private int getDefaultVerificationResponse() { 9836 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9837 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9838 DEFAULT_VERIFICATION_RESPONSE); 9839 } 9840 9841 /** 9842 * Check whether or not package verification has been enabled. 9843 * 9844 * @return true if verification should be performed 9845 */ 9846 private boolean isVerificationEnabled(int userId, int installFlags) { 9847 if (!DEFAULT_VERIFY_ENABLE) { 9848 return false; 9849 } 9850 9851 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9852 9853 // Check if installing from ADB 9854 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9855 // Do not run verification in a test harness environment 9856 if (ActivityManager.isRunningInTestHarness()) { 9857 return false; 9858 } 9859 if (ensureVerifyAppsEnabled) { 9860 return true; 9861 } 9862 // Check if the developer does not want package verification for ADB installs 9863 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9864 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9865 return false; 9866 } 9867 } 9868 9869 if (ensureVerifyAppsEnabled) { 9870 return true; 9871 } 9872 9873 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9874 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9875 } 9876 9877 @Override 9878 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9879 throws RemoteException { 9880 mContext.enforceCallingOrSelfPermission( 9881 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9882 "Only intentfilter verification agents can verify applications"); 9883 9884 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9885 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9886 Binder.getCallingUid(), verificationCode, failedDomains); 9887 msg.arg1 = id; 9888 msg.obj = response; 9889 mHandler.sendMessage(msg); 9890 } 9891 9892 @Override 9893 public int getIntentVerificationStatus(String packageName, int userId) { 9894 synchronized (mPackages) { 9895 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9896 } 9897 } 9898 9899 @Override 9900 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9901 mContext.enforceCallingOrSelfPermission( 9902 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9903 9904 boolean result = false; 9905 synchronized (mPackages) { 9906 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9907 } 9908 if (result) { 9909 scheduleWritePackageRestrictionsLocked(userId); 9910 } 9911 return result; 9912 } 9913 9914 @Override 9915 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9916 synchronized (mPackages) { 9917 return mSettings.getIntentFilterVerificationsLPr(packageName); 9918 } 9919 } 9920 9921 @Override 9922 public List<IntentFilter> getAllIntentFilters(String packageName) { 9923 if (TextUtils.isEmpty(packageName)) { 9924 return Collections.<IntentFilter>emptyList(); 9925 } 9926 synchronized (mPackages) { 9927 PackageParser.Package pkg = mPackages.get(packageName); 9928 if (pkg == null || pkg.activities == null) { 9929 return Collections.<IntentFilter>emptyList(); 9930 } 9931 final int count = pkg.activities.size(); 9932 ArrayList<IntentFilter> result = new ArrayList<>(); 9933 for (int n=0; n<count; n++) { 9934 PackageParser.Activity activity = pkg.activities.get(n); 9935 if (activity.intents != null || activity.intents.size() > 0) { 9936 result.addAll(activity.intents); 9937 } 9938 } 9939 return result; 9940 } 9941 } 9942 9943 @Override 9944 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9945 mContext.enforceCallingOrSelfPermission( 9946 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9947 9948 synchronized (mPackages) { 9949 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9950 if (packageName != null) { 9951 result |= updateIntentVerificationStatus(packageName, 9952 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9953 userId); 9954 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9955 packageName, userId); 9956 } 9957 return result; 9958 } 9959 } 9960 9961 @Override 9962 public String getDefaultBrowserPackageName(int userId) { 9963 synchronized (mPackages) { 9964 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9965 } 9966 } 9967 9968 /** 9969 * Get the "allow unknown sources" setting. 9970 * 9971 * @return the current "allow unknown sources" setting 9972 */ 9973 private int getUnknownSourcesSettings() { 9974 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9975 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9976 -1); 9977 } 9978 9979 @Override 9980 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9981 final int uid = Binder.getCallingUid(); 9982 // writer 9983 synchronized (mPackages) { 9984 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9985 if (targetPackageSetting == null) { 9986 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9987 } 9988 9989 PackageSetting installerPackageSetting; 9990 if (installerPackageName != null) { 9991 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9992 if (installerPackageSetting == null) { 9993 throw new IllegalArgumentException("Unknown installer package: " 9994 + installerPackageName); 9995 } 9996 } else { 9997 installerPackageSetting = null; 9998 } 9999 10000 Signature[] callerSignature; 10001 Object obj = mSettings.getUserIdLPr(uid); 10002 if (obj != null) { 10003 if (obj instanceof SharedUserSetting) { 10004 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10005 } else if (obj instanceof PackageSetting) { 10006 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10007 } else { 10008 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10009 } 10010 } else { 10011 throw new SecurityException("Unknown calling uid " + uid); 10012 } 10013 10014 // Verify: can't set installerPackageName to a package that is 10015 // not signed with the same cert as the caller. 10016 if (installerPackageSetting != null) { 10017 if (compareSignatures(callerSignature, 10018 installerPackageSetting.signatures.mSignatures) 10019 != PackageManager.SIGNATURE_MATCH) { 10020 throw new SecurityException( 10021 "Caller does not have same cert as new installer package " 10022 + installerPackageName); 10023 } 10024 } 10025 10026 // Verify: if target already has an installer package, it must 10027 // be signed with the same cert as the caller. 10028 if (targetPackageSetting.installerPackageName != null) { 10029 PackageSetting setting = mSettings.mPackages.get( 10030 targetPackageSetting.installerPackageName); 10031 // If the currently set package isn't valid, then it's always 10032 // okay to change it. 10033 if (setting != null) { 10034 if (compareSignatures(callerSignature, 10035 setting.signatures.mSignatures) 10036 != PackageManager.SIGNATURE_MATCH) { 10037 throw new SecurityException( 10038 "Caller does not have same cert as old installer package " 10039 + targetPackageSetting.installerPackageName); 10040 } 10041 } 10042 } 10043 10044 // Okay! 10045 targetPackageSetting.installerPackageName = installerPackageName; 10046 scheduleWriteSettingsLocked(); 10047 } 10048 } 10049 10050 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10051 // Queue up an async operation since the package installation may take a little while. 10052 mHandler.post(new Runnable() { 10053 public void run() { 10054 mHandler.removeCallbacks(this); 10055 // Result object to be returned 10056 PackageInstalledInfo res = new PackageInstalledInfo(); 10057 res.returnCode = currentStatus; 10058 res.uid = -1; 10059 res.pkg = null; 10060 res.removedInfo = new PackageRemovedInfo(); 10061 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10062 args.doPreInstall(res.returnCode); 10063 synchronized (mInstallLock) { 10064 installPackageLI(args, res); 10065 } 10066 args.doPostInstall(res.returnCode, res.uid); 10067 } 10068 10069 // A restore should be performed at this point if (a) the install 10070 // succeeded, (b) the operation is not an update, and (c) the new 10071 // package has not opted out of backup participation. 10072 final boolean update = res.removedInfo.removedPackage != null; 10073 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10074 boolean doRestore = !update 10075 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10076 10077 // Set up the post-install work request bookkeeping. This will be used 10078 // and cleaned up by the post-install event handling regardless of whether 10079 // there's a restore pass performed. Token values are >= 1. 10080 int token; 10081 if (mNextInstallToken < 0) mNextInstallToken = 1; 10082 token = mNextInstallToken++; 10083 10084 PostInstallData data = new PostInstallData(args, res); 10085 mRunningInstalls.put(token, data); 10086 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10087 10088 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10089 // Pass responsibility to the Backup Manager. It will perform a 10090 // restore if appropriate, then pass responsibility back to the 10091 // Package Manager to run the post-install observer callbacks 10092 // and broadcasts. 10093 IBackupManager bm = IBackupManager.Stub.asInterface( 10094 ServiceManager.getService(Context.BACKUP_SERVICE)); 10095 if (bm != null) { 10096 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10097 + " to BM for possible restore"); 10098 try { 10099 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10100 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10101 } else { 10102 doRestore = false; 10103 } 10104 } catch (RemoteException e) { 10105 // can't happen; the backup manager is local 10106 } catch (Exception e) { 10107 Slog.e(TAG, "Exception trying to enqueue restore", e); 10108 doRestore = false; 10109 } 10110 } else { 10111 Slog.e(TAG, "Backup Manager not found!"); 10112 doRestore = false; 10113 } 10114 } 10115 10116 if (!doRestore) { 10117 // No restore possible, or the Backup Manager was mysteriously not 10118 // available -- just fire the post-install work request directly. 10119 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10120 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10121 mHandler.sendMessage(msg); 10122 } 10123 } 10124 }); 10125 } 10126 10127 private abstract class HandlerParams { 10128 private static final int MAX_RETRIES = 4; 10129 10130 /** 10131 * Number of times startCopy() has been attempted and had a non-fatal 10132 * error. 10133 */ 10134 private int mRetries = 0; 10135 10136 /** User handle for the user requesting the information or installation. */ 10137 private final UserHandle mUser; 10138 10139 HandlerParams(UserHandle user) { 10140 mUser = user; 10141 } 10142 10143 UserHandle getUser() { 10144 return mUser; 10145 } 10146 10147 final boolean startCopy() { 10148 boolean res; 10149 try { 10150 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10151 10152 if (++mRetries > MAX_RETRIES) { 10153 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10154 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10155 handleServiceError(); 10156 return false; 10157 } else { 10158 handleStartCopy(); 10159 res = true; 10160 } 10161 } catch (RemoteException e) { 10162 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10163 mHandler.sendEmptyMessage(MCS_RECONNECT); 10164 res = false; 10165 } 10166 handleReturnCode(); 10167 return res; 10168 } 10169 10170 final void serviceError() { 10171 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10172 handleServiceError(); 10173 handleReturnCode(); 10174 } 10175 10176 abstract void handleStartCopy() throws RemoteException; 10177 abstract void handleServiceError(); 10178 abstract void handleReturnCode(); 10179 } 10180 10181 class MeasureParams extends HandlerParams { 10182 private final PackageStats mStats; 10183 private boolean mSuccess; 10184 10185 private final IPackageStatsObserver mObserver; 10186 10187 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10188 super(new UserHandle(stats.userHandle)); 10189 mObserver = observer; 10190 mStats = stats; 10191 } 10192 10193 @Override 10194 public String toString() { 10195 return "MeasureParams{" 10196 + Integer.toHexString(System.identityHashCode(this)) 10197 + " " + mStats.packageName + "}"; 10198 } 10199 10200 @Override 10201 void handleStartCopy() throws RemoteException { 10202 synchronized (mInstallLock) { 10203 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10204 } 10205 10206 if (mSuccess) { 10207 final boolean mounted; 10208 if (Environment.isExternalStorageEmulated()) { 10209 mounted = true; 10210 } else { 10211 final String status = Environment.getExternalStorageState(); 10212 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10213 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10214 } 10215 10216 if (mounted) { 10217 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10218 10219 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10220 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10221 10222 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10223 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10224 10225 // Always subtract cache size, since it's a subdirectory 10226 mStats.externalDataSize -= mStats.externalCacheSize; 10227 10228 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10229 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10230 10231 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10232 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10233 } 10234 } 10235 } 10236 10237 @Override 10238 void handleReturnCode() { 10239 if (mObserver != null) { 10240 try { 10241 mObserver.onGetStatsCompleted(mStats, mSuccess); 10242 } catch (RemoteException e) { 10243 Slog.i(TAG, "Observer no longer exists."); 10244 } 10245 } 10246 } 10247 10248 @Override 10249 void handleServiceError() { 10250 Slog.e(TAG, "Could not measure application " + mStats.packageName 10251 + " external storage"); 10252 } 10253 } 10254 10255 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10256 throws RemoteException { 10257 long result = 0; 10258 for (File path : paths) { 10259 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10260 } 10261 return result; 10262 } 10263 10264 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10265 for (File path : paths) { 10266 try { 10267 mcs.clearDirectory(path.getAbsolutePath()); 10268 } catch (RemoteException e) { 10269 } 10270 } 10271 } 10272 10273 static class OriginInfo { 10274 /** 10275 * Location where install is coming from, before it has been 10276 * copied/renamed into place. This could be a single monolithic APK 10277 * file, or a cluster directory. This location may be untrusted. 10278 */ 10279 final File file; 10280 final String cid; 10281 10282 /** 10283 * Flag indicating that {@link #file} or {@link #cid} has already been 10284 * staged, meaning downstream users don't need to defensively copy the 10285 * contents. 10286 */ 10287 final boolean staged; 10288 10289 /** 10290 * Flag indicating that {@link #file} or {@link #cid} is an already 10291 * installed app that is being moved. 10292 */ 10293 final boolean existing; 10294 10295 final String resolvedPath; 10296 final File resolvedFile; 10297 10298 static OriginInfo fromNothing() { 10299 return new OriginInfo(null, null, false, false); 10300 } 10301 10302 static OriginInfo fromUntrustedFile(File file) { 10303 return new OriginInfo(file, null, false, false); 10304 } 10305 10306 static OriginInfo fromExistingFile(File file) { 10307 return new OriginInfo(file, null, false, true); 10308 } 10309 10310 static OriginInfo fromStagedFile(File file) { 10311 return new OriginInfo(file, null, true, false); 10312 } 10313 10314 static OriginInfo fromStagedContainer(String cid) { 10315 return new OriginInfo(null, cid, true, false); 10316 } 10317 10318 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10319 this.file = file; 10320 this.cid = cid; 10321 this.staged = staged; 10322 this.existing = existing; 10323 10324 if (cid != null) { 10325 resolvedPath = PackageHelper.getSdDir(cid); 10326 resolvedFile = new File(resolvedPath); 10327 } else if (file != null) { 10328 resolvedPath = file.getAbsolutePath(); 10329 resolvedFile = file; 10330 } else { 10331 resolvedPath = null; 10332 resolvedFile = null; 10333 } 10334 } 10335 } 10336 10337 class MoveInfo { 10338 final int moveId; 10339 final String fromUuid; 10340 final String toUuid; 10341 final String packageName; 10342 final String dataAppName; 10343 final int appId; 10344 final String seinfo; 10345 10346 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10347 String dataAppName, int appId, String seinfo) { 10348 this.moveId = moveId; 10349 this.fromUuid = fromUuid; 10350 this.toUuid = toUuid; 10351 this.packageName = packageName; 10352 this.dataAppName = dataAppName; 10353 this.appId = appId; 10354 this.seinfo = seinfo; 10355 } 10356 } 10357 10358 class InstallParams extends HandlerParams { 10359 final OriginInfo origin; 10360 final MoveInfo move; 10361 final IPackageInstallObserver2 observer; 10362 int installFlags; 10363 final String installerPackageName; 10364 final String volumeUuid; 10365 final VerificationParams verificationParams; 10366 private InstallArgs mArgs; 10367 private int mRet; 10368 final String packageAbiOverride; 10369 final String[] grantedRuntimePermissions; 10370 10371 10372 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10373 int installFlags, String installerPackageName, String volumeUuid, 10374 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10375 String[] grantedPermissions) { 10376 super(user); 10377 this.origin = origin; 10378 this.move = move; 10379 this.observer = observer; 10380 this.installFlags = installFlags; 10381 this.installerPackageName = installerPackageName; 10382 this.volumeUuid = volumeUuid; 10383 this.verificationParams = verificationParams; 10384 this.packageAbiOverride = packageAbiOverride; 10385 this.grantedRuntimePermissions = grantedPermissions; 10386 } 10387 10388 @Override 10389 public String toString() { 10390 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10391 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10392 } 10393 10394 public ManifestDigest getManifestDigest() { 10395 if (verificationParams == null) { 10396 return null; 10397 } 10398 return verificationParams.getManifestDigest(); 10399 } 10400 10401 private int installLocationPolicy(PackageInfoLite pkgLite) { 10402 String packageName = pkgLite.packageName; 10403 int installLocation = pkgLite.installLocation; 10404 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10405 // reader 10406 synchronized (mPackages) { 10407 PackageParser.Package pkg = mPackages.get(packageName); 10408 if (pkg != null) { 10409 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10410 // Check for downgrading. 10411 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10412 try { 10413 checkDowngrade(pkg, pkgLite); 10414 } catch (PackageManagerException e) { 10415 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10416 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10417 } 10418 } 10419 // Check for updated system application. 10420 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10421 if (onSd) { 10422 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10423 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10424 } 10425 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10426 } else { 10427 if (onSd) { 10428 // Install flag overrides everything. 10429 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10430 } 10431 // If current upgrade specifies particular preference 10432 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10433 // Application explicitly specified internal. 10434 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10435 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10436 // App explictly prefers external. Let policy decide 10437 } else { 10438 // Prefer previous location 10439 if (isExternal(pkg)) { 10440 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10441 } 10442 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10443 } 10444 } 10445 } else { 10446 // Invalid install. Return error code 10447 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10448 } 10449 } 10450 } 10451 // All the special cases have been taken care of. 10452 // Return result based on recommended install location. 10453 if (onSd) { 10454 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10455 } 10456 return pkgLite.recommendedInstallLocation; 10457 } 10458 10459 /* 10460 * Invoke remote method to get package information and install 10461 * location values. Override install location based on default 10462 * policy if needed and then create install arguments based 10463 * on the install location. 10464 */ 10465 public void handleStartCopy() throws RemoteException { 10466 int ret = PackageManager.INSTALL_SUCCEEDED; 10467 10468 // If we're already staged, we've firmly committed to an install location 10469 if (origin.staged) { 10470 if (origin.file != null) { 10471 installFlags |= PackageManager.INSTALL_INTERNAL; 10472 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10473 } else if (origin.cid != null) { 10474 installFlags |= PackageManager.INSTALL_EXTERNAL; 10475 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10476 } else { 10477 throw new IllegalStateException("Invalid stage location"); 10478 } 10479 } 10480 10481 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10482 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10483 10484 PackageInfoLite pkgLite = null; 10485 10486 if (onInt && onSd) { 10487 // Check if both bits are set. 10488 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10489 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10490 } else { 10491 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10492 packageAbiOverride); 10493 10494 /* 10495 * If we have too little free space, try to free cache 10496 * before giving up. 10497 */ 10498 if (!origin.staged && pkgLite.recommendedInstallLocation 10499 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10500 // TODO: focus freeing disk space on the target device 10501 final StorageManager storage = StorageManager.from(mContext); 10502 final long lowThreshold = storage.getStorageLowBytes( 10503 Environment.getDataDirectory()); 10504 10505 final long sizeBytes = mContainerService.calculateInstalledSize( 10506 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10507 10508 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10509 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10510 installFlags, packageAbiOverride); 10511 } 10512 10513 /* 10514 * The cache free must have deleted the file we 10515 * downloaded to install. 10516 * 10517 * TODO: fix the "freeCache" call to not delete 10518 * the file we care about. 10519 */ 10520 if (pkgLite.recommendedInstallLocation 10521 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10522 pkgLite.recommendedInstallLocation 10523 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10524 } 10525 } 10526 } 10527 10528 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10529 int loc = pkgLite.recommendedInstallLocation; 10530 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10531 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10532 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10533 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10534 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10535 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10536 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10537 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10538 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10539 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10540 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10541 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10542 } else { 10543 // Override with defaults if needed. 10544 loc = installLocationPolicy(pkgLite); 10545 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10546 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10547 } else if (!onSd && !onInt) { 10548 // Override install location with flags 10549 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10550 // Set the flag to install on external media. 10551 installFlags |= PackageManager.INSTALL_EXTERNAL; 10552 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10553 } else { 10554 // Make sure the flag for installing on external 10555 // media is unset 10556 installFlags |= PackageManager.INSTALL_INTERNAL; 10557 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10558 } 10559 } 10560 } 10561 } 10562 10563 final InstallArgs args = createInstallArgs(this); 10564 mArgs = args; 10565 10566 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10567 /* 10568 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10569 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10570 */ 10571 int userIdentifier = getUser().getIdentifier(); 10572 if (userIdentifier == UserHandle.USER_ALL 10573 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10574 userIdentifier = UserHandle.USER_OWNER; 10575 } 10576 10577 /* 10578 * Determine if we have any installed package verifiers. If we 10579 * do, then we'll defer to them to verify the packages. 10580 */ 10581 final int requiredUid = mRequiredVerifierPackage == null ? -1 10582 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10583 if (!origin.existing && requiredUid != -1 10584 && isVerificationEnabled(userIdentifier, installFlags)) { 10585 final Intent verification = new Intent( 10586 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10587 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10588 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10589 PACKAGE_MIME_TYPE); 10590 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10591 10592 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10593 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10594 0 /* TODO: Which userId? */); 10595 10596 if (DEBUG_VERIFY) { 10597 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10598 + verification.toString() + " with " + pkgLite.verifiers.length 10599 + " optional verifiers"); 10600 } 10601 10602 final int verificationId = mPendingVerificationToken++; 10603 10604 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10605 10606 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10607 installerPackageName); 10608 10609 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10610 installFlags); 10611 10612 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10613 pkgLite.packageName); 10614 10615 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10616 pkgLite.versionCode); 10617 10618 if (verificationParams != null) { 10619 if (verificationParams.getVerificationURI() != null) { 10620 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10621 verificationParams.getVerificationURI()); 10622 } 10623 if (verificationParams.getOriginatingURI() != null) { 10624 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10625 verificationParams.getOriginatingURI()); 10626 } 10627 if (verificationParams.getReferrer() != null) { 10628 verification.putExtra(Intent.EXTRA_REFERRER, 10629 verificationParams.getReferrer()); 10630 } 10631 if (verificationParams.getOriginatingUid() >= 0) { 10632 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10633 verificationParams.getOriginatingUid()); 10634 } 10635 if (verificationParams.getInstallerUid() >= 0) { 10636 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10637 verificationParams.getInstallerUid()); 10638 } 10639 } 10640 10641 final PackageVerificationState verificationState = new PackageVerificationState( 10642 requiredUid, args); 10643 10644 mPendingVerification.append(verificationId, verificationState); 10645 10646 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10647 receivers, verificationState); 10648 10649 // Apps installed for "all" users use the device owner to verify the app 10650 UserHandle verifierUser = getUser(); 10651 if (verifierUser == UserHandle.ALL) { 10652 verifierUser = UserHandle.OWNER; 10653 } 10654 10655 /* 10656 * If any sufficient verifiers were listed in the package 10657 * manifest, attempt to ask them. 10658 */ 10659 if (sufficientVerifiers != null) { 10660 final int N = sufficientVerifiers.size(); 10661 if (N == 0) { 10662 Slog.i(TAG, "Additional verifiers required, but none installed."); 10663 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10664 } else { 10665 for (int i = 0; i < N; i++) { 10666 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10667 10668 final Intent sufficientIntent = new Intent(verification); 10669 sufficientIntent.setComponent(verifierComponent); 10670 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10671 } 10672 } 10673 } 10674 10675 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10676 mRequiredVerifierPackage, receivers); 10677 if (ret == PackageManager.INSTALL_SUCCEEDED 10678 && mRequiredVerifierPackage != null) { 10679 /* 10680 * Send the intent to the required verification agent, 10681 * but only start the verification timeout after the 10682 * target BroadcastReceivers have run. 10683 */ 10684 verification.setComponent(requiredVerifierComponent); 10685 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10686 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10687 new BroadcastReceiver() { 10688 @Override 10689 public void onReceive(Context context, Intent intent) { 10690 final Message msg = mHandler 10691 .obtainMessage(CHECK_PENDING_VERIFICATION); 10692 msg.arg1 = verificationId; 10693 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10694 } 10695 }, null, 0, null, null); 10696 10697 /* 10698 * We don't want the copy to proceed until verification 10699 * succeeds, so null out this field. 10700 */ 10701 mArgs = null; 10702 } 10703 } else { 10704 /* 10705 * No package verification is enabled, so immediately start 10706 * the remote call to initiate copy using temporary file. 10707 */ 10708 ret = args.copyApk(mContainerService, true); 10709 } 10710 } 10711 10712 mRet = ret; 10713 } 10714 10715 @Override 10716 void handleReturnCode() { 10717 // If mArgs is null, then MCS couldn't be reached. When it 10718 // reconnects, it will try again to install. At that point, this 10719 // will succeed. 10720 if (mArgs != null) { 10721 processPendingInstall(mArgs, mRet); 10722 } 10723 } 10724 10725 @Override 10726 void handleServiceError() { 10727 mArgs = createInstallArgs(this); 10728 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10729 } 10730 10731 public boolean isForwardLocked() { 10732 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10733 } 10734 } 10735 10736 /** 10737 * Used during creation of InstallArgs 10738 * 10739 * @param installFlags package installation flags 10740 * @return true if should be installed on external storage 10741 */ 10742 private static boolean installOnExternalAsec(int installFlags) { 10743 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10744 return false; 10745 } 10746 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10747 return true; 10748 } 10749 return false; 10750 } 10751 10752 /** 10753 * Used during creation of InstallArgs 10754 * 10755 * @param installFlags package installation flags 10756 * @return true if should be installed as forward locked 10757 */ 10758 private static boolean installForwardLocked(int installFlags) { 10759 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10760 } 10761 10762 private InstallArgs createInstallArgs(InstallParams params) { 10763 if (params.move != null) { 10764 return new MoveInstallArgs(params); 10765 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10766 return new AsecInstallArgs(params); 10767 } else { 10768 return new FileInstallArgs(params); 10769 } 10770 } 10771 10772 /** 10773 * Create args that describe an existing installed package. Typically used 10774 * when cleaning up old installs, or used as a move source. 10775 */ 10776 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10777 String resourcePath, String[] instructionSets) { 10778 final boolean isInAsec; 10779 if (installOnExternalAsec(installFlags)) { 10780 /* Apps on SD card are always in ASEC containers. */ 10781 isInAsec = true; 10782 } else if (installForwardLocked(installFlags) 10783 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10784 /* 10785 * Forward-locked apps are only in ASEC containers if they're the 10786 * new style 10787 */ 10788 isInAsec = true; 10789 } else { 10790 isInAsec = false; 10791 } 10792 10793 if (isInAsec) { 10794 return new AsecInstallArgs(codePath, instructionSets, 10795 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10796 } else { 10797 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10798 } 10799 } 10800 10801 static abstract class InstallArgs { 10802 /** @see InstallParams#origin */ 10803 final OriginInfo origin; 10804 /** @see InstallParams#move */ 10805 final MoveInfo move; 10806 10807 final IPackageInstallObserver2 observer; 10808 // Always refers to PackageManager flags only 10809 final int installFlags; 10810 final String installerPackageName; 10811 final String volumeUuid; 10812 final ManifestDigest manifestDigest; 10813 final UserHandle user; 10814 final String abiOverride; 10815 final String[] installGrantPermissions; 10816 10817 // The list of instruction sets supported by this app. This is currently 10818 // only used during the rmdex() phase to clean up resources. We can get rid of this 10819 // if we move dex files under the common app path. 10820 /* nullable */ String[] instructionSets; 10821 10822 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10823 int installFlags, String installerPackageName, String volumeUuid, 10824 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10825 String abiOverride, String[] installGrantPermissions) { 10826 this.origin = origin; 10827 this.move = move; 10828 this.installFlags = installFlags; 10829 this.observer = observer; 10830 this.installerPackageName = installerPackageName; 10831 this.volumeUuid = volumeUuid; 10832 this.manifestDigest = manifestDigest; 10833 this.user = user; 10834 this.instructionSets = instructionSets; 10835 this.abiOverride = abiOverride; 10836 this.installGrantPermissions = installGrantPermissions; 10837 } 10838 10839 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10840 abstract int doPreInstall(int status); 10841 10842 /** 10843 * Rename package into final resting place. All paths on the given 10844 * scanned package should be updated to reflect the rename. 10845 */ 10846 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10847 abstract int doPostInstall(int status, int uid); 10848 10849 /** @see PackageSettingBase#codePathString */ 10850 abstract String getCodePath(); 10851 /** @see PackageSettingBase#resourcePathString */ 10852 abstract String getResourcePath(); 10853 10854 // Need installer lock especially for dex file removal. 10855 abstract void cleanUpResourcesLI(); 10856 abstract boolean doPostDeleteLI(boolean delete); 10857 10858 /** 10859 * Called before the source arguments are copied. This is used mostly 10860 * for MoveParams when it needs to read the source file to put it in the 10861 * destination. 10862 */ 10863 int doPreCopy() { 10864 return PackageManager.INSTALL_SUCCEEDED; 10865 } 10866 10867 /** 10868 * Called after the source arguments are copied. This is used mostly for 10869 * MoveParams when it needs to read the source file to put it in the 10870 * destination. 10871 * 10872 * @return 10873 */ 10874 int doPostCopy(int uid) { 10875 return PackageManager.INSTALL_SUCCEEDED; 10876 } 10877 10878 protected boolean isFwdLocked() { 10879 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10880 } 10881 10882 protected boolean isExternalAsec() { 10883 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10884 } 10885 10886 UserHandle getUser() { 10887 return user; 10888 } 10889 } 10890 10891 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10892 if (!allCodePaths.isEmpty()) { 10893 if (instructionSets == null) { 10894 throw new IllegalStateException("instructionSet == null"); 10895 } 10896 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10897 for (String codePath : allCodePaths) { 10898 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10899 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10900 if (retCode < 0) { 10901 Slog.w(TAG, "Couldn't remove dex file for package: " 10902 + " at location " + codePath + ", retcode=" + retCode); 10903 // we don't consider this to be a failure of the core package deletion 10904 } 10905 } 10906 } 10907 } 10908 } 10909 10910 /** 10911 * Logic to handle installation of non-ASEC applications, including copying 10912 * and renaming logic. 10913 */ 10914 class FileInstallArgs extends InstallArgs { 10915 private File codeFile; 10916 private File resourceFile; 10917 10918 // Example topology: 10919 // /data/app/com.example/base.apk 10920 // /data/app/com.example/split_foo.apk 10921 // /data/app/com.example/lib/arm/libfoo.so 10922 // /data/app/com.example/lib/arm64/libfoo.so 10923 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10924 10925 /** New install */ 10926 FileInstallArgs(InstallParams params) { 10927 super(params.origin, params.move, params.observer, params.installFlags, 10928 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10929 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10930 params.grantedRuntimePermissions); 10931 if (isFwdLocked()) { 10932 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10933 } 10934 } 10935 10936 /** Existing install */ 10937 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10938 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10939 null, null); 10940 this.codeFile = (codePath != null) ? new File(codePath) : null; 10941 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10942 } 10943 10944 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10945 if (origin.staged) { 10946 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10947 codeFile = origin.file; 10948 resourceFile = origin.file; 10949 return PackageManager.INSTALL_SUCCEEDED; 10950 } 10951 10952 try { 10953 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10954 codeFile = tempDir; 10955 resourceFile = tempDir; 10956 } catch (IOException e) { 10957 Slog.w(TAG, "Failed to create copy file: " + e); 10958 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10959 } 10960 10961 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10962 @Override 10963 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10964 if (!FileUtils.isValidExtFilename(name)) { 10965 throw new IllegalArgumentException("Invalid filename: " + name); 10966 } 10967 try { 10968 final File file = new File(codeFile, name); 10969 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10970 O_RDWR | O_CREAT, 0644); 10971 Os.chmod(file.getAbsolutePath(), 0644); 10972 return new ParcelFileDescriptor(fd); 10973 } catch (ErrnoException e) { 10974 throw new RemoteException("Failed to open: " + e.getMessage()); 10975 } 10976 } 10977 }; 10978 10979 int ret = PackageManager.INSTALL_SUCCEEDED; 10980 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10981 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10982 Slog.e(TAG, "Failed to copy package"); 10983 return ret; 10984 } 10985 10986 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10987 NativeLibraryHelper.Handle handle = null; 10988 try { 10989 handle = NativeLibraryHelper.Handle.create(codeFile); 10990 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10991 abiOverride); 10992 } catch (IOException e) { 10993 Slog.e(TAG, "Copying native libraries failed", e); 10994 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10995 } finally { 10996 IoUtils.closeQuietly(handle); 10997 } 10998 10999 return ret; 11000 } 11001 11002 int doPreInstall(int status) { 11003 if (status != PackageManager.INSTALL_SUCCEEDED) { 11004 cleanUp(); 11005 } 11006 return status; 11007 } 11008 11009 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11010 if (status != PackageManager.INSTALL_SUCCEEDED) { 11011 cleanUp(); 11012 return false; 11013 } 11014 11015 final File targetDir = codeFile.getParentFile(); 11016 final File beforeCodeFile = codeFile; 11017 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11018 11019 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11020 try { 11021 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11022 } catch (ErrnoException e) { 11023 Slog.w(TAG, "Failed to rename", e); 11024 return false; 11025 } 11026 11027 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11028 Slog.w(TAG, "Failed to restorecon"); 11029 return false; 11030 } 11031 11032 // Reflect the rename internally 11033 codeFile = afterCodeFile; 11034 resourceFile = afterCodeFile; 11035 11036 // Reflect the rename in scanned details 11037 pkg.codePath = afterCodeFile.getAbsolutePath(); 11038 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11039 pkg.baseCodePath); 11040 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11041 pkg.splitCodePaths); 11042 11043 // Reflect the rename in app info 11044 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11045 pkg.applicationInfo.setCodePath(pkg.codePath); 11046 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11047 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11048 pkg.applicationInfo.setResourcePath(pkg.codePath); 11049 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11050 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11051 11052 return true; 11053 } 11054 11055 int doPostInstall(int status, int uid) { 11056 if (status != PackageManager.INSTALL_SUCCEEDED) { 11057 cleanUp(); 11058 } 11059 return status; 11060 } 11061 11062 @Override 11063 String getCodePath() { 11064 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11065 } 11066 11067 @Override 11068 String getResourcePath() { 11069 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11070 } 11071 11072 private boolean cleanUp() { 11073 if (codeFile == null || !codeFile.exists()) { 11074 return false; 11075 } 11076 11077 if (codeFile.isDirectory()) { 11078 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11079 } else { 11080 codeFile.delete(); 11081 } 11082 11083 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11084 resourceFile.delete(); 11085 } 11086 11087 return true; 11088 } 11089 11090 void cleanUpResourcesLI() { 11091 // Try enumerating all code paths before deleting 11092 List<String> allCodePaths = Collections.EMPTY_LIST; 11093 if (codeFile != null && codeFile.exists()) { 11094 try { 11095 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11096 allCodePaths = pkg.getAllCodePaths(); 11097 } catch (PackageParserException e) { 11098 // Ignored; we tried our best 11099 } 11100 } 11101 11102 cleanUp(); 11103 removeDexFiles(allCodePaths, instructionSets); 11104 } 11105 11106 boolean doPostDeleteLI(boolean delete) { 11107 // XXX err, shouldn't we respect the delete flag? 11108 cleanUpResourcesLI(); 11109 return true; 11110 } 11111 } 11112 11113 private boolean isAsecExternal(String cid) { 11114 final String asecPath = PackageHelper.getSdFilesystem(cid); 11115 return !asecPath.startsWith(mAsecInternalPath); 11116 } 11117 11118 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11119 PackageManagerException { 11120 if (copyRet < 0) { 11121 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11122 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11123 throw new PackageManagerException(copyRet, message); 11124 } 11125 } 11126 } 11127 11128 /** 11129 * Extract the MountService "container ID" from the full code path of an 11130 * .apk. 11131 */ 11132 static String cidFromCodePath(String fullCodePath) { 11133 int eidx = fullCodePath.lastIndexOf("/"); 11134 String subStr1 = fullCodePath.substring(0, eidx); 11135 int sidx = subStr1.lastIndexOf("/"); 11136 return subStr1.substring(sidx+1, eidx); 11137 } 11138 11139 /** 11140 * Logic to handle installation of ASEC applications, including copying and 11141 * renaming logic. 11142 */ 11143 class AsecInstallArgs extends InstallArgs { 11144 static final String RES_FILE_NAME = "pkg.apk"; 11145 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11146 11147 String cid; 11148 String packagePath; 11149 String resourcePath; 11150 11151 /** New install */ 11152 AsecInstallArgs(InstallParams params) { 11153 super(params.origin, params.move, params.observer, params.installFlags, 11154 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11155 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11156 params.grantedRuntimePermissions); 11157 } 11158 11159 /** Existing install */ 11160 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11161 boolean isExternal, boolean isForwardLocked) { 11162 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11163 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11164 instructionSets, null, null); 11165 // Hackily pretend we're still looking at a full code path 11166 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11167 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11168 } 11169 11170 // Extract cid from fullCodePath 11171 int eidx = fullCodePath.lastIndexOf("/"); 11172 String subStr1 = fullCodePath.substring(0, eidx); 11173 int sidx = subStr1.lastIndexOf("/"); 11174 cid = subStr1.substring(sidx+1, eidx); 11175 setMountPath(subStr1); 11176 } 11177 11178 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11179 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11180 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11181 instructionSets, null, null); 11182 this.cid = cid; 11183 setMountPath(PackageHelper.getSdDir(cid)); 11184 } 11185 11186 void createCopyFile() { 11187 cid = mInstallerService.allocateExternalStageCidLegacy(); 11188 } 11189 11190 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11191 if (origin.staged) { 11192 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11193 cid = origin.cid; 11194 setMountPath(PackageHelper.getSdDir(cid)); 11195 return PackageManager.INSTALL_SUCCEEDED; 11196 } 11197 11198 if (temp) { 11199 createCopyFile(); 11200 } else { 11201 /* 11202 * Pre-emptively destroy the container since it's destroyed if 11203 * copying fails due to it existing anyway. 11204 */ 11205 PackageHelper.destroySdDir(cid); 11206 } 11207 11208 final String newMountPath = imcs.copyPackageToContainer( 11209 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11210 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11211 11212 if (newMountPath != null) { 11213 setMountPath(newMountPath); 11214 return PackageManager.INSTALL_SUCCEEDED; 11215 } else { 11216 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11217 } 11218 } 11219 11220 @Override 11221 String getCodePath() { 11222 return packagePath; 11223 } 11224 11225 @Override 11226 String getResourcePath() { 11227 return resourcePath; 11228 } 11229 11230 int doPreInstall(int status) { 11231 if (status != PackageManager.INSTALL_SUCCEEDED) { 11232 // Destroy container 11233 PackageHelper.destroySdDir(cid); 11234 } else { 11235 boolean mounted = PackageHelper.isContainerMounted(cid); 11236 if (!mounted) { 11237 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11238 Process.SYSTEM_UID); 11239 if (newMountPath != null) { 11240 setMountPath(newMountPath); 11241 } else { 11242 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11243 } 11244 } 11245 } 11246 return status; 11247 } 11248 11249 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11250 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11251 String newMountPath = null; 11252 if (PackageHelper.isContainerMounted(cid)) { 11253 // Unmount the container 11254 if (!PackageHelper.unMountSdDir(cid)) { 11255 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11256 return false; 11257 } 11258 } 11259 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11260 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11261 " which might be stale. Will try to clean up."); 11262 // Clean up the stale container and proceed to recreate. 11263 if (!PackageHelper.destroySdDir(newCacheId)) { 11264 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11265 return false; 11266 } 11267 // Successfully cleaned up stale container. Try to rename again. 11268 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11269 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11270 + " inspite of cleaning it up."); 11271 return false; 11272 } 11273 } 11274 if (!PackageHelper.isContainerMounted(newCacheId)) { 11275 Slog.w(TAG, "Mounting container " + newCacheId); 11276 newMountPath = PackageHelper.mountSdDir(newCacheId, 11277 getEncryptKey(), Process.SYSTEM_UID); 11278 } else { 11279 newMountPath = PackageHelper.getSdDir(newCacheId); 11280 } 11281 if (newMountPath == null) { 11282 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11283 return false; 11284 } 11285 Log.i(TAG, "Succesfully renamed " + cid + 11286 " to " + newCacheId + 11287 " at new path: " + newMountPath); 11288 cid = newCacheId; 11289 11290 final File beforeCodeFile = new File(packagePath); 11291 setMountPath(newMountPath); 11292 final File afterCodeFile = new File(packagePath); 11293 11294 // Reflect the rename in scanned details 11295 pkg.codePath = afterCodeFile.getAbsolutePath(); 11296 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11297 pkg.baseCodePath); 11298 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11299 pkg.splitCodePaths); 11300 11301 // Reflect the rename in app info 11302 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11303 pkg.applicationInfo.setCodePath(pkg.codePath); 11304 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11305 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11306 pkg.applicationInfo.setResourcePath(pkg.codePath); 11307 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11308 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11309 11310 return true; 11311 } 11312 11313 private void setMountPath(String mountPath) { 11314 final File mountFile = new File(mountPath); 11315 11316 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11317 if (monolithicFile.exists()) { 11318 packagePath = monolithicFile.getAbsolutePath(); 11319 if (isFwdLocked()) { 11320 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11321 } else { 11322 resourcePath = packagePath; 11323 } 11324 } else { 11325 packagePath = mountFile.getAbsolutePath(); 11326 resourcePath = packagePath; 11327 } 11328 } 11329 11330 int doPostInstall(int status, int uid) { 11331 if (status != PackageManager.INSTALL_SUCCEEDED) { 11332 cleanUp(); 11333 } else { 11334 final int groupOwner; 11335 final String protectedFile; 11336 if (isFwdLocked()) { 11337 groupOwner = UserHandle.getSharedAppGid(uid); 11338 protectedFile = RES_FILE_NAME; 11339 } else { 11340 groupOwner = -1; 11341 protectedFile = null; 11342 } 11343 11344 if (uid < Process.FIRST_APPLICATION_UID 11345 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11346 Slog.e(TAG, "Failed to finalize " + cid); 11347 PackageHelper.destroySdDir(cid); 11348 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11349 } 11350 11351 boolean mounted = PackageHelper.isContainerMounted(cid); 11352 if (!mounted) { 11353 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11354 } 11355 } 11356 return status; 11357 } 11358 11359 private void cleanUp() { 11360 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11361 11362 // Destroy secure container 11363 PackageHelper.destroySdDir(cid); 11364 } 11365 11366 private List<String> getAllCodePaths() { 11367 final File codeFile = new File(getCodePath()); 11368 if (codeFile != null && codeFile.exists()) { 11369 try { 11370 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11371 return pkg.getAllCodePaths(); 11372 } catch (PackageParserException e) { 11373 // Ignored; we tried our best 11374 } 11375 } 11376 return Collections.EMPTY_LIST; 11377 } 11378 11379 void cleanUpResourcesLI() { 11380 // Enumerate all code paths before deleting 11381 cleanUpResourcesLI(getAllCodePaths()); 11382 } 11383 11384 private void cleanUpResourcesLI(List<String> allCodePaths) { 11385 cleanUp(); 11386 removeDexFiles(allCodePaths, instructionSets); 11387 } 11388 11389 String getPackageName() { 11390 return getAsecPackageName(cid); 11391 } 11392 11393 boolean doPostDeleteLI(boolean delete) { 11394 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11395 final List<String> allCodePaths = getAllCodePaths(); 11396 boolean mounted = PackageHelper.isContainerMounted(cid); 11397 if (mounted) { 11398 // Unmount first 11399 if (PackageHelper.unMountSdDir(cid)) { 11400 mounted = false; 11401 } 11402 } 11403 if (!mounted && delete) { 11404 cleanUpResourcesLI(allCodePaths); 11405 } 11406 return !mounted; 11407 } 11408 11409 @Override 11410 int doPreCopy() { 11411 if (isFwdLocked()) { 11412 if (!PackageHelper.fixSdPermissions(cid, 11413 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11414 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11415 } 11416 } 11417 11418 return PackageManager.INSTALL_SUCCEEDED; 11419 } 11420 11421 @Override 11422 int doPostCopy(int uid) { 11423 if (isFwdLocked()) { 11424 if (uid < Process.FIRST_APPLICATION_UID 11425 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11426 RES_FILE_NAME)) { 11427 Slog.e(TAG, "Failed to finalize " + cid); 11428 PackageHelper.destroySdDir(cid); 11429 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11430 } 11431 } 11432 11433 return PackageManager.INSTALL_SUCCEEDED; 11434 } 11435 } 11436 11437 /** 11438 * Logic to handle movement of existing installed applications. 11439 */ 11440 class MoveInstallArgs extends InstallArgs { 11441 private File codeFile; 11442 private File resourceFile; 11443 11444 /** New install */ 11445 MoveInstallArgs(InstallParams params) { 11446 super(params.origin, params.move, params.observer, params.installFlags, 11447 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11448 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11449 params.grantedRuntimePermissions); 11450 } 11451 11452 int copyApk(IMediaContainerService imcs, boolean temp) { 11453 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11454 + move.fromUuid + " to " + move.toUuid); 11455 synchronized (mInstaller) { 11456 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11457 move.dataAppName, move.appId, move.seinfo) != 0) { 11458 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11459 } 11460 } 11461 11462 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11463 resourceFile = codeFile; 11464 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11465 11466 return PackageManager.INSTALL_SUCCEEDED; 11467 } 11468 11469 int doPreInstall(int status) { 11470 if (status != PackageManager.INSTALL_SUCCEEDED) { 11471 cleanUp(move.toUuid); 11472 } 11473 return status; 11474 } 11475 11476 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11477 if (status != PackageManager.INSTALL_SUCCEEDED) { 11478 cleanUp(move.toUuid); 11479 return false; 11480 } 11481 11482 // Reflect the move in app info 11483 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11484 pkg.applicationInfo.setCodePath(pkg.codePath); 11485 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11486 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11487 pkg.applicationInfo.setResourcePath(pkg.codePath); 11488 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11489 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11490 11491 return true; 11492 } 11493 11494 int doPostInstall(int status, int uid) { 11495 if (status == PackageManager.INSTALL_SUCCEEDED) { 11496 cleanUp(move.fromUuid); 11497 } else { 11498 cleanUp(move.toUuid); 11499 } 11500 return status; 11501 } 11502 11503 @Override 11504 String getCodePath() { 11505 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11506 } 11507 11508 @Override 11509 String getResourcePath() { 11510 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11511 } 11512 11513 private boolean cleanUp(String volumeUuid) { 11514 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11515 move.dataAppName); 11516 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11517 synchronized (mInstallLock) { 11518 // Clean up both app data and code 11519 removeDataDirsLI(volumeUuid, move.packageName); 11520 if (codeFile.isDirectory()) { 11521 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11522 } else { 11523 codeFile.delete(); 11524 } 11525 } 11526 return true; 11527 } 11528 11529 void cleanUpResourcesLI() { 11530 throw new UnsupportedOperationException(); 11531 } 11532 11533 boolean doPostDeleteLI(boolean delete) { 11534 throw new UnsupportedOperationException(); 11535 } 11536 } 11537 11538 static String getAsecPackageName(String packageCid) { 11539 int idx = packageCid.lastIndexOf("-"); 11540 if (idx == -1) { 11541 return packageCid; 11542 } 11543 return packageCid.substring(0, idx); 11544 } 11545 11546 // Utility method used to create code paths based on package name and available index. 11547 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11548 String idxStr = ""; 11549 int idx = 1; 11550 // Fall back to default value of idx=1 if prefix is not 11551 // part of oldCodePath 11552 if (oldCodePath != null) { 11553 String subStr = oldCodePath; 11554 // Drop the suffix right away 11555 if (suffix != null && subStr.endsWith(suffix)) { 11556 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11557 } 11558 // If oldCodePath already contains prefix find out the 11559 // ending index to either increment or decrement. 11560 int sidx = subStr.lastIndexOf(prefix); 11561 if (sidx != -1) { 11562 subStr = subStr.substring(sidx + prefix.length()); 11563 if (subStr != null) { 11564 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11565 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11566 } 11567 try { 11568 idx = Integer.parseInt(subStr); 11569 if (idx <= 1) { 11570 idx++; 11571 } else { 11572 idx--; 11573 } 11574 } catch(NumberFormatException e) { 11575 } 11576 } 11577 } 11578 } 11579 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11580 return prefix + idxStr; 11581 } 11582 11583 private File getNextCodePath(File targetDir, String packageName) { 11584 int suffix = 1; 11585 File result; 11586 do { 11587 result = new File(targetDir, packageName + "-" + suffix); 11588 suffix++; 11589 } while (result.exists()); 11590 return result; 11591 } 11592 11593 // Utility method that returns the relative package path with respect 11594 // to the installation directory. Like say for /data/data/com.test-1.apk 11595 // string com.test-1 is returned. 11596 static String deriveCodePathName(String codePath) { 11597 if (codePath == null) { 11598 return null; 11599 } 11600 final File codeFile = new File(codePath); 11601 final String name = codeFile.getName(); 11602 if (codeFile.isDirectory()) { 11603 return name; 11604 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11605 final int lastDot = name.lastIndexOf('.'); 11606 return name.substring(0, lastDot); 11607 } else { 11608 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11609 return null; 11610 } 11611 } 11612 11613 class PackageInstalledInfo { 11614 String name; 11615 int uid; 11616 // The set of users that originally had this package installed. 11617 int[] origUsers; 11618 // The set of users that now have this package installed. 11619 int[] newUsers; 11620 PackageParser.Package pkg; 11621 int returnCode; 11622 String returnMsg; 11623 PackageRemovedInfo removedInfo; 11624 11625 public void setError(int code, String msg) { 11626 returnCode = code; 11627 returnMsg = msg; 11628 Slog.w(TAG, msg); 11629 } 11630 11631 public void setError(String msg, PackageParserException e) { 11632 returnCode = e.error; 11633 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11634 Slog.w(TAG, msg, e); 11635 } 11636 11637 public void setError(String msg, PackageManagerException e) { 11638 returnCode = e.error; 11639 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11640 Slog.w(TAG, msg, e); 11641 } 11642 11643 // In some error cases we want to convey more info back to the observer 11644 String origPackage; 11645 String origPermission; 11646 } 11647 11648 /* 11649 * Install a non-existing package. 11650 */ 11651 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11652 UserHandle user, String installerPackageName, String volumeUuid, 11653 PackageInstalledInfo res) { 11654 // Remember this for later, in case we need to rollback this install 11655 String pkgName = pkg.packageName; 11656 11657 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11658 final boolean dataDirExists = Environment 11659 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11660 synchronized(mPackages) { 11661 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11662 // A package with the same name is already installed, though 11663 // it has been renamed to an older name. The package we 11664 // are trying to install should be installed as an update to 11665 // the existing one, but that has not been requested, so bail. 11666 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11667 + " without first uninstalling package running as " 11668 + mSettings.mRenamedPackages.get(pkgName)); 11669 return; 11670 } 11671 if (mPackages.containsKey(pkgName)) { 11672 // Don't allow installation over an existing package with the same name. 11673 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11674 + " without first uninstalling."); 11675 return; 11676 } 11677 } 11678 11679 try { 11680 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11681 System.currentTimeMillis(), user); 11682 11683 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11684 // delete the partially installed application. the data directory will have to be 11685 // restored if it was already existing 11686 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11687 // remove package from internal structures. Note that we want deletePackageX to 11688 // delete the package data and cache directories that it created in 11689 // scanPackageLocked, unless those directories existed before we even tried to 11690 // install. 11691 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11692 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11693 res.removedInfo, true); 11694 } 11695 11696 } catch (PackageManagerException e) { 11697 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11698 } 11699 } 11700 11701 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11702 // Can't rotate keys during boot or if sharedUser. 11703 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11704 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11705 return false; 11706 } 11707 // app is using upgradeKeySets; make sure all are valid 11708 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11709 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11710 for (int i = 0; i < upgradeKeySets.length; i++) { 11711 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11712 Slog.wtf(TAG, "Package " 11713 + (oldPs.name != null ? oldPs.name : "<null>") 11714 + " contains upgrade-key-set reference to unknown key-set: " 11715 + upgradeKeySets[i] 11716 + " reverting to signatures check."); 11717 return false; 11718 } 11719 } 11720 return true; 11721 } 11722 11723 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11724 // Upgrade keysets are being used. Determine if new package has a superset of the 11725 // required keys. 11726 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11727 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11728 for (int i = 0; i < upgradeKeySets.length; i++) { 11729 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11730 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11731 return true; 11732 } 11733 } 11734 return false; 11735 } 11736 11737 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11738 UserHandle user, String installerPackageName, String volumeUuid, 11739 PackageInstalledInfo res) { 11740 final PackageParser.Package oldPackage; 11741 final String pkgName = pkg.packageName; 11742 final int[] allUsers; 11743 final boolean[] perUserInstalled; 11744 final boolean weFroze; 11745 11746 // First find the old package info and check signatures 11747 synchronized(mPackages) { 11748 oldPackage = mPackages.get(pkgName); 11749 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11750 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11751 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11752 if(!checkUpgradeKeySetLP(ps, pkg)) { 11753 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11754 "New package not signed by keys specified by upgrade-keysets: " 11755 + pkgName); 11756 return; 11757 } 11758 } else { 11759 // default to original signature matching 11760 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11761 != PackageManager.SIGNATURE_MATCH) { 11762 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11763 "New package has a different signature: " + pkgName); 11764 return; 11765 } 11766 } 11767 11768 // In case of rollback, remember per-user/profile install state 11769 allUsers = sUserManager.getUserIds(); 11770 perUserInstalled = new boolean[allUsers.length]; 11771 for (int i = 0; i < allUsers.length; i++) { 11772 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11773 } 11774 11775 // Mark the app as frozen to prevent launching during the upgrade 11776 // process, and then kill all running instances 11777 if (!ps.frozen) { 11778 ps.frozen = true; 11779 weFroze = true; 11780 } else { 11781 weFroze = false; 11782 } 11783 } 11784 11785 // Now that we're guarded by frozen state, kill app during upgrade 11786 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11787 11788 try { 11789 boolean sysPkg = (isSystemApp(oldPackage)); 11790 if (sysPkg) { 11791 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11792 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11793 } else { 11794 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11795 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11796 } 11797 } finally { 11798 // Regardless of success or failure of upgrade steps above, always 11799 // unfreeze the package if we froze it 11800 if (weFroze) { 11801 unfreezePackage(pkgName); 11802 } 11803 } 11804 } 11805 11806 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11807 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11808 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11809 String volumeUuid, PackageInstalledInfo res) { 11810 String pkgName = deletedPackage.packageName; 11811 boolean deletedPkg = true; 11812 boolean updatedSettings = false; 11813 11814 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11815 + deletedPackage); 11816 long origUpdateTime; 11817 if (pkg.mExtras != null) { 11818 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11819 } else { 11820 origUpdateTime = 0; 11821 } 11822 11823 // First delete the existing package while retaining the data directory 11824 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11825 res.removedInfo, true)) { 11826 // If the existing package wasn't successfully deleted 11827 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11828 deletedPkg = false; 11829 } else { 11830 // Successfully deleted the old package; proceed with replace. 11831 11832 // If deleted package lived in a container, give users a chance to 11833 // relinquish resources before killing. 11834 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11835 if (DEBUG_INSTALL) { 11836 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11837 } 11838 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11839 final ArrayList<String> pkgList = new ArrayList<String>(1); 11840 pkgList.add(deletedPackage.applicationInfo.packageName); 11841 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11842 } 11843 11844 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11845 try { 11846 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11847 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11848 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11849 perUserInstalled, res, user); 11850 updatedSettings = true; 11851 } catch (PackageManagerException e) { 11852 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11853 } 11854 } 11855 11856 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11857 // remove package from internal structures. Note that we want deletePackageX to 11858 // delete the package data and cache directories that it created in 11859 // scanPackageLocked, unless those directories existed before we even tried to 11860 // install. 11861 if(updatedSettings) { 11862 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11863 deletePackageLI( 11864 pkgName, null, true, allUsers, perUserInstalled, 11865 PackageManager.DELETE_KEEP_DATA, 11866 res.removedInfo, true); 11867 } 11868 // Since we failed to install the new package we need to restore the old 11869 // package that we deleted. 11870 if (deletedPkg) { 11871 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11872 File restoreFile = new File(deletedPackage.codePath); 11873 // Parse old package 11874 boolean oldExternal = isExternal(deletedPackage); 11875 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11876 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11877 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11878 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11879 try { 11880 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11881 } catch (PackageManagerException e) { 11882 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11883 + e.getMessage()); 11884 return; 11885 } 11886 // Restore of old package succeeded. Update permissions. 11887 // writer 11888 synchronized (mPackages) { 11889 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11890 UPDATE_PERMISSIONS_ALL); 11891 // can downgrade to reader 11892 mSettings.writeLPr(); 11893 } 11894 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11895 } 11896 } 11897 } 11898 11899 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11900 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11901 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11902 String volumeUuid, PackageInstalledInfo res) { 11903 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11904 + ", old=" + deletedPackage); 11905 boolean disabledSystem = false; 11906 boolean updatedSettings = false; 11907 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11908 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11909 != 0) { 11910 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11911 } 11912 String packageName = deletedPackage.packageName; 11913 if (packageName == null) { 11914 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11915 "Attempt to delete null packageName."); 11916 return; 11917 } 11918 PackageParser.Package oldPkg; 11919 PackageSetting oldPkgSetting; 11920 // reader 11921 synchronized (mPackages) { 11922 oldPkg = mPackages.get(packageName); 11923 oldPkgSetting = mSettings.mPackages.get(packageName); 11924 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11925 (oldPkgSetting == null)) { 11926 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11927 "Couldn't find package:" + packageName + " information"); 11928 return; 11929 } 11930 } 11931 11932 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11933 res.removedInfo.removedPackage = packageName; 11934 // Remove existing system package 11935 removePackageLI(oldPkgSetting, true); 11936 // writer 11937 synchronized (mPackages) { 11938 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11939 if (!disabledSystem && deletedPackage != null) { 11940 // We didn't need to disable the .apk as a current system package, 11941 // which means we are replacing another update that is already 11942 // installed. We need to make sure to delete the older one's .apk. 11943 res.removedInfo.args = createInstallArgsForExisting(0, 11944 deletedPackage.applicationInfo.getCodePath(), 11945 deletedPackage.applicationInfo.getResourcePath(), 11946 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11947 } else { 11948 res.removedInfo.args = null; 11949 } 11950 } 11951 11952 // Successfully disabled the old package. Now proceed with re-installation 11953 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11954 11955 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11956 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11957 11958 PackageParser.Package newPackage = null; 11959 try { 11960 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11961 if (newPackage.mExtras != null) { 11962 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11963 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11964 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11965 11966 // is the update attempting to change shared user? that isn't going to work... 11967 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11968 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11969 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11970 + " to " + newPkgSetting.sharedUser); 11971 updatedSettings = true; 11972 } 11973 } 11974 11975 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11976 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11977 perUserInstalled, res, user); 11978 updatedSettings = true; 11979 } 11980 11981 } catch (PackageManagerException e) { 11982 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11983 } 11984 11985 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11986 // Re installation failed. Restore old information 11987 // Remove new pkg information 11988 if (newPackage != null) { 11989 removeInstalledPackageLI(newPackage, true); 11990 } 11991 // Add back the old system package 11992 try { 11993 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11994 } catch (PackageManagerException e) { 11995 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11996 } 11997 // Restore the old system information in Settings 11998 synchronized (mPackages) { 11999 if (disabledSystem) { 12000 mSettings.enableSystemPackageLPw(packageName); 12001 } 12002 if (updatedSettings) { 12003 mSettings.setInstallerPackageName(packageName, 12004 oldPkgSetting.installerPackageName); 12005 } 12006 mSettings.writeLPr(); 12007 } 12008 } 12009 } 12010 12011 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12012 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12013 UserHandle user) { 12014 String pkgName = newPackage.packageName; 12015 synchronized (mPackages) { 12016 //write settings. the installStatus will be incomplete at this stage. 12017 //note that the new package setting would have already been 12018 //added to mPackages. It hasn't been persisted yet. 12019 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12020 mSettings.writeLPr(); 12021 } 12022 12023 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12024 12025 synchronized (mPackages) { 12026 updatePermissionsLPw(newPackage.packageName, newPackage, 12027 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12028 ? UPDATE_PERMISSIONS_ALL : 0)); 12029 // For system-bundled packages, we assume that installing an upgraded version 12030 // of the package implies that the user actually wants to run that new code, 12031 // so we enable the package. 12032 PackageSetting ps = mSettings.mPackages.get(pkgName); 12033 if (ps != null) { 12034 if (isSystemApp(newPackage)) { 12035 // NB: implicit assumption that system package upgrades apply to all users 12036 if (DEBUG_INSTALL) { 12037 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12038 } 12039 if (res.origUsers != null) { 12040 for (int userHandle : res.origUsers) { 12041 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12042 userHandle, installerPackageName); 12043 } 12044 } 12045 // Also convey the prior install/uninstall state 12046 if (allUsers != null && perUserInstalled != null) { 12047 for (int i = 0; i < allUsers.length; i++) { 12048 if (DEBUG_INSTALL) { 12049 Slog.d(TAG, " user " + allUsers[i] 12050 + " => " + perUserInstalled[i]); 12051 } 12052 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12053 } 12054 // these install state changes will be persisted in the 12055 // upcoming call to mSettings.writeLPr(). 12056 } 12057 } 12058 // It's implied that when a user requests installation, they want the app to be 12059 // installed and enabled. 12060 int userId = user.getIdentifier(); 12061 if (userId != UserHandle.USER_ALL) { 12062 ps.setInstalled(true, userId); 12063 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12064 } 12065 } 12066 res.name = pkgName; 12067 res.uid = newPackage.applicationInfo.uid; 12068 res.pkg = newPackage; 12069 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12070 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12071 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12072 //to update install status 12073 mSettings.writeLPr(); 12074 } 12075 } 12076 12077 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12078 final int installFlags = args.installFlags; 12079 final String installerPackageName = args.installerPackageName; 12080 final String volumeUuid = args.volumeUuid; 12081 final File tmpPackageFile = new File(args.getCodePath()); 12082 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12083 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12084 || (args.volumeUuid != null)); 12085 boolean replace = false; 12086 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12087 if (args.move != null) { 12088 // moving a complete application; perfom an initial scan on the new install location 12089 scanFlags |= SCAN_INITIAL; 12090 } 12091 // Result object to be returned 12092 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12093 12094 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12095 // Retrieve PackageSettings and parse package 12096 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12097 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12098 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12099 PackageParser pp = new PackageParser(); 12100 pp.setSeparateProcesses(mSeparateProcesses); 12101 pp.setDisplayMetrics(mMetrics); 12102 12103 final PackageParser.Package pkg; 12104 try { 12105 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12106 } catch (PackageParserException e) { 12107 res.setError("Failed parse during installPackageLI", e); 12108 return; 12109 } 12110 12111 // Mark that we have an install time CPU ABI override. 12112 pkg.cpuAbiOverride = args.abiOverride; 12113 12114 String pkgName = res.name = pkg.packageName; 12115 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12116 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12117 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12118 return; 12119 } 12120 } 12121 12122 try { 12123 pp.collectCertificates(pkg, parseFlags); 12124 pp.collectManifestDigest(pkg); 12125 } catch (PackageParserException e) { 12126 res.setError("Failed collect during installPackageLI", e); 12127 return; 12128 } 12129 12130 /* If the installer passed in a manifest digest, compare it now. */ 12131 if (args.manifestDigest != null) { 12132 if (DEBUG_INSTALL) { 12133 final String parsedManifest = pkg.manifestDigest == null ? "null" 12134 : pkg.manifestDigest.toString(); 12135 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12136 + parsedManifest); 12137 } 12138 12139 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12140 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12141 return; 12142 } 12143 } else if (DEBUG_INSTALL) { 12144 final String parsedManifest = pkg.manifestDigest == null 12145 ? "null" : pkg.manifestDigest.toString(); 12146 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12147 } 12148 12149 // Get rid of all references to package scan path via parser. 12150 pp = null; 12151 String oldCodePath = null; 12152 boolean systemApp = false; 12153 synchronized (mPackages) { 12154 // Check if installing already existing package 12155 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12156 String oldName = mSettings.mRenamedPackages.get(pkgName); 12157 if (pkg.mOriginalPackages != null 12158 && pkg.mOriginalPackages.contains(oldName) 12159 && mPackages.containsKey(oldName)) { 12160 // This package is derived from an original package, 12161 // and this device has been updating from that original 12162 // name. We must continue using the original name, so 12163 // rename the new package here. 12164 pkg.setPackageName(oldName); 12165 pkgName = pkg.packageName; 12166 replace = true; 12167 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12168 + oldName + " pkgName=" + pkgName); 12169 } else if (mPackages.containsKey(pkgName)) { 12170 // This package, under its official name, already exists 12171 // on the device; we should replace it. 12172 replace = true; 12173 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12174 } 12175 12176 // Prevent apps opting out from runtime permissions 12177 if (replace) { 12178 PackageParser.Package oldPackage = mPackages.get(pkgName); 12179 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12180 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12181 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12182 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12183 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12184 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12185 + " doesn't support runtime permissions but the old" 12186 + " target SDK " + oldTargetSdk + " does."); 12187 return; 12188 } 12189 } 12190 } 12191 12192 PackageSetting ps = mSettings.mPackages.get(pkgName); 12193 if (ps != null) { 12194 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12195 12196 // Quick sanity check that we're signed correctly if updating; 12197 // we'll check this again later when scanning, but we want to 12198 // bail early here before tripping over redefined permissions. 12199 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12200 if (!checkUpgradeKeySetLP(ps, pkg)) { 12201 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12202 + pkg.packageName + " upgrade keys do not match the " 12203 + "previously installed version"); 12204 return; 12205 } 12206 } else { 12207 try { 12208 verifySignaturesLP(ps, pkg); 12209 } catch (PackageManagerException e) { 12210 res.setError(e.error, e.getMessage()); 12211 return; 12212 } 12213 } 12214 12215 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12216 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12217 systemApp = (ps.pkg.applicationInfo.flags & 12218 ApplicationInfo.FLAG_SYSTEM) != 0; 12219 } 12220 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12221 } 12222 12223 // Check whether the newly-scanned package wants to define an already-defined perm 12224 int N = pkg.permissions.size(); 12225 for (int i = N-1; i >= 0; i--) { 12226 PackageParser.Permission perm = pkg.permissions.get(i); 12227 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12228 if (bp != null) { 12229 // If the defining package is signed with our cert, it's okay. This 12230 // also includes the "updating the same package" case, of course. 12231 // "updating same package" could also involve key-rotation. 12232 final boolean sigsOk; 12233 if (bp.sourcePackage.equals(pkg.packageName) 12234 && (bp.packageSetting instanceof PackageSetting) 12235 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12236 scanFlags))) { 12237 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12238 } else { 12239 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12240 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12241 } 12242 if (!sigsOk) { 12243 // If the owning package is the system itself, we log but allow 12244 // install to proceed; we fail the install on all other permission 12245 // redefinitions. 12246 if (!bp.sourcePackage.equals("android")) { 12247 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12248 + pkg.packageName + " attempting to redeclare permission " 12249 + perm.info.name + " already owned by " + bp.sourcePackage); 12250 res.origPermission = perm.info.name; 12251 res.origPackage = bp.sourcePackage; 12252 return; 12253 } else { 12254 Slog.w(TAG, "Package " + pkg.packageName 12255 + " attempting to redeclare system permission " 12256 + perm.info.name + "; ignoring new declaration"); 12257 pkg.permissions.remove(i); 12258 } 12259 } 12260 } 12261 } 12262 12263 } 12264 12265 if (systemApp && onExternal) { 12266 // Disable updates to system apps on sdcard 12267 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12268 "Cannot install updates to system apps on sdcard"); 12269 return; 12270 } 12271 12272 if (args.move != null) { 12273 // We did an in-place move, so dex is ready to roll 12274 scanFlags |= SCAN_NO_DEX; 12275 scanFlags |= SCAN_MOVE; 12276 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12277 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12278 scanFlags |= SCAN_NO_DEX; 12279 12280 try { 12281 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12282 true /* extract libs */); 12283 } catch (PackageManagerException pme) { 12284 Slog.e(TAG, "Error deriving application ABI", pme); 12285 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12286 return; 12287 } 12288 12289 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12290 int result = mPackageDexOptimizer 12291 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12292 false /* defer */, false /* inclDependencies */); 12293 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12294 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12295 return; 12296 } 12297 } 12298 12299 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12300 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12301 return; 12302 } 12303 12304 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12305 12306 if (replace) { 12307 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12308 installerPackageName, volumeUuid, res); 12309 } else { 12310 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12311 args.user, installerPackageName, volumeUuid, res); 12312 } 12313 synchronized (mPackages) { 12314 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12315 if (ps != null) { 12316 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12317 } 12318 } 12319 } 12320 12321 private void startIntentFilterVerifications(int userId, boolean replacing, 12322 PackageParser.Package pkg) { 12323 if (mIntentFilterVerifierComponent == null) { 12324 Slog.w(TAG, "No IntentFilter verification will not be done as " 12325 + "there is no IntentFilterVerifier available!"); 12326 return; 12327 } 12328 12329 final int verifierUid = getPackageUid( 12330 mIntentFilterVerifierComponent.getPackageName(), 12331 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12332 12333 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12334 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12335 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12336 mHandler.sendMessage(msg); 12337 } 12338 12339 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12340 PackageParser.Package pkg) { 12341 int size = pkg.activities.size(); 12342 if (size == 0) { 12343 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12344 "No activity, so no need to verify any IntentFilter!"); 12345 return; 12346 } 12347 12348 final boolean hasDomainURLs = hasDomainURLs(pkg); 12349 if (!hasDomainURLs) { 12350 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12351 "No domain URLs, so no need to verify any IntentFilter!"); 12352 return; 12353 } 12354 12355 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12356 + " if any IntentFilter from the " + size 12357 + " Activities needs verification ..."); 12358 12359 int count = 0; 12360 final String packageName = pkg.packageName; 12361 12362 synchronized (mPackages) { 12363 // If this is a new install and we see that we've already run verification for this 12364 // package, we have nothing to do: it means the state was restored from backup. 12365 if (!replacing) { 12366 IntentFilterVerificationInfo ivi = 12367 mSettings.getIntentFilterVerificationLPr(packageName); 12368 if (ivi != null) { 12369 if (DEBUG_DOMAIN_VERIFICATION) { 12370 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12371 + ivi.getStatusString()); 12372 } 12373 return; 12374 } 12375 } 12376 12377 // If any filters need to be verified, then all need to be. 12378 boolean needToVerify = false; 12379 for (PackageParser.Activity a : pkg.activities) { 12380 for (ActivityIntentInfo filter : a.intents) { 12381 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12382 if (DEBUG_DOMAIN_VERIFICATION) { 12383 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12384 } 12385 needToVerify = true; 12386 break; 12387 } 12388 } 12389 } 12390 12391 if (needToVerify) { 12392 final int verificationId = mIntentFilterVerificationToken++; 12393 for (PackageParser.Activity a : pkg.activities) { 12394 for (ActivityIntentInfo filter : a.intents) { 12395 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12396 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12397 "Verification needed for IntentFilter:" + filter.toString()); 12398 mIntentFilterVerifier.addOneIntentFilterVerification( 12399 verifierUid, userId, verificationId, filter, packageName); 12400 count++; 12401 } 12402 } 12403 } 12404 } 12405 } 12406 12407 if (count > 0) { 12408 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12409 + " IntentFilter verification" + (count > 1 ? "s" : "") 12410 + " for userId:" + userId); 12411 mIntentFilterVerifier.startVerifications(userId); 12412 } else { 12413 if (DEBUG_DOMAIN_VERIFICATION) { 12414 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12415 } 12416 } 12417 } 12418 12419 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12420 final ComponentName cn = filter.activity.getComponentName(); 12421 final String packageName = cn.getPackageName(); 12422 12423 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12424 packageName); 12425 if (ivi == null) { 12426 return true; 12427 } 12428 int status = ivi.getStatus(); 12429 switch (status) { 12430 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12431 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12432 return true; 12433 12434 default: 12435 // Nothing to do 12436 return false; 12437 } 12438 } 12439 12440 private static boolean isMultiArch(PackageSetting ps) { 12441 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12442 } 12443 12444 private static boolean isMultiArch(ApplicationInfo info) { 12445 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12446 } 12447 12448 private static boolean isExternal(PackageParser.Package pkg) { 12449 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12450 } 12451 12452 private static boolean isExternal(PackageSetting ps) { 12453 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12454 } 12455 12456 private static boolean isExternal(ApplicationInfo info) { 12457 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12458 } 12459 12460 private static boolean isSystemApp(PackageParser.Package pkg) { 12461 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12462 } 12463 12464 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12465 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12466 } 12467 12468 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12469 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12470 } 12471 12472 private static boolean isSystemApp(PackageSetting ps) { 12473 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12474 } 12475 12476 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12477 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12478 } 12479 12480 private int packageFlagsToInstallFlags(PackageSetting ps) { 12481 int installFlags = 0; 12482 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12483 // This existing package was an external ASEC install when we have 12484 // the external flag without a UUID 12485 installFlags |= PackageManager.INSTALL_EXTERNAL; 12486 } 12487 if (ps.isForwardLocked()) { 12488 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12489 } 12490 return installFlags; 12491 } 12492 12493 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12494 if (isExternal(pkg)) { 12495 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12496 return mSettings.getExternalVersion(); 12497 } else { 12498 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12499 } 12500 } else { 12501 return mSettings.getInternalVersion(); 12502 } 12503 } 12504 12505 private void deleteTempPackageFiles() { 12506 final FilenameFilter filter = new FilenameFilter() { 12507 public boolean accept(File dir, String name) { 12508 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12509 } 12510 }; 12511 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12512 file.delete(); 12513 } 12514 } 12515 12516 @Override 12517 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12518 int flags) { 12519 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12520 flags); 12521 } 12522 12523 @Override 12524 public void deletePackage(final String packageName, 12525 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12526 mContext.enforceCallingOrSelfPermission( 12527 android.Manifest.permission.DELETE_PACKAGES, null); 12528 Preconditions.checkNotNull(packageName); 12529 Preconditions.checkNotNull(observer); 12530 final int uid = Binder.getCallingUid(); 12531 if (UserHandle.getUserId(uid) != userId) { 12532 mContext.enforceCallingPermission( 12533 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12534 "deletePackage for user " + userId); 12535 } 12536 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12537 try { 12538 observer.onPackageDeleted(packageName, 12539 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12540 } catch (RemoteException re) { 12541 } 12542 return; 12543 } 12544 12545 boolean uninstallBlocked = false; 12546 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12547 int[] users = sUserManager.getUserIds(); 12548 for (int i = 0; i < users.length; ++i) { 12549 if (getBlockUninstallForUser(packageName, users[i])) { 12550 uninstallBlocked = true; 12551 break; 12552 } 12553 } 12554 } else { 12555 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12556 } 12557 if (uninstallBlocked) { 12558 try { 12559 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12560 null); 12561 } catch (RemoteException re) { 12562 } 12563 return; 12564 } 12565 12566 if (DEBUG_REMOVE) { 12567 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12568 } 12569 // Queue up an async operation since the package deletion may take a little while. 12570 mHandler.post(new Runnable() { 12571 public void run() { 12572 mHandler.removeCallbacks(this); 12573 final int returnCode = deletePackageX(packageName, userId, flags); 12574 if (observer != null) { 12575 try { 12576 observer.onPackageDeleted(packageName, returnCode, null); 12577 } catch (RemoteException e) { 12578 Log.i(TAG, "Observer no longer exists."); 12579 } //end catch 12580 } //end if 12581 } //end run 12582 }); 12583 } 12584 12585 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12586 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12587 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12588 try { 12589 if (dpm != null) { 12590 if (dpm.isDeviceOwner(packageName)) { 12591 return true; 12592 } 12593 int[] users; 12594 if (userId == UserHandle.USER_ALL) { 12595 users = sUserManager.getUserIds(); 12596 } else { 12597 users = new int[]{userId}; 12598 } 12599 for (int i = 0; i < users.length; ++i) { 12600 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12601 return true; 12602 } 12603 } 12604 } 12605 } catch (RemoteException e) { 12606 } 12607 return false; 12608 } 12609 12610 /** 12611 * This method is an internal method that could be get invoked either 12612 * to delete an installed package or to clean up a failed installation. 12613 * After deleting an installed package, a broadcast is sent to notify any 12614 * listeners that the package has been installed. For cleaning up a failed 12615 * installation, the broadcast is not necessary since the package's 12616 * installation wouldn't have sent the initial broadcast either 12617 * The key steps in deleting a package are 12618 * deleting the package information in internal structures like mPackages, 12619 * deleting the packages base directories through installd 12620 * updating mSettings to reflect current status 12621 * persisting settings for later use 12622 * sending a broadcast if necessary 12623 */ 12624 private int deletePackageX(String packageName, int userId, int flags) { 12625 final PackageRemovedInfo info = new PackageRemovedInfo(); 12626 final boolean res; 12627 12628 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12629 ? UserHandle.ALL : new UserHandle(userId); 12630 12631 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12632 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12633 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12634 } 12635 12636 boolean removedForAllUsers = false; 12637 boolean systemUpdate = false; 12638 12639 // for the uninstall-updates case and restricted profiles, remember the per- 12640 // userhandle installed state 12641 int[] allUsers; 12642 boolean[] perUserInstalled; 12643 synchronized (mPackages) { 12644 PackageSetting ps = mSettings.mPackages.get(packageName); 12645 allUsers = sUserManager.getUserIds(); 12646 perUserInstalled = new boolean[allUsers.length]; 12647 for (int i = 0; i < allUsers.length; i++) { 12648 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12649 } 12650 } 12651 12652 synchronized (mInstallLock) { 12653 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12654 res = deletePackageLI(packageName, removeForUser, 12655 true, allUsers, perUserInstalled, 12656 flags | REMOVE_CHATTY, info, true); 12657 systemUpdate = info.isRemovedPackageSystemUpdate; 12658 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12659 removedForAllUsers = true; 12660 } 12661 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12662 + " removedForAllUsers=" + removedForAllUsers); 12663 } 12664 12665 if (res) { 12666 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12667 12668 // If the removed package was a system update, the old system package 12669 // was re-enabled; we need to broadcast this information 12670 if (systemUpdate) { 12671 Bundle extras = new Bundle(1); 12672 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12673 ? info.removedAppId : info.uid); 12674 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12675 12676 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12677 extras, null, null, null); 12678 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12679 extras, null, null, null); 12680 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12681 null, packageName, null, null); 12682 } 12683 } 12684 // Force a gc here. 12685 Runtime.getRuntime().gc(); 12686 // Delete the resources here after sending the broadcast to let 12687 // other processes clean up before deleting resources. 12688 if (info.args != null) { 12689 synchronized (mInstallLock) { 12690 info.args.doPostDeleteLI(true); 12691 } 12692 } 12693 12694 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12695 } 12696 12697 class PackageRemovedInfo { 12698 String removedPackage; 12699 int uid = -1; 12700 int removedAppId = -1; 12701 int[] removedUsers = null; 12702 boolean isRemovedPackageSystemUpdate = false; 12703 // Clean up resources deleted packages. 12704 InstallArgs args = null; 12705 12706 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12707 Bundle extras = new Bundle(1); 12708 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12709 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12710 if (replacing) { 12711 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12712 } 12713 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12714 if (removedPackage != null) { 12715 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12716 extras, null, null, removedUsers); 12717 if (fullRemove && !replacing) { 12718 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12719 extras, null, null, removedUsers); 12720 } 12721 } 12722 if (removedAppId >= 0) { 12723 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12724 removedUsers); 12725 } 12726 } 12727 } 12728 12729 /* 12730 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12731 * flag is not set, the data directory is removed as well. 12732 * make sure this flag is set for partially installed apps. If not its meaningless to 12733 * delete a partially installed application. 12734 */ 12735 private void removePackageDataLI(PackageSetting ps, 12736 int[] allUserHandles, boolean[] perUserInstalled, 12737 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12738 String packageName = ps.name; 12739 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12740 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12741 // Retrieve object to delete permissions for shared user later on 12742 final PackageSetting deletedPs; 12743 // reader 12744 synchronized (mPackages) { 12745 deletedPs = mSettings.mPackages.get(packageName); 12746 if (outInfo != null) { 12747 outInfo.removedPackage = packageName; 12748 outInfo.removedUsers = deletedPs != null 12749 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12750 : null; 12751 } 12752 } 12753 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12754 removeDataDirsLI(ps.volumeUuid, packageName); 12755 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12756 } 12757 // writer 12758 synchronized (mPackages) { 12759 if (deletedPs != null) { 12760 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12761 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12762 clearDefaultBrowserIfNeeded(packageName); 12763 if (outInfo != null) { 12764 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12765 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12766 } 12767 updatePermissionsLPw(deletedPs.name, null, 0); 12768 if (deletedPs.sharedUser != null) { 12769 // Remove permissions associated with package. Since runtime 12770 // permissions are per user we have to kill the removed package 12771 // or packages running under the shared user of the removed 12772 // package if revoking the permissions requested only by the removed 12773 // package is successful and this causes a change in gids. 12774 for (int userId : UserManagerService.getInstance().getUserIds()) { 12775 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12776 userId); 12777 if (userIdToKill == UserHandle.USER_ALL 12778 || userIdToKill >= UserHandle.USER_OWNER) { 12779 // If gids changed for this user, kill all affected packages. 12780 mHandler.post(new Runnable() { 12781 @Override 12782 public void run() { 12783 // This has to happen with no lock held. 12784 killSettingPackagesForUser(deletedPs, userIdToKill, 12785 KILL_APP_REASON_GIDS_CHANGED); 12786 } 12787 }); 12788 break; 12789 } 12790 } 12791 } 12792 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12793 } 12794 // make sure to preserve per-user disabled state if this removal was just 12795 // a downgrade of a system app to the factory package 12796 if (allUserHandles != null && perUserInstalled != null) { 12797 if (DEBUG_REMOVE) { 12798 Slog.d(TAG, "Propagating install state across downgrade"); 12799 } 12800 for (int i = 0; i < allUserHandles.length; i++) { 12801 if (DEBUG_REMOVE) { 12802 Slog.d(TAG, " user " + allUserHandles[i] 12803 + " => " + perUserInstalled[i]); 12804 } 12805 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12806 } 12807 } 12808 } 12809 // can downgrade to reader 12810 if (writeSettings) { 12811 // Save settings now 12812 mSettings.writeLPr(); 12813 } 12814 } 12815 if (outInfo != null) { 12816 // A user ID was deleted here. Go through all users and remove it 12817 // from KeyStore. 12818 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12819 } 12820 } 12821 12822 static boolean locationIsPrivileged(File path) { 12823 try { 12824 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12825 .getCanonicalPath(); 12826 return path.getCanonicalPath().startsWith(privilegedAppDir); 12827 } catch (IOException e) { 12828 Slog.e(TAG, "Unable to access code path " + path); 12829 } 12830 return false; 12831 } 12832 12833 /* 12834 * Tries to delete system package. 12835 */ 12836 private boolean deleteSystemPackageLI(PackageSetting newPs, 12837 int[] allUserHandles, boolean[] perUserInstalled, 12838 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12839 final boolean applyUserRestrictions 12840 = (allUserHandles != null) && (perUserInstalled != null); 12841 PackageSetting disabledPs = null; 12842 // Confirm if the system package has been updated 12843 // An updated system app can be deleted. This will also have to restore 12844 // the system pkg from system partition 12845 // reader 12846 synchronized (mPackages) { 12847 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12848 } 12849 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12850 + " disabledPs=" + disabledPs); 12851 if (disabledPs == null) { 12852 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12853 return false; 12854 } else if (DEBUG_REMOVE) { 12855 Slog.d(TAG, "Deleting system pkg from data partition"); 12856 } 12857 if (DEBUG_REMOVE) { 12858 if (applyUserRestrictions) { 12859 Slog.d(TAG, "Remembering install states:"); 12860 for (int i = 0; i < allUserHandles.length; i++) { 12861 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12862 } 12863 } 12864 } 12865 // Delete the updated package 12866 outInfo.isRemovedPackageSystemUpdate = true; 12867 if (disabledPs.versionCode < newPs.versionCode) { 12868 // Delete data for downgrades 12869 flags &= ~PackageManager.DELETE_KEEP_DATA; 12870 } else { 12871 // Preserve data by setting flag 12872 flags |= PackageManager.DELETE_KEEP_DATA; 12873 } 12874 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12875 allUserHandles, perUserInstalled, outInfo, writeSettings); 12876 if (!ret) { 12877 return false; 12878 } 12879 // writer 12880 synchronized (mPackages) { 12881 // Reinstate the old system package 12882 mSettings.enableSystemPackageLPw(newPs.name); 12883 // Remove any native libraries from the upgraded package. 12884 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12885 } 12886 // Install the system package 12887 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12888 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12889 if (locationIsPrivileged(disabledPs.codePath)) { 12890 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12891 } 12892 12893 final PackageParser.Package newPkg; 12894 try { 12895 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12896 } catch (PackageManagerException e) { 12897 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12898 return false; 12899 } 12900 12901 // writer 12902 synchronized (mPackages) { 12903 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12904 12905 // Propagate the permissions state as we do want to drop on the floor 12906 // runtime permissions. The update permissions method below will take 12907 // care of removing obsolete permissions and grant install permissions. 12908 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12909 updatePermissionsLPw(newPkg.packageName, newPkg, 12910 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12911 12912 if (applyUserRestrictions) { 12913 if (DEBUG_REMOVE) { 12914 Slog.d(TAG, "Propagating install state across reinstall"); 12915 } 12916 for (int i = 0; i < allUserHandles.length; i++) { 12917 if (DEBUG_REMOVE) { 12918 Slog.d(TAG, " user " + allUserHandles[i] 12919 + " => " + perUserInstalled[i]); 12920 } 12921 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12922 } 12923 // Regardless of writeSettings we need to ensure that this restriction 12924 // state propagation is persisted 12925 mSettings.writeAllUsersPackageRestrictionsLPr(); 12926 } 12927 // can downgrade to reader here 12928 if (writeSettings) { 12929 mSettings.writeLPr(); 12930 } 12931 } 12932 return true; 12933 } 12934 12935 private boolean deleteInstalledPackageLI(PackageSetting ps, 12936 boolean deleteCodeAndResources, int flags, 12937 int[] allUserHandles, boolean[] perUserInstalled, 12938 PackageRemovedInfo outInfo, boolean writeSettings) { 12939 if (outInfo != null) { 12940 outInfo.uid = ps.appId; 12941 } 12942 12943 // Delete package data from internal structures and also remove data if flag is set 12944 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12945 12946 // Delete application code and resources 12947 if (deleteCodeAndResources && (outInfo != null)) { 12948 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12949 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12950 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12951 } 12952 return true; 12953 } 12954 12955 @Override 12956 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12957 int userId) { 12958 mContext.enforceCallingOrSelfPermission( 12959 android.Manifest.permission.DELETE_PACKAGES, null); 12960 synchronized (mPackages) { 12961 PackageSetting ps = mSettings.mPackages.get(packageName); 12962 if (ps == null) { 12963 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12964 return false; 12965 } 12966 if (!ps.getInstalled(userId)) { 12967 // Can't block uninstall for an app that is not installed or enabled. 12968 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12969 return false; 12970 } 12971 ps.setBlockUninstall(blockUninstall, userId); 12972 mSettings.writePackageRestrictionsLPr(userId); 12973 } 12974 return true; 12975 } 12976 12977 @Override 12978 public boolean getBlockUninstallForUser(String packageName, int userId) { 12979 synchronized (mPackages) { 12980 PackageSetting ps = mSettings.mPackages.get(packageName); 12981 if (ps == null) { 12982 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12983 return false; 12984 } 12985 return ps.getBlockUninstall(userId); 12986 } 12987 } 12988 12989 /* 12990 * This method handles package deletion in general 12991 */ 12992 private boolean deletePackageLI(String packageName, UserHandle user, 12993 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12994 int flags, PackageRemovedInfo outInfo, 12995 boolean writeSettings) { 12996 if (packageName == null) { 12997 Slog.w(TAG, "Attempt to delete null packageName."); 12998 return false; 12999 } 13000 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13001 PackageSetting ps; 13002 boolean dataOnly = false; 13003 int removeUser = -1; 13004 int appId = -1; 13005 synchronized (mPackages) { 13006 ps = mSettings.mPackages.get(packageName); 13007 if (ps == null) { 13008 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13009 return false; 13010 } 13011 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13012 && user.getIdentifier() != UserHandle.USER_ALL) { 13013 // The caller is asking that the package only be deleted for a single 13014 // user. To do this, we just mark its uninstalled state and delete 13015 // its data. If this is a system app, we only allow this to happen if 13016 // they have set the special DELETE_SYSTEM_APP which requests different 13017 // semantics than normal for uninstalling system apps. 13018 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13019 ps.setUserState(user.getIdentifier(), 13020 COMPONENT_ENABLED_STATE_DEFAULT, 13021 false, //installed 13022 true, //stopped 13023 true, //notLaunched 13024 false, //hidden 13025 null, null, null, 13026 false, // blockUninstall 13027 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13028 if (!isSystemApp(ps)) { 13029 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13030 // Other user still have this package installed, so all 13031 // we need to do is clear this user's data and save that 13032 // it is uninstalled. 13033 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13034 removeUser = user.getIdentifier(); 13035 appId = ps.appId; 13036 scheduleWritePackageRestrictionsLocked(removeUser); 13037 } else { 13038 // We need to set it back to 'installed' so the uninstall 13039 // broadcasts will be sent correctly. 13040 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13041 ps.setInstalled(true, user.getIdentifier()); 13042 } 13043 } else { 13044 // This is a system app, so we assume that the 13045 // other users still have this package installed, so all 13046 // we need to do is clear this user's data and save that 13047 // it is uninstalled. 13048 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13049 removeUser = user.getIdentifier(); 13050 appId = ps.appId; 13051 scheduleWritePackageRestrictionsLocked(removeUser); 13052 } 13053 } 13054 } 13055 13056 if (removeUser >= 0) { 13057 // From above, we determined that we are deleting this only 13058 // for a single user. Continue the work here. 13059 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13060 if (outInfo != null) { 13061 outInfo.removedPackage = packageName; 13062 outInfo.removedAppId = appId; 13063 outInfo.removedUsers = new int[] {removeUser}; 13064 } 13065 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13066 removeKeystoreDataIfNeeded(removeUser, appId); 13067 schedulePackageCleaning(packageName, removeUser, false); 13068 synchronized (mPackages) { 13069 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13070 scheduleWritePackageRestrictionsLocked(removeUser); 13071 } 13072 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13073 } 13074 return true; 13075 } 13076 13077 if (dataOnly) { 13078 // Delete application data first 13079 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13080 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13081 return true; 13082 } 13083 13084 boolean ret = false; 13085 if (isSystemApp(ps)) { 13086 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13087 // When an updated system application is deleted we delete the existing resources as well and 13088 // fall back to existing code in system partition 13089 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13090 flags, outInfo, writeSettings); 13091 } else { 13092 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13093 // Kill application pre-emptively especially for apps on sd. 13094 killApplication(packageName, ps.appId, "uninstall pkg"); 13095 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13096 allUserHandles, perUserInstalled, 13097 outInfo, writeSettings); 13098 } 13099 13100 return ret; 13101 } 13102 13103 private final class ClearStorageConnection implements ServiceConnection { 13104 IMediaContainerService mContainerService; 13105 13106 @Override 13107 public void onServiceConnected(ComponentName name, IBinder service) { 13108 synchronized (this) { 13109 mContainerService = IMediaContainerService.Stub.asInterface(service); 13110 notifyAll(); 13111 } 13112 } 13113 13114 @Override 13115 public void onServiceDisconnected(ComponentName name) { 13116 } 13117 } 13118 13119 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13120 final boolean mounted; 13121 if (Environment.isExternalStorageEmulated()) { 13122 mounted = true; 13123 } else { 13124 final String status = Environment.getExternalStorageState(); 13125 13126 mounted = status.equals(Environment.MEDIA_MOUNTED) 13127 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13128 } 13129 13130 if (!mounted) { 13131 return; 13132 } 13133 13134 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13135 int[] users; 13136 if (userId == UserHandle.USER_ALL) { 13137 users = sUserManager.getUserIds(); 13138 } else { 13139 users = new int[] { userId }; 13140 } 13141 final ClearStorageConnection conn = new ClearStorageConnection(); 13142 if (mContext.bindServiceAsUser( 13143 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13144 try { 13145 for (int curUser : users) { 13146 long timeout = SystemClock.uptimeMillis() + 5000; 13147 synchronized (conn) { 13148 long now = SystemClock.uptimeMillis(); 13149 while (conn.mContainerService == null && now < timeout) { 13150 try { 13151 conn.wait(timeout - now); 13152 } catch (InterruptedException e) { 13153 } 13154 } 13155 } 13156 if (conn.mContainerService == null) { 13157 return; 13158 } 13159 13160 final UserEnvironment userEnv = new UserEnvironment(curUser); 13161 clearDirectory(conn.mContainerService, 13162 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13163 if (allData) { 13164 clearDirectory(conn.mContainerService, 13165 userEnv.buildExternalStorageAppDataDirs(packageName)); 13166 clearDirectory(conn.mContainerService, 13167 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13168 } 13169 } 13170 } finally { 13171 mContext.unbindService(conn); 13172 } 13173 } 13174 } 13175 13176 @Override 13177 public void clearApplicationUserData(final String packageName, 13178 final IPackageDataObserver observer, final int userId) { 13179 mContext.enforceCallingOrSelfPermission( 13180 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13181 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13182 // Queue up an async operation since the package deletion may take a little while. 13183 mHandler.post(new Runnable() { 13184 public void run() { 13185 mHandler.removeCallbacks(this); 13186 final boolean succeeded; 13187 synchronized (mInstallLock) { 13188 succeeded = clearApplicationUserDataLI(packageName, userId); 13189 } 13190 clearExternalStorageDataSync(packageName, userId, true); 13191 if (succeeded) { 13192 // invoke DeviceStorageMonitor's update method to clear any notifications 13193 DeviceStorageMonitorInternal 13194 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13195 if (dsm != null) { 13196 dsm.checkMemory(); 13197 } 13198 } 13199 if(observer != null) { 13200 try { 13201 observer.onRemoveCompleted(packageName, succeeded); 13202 } catch (RemoteException e) { 13203 Log.i(TAG, "Observer no longer exists."); 13204 } 13205 } //end if observer 13206 } //end run 13207 }); 13208 } 13209 13210 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13211 if (packageName == null) { 13212 Slog.w(TAG, "Attempt to delete null packageName."); 13213 return false; 13214 } 13215 13216 // Try finding details about the requested package 13217 PackageParser.Package pkg; 13218 synchronized (mPackages) { 13219 pkg = mPackages.get(packageName); 13220 if (pkg == null) { 13221 final PackageSetting ps = mSettings.mPackages.get(packageName); 13222 if (ps != null) { 13223 pkg = ps.pkg; 13224 } 13225 } 13226 13227 if (pkg == null) { 13228 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13229 return false; 13230 } 13231 13232 PackageSetting ps = (PackageSetting) pkg.mExtras; 13233 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13234 } 13235 13236 // Always delete data directories for package, even if we found no other 13237 // record of app. This helps users recover from UID mismatches without 13238 // resorting to a full data wipe. 13239 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13240 if (retCode < 0) { 13241 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13242 return false; 13243 } 13244 13245 final int appId = pkg.applicationInfo.uid; 13246 removeKeystoreDataIfNeeded(userId, appId); 13247 13248 // Create a native library symlink only if we have native libraries 13249 // and if the native libraries are 32 bit libraries. We do not provide 13250 // this symlink for 64 bit libraries. 13251 if (pkg.applicationInfo.primaryCpuAbi != null && 13252 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13253 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13254 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13255 nativeLibPath, userId) < 0) { 13256 Slog.w(TAG, "Failed linking native library dir"); 13257 return false; 13258 } 13259 } 13260 13261 return true; 13262 } 13263 13264 /** 13265 * Reverts user permission state changes (permissions and flags). 13266 * 13267 * @param ps The package for which to reset. 13268 * @param userId The device user for which to do a reset. 13269 */ 13270 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13271 final PackageSetting ps, final int userId) { 13272 if (ps.pkg == null) { 13273 return; 13274 } 13275 13276 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13277 | FLAG_PERMISSION_USER_FIXED 13278 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13279 13280 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13281 | FLAG_PERMISSION_POLICY_FIXED; 13282 13283 boolean writeInstallPermissions = false; 13284 boolean writeRuntimePermissions = false; 13285 13286 final int permissionCount = ps.pkg.requestedPermissions.size(); 13287 for (int i = 0; i < permissionCount; i++) { 13288 String permission = ps.pkg.requestedPermissions.get(i); 13289 13290 BasePermission bp = mSettings.mPermissions.get(permission); 13291 if (bp == null) { 13292 continue; 13293 } 13294 13295 // If shared user we just reset the state to which only this app contributed. 13296 if (ps.sharedUser != null) { 13297 boolean used = false; 13298 final int packageCount = ps.sharedUser.packages.size(); 13299 for (int j = 0; j < packageCount; j++) { 13300 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13301 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13302 && pkg.pkg.requestedPermissions.contains(permission)) { 13303 used = true; 13304 break; 13305 } 13306 } 13307 if (used) { 13308 continue; 13309 } 13310 } 13311 13312 PermissionsState permissionsState = ps.getPermissionsState(); 13313 13314 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13315 13316 // Always clear the user settable flags. 13317 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13318 bp.name) != null; 13319 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13320 if (hasInstallState) { 13321 writeInstallPermissions = true; 13322 } else { 13323 writeRuntimePermissions = true; 13324 } 13325 } 13326 13327 // Below is only runtime permission handling. 13328 if (!bp.isRuntime()) { 13329 continue; 13330 } 13331 13332 // Never clobber system or policy. 13333 if ((oldFlags & policyOrSystemFlags) != 0) { 13334 continue; 13335 } 13336 13337 // If this permission was granted by default, make sure it is. 13338 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13339 if (permissionsState.grantRuntimePermission(bp, userId) 13340 != PERMISSION_OPERATION_FAILURE) { 13341 writeRuntimePermissions = true; 13342 } 13343 } else { 13344 // Otherwise, reset the permission. 13345 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13346 switch (revokeResult) { 13347 case PERMISSION_OPERATION_SUCCESS: { 13348 writeRuntimePermissions = true; 13349 } break; 13350 13351 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13352 writeRuntimePermissions = true; 13353 // If gids changed for this user, kill all affected packages. 13354 mHandler.post(new Runnable() { 13355 @Override 13356 public void run() { 13357 // This has to happen with no lock held. 13358 killSettingPackagesForUser(ps, userId, 13359 KILL_APP_REASON_GIDS_CHANGED); 13360 } 13361 }); 13362 } break; 13363 } 13364 } 13365 } 13366 13367 // Synchronously write as we are taking permissions away. 13368 if (writeRuntimePermissions) { 13369 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13370 } 13371 13372 // Synchronously write as we are taking permissions away. 13373 if (writeInstallPermissions) { 13374 mSettings.writeLPr(); 13375 } 13376 } 13377 13378 /** 13379 * Remove entries from the keystore daemon. Will only remove it if the 13380 * {@code appId} is valid. 13381 */ 13382 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13383 if (appId < 0) { 13384 return; 13385 } 13386 13387 final KeyStore keyStore = KeyStore.getInstance(); 13388 if (keyStore != null) { 13389 if (userId == UserHandle.USER_ALL) { 13390 for (final int individual : sUserManager.getUserIds()) { 13391 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13392 } 13393 } else { 13394 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13395 } 13396 } else { 13397 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13398 } 13399 } 13400 13401 @Override 13402 public void deleteApplicationCacheFiles(final String packageName, 13403 final IPackageDataObserver observer) { 13404 mContext.enforceCallingOrSelfPermission( 13405 android.Manifest.permission.DELETE_CACHE_FILES, null); 13406 // Queue up an async operation since the package deletion may take a little while. 13407 final int userId = UserHandle.getCallingUserId(); 13408 mHandler.post(new Runnable() { 13409 public void run() { 13410 mHandler.removeCallbacks(this); 13411 final boolean succeded; 13412 synchronized (mInstallLock) { 13413 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13414 } 13415 clearExternalStorageDataSync(packageName, userId, false); 13416 if (observer != null) { 13417 try { 13418 observer.onRemoveCompleted(packageName, succeded); 13419 } catch (RemoteException e) { 13420 Log.i(TAG, "Observer no longer exists."); 13421 } 13422 } //end if observer 13423 } //end run 13424 }); 13425 } 13426 13427 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13428 if (packageName == null) { 13429 Slog.w(TAG, "Attempt to delete null packageName."); 13430 return false; 13431 } 13432 PackageParser.Package p; 13433 synchronized (mPackages) { 13434 p = mPackages.get(packageName); 13435 } 13436 if (p == null) { 13437 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13438 return false; 13439 } 13440 final ApplicationInfo applicationInfo = p.applicationInfo; 13441 if (applicationInfo == null) { 13442 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13443 return false; 13444 } 13445 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13446 if (retCode < 0) { 13447 Slog.w(TAG, "Couldn't remove cache files for package: " 13448 + packageName + " u" + userId); 13449 return false; 13450 } 13451 return true; 13452 } 13453 13454 @Override 13455 public void getPackageSizeInfo(final String packageName, int userHandle, 13456 final IPackageStatsObserver observer) { 13457 mContext.enforceCallingOrSelfPermission( 13458 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13459 if (packageName == null) { 13460 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13461 } 13462 13463 PackageStats stats = new PackageStats(packageName, userHandle); 13464 13465 /* 13466 * Queue up an async operation since the package measurement may take a 13467 * little while. 13468 */ 13469 Message msg = mHandler.obtainMessage(INIT_COPY); 13470 msg.obj = new MeasureParams(stats, observer); 13471 mHandler.sendMessage(msg); 13472 } 13473 13474 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13475 PackageStats pStats) { 13476 if (packageName == null) { 13477 Slog.w(TAG, "Attempt to get size of null packageName."); 13478 return false; 13479 } 13480 PackageParser.Package p; 13481 boolean dataOnly = false; 13482 String libDirRoot = null; 13483 String asecPath = null; 13484 PackageSetting ps = null; 13485 synchronized (mPackages) { 13486 p = mPackages.get(packageName); 13487 ps = mSettings.mPackages.get(packageName); 13488 if(p == null) { 13489 dataOnly = true; 13490 if((ps == null) || (ps.pkg == null)) { 13491 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13492 return false; 13493 } 13494 p = ps.pkg; 13495 } 13496 if (ps != null) { 13497 libDirRoot = ps.legacyNativeLibraryPathString; 13498 } 13499 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13500 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13501 if (secureContainerId != null) { 13502 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13503 } 13504 } 13505 } 13506 String publicSrcDir = null; 13507 if(!dataOnly) { 13508 final ApplicationInfo applicationInfo = p.applicationInfo; 13509 if (applicationInfo == null) { 13510 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13511 return false; 13512 } 13513 if (p.isForwardLocked()) { 13514 publicSrcDir = applicationInfo.getBaseResourcePath(); 13515 } 13516 } 13517 // TODO: extend to measure size of split APKs 13518 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13519 // not just the first level. 13520 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13521 // just the primary. 13522 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13523 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13524 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13525 if (res < 0) { 13526 return false; 13527 } 13528 13529 // Fix-up for forward-locked applications in ASEC containers. 13530 if (!isExternal(p)) { 13531 pStats.codeSize += pStats.externalCodeSize; 13532 pStats.externalCodeSize = 0L; 13533 } 13534 13535 return true; 13536 } 13537 13538 13539 @Override 13540 public void addPackageToPreferred(String packageName) { 13541 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13542 } 13543 13544 @Override 13545 public void removePackageFromPreferred(String packageName) { 13546 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13547 } 13548 13549 @Override 13550 public List<PackageInfo> getPreferredPackages(int flags) { 13551 return new ArrayList<PackageInfo>(); 13552 } 13553 13554 private int getUidTargetSdkVersionLockedLPr(int uid) { 13555 Object obj = mSettings.getUserIdLPr(uid); 13556 if (obj instanceof SharedUserSetting) { 13557 final SharedUserSetting sus = (SharedUserSetting) obj; 13558 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13559 final Iterator<PackageSetting> it = sus.packages.iterator(); 13560 while (it.hasNext()) { 13561 final PackageSetting ps = it.next(); 13562 if (ps.pkg != null) { 13563 int v = ps.pkg.applicationInfo.targetSdkVersion; 13564 if (v < vers) vers = v; 13565 } 13566 } 13567 return vers; 13568 } else if (obj instanceof PackageSetting) { 13569 final PackageSetting ps = (PackageSetting) obj; 13570 if (ps.pkg != null) { 13571 return ps.pkg.applicationInfo.targetSdkVersion; 13572 } 13573 } 13574 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13575 } 13576 13577 @Override 13578 public void addPreferredActivity(IntentFilter filter, int match, 13579 ComponentName[] set, ComponentName activity, int userId) { 13580 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13581 "Adding preferred"); 13582 } 13583 13584 private void addPreferredActivityInternal(IntentFilter filter, int match, 13585 ComponentName[] set, ComponentName activity, boolean always, int userId, 13586 String opname) { 13587 // writer 13588 int callingUid = Binder.getCallingUid(); 13589 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13590 if (filter.countActions() == 0) { 13591 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13592 return; 13593 } 13594 synchronized (mPackages) { 13595 if (mContext.checkCallingOrSelfPermission( 13596 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13597 != PackageManager.PERMISSION_GRANTED) { 13598 if (getUidTargetSdkVersionLockedLPr(callingUid) 13599 < Build.VERSION_CODES.FROYO) { 13600 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13601 + callingUid); 13602 return; 13603 } 13604 mContext.enforceCallingOrSelfPermission( 13605 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13606 } 13607 13608 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13609 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13610 + userId + ":"); 13611 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13612 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13613 scheduleWritePackageRestrictionsLocked(userId); 13614 } 13615 } 13616 13617 @Override 13618 public void replacePreferredActivity(IntentFilter filter, int match, 13619 ComponentName[] set, ComponentName activity, int userId) { 13620 if (filter.countActions() != 1) { 13621 throw new IllegalArgumentException( 13622 "replacePreferredActivity expects filter to have only 1 action."); 13623 } 13624 if (filter.countDataAuthorities() != 0 13625 || filter.countDataPaths() != 0 13626 || filter.countDataSchemes() > 1 13627 || filter.countDataTypes() != 0) { 13628 throw new IllegalArgumentException( 13629 "replacePreferredActivity expects filter to have no data authorities, " + 13630 "paths, or types; and at most one scheme."); 13631 } 13632 13633 final int callingUid = Binder.getCallingUid(); 13634 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13635 synchronized (mPackages) { 13636 if (mContext.checkCallingOrSelfPermission( 13637 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13638 != PackageManager.PERMISSION_GRANTED) { 13639 if (getUidTargetSdkVersionLockedLPr(callingUid) 13640 < Build.VERSION_CODES.FROYO) { 13641 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13642 + Binder.getCallingUid()); 13643 return; 13644 } 13645 mContext.enforceCallingOrSelfPermission( 13646 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13647 } 13648 13649 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13650 if (pir != null) { 13651 // Get all of the existing entries that exactly match this filter. 13652 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13653 if (existing != null && existing.size() == 1) { 13654 PreferredActivity cur = existing.get(0); 13655 if (DEBUG_PREFERRED) { 13656 Slog.i(TAG, "Checking replace of preferred:"); 13657 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13658 if (!cur.mPref.mAlways) { 13659 Slog.i(TAG, " -- CUR; not mAlways!"); 13660 } else { 13661 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13662 Slog.i(TAG, " -- CUR: mSet=" 13663 + Arrays.toString(cur.mPref.mSetComponents)); 13664 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13665 Slog.i(TAG, " -- NEW: mMatch=" 13666 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13667 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13668 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13669 } 13670 } 13671 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13672 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13673 && cur.mPref.sameSet(set)) { 13674 // Setting the preferred activity to what it happens to be already 13675 if (DEBUG_PREFERRED) { 13676 Slog.i(TAG, "Replacing with same preferred activity " 13677 + cur.mPref.mShortComponent + " for user " 13678 + userId + ":"); 13679 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13680 } 13681 return; 13682 } 13683 } 13684 13685 if (existing != null) { 13686 if (DEBUG_PREFERRED) { 13687 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13688 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13689 } 13690 for (int i = 0; i < existing.size(); i++) { 13691 PreferredActivity pa = existing.get(i); 13692 if (DEBUG_PREFERRED) { 13693 Slog.i(TAG, "Removing existing preferred activity " 13694 + pa.mPref.mComponent + ":"); 13695 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13696 } 13697 pir.removeFilter(pa); 13698 } 13699 } 13700 } 13701 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13702 "Replacing preferred"); 13703 } 13704 } 13705 13706 @Override 13707 public void clearPackagePreferredActivities(String packageName) { 13708 final int uid = Binder.getCallingUid(); 13709 // writer 13710 synchronized (mPackages) { 13711 PackageParser.Package pkg = mPackages.get(packageName); 13712 if (pkg == null || pkg.applicationInfo.uid != uid) { 13713 if (mContext.checkCallingOrSelfPermission( 13714 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13715 != PackageManager.PERMISSION_GRANTED) { 13716 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13717 < Build.VERSION_CODES.FROYO) { 13718 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13719 + Binder.getCallingUid()); 13720 return; 13721 } 13722 mContext.enforceCallingOrSelfPermission( 13723 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13724 } 13725 } 13726 13727 int user = UserHandle.getCallingUserId(); 13728 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13729 scheduleWritePackageRestrictionsLocked(user); 13730 } 13731 } 13732 } 13733 13734 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13735 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13736 ArrayList<PreferredActivity> removed = null; 13737 boolean changed = false; 13738 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13739 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13740 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13741 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13742 continue; 13743 } 13744 Iterator<PreferredActivity> it = pir.filterIterator(); 13745 while (it.hasNext()) { 13746 PreferredActivity pa = it.next(); 13747 // Mark entry for removal only if it matches the package name 13748 // and the entry is of type "always". 13749 if (packageName == null || 13750 (pa.mPref.mComponent.getPackageName().equals(packageName) 13751 && pa.mPref.mAlways)) { 13752 if (removed == null) { 13753 removed = new ArrayList<PreferredActivity>(); 13754 } 13755 removed.add(pa); 13756 } 13757 } 13758 if (removed != null) { 13759 for (int j=0; j<removed.size(); j++) { 13760 PreferredActivity pa = removed.get(j); 13761 pir.removeFilter(pa); 13762 } 13763 changed = true; 13764 } 13765 } 13766 return changed; 13767 } 13768 13769 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13770 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13771 if (userId == UserHandle.USER_ALL) { 13772 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13773 sUserManager.getUserIds())) { 13774 for (int oneUserId : sUserManager.getUserIds()) { 13775 scheduleWritePackageRestrictionsLocked(oneUserId); 13776 } 13777 } 13778 } else { 13779 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13780 scheduleWritePackageRestrictionsLocked(userId); 13781 } 13782 } 13783 } 13784 13785 13786 void clearDefaultBrowserIfNeeded(String packageName) { 13787 for (int oneUserId : sUserManager.getUserIds()) { 13788 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13789 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13790 if (packageName.equals(defaultBrowserPackageName)) { 13791 setDefaultBrowserPackageName(null, oneUserId); 13792 } 13793 } 13794 } 13795 13796 @Override 13797 public void resetPreferredActivities(int userId) { 13798 mContext.enforceCallingOrSelfPermission( 13799 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13800 // writer 13801 synchronized (mPackages) { 13802 clearPackagePreferredActivitiesLPw(null, userId); 13803 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13804 applyFactoryDefaultBrowserLPw(userId); 13805 primeDomainVerificationsLPw(userId); 13806 13807 scheduleWritePackageRestrictionsLocked(userId); 13808 } 13809 } 13810 13811 @Override 13812 public int getPreferredActivities(List<IntentFilter> outFilters, 13813 List<ComponentName> outActivities, String packageName) { 13814 13815 int num = 0; 13816 final int userId = UserHandle.getCallingUserId(); 13817 // reader 13818 synchronized (mPackages) { 13819 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13820 if (pir != null) { 13821 final Iterator<PreferredActivity> it = pir.filterIterator(); 13822 while (it.hasNext()) { 13823 final PreferredActivity pa = it.next(); 13824 if (packageName == null 13825 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13826 && pa.mPref.mAlways)) { 13827 if (outFilters != null) { 13828 outFilters.add(new IntentFilter(pa)); 13829 } 13830 if (outActivities != null) { 13831 outActivities.add(pa.mPref.mComponent); 13832 } 13833 } 13834 } 13835 } 13836 } 13837 13838 return num; 13839 } 13840 13841 @Override 13842 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13843 int userId) { 13844 int callingUid = Binder.getCallingUid(); 13845 if (callingUid != Process.SYSTEM_UID) { 13846 throw new SecurityException( 13847 "addPersistentPreferredActivity can only be run by the system"); 13848 } 13849 if (filter.countActions() == 0) { 13850 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13851 return; 13852 } 13853 synchronized (mPackages) { 13854 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13855 " :"); 13856 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13857 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13858 new PersistentPreferredActivity(filter, activity)); 13859 scheduleWritePackageRestrictionsLocked(userId); 13860 } 13861 } 13862 13863 @Override 13864 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13865 int callingUid = Binder.getCallingUid(); 13866 if (callingUid != Process.SYSTEM_UID) { 13867 throw new SecurityException( 13868 "clearPackagePersistentPreferredActivities can only be run by the system"); 13869 } 13870 ArrayList<PersistentPreferredActivity> removed = null; 13871 boolean changed = false; 13872 synchronized (mPackages) { 13873 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13874 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13875 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13876 .valueAt(i); 13877 if (userId != thisUserId) { 13878 continue; 13879 } 13880 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13881 while (it.hasNext()) { 13882 PersistentPreferredActivity ppa = it.next(); 13883 // Mark entry for removal only if it matches the package name. 13884 if (ppa.mComponent.getPackageName().equals(packageName)) { 13885 if (removed == null) { 13886 removed = new ArrayList<PersistentPreferredActivity>(); 13887 } 13888 removed.add(ppa); 13889 } 13890 } 13891 if (removed != null) { 13892 for (int j=0; j<removed.size(); j++) { 13893 PersistentPreferredActivity ppa = removed.get(j); 13894 ppir.removeFilter(ppa); 13895 } 13896 changed = true; 13897 } 13898 } 13899 13900 if (changed) { 13901 scheduleWritePackageRestrictionsLocked(userId); 13902 } 13903 } 13904 } 13905 13906 /** 13907 * Common machinery for picking apart a restored XML blob and passing 13908 * it to a caller-supplied functor to be applied to the running system. 13909 */ 13910 private void restoreFromXml(XmlPullParser parser, int userId, 13911 String expectedStartTag, BlobXmlRestorer functor) 13912 throws IOException, XmlPullParserException { 13913 int type; 13914 while ((type = parser.next()) != XmlPullParser.START_TAG 13915 && type != XmlPullParser.END_DOCUMENT) { 13916 } 13917 if (type != XmlPullParser.START_TAG) { 13918 // oops didn't find a start tag?! 13919 if (DEBUG_BACKUP) { 13920 Slog.e(TAG, "Didn't find start tag during restore"); 13921 } 13922 return; 13923 } 13924 13925 // this is supposed to be TAG_PREFERRED_BACKUP 13926 if (!expectedStartTag.equals(parser.getName())) { 13927 if (DEBUG_BACKUP) { 13928 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13929 } 13930 return; 13931 } 13932 13933 // skip interfering stuff, then we're aligned with the backing implementation 13934 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13935 functor.apply(parser, userId); 13936 } 13937 13938 private interface BlobXmlRestorer { 13939 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13940 } 13941 13942 /** 13943 * Non-Binder method, support for the backup/restore mechanism: write the 13944 * full set of preferred activities in its canonical XML format. Returns the 13945 * XML output as a byte array, or null if there is none. 13946 */ 13947 @Override 13948 public byte[] getPreferredActivityBackup(int userId) { 13949 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13950 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13951 } 13952 13953 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13954 try { 13955 final XmlSerializer serializer = new FastXmlSerializer(); 13956 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13957 serializer.startDocument(null, true); 13958 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13959 13960 synchronized (mPackages) { 13961 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13962 } 13963 13964 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13965 serializer.endDocument(); 13966 serializer.flush(); 13967 } catch (Exception e) { 13968 if (DEBUG_BACKUP) { 13969 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13970 } 13971 return null; 13972 } 13973 13974 return dataStream.toByteArray(); 13975 } 13976 13977 @Override 13978 public void restorePreferredActivities(byte[] backup, int userId) { 13979 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13980 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13981 } 13982 13983 try { 13984 final XmlPullParser parser = Xml.newPullParser(); 13985 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13986 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13987 new BlobXmlRestorer() { 13988 @Override 13989 public void apply(XmlPullParser parser, int userId) 13990 throws XmlPullParserException, IOException { 13991 synchronized (mPackages) { 13992 mSettings.readPreferredActivitiesLPw(parser, userId); 13993 } 13994 } 13995 } ); 13996 } catch (Exception e) { 13997 if (DEBUG_BACKUP) { 13998 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13999 } 14000 } 14001 } 14002 14003 /** 14004 * Non-Binder method, support for the backup/restore mechanism: write the 14005 * default browser (etc) settings in its canonical XML format. Returns the default 14006 * browser XML representation as a byte array, or null if there is none. 14007 */ 14008 @Override 14009 public byte[] getDefaultAppsBackup(int userId) { 14010 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14011 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14012 } 14013 14014 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14015 try { 14016 final XmlSerializer serializer = new FastXmlSerializer(); 14017 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14018 serializer.startDocument(null, true); 14019 serializer.startTag(null, TAG_DEFAULT_APPS); 14020 14021 synchronized (mPackages) { 14022 mSettings.writeDefaultAppsLPr(serializer, userId); 14023 } 14024 14025 serializer.endTag(null, TAG_DEFAULT_APPS); 14026 serializer.endDocument(); 14027 serializer.flush(); 14028 } catch (Exception e) { 14029 if (DEBUG_BACKUP) { 14030 Slog.e(TAG, "Unable to write default apps for backup", e); 14031 } 14032 return null; 14033 } 14034 14035 return dataStream.toByteArray(); 14036 } 14037 14038 @Override 14039 public void restoreDefaultApps(byte[] backup, int userId) { 14040 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14041 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14042 } 14043 14044 try { 14045 final XmlPullParser parser = Xml.newPullParser(); 14046 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14047 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14048 new BlobXmlRestorer() { 14049 @Override 14050 public void apply(XmlPullParser parser, int userId) 14051 throws XmlPullParserException, IOException { 14052 synchronized (mPackages) { 14053 mSettings.readDefaultAppsLPw(parser, userId); 14054 } 14055 } 14056 } ); 14057 } catch (Exception e) { 14058 if (DEBUG_BACKUP) { 14059 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14060 } 14061 } 14062 } 14063 14064 @Override 14065 public byte[] getIntentFilterVerificationBackup(int userId) { 14066 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14067 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14068 } 14069 14070 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14071 try { 14072 final XmlSerializer serializer = new FastXmlSerializer(); 14073 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14074 serializer.startDocument(null, true); 14075 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14076 14077 synchronized (mPackages) { 14078 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14079 } 14080 14081 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14082 serializer.endDocument(); 14083 serializer.flush(); 14084 } catch (Exception e) { 14085 if (DEBUG_BACKUP) { 14086 Slog.e(TAG, "Unable to write default apps for backup", e); 14087 } 14088 return null; 14089 } 14090 14091 return dataStream.toByteArray(); 14092 } 14093 14094 @Override 14095 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14096 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14097 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14098 } 14099 14100 try { 14101 final XmlPullParser parser = Xml.newPullParser(); 14102 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14103 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14104 new BlobXmlRestorer() { 14105 @Override 14106 public void apply(XmlPullParser parser, int userId) 14107 throws XmlPullParserException, IOException { 14108 synchronized (mPackages) { 14109 mSettings.readAllDomainVerificationsLPr(parser, userId); 14110 mSettings.writeLPr(); 14111 } 14112 } 14113 } ); 14114 } catch (Exception e) { 14115 if (DEBUG_BACKUP) { 14116 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14117 } 14118 } 14119 } 14120 14121 @Override 14122 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14123 int sourceUserId, int targetUserId, int flags) { 14124 mContext.enforceCallingOrSelfPermission( 14125 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14126 int callingUid = Binder.getCallingUid(); 14127 enforceOwnerRights(ownerPackage, callingUid); 14128 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14129 if (intentFilter.countActions() == 0) { 14130 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14131 return; 14132 } 14133 synchronized (mPackages) { 14134 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14135 ownerPackage, targetUserId, flags); 14136 CrossProfileIntentResolver resolver = 14137 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14138 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14139 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14140 if (existing != null) { 14141 int size = existing.size(); 14142 for (int i = 0; i < size; i++) { 14143 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14144 return; 14145 } 14146 } 14147 } 14148 resolver.addFilter(newFilter); 14149 scheduleWritePackageRestrictionsLocked(sourceUserId); 14150 } 14151 } 14152 14153 @Override 14154 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14155 mContext.enforceCallingOrSelfPermission( 14156 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14157 int callingUid = Binder.getCallingUid(); 14158 enforceOwnerRights(ownerPackage, callingUid); 14159 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14160 synchronized (mPackages) { 14161 CrossProfileIntentResolver resolver = 14162 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14163 ArraySet<CrossProfileIntentFilter> set = 14164 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14165 for (CrossProfileIntentFilter filter : set) { 14166 if (filter.getOwnerPackage().equals(ownerPackage)) { 14167 resolver.removeFilter(filter); 14168 } 14169 } 14170 scheduleWritePackageRestrictionsLocked(sourceUserId); 14171 } 14172 } 14173 14174 // Enforcing that callingUid is owning pkg on userId 14175 private void enforceOwnerRights(String pkg, int callingUid) { 14176 // The system owns everything. 14177 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14178 return; 14179 } 14180 int callingUserId = UserHandle.getUserId(callingUid); 14181 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14182 if (pi == null) { 14183 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14184 + callingUserId); 14185 } 14186 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14187 throw new SecurityException("Calling uid " + callingUid 14188 + " does not own package " + pkg); 14189 } 14190 } 14191 14192 @Override 14193 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14194 Intent intent = new Intent(Intent.ACTION_MAIN); 14195 intent.addCategory(Intent.CATEGORY_HOME); 14196 14197 final int callingUserId = UserHandle.getCallingUserId(); 14198 List<ResolveInfo> list = queryIntentActivities(intent, null, 14199 PackageManager.GET_META_DATA, callingUserId); 14200 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14201 true, false, false, callingUserId); 14202 14203 allHomeCandidates.clear(); 14204 if (list != null) { 14205 for (ResolveInfo ri : list) { 14206 allHomeCandidates.add(ri); 14207 } 14208 } 14209 return (preferred == null || preferred.activityInfo == null) 14210 ? null 14211 : new ComponentName(preferred.activityInfo.packageName, 14212 preferred.activityInfo.name); 14213 } 14214 14215 @Override 14216 public void setApplicationEnabledSetting(String appPackageName, 14217 int newState, int flags, int userId, String callingPackage) { 14218 if (!sUserManager.exists(userId)) return; 14219 if (callingPackage == null) { 14220 callingPackage = Integer.toString(Binder.getCallingUid()); 14221 } 14222 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14223 } 14224 14225 @Override 14226 public void setComponentEnabledSetting(ComponentName componentName, 14227 int newState, int flags, int userId) { 14228 if (!sUserManager.exists(userId)) return; 14229 setEnabledSetting(componentName.getPackageName(), 14230 componentName.getClassName(), newState, flags, userId, null); 14231 } 14232 14233 private void setEnabledSetting(final String packageName, String className, int newState, 14234 final int flags, int userId, String callingPackage) { 14235 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14236 || newState == COMPONENT_ENABLED_STATE_ENABLED 14237 || newState == COMPONENT_ENABLED_STATE_DISABLED 14238 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14239 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14240 throw new IllegalArgumentException("Invalid new component state: " 14241 + newState); 14242 } 14243 PackageSetting pkgSetting; 14244 final int uid = Binder.getCallingUid(); 14245 final int permission = mContext.checkCallingOrSelfPermission( 14246 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14247 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14248 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14249 boolean sendNow = false; 14250 boolean isApp = (className == null); 14251 String componentName = isApp ? packageName : className; 14252 int packageUid = -1; 14253 ArrayList<String> components; 14254 14255 // writer 14256 synchronized (mPackages) { 14257 pkgSetting = mSettings.mPackages.get(packageName); 14258 if (pkgSetting == null) { 14259 if (className == null) { 14260 throw new IllegalArgumentException( 14261 "Unknown package: " + packageName); 14262 } 14263 throw new IllegalArgumentException( 14264 "Unknown component: " + packageName 14265 + "/" + className); 14266 } 14267 // Allow root and verify that userId is not being specified by a different user 14268 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14269 throw new SecurityException( 14270 "Permission Denial: attempt to change component state from pid=" 14271 + Binder.getCallingPid() 14272 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14273 } 14274 if (className == null) { 14275 // We're dealing with an application/package level state change 14276 if (pkgSetting.getEnabled(userId) == newState) { 14277 // Nothing to do 14278 return; 14279 } 14280 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14281 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14282 // Don't care about who enables an app. 14283 callingPackage = null; 14284 } 14285 pkgSetting.setEnabled(newState, userId, callingPackage); 14286 // pkgSetting.pkg.mSetEnabled = newState; 14287 } else { 14288 // We're dealing with a component level state change 14289 // First, verify that this is a valid class name. 14290 PackageParser.Package pkg = pkgSetting.pkg; 14291 if (pkg == null || !pkg.hasComponentClassName(className)) { 14292 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14293 throw new IllegalArgumentException("Component class " + className 14294 + " does not exist in " + packageName); 14295 } else { 14296 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14297 + className + " does not exist in " + packageName); 14298 } 14299 } 14300 switch (newState) { 14301 case COMPONENT_ENABLED_STATE_ENABLED: 14302 if (!pkgSetting.enableComponentLPw(className, userId)) { 14303 return; 14304 } 14305 break; 14306 case COMPONENT_ENABLED_STATE_DISABLED: 14307 if (!pkgSetting.disableComponentLPw(className, userId)) { 14308 return; 14309 } 14310 break; 14311 case COMPONENT_ENABLED_STATE_DEFAULT: 14312 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14313 return; 14314 } 14315 break; 14316 default: 14317 Slog.e(TAG, "Invalid new component state: " + newState); 14318 return; 14319 } 14320 } 14321 scheduleWritePackageRestrictionsLocked(userId); 14322 components = mPendingBroadcasts.get(userId, packageName); 14323 final boolean newPackage = components == null; 14324 if (newPackage) { 14325 components = new ArrayList<String>(); 14326 } 14327 if (!components.contains(componentName)) { 14328 components.add(componentName); 14329 } 14330 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14331 sendNow = true; 14332 // Purge entry from pending broadcast list if another one exists already 14333 // since we are sending one right away. 14334 mPendingBroadcasts.remove(userId, packageName); 14335 } else { 14336 if (newPackage) { 14337 mPendingBroadcasts.put(userId, packageName, components); 14338 } 14339 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14340 // Schedule a message 14341 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14342 } 14343 } 14344 } 14345 14346 long callingId = Binder.clearCallingIdentity(); 14347 try { 14348 if (sendNow) { 14349 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14350 sendPackageChangedBroadcast(packageName, 14351 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14352 } 14353 } finally { 14354 Binder.restoreCallingIdentity(callingId); 14355 } 14356 } 14357 14358 private void sendPackageChangedBroadcast(String packageName, 14359 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14360 if (DEBUG_INSTALL) 14361 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14362 + componentNames); 14363 Bundle extras = new Bundle(4); 14364 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14365 String nameList[] = new String[componentNames.size()]; 14366 componentNames.toArray(nameList); 14367 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14368 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14369 extras.putInt(Intent.EXTRA_UID, packageUid); 14370 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14371 new int[] {UserHandle.getUserId(packageUid)}); 14372 } 14373 14374 @Override 14375 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14376 if (!sUserManager.exists(userId)) return; 14377 final int uid = Binder.getCallingUid(); 14378 final int permission = mContext.checkCallingOrSelfPermission( 14379 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14380 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14381 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14382 // writer 14383 synchronized (mPackages) { 14384 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14385 allowedByPermission, uid, userId)) { 14386 scheduleWritePackageRestrictionsLocked(userId); 14387 } 14388 } 14389 } 14390 14391 @Override 14392 public String getInstallerPackageName(String packageName) { 14393 // reader 14394 synchronized (mPackages) { 14395 return mSettings.getInstallerPackageNameLPr(packageName); 14396 } 14397 } 14398 14399 @Override 14400 public int getApplicationEnabledSetting(String packageName, int userId) { 14401 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14402 int uid = Binder.getCallingUid(); 14403 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14404 // reader 14405 synchronized (mPackages) { 14406 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14407 } 14408 } 14409 14410 @Override 14411 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14412 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14413 int uid = Binder.getCallingUid(); 14414 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14415 // reader 14416 synchronized (mPackages) { 14417 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14418 } 14419 } 14420 14421 @Override 14422 public void enterSafeMode() { 14423 enforceSystemOrRoot("Only the system can request entering safe mode"); 14424 14425 if (!mSystemReady) { 14426 mSafeMode = true; 14427 } 14428 } 14429 14430 @Override 14431 public void systemReady() { 14432 mSystemReady = true; 14433 14434 // Read the compatibilty setting when the system is ready. 14435 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14436 mContext.getContentResolver(), 14437 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14438 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14439 if (DEBUG_SETTINGS) { 14440 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14441 } 14442 14443 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14444 14445 synchronized (mPackages) { 14446 // Verify that all of the preferred activity components actually 14447 // exist. It is possible for applications to be updated and at 14448 // that point remove a previously declared activity component that 14449 // had been set as a preferred activity. We try to clean this up 14450 // the next time we encounter that preferred activity, but it is 14451 // possible for the user flow to never be able to return to that 14452 // situation so here we do a sanity check to make sure we haven't 14453 // left any junk around. 14454 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14455 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14456 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14457 removed.clear(); 14458 for (PreferredActivity pa : pir.filterSet()) { 14459 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14460 removed.add(pa); 14461 } 14462 } 14463 if (removed.size() > 0) { 14464 for (int r=0; r<removed.size(); r++) { 14465 PreferredActivity pa = removed.get(r); 14466 Slog.w(TAG, "Removing dangling preferred activity: " 14467 + pa.mPref.mComponent); 14468 pir.removeFilter(pa); 14469 } 14470 mSettings.writePackageRestrictionsLPr( 14471 mSettings.mPreferredActivities.keyAt(i)); 14472 } 14473 } 14474 14475 for (int userId : UserManagerService.getInstance().getUserIds()) { 14476 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14477 grantPermissionsUserIds = ArrayUtils.appendInt( 14478 grantPermissionsUserIds, userId); 14479 } 14480 } 14481 } 14482 sUserManager.systemReady(); 14483 14484 // If we upgraded grant all default permissions before kicking off. 14485 for (int userId : grantPermissionsUserIds) { 14486 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14487 } 14488 14489 // Kick off any messages waiting for system ready 14490 if (mPostSystemReadyMessages != null) { 14491 for (Message msg : mPostSystemReadyMessages) { 14492 msg.sendToTarget(); 14493 } 14494 mPostSystemReadyMessages = null; 14495 } 14496 14497 // Watch for external volumes that come and go over time 14498 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14499 storage.registerListener(mStorageListener); 14500 14501 mInstallerService.systemReady(); 14502 mPackageDexOptimizer.systemReady(); 14503 14504 MountServiceInternal mountServiceInternal = LocalServices.getService( 14505 MountServiceInternal.class); 14506 mountServiceInternal.addExternalStoragePolicy( 14507 new MountServiceInternal.ExternalStorageMountPolicy() { 14508 @Override 14509 public int getMountMode(int uid, String packageName) { 14510 if (Process.isIsolated(uid)) { 14511 return Zygote.MOUNT_EXTERNAL_NONE; 14512 } 14513 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14514 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14515 } 14516 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14517 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14518 } 14519 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14520 return Zygote.MOUNT_EXTERNAL_READ; 14521 } 14522 return Zygote.MOUNT_EXTERNAL_WRITE; 14523 } 14524 14525 @Override 14526 public boolean hasExternalStorage(int uid, String packageName) { 14527 return true; 14528 } 14529 }); 14530 } 14531 14532 @Override 14533 public boolean isSafeMode() { 14534 return mSafeMode; 14535 } 14536 14537 @Override 14538 public boolean hasSystemUidErrors() { 14539 return mHasSystemUidErrors; 14540 } 14541 14542 static String arrayToString(int[] array) { 14543 StringBuffer buf = new StringBuffer(128); 14544 buf.append('['); 14545 if (array != null) { 14546 for (int i=0; i<array.length; i++) { 14547 if (i > 0) buf.append(", "); 14548 buf.append(array[i]); 14549 } 14550 } 14551 buf.append(']'); 14552 return buf.toString(); 14553 } 14554 14555 static class DumpState { 14556 public static final int DUMP_LIBS = 1 << 0; 14557 public static final int DUMP_FEATURES = 1 << 1; 14558 public static final int DUMP_RESOLVERS = 1 << 2; 14559 public static final int DUMP_PERMISSIONS = 1 << 3; 14560 public static final int DUMP_PACKAGES = 1 << 4; 14561 public static final int DUMP_SHARED_USERS = 1 << 5; 14562 public static final int DUMP_MESSAGES = 1 << 6; 14563 public static final int DUMP_PROVIDERS = 1 << 7; 14564 public static final int DUMP_VERIFIERS = 1 << 8; 14565 public static final int DUMP_PREFERRED = 1 << 9; 14566 public static final int DUMP_PREFERRED_XML = 1 << 10; 14567 public static final int DUMP_KEYSETS = 1 << 11; 14568 public static final int DUMP_VERSION = 1 << 12; 14569 public static final int DUMP_INSTALLS = 1 << 13; 14570 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14571 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14572 14573 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14574 14575 private int mTypes; 14576 14577 private int mOptions; 14578 14579 private boolean mTitlePrinted; 14580 14581 private SharedUserSetting mSharedUser; 14582 14583 public boolean isDumping(int type) { 14584 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14585 return true; 14586 } 14587 14588 return (mTypes & type) != 0; 14589 } 14590 14591 public void setDump(int type) { 14592 mTypes |= type; 14593 } 14594 14595 public boolean isOptionEnabled(int option) { 14596 return (mOptions & option) != 0; 14597 } 14598 14599 public void setOptionEnabled(int option) { 14600 mOptions |= option; 14601 } 14602 14603 public boolean onTitlePrinted() { 14604 final boolean printed = mTitlePrinted; 14605 mTitlePrinted = true; 14606 return printed; 14607 } 14608 14609 public boolean getTitlePrinted() { 14610 return mTitlePrinted; 14611 } 14612 14613 public void setTitlePrinted(boolean enabled) { 14614 mTitlePrinted = enabled; 14615 } 14616 14617 public SharedUserSetting getSharedUser() { 14618 return mSharedUser; 14619 } 14620 14621 public void setSharedUser(SharedUserSetting user) { 14622 mSharedUser = user; 14623 } 14624 } 14625 14626 @Override 14627 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14628 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14629 != PackageManager.PERMISSION_GRANTED) { 14630 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14631 + Binder.getCallingPid() 14632 + ", uid=" + Binder.getCallingUid() 14633 + " without permission " 14634 + android.Manifest.permission.DUMP); 14635 return; 14636 } 14637 14638 DumpState dumpState = new DumpState(); 14639 boolean fullPreferred = false; 14640 boolean checkin = false; 14641 14642 String packageName = null; 14643 ArraySet<String> permissionNames = null; 14644 14645 int opti = 0; 14646 while (opti < args.length) { 14647 String opt = args[opti]; 14648 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14649 break; 14650 } 14651 opti++; 14652 14653 if ("-a".equals(opt)) { 14654 // Right now we only know how to print all. 14655 } else if ("-h".equals(opt)) { 14656 pw.println("Package manager dump options:"); 14657 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14658 pw.println(" --checkin: dump for a checkin"); 14659 pw.println(" -f: print details of intent filters"); 14660 pw.println(" -h: print this help"); 14661 pw.println(" cmd may be one of:"); 14662 pw.println(" l[ibraries]: list known shared libraries"); 14663 pw.println(" f[ibraries]: list device features"); 14664 pw.println(" k[eysets]: print known keysets"); 14665 pw.println(" r[esolvers]: dump intent resolvers"); 14666 pw.println(" perm[issions]: dump permissions"); 14667 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14668 pw.println(" pref[erred]: print preferred package settings"); 14669 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14670 pw.println(" prov[iders]: dump content providers"); 14671 pw.println(" p[ackages]: dump installed packages"); 14672 pw.println(" s[hared-users]: dump shared user IDs"); 14673 pw.println(" m[essages]: print collected runtime messages"); 14674 pw.println(" v[erifiers]: print package verifier info"); 14675 pw.println(" version: print database version info"); 14676 pw.println(" write: write current settings now"); 14677 pw.println(" <package.name>: info about given package"); 14678 pw.println(" installs: details about install sessions"); 14679 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14680 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14681 return; 14682 } else if ("--checkin".equals(opt)) { 14683 checkin = true; 14684 } else if ("-f".equals(opt)) { 14685 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14686 } else { 14687 pw.println("Unknown argument: " + opt + "; use -h for help"); 14688 } 14689 } 14690 14691 // Is the caller requesting to dump a particular piece of data? 14692 if (opti < args.length) { 14693 String cmd = args[opti]; 14694 opti++; 14695 // Is this a package name? 14696 if ("android".equals(cmd) || cmd.contains(".")) { 14697 packageName = cmd; 14698 // When dumping a single package, we always dump all of its 14699 // filter information since the amount of data will be reasonable. 14700 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14701 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14702 dumpState.setDump(DumpState.DUMP_LIBS); 14703 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14704 dumpState.setDump(DumpState.DUMP_FEATURES); 14705 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14706 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14707 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14708 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14709 } else if ("permission".equals(cmd)) { 14710 if (opti >= args.length) { 14711 pw.println("Error: permission requires permission name"); 14712 return; 14713 } 14714 permissionNames = new ArraySet<>(); 14715 while (opti < args.length) { 14716 permissionNames.add(args[opti]); 14717 opti++; 14718 } 14719 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14720 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14721 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14722 dumpState.setDump(DumpState.DUMP_PREFERRED); 14723 } else if ("preferred-xml".equals(cmd)) { 14724 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14725 if (opti < args.length && "--full".equals(args[opti])) { 14726 fullPreferred = true; 14727 opti++; 14728 } 14729 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14730 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14731 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14732 dumpState.setDump(DumpState.DUMP_PACKAGES); 14733 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14734 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14735 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14736 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14737 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14738 dumpState.setDump(DumpState.DUMP_MESSAGES); 14739 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14740 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14741 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14742 || "intent-filter-verifiers".equals(cmd)) { 14743 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14744 } else if ("version".equals(cmd)) { 14745 dumpState.setDump(DumpState.DUMP_VERSION); 14746 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14747 dumpState.setDump(DumpState.DUMP_KEYSETS); 14748 } else if ("installs".equals(cmd)) { 14749 dumpState.setDump(DumpState.DUMP_INSTALLS); 14750 } else if ("write".equals(cmd)) { 14751 synchronized (mPackages) { 14752 mSettings.writeLPr(); 14753 pw.println("Settings written."); 14754 return; 14755 } 14756 } 14757 } 14758 14759 if (checkin) { 14760 pw.println("vers,1"); 14761 } 14762 14763 // reader 14764 synchronized (mPackages) { 14765 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14766 if (!checkin) { 14767 if (dumpState.onTitlePrinted()) 14768 pw.println(); 14769 pw.println("Database versions:"); 14770 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14771 } 14772 } 14773 14774 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14775 if (!checkin) { 14776 if (dumpState.onTitlePrinted()) 14777 pw.println(); 14778 pw.println("Verifiers:"); 14779 pw.print(" Required: "); 14780 pw.print(mRequiredVerifierPackage); 14781 pw.print(" (uid="); 14782 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14783 pw.println(")"); 14784 } else if (mRequiredVerifierPackage != null) { 14785 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14786 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14787 } 14788 } 14789 14790 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14791 packageName == null) { 14792 if (mIntentFilterVerifierComponent != null) { 14793 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14794 if (!checkin) { 14795 if (dumpState.onTitlePrinted()) 14796 pw.println(); 14797 pw.println("Intent Filter Verifier:"); 14798 pw.print(" Using: "); 14799 pw.print(verifierPackageName); 14800 pw.print(" (uid="); 14801 pw.print(getPackageUid(verifierPackageName, 0)); 14802 pw.println(")"); 14803 } else if (verifierPackageName != null) { 14804 pw.print("ifv,"); pw.print(verifierPackageName); 14805 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14806 } 14807 } else { 14808 pw.println(); 14809 pw.println("No Intent Filter Verifier available!"); 14810 } 14811 } 14812 14813 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14814 boolean printedHeader = false; 14815 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14816 while (it.hasNext()) { 14817 String name = it.next(); 14818 SharedLibraryEntry ent = mSharedLibraries.get(name); 14819 if (!checkin) { 14820 if (!printedHeader) { 14821 if (dumpState.onTitlePrinted()) 14822 pw.println(); 14823 pw.println("Libraries:"); 14824 printedHeader = true; 14825 } 14826 pw.print(" "); 14827 } else { 14828 pw.print("lib,"); 14829 } 14830 pw.print(name); 14831 if (!checkin) { 14832 pw.print(" -> "); 14833 } 14834 if (ent.path != null) { 14835 if (!checkin) { 14836 pw.print("(jar) "); 14837 pw.print(ent.path); 14838 } else { 14839 pw.print(",jar,"); 14840 pw.print(ent.path); 14841 } 14842 } else { 14843 if (!checkin) { 14844 pw.print("(apk) "); 14845 pw.print(ent.apk); 14846 } else { 14847 pw.print(",apk,"); 14848 pw.print(ent.apk); 14849 } 14850 } 14851 pw.println(); 14852 } 14853 } 14854 14855 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14856 if (dumpState.onTitlePrinted()) 14857 pw.println(); 14858 if (!checkin) { 14859 pw.println("Features:"); 14860 } 14861 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14862 while (it.hasNext()) { 14863 String name = it.next(); 14864 if (!checkin) { 14865 pw.print(" "); 14866 } else { 14867 pw.print("feat,"); 14868 } 14869 pw.println(name); 14870 } 14871 } 14872 14873 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14874 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14875 : "Activity Resolver Table:", " ", packageName, 14876 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14877 dumpState.setTitlePrinted(true); 14878 } 14879 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14880 : "Receiver Resolver Table:", " ", packageName, 14881 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14882 dumpState.setTitlePrinted(true); 14883 } 14884 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14885 : "Service Resolver Table:", " ", packageName, 14886 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14887 dumpState.setTitlePrinted(true); 14888 } 14889 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14890 : "Provider Resolver Table:", " ", packageName, 14891 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14892 dumpState.setTitlePrinted(true); 14893 } 14894 } 14895 14896 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14897 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14898 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14899 int user = mSettings.mPreferredActivities.keyAt(i); 14900 if (pir.dump(pw, 14901 dumpState.getTitlePrinted() 14902 ? "\nPreferred Activities User " + user + ":" 14903 : "Preferred Activities User " + user + ":", " ", 14904 packageName, true, false)) { 14905 dumpState.setTitlePrinted(true); 14906 } 14907 } 14908 } 14909 14910 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14911 pw.flush(); 14912 FileOutputStream fout = new FileOutputStream(fd); 14913 BufferedOutputStream str = new BufferedOutputStream(fout); 14914 XmlSerializer serializer = new FastXmlSerializer(); 14915 try { 14916 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14917 serializer.startDocument(null, true); 14918 serializer.setFeature( 14919 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14920 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14921 serializer.endDocument(); 14922 serializer.flush(); 14923 } catch (IllegalArgumentException e) { 14924 pw.println("Failed writing: " + e); 14925 } catch (IllegalStateException e) { 14926 pw.println("Failed writing: " + e); 14927 } catch (IOException e) { 14928 pw.println("Failed writing: " + e); 14929 } 14930 } 14931 14932 if (!checkin 14933 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14934 && packageName == null) { 14935 pw.println(); 14936 int count = mSettings.mPackages.size(); 14937 if (count == 0) { 14938 pw.println("No applications!"); 14939 pw.println(); 14940 } else { 14941 final String prefix = " "; 14942 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14943 if (allPackageSettings.size() == 0) { 14944 pw.println("No domain preferred apps!"); 14945 pw.println(); 14946 } else { 14947 pw.println("App verification status:"); 14948 pw.println(); 14949 count = 0; 14950 for (PackageSetting ps : allPackageSettings) { 14951 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14952 if (ivi == null || ivi.getPackageName() == null) continue; 14953 pw.println(prefix + "Package: " + ivi.getPackageName()); 14954 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14955 pw.println(prefix + "Status: " + ivi.getStatusString()); 14956 pw.println(); 14957 count++; 14958 } 14959 if (count == 0) { 14960 pw.println(prefix + "No app verification established."); 14961 pw.println(); 14962 } 14963 for (int userId : sUserManager.getUserIds()) { 14964 pw.println("App linkages for user " + userId + ":"); 14965 pw.println(); 14966 count = 0; 14967 for (PackageSetting ps : allPackageSettings) { 14968 final long status = ps.getDomainVerificationStatusForUser(userId); 14969 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14970 continue; 14971 } 14972 pw.println(prefix + "Package: " + ps.name); 14973 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14974 String statusStr = IntentFilterVerificationInfo. 14975 getStatusStringFromValue(status); 14976 pw.println(prefix + "Status: " + statusStr); 14977 pw.println(); 14978 count++; 14979 } 14980 if (count == 0) { 14981 pw.println(prefix + "No configured app linkages."); 14982 pw.println(); 14983 } 14984 } 14985 } 14986 } 14987 } 14988 14989 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14990 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14991 if (packageName == null && permissionNames == null) { 14992 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14993 if (iperm == 0) { 14994 if (dumpState.onTitlePrinted()) 14995 pw.println(); 14996 pw.println("AppOp Permissions:"); 14997 } 14998 pw.print(" AppOp Permission "); 14999 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15000 pw.println(":"); 15001 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15002 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15003 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15004 } 15005 } 15006 } 15007 } 15008 15009 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15010 boolean printedSomething = false; 15011 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15012 if (packageName != null && !packageName.equals(p.info.packageName)) { 15013 continue; 15014 } 15015 if (!printedSomething) { 15016 if (dumpState.onTitlePrinted()) 15017 pw.println(); 15018 pw.println("Registered ContentProviders:"); 15019 printedSomething = true; 15020 } 15021 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15022 pw.print(" "); pw.println(p.toString()); 15023 } 15024 printedSomething = false; 15025 for (Map.Entry<String, PackageParser.Provider> entry : 15026 mProvidersByAuthority.entrySet()) { 15027 PackageParser.Provider p = entry.getValue(); 15028 if (packageName != null && !packageName.equals(p.info.packageName)) { 15029 continue; 15030 } 15031 if (!printedSomething) { 15032 if (dumpState.onTitlePrinted()) 15033 pw.println(); 15034 pw.println("ContentProvider Authorities:"); 15035 printedSomething = true; 15036 } 15037 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15038 pw.print(" "); pw.println(p.toString()); 15039 if (p.info != null && p.info.applicationInfo != null) { 15040 final String appInfo = p.info.applicationInfo.toString(); 15041 pw.print(" applicationInfo="); pw.println(appInfo); 15042 } 15043 } 15044 } 15045 15046 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15047 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15048 } 15049 15050 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15051 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15052 } 15053 15054 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15055 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15056 } 15057 15058 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15059 // XXX should handle packageName != null by dumping only install data that 15060 // the given package is involved with. 15061 if (dumpState.onTitlePrinted()) pw.println(); 15062 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15063 } 15064 15065 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15066 if (dumpState.onTitlePrinted()) pw.println(); 15067 mSettings.dumpReadMessagesLPr(pw, dumpState); 15068 15069 pw.println(); 15070 pw.println("Package warning messages:"); 15071 BufferedReader in = null; 15072 String line = null; 15073 try { 15074 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15075 while ((line = in.readLine()) != null) { 15076 if (line.contains("ignored: updated version")) continue; 15077 pw.println(line); 15078 } 15079 } catch (IOException ignored) { 15080 } finally { 15081 IoUtils.closeQuietly(in); 15082 } 15083 } 15084 15085 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15086 BufferedReader in = null; 15087 String line = null; 15088 try { 15089 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15090 while ((line = in.readLine()) != null) { 15091 if (line.contains("ignored: updated version")) continue; 15092 pw.print("msg,"); 15093 pw.println(line); 15094 } 15095 } catch (IOException ignored) { 15096 } finally { 15097 IoUtils.closeQuietly(in); 15098 } 15099 } 15100 } 15101 } 15102 15103 private String dumpDomainString(String packageName) { 15104 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15105 List<IntentFilter> filters = getAllIntentFilters(packageName); 15106 15107 ArraySet<String> result = new ArraySet<>(); 15108 if (iviList.size() > 0) { 15109 for (IntentFilterVerificationInfo ivi : iviList) { 15110 for (String host : ivi.getDomains()) { 15111 result.add(host); 15112 } 15113 } 15114 } 15115 if (filters != null && filters.size() > 0) { 15116 for (IntentFilter filter : filters) { 15117 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15118 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15119 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15120 result.addAll(filter.getHostsList()); 15121 } 15122 } 15123 } 15124 15125 StringBuilder sb = new StringBuilder(result.size() * 16); 15126 for (String domain : result) { 15127 if (sb.length() > 0) sb.append(" "); 15128 sb.append(domain); 15129 } 15130 return sb.toString(); 15131 } 15132 15133 // ------- apps on sdcard specific code ------- 15134 static final boolean DEBUG_SD_INSTALL = false; 15135 15136 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15137 15138 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15139 15140 private boolean mMediaMounted = false; 15141 15142 static String getEncryptKey() { 15143 try { 15144 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15145 SD_ENCRYPTION_KEYSTORE_NAME); 15146 if (sdEncKey == null) { 15147 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15148 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15149 if (sdEncKey == null) { 15150 Slog.e(TAG, "Failed to create encryption keys"); 15151 return null; 15152 } 15153 } 15154 return sdEncKey; 15155 } catch (NoSuchAlgorithmException nsae) { 15156 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15157 return null; 15158 } catch (IOException ioe) { 15159 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15160 return null; 15161 } 15162 } 15163 15164 /* 15165 * Update media status on PackageManager. 15166 */ 15167 @Override 15168 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15169 int callingUid = Binder.getCallingUid(); 15170 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15171 throw new SecurityException("Media status can only be updated by the system"); 15172 } 15173 // reader; this apparently protects mMediaMounted, but should probably 15174 // be a different lock in that case. 15175 synchronized (mPackages) { 15176 Log.i(TAG, "Updating external media status from " 15177 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15178 + (mediaStatus ? "mounted" : "unmounted")); 15179 if (DEBUG_SD_INSTALL) 15180 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15181 + ", mMediaMounted=" + mMediaMounted); 15182 if (mediaStatus == mMediaMounted) { 15183 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15184 : 0, -1); 15185 mHandler.sendMessage(msg); 15186 return; 15187 } 15188 mMediaMounted = mediaStatus; 15189 } 15190 // Queue up an async operation since the package installation may take a 15191 // little while. 15192 mHandler.post(new Runnable() { 15193 public void run() { 15194 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15195 } 15196 }); 15197 } 15198 15199 /** 15200 * Called by MountService when the initial ASECs to scan are available. 15201 * Should block until all the ASEC containers are finished being scanned. 15202 */ 15203 public void scanAvailableAsecs() { 15204 updateExternalMediaStatusInner(true, false, false); 15205 if (mShouldRestoreconData) { 15206 SELinuxMMAC.setRestoreconDone(); 15207 mShouldRestoreconData = false; 15208 } 15209 } 15210 15211 /* 15212 * Collect information of applications on external media, map them against 15213 * existing containers and update information based on current mount status. 15214 * Please note that we always have to report status if reportStatus has been 15215 * set to true especially when unloading packages. 15216 */ 15217 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15218 boolean externalStorage) { 15219 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15220 int[] uidArr = EmptyArray.INT; 15221 15222 final String[] list = PackageHelper.getSecureContainerList(); 15223 if (ArrayUtils.isEmpty(list)) { 15224 Log.i(TAG, "No secure containers found"); 15225 } else { 15226 // Process list of secure containers and categorize them 15227 // as active or stale based on their package internal state. 15228 15229 // reader 15230 synchronized (mPackages) { 15231 for (String cid : list) { 15232 // Leave stages untouched for now; installer service owns them 15233 if (PackageInstallerService.isStageName(cid)) continue; 15234 15235 if (DEBUG_SD_INSTALL) 15236 Log.i(TAG, "Processing container " + cid); 15237 String pkgName = getAsecPackageName(cid); 15238 if (pkgName == null) { 15239 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15240 continue; 15241 } 15242 if (DEBUG_SD_INSTALL) 15243 Log.i(TAG, "Looking for pkg : " + pkgName); 15244 15245 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15246 if (ps == null) { 15247 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15248 continue; 15249 } 15250 15251 /* 15252 * Skip packages that are not external if we're unmounting 15253 * external storage. 15254 */ 15255 if (externalStorage && !isMounted && !isExternal(ps)) { 15256 continue; 15257 } 15258 15259 final AsecInstallArgs args = new AsecInstallArgs(cid, 15260 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15261 // The package status is changed only if the code path 15262 // matches between settings and the container id. 15263 if (ps.codePathString != null 15264 && ps.codePathString.startsWith(args.getCodePath())) { 15265 if (DEBUG_SD_INSTALL) { 15266 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15267 + " at code path: " + ps.codePathString); 15268 } 15269 15270 // We do have a valid package installed on sdcard 15271 processCids.put(args, ps.codePathString); 15272 final int uid = ps.appId; 15273 if (uid != -1) { 15274 uidArr = ArrayUtils.appendInt(uidArr, uid); 15275 } 15276 } else { 15277 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15278 + ps.codePathString); 15279 } 15280 } 15281 } 15282 15283 Arrays.sort(uidArr); 15284 } 15285 15286 // Process packages with valid entries. 15287 if (isMounted) { 15288 if (DEBUG_SD_INSTALL) 15289 Log.i(TAG, "Loading packages"); 15290 loadMediaPackages(processCids, uidArr); 15291 startCleaningPackages(); 15292 mInstallerService.onSecureContainersAvailable(); 15293 } else { 15294 if (DEBUG_SD_INSTALL) 15295 Log.i(TAG, "Unloading packages"); 15296 unloadMediaPackages(processCids, uidArr, reportStatus); 15297 } 15298 } 15299 15300 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15301 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15302 final int size = infos.size(); 15303 final String[] packageNames = new String[size]; 15304 final int[] packageUids = new int[size]; 15305 for (int i = 0; i < size; i++) { 15306 final ApplicationInfo info = infos.get(i); 15307 packageNames[i] = info.packageName; 15308 packageUids[i] = info.uid; 15309 } 15310 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15311 finishedReceiver); 15312 } 15313 15314 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15315 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15316 sendResourcesChangedBroadcast(mediaStatus, replacing, 15317 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15318 } 15319 15320 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15321 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15322 int size = pkgList.length; 15323 if (size > 0) { 15324 // Send broadcasts here 15325 Bundle extras = new Bundle(); 15326 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15327 if (uidArr != null) { 15328 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15329 } 15330 if (replacing) { 15331 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15332 } 15333 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15334 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15335 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15336 } 15337 } 15338 15339 /* 15340 * Look at potentially valid container ids from processCids If package 15341 * information doesn't match the one on record or package scanning fails, 15342 * the cid is added to list of removeCids. We currently don't delete stale 15343 * containers. 15344 */ 15345 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15346 ArrayList<String> pkgList = new ArrayList<String>(); 15347 Set<AsecInstallArgs> keys = processCids.keySet(); 15348 15349 for (AsecInstallArgs args : keys) { 15350 String codePath = processCids.get(args); 15351 if (DEBUG_SD_INSTALL) 15352 Log.i(TAG, "Loading container : " + args.cid); 15353 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15354 try { 15355 // Make sure there are no container errors first. 15356 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15357 Slog.e(TAG, "Failed to mount cid : " + args.cid 15358 + " when installing from sdcard"); 15359 continue; 15360 } 15361 // Check code path here. 15362 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15363 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15364 + " does not match one in settings " + codePath); 15365 continue; 15366 } 15367 // Parse package 15368 int parseFlags = mDefParseFlags; 15369 if (args.isExternalAsec()) { 15370 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15371 } 15372 if (args.isFwdLocked()) { 15373 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15374 } 15375 15376 synchronized (mInstallLock) { 15377 PackageParser.Package pkg = null; 15378 try { 15379 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15380 } catch (PackageManagerException e) { 15381 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15382 } 15383 // Scan the package 15384 if (pkg != null) { 15385 /* 15386 * TODO why is the lock being held? doPostInstall is 15387 * called in other places without the lock. This needs 15388 * to be straightened out. 15389 */ 15390 // writer 15391 synchronized (mPackages) { 15392 retCode = PackageManager.INSTALL_SUCCEEDED; 15393 pkgList.add(pkg.packageName); 15394 // Post process args 15395 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15396 pkg.applicationInfo.uid); 15397 } 15398 } else { 15399 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15400 } 15401 } 15402 15403 } finally { 15404 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15405 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15406 } 15407 } 15408 } 15409 // writer 15410 synchronized (mPackages) { 15411 // If the platform SDK has changed since the last time we booted, 15412 // we need to re-grant app permission to catch any new ones that 15413 // appear. This is really a hack, and means that apps can in some 15414 // cases get permissions that the user didn't initially explicitly 15415 // allow... it would be nice to have some better way to handle 15416 // this situation. 15417 final VersionInfo ver = mSettings.getExternalVersion(); 15418 15419 int updateFlags = UPDATE_PERMISSIONS_ALL; 15420 if (ver.sdkVersion != mSdkVersion) { 15421 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15422 + mSdkVersion + "; regranting permissions for external"); 15423 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15424 } 15425 updatePermissionsLPw(null, null, updateFlags); 15426 15427 // Yay, everything is now upgraded 15428 ver.forceCurrent(); 15429 15430 // can downgrade to reader 15431 // Persist settings 15432 mSettings.writeLPr(); 15433 } 15434 // Send a broadcast to let everyone know we are done processing 15435 if (pkgList.size() > 0) { 15436 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15437 } 15438 } 15439 15440 /* 15441 * Utility method to unload a list of specified containers 15442 */ 15443 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15444 // Just unmount all valid containers. 15445 for (AsecInstallArgs arg : cidArgs) { 15446 synchronized (mInstallLock) { 15447 arg.doPostDeleteLI(false); 15448 } 15449 } 15450 } 15451 15452 /* 15453 * Unload packages mounted on external media. This involves deleting package 15454 * data from internal structures, sending broadcasts about diabled packages, 15455 * gc'ing to free up references, unmounting all secure containers 15456 * corresponding to packages on external media, and posting a 15457 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15458 * that we always have to post this message if status has been requested no 15459 * matter what. 15460 */ 15461 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15462 final boolean reportStatus) { 15463 if (DEBUG_SD_INSTALL) 15464 Log.i(TAG, "unloading media packages"); 15465 ArrayList<String> pkgList = new ArrayList<String>(); 15466 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15467 final Set<AsecInstallArgs> keys = processCids.keySet(); 15468 for (AsecInstallArgs args : keys) { 15469 String pkgName = args.getPackageName(); 15470 if (DEBUG_SD_INSTALL) 15471 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15472 // Delete package internally 15473 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15474 synchronized (mInstallLock) { 15475 boolean res = deletePackageLI(pkgName, null, false, null, null, 15476 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15477 if (res) { 15478 pkgList.add(pkgName); 15479 } else { 15480 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15481 failedList.add(args); 15482 } 15483 } 15484 } 15485 15486 // reader 15487 synchronized (mPackages) { 15488 // We didn't update the settings after removing each package; 15489 // write them now for all packages. 15490 mSettings.writeLPr(); 15491 } 15492 15493 // We have to absolutely send UPDATED_MEDIA_STATUS only 15494 // after confirming that all the receivers processed the ordered 15495 // broadcast when packages get disabled, force a gc to clean things up. 15496 // and unload all the containers. 15497 if (pkgList.size() > 0) { 15498 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15499 new IIntentReceiver.Stub() { 15500 public void performReceive(Intent intent, int resultCode, String data, 15501 Bundle extras, boolean ordered, boolean sticky, 15502 int sendingUser) throws RemoteException { 15503 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15504 reportStatus ? 1 : 0, 1, keys); 15505 mHandler.sendMessage(msg); 15506 } 15507 }); 15508 } else { 15509 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15510 keys); 15511 mHandler.sendMessage(msg); 15512 } 15513 } 15514 15515 private void loadPrivatePackages(VolumeInfo vol) { 15516 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15517 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15518 synchronized (mInstallLock) { 15519 synchronized (mPackages) { 15520 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15521 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15522 for (PackageSetting ps : packages) { 15523 final PackageParser.Package pkg; 15524 try { 15525 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15526 loaded.add(pkg.applicationInfo); 15527 } catch (PackageManagerException e) { 15528 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15529 } 15530 15531 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15532 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15533 } 15534 } 15535 15536 int updateFlags = UPDATE_PERMISSIONS_ALL; 15537 if (ver.sdkVersion != mSdkVersion) { 15538 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15539 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15540 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15541 } 15542 updatePermissionsLPw(null, null, updateFlags); 15543 15544 // Yay, everything is now upgraded 15545 ver.forceCurrent(); 15546 15547 mSettings.writeLPr(); 15548 } 15549 } 15550 15551 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15552 sendResourcesChangedBroadcast(true, false, loaded, null); 15553 } 15554 15555 private void unloadPrivatePackages(VolumeInfo vol) { 15556 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15557 synchronized (mInstallLock) { 15558 synchronized (mPackages) { 15559 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15560 for (PackageSetting ps : packages) { 15561 if (ps.pkg == null) continue; 15562 15563 final ApplicationInfo info = ps.pkg.applicationInfo; 15564 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15565 if (deletePackageLI(ps.name, null, false, null, null, 15566 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15567 unloaded.add(info); 15568 } else { 15569 Slog.w(TAG, "Failed to unload " + ps.codePath); 15570 } 15571 } 15572 15573 mSettings.writeLPr(); 15574 } 15575 } 15576 15577 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15578 sendResourcesChangedBroadcast(false, false, unloaded, null); 15579 } 15580 15581 /** 15582 * Examine all users present on given mounted volume, and destroy data 15583 * belonging to users that are no longer valid, or whose user ID has been 15584 * recycled. 15585 */ 15586 private void reconcileUsers(String volumeUuid) { 15587 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15588 if (ArrayUtils.isEmpty(files)) { 15589 Slog.d(TAG, "No users found on " + volumeUuid); 15590 return; 15591 } 15592 15593 for (File file : files) { 15594 if (!file.isDirectory()) continue; 15595 15596 final int userId; 15597 final UserInfo info; 15598 try { 15599 userId = Integer.parseInt(file.getName()); 15600 info = sUserManager.getUserInfo(userId); 15601 } catch (NumberFormatException e) { 15602 Slog.w(TAG, "Invalid user directory " + file); 15603 continue; 15604 } 15605 15606 boolean destroyUser = false; 15607 if (info == null) { 15608 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15609 + " because no matching user was found"); 15610 destroyUser = true; 15611 } else { 15612 try { 15613 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15614 } catch (IOException e) { 15615 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15616 + " because we failed to enforce serial number: " + e); 15617 destroyUser = true; 15618 } 15619 } 15620 15621 if (destroyUser) { 15622 synchronized (mInstallLock) { 15623 mInstaller.removeUserDataDirs(volumeUuid, userId); 15624 } 15625 } 15626 } 15627 15628 final UserManager um = mContext.getSystemService(UserManager.class); 15629 for (UserInfo user : um.getUsers()) { 15630 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15631 if (userDir.exists()) continue; 15632 15633 try { 15634 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15635 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15636 } catch (IOException e) { 15637 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15638 } 15639 } 15640 } 15641 15642 /** 15643 * Examine all apps present on given mounted volume, and destroy apps that 15644 * aren't expected, either due to uninstallation or reinstallation on 15645 * another volume. 15646 */ 15647 private void reconcileApps(String volumeUuid) { 15648 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15649 if (ArrayUtils.isEmpty(files)) { 15650 Slog.d(TAG, "No apps found on " + volumeUuid); 15651 return; 15652 } 15653 15654 for (File file : files) { 15655 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15656 && !PackageInstallerService.isStageName(file.getName()); 15657 if (!isPackage) { 15658 // Ignore entries which are not packages 15659 continue; 15660 } 15661 15662 boolean destroyApp = false; 15663 String packageName = null; 15664 try { 15665 final PackageLite pkg = PackageParser.parsePackageLite(file, 15666 PackageParser.PARSE_MUST_BE_APK); 15667 packageName = pkg.packageName; 15668 15669 synchronized (mPackages) { 15670 final PackageSetting ps = mSettings.mPackages.get(packageName); 15671 if (ps == null) { 15672 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15673 + volumeUuid + " because we found no install record"); 15674 destroyApp = true; 15675 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15676 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15677 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15678 destroyApp = true; 15679 } 15680 } 15681 15682 } catch (PackageParserException e) { 15683 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15684 destroyApp = true; 15685 } 15686 15687 if (destroyApp) { 15688 synchronized (mInstallLock) { 15689 if (packageName != null) { 15690 removeDataDirsLI(volumeUuid, packageName); 15691 } 15692 if (file.isDirectory()) { 15693 mInstaller.rmPackageDir(file.getAbsolutePath()); 15694 } else { 15695 file.delete(); 15696 } 15697 } 15698 } 15699 } 15700 } 15701 15702 private void unfreezePackage(String packageName) { 15703 synchronized (mPackages) { 15704 final PackageSetting ps = mSettings.mPackages.get(packageName); 15705 if (ps != null) { 15706 ps.frozen = false; 15707 } 15708 } 15709 } 15710 15711 @Override 15712 public int movePackage(final String packageName, final String volumeUuid) { 15713 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15714 15715 final int moveId = mNextMoveId.getAndIncrement(); 15716 try { 15717 movePackageInternal(packageName, volumeUuid, moveId); 15718 } catch (PackageManagerException e) { 15719 Slog.w(TAG, "Failed to move " + packageName, e); 15720 mMoveCallbacks.notifyStatusChanged(moveId, 15721 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15722 } 15723 return moveId; 15724 } 15725 15726 private void movePackageInternal(final String packageName, final String volumeUuid, 15727 final int moveId) throws PackageManagerException { 15728 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15729 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15730 final PackageManager pm = mContext.getPackageManager(); 15731 15732 final boolean currentAsec; 15733 final String currentVolumeUuid; 15734 final File codeFile; 15735 final String installerPackageName; 15736 final String packageAbiOverride; 15737 final int appId; 15738 final String seinfo; 15739 final String label; 15740 15741 // reader 15742 synchronized (mPackages) { 15743 final PackageParser.Package pkg = mPackages.get(packageName); 15744 final PackageSetting ps = mSettings.mPackages.get(packageName); 15745 if (pkg == null || ps == null) { 15746 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15747 } 15748 15749 if (pkg.applicationInfo.isSystemApp()) { 15750 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15751 "Cannot move system application"); 15752 } 15753 15754 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15755 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15756 "Package already moved to " + volumeUuid); 15757 } 15758 15759 final File probe = new File(pkg.codePath); 15760 final File probeOat = new File(probe, "oat"); 15761 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15762 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15763 "Move only supported for modern cluster style installs"); 15764 } 15765 15766 if (ps.frozen) { 15767 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15768 "Failed to move already frozen package"); 15769 } 15770 ps.frozen = true; 15771 15772 currentAsec = pkg.applicationInfo.isForwardLocked() 15773 || pkg.applicationInfo.isExternalAsec(); 15774 currentVolumeUuid = ps.volumeUuid; 15775 codeFile = new File(pkg.codePath); 15776 installerPackageName = ps.installerPackageName; 15777 packageAbiOverride = ps.cpuAbiOverrideString; 15778 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15779 seinfo = pkg.applicationInfo.seinfo; 15780 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15781 } 15782 15783 // Now that we're guarded by frozen state, kill app during move 15784 killApplication(packageName, appId, "move pkg"); 15785 15786 final Bundle extras = new Bundle(); 15787 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15788 extras.putString(Intent.EXTRA_TITLE, label); 15789 mMoveCallbacks.notifyCreated(moveId, extras); 15790 15791 int installFlags; 15792 final boolean moveCompleteApp; 15793 final File measurePath; 15794 15795 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15796 installFlags = INSTALL_INTERNAL; 15797 moveCompleteApp = !currentAsec; 15798 measurePath = Environment.getDataAppDirectory(volumeUuid); 15799 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15800 installFlags = INSTALL_EXTERNAL; 15801 moveCompleteApp = false; 15802 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15803 } else { 15804 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15805 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15806 || !volume.isMountedWritable()) { 15807 unfreezePackage(packageName); 15808 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15809 "Move location not mounted private volume"); 15810 } 15811 15812 Preconditions.checkState(!currentAsec); 15813 15814 installFlags = INSTALL_INTERNAL; 15815 moveCompleteApp = true; 15816 measurePath = Environment.getDataAppDirectory(volumeUuid); 15817 } 15818 15819 final PackageStats stats = new PackageStats(null, -1); 15820 synchronized (mInstaller) { 15821 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15822 unfreezePackage(packageName); 15823 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15824 "Failed to measure package size"); 15825 } 15826 } 15827 15828 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15829 + stats.dataSize); 15830 15831 final long startFreeBytes = measurePath.getFreeSpace(); 15832 final long sizeBytes; 15833 if (moveCompleteApp) { 15834 sizeBytes = stats.codeSize + stats.dataSize; 15835 } else { 15836 sizeBytes = stats.codeSize; 15837 } 15838 15839 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15840 unfreezePackage(packageName); 15841 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15842 "Not enough free space to move"); 15843 } 15844 15845 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15846 15847 final CountDownLatch installedLatch = new CountDownLatch(1); 15848 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15849 @Override 15850 public void onUserActionRequired(Intent intent) throws RemoteException { 15851 throw new IllegalStateException(); 15852 } 15853 15854 @Override 15855 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15856 Bundle extras) throws RemoteException { 15857 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15858 + PackageManager.installStatusToString(returnCode, msg)); 15859 15860 installedLatch.countDown(); 15861 15862 // Regardless of success or failure of the move operation, 15863 // always unfreeze the package 15864 unfreezePackage(packageName); 15865 15866 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15867 switch (status) { 15868 case PackageInstaller.STATUS_SUCCESS: 15869 mMoveCallbacks.notifyStatusChanged(moveId, 15870 PackageManager.MOVE_SUCCEEDED); 15871 break; 15872 case PackageInstaller.STATUS_FAILURE_STORAGE: 15873 mMoveCallbacks.notifyStatusChanged(moveId, 15874 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15875 break; 15876 default: 15877 mMoveCallbacks.notifyStatusChanged(moveId, 15878 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15879 break; 15880 } 15881 } 15882 }; 15883 15884 final MoveInfo move; 15885 if (moveCompleteApp) { 15886 // Kick off a thread to report progress estimates 15887 new Thread() { 15888 @Override 15889 public void run() { 15890 while (true) { 15891 try { 15892 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15893 break; 15894 } 15895 } catch (InterruptedException ignored) { 15896 } 15897 15898 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15899 final int progress = 10 + (int) MathUtils.constrain( 15900 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15901 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15902 } 15903 } 15904 }.start(); 15905 15906 final String dataAppName = codeFile.getName(); 15907 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15908 dataAppName, appId, seinfo); 15909 } else { 15910 move = null; 15911 } 15912 15913 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15914 15915 final Message msg = mHandler.obtainMessage(INIT_COPY); 15916 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15917 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15918 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 15919 mHandler.sendMessage(msg); 15920 } 15921 15922 @Override 15923 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15924 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15925 15926 final int realMoveId = mNextMoveId.getAndIncrement(); 15927 final Bundle extras = new Bundle(); 15928 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15929 mMoveCallbacks.notifyCreated(realMoveId, extras); 15930 15931 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15932 @Override 15933 public void onCreated(int moveId, Bundle extras) { 15934 // Ignored 15935 } 15936 15937 @Override 15938 public void onStatusChanged(int moveId, int status, long estMillis) { 15939 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15940 } 15941 }; 15942 15943 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15944 storage.setPrimaryStorageUuid(volumeUuid, callback); 15945 return realMoveId; 15946 } 15947 15948 @Override 15949 public int getMoveStatus(int moveId) { 15950 mContext.enforceCallingOrSelfPermission( 15951 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15952 return mMoveCallbacks.mLastStatus.get(moveId); 15953 } 15954 15955 @Override 15956 public void registerMoveCallback(IPackageMoveObserver callback) { 15957 mContext.enforceCallingOrSelfPermission( 15958 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15959 mMoveCallbacks.register(callback); 15960 } 15961 15962 @Override 15963 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15964 mContext.enforceCallingOrSelfPermission( 15965 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15966 mMoveCallbacks.unregister(callback); 15967 } 15968 15969 @Override 15970 public boolean setInstallLocation(int loc) { 15971 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15972 null); 15973 if (getInstallLocation() == loc) { 15974 return true; 15975 } 15976 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15977 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15978 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15979 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15980 return true; 15981 } 15982 return false; 15983 } 15984 15985 @Override 15986 public int getInstallLocation() { 15987 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15988 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15989 PackageHelper.APP_INSTALL_AUTO); 15990 } 15991 15992 /** Called by UserManagerService */ 15993 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15994 mDirtyUsers.remove(userHandle); 15995 mSettings.removeUserLPw(userHandle); 15996 mPendingBroadcasts.remove(userHandle); 15997 if (mInstaller != null) { 15998 // Technically, we shouldn't be doing this with the package lock 15999 // held. However, this is very rare, and there is already so much 16000 // other disk I/O going on, that we'll let it slide for now. 16001 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16002 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16003 final String volumeUuid = vol.getFsUuid(); 16004 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16005 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16006 } 16007 } 16008 mUserNeedsBadging.delete(userHandle); 16009 removeUnusedPackagesLILPw(userManager, userHandle); 16010 } 16011 16012 /** 16013 * We're removing userHandle and would like to remove any downloaded packages 16014 * that are no longer in use by any other user. 16015 * @param userHandle the user being removed 16016 */ 16017 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16018 final boolean DEBUG_CLEAN_APKS = false; 16019 int [] users = userManager.getUserIdsLPr(); 16020 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16021 while (psit.hasNext()) { 16022 PackageSetting ps = psit.next(); 16023 if (ps.pkg == null) { 16024 continue; 16025 } 16026 final String packageName = ps.pkg.packageName; 16027 // Skip over if system app 16028 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16029 continue; 16030 } 16031 if (DEBUG_CLEAN_APKS) { 16032 Slog.i(TAG, "Checking package " + packageName); 16033 } 16034 boolean keep = false; 16035 for (int i = 0; i < users.length; i++) { 16036 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16037 keep = true; 16038 if (DEBUG_CLEAN_APKS) { 16039 Slog.i(TAG, " Keeping package " + packageName + " for user " 16040 + users[i]); 16041 } 16042 break; 16043 } 16044 } 16045 if (!keep) { 16046 if (DEBUG_CLEAN_APKS) { 16047 Slog.i(TAG, " Removing package " + packageName); 16048 } 16049 mHandler.post(new Runnable() { 16050 public void run() { 16051 deletePackageX(packageName, userHandle, 0); 16052 } //end run 16053 }); 16054 } 16055 } 16056 } 16057 16058 /** Called by UserManagerService */ 16059 void createNewUserLILPw(int userHandle) { 16060 if (mInstaller != null) { 16061 mInstaller.createUserConfig(userHandle); 16062 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16063 applyFactoryDefaultBrowserLPw(userHandle); 16064 primeDomainVerificationsLPw(userHandle); 16065 } 16066 } 16067 16068 void newUserCreated(final int userHandle) { 16069 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16070 } 16071 16072 @Override 16073 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16074 mContext.enforceCallingOrSelfPermission( 16075 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16076 "Only package verification agents can read the verifier device identity"); 16077 16078 synchronized (mPackages) { 16079 return mSettings.getVerifierDeviceIdentityLPw(); 16080 } 16081 } 16082 16083 @Override 16084 public void setPermissionEnforced(String permission, boolean enforced) { 16085 // TODO: Now that we no longer change GID for storage, this should to away. 16086 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16087 "setPermissionEnforced"); 16088 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16089 synchronized (mPackages) { 16090 if (mSettings.mReadExternalStorageEnforced == null 16091 || mSettings.mReadExternalStorageEnforced != enforced) { 16092 mSettings.mReadExternalStorageEnforced = enforced; 16093 mSettings.writeLPr(); 16094 } 16095 } 16096 // kill any non-foreground processes so we restart them and 16097 // grant/revoke the GID. 16098 final IActivityManager am = ActivityManagerNative.getDefault(); 16099 if (am != null) { 16100 final long token = Binder.clearCallingIdentity(); 16101 try { 16102 am.killProcessesBelowForeground("setPermissionEnforcement"); 16103 } catch (RemoteException e) { 16104 } finally { 16105 Binder.restoreCallingIdentity(token); 16106 } 16107 } 16108 } else { 16109 throw new IllegalArgumentException("No selective enforcement for " + permission); 16110 } 16111 } 16112 16113 @Override 16114 @Deprecated 16115 public boolean isPermissionEnforced(String permission) { 16116 return true; 16117 } 16118 16119 @Override 16120 public boolean isStorageLow() { 16121 final long token = Binder.clearCallingIdentity(); 16122 try { 16123 final DeviceStorageMonitorInternal 16124 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16125 if (dsm != null) { 16126 return dsm.isMemoryLow(); 16127 } else { 16128 return false; 16129 } 16130 } finally { 16131 Binder.restoreCallingIdentity(token); 16132 } 16133 } 16134 16135 @Override 16136 public IPackageInstaller getPackageInstaller() { 16137 return mInstallerService; 16138 } 16139 16140 private boolean userNeedsBadging(int userId) { 16141 int index = mUserNeedsBadging.indexOfKey(userId); 16142 if (index < 0) { 16143 final UserInfo userInfo; 16144 final long token = Binder.clearCallingIdentity(); 16145 try { 16146 userInfo = sUserManager.getUserInfo(userId); 16147 } finally { 16148 Binder.restoreCallingIdentity(token); 16149 } 16150 final boolean b; 16151 if (userInfo != null && userInfo.isManagedProfile()) { 16152 b = true; 16153 } else { 16154 b = false; 16155 } 16156 mUserNeedsBadging.put(userId, b); 16157 return b; 16158 } 16159 return mUserNeedsBadging.valueAt(index); 16160 } 16161 16162 @Override 16163 public KeySet getKeySetByAlias(String packageName, String alias) { 16164 if (packageName == null || alias == null) { 16165 return null; 16166 } 16167 synchronized(mPackages) { 16168 final PackageParser.Package pkg = mPackages.get(packageName); 16169 if (pkg == null) { 16170 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16171 throw new IllegalArgumentException("Unknown package: " + packageName); 16172 } 16173 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16174 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16175 } 16176 } 16177 16178 @Override 16179 public KeySet getSigningKeySet(String packageName) { 16180 if (packageName == null) { 16181 return null; 16182 } 16183 synchronized(mPackages) { 16184 final PackageParser.Package pkg = mPackages.get(packageName); 16185 if (pkg == null) { 16186 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16187 throw new IllegalArgumentException("Unknown package: " + packageName); 16188 } 16189 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16190 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16191 throw new SecurityException("May not access signing KeySet of other apps."); 16192 } 16193 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16194 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16195 } 16196 } 16197 16198 @Override 16199 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16200 if (packageName == null || ks == null) { 16201 return false; 16202 } 16203 synchronized(mPackages) { 16204 final PackageParser.Package pkg = mPackages.get(packageName); 16205 if (pkg == null) { 16206 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16207 throw new IllegalArgumentException("Unknown package: " + packageName); 16208 } 16209 IBinder ksh = ks.getToken(); 16210 if (ksh instanceof KeySetHandle) { 16211 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16212 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16213 } 16214 return false; 16215 } 16216 } 16217 16218 @Override 16219 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16220 if (packageName == null || ks == null) { 16221 return false; 16222 } 16223 synchronized(mPackages) { 16224 final PackageParser.Package pkg = mPackages.get(packageName); 16225 if (pkg == null) { 16226 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16227 throw new IllegalArgumentException("Unknown package: " + packageName); 16228 } 16229 IBinder ksh = ks.getToken(); 16230 if (ksh instanceof KeySetHandle) { 16231 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16232 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16233 } 16234 return false; 16235 } 16236 } 16237 16238 public void getUsageStatsIfNoPackageUsageInfo() { 16239 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16240 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16241 if (usm == null) { 16242 throw new IllegalStateException("UsageStatsManager must be initialized"); 16243 } 16244 long now = System.currentTimeMillis(); 16245 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16246 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16247 String packageName = entry.getKey(); 16248 PackageParser.Package pkg = mPackages.get(packageName); 16249 if (pkg == null) { 16250 continue; 16251 } 16252 UsageStats usage = entry.getValue(); 16253 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16254 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16255 } 16256 } 16257 } 16258 16259 /** 16260 * Check and throw if the given before/after packages would be considered a 16261 * downgrade. 16262 */ 16263 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16264 throws PackageManagerException { 16265 if (after.versionCode < before.mVersionCode) { 16266 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16267 "Update version code " + after.versionCode + " is older than current " 16268 + before.mVersionCode); 16269 } else if (after.versionCode == before.mVersionCode) { 16270 if (after.baseRevisionCode < before.baseRevisionCode) { 16271 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16272 "Update base revision code " + after.baseRevisionCode 16273 + " is older than current " + before.baseRevisionCode); 16274 } 16275 16276 if (!ArrayUtils.isEmpty(after.splitNames)) { 16277 for (int i = 0; i < after.splitNames.length; i++) { 16278 final String splitName = after.splitNames[i]; 16279 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16280 if (j != -1) { 16281 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16282 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16283 "Update split " + splitName + " revision code " 16284 + after.splitRevisionCodes[i] + " is older than current " 16285 + before.splitRevisionCodes[j]); 16286 } 16287 } 16288 } 16289 } 16290 } 16291 } 16292 16293 private static class MoveCallbacks extends Handler { 16294 private static final int MSG_CREATED = 1; 16295 private static final int MSG_STATUS_CHANGED = 2; 16296 16297 private final RemoteCallbackList<IPackageMoveObserver> 16298 mCallbacks = new RemoteCallbackList<>(); 16299 16300 private final SparseIntArray mLastStatus = new SparseIntArray(); 16301 16302 public MoveCallbacks(Looper looper) { 16303 super(looper); 16304 } 16305 16306 public void register(IPackageMoveObserver callback) { 16307 mCallbacks.register(callback); 16308 } 16309 16310 public void unregister(IPackageMoveObserver callback) { 16311 mCallbacks.unregister(callback); 16312 } 16313 16314 @Override 16315 public void handleMessage(Message msg) { 16316 final SomeArgs args = (SomeArgs) msg.obj; 16317 final int n = mCallbacks.beginBroadcast(); 16318 for (int i = 0; i < n; i++) { 16319 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16320 try { 16321 invokeCallback(callback, msg.what, args); 16322 } catch (RemoteException ignored) { 16323 } 16324 } 16325 mCallbacks.finishBroadcast(); 16326 args.recycle(); 16327 } 16328 16329 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16330 throws RemoteException { 16331 switch (what) { 16332 case MSG_CREATED: { 16333 callback.onCreated(args.argi1, (Bundle) args.arg2); 16334 break; 16335 } 16336 case MSG_STATUS_CHANGED: { 16337 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16338 break; 16339 } 16340 } 16341 } 16342 16343 private void notifyCreated(int moveId, Bundle extras) { 16344 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16345 16346 final SomeArgs args = SomeArgs.obtain(); 16347 args.argi1 = moveId; 16348 args.arg2 = extras; 16349 obtainMessage(MSG_CREATED, args).sendToTarget(); 16350 } 16351 16352 private void notifyStatusChanged(int moveId, int status) { 16353 notifyStatusChanged(moveId, status, -1); 16354 } 16355 16356 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16357 Slog.v(TAG, "Move " + moveId + " status " + status); 16358 16359 final SomeArgs args = SomeArgs.obtain(); 16360 args.argi1 = moveId; 16361 args.argi2 = status; 16362 args.arg3 = estMillis; 16363 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16364 16365 synchronized (mLastStatus) { 16366 mLastStatus.put(moveId, status); 16367 } 16368 } 16369 } 16370 16371 private final class OnPermissionChangeListeners extends Handler { 16372 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16373 16374 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16375 new RemoteCallbackList<>(); 16376 16377 public OnPermissionChangeListeners(Looper looper) { 16378 super(looper); 16379 } 16380 16381 @Override 16382 public void handleMessage(Message msg) { 16383 switch (msg.what) { 16384 case MSG_ON_PERMISSIONS_CHANGED: { 16385 final int uid = msg.arg1; 16386 handleOnPermissionsChanged(uid); 16387 } break; 16388 } 16389 } 16390 16391 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16392 mPermissionListeners.register(listener); 16393 16394 } 16395 16396 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16397 mPermissionListeners.unregister(listener); 16398 } 16399 16400 public void onPermissionsChanged(int uid) { 16401 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16402 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16403 } 16404 } 16405 16406 private void handleOnPermissionsChanged(int uid) { 16407 final int count = mPermissionListeners.beginBroadcast(); 16408 try { 16409 for (int i = 0; i < count; i++) { 16410 IOnPermissionsChangeListener callback = mPermissionListeners 16411 .getBroadcastItem(i); 16412 try { 16413 callback.onPermissionsChanged(uid); 16414 } catch (RemoteException e) { 16415 Log.e(TAG, "Permission listener is dead", e); 16416 } 16417 } 16418 } finally { 16419 mPermissionListeners.finishBroadcast(); 16420 } 16421 } 16422 } 16423 16424 private class PackageManagerInternalImpl extends PackageManagerInternal { 16425 @Override 16426 public void setLocationPackagesProvider(PackagesProvider provider) { 16427 synchronized (mPackages) { 16428 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16429 } 16430 } 16431 16432 @Override 16433 public void setImePackagesProvider(PackagesProvider provider) { 16434 synchronized (mPackages) { 16435 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16436 } 16437 } 16438 16439 @Override 16440 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16441 synchronized (mPackages) { 16442 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16443 } 16444 } 16445 16446 @Override 16447 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16448 synchronized (mPackages) { 16449 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16450 } 16451 } 16452 16453 @Override 16454 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16455 synchronized (mPackages) { 16456 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16457 } 16458 } 16459 16460 @Override 16461 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16462 synchronized (mPackages) { 16463 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16464 } 16465 } 16466 16467 @Override 16468 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16469 synchronized (mPackages) { 16470 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16471 packageName, userId); 16472 } 16473 } 16474 16475 @Override 16476 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16477 synchronized (mPackages) { 16478 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16479 packageName, userId); 16480 } 16481 } 16482 } 16483 16484 @Override 16485 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16486 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16487 synchronized (mPackages) { 16488 final long identity = Binder.clearCallingIdentity(); 16489 try { 16490 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16491 packageNames, userId); 16492 } finally { 16493 Binder.restoreCallingIdentity(identity); 16494 } 16495 } 16496 } 16497 16498 private static void enforceSystemOrPhoneCaller(String tag) { 16499 int callingUid = Binder.getCallingUid(); 16500 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16501 throw new SecurityException( 16502 "Cannot call " + tag + " from UID " + callingUid); 16503 } 16504 } 16505} 16506