PackageManagerService.java revision a0bfc2063533d4b93435a49c9e19e54989c3459a
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.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 22import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 85 86import android.Manifest; 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IOnPermissionsChangeListener; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.IntentFilterVerificationInfo; 118import android.content.pm.KeySet; 119import android.content.pm.ManifestDigest; 120import android.content.pm.PackageCleanItem; 121import android.content.pm.PackageInfo; 122import android.content.pm.PackageInfoLite; 123import android.content.pm.PackageInstaller; 124import android.content.pm.PackageManager; 125import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 126import android.content.pm.PackageManagerInternal; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageStats; 132import android.content.pm.PackageUserState; 133import android.content.pm.ParceledListSlice; 134import android.content.pm.PermissionGroupInfo; 135import android.content.pm.PermissionInfo; 136import android.content.pm.ProviderInfo; 137import android.content.pm.ResolveInfo; 138import android.content.pm.ServiceInfo; 139import android.content.pm.Signature; 140import android.content.pm.UserInfo; 141import android.content.pm.VerificationParams; 142import android.content.pm.VerifierDeviceIdentity; 143import android.content.pm.VerifierInfo; 144import android.content.res.Resources; 145import android.hardware.display.DisplayManager; 146import android.net.Uri; 147import android.os.Debug; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteCallbackList; 162import android.os.RemoteException; 163import android.os.SELinux; 164import android.os.ServiceManager; 165import android.os.SystemClock; 166import android.os.SystemProperties; 167import android.os.UserHandle; 168import android.os.UserManager; 169import android.os.storage.IMountService; 170import android.os.storage.MountServiceInternal; 171import android.os.storage.StorageEventListener; 172import android.os.storage.StorageManager; 173import android.os.storage.VolumeInfo; 174import android.os.storage.VolumeRecord; 175import android.security.KeyStore; 176import android.security.SystemKeyStore; 177import android.system.ErrnoException; 178import android.system.Os; 179import android.system.StructStat; 180import android.text.TextUtils; 181import android.text.format.DateUtils; 182import android.util.ArrayMap; 183import android.util.ArraySet; 184import android.util.AtomicFile; 185import android.util.DisplayMetrics; 186import android.util.EventLog; 187import android.util.ExceptionUtils; 188import android.util.Log; 189import android.util.LogPrinter; 190import android.util.MathUtils; 191import android.util.PrintStreamPrinter; 192import android.util.Slog; 193import android.util.SparseArray; 194import android.util.SparseBooleanArray; 195import android.util.SparseIntArray; 196import android.util.Xml; 197import android.view.Display; 198 199import dalvik.system.DexFile; 200import dalvik.system.VMRuntime; 201 202import libcore.io.IoUtils; 203import libcore.util.EmptyArray; 204 205import com.android.internal.R; 206import com.android.internal.annotations.GuardedBy; 207import com.android.internal.app.IMediaContainerService; 208import com.android.internal.app.ResolverActivity; 209import com.android.internal.content.NativeLibraryHelper; 210import com.android.internal.content.PackageHelper; 211import com.android.internal.os.IParcelFileDescriptorFactory; 212import com.android.internal.os.SomeArgs; 213import com.android.internal.os.Zygote; 214import com.android.internal.util.ArrayUtils; 215import com.android.internal.util.FastPrintWriter; 216import com.android.internal.util.FastXmlSerializer; 217import com.android.internal.util.IndentingPrintWriter; 218import com.android.internal.util.Preconditions; 219import com.android.server.EventLogTags; 220import com.android.server.FgThread; 221import com.android.server.IntentResolver; 222import com.android.server.LocalServices; 223import com.android.server.ServiceThread; 224import com.android.server.SystemConfig; 225import com.android.server.Watchdog; 226import com.android.server.pm.PermissionsState.PermissionState; 227import com.android.server.pm.Settings.DatabaseVersion; 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, 1341 args.user.getIdentifier()); 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 // Remove any apps installed on the forgotten volume 1657 synchronized (mPackages) { 1658 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1659 for (PackageSetting ps : packages) { 1660 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1661 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1662 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1663 } 1664 1665 mSettings.writeLPr(); 1666 } 1667 } 1668 }; 1669 1670 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1671 if (userId >= UserHandle.USER_OWNER) { 1672 grantRequestedRuntimePermissionsForUser(pkg, userId); 1673 } else if (userId == UserHandle.USER_ALL) { 1674 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1675 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1676 } 1677 } 1678 1679 // We could have touched GID membership, so flush out packages.list 1680 synchronized (mPackages) { 1681 mSettings.writePackageListLPr(); 1682 } 1683 } 1684 1685 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1686 SettingBase sb = (SettingBase) pkg.mExtras; 1687 if (sb == null) { 1688 return; 1689 } 1690 1691 PermissionsState permissionsState = sb.getPermissionsState(); 1692 1693 for (String permission : pkg.requestedPermissions) { 1694 BasePermission bp = mSettings.mPermissions.get(permission); 1695 if (bp != null && bp.isRuntime()) { 1696 permissionsState.grantRuntimePermission(bp, userId); 1697 } 1698 } 1699 } 1700 1701 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1702 Bundle extras = null; 1703 switch (res.returnCode) { 1704 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1705 extras = new Bundle(); 1706 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1707 res.origPermission); 1708 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1709 res.origPackage); 1710 break; 1711 } 1712 case PackageManager.INSTALL_SUCCEEDED: { 1713 extras = new Bundle(); 1714 extras.putBoolean(Intent.EXTRA_REPLACING, 1715 res.removedInfo != null && res.removedInfo.removedPackage != null); 1716 break; 1717 } 1718 } 1719 return extras; 1720 } 1721 1722 void scheduleWriteSettingsLocked() { 1723 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1724 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1725 } 1726 } 1727 1728 void scheduleWritePackageRestrictionsLocked(int userId) { 1729 if (!sUserManager.exists(userId)) return; 1730 mDirtyUsers.add(userId); 1731 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1732 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1733 } 1734 } 1735 1736 public static PackageManagerService main(Context context, Installer installer, 1737 boolean factoryTest, boolean onlyCore) { 1738 PackageManagerService m = new PackageManagerService(context, installer, 1739 factoryTest, onlyCore); 1740 ServiceManager.addService("package", m); 1741 return m; 1742 } 1743 1744 static String[] splitString(String str, char sep) { 1745 int count = 1; 1746 int i = 0; 1747 while ((i=str.indexOf(sep, i)) >= 0) { 1748 count++; 1749 i++; 1750 } 1751 1752 String[] res = new String[count]; 1753 i=0; 1754 count = 0; 1755 int lastI=0; 1756 while ((i=str.indexOf(sep, i)) >= 0) { 1757 res[count] = str.substring(lastI, i); 1758 count++; 1759 i++; 1760 lastI = i; 1761 } 1762 res[count] = str.substring(lastI, str.length()); 1763 return res; 1764 } 1765 1766 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1767 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1768 Context.DISPLAY_SERVICE); 1769 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1770 } 1771 1772 public PackageManagerService(Context context, Installer installer, 1773 boolean factoryTest, boolean onlyCore) { 1774 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1775 SystemClock.uptimeMillis()); 1776 1777 if (mSdkVersion <= 0) { 1778 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1779 } 1780 1781 mContext = context; 1782 mFactoryTest = factoryTest; 1783 mOnlyCore = onlyCore; 1784 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1785 mMetrics = new DisplayMetrics(); 1786 mSettings = new Settings(mPackages); 1787 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1788 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1789 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1790 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1791 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1792 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1793 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1794 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1795 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1796 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1797 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1798 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1799 1800 // TODO: add a property to control this? 1801 long dexOptLRUThresholdInMinutes; 1802 if (mLazyDexOpt) { 1803 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1804 } else { 1805 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1806 } 1807 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1808 1809 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1810 if (separateProcesses != null && separateProcesses.length() > 0) { 1811 if ("*".equals(separateProcesses)) { 1812 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1813 mSeparateProcesses = null; 1814 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1815 } else { 1816 mDefParseFlags = 0; 1817 mSeparateProcesses = separateProcesses.split(","); 1818 Slog.w(TAG, "Running with debug.separate_processes: " 1819 + separateProcesses); 1820 } 1821 } else { 1822 mDefParseFlags = 0; 1823 mSeparateProcesses = null; 1824 } 1825 1826 mInstaller = installer; 1827 mPackageDexOptimizer = new PackageDexOptimizer(this); 1828 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1829 1830 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1831 FgThread.get().getLooper()); 1832 1833 getDefaultDisplayMetrics(context, mMetrics); 1834 1835 SystemConfig systemConfig = SystemConfig.getInstance(); 1836 mGlobalGids = systemConfig.getGlobalGids(); 1837 mSystemPermissions = systemConfig.getSystemPermissions(); 1838 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1839 1840 synchronized (mInstallLock) { 1841 // writer 1842 synchronized (mPackages) { 1843 mHandlerThread = new ServiceThread(TAG, 1844 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1845 mHandlerThread.start(); 1846 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1847 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1848 1849 File dataDir = Environment.getDataDirectory(); 1850 mAppDataDir = new File(dataDir, "data"); 1851 mAppInstallDir = new File(dataDir, "app"); 1852 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1853 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1854 mUserAppDataDir = new File(dataDir, "user"); 1855 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1856 1857 sUserManager = new UserManagerService(context, this, 1858 mInstallLock, mPackages); 1859 1860 // Propagate permission configuration in to package manager. 1861 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1862 = systemConfig.getPermissions(); 1863 for (int i=0; i<permConfig.size(); i++) { 1864 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1865 BasePermission bp = mSettings.mPermissions.get(perm.name); 1866 if (bp == null) { 1867 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1868 mSettings.mPermissions.put(perm.name, bp); 1869 } 1870 if (perm.gids != null) { 1871 bp.setGids(perm.gids, perm.perUser); 1872 } 1873 } 1874 1875 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1876 for (int i=0; i<libConfig.size(); i++) { 1877 mSharedLibraries.put(libConfig.keyAt(i), 1878 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1879 } 1880 1881 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1882 1883 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1884 mSdkVersion, mOnlyCore); 1885 1886 String customResolverActivity = Resources.getSystem().getString( 1887 R.string.config_customResolverActivity); 1888 if (TextUtils.isEmpty(customResolverActivity)) { 1889 customResolverActivity = null; 1890 } else { 1891 mCustomResolverComponentName = ComponentName.unflattenFromString( 1892 customResolverActivity); 1893 } 1894 1895 long startTime = SystemClock.uptimeMillis(); 1896 1897 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1898 startTime); 1899 1900 // Set flag to monitor and not change apk file paths when 1901 // scanning install directories. 1902 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1903 1904 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1905 1906 /** 1907 * Add everything in the in the boot class path to the 1908 * list of process files because dexopt will have been run 1909 * if necessary during zygote startup. 1910 */ 1911 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1912 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1913 1914 if (bootClassPath != null) { 1915 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1916 for (String element : bootClassPathElements) { 1917 alreadyDexOpted.add(element); 1918 } 1919 } else { 1920 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1921 } 1922 1923 if (systemServerClassPath != null) { 1924 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1925 for (String element : systemServerClassPathElements) { 1926 alreadyDexOpted.add(element); 1927 } 1928 } else { 1929 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1930 } 1931 1932 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1933 final String[] dexCodeInstructionSets = 1934 getDexCodeInstructionSets( 1935 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1936 1937 /** 1938 * Ensure all external libraries have had dexopt run on them. 1939 */ 1940 if (mSharedLibraries.size() > 0) { 1941 // NOTE: For now, we're compiling these system "shared libraries" 1942 // (and framework jars) into all available architectures. It's possible 1943 // to compile them only when we come across an app that uses them (there's 1944 // already logic for that in scanPackageLI) but that adds some complexity. 1945 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1946 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1947 final String lib = libEntry.path; 1948 if (lib == null) { 1949 continue; 1950 } 1951 1952 try { 1953 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1954 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1955 alreadyDexOpted.add(lib); 1956 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1957 } 1958 } catch (FileNotFoundException e) { 1959 Slog.w(TAG, "Library not found: " + lib); 1960 } catch (IOException e) { 1961 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1962 + e.getMessage()); 1963 } 1964 } 1965 } 1966 } 1967 1968 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1969 1970 // Gross hack for now: we know this file doesn't contain any 1971 // code, so don't dexopt it to avoid the resulting log spew. 1972 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1973 1974 // Gross hack for now: we know this file is only part of 1975 // the boot class path for art, so don't dexopt it to 1976 // avoid the resulting log spew. 1977 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1978 1979 /** 1980 * There are a number of commands implemented in Java, which 1981 * we currently need to do the dexopt on so that they can be 1982 * run from a non-root shell. 1983 */ 1984 String[] frameworkFiles = frameworkDir.list(); 1985 if (frameworkFiles != null) { 1986 // TODO: We could compile these only for the most preferred ABI. We should 1987 // first double check that the dex files for these commands are not referenced 1988 // by other system apps. 1989 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1990 for (int i=0; i<frameworkFiles.length; i++) { 1991 File libPath = new File(frameworkDir, frameworkFiles[i]); 1992 String path = libPath.getPath(); 1993 // Skip the file if we already did it. 1994 if (alreadyDexOpted.contains(path)) { 1995 continue; 1996 } 1997 // Skip the file if it is not a type we want to dexopt. 1998 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1999 continue; 2000 } 2001 try { 2002 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2003 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2004 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2005 } 2006 } catch (FileNotFoundException e) { 2007 Slog.w(TAG, "Jar not found: " + path); 2008 } catch (IOException e) { 2009 Slog.w(TAG, "Exception reading jar: " + path, e); 2010 } 2011 } 2012 } 2013 } 2014 2015 // Collect vendor overlay packages. 2016 // (Do this before scanning any apps.) 2017 // For security and version matching reason, only consider 2018 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2019 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2020 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2021 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2022 2023 // Find base frameworks (resource packages without code). 2024 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2025 | PackageParser.PARSE_IS_SYSTEM_DIR 2026 | PackageParser.PARSE_IS_PRIVILEGED, 2027 scanFlags | SCAN_NO_DEX, 0); 2028 2029 // Collected privileged system packages. 2030 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2031 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2032 | PackageParser.PARSE_IS_SYSTEM_DIR 2033 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2034 2035 // Collect ordinary system packages. 2036 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2037 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2038 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2039 2040 // Collect all vendor packages. 2041 File vendorAppDir = new File("/vendor/app"); 2042 try { 2043 vendorAppDir = vendorAppDir.getCanonicalFile(); 2044 } catch (IOException e) { 2045 // failed to look up canonical path, continue with original one 2046 } 2047 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2048 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2049 2050 // Collect all OEM packages. 2051 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2052 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2053 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2054 2055 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2056 mInstaller.moveFiles(); 2057 2058 // Prune any system packages that no longer exist. 2059 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2060 if (!mOnlyCore) { 2061 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2062 while (psit.hasNext()) { 2063 PackageSetting ps = psit.next(); 2064 2065 /* 2066 * If this is not a system app, it can't be a 2067 * disable system app. 2068 */ 2069 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2070 continue; 2071 } 2072 2073 /* 2074 * If the package is scanned, it's not erased. 2075 */ 2076 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2077 if (scannedPkg != null) { 2078 /* 2079 * If the system app is both scanned and in the 2080 * disabled packages list, then it must have been 2081 * added via OTA. Remove it from the currently 2082 * scanned package so the previously user-installed 2083 * application can be scanned. 2084 */ 2085 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2086 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2087 + ps.name + "; removing system app. Last known codePath=" 2088 + ps.codePathString + ", installStatus=" + ps.installStatus 2089 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2090 + scannedPkg.mVersionCode); 2091 removePackageLI(ps, true); 2092 mExpectingBetter.put(ps.name, ps.codePath); 2093 } 2094 2095 continue; 2096 } 2097 2098 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2099 psit.remove(); 2100 logCriticalInfo(Log.WARN, "System package " + ps.name 2101 + " no longer exists; wiping its data"); 2102 removeDataDirsLI(null, ps.name); 2103 } else { 2104 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2105 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2106 possiblyDeletedUpdatedSystemApps.add(ps.name); 2107 } 2108 } 2109 } 2110 } 2111 2112 //look for any incomplete package installations 2113 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2114 //clean up list 2115 for(int i = 0; i < deletePkgsList.size(); i++) { 2116 //clean up here 2117 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2118 } 2119 //delete tmp files 2120 deleteTempPackageFiles(); 2121 2122 // Remove any shared userIDs that have no associated packages 2123 mSettings.pruneSharedUsersLPw(); 2124 2125 if (!mOnlyCore) { 2126 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2127 SystemClock.uptimeMillis()); 2128 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2129 2130 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2131 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2132 2133 /** 2134 * Remove disable package settings for any updated system 2135 * apps that were removed via an OTA. If they're not a 2136 * previously-updated app, remove them completely. 2137 * Otherwise, just revoke their system-level permissions. 2138 */ 2139 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2140 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2141 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2142 2143 String msg; 2144 if (deletedPkg == null) { 2145 msg = "Updated system package " + deletedAppName 2146 + " no longer exists; wiping its data"; 2147 removeDataDirsLI(null, deletedAppName); 2148 } else { 2149 msg = "Updated system app + " + deletedAppName 2150 + " no longer present; removing system privileges for " 2151 + deletedAppName; 2152 2153 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2154 2155 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2156 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2157 } 2158 logCriticalInfo(Log.WARN, msg); 2159 } 2160 2161 /** 2162 * Make sure all system apps that we expected to appear on 2163 * the userdata partition actually showed up. If they never 2164 * appeared, crawl back and revive the system version. 2165 */ 2166 for (int i = 0; i < mExpectingBetter.size(); i++) { 2167 final String packageName = mExpectingBetter.keyAt(i); 2168 if (!mPackages.containsKey(packageName)) { 2169 final File scanFile = mExpectingBetter.valueAt(i); 2170 2171 logCriticalInfo(Log.WARN, "Expected better " + packageName 2172 + " but never showed up; reverting to system"); 2173 2174 final int reparseFlags; 2175 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2176 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2177 | PackageParser.PARSE_IS_SYSTEM_DIR 2178 | PackageParser.PARSE_IS_PRIVILEGED; 2179 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2180 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2181 | PackageParser.PARSE_IS_SYSTEM_DIR; 2182 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2183 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2184 | PackageParser.PARSE_IS_SYSTEM_DIR; 2185 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2186 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2187 | PackageParser.PARSE_IS_SYSTEM_DIR; 2188 } else { 2189 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2190 continue; 2191 } 2192 2193 mSettings.enableSystemPackageLPw(packageName); 2194 2195 try { 2196 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2197 } catch (PackageManagerException e) { 2198 Slog.e(TAG, "Failed to parse original system package: " 2199 + e.getMessage()); 2200 } 2201 } 2202 } 2203 } 2204 mExpectingBetter.clear(); 2205 2206 // Now that we know all of the shared libraries, update all clients to have 2207 // the correct library paths. 2208 updateAllSharedLibrariesLPw(); 2209 2210 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2211 // NOTE: We ignore potential failures here during a system scan (like 2212 // the rest of the commands above) because there's precious little we 2213 // can do about it. A settings error is reported, though. 2214 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2215 false /* force dexopt */, false /* defer dexopt */); 2216 } 2217 2218 // Now that we know all the packages we are keeping, 2219 // read and update their last usage times. 2220 mPackageUsage.readLP(); 2221 2222 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2223 SystemClock.uptimeMillis()); 2224 Slog.i(TAG, "Time to scan packages: " 2225 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2226 + " seconds"); 2227 2228 // If the platform SDK has changed since the last time we booted, 2229 // we need to re-grant app permission to catch any new ones that 2230 // appear. This is really a hack, and means that apps can in some 2231 // cases get permissions that the user didn't initially explicitly 2232 // allow... it would be nice to have some better way to handle 2233 // this situation. 2234 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2235 != mSdkVersion; 2236 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2237 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2238 + "; regranting permissions for internal storage"); 2239 mSettings.mInternalSdkPlatform = mSdkVersion; 2240 2241 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2242 | (regrantPermissions 2243 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2244 : 0)); 2245 2246 // If this is the first boot, and it is a normal boot, then 2247 // we need to initialize the default preferred apps. 2248 if (!mRestoredSettings && !onlyCore) { 2249 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2250 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2251 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2252 } 2253 2254 // If this is first boot after an OTA, and a normal boot, then 2255 // we need to clear code cache directories. 2256 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2257 if (mIsUpgrade && !onlyCore) { 2258 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2259 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2260 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2261 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2262 } 2263 mSettings.mFingerprint = Build.FINGERPRINT; 2264 } 2265 2266 checkDefaultBrowser(); 2267 2268 // All the changes are done during package scanning. 2269 mSettings.updateInternalDatabaseVersion(); 2270 2271 // can downgrade to reader 2272 mSettings.writeLPr(); 2273 2274 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2275 SystemClock.uptimeMillis()); 2276 2277 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2278 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2279 2280 mInstallerService = new PackageInstallerService(context, this); 2281 2282 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2283 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2284 mIntentFilterVerifierComponent); 2285 2286 } // synchronized (mPackages) 2287 } // synchronized (mInstallLock) 2288 2289 // Now after opening every single application zip, make sure they 2290 // are all flushed. Not really needed, but keeps things nice and 2291 // tidy. 2292 Runtime.getRuntime().gc(); 2293 2294 // Expose private service for system components to use. 2295 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2296 } 2297 2298 @Override 2299 public boolean isFirstBoot() { 2300 return !mRestoredSettings; 2301 } 2302 2303 @Override 2304 public boolean isOnlyCoreApps() { 2305 return mOnlyCore; 2306 } 2307 2308 @Override 2309 public boolean isUpgrade() { 2310 return mIsUpgrade; 2311 } 2312 2313 private String getRequiredVerifierLPr() { 2314 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2315 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2316 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2317 2318 String requiredVerifier = null; 2319 2320 final int N = receivers.size(); 2321 for (int i = 0; i < N; i++) { 2322 final ResolveInfo info = receivers.get(i); 2323 2324 if (info.activityInfo == null) { 2325 continue; 2326 } 2327 2328 final String packageName = info.activityInfo.packageName; 2329 2330 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2331 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2332 continue; 2333 } 2334 2335 if (requiredVerifier != null) { 2336 throw new RuntimeException("There can be only one required verifier"); 2337 } 2338 2339 requiredVerifier = packageName; 2340 } 2341 2342 return requiredVerifier; 2343 } 2344 2345 private String getRequiredInstallerLPr() { 2346 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2347 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2348 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2349 2350 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2351 PACKAGE_MIME_TYPE, 0, 0); 2352 2353 String requiredInstaller = null; 2354 2355 final int N = installers.size(); 2356 for (int i = 0; i < N; i++) { 2357 final ResolveInfo info = installers.get(i); 2358 final String packageName = info.activityInfo.packageName; 2359 2360 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2361 continue; 2362 } 2363 2364 if (requiredInstaller != null) { 2365 throw new RuntimeException("There must be one required installer"); 2366 } 2367 2368 requiredInstaller = packageName; 2369 } 2370 2371 if (requiredInstaller == null) { 2372 throw new RuntimeException("There must be one required installer"); 2373 } 2374 2375 return requiredInstaller; 2376 } 2377 2378 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2379 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2380 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2381 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2382 2383 ComponentName verifierComponentName = null; 2384 2385 int priority = -1000; 2386 final int N = receivers.size(); 2387 for (int i = 0; i < N; i++) { 2388 final ResolveInfo info = receivers.get(i); 2389 2390 if (info.activityInfo == null) { 2391 continue; 2392 } 2393 2394 final String packageName = info.activityInfo.packageName; 2395 2396 final PackageSetting ps = mSettings.mPackages.get(packageName); 2397 if (ps == null) { 2398 continue; 2399 } 2400 2401 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2402 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2403 continue; 2404 } 2405 2406 // Select the IntentFilterVerifier with the highest priority 2407 if (priority < info.priority) { 2408 priority = info.priority; 2409 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2410 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2411 + verifierComponentName + " with priority: " + info.priority); 2412 } 2413 } 2414 2415 return verifierComponentName; 2416 } 2417 2418 private void primeDomainVerificationsLPw(int userId) { 2419 if (DEBUG_DOMAIN_VERIFICATION) { 2420 Slog.d(TAG, "Priming domain verifications in user " + userId); 2421 } 2422 2423 SystemConfig systemConfig = SystemConfig.getInstance(); 2424 ArraySet<String> packages = systemConfig.getLinkedApps(); 2425 ArraySet<String> domains = new ArraySet<String>(); 2426 2427 for (String packageName : packages) { 2428 PackageParser.Package pkg = mPackages.get(packageName); 2429 if (pkg != null) { 2430 if (!pkg.isSystemApp()) { 2431 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2432 continue; 2433 } 2434 2435 domains.clear(); 2436 for (PackageParser.Activity a : pkg.activities) { 2437 for (ActivityIntentInfo filter : a.intents) { 2438 if (hasValidDomains(filter)) { 2439 domains.addAll(filter.getHostsList()); 2440 } 2441 } 2442 } 2443 2444 if (domains.size() > 0) { 2445 if (DEBUG_DOMAIN_VERIFICATION) { 2446 Slog.v(TAG, " + " + packageName); 2447 } 2448 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2449 // state w.r.t. the formal app-linkage "no verification attempted" state; 2450 // and then 'always' in the per-user state actually used for intent resolution. 2451 final IntentFilterVerificationInfo ivi; 2452 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2453 new ArrayList<String>(domains)); 2454 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2455 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2456 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2457 } else { 2458 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2459 + "' does not handle web links"); 2460 } 2461 } else { 2462 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2463 } 2464 } 2465 2466 scheduleWritePackageRestrictionsLocked(userId); 2467 scheduleWriteSettingsLocked(); 2468 } 2469 2470 private void applyFactoryDefaultBrowserLPw(int userId) { 2471 // The default browser app's package name is stored in a string resource, 2472 // with a product-specific overlay used for vendor customization. 2473 String browserPkg = mContext.getResources().getString( 2474 com.android.internal.R.string.default_browser); 2475 if (!TextUtils.isEmpty(browserPkg)) { 2476 // non-empty string => required to be a known package 2477 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2478 if (ps == null) { 2479 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2480 browserPkg = null; 2481 } else { 2482 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2483 } 2484 } 2485 2486 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2487 // default. If there's more than one, just leave everything alone. 2488 if (browserPkg == null) { 2489 calculateDefaultBrowserLPw(userId); 2490 } 2491 } 2492 2493 private void calculateDefaultBrowserLPw(int userId) { 2494 List<String> allBrowsers = resolveAllBrowserApps(userId); 2495 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2496 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2497 } 2498 2499 private List<String> resolveAllBrowserApps(int userId) { 2500 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2501 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2502 PackageManager.MATCH_ALL, userId); 2503 2504 final int count = list.size(); 2505 List<String> result = new ArrayList<String>(count); 2506 for (int i=0; i<count; i++) { 2507 ResolveInfo info = list.get(i); 2508 if (info.activityInfo == null 2509 || !info.handleAllWebDataURI 2510 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2511 || result.contains(info.activityInfo.packageName)) { 2512 continue; 2513 } 2514 result.add(info.activityInfo.packageName); 2515 } 2516 2517 return result; 2518 } 2519 2520 private boolean packageIsBrowser(String packageName, int userId) { 2521 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2522 PackageManager.MATCH_ALL, userId); 2523 final int N = list.size(); 2524 for (int i = 0; i < N; i++) { 2525 ResolveInfo info = list.get(i); 2526 if (packageName.equals(info.activityInfo.packageName)) { 2527 return true; 2528 } 2529 } 2530 return false; 2531 } 2532 2533 private void checkDefaultBrowser() { 2534 final int myUserId = UserHandle.myUserId(); 2535 final String packageName = getDefaultBrowserPackageName(myUserId); 2536 if (packageName != null) { 2537 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2538 if (info == null) { 2539 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2540 synchronized (mPackages) { 2541 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2542 } 2543 } 2544 } 2545 } 2546 2547 @Override 2548 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2549 throws RemoteException { 2550 try { 2551 return super.onTransact(code, data, reply, flags); 2552 } catch (RuntimeException e) { 2553 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2554 Slog.wtf(TAG, "Package Manager Crash", e); 2555 } 2556 throw e; 2557 } 2558 } 2559 2560 void cleanupInstallFailedPackage(PackageSetting ps) { 2561 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2562 2563 removeDataDirsLI(ps.volumeUuid, ps.name); 2564 if (ps.codePath != null) { 2565 if (ps.codePath.isDirectory()) { 2566 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2567 } else { 2568 ps.codePath.delete(); 2569 } 2570 } 2571 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2572 if (ps.resourcePath.isDirectory()) { 2573 FileUtils.deleteContents(ps.resourcePath); 2574 } 2575 ps.resourcePath.delete(); 2576 } 2577 mSettings.removePackageLPw(ps.name); 2578 } 2579 2580 static int[] appendInts(int[] cur, int[] add) { 2581 if (add == null) return cur; 2582 if (cur == null) return add; 2583 final int N = add.length; 2584 for (int i=0; i<N; i++) { 2585 cur = appendInt(cur, add[i]); 2586 } 2587 return cur; 2588 } 2589 2590 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2591 if (!sUserManager.exists(userId)) return null; 2592 final PackageSetting ps = (PackageSetting) p.mExtras; 2593 if (ps == null) { 2594 return null; 2595 } 2596 2597 final PermissionsState permissionsState = ps.getPermissionsState(); 2598 2599 final int[] gids = permissionsState.computeGids(userId); 2600 final Set<String> permissions = permissionsState.getPermissions(userId); 2601 final PackageUserState state = ps.readUserState(userId); 2602 2603 return PackageParser.generatePackageInfo(p, gids, flags, 2604 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2605 } 2606 2607 @Override 2608 public boolean isPackageFrozen(String packageName) { 2609 synchronized (mPackages) { 2610 final PackageSetting ps = mSettings.mPackages.get(packageName); 2611 if (ps != null) { 2612 return ps.frozen; 2613 } 2614 } 2615 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2616 return true; 2617 } 2618 2619 @Override 2620 public boolean isPackageAvailable(String packageName, int userId) { 2621 if (!sUserManager.exists(userId)) return false; 2622 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2623 synchronized (mPackages) { 2624 PackageParser.Package p = mPackages.get(packageName); 2625 if (p != null) { 2626 final PackageSetting ps = (PackageSetting) p.mExtras; 2627 if (ps != null) { 2628 final PackageUserState state = ps.readUserState(userId); 2629 if (state != null) { 2630 return PackageParser.isAvailable(state); 2631 } 2632 } 2633 } 2634 } 2635 return false; 2636 } 2637 2638 @Override 2639 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2640 if (!sUserManager.exists(userId)) return null; 2641 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2642 // reader 2643 synchronized (mPackages) { 2644 PackageParser.Package p = mPackages.get(packageName); 2645 if (DEBUG_PACKAGE_INFO) 2646 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2647 if (p != null) { 2648 return generatePackageInfo(p, flags, userId); 2649 } 2650 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2651 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2652 } 2653 } 2654 return null; 2655 } 2656 2657 @Override 2658 public String[] currentToCanonicalPackageNames(String[] names) { 2659 String[] out = new String[names.length]; 2660 // reader 2661 synchronized (mPackages) { 2662 for (int i=names.length-1; i>=0; i--) { 2663 PackageSetting ps = mSettings.mPackages.get(names[i]); 2664 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2665 } 2666 } 2667 return out; 2668 } 2669 2670 @Override 2671 public String[] canonicalToCurrentPackageNames(String[] names) { 2672 String[] out = new String[names.length]; 2673 // reader 2674 synchronized (mPackages) { 2675 for (int i=names.length-1; i>=0; i--) { 2676 String cur = mSettings.mRenamedPackages.get(names[i]); 2677 out[i] = cur != null ? cur : names[i]; 2678 } 2679 } 2680 return out; 2681 } 2682 2683 @Override 2684 public int getPackageUid(String packageName, int userId) { 2685 if (!sUserManager.exists(userId)) return -1; 2686 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2687 2688 // reader 2689 synchronized (mPackages) { 2690 PackageParser.Package p = mPackages.get(packageName); 2691 if(p != null) { 2692 return UserHandle.getUid(userId, p.applicationInfo.uid); 2693 } 2694 PackageSetting ps = mSettings.mPackages.get(packageName); 2695 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2696 return -1; 2697 } 2698 p = ps.pkg; 2699 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2700 } 2701 } 2702 2703 @Override 2704 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2705 if (!sUserManager.exists(userId)) { 2706 return null; 2707 } 2708 2709 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2710 "getPackageGids"); 2711 2712 // reader 2713 synchronized (mPackages) { 2714 PackageParser.Package p = mPackages.get(packageName); 2715 if (DEBUG_PACKAGE_INFO) { 2716 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2717 } 2718 if (p != null) { 2719 PackageSetting ps = (PackageSetting) p.mExtras; 2720 return ps.getPermissionsState().computeGids(userId); 2721 } 2722 } 2723 2724 return null; 2725 } 2726 2727 static PermissionInfo generatePermissionInfo( 2728 BasePermission bp, int flags) { 2729 if (bp.perm != null) { 2730 return PackageParser.generatePermissionInfo(bp.perm, flags); 2731 } 2732 PermissionInfo pi = new PermissionInfo(); 2733 pi.name = bp.name; 2734 pi.packageName = bp.sourcePackage; 2735 pi.nonLocalizedLabel = bp.name; 2736 pi.protectionLevel = bp.protectionLevel; 2737 return pi; 2738 } 2739 2740 @Override 2741 public PermissionInfo getPermissionInfo(String name, int flags) { 2742 // reader 2743 synchronized (mPackages) { 2744 final BasePermission p = mSettings.mPermissions.get(name); 2745 if (p != null) { 2746 return generatePermissionInfo(p, flags); 2747 } 2748 return null; 2749 } 2750 } 2751 2752 @Override 2753 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2754 // reader 2755 synchronized (mPackages) { 2756 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2757 for (BasePermission p : mSettings.mPermissions.values()) { 2758 if (group == null) { 2759 if (p.perm == null || p.perm.info.group == null) { 2760 out.add(generatePermissionInfo(p, flags)); 2761 } 2762 } else { 2763 if (p.perm != null && group.equals(p.perm.info.group)) { 2764 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2765 } 2766 } 2767 } 2768 2769 if (out.size() > 0) { 2770 return out; 2771 } 2772 return mPermissionGroups.containsKey(group) ? out : null; 2773 } 2774 } 2775 2776 @Override 2777 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2778 // reader 2779 synchronized (mPackages) { 2780 return PackageParser.generatePermissionGroupInfo( 2781 mPermissionGroups.get(name), flags); 2782 } 2783 } 2784 2785 @Override 2786 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2787 // reader 2788 synchronized (mPackages) { 2789 final int N = mPermissionGroups.size(); 2790 ArrayList<PermissionGroupInfo> out 2791 = new ArrayList<PermissionGroupInfo>(N); 2792 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2793 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2794 } 2795 return out; 2796 } 2797 } 2798 2799 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2800 int userId) { 2801 if (!sUserManager.exists(userId)) return null; 2802 PackageSetting ps = mSettings.mPackages.get(packageName); 2803 if (ps != null) { 2804 if (ps.pkg == null) { 2805 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2806 flags, userId); 2807 if (pInfo != null) { 2808 return pInfo.applicationInfo; 2809 } 2810 return null; 2811 } 2812 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2813 ps.readUserState(userId), userId); 2814 } 2815 return null; 2816 } 2817 2818 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2819 int userId) { 2820 if (!sUserManager.exists(userId)) return null; 2821 PackageSetting ps = mSettings.mPackages.get(packageName); 2822 if (ps != null) { 2823 PackageParser.Package pkg = ps.pkg; 2824 if (pkg == null) { 2825 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2826 return null; 2827 } 2828 // Only data remains, so we aren't worried about code paths 2829 pkg = new PackageParser.Package(packageName); 2830 pkg.applicationInfo.packageName = packageName; 2831 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2832 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2833 pkg.applicationInfo.dataDir = Environment 2834 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2835 .getAbsolutePath(); 2836 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2837 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2838 } 2839 return generatePackageInfo(pkg, flags, userId); 2840 } 2841 return null; 2842 } 2843 2844 @Override 2845 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2846 if (!sUserManager.exists(userId)) return null; 2847 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2848 // writer 2849 synchronized (mPackages) { 2850 PackageParser.Package p = mPackages.get(packageName); 2851 if (DEBUG_PACKAGE_INFO) Log.v( 2852 TAG, "getApplicationInfo " + packageName 2853 + ": " + p); 2854 if (p != null) { 2855 PackageSetting ps = mSettings.mPackages.get(packageName); 2856 if (ps == null) return null; 2857 // Note: isEnabledLP() does not apply here - always return info 2858 return PackageParser.generateApplicationInfo( 2859 p, flags, ps.readUserState(userId), userId); 2860 } 2861 if ("android".equals(packageName)||"system".equals(packageName)) { 2862 return mAndroidApplication; 2863 } 2864 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2865 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2866 } 2867 } 2868 return null; 2869 } 2870 2871 @Override 2872 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2873 final IPackageDataObserver observer) { 2874 mContext.enforceCallingOrSelfPermission( 2875 android.Manifest.permission.CLEAR_APP_CACHE, null); 2876 // Queue up an async operation since clearing cache may take a little while. 2877 mHandler.post(new Runnable() { 2878 public void run() { 2879 mHandler.removeCallbacks(this); 2880 int retCode = -1; 2881 synchronized (mInstallLock) { 2882 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2883 if (retCode < 0) { 2884 Slog.w(TAG, "Couldn't clear application caches"); 2885 } 2886 } 2887 if (observer != null) { 2888 try { 2889 observer.onRemoveCompleted(null, (retCode >= 0)); 2890 } catch (RemoteException e) { 2891 Slog.w(TAG, "RemoveException when invoking call back"); 2892 } 2893 } 2894 } 2895 }); 2896 } 2897 2898 @Override 2899 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2900 final IntentSender pi) { 2901 mContext.enforceCallingOrSelfPermission( 2902 android.Manifest.permission.CLEAR_APP_CACHE, null); 2903 // Queue up an async operation since clearing cache may take a little while. 2904 mHandler.post(new Runnable() { 2905 public void run() { 2906 mHandler.removeCallbacks(this); 2907 int retCode = -1; 2908 synchronized (mInstallLock) { 2909 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2910 if (retCode < 0) { 2911 Slog.w(TAG, "Couldn't clear application caches"); 2912 } 2913 } 2914 if(pi != null) { 2915 try { 2916 // Callback via pending intent 2917 int code = (retCode >= 0) ? 1 : 0; 2918 pi.sendIntent(null, code, null, 2919 null, null); 2920 } catch (SendIntentException e1) { 2921 Slog.i(TAG, "Failed to send pending intent"); 2922 } 2923 } 2924 } 2925 }); 2926 } 2927 2928 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2929 synchronized (mInstallLock) { 2930 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2931 throw new IOException("Failed to free enough space"); 2932 } 2933 } 2934 } 2935 2936 @Override 2937 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2938 if (!sUserManager.exists(userId)) return null; 2939 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2940 synchronized (mPackages) { 2941 PackageParser.Activity a = mActivities.mActivities.get(component); 2942 2943 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2944 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2945 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2946 if (ps == null) return null; 2947 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2948 userId); 2949 } 2950 if (mResolveComponentName.equals(component)) { 2951 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2952 new PackageUserState(), userId); 2953 } 2954 } 2955 return null; 2956 } 2957 2958 @Override 2959 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2960 String resolvedType) { 2961 synchronized (mPackages) { 2962 PackageParser.Activity a = mActivities.mActivities.get(component); 2963 if (a == null) { 2964 return false; 2965 } 2966 for (int i=0; i<a.intents.size(); i++) { 2967 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2968 intent.getData(), intent.getCategories(), TAG) >= 0) { 2969 return true; 2970 } 2971 } 2972 return false; 2973 } 2974 } 2975 2976 @Override 2977 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2978 if (!sUserManager.exists(userId)) return null; 2979 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2980 synchronized (mPackages) { 2981 PackageParser.Activity a = mReceivers.mActivities.get(component); 2982 if (DEBUG_PACKAGE_INFO) Log.v( 2983 TAG, "getReceiverInfo " + component + ": " + a); 2984 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2985 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2986 if (ps == null) return null; 2987 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2988 userId); 2989 } 2990 } 2991 return null; 2992 } 2993 2994 @Override 2995 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2996 if (!sUserManager.exists(userId)) return null; 2997 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2998 synchronized (mPackages) { 2999 PackageParser.Service s = mServices.mServices.get(component); 3000 if (DEBUG_PACKAGE_INFO) Log.v( 3001 TAG, "getServiceInfo " + component + ": " + s); 3002 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3003 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3004 if (ps == null) return null; 3005 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3006 userId); 3007 } 3008 } 3009 return null; 3010 } 3011 3012 @Override 3013 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3014 if (!sUserManager.exists(userId)) return null; 3015 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3016 synchronized (mPackages) { 3017 PackageParser.Provider p = mProviders.mProviders.get(component); 3018 if (DEBUG_PACKAGE_INFO) Log.v( 3019 TAG, "getProviderInfo " + component + ": " + p); 3020 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3021 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3022 if (ps == null) return null; 3023 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3024 userId); 3025 } 3026 } 3027 return null; 3028 } 3029 3030 @Override 3031 public String[] getSystemSharedLibraryNames() { 3032 Set<String> libSet; 3033 synchronized (mPackages) { 3034 libSet = mSharedLibraries.keySet(); 3035 int size = libSet.size(); 3036 if (size > 0) { 3037 String[] libs = new String[size]; 3038 libSet.toArray(libs); 3039 return libs; 3040 } 3041 } 3042 return null; 3043 } 3044 3045 /** 3046 * @hide 3047 */ 3048 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3049 synchronized (mPackages) { 3050 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3051 if (lib != null && lib.apk != null) { 3052 return mPackages.get(lib.apk); 3053 } 3054 } 3055 return null; 3056 } 3057 3058 @Override 3059 public FeatureInfo[] getSystemAvailableFeatures() { 3060 Collection<FeatureInfo> featSet; 3061 synchronized (mPackages) { 3062 featSet = mAvailableFeatures.values(); 3063 int size = featSet.size(); 3064 if (size > 0) { 3065 FeatureInfo[] features = new FeatureInfo[size+1]; 3066 featSet.toArray(features); 3067 FeatureInfo fi = new FeatureInfo(); 3068 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3069 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3070 features[size] = fi; 3071 return features; 3072 } 3073 } 3074 return null; 3075 } 3076 3077 @Override 3078 public boolean hasSystemFeature(String name) { 3079 synchronized (mPackages) { 3080 return mAvailableFeatures.containsKey(name); 3081 } 3082 } 3083 3084 private void checkValidCaller(int uid, int userId) { 3085 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3086 return; 3087 3088 throw new SecurityException("Caller uid=" + uid 3089 + " is not privileged to communicate with user=" + userId); 3090 } 3091 3092 @Override 3093 public int checkPermission(String permName, String pkgName, int userId) { 3094 if (!sUserManager.exists(userId)) { 3095 return PackageManager.PERMISSION_DENIED; 3096 } 3097 3098 synchronized (mPackages) { 3099 final PackageParser.Package p = mPackages.get(pkgName); 3100 if (p != null && p.mExtras != null) { 3101 final PackageSetting ps = (PackageSetting) p.mExtras; 3102 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3103 return PackageManager.PERMISSION_GRANTED; 3104 } 3105 } 3106 } 3107 3108 return PackageManager.PERMISSION_DENIED; 3109 } 3110 3111 @Override 3112 public int checkUidPermission(String permName, int uid) { 3113 final int userId = UserHandle.getUserId(uid); 3114 3115 if (!sUserManager.exists(userId)) { 3116 return PackageManager.PERMISSION_DENIED; 3117 } 3118 3119 synchronized (mPackages) { 3120 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3121 if (obj != null) { 3122 final SettingBase ps = (SettingBase) obj; 3123 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3124 return PackageManager.PERMISSION_GRANTED; 3125 } 3126 } else { 3127 ArraySet<String> perms = mSystemPermissions.get(uid); 3128 if (perms != null && perms.contains(permName)) { 3129 return PackageManager.PERMISSION_GRANTED; 3130 } 3131 } 3132 } 3133 3134 return PackageManager.PERMISSION_DENIED; 3135 } 3136 3137 @Override 3138 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3139 if (UserHandle.getCallingUserId() != userId) { 3140 mContext.enforceCallingPermission( 3141 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3142 "isPermissionRevokedByPolicy for user " + userId); 3143 } 3144 3145 if (checkPermission(permission, packageName, userId) 3146 == PackageManager.PERMISSION_GRANTED) { 3147 return false; 3148 } 3149 3150 final long identity = Binder.clearCallingIdentity(); 3151 try { 3152 final int flags = getPermissionFlags(permission, packageName, userId); 3153 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3154 } finally { 3155 Binder.restoreCallingIdentity(identity); 3156 } 3157 } 3158 3159 /** 3160 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3161 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3162 * @param checkShell TODO(yamasani): 3163 * @param message the message to log on security exception 3164 */ 3165 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3166 boolean checkShell, String message) { 3167 if (userId < 0) { 3168 throw new IllegalArgumentException("Invalid userId " + userId); 3169 } 3170 if (checkShell) { 3171 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3172 } 3173 if (userId == UserHandle.getUserId(callingUid)) return; 3174 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3175 if (requireFullPermission) { 3176 mContext.enforceCallingOrSelfPermission( 3177 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3178 } else { 3179 try { 3180 mContext.enforceCallingOrSelfPermission( 3181 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3182 } catch (SecurityException se) { 3183 mContext.enforceCallingOrSelfPermission( 3184 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3185 } 3186 } 3187 } 3188 } 3189 3190 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3191 if (callingUid == Process.SHELL_UID) { 3192 if (userHandle >= 0 3193 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3194 throw new SecurityException("Shell does not have permission to access user " 3195 + userHandle); 3196 } else if (userHandle < 0) { 3197 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3198 + Debug.getCallers(3)); 3199 } 3200 } 3201 } 3202 3203 private BasePermission findPermissionTreeLP(String permName) { 3204 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3205 if (permName.startsWith(bp.name) && 3206 permName.length() > bp.name.length() && 3207 permName.charAt(bp.name.length()) == '.') { 3208 return bp; 3209 } 3210 } 3211 return null; 3212 } 3213 3214 private BasePermission checkPermissionTreeLP(String permName) { 3215 if (permName != null) { 3216 BasePermission bp = findPermissionTreeLP(permName); 3217 if (bp != null) { 3218 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3219 return bp; 3220 } 3221 throw new SecurityException("Calling uid " 3222 + Binder.getCallingUid() 3223 + " is not allowed to add to permission tree " 3224 + bp.name + " owned by uid " + bp.uid); 3225 } 3226 } 3227 throw new SecurityException("No permission tree found for " + permName); 3228 } 3229 3230 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3231 if (s1 == null) { 3232 return s2 == null; 3233 } 3234 if (s2 == null) { 3235 return false; 3236 } 3237 if (s1.getClass() != s2.getClass()) { 3238 return false; 3239 } 3240 return s1.equals(s2); 3241 } 3242 3243 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3244 if (pi1.icon != pi2.icon) return false; 3245 if (pi1.logo != pi2.logo) return false; 3246 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3247 if (!compareStrings(pi1.name, pi2.name)) return false; 3248 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3249 // We'll take care of setting this one. 3250 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3251 // These are not currently stored in settings. 3252 //if (!compareStrings(pi1.group, pi2.group)) return false; 3253 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3254 //if (pi1.labelRes != pi2.labelRes) return false; 3255 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3256 return true; 3257 } 3258 3259 int permissionInfoFootprint(PermissionInfo info) { 3260 int size = info.name.length(); 3261 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3262 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3263 return size; 3264 } 3265 3266 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3267 int size = 0; 3268 for (BasePermission perm : mSettings.mPermissions.values()) { 3269 if (perm.uid == tree.uid) { 3270 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3271 } 3272 } 3273 return size; 3274 } 3275 3276 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3277 // We calculate the max size of permissions defined by this uid and throw 3278 // if that plus the size of 'info' would exceed our stated maximum. 3279 if (tree.uid != Process.SYSTEM_UID) { 3280 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3281 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3282 throw new SecurityException("Permission tree size cap exceeded"); 3283 } 3284 } 3285 } 3286 3287 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3288 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3289 throw new SecurityException("Label must be specified in permission"); 3290 } 3291 BasePermission tree = checkPermissionTreeLP(info.name); 3292 BasePermission bp = mSettings.mPermissions.get(info.name); 3293 boolean added = bp == null; 3294 boolean changed = true; 3295 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3296 if (added) { 3297 enforcePermissionCapLocked(info, tree); 3298 bp = new BasePermission(info.name, tree.sourcePackage, 3299 BasePermission.TYPE_DYNAMIC); 3300 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3301 throw new SecurityException( 3302 "Not allowed to modify non-dynamic permission " 3303 + info.name); 3304 } else { 3305 if (bp.protectionLevel == fixedLevel 3306 && bp.perm.owner.equals(tree.perm.owner) 3307 && bp.uid == tree.uid 3308 && comparePermissionInfos(bp.perm.info, info)) { 3309 changed = false; 3310 } 3311 } 3312 bp.protectionLevel = fixedLevel; 3313 info = new PermissionInfo(info); 3314 info.protectionLevel = fixedLevel; 3315 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3316 bp.perm.info.packageName = tree.perm.info.packageName; 3317 bp.uid = tree.uid; 3318 if (added) { 3319 mSettings.mPermissions.put(info.name, bp); 3320 } 3321 if (changed) { 3322 if (!async) { 3323 mSettings.writeLPr(); 3324 } else { 3325 scheduleWriteSettingsLocked(); 3326 } 3327 } 3328 return added; 3329 } 3330 3331 @Override 3332 public boolean addPermission(PermissionInfo info) { 3333 synchronized (mPackages) { 3334 return addPermissionLocked(info, false); 3335 } 3336 } 3337 3338 @Override 3339 public boolean addPermissionAsync(PermissionInfo info) { 3340 synchronized (mPackages) { 3341 return addPermissionLocked(info, true); 3342 } 3343 } 3344 3345 @Override 3346 public void removePermission(String name) { 3347 synchronized (mPackages) { 3348 checkPermissionTreeLP(name); 3349 BasePermission bp = mSettings.mPermissions.get(name); 3350 if (bp != null) { 3351 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3352 throw new SecurityException( 3353 "Not allowed to modify non-dynamic permission " 3354 + name); 3355 } 3356 mSettings.mPermissions.remove(name); 3357 mSettings.writeLPr(); 3358 } 3359 } 3360 } 3361 3362 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3363 BasePermission bp) { 3364 int index = pkg.requestedPermissions.indexOf(bp.name); 3365 if (index == -1) { 3366 throw new SecurityException("Package " + pkg.packageName 3367 + " has not requested permission " + bp.name); 3368 } 3369 if (!bp.isRuntime()) { 3370 throw new SecurityException("Permission " + bp.name 3371 + " is not a changeable permission type"); 3372 } 3373 } 3374 3375 @Override 3376 public void grantRuntimePermission(String packageName, String name, final int userId) { 3377 if (!sUserManager.exists(userId)) { 3378 Log.e(TAG, "No such user:" + userId); 3379 return; 3380 } 3381 3382 mContext.enforceCallingOrSelfPermission( 3383 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3384 "grantRuntimePermission"); 3385 3386 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3387 "grantRuntimePermission"); 3388 3389 final int uid; 3390 final SettingBase sb; 3391 3392 synchronized (mPackages) { 3393 final PackageParser.Package pkg = mPackages.get(packageName); 3394 if (pkg == null) { 3395 throw new IllegalArgumentException("Unknown package: " + packageName); 3396 } 3397 3398 final BasePermission bp = mSettings.mPermissions.get(name); 3399 if (bp == null) { 3400 throw new IllegalArgumentException("Unknown permission: " + name); 3401 } 3402 3403 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3404 3405 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3406 sb = (SettingBase) pkg.mExtras; 3407 if (sb == null) { 3408 throw new IllegalArgumentException("Unknown package: " + packageName); 3409 } 3410 3411 final PermissionsState permissionsState = sb.getPermissionsState(); 3412 3413 final int flags = permissionsState.getPermissionFlags(name, userId); 3414 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3415 throw new SecurityException("Cannot grant system fixed permission: " 3416 + name + " for package: " + packageName); 3417 } 3418 3419 final int result = permissionsState.grantRuntimePermission(bp, userId); 3420 switch (result) { 3421 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3422 return; 3423 } 3424 3425 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3426 mHandler.post(new Runnable() { 3427 @Override 3428 public void run() { 3429 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3430 } 3431 }); 3432 } break; 3433 } 3434 3435 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3436 3437 // Not critical if that is lost - app has to request again. 3438 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3439 } 3440 3441 // Only need to do this if user is initialized. Otherwise it's a new user 3442 // and there are no processes running as the user yet and there's no need 3443 // to make an expensive call to remount processes for the changed permissions. 3444 if (READ_EXTERNAL_STORAGE.equals(name) 3445 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3446 final long token = Binder.clearCallingIdentity(); 3447 try { 3448 if (sUserManager.isInitialized(userId)) { 3449 MountServiceInternal mountServiceInternal = LocalServices.getService( 3450 MountServiceInternal.class); 3451 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3452 } 3453 } finally { 3454 Binder.restoreCallingIdentity(token); 3455 } 3456 } 3457 } 3458 3459 @Override 3460 public void revokeRuntimePermission(String packageName, String name, int userId) { 3461 if (!sUserManager.exists(userId)) { 3462 Log.e(TAG, "No such user:" + userId); 3463 return; 3464 } 3465 3466 mContext.enforceCallingOrSelfPermission( 3467 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3468 "revokeRuntimePermission"); 3469 3470 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3471 "revokeRuntimePermission"); 3472 3473 final SettingBase sb; 3474 3475 synchronized (mPackages) { 3476 final PackageParser.Package pkg = mPackages.get(packageName); 3477 if (pkg == null) { 3478 throw new IllegalArgumentException("Unknown package: " + packageName); 3479 } 3480 3481 final BasePermission bp = mSettings.mPermissions.get(name); 3482 if (bp == null) { 3483 throw new IllegalArgumentException("Unknown permission: " + name); 3484 } 3485 3486 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3487 3488 sb = (SettingBase) pkg.mExtras; 3489 if (sb == null) { 3490 throw new IllegalArgumentException("Unknown package: " + packageName); 3491 } 3492 3493 final PermissionsState permissionsState = sb.getPermissionsState(); 3494 3495 final int flags = permissionsState.getPermissionFlags(name, userId); 3496 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3497 throw new SecurityException("Cannot revoke system fixed permission: " 3498 + name + " for package: " + packageName); 3499 } 3500 3501 if (permissionsState.revokeRuntimePermission(bp, userId) == 3502 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3503 return; 3504 } 3505 3506 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3507 3508 // Critical, after this call app should never have the permission. 3509 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3510 } 3511 3512 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3513 } 3514 3515 @Override 3516 public void resetRuntimePermissions() { 3517 mContext.enforceCallingOrSelfPermission( 3518 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3519 "revokeRuntimePermission"); 3520 3521 int callingUid = Binder.getCallingUid(); 3522 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3523 mContext.enforceCallingOrSelfPermission( 3524 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3525 "resetRuntimePermissions"); 3526 } 3527 3528 final int[] userIds; 3529 3530 synchronized (mPackages) { 3531 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3532 final int userCount = UserManagerService.getInstance().getUserIds().length; 3533 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3534 } 3535 3536 for (int userId : userIds) { 3537 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3538 } 3539 } 3540 3541 @Override 3542 public int getPermissionFlags(String name, String packageName, int userId) { 3543 if (!sUserManager.exists(userId)) { 3544 return 0; 3545 } 3546 3547 mContext.enforceCallingOrSelfPermission( 3548 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3549 "getPermissionFlags"); 3550 3551 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3552 "getPermissionFlags"); 3553 3554 synchronized (mPackages) { 3555 final PackageParser.Package pkg = mPackages.get(packageName); 3556 if (pkg == null) { 3557 throw new IllegalArgumentException("Unknown package: " + packageName); 3558 } 3559 3560 final BasePermission bp = mSettings.mPermissions.get(name); 3561 if (bp == null) { 3562 throw new IllegalArgumentException("Unknown permission: " + name); 3563 } 3564 3565 SettingBase sb = (SettingBase) pkg.mExtras; 3566 if (sb == null) { 3567 throw new IllegalArgumentException("Unknown package: " + packageName); 3568 } 3569 3570 PermissionsState permissionsState = sb.getPermissionsState(); 3571 return permissionsState.getPermissionFlags(name, userId); 3572 } 3573 } 3574 3575 @Override 3576 public void updatePermissionFlags(String name, String packageName, int flagMask, 3577 int flagValues, int userId) { 3578 if (!sUserManager.exists(userId)) { 3579 return; 3580 } 3581 3582 mContext.enforceCallingOrSelfPermission( 3583 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3584 "updatePermissionFlags"); 3585 3586 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3587 "updatePermissionFlags"); 3588 3589 // Only the system can change system fixed flags. 3590 if (getCallingUid() != Process.SYSTEM_UID) { 3591 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3592 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3593 } 3594 3595 synchronized (mPackages) { 3596 final PackageParser.Package pkg = mPackages.get(packageName); 3597 if (pkg == null) { 3598 throw new IllegalArgumentException("Unknown package: " + packageName); 3599 } 3600 3601 final BasePermission bp = mSettings.mPermissions.get(name); 3602 if (bp == null) { 3603 throw new IllegalArgumentException("Unknown permission: " + name); 3604 } 3605 3606 SettingBase sb = (SettingBase) pkg.mExtras; 3607 if (sb == null) { 3608 throw new IllegalArgumentException("Unknown package: " + packageName); 3609 } 3610 3611 PermissionsState permissionsState = sb.getPermissionsState(); 3612 3613 // Only the package manager can change flags for system component permissions. 3614 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3615 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3616 return; 3617 } 3618 3619 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3620 3621 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3622 // Install and runtime permissions are stored in different places, 3623 // so figure out what permission changed and persist the change. 3624 if (permissionsState.getInstallPermissionState(name) != null) { 3625 scheduleWriteSettingsLocked(); 3626 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3627 || hadState) { 3628 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3629 } 3630 } 3631 } 3632 } 3633 3634 /** 3635 * Update the permission flags for all packages and runtime permissions of a user in order 3636 * to allow device or profile owner to remove POLICY_FIXED. 3637 */ 3638 @Override 3639 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3640 if (!sUserManager.exists(userId)) { 3641 return; 3642 } 3643 3644 mContext.enforceCallingOrSelfPermission( 3645 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3646 "updatePermissionFlagsForAllApps"); 3647 3648 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3649 "updatePermissionFlagsForAllApps"); 3650 3651 // Only the system can change system fixed flags. 3652 if (getCallingUid() != Process.SYSTEM_UID) { 3653 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3654 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3655 } 3656 3657 synchronized (mPackages) { 3658 boolean changed = false; 3659 final int packageCount = mPackages.size(); 3660 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3661 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3662 SettingBase sb = (SettingBase) pkg.mExtras; 3663 if (sb == null) { 3664 continue; 3665 } 3666 PermissionsState permissionsState = sb.getPermissionsState(); 3667 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3668 userId, flagMask, flagValues); 3669 } 3670 if (changed) { 3671 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3672 } 3673 } 3674 } 3675 3676 @Override 3677 public boolean shouldShowRequestPermissionRationale(String permissionName, 3678 String packageName, int userId) { 3679 if (UserHandle.getCallingUserId() != userId) { 3680 mContext.enforceCallingPermission( 3681 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3682 "canShowRequestPermissionRationale for user " + userId); 3683 } 3684 3685 final int uid = getPackageUid(packageName, userId); 3686 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3687 return false; 3688 } 3689 3690 if (checkPermission(permissionName, packageName, userId) 3691 == PackageManager.PERMISSION_GRANTED) { 3692 return false; 3693 } 3694 3695 final int flags; 3696 3697 final long identity = Binder.clearCallingIdentity(); 3698 try { 3699 flags = getPermissionFlags(permissionName, 3700 packageName, userId); 3701 } finally { 3702 Binder.restoreCallingIdentity(identity); 3703 } 3704 3705 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3706 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3707 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3708 3709 if ((flags & fixedFlags) != 0) { 3710 return false; 3711 } 3712 3713 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3714 } 3715 3716 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3717 BasePermission bp = mSettings.mPermissions.get(permission); 3718 if (bp == null) { 3719 throw new SecurityException("Missing " + permission + " permission"); 3720 } 3721 3722 SettingBase sb = (SettingBase) pkg.mExtras; 3723 PermissionsState permissionsState = sb.getPermissionsState(); 3724 3725 if (permissionsState.grantInstallPermission(bp) != 3726 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3727 scheduleWriteSettingsLocked(); 3728 } 3729 } 3730 3731 @Override 3732 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3733 mContext.enforceCallingOrSelfPermission( 3734 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3735 "addOnPermissionsChangeListener"); 3736 3737 synchronized (mPackages) { 3738 mOnPermissionChangeListeners.addListenerLocked(listener); 3739 } 3740 } 3741 3742 @Override 3743 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3744 synchronized (mPackages) { 3745 mOnPermissionChangeListeners.removeListenerLocked(listener); 3746 } 3747 } 3748 3749 @Override 3750 public boolean isProtectedBroadcast(String actionName) { 3751 synchronized (mPackages) { 3752 return mProtectedBroadcasts.contains(actionName); 3753 } 3754 } 3755 3756 @Override 3757 public int checkSignatures(String pkg1, String pkg2) { 3758 synchronized (mPackages) { 3759 final PackageParser.Package p1 = mPackages.get(pkg1); 3760 final PackageParser.Package p2 = mPackages.get(pkg2); 3761 if (p1 == null || p1.mExtras == null 3762 || p2 == null || p2.mExtras == null) { 3763 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3764 } 3765 return compareSignatures(p1.mSignatures, p2.mSignatures); 3766 } 3767 } 3768 3769 @Override 3770 public int checkUidSignatures(int uid1, int uid2) { 3771 // Map to base uids. 3772 uid1 = UserHandle.getAppId(uid1); 3773 uid2 = UserHandle.getAppId(uid2); 3774 // reader 3775 synchronized (mPackages) { 3776 Signature[] s1; 3777 Signature[] s2; 3778 Object obj = mSettings.getUserIdLPr(uid1); 3779 if (obj != null) { 3780 if (obj instanceof SharedUserSetting) { 3781 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3782 } else if (obj instanceof PackageSetting) { 3783 s1 = ((PackageSetting)obj).signatures.mSignatures; 3784 } else { 3785 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3786 } 3787 } else { 3788 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3789 } 3790 obj = mSettings.getUserIdLPr(uid2); 3791 if (obj != null) { 3792 if (obj instanceof SharedUserSetting) { 3793 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3794 } else if (obj instanceof PackageSetting) { 3795 s2 = ((PackageSetting)obj).signatures.mSignatures; 3796 } else { 3797 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3798 } 3799 } else { 3800 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3801 } 3802 return compareSignatures(s1, s2); 3803 } 3804 } 3805 3806 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3807 final long identity = Binder.clearCallingIdentity(); 3808 try { 3809 if (sb instanceof SharedUserSetting) { 3810 SharedUserSetting sus = (SharedUserSetting) sb; 3811 final int packageCount = sus.packages.size(); 3812 for (int i = 0; i < packageCount; i++) { 3813 PackageSetting susPs = sus.packages.valueAt(i); 3814 if (userId == UserHandle.USER_ALL) { 3815 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3816 } else { 3817 final int uid = UserHandle.getUid(userId, susPs.appId); 3818 killUid(uid, reason); 3819 } 3820 } 3821 } else if (sb instanceof PackageSetting) { 3822 PackageSetting ps = (PackageSetting) sb; 3823 if (userId == UserHandle.USER_ALL) { 3824 killApplication(ps.pkg.packageName, ps.appId, reason); 3825 } else { 3826 final int uid = UserHandle.getUid(userId, ps.appId); 3827 killUid(uid, reason); 3828 } 3829 } 3830 } finally { 3831 Binder.restoreCallingIdentity(identity); 3832 } 3833 } 3834 3835 private static void killUid(int uid, String reason) { 3836 IActivityManager am = ActivityManagerNative.getDefault(); 3837 if (am != null) { 3838 try { 3839 am.killUid(uid, reason); 3840 } catch (RemoteException e) { 3841 /* ignore - same process */ 3842 } 3843 } 3844 } 3845 3846 /** 3847 * Compares two sets of signatures. Returns: 3848 * <br /> 3849 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3850 * <br /> 3851 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3852 * <br /> 3853 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3854 * <br /> 3855 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3856 * <br /> 3857 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3858 */ 3859 static int compareSignatures(Signature[] s1, Signature[] s2) { 3860 if (s1 == null) { 3861 return s2 == null 3862 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3863 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3864 } 3865 3866 if (s2 == null) { 3867 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3868 } 3869 3870 if (s1.length != s2.length) { 3871 return PackageManager.SIGNATURE_NO_MATCH; 3872 } 3873 3874 // Since both signature sets are of size 1, we can compare without HashSets. 3875 if (s1.length == 1) { 3876 return s1[0].equals(s2[0]) ? 3877 PackageManager.SIGNATURE_MATCH : 3878 PackageManager.SIGNATURE_NO_MATCH; 3879 } 3880 3881 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3882 for (Signature sig : s1) { 3883 set1.add(sig); 3884 } 3885 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3886 for (Signature sig : s2) { 3887 set2.add(sig); 3888 } 3889 // Make sure s2 contains all signatures in s1. 3890 if (set1.equals(set2)) { 3891 return PackageManager.SIGNATURE_MATCH; 3892 } 3893 return PackageManager.SIGNATURE_NO_MATCH; 3894 } 3895 3896 /** 3897 * If the database version for this type of package (internal storage or 3898 * external storage) is less than the version where package signatures 3899 * were updated, return true. 3900 */ 3901 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3902 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3903 DatabaseVersion.SIGNATURE_END_ENTITY)) 3904 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3905 DatabaseVersion.SIGNATURE_END_ENTITY)); 3906 } 3907 3908 /** 3909 * Used for backward compatibility to make sure any packages with 3910 * certificate chains get upgraded to the new style. {@code existingSigs} 3911 * will be in the old format (since they were stored on disk from before the 3912 * system upgrade) and {@code scannedSigs} will be in the newer format. 3913 */ 3914 private int compareSignaturesCompat(PackageSignatures existingSigs, 3915 PackageParser.Package scannedPkg) { 3916 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3917 return PackageManager.SIGNATURE_NO_MATCH; 3918 } 3919 3920 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3921 for (Signature sig : existingSigs.mSignatures) { 3922 existingSet.add(sig); 3923 } 3924 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3925 for (Signature sig : scannedPkg.mSignatures) { 3926 try { 3927 Signature[] chainSignatures = sig.getChainSignatures(); 3928 for (Signature chainSig : chainSignatures) { 3929 scannedCompatSet.add(chainSig); 3930 } 3931 } catch (CertificateEncodingException e) { 3932 scannedCompatSet.add(sig); 3933 } 3934 } 3935 /* 3936 * Make sure the expanded scanned set contains all signatures in the 3937 * existing one. 3938 */ 3939 if (scannedCompatSet.equals(existingSet)) { 3940 // Migrate the old signatures to the new scheme. 3941 existingSigs.assignSignatures(scannedPkg.mSignatures); 3942 // The new KeySets will be re-added later in the scanning process. 3943 synchronized (mPackages) { 3944 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3945 } 3946 return PackageManager.SIGNATURE_MATCH; 3947 } 3948 return PackageManager.SIGNATURE_NO_MATCH; 3949 } 3950 3951 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3952 if (isExternal(scannedPkg)) { 3953 return mSettings.isExternalDatabaseVersionOlderThan( 3954 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3955 } else { 3956 return mSettings.isInternalDatabaseVersionOlderThan( 3957 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3958 } 3959 } 3960 3961 private int compareSignaturesRecover(PackageSignatures existingSigs, 3962 PackageParser.Package scannedPkg) { 3963 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3964 return PackageManager.SIGNATURE_NO_MATCH; 3965 } 3966 3967 String msg = null; 3968 try { 3969 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3970 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3971 + scannedPkg.packageName); 3972 return PackageManager.SIGNATURE_MATCH; 3973 } 3974 } catch (CertificateException e) { 3975 msg = e.getMessage(); 3976 } 3977 3978 logCriticalInfo(Log.INFO, 3979 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3980 return PackageManager.SIGNATURE_NO_MATCH; 3981 } 3982 3983 @Override 3984 public String[] getPackagesForUid(int uid) { 3985 uid = UserHandle.getAppId(uid); 3986 // reader 3987 synchronized (mPackages) { 3988 Object obj = mSettings.getUserIdLPr(uid); 3989 if (obj instanceof SharedUserSetting) { 3990 final SharedUserSetting sus = (SharedUserSetting) obj; 3991 final int N = sus.packages.size(); 3992 final String[] res = new String[N]; 3993 final Iterator<PackageSetting> it = sus.packages.iterator(); 3994 int i = 0; 3995 while (it.hasNext()) { 3996 res[i++] = it.next().name; 3997 } 3998 return res; 3999 } else if (obj instanceof PackageSetting) { 4000 final PackageSetting ps = (PackageSetting) obj; 4001 return new String[] { ps.name }; 4002 } 4003 } 4004 return null; 4005 } 4006 4007 @Override 4008 public String getNameForUid(int uid) { 4009 // reader 4010 synchronized (mPackages) { 4011 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4012 if (obj instanceof SharedUserSetting) { 4013 final SharedUserSetting sus = (SharedUserSetting) obj; 4014 return sus.name + ":" + sus.userId; 4015 } else if (obj instanceof PackageSetting) { 4016 final PackageSetting ps = (PackageSetting) obj; 4017 return ps.name; 4018 } 4019 } 4020 return null; 4021 } 4022 4023 @Override 4024 public int getUidForSharedUser(String sharedUserName) { 4025 if(sharedUserName == null) { 4026 return -1; 4027 } 4028 // reader 4029 synchronized (mPackages) { 4030 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4031 if (suid == null) { 4032 return -1; 4033 } 4034 return suid.userId; 4035 } 4036 } 4037 4038 @Override 4039 public int getFlagsForUid(int uid) { 4040 synchronized (mPackages) { 4041 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4042 if (obj instanceof SharedUserSetting) { 4043 final SharedUserSetting sus = (SharedUserSetting) obj; 4044 return sus.pkgFlags; 4045 } else if (obj instanceof PackageSetting) { 4046 final PackageSetting ps = (PackageSetting) obj; 4047 return ps.pkgFlags; 4048 } 4049 } 4050 return 0; 4051 } 4052 4053 @Override 4054 public int getPrivateFlagsForUid(int uid) { 4055 synchronized (mPackages) { 4056 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4057 if (obj instanceof SharedUserSetting) { 4058 final SharedUserSetting sus = (SharedUserSetting) obj; 4059 return sus.pkgPrivateFlags; 4060 } else if (obj instanceof PackageSetting) { 4061 final PackageSetting ps = (PackageSetting) obj; 4062 return ps.pkgPrivateFlags; 4063 } 4064 } 4065 return 0; 4066 } 4067 4068 @Override 4069 public boolean isUidPrivileged(int uid) { 4070 uid = UserHandle.getAppId(uid); 4071 // reader 4072 synchronized (mPackages) { 4073 Object obj = mSettings.getUserIdLPr(uid); 4074 if (obj instanceof SharedUserSetting) { 4075 final SharedUserSetting sus = (SharedUserSetting) obj; 4076 final Iterator<PackageSetting> it = sus.packages.iterator(); 4077 while (it.hasNext()) { 4078 if (it.next().isPrivileged()) { 4079 return true; 4080 } 4081 } 4082 } else if (obj instanceof PackageSetting) { 4083 final PackageSetting ps = (PackageSetting) obj; 4084 return ps.isPrivileged(); 4085 } 4086 } 4087 return false; 4088 } 4089 4090 @Override 4091 public String[] getAppOpPermissionPackages(String permissionName) { 4092 synchronized (mPackages) { 4093 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4094 if (pkgs == null) { 4095 return null; 4096 } 4097 return pkgs.toArray(new String[pkgs.size()]); 4098 } 4099 } 4100 4101 @Override 4102 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4103 int flags, int userId) { 4104 if (!sUserManager.exists(userId)) return null; 4105 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4106 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4107 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4108 } 4109 4110 @Override 4111 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4112 IntentFilter filter, int match, ComponentName activity) { 4113 final int userId = UserHandle.getCallingUserId(); 4114 if (DEBUG_PREFERRED) { 4115 Log.v(TAG, "setLastChosenActivity intent=" + intent 4116 + " resolvedType=" + resolvedType 4117 + " flags=" + flags 4118 + " filter=" + filter 4119 + " match=" + match 4120 + " activity=" + activity); 4121 filter.dump(new PrintStreamPrinter(System.out), " "); 4122 } 4123 intent.setComponent(null); 4124 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4125 // Find any earlier preferred or last chosen entries and nuke them 4126 findPreferredActivity(intent, resolvedType, 4127 flags, query, 0, false, true, false, userId); 4128 // Add the new activity as the last chosen for this filter 4129 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4130 "Setting last chosen"); 4131 } 4132 4133 @Override 4134 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4135 final int userId = UserHandle.getCallingUserId(); 4136 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4137 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4138 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4139 false, false, false, userId); 4140 } 4141 4142 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4143 int flags, List<ResolveInfo> query, int userId) { 4144 if (query != null) { 4145 final int N = query.size(); 4146 if (N == 1) { 4147 return query.get(0); 4148 } else if (N > 1) { 4149 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4150 // If there is more than one activity with the same priority, 4151 // then let the user decide between them. 4152 ResolveInfo r0 = query.get(0); 4153 ResolveInfo r1 = query.get(1); 4154 if (DEBUG_INTENT_MATCHING || debug) { 4155 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4156 + r1.activityInfo.name + "=" + r1.priority); 4157 } 4158 // If the first activity has a higher priority, or a different 4159 // default, then it is always desireable to pick it. 4160 if (r0.priority != r1.priority 4161 || r0.preferredOrder != r1.preferredOrder 4162 || r0.isDefault != r1.isDefault) { 4163 return query.get(0); 4164 } 4165 // If we have saved a preference for a preferred activity for 4166 // this Intent, use that. 4167 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4168 flags, query, r0.priority, true, false, debug, userId); 4169 if (ri != null) { 4170 return ri; 4171 } 4172 if (userId != 0) { 4173 ri = new ResolveInfo(mResolveInfo); 4174 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4175 ri.activityInfo.applicationInfo = new ApplicationInfo( 4176 ri.activityInfo.applicationInfo); 4177 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4178 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4179 return ri; 4180 } 4181 return mResolveInfo; 4182 } 4183 } 4184 return null; 4185 } 4186 4187 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4188 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4189 final int N = query.size(); 4190 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4191 .get(userId); 4192 // Get the list of persistent preferred activities that handle the intent 4193 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4194 List<PersistentPreferredActivity> pprefs = ppir != null 4195 ? ppir.queryIntent(intent, resolvedType, 4196 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4197 : null; 4198 if (pprefs != null && pprefs.size() > 0) { 4199 final int M = pprefs.size(); 4200 for (int i=0; i<M; i++) { 4201 final PersistentPreferredActivity ppa = pprefs.get(i); 4202 if (DEBUG_PREFERRED || debug) { 4203 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4204 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4205 + "\n component=" + ppa.mComponent); 4206 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4207 } 4208 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4209 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4210 if (DEBUG_PREFERRED || debug) { 4211 Slog.v(TAG, "Found persistent preferred activity:"); 4212 if (ai != null) { 4213 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4214 } else { 4215 Slog.v(TAG, " null"); 4216 } 4217 } 4218 if (ai == null) { 4219 // This previously registered persistent preferred activity 4220 // component is no longer known. Ignore it and do NOT remove it. 4221 continue; 4222 } 4223 for (int j=0; j<N; j++) { 4224 final ResolveInfo ri = query.get(j); 4225 if (!ri.activityInfo.applicationInfo.packageName 4226 .equals(ai.applicationInfo.packageName)) { 4227 continue; 4228 } 4229 if (!ri.activityInfo.name.equals(ai.name)) { 4230 continue; 4231 } 4232 // Found a persistent preference that can handle the intent. 4233 if (DEBUG_PREFERRED || debug) { 4234 Slog.v(TAG, "Returning persistent preferred activity: " + 4235 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4236 } 4237 return ri; 4238 } 4239 } 4240 } 4241 return null; 4242 } 4243 4244 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4245 List<ResolveInfo> query, int priority, boolean always, 4246 boolean removeMatches, boolean debug, int userId) { 4247 if (!sUserManager.exists(userId)) return null; 4248 // writer 4249 synchronized (mPackages) { 4250 if (intent.getSelector() != null) { 4251 intent = intent.getSelector(); 4252 } 4253 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4254 4255 // Try to find a matching persistent preferred activity. 4256 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4257 debug, userId); 4258 4259 // If a persistent preferred activity matched, use it. 4260 if (pri != null) { 4261 return pri; 4262 } 4263 4264 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4265 // Get the list of preferred activities that handle the intent 4266 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4267 List<PreferredActivity> prefs = pir != null 4268 ? pir.queryIntent(intent, resolvedType, 4269 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4270 : null; 4271 if (prefs != null && prefs.size() > 0) { 4272 boolean changed = false; 4273 try { 4274 // First figure out how good the original match set is. 4275 // We will only allow preferred activities that came 4276 // from the same match quality. 4277 int match = 0; 4278 4279 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4280 4281 final int N = query.size(); 4282 for (int j=0; j<N; j++) { 4283 final ResolveInfo ri = query.get(j); 4284 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4285 + ": 0x" + Integer.toHexString(match)); 4286 if (ri.match > match) { 4287 match = ri.match; 4288 } 4289 } 4290 4291 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4292 + Integer.toHexString(match)); 4293 4294 match &= IntentFilter.MATCH_CATEGORY_MASK; 4295 final int M = prefs.size(); 4296 for (int i=0; i<M; i++) { 4297 final PreferredActivity pa = prefs.get(i); 4298 if (DEBUG_PREFERRED || debug) { 4299 Slog.v(TAG, "Checking PreferredActivity ds=" 4300 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4301 + "\n component=" + pa.mPref.mComponent); 4302 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4303 } 4304 if (pa.mPref.mMatch != match) { 4305 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4306 + Integer.toHexString(pa.mPref.mMatch)); 4307 continue; 4308 } 4309 // If it's not an "always" type preferred activity and that's what we're 4310 // looking for, skip it. 4311 if (always && !pa.mPref.mAlways) { 4312 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4313 continue; 4314 } 4315 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4316 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4317 if (DEBUG_PREFERRED || debug) { 4318 Slog.v(TAG, "Found preferred activity:"); 4319 if (ai != null) { 4320 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4321 } else { 4322 Slog.v(TAG, " null"); 4323 } 4324 } 4325 if (ai == null) { 4326 // This previously registered preferred activity 4327 // component is no longer known. Most likely an update 4328 // to the app was installed and in the new version this 4329 // component no longer exists. Clean it up by removing 4330 // it from the preferred activities list, and skip it. 4331 Slog.w(TAG, "Removing dangling preferred activity: " 4332 + pa.mPref.mComponent); 4333 pir.removeFilter(pa); 4334 changed = true; 4335 continue; 4336 } 4337 for (int j=0; j<N; j++) { 4338 final ResolveInfo ri = query.get(j); 4339 if (!ri.activityInfo.applicationInfo.packageName 4340 .equals(ai.applicationInfo.packageName)) { 4341 continue; 4342 } 4343 if (!ri.activityInfo.name.equals(ai.name)) { 4344 continue; 4345 } 4346 4347 if (removeMatches) { 4348 pir.removeFilter(pa); 4349 changed = true; 4350 if (DEBUG_PREFERRED) { 4351 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4352 } 4353 break; 4354 } 4355 4356 // Okay we found a previously set preferred or last chosen app. 4357 // If the result set is different from when this 4358 // was created, we need to clear it and re-ask the 4359 // user their preference, if we're looking for an "always" type entry. 4360 if (always && !pa.mPref.sameSet(query)) { 4361 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4362 + intent + " type " + resolvedType); 4363 if (DEBUG_PREFERRED) { 4364 Slog.v(TAG, "Removing preferred activity since set changed " 4365 + pa.mPref.mComponent); 4366 } 4367 pir.removeFilter(pa); 4368 // Re-add the filter as a "last chosen" entry (!always) 4369 PreferredActivity lastChosen = new PreferredActivity( 4370 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4371 pir.addFilter(lastChosen); 4372 changed = true; 4373 return null; 4374 } 4375 4376 // Yay! Either the set matched or we're looking for the last chosen 4377 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4378 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4379 return ri; 4380 } 4381 } 4382 } finally { 4383 if (changed) { 4384 if (DEBUG_PREFERRED) { 4385 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4386 } 4387 scheduleWritePackageRestrictionsLocked(userId); 4388 } 4389 } 4390 } 4391 } 4392 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4393 return null; 4394 } 4395 4396 /* 4397 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4398 */ 4399 @Override 4400 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4401 int targetUserId) { 4402 mContext.enforceCallingOrSelfPermission( 4403 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4404 List<CrossProfileIntentFilter> matches = 4405 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4406 if (matches != null) { 4407 int size = matches.size(); 4408 for (int i = 0; i < size; i++) { 4409 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4410 } 4411 } 4412 if (hasWebURI(intent)) { 4413 // cross-profile app linking works only towards the parent. 4414 final UserInfo parent = getProfileParent(sourceUserId); 4415 synchronized(mPackages) { 4416 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4417 intent, resolvedType, 0, sourceUserId, parent.id); 4418 return xpDomainInfo != null 4419 && xpDomainInfo.bestDomainVerificationStatus != 4420 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 4421 } 4422 } 4423 return false; 4424 } 4425 4426 private UserInfo getProfileParent(int userId) { 4427 final long identity = Binder.clearCallingIdentity(); 4428 try { 4429 return sUserManager.getProfileParent(userId); 4430 } finally { 4431 Binder.restoreCallingIdentity(identity); 4432 } 4433 } 4434 4435 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4436 String resolvedType, int userId) { 4437 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4438 if (resolver != null) { 4439 return resolver.queryIntent(intent, resolvedType, false, userId); 4440 } 4441 return null; 4442 } 4443 4444 @Override 4445 public List<ResolveInfo> queryIntentActivities(Intent intent, 4446 String resolvedType, int flags, int userId) { 4447 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4448 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4449 ComponentName comp = intent.getComponent(); 4450 if (comp == null) { 4451 if (intent.getSelector() != null) { 4452 intent = intent.getSelector(); 4453 comp = intent.getComponent(); 4454 } 4455 } 4456 4457 if (comp != null) { 4458 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4459 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4460 if (ai != null) { 4461 final ResolveInfo ri = new ResolveInfo(); 4462 ri.activityInfo = ai; 4463 list.add(ri); 4464 } 4465 return list; 4466 } 4467 4468 // reader 4469 synchronized (mPackages) { 4470 final String pkgName = intent.getPackage(); 4471 if (pkgName == null) { 4472 List<CrossProfileIntentFilter> matchingFilters = 4473 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4474 // Check for results that need to skip the current profile. 4475 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4476 resolvedType, flags, userId); 4477 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4478 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4479 result.add(xpResolveInfo); 4480 return filterIfNotPrimaryUser(result, userId); 4481 } 4482 4483 // Check for results in the current profile. 4484 List<ResolveInfo> result = mActivities.queryIntent( 4485 intent, resolvedType, flags, userId); 4486 4487 // Check for cross profile results. 4488 xpResolveInfo = queryCrossProfileIntents( 4489 matchingFilters, intent, resolvedType, flags, userId); 4490 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4491 result.add(xpResolveInfo); 4492 Collections.sort(result, mResolvePrioritySorter); 4493 } 4494 result = filterIfNotPrimaryUser(result, userId); 4495 if (hasWebURI(intent)) { 4496 CrossProfileDomainInfo xpDomainInfo = null; 4497 final UserInfo parent = getProfileParent(userId); 4498 if (parent != null) { 4499 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4500 flags, userId, parent.id); 4501 } 4502 if (xpDomainInfo != null) { 4503 if (xpResolveInfo != null) { 4504 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4505 // in the result. 4506 result.remove(xpResolveInfo); 4507 } 4508 if (result.size() == 0) { 4509 result.add(xpDomainInfo.resolveInfo); 4510 return result; 4511 } 4512 } else if (result.size() <= 1) { 4513 return result; 4514 } 4515 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4516 xpDomainInfo, userId); 4517 Collections.sort(result, mResolvePrioritySorter); 4518 } 4519 return result; 4520 } 4521 final PackageParser.Package pkg = mPackages.get(pkgName); 4522 if (pkg != null) { 4523 return filterIfNotPrimaryUser( 4524 mActivities.queryIntentForPackage( 4525 intent, resolvedType, flags, pkg.activities, userId), 4526 userId); 4527 } 4528 return new ArrayList<ResolveInfo>(); 4529 } 4530 } 4531 4532 private static class CrossProfileDomainInfo { 4533 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4534 ResolveInfo resolveInfo; 4535 /* Best domain verification status of the activities found in the other profile */ 4536 int bestDomainVerificationStatus; 4537 } 4538 4539 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4540 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4541 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4542 sourceUserId)) { 4543 return null; 4544 } 4545 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4546 resolvedType, flags, parentUserId); 4547 4548 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4549 return null; 4550 } 4551 CrossProfileDomainInfo result = null; 4552 int size = resultTargetUser.size(); 4553 for (int i = 0; i < size; i++) { 4554 ResolveInfo riTargetUser = resultTargetUser.get(i); 4555 // Intent filter verification is only for filters that specify a host. So don't return 4556 // those that handle all web uris. 4557 if (riTargetUser.handleAllWebDataURI) { 4558 continue; 4559 } 4560 String packageName = riTargetUser.activityInfo.packageName; 4561 PackageSetting ps = mSettings.mPackages.get(packageName); 4562 if (ps == null) { 4563 continue; 4564 } 4565 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4566 int status = (int)(verificationState >> 32); 4567 if (result == null) { 4568 result = new CrossProfileDomainInfo(); 4569 result.resolveInfo = 4570 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4571 result.bestDomainVerificationStatus = status; 4572 } else { 4573 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4574 result.bestDomainVerificationStatus); 4575 } 4576 } 4577 return result; 4578 } 4579 4580 /** 4581 * Verification statuses are ordered from the worse to the best, except for 4582 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4583 */ 4584 private int bestDomainVerificationStatus(int status1, int status2) { 4585 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4586 return status2; 4587 } 4588 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4589 return status1; 4590 } 4591 return (int) MathUtils.max(status1, status2); 4592 } 4593 4594 private boolean isUserEnabled(int userId) { 4595 long callingId = Binder.clearCallingIdentity(); 4596 try { 4597 UserInfo userInfo = sUserManager.getUserInfo(userId); 4598 return userInfo != null && userInfo.isEnabled(); 4599 } finally { 4600 Binder.restoreCallingIdentity(callingId); 4601 } 4602 } 4603 4604 /** 4605 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4606 * 4607 * @return filtered list 4608 */ 4609 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4610 if (userId == UserHandle.USER_OWNER) { 4611 return resolveInfos; 4612 } 4613 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4614 ResolveInfo info = resolveInfos.get(i); 4615 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4616 resolveInfos.remove(i); 4617 } 4618 } 4619 return resolveInfos; 4620 } 4621 4622 private static boolean hasWebURI(Intent intent) { 4623 if (intent.getData() == null) { 4624 return false; 4625 } 4626 final String scheme = intent.getScheme(); 4627 if (TextUtils.isEmpty(scheme)) { 4628 return false; 4629 } 4630 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4631 } 4632 4633 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4634 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4635 int userId) { 4636 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4637 4638 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4639 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4640 candidates.size()); 4641 } 4642 4643 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4644 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4645 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4646 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4647 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4648 4649 synchronized (mPackages) { 4650 final int count = candidates.size(); 4651 // First, try to use linked apps. Partition the candidates into four lists: 4652 // one for the final results, one for the "do not use ever", one for "undefined status" 4653 // and finally one for "browser app type". 4654 for (int n=0; n<count; n++) { 4655 ResolveInfo info = candidates.get(n); 4656 String packageName = info.activityInfo.packageName; 4657 PackageSetting ps = mSettings.mPackages.get(packageName); 4658 if (ps != null) { 4659 // Add to the special match all list (Browser use case) 4660 if (info.handleAllWebDataURI) { 4661 matchAllList.add(info); 4662 continue; 4663 } 4664 // Try to get the status from User settings first 4665 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4666 int status = (int)(packedStatus >> 32); 4667 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4668 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4669 if (DEBUG_DOMAIN_VERIFICATION) { 4670 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4671 + " : linkgen=" + linkGeneration); 4672 } 4673 // Use link-enabled generation as preferredOrder, i.e. 4674 // prefer newly-enabled over earlier-enabled. 4675 info.preferredOrder = linkGeneration; 4676 alwaysList.add(info); 4677 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4678 if (DEBUG_DOMAIN_VERIFICATION) { 4679 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4680 } 4681 neverList.add(info); 4682 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4683 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4684 if (DEBUG_DOMAIN_VERIFICATION) { 4685 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4686 } 4687 undefinedList.add(info); 4688 } 4689 } 4690 } 4691 // First try to add the "always" resolution(s) for the current user, if any 4692 if (alwaysList.size() > 0) { 4693 result.addAll(alwaysList); 4694 // if there is an "always" for the parent user, add it. 4695 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4696 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4697 result.add(xpDomainInfo.resolveInfo); 4698 } else { 4699 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4700 result.addAll(undefinedList); 4701 if (xpDomainInfo != null && ( 4702 xpDomainInfo.bestDomainVerificationStatus 4703 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4704 || xpDomainInfo.bestDomainVerificationStatus 4705 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4706 result.add(xpDomainInfo.resolveInfo); 4707 } 4708 // Also add Browsers (all of them or only the default one) 4709 if ((matchFlags & MATCH_ALL) != 0) { 4710 result.addAll(matchAllList); 4711 } else { 4712 // Browser/generic handling case. If there's a default browser, go straight 4713 // to that (but only if there is no other higher-priority match). 4714 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4715 int maxMatchPrio = 0; 4716 ResolveInfo defaultBrowserMatch = null; 4717 final int numCandidates = matchAllList.size(); 4718 for (int n = 0; n < numCandidates; n++) { 4719 ResolveInfo info = matchAllList.get(n); 4720 // track the highest overall match priority... 4721 if (info.priority > maxMatchPrio) { 4722 maxMatchPrio = info.priority; 4723 } 4724 // ...and the highest-priority default browser match 4725 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4726 if (defaultBrowserMatch == null 4727 || (defaultBrowserMatch.priority < info.priority)) { 4728 if (debug) { 4729 Slog.v(TAG, "Considering default browser match " + info); 4730 } 4731 defaultBrowserMatch = info; 4732 } 4733 } 4734 } 4735 if (defaultBrowserMatch != null 4736 && defaultBrowserMatch.priority >= maxMatchPrio 4737 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4738 { 4739 if (debug) { 4740 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4741 } 4742 result.add(defaultBrowserMatch); 4743 } else { 4744 result.addAll(matchAllList); 4745 } 4746 } 4747 4748 // If there is nothing selected, add all candidates and remove the ones that the user 4749 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4750 if (result.size() == 0) { 4751 result.addAll(candidates); 4752 result.removeAll(neverList); 4753 } 4754 } 4755 } 4756 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4757 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4758 result.size()); 4759 for (ResolveInfo info : result) { 4760 Slog.v(TAG, " + " + info.activityInfo); 4761 } 4762 } 4763 return result; 4764 } 4765 4766 // Returns a packed value as a long: 4767 // 4768 // high 'int'-sized word: link status: undefined/ask/never/always. 4769 // low 'int'-sized word: relative priority among 'always' results. 4770 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4771 long result = ps.getDomainVerificationStatusForUser(userId); 4772 // if none available, get the master status 4773 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4774 if (ps.getIntentFilterVerificationInfo() != null) { 4775 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4776 } 4777 } 4778 return result; 4779 } 4780 4781 private ResolveInfo querySkipCurrentProfileIntents( 4782 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4783 int flags, int sourceUserId) { 4784 if (matchingFilters != null) { 4785 int size = matchingFilters.size(); 4786 for (int i = 0; i < size; i ++) { 4787 CrossProfileIntentFilter filter = matchingFilters.get(i); 4788 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4789 // Checking if there are activities in the target user that can handle the 4790 // intent. 4791 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4792 flags, sourceUserId); 4793 if (resolveInfo != null) { 4794 return resolveInfo; 4795 } 4796 } 4797 } 4798 } 4799 return null; 4800 } 4801 4802 // Return matching ResolveInfo if any for skip current profile intent filters. 4803 private ResolveInfo queryCrossProfileIntents( 4804 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4805 int flags, int sourceUserId) { 4806 if (matchingFilters != null) { 4807 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4808 // match the same intent. For performance reasons, it is better not to 4809 // run queryIntent twice for the same userId 4810 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4811 int size = matchingFilters.size(); 4812 for (int i = 0; i < size; i++) { 4813 CrossProfileIntentFilter filter = matchingFilters.get(i); 4814 int targetUserId = filter.getTargetUserId(); 4815 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4816 && !alreadyTriedUserIds.get(targetUserId)) { 4817 // Checking if there are activities in the target user that can handle the 4818 // intent. 4819 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4820 flags, sourceUserId); 4821 if (resolveInfo != null) return resolveInfo; 4822 alreadyTriedUserIds.put(targetUserId, true); 4823 } 4824 } 4825 } 4826 return null; 4827 } 4828 4829 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4830 String resolvedType, int flags, int sourceUserId) { 4831 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4832 resolvedType, flags, filter.getTargetUserId()); 4833 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4834 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4835 } 4836 return null; 4837 } 4838 4839 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4840 int sourceUserId, int targetUserId) { 4841 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4842 String className; 4843 if (targetUserId == UserHandle.USER_OWNER) { 4844 className = FORWARD_INTENT_TO_USER_OWNER; 4845 } else { 4846 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4847 } 4848 ComponentName forwardingActivityComponentName = new ComponentName( 4849 mAndroidApplication.packageName, className); 4850 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4851 sourceUserId); 4852 if (targetUserId == UserHandle.USER_OWNER) { 4853 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4854 forwardingResolveInfo.noResourceId = true; 4855 } 4856 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4857 forwardingResolveInfo.priority = 0; 4858 forwardingResolveInfo.preferredOrder = 0; 4859 forwardingResolveInfo.match = 0; 4860 forwardingResolveInfo.isDefault = true; 4861 forwardingResolveInfo.filter = filter; 4862 forwardingResolveInfo.targetUserId = targetUserId; 4863 return forwardingResolveInfo; 4864 } 4865 4866 @Override 4867 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4868 Intent[] specifics, String[] specificTypes, Intent intent, 4869 String resolvedType, int flags, int userId) { 4870 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4871 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4872 false, "query intent activity options"); 4873 final String resultsAction = intent.getAction(); 4874 4875 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4876 | PackageManager.GET_RESOLVED_FILTER, userId); 4877 4878 if (DEBUG_INTENT_MATCHING) { 4879 Log.v(TAG, "Query " + intent + ": " + results); 4880 } 4881 4882 int specificsPos = 0; 4883 int N; 4884 4885 // todo: note that the algorithm used here is O(N^2). This 4886 // isn't a problem in our current environment, but if we start running 4887 // into situations where we have more than 5 or 10 matches then this 4888 // should probably be changed to something smarter... 4889 4890 // First we go through and resolve each of the specific items 4891 // that were supplied, taking care of removing any corresponding 4892 // duplicate items in the generic resolve list. 4893 if (specifics != null) { 4894 for (int i=0; i<specifics.length; i++) { 4895 final Intent sintent = specifics[i]; 4896 if (sintent == null) { 4897 continue; 4898 } 4899 4900 if (DEBUG_INTENT_MATCHING) { 4901 Log.v(TAG, "Specific #" + i + ": " + sintent); 4902 } 4903 4904 String action = sintent.getAction(); 4905 if (resultsAction != null && resultsAction.equals(action)) { 4906 // If this action was explicitly requested, then don't 4907 // remove things that have it. 4908 action = null; 4909 } 4910 4911 ResolveInfo ri = null; 4912 ActivityInfo ai = null; 4913 4914 ComponentName comp = sintent.getComponent(); 4915 if (comp == null) { 4916 ri = resolveIntent( 4917 sintent, 4918 specificTypes != null ? specificTypes[i] : null, 4919 flags, userId); 4920 if (ri == null) { 4921 continue; 4922 } 4923 if (ri == mResolveInfo) { 4924 // ACK! Must do something better with this. 4925 } 4926 ai = ri.activityInfo; 4927 comp = new ComponentName(ai.applicationInfo.packageName, 4928 ai.name); 4929 } else { 4930 ai = getActivityInfo(comp, flags, userId); 4931 if (ai == null) { 4932 continue; 4933 } 4934 } 4935 4936 // Look for any generic query activities that are duplicates 4937 // of this specific one, and remove them from the results. 4938 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4939 N = results.size(); 4940 int j; 4941 for (j=specificsPos; j<N; j++) { 4942 ResolveInfo sri = results.get(j); 4943 if ((sri.activityInfo.name.equals(comp.getClassName()) 4944 && sri.activityInfo.applicationInfo.packageName.equals( 4945 comp.getPackageName())) 4946 || (action != null && sri.filter.matchAction(action))) { 4947 results.remove(j); 4948 if (DEBUG_INTENT_MATCHING) Log.v( 4949 TAG, "Removing duplicate item from " + j 4950 + " due to specific " + specificsPos); 4951 if (ri == null) { 4952 ri = sri; 4953 } 4954 j--; 4955 N--; 4956 } 4957 } 4958 4959 // Add this specific item to its proper place. 4960 if (ri == null) { 4961 ri = new ResolveInfo(); 4962 ri.activityInfo = ai; 4963 } 4964 results.add(specificsPos, ri); 4965 ri.specificIndex = i; 4966 specificsPos++; 4967 } 4968 } 4969 4970 // Now we go through the remaining generic results and remove any 4971 // duplicate actions that are found here. 4972 N = results.size(); 4973 for (int i=specificsPos; i<N-1; i++) { 4974 final ResolveInfo rii = results.get(i); 4975 if (rii.filter == null) { 4976 continue; 4977 } 4978 4979 // Iterate over all of the actions of this result's intent 4980 // filter... typically this should be just one. 4981 final Iterator<String> it = rii.filter.actionsIterator(); 4982 if (it == null) { 4983 continue; 4984 } 4985 while (it.hasNext()) { 4986 final String action = it.next(); 4987 if (resultsAction != null && resultsAction.equals(action)) { 4988 // If this action was explicitly requested, then don't 4989 // remove things that have it. 4990 continue; 4991 } 4992 for (int j=i+1; j<N; j++) { 4993 final ResolveInfo rij = results.get(j); 4994 if (rij.filter != null && rij.filter.hasAction(action)) { 4995 results.remove(j); 4996 if (DEBUG_INTENT_MATCHING) Log.v( 4997 TAG, "Removing duplicate item from " + j 4998 + " due to action " + action + " at " + i); 4999 j--; 5000 N--; 5001 } 5002 } 5003 } 5004 5005 // If the caller didn't request filter information, drop it now 5006 // so we don't have to marshall/unmarshall it. 5007 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5008 rii.filter = null; 5009 } 5010 } 5011 5012 // Filter out the caller activity if so requested. 5013 if (caller != null) { 5014 N = results.size(); 5015 for (int i=0; i<N; i++) { 5016 ActivityInfo ainfo = results.get(i).activityInfo; 5017 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5018 && caller.getClassName().equals(ainfo.name)) { 5019 results.remove(i); 5020 break; 5021 } 5022 } 5023 } 5024 5025 // If the caller didn't request filter information, 5026 // drop them now so we don't have to 5027 // marshall/unmarshall it. 5028 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5029 N = results.size(); 5030 for (int i=0; i<N; i++) { 5031 results.get(i).filter = null; 5032 } 5033 } 5034 5035 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5036 return results; 5037 } 5038 5039 @Override 5040 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5041 int userId) { 5042 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5043 ComponentName comp = intent.getComponent(); 5044 if (comp == null) { 5045 if (intent.getSelector() != null) { 5046 intent = intent.getSelector(); 5047 comp = intent.getComponent(); 5048 } 5049 } 5050 if (comp != null) { 5051 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5052 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5053 if (ai != null) { 5054 ResolveInfo ri = new ResolveInfo(); 5055 ri.activityInfo = ai; 5056 list.add(ri); 5057 } 5058 return list; 5059 } 5060 5061 // reader 5062 synchronized (mPackages) { 5063 String pkgName = intent.getPackage(); 5064 if (pkgName == null) { 5065 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5066 } 5067 final PackageParser.Package pkg = mPackages.get(pkgName); 5068 if (pkg != null) { 5069 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5070 userId); 5071 } 5072 return null; 5073 } 5074 } 5075 5076 @Override 5077 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5078 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5079 if (!sUserManager.exists(userId)) return null; 5080 if (query != null) { 5081 if (query.size() >= 1) { 5082 // If there is more than one service with the same priority, 5083 // just arbitrarily pick the first one. 5084 return query.get(0); 5085 } 5086 } 5087 return null; 5088 } 5089 5090 @Override 5091 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5092 int userId) { 5093 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5094 ComponentName comp = intent.getComponent(); 5095 if (comp == null) { 5096 if (intent.getSelector() != null) { 5097 intent = intent.getSelector(); 5098 comp = intent.getComponent(); 5099 } 5100 } 5101 if (comp != null) { 5102 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5103 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5104 if (si != null) { 5105 final ResolveInfo ri = new ResolveInfo(); 5106 ri.serviceInfo = si; 5107 list.add(ri); 5108 } 5109 return list; 5110 } 5111 5112 // reader 5113 synchronized (mPackages) { 5114 String pkgName = intent.getPackage(); 5115 if (pkgName == null) { 5116 return mServices.queryIntent(intent, resolvedType, flags, userId); 5117 } 5118 final PackageParser.Package pkg = mPackages.get(pkgName); 5119 if (pkg != null) { 5120 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5121 userId); 5122 } 5123 return null; 5124 } 5125 } 5126 5127 @Override 5128 public List<ResolveInfo> queryIntentContentProviders( 5129 Intent intent, String resolvedType, int flags, int userId) { 5130 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5131 ComponentName comp = intent.getComponent(); 5132 if (comp == null) { 5133 if (intent.getSelector() != null) { 5134 intent = intent.getSelector(); 5135 comp = intent.getComponent(); 5136 } 5137 } 5138 if (comp != null) { 5139 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5140 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5141 if (pi != null) { 5142 final ResolveInfo ri = new ResolveInfo(); 5143 ri.providerInfo = pi; 5144 list.add(ri); 5145 } 5146 return list; 5147 } 5148 5149 // reader 5150 synchronized (mPackages) { 5151 String pkgName = intent.getPackage(); 5152 if (pkgName == null) { 5153 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5154 } 5155 final PackageParser.Package pkg = mPackages.get(pkgName); 5156 if (pkg != null) { 5157 return mProviders.queryIntentForPackage( 5158 intent, resolvedType, flags, pkg.providers, userId); 5159 } 5160 return null; 5161 } 5162 } 5163 5164 @Override 5165 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5166 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5167 5168 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5169 5170 // writer 5171 synchronized (mPackages) { 5172 ArrayList<PackageInfo> list; 5173 if (listUninstalled) { 5174 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5175 for (PackageSetting ps : mSettings.mPackages.values()) { 5176 PackageInfo pi; 5177 if (ps.pkg != null) { 5178 pi = generatePackageInfo(ps.pkg, flags, userId); 5179 } else { 5180 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5181 } 5182 if (pi != null) { 5183 list.add(pi); 5184 } 5185 } 5186 } else { 5187 list = new ArrayList<PackageInfo>(mPackages.size()); 5188 for (PackageParser.Package p : mPackages.values()) { 5189 PackageInfo pi = generatePackageInfo(p, flags, userId); 5190 if (pi != null) { 5191 list.add(pi); 5192 } 5193 } 5194 } 5195 5196 return new ParceledListSlice<PackageInfo>(list); 5197 } 5198 } 5199 5200 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5201 String[] permissions, boolean[] tmp, int flags, int userId) { 5202 int numMatch = 0; 5203 final PermissionsState permissionsState = ps.getPermissionsState(); 5204 for (int i=0; i<permissions.length; i++) { 5205 final String permission = permissions[i]; 5206 if (permissionsState.hasPermission(permission, userId)) { 5207 tmp[i] = true; 5208 numMatch++; 5209 } else { 5210 tmp[i] = false; 5211 } 5212 } 5213 if (numMatch == 0) { 5214 return; 5215 } 5216 PackageInfo pi; 5217 if (ps.pkg != null) { 5218 pi = generatePackageInfo(ps.pkg, flags, userId); 5219 } else { 5220 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5221 } 5222 // The above might return null in cases of uninstalled apps or install-state 5223 // skew across users/profiles. 5224 if (pi != null) { 5225 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5226 if (numMatch == permissions.length) { 5227 pi.requestedPermissions = permissions; 5228 } else { 5229 pi.requestedPermissions = new String[numMatch]; 5230 numMatch = 0; 5231 for (int i=0; i<permissions.length; i++) { 5232 if (tmp[i]) { 5233 pi.requestedPermissions[numMatch] = permissions[i]; 5234 numMatch++; 5235 } 5236 } 5237 } 5238 } 5239 list.add(pi); 5240 } 5241 } 5242 5243 @Override 5244 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5245 String[] permissions, int flags, int userId) { 5246 if (!sUserManager.exists(userId)) return null; 5247 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5248 5249 // writer 5250 synchronized (mPackages) { 5251 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5252 boolean[] tmpBools = new boolean[permissions.length]; 5253 if (listUninstalled) { 5254 for (PackageSetting ps : mSettings.mPackages.values()) { 5255 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5256 } 5257 } else { 5258 for (PackageParser.Package pkg : mPackages.values()) { 5259 PackageSetting ps = (PackageSetting)pkg.mExtras; 5260 if (ps != null) { 5261 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5262 userId); 5263 } 5264 } 5265 } 5266 5267 return new ParceledListSlice<PackageInfo>(list); 5268 } 5269 } 5270 5271 @Override 5272 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5273 if (!sUserManager.exists(userId)) return null; 5274 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5275 5276 // writer 5277 synchronized (mPackages) { 5278 ArrayList<ApplicationInfo> list; 5279 if (listUninstalled) { 5280 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5281 for (PackageSetting ps : mSettings.mPackages.values()) { 5282 ApplicationInfo ai; 5283 if (ps.pkg != null) { 5284 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5285 ps.readUserState(userId), userId); 5286 } else { 5287 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5288 } 5289 if (ai != null) { 5290 list.add(ai); 5291 } 5292 } 5293 } else { 5294 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5295 for (PackageParser.Package p : mPackages.values()) { 5296 if (p.mExtras != null) { 5297 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5298 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5299 if (ai != null) { 5300 list.add(ai); 5301 } 5302 } 5303 } 5304 } 5305 5306 return new ParceledListSlice<ApplicationInfo>(list); 5307 } 5308 } 5309 5310 public List<ApplicationInfo> getPersistentApplications(int flags) { 5311 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5312 5313 // reader 5314 synchronized (mPackages) { 5315 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5316 final int userId = UserHandle.getCallingUserId(); 5317 while (i.hasNext()) { 5318 final PackageParser.Package p = i.next(); 5319 if (p.applicationInfo != null 5320 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5321 && (!mSafeMode || isSystemApp(p))) { 5322 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5323 if (ps != null) { 5324 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5325 ps.readUserState(userId), userId); 5326 if (ai != null) { 5327 finalList.add(ai); 5328 } 5329 } 5330 } 5331 } 5332 } 5333 5334 return finalList; 5335 } 5336 5337 @Override 5338 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5339 if (!sUserManager.exists(userId)) return null; 5340 // reader 5341 synchronized (mPackages) { 5342 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5343 PackageSetting ps = provider != null 5344 ? mSettings.mPackages.get(provider.owner.packageName) 5345 : null; 5346 return ps != null 5347 && mSettings.isEnabledLPr(provider.info, flags, userId) 5348 && (!mSafeMode || (provider.info.applicationInfo.flags 5349 &ApplicationInfo.FLAG_SYSTEM) != 0) 5350 ? PackageParser.generateProviderInfo(provider, flags, 5351 ps.readUserState(userId), userId) 5352 : null; 5353 } 5354 } 5355 5356 /** 5357 * @deprecated 5358 */ 5359 @Deprecated 5360 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5361 // reader 5362 synchronized (mPackages) { 5363 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5364 .entrySet().iterator(); 5365 final int userId = UserHandle.getCallingUserId(); 5366 while (i.hasNext()) { 5367 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5368 PackageParser.Provider p = entry.getValue(); 5369 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5370 5371 if (ps != null && p.syncable 5372 && (!mSafeMode || (p.info.applicationInfo.flags 5373 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5374 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5375 ps.readUserState(userId), userId); 5376 if (info != null) { 5377 outNames.add(entry.getKey()); 5378 outInfo.add(info); 5379 } 5380 } 5381 } 5382 } 5383 } 5384 5385 @Override 5386 public List<ProviderInfo> queryContentProviders(String processName, 5387 int uid, int flags) { 5388 ArrayList<ProviderInfo> finalList = null; 5389 // reader 5390 synchronized (mPackages) { 5391 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5392 final int userId = processName != null ? 5393 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5394 while (i.hasNext()) { 5395 final PackageParser.Provider p = i.next(); 5396 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5397 if (ps != null && p.info.authority != null 5398 && (processName == null 5399 || (p.info.processName.equals(processName) 5400 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5401 && mSettings.isEnabledLPr(p.info, flags, userId) 5402 && (!mSafeMode 5403 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5404 if (finalList == null) { 5405 finalList = new ArrayList<ProviderInfo>(3); 5406 } 5407 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5408 ps.readUserState(userId), userId); 5409 if (info != null) { 5410 finalList.add(info); 5411 } 5412 } 5413 } 5414 } 5415 5416 if (finalList != null) { 5417 Collections.sort(finalList, mProviderInitOrderSorter); 5418 } 5419 5420 return finalList; 5421 } 5422 5423 @Override 5424 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5425 int flags) { 5426 // reader 5427 synchronized (mPackages) { 5428 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5429 return PackageParser.generateInstrumentationInfo(i, flags); 5430 } 5431 } 5432 5433 @Override 5434 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5435 int flags) { 5436 ArrayList<InstrumentationInfo> finalList = 5437 new ArrayList<InstrumentationInfo>(); 5438 5439 // reader 5440 synchronized (mPackages) { 5441 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5442 while (i.hasNext()) { 5443 final PackageParser.Instrumentation p = i.next(); 5444 if (targetPackage == null 5445 || targetPackage.equals(p.info.targetPackage)) { 5446 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5447 flags); 5448 if (ii != null) { 5449 finalList.add(ii); 5450 } 5451 } 5452 } 5453 } 5454 5455 return finalList; 5456 } 5457 5458 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5459 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5460 if (overlays == null) { 5461 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5462 return; 5463 } 5464 for (PackageParser.Package opkg : overlays.values()) { 5465 // Not much to do if idmap fails: we already logged the error 5466 // and we certainly don't want to abort installation of pkg simply 5467 // because an overlay didn't fit properly. For these reasons, 5468 // ignore the return value of createIdmapForPackagePairLI. 5469 createIdmapForPackagePairLI(pkg, opkg); 5470 } 5471 } 5472 5473 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5474 PackageParser.Package opkg) { 5475 if (!opkg.mTrustedOverlay) { 5476 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5477 opkg.baseCodePath + ": overlay not trusted"); 5478 return false; 5479 } 5480 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5481 if (overlaySet == null) { 5482 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5483 opkg.baseCodePath + " but target package has no known overlays"); 5484 return false; 5485 } 5486 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5487 // TODO: generate idmap for split APKs 5488 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5489 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5490 + opkg.baseCodePath); 5491 return false; 5492 } 5493 PackageParser.Package[] overlayArray = 5494 overlaySet.values().toArray(new PackageParser.Package[0]); 5495 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5496 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5497 return p1.mOverlayPriority - p2.mOverlayPriority; 5498 } 5499 }; 5500 Arrays.sort(overlayArray, cmp); 5501 5502 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5503 int i = 0; 5504 for (PackageParser.Package p : overlayArray) { 5505 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5506 } 5507 return true; 5508 } 5509 5510 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5511 final File[] files = dir.listFiles(); 5512 if (ArrayUtils.isEmpty(files)) { 5513 Log.d(TAG, "No files in app dir " + dir); 5514 return; 5515 } 5516 5517 if (DEBUG_PACKAGE_SCANNING) { 5518 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5519 + " flags=0x" + Integer.toHexString(parseFlags)); 5520 } 5521 5522 for (File file : files) { 5523 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5524 && !PackageInstallerService.isStageName(file.getName()); 5525 if (!isPackage) { 5526 // Ignore entries which are not packages 5527 continue; 5528 } 5529 try { 5530 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5531 scanFlags, currentTime, null); 5532 } catch (PackageManagerException e) { 5533 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5534 5535 // Delete invalid userdata apps 5536 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5537 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5538 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5539 if (file.isDirectory()) { 5540 mInstaller.rmPackageDir(file.getAbsolutePath()); 5541 } else { 5542 file.delete(); 5543 } 5544 } 5545 } 5546 } 5547 } 5548 5549 private static File getSettingsProblemFile() { 5550 File dataDir = Environment.getDataDirectory(); 5551 File systemDir = new File(dataDir, "system"); 5552 File fname = new File(systemDir, "uiderrors.txt"); 5553 return fname; 5554 } 5555 5556 static void reportSettingsProblem(int priority, String msg) { 5557 logCriticalInfo(priority, msg); 5558 } 5559 5560 static void logCriticalInfo(int priority, String msg) { 5561 Slog.println(priority, TAG, msg); 5562 EventLogTags.writePmCriticalInfo(msg); 5563 try { 5564 File fname = getSettingsProblemFile(); 5565 FileOutputStream out = new FileOutputStream(fname, true); 5566 PrintWriter pw = new FastPrintWriter(out); 5567 SimpleDateFormat formatter = new SimpleDateFormat(); 5568 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5569 pw.println(dateString + ": " + msg); 5570 pw.close(); 5571 FileUtils.setPermissions( 5572 fname.toString(), 5573 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5574 -1, -1); 5575 } catch (java.io.IOException e) { 5576 } 5577 } 5578 5579 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5580 PackageParser.Package pkg, File srcFile, int parseFlags) 5581 throws PackageManagerException { 5582 if (ps != null 5583 && ps.codePath.equals(srcFile) 5584 && ps.timeStamp == srcFile.lastModified() 5585 && !isCompatSignatureUpdateNeeded(pkg) 5586 && !isRecoverSignatureUpdateNeeded(pkg)) { 5587 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5588 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5589 ArraySet<PublicKey> signingKs; 5590 synchronized (mPackages) { 5591 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5592 } 5593 if (ps.signatures.mSignatures != null 5594 && ps.signatures.mSignatures.length != 0 5595 && signingKs != null) { 5596 // Optimization: reuse the existing cached certificates 5597 // if the package appears to be unchanged. 5598 pkg.mSignatures = ps.signatures.mSignatures; 5599 pkg.mSigningKeys = signingKs; 5600 return; 5601 } 5602 5603 Slog.w(TAG, "PackageSetting for " + ps.name 5604 + " is missing signatures. Collecting certs again to recover them."); 5605 } else { 5606 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5607 } 5608 5609 try { 5610 pp.collectCertificates(pkg, parseFlags); 5611 pp.collectManifestDigest(pkg); 5612 } catch (PackageParserException e) { 5613 throw PackageManagerException.from(e); 5614 } 5615 } 5616 5617 /* 5618 * Scan a package and return the newly parsed package. 5619 * Returns null in case of errors and the error code is stored in mLastScanError 5620 */ 5621 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5622 long currentTime, UserHandle user) throws PackageManagerException { 5623 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5624 parseFlags |= mDefParseFlags; 5625 PackageParser pp = new PackageParser(); 5626 pp.setSeparateProcesses(mSeparateProcesses); 5627 pp.setOnlyCoreApps(mOnlyCore); 5628 pp.setDisplayMetrics(mMetrics); 5629 5630 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5631 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5632 } 5633 5634 final PackageParser.Package pkg; 5635 try { 5636 pkg = pp.parsePackage(scanFile, parseFlags); 5637 } catch (PackageParserException e) { 5638 throw PackageManagerException.from(e); 5639 } 5640 5641 PackageSetting ps = null; 5642 PackageSetting updatedPkg; 5643 // reader 5644 synchronized (mPackages) { 5645 // Look to see if we already know about this package. 5646 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5647 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5648 // This package has been renamed to its original name. Let's 5649 // use that. 5650 ps = mSettings.peekPackageLPr(oldName); 5651 } 5652 // If there was no original package, see one for the real package name. 5653 if (ps == null) { 5654 ps = mSettings.peekPackageLPr(pkg.packageName); 5655 } 5656 // Check to see if this package could be hiding/updating a system 5657 // package. Must look for it either under the original or real 5658 // package name depending on our state. 5659 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5660 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5661 } 5662 boolean updatedPkgBetter = false; 5663 // First check if this is a system package that may involve an update 5664 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5665 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5666 // it needs to drop FLAG_PRIVILEGED. 5667 if (locationIsPrivileged(scanFile)) { 5668 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5669 } else { 5670 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5671 } 5672 5673 if (ps != null && !ps.codePath.equals(scanFile)) { 5674 // The path has changed from what was last scanned... check the 5675 // version of the new path against what we have stored to determine 5676 // what to do. 5677 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5678 if (pkg.mVersionCode <= ps.versionCode) { 5679 // The system package has been updated and the code path does not match 5680 // Ignore entry. Skip it. 5681 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5682 + " ignored: updated version " + ps.versionCode 5683 + " better than this " + pkg.mVersionCode); 5684 if (!updatedPkg.codePath.equals(scanFile)) { 5685 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5686 + ps.name + " changing from " + updatedPkg.codePathString 5687 + " to " + scanFile); 5688 updatedPkg.codePath = scanFile; 5689 updatedPkg.codePathString = scanFile.toString(); 5690 updatedPkg.resourcePath = scanFile; 5691 updatedPkg.resourcePathString = scanFile.toString(); 5692 } 5693 updatedPkg.pkg = pkg; 5694 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5695 "Package " + ps.name + " at " + scanFile 5696 + " ignored: updated version " + ps.versionCode 5697 + " better than this " + pkg.mVersionCode); 5698 } else { 5699 // The current app on the system partition is better than 5700 // what we have updated to on the data partition; switch 5701 // back to the system partition version. 5702 // At this point, its safely assumed that package installation for 5703 // apps in system partition will go through. If not there won't be a working 5704 // version of the app 5705 // writer 5706 synchronized (mPackages) { 5707 // Just remove the loaded entries from package lists. 5708 mPackages.remove(ps.name); 5709 } 5710 5711 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5712 + " reverting from " + ps.codePathString 5713 + ": new version " + pkg.mVersionCode 5714 + " better than installed " + ps.versionCode); 5715 5716 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5717 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5718 synchronized (mInstallLock) { 5719 args.cleanUpResourcesLI(); 5720 } 5721 synchronized (mPackages) { 5722 mSettings.enableSystemPackageLPw(ps.name); 5723 } 5724 updatedPkgBetter = true; 5725 } 5726 } 5727 } 5728 5729 if (updatedPkg != null) { 5730 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5731 // initially 5732 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5733 5734 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5735 // flag set initially 5736 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5737 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5738 } 5739 } 5740 5741 // Verify certificates against what was last scanned 5742 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5743 5744 /* 5745 * A new system app appeared, but we already had a non-system one of the 5746 * same name installed earlier. 5747 */ 5748 boolean shouldHideSystemApp = false; 5749 if (updatedPkg == null && ps != null 5750 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5751 /* 5752 * Check to make sure the signatures match first. If they don't, 5753 * wipe the installed application and its data. 5754 */ 5755 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5756 != PackageManager.SIGNATURE_MATCH) { 5757 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5758 + " signatures don't match existing userdata copy; removing"); 5759 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5760 ps = null; 5761 } else { 5762 /* 5763 * If the newly-added system app is an older version than the 5764 * already installed version, hide it. It will be scanned later 5765 * and re-added like an update. 5766 */ 5767 if (pkg.mVersionCode <= ps.versionCode) { 5768 shouldHideSystemApp = true; 5769 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5770 + " but new version " + pkg.mVersionCode + " better than installed " 5771 + ps.versionCode + "; hiding system"); 5772 } else { 5773 /* 5774 * The newly found system app is a newer version that the 5775 * one previously installed. Simply remove the 5776 * already-installed application and replace it with our own 5777 * while keeping the application data. 5778 */ 5779 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5780 + " reverting from " + ps.codePathString + ": new version " 5781 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5782 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5783 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5784 synchronized (mInstallLock) { 5785 args.cleanUpResourcesLI(); 5786 } 5787 } 5788 } 5789 } 5790 5791 // The apk is forward locked (not public) if its code and resources 5792 // are kept in different files. (except for app in either system or 5793 // vendor path). 5794 // TODO grab this value from PackageSettings 5795 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5796 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5797 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5798 } 5799 } 5800 5801 // TODO: extend to support forward-locked splits 5802 String resourcePath = null; 5803 String baseResourcePath = null; 5804 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5805 if (ps != null && ps.resourcePathString != null) { 5806 resourcePath = ps.resourcePathString; 5807 baseResourcePath = ps.resourcePathString; 5808 } else { 5809 // Should not happen at all. Just log an error. 5810 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5811 } 5812 } else { 5813 resourcePath = pkg.codePath; 5814 baseResourcePath = pkg.baseCodePath; 5815 } 5816 5817 // Set application objects path explicitly. 5818 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5819 pkg.applicationInfo.setCodePath(pkg.codePath); 5820 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5821 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5822 pkg.applicationInfo.setResourcePath(resourcePath); 5823 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5824 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5825 5826 // Note that we invoke the following method only if we are about to unpack an application 5827 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5828 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5829 5830 /* 5831 * If the system app should be overridden by a previously installed 5832 * data, hide the system app now and let the /data/app scan pick it up 5833 * again. 5834 */ 5835 if (shouldHideSystemApp) { 5836 synchronized (mPackages) { 5837 /* 5838 * We have to grant systems permissions before we hide, because 5839 * grantPermissions will assume the package update is trying to 5840 * expand its permissions. 5841 */ 5842 grantPermissionsLPw(pkg, true, pkg.packageName); 5843 mSettings.disableSystemPackageLPw(pkg.packageName); 5844 } 5845 } 5846 5847 return scannedPkg; 5848 } 5849 5850 private static String fixProcessName(String defProcessName, 5851 String processName, int uid) { 5852 if (processName == null) { 5853 return defProcessName; 5854 } 5855 return processName; 5856 } 5857 5858 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5859 throws PackageManagerException { 5860 if (pkgSetting.signatures.mSignatures != null) { 5861 // Already existing package. Make sure signatures match 5862 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5863 == PackageManager.SIGNATURE_MATCH; 5864 if (!match) { 5865 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5866 == PackageManager.SIGNATURE_MATCH; 5867 } 5868 if (!match) { 5869 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5870 == PackageManager.SIGNATURE_MATCH; 5871 } 5872 if (!match) { 5873 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5874 + pkg.packageName + " signatures do not match the " 5875 + "previously installed version; ignoring!"); 5876 } 5877 } 5878 5879 // Check for shared user signatures 5880 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5881 // Already existing package. Make sure signatures match 5882 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5883 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5884 if (!match) { 5885 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5886 == PackageManager.SIGNATURE_MATCH; 5887 } 5888 if (!match) { 5889 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5890 == PackageManager.SIGNATURE_MATCH; 5891 } 5892 if (!match) { 5893 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5894 "Package " + pkg.packageName 5895 + " has no signatures that match those in shared user " 5896 + pkgSetting.sharedUser.name + "; ignoring!"); 5897 } 5898 } 5899 } 5900 5901 /** 5902 * Enforces that only the system UID or root's UID can call a method exposed 5903 * via Binder. 5904 * 5905 * @param message used as message if SecurityException is thrown 5906 * @throws SecurityException if the caller is not system or root 5907 */ 5908 private static final void enforceSystemOrRoot(String message) { 5909 final int uid = Binder.getCallingUid(); 5910 if (uid != Process.SYSTEM_UID && uid != 0) { 5911 throw new SecurityException(message); 5912 } 5913 } 5914 5915 @Override 5916 public void performBootDexOpt() { 5917 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5918 5919 // Before everything else, see whether we need to fstrim. 5920 try { 5921 IMountService ms = PackageHelper.getMountService(); 5922 if (ms != null) { 5923 final boolean isUpgrade = isUpgrade(); 5924 boolean doTrim = isUpgrade; 5925 if (doTrim) { 5926 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5927 } else { 5928 final long interval = android.provider.Settings.Global.getLong( 5929 mContext.getContentResolver(), 5930 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5931 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5932 if (interval > 0) { 5933 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5934 if (timeSinceLast > interval) { 5935 doTrim = true; 5936 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5937 + "; running immediately"); 5938 } 5939 } 5940 } 5941 if (doTrim) { 5942 if (!isFirstBoot()) { 5943 try { 5944 ActivityManagerNative.getDefault().showBootMessage( 5945 mContext.getResources().getString( 5946 R.string.android_upgrading_fstrim), true); 5947 } catch (RemoteException e) { 5948 } 5949 } 5950 ms.runMaintenance(); 5951 } 5952 } else { 5953 Slog.e(TAG, "Mount service unavailable!"); 5954 } 5955 } catch (RemoteException e) { 5956 // Can't happen; MountService is local 5957 } 5958 5959 final ArraySet<PackageParser.Package> pkgs; 5960 synchronized (mPackages) { 5961 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5962 } 5963 5964 if (pkgs != null) { 5965 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5966 // in case the device runs out of space. 5967 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5968 // Give priority to core apps. 5969 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5970 PackageParser.Package pkg = it.next(); 5971 if (pkg.coreApp) { 5972 if (DEBUG_DEXOPT) { 5973 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5974 } 5975 sortedPkgs.add(pkg); 5976 it.remove(); 5977 } 5978 } 5979 // Give priority to system apps that listen for pre boot complete. 5980 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5981 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5982 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5983 PackageParser.Package pkg = it.next(); 5984 if (pkgNames.contains(pkg.packageName)) { 5985 if (DEBUG_DEXOPT) { 5986 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5987 } 5988 sortedPkgs.add(pkg); 5989 it.remove(); 5990 } 5991 } 5992 // Give priority to system apps. 5993 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5994 PackageParser.Package pkg = it.next(); 5995 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5996 if (DEBUG_DEXOPT) { 5997 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5998 } 5999 sortedPkgs.add(pkg); 6000 it.remove(); 6001 } 6002 } 6003 // Give priority to updated system apps. 6004 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6005 PackageParser.Package pkg = it.next(); 6006 if (pkg.isUpdatedSystemApp()) { 6007 if (DEBUG_DEXOPT) { 6008 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6009 } 6010 sortedPkgs.add(pkg); 6011 it.remove(); 6012 } 6013 } 6014 // Give priority to apps that listen for boot complete. 6015 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6016 pkgNames = getPackageNamesForIntent(intent); 6017 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6018 PackageParser.Package pkg = it.next(); 6019 if (pkgNames.contains(pkg.packageName)) { 6020 if (DEBUG_DEXOPT) { 6021 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6022 } 6023 sortedPkgs.add(pkg); 6024 it.remove(); 6025 } 6026 } 6027 // Filter out packages that aren't recently used. 6028 filterRecentlyUsedApps(pkgs); 6029 // Add all remaining apps. 6030 for (PackageParser.Package pkg : pkgs) { 6031 if (DEBUG_DEXOPT) { 6032 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6033 } 6034 sortedPkgs.add(pkg); 6035 } 6036 6037 // If we want to be lazy, filter everything that wasn't recently used. 6038 if (mLazyDexOpt) { 6039 filterRecentlyUsedApps(sortedPkgs); 6040 } 6041 6042 int i = 0; 6043 int total = sortedPkgs.size(); 6044 File dataDir = Environment.getDataDirectory(); 6045 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6046 if (lowThreshold == 0) { 6047 throw new IllegalStateException("Invalid low memory threshold"); 6048 } 6049 for (PackageParser.Package pkg : sortedPkgs) { 6050 long usableSpace = dataDir.getUsableSpace(); 6051 if (usableSpace < lowThreshold) { 6052 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6053 break; 6054 } 6055 performBootDexOpt(pkg, ++i, total); 6056 } 6057 } 6058 } 6059 6060 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6061 // Filter out packages that aren't recently used. 6062 // 6063 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6064 // should do a full dexopt. 6065 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6066 int total = pkgs.size(); 6067 int skipped = 0; 6068 long now = System.currentTimeMillis(); 6069 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6070 PackageParser.Package pkg = i.next(); 6071 long then = pkg.mLastPackageUsageTimeInMills; 6072 if (then + mDexOptLRUThresholdInMills < now) { 6073 if (DEBUG_DEXOPT) { 6074 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6075 ((then == 0) ? "never" : new Date(then))); 6076 } 6077 i.remove(); 6078 skipped++; 6079 } 6080 } 6081 if (DEBUG_DEXOPT) { 6082 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6083 } 6084 } 6085 } 6086 6087 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6088 List<ResolveInfo> ris = null; 6089 try { 6090 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6091 intent, null, 0, UserHandle.USER_OWNER); 6092 } catch (RemoteException e) { 6093 } 6094 ArraySet<String> pkgNames = new ArraySet<String>(); 6095 if (ris != null) { 6096 for (ResolveInfo ri : ris) { 6097 pkgNames.add(ri.activityInfo.packageName); 6098 } 6099 } 6100 return pkgNames; 6101 } 6102 6103 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6104 if (DEBUG_DEXOPT) { 6105 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6106 } 6107 if (!isFirstBoot()) { 6108 try { 6109 ActivityManagerNative.getDefault().showBootMessage( 6110 mContext.getResources().getString(R.string.android_upgrading_apk, 6111 curr, total), true); 6112 } catch (RemoteException e) { 6113 } 6114 } 6115 PackageParser.Package p = pkg; 6116 synchronized (mInstallLock) { 6117 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6118 false /* force dex */, false /* defer */, true /* include dependencies */); 6119 } 6120 } 6121 6122 @Override 6123 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6124 return performDexOpt(packageName, instructionSet, false); 6125 } 6126 6127 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6128 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6129 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6130 if (!dexopt && !updateUsage) { 6131 // We aren't going to dexopt or update usage, so bail early. 6132 return false; 6133 } 6134 PackageParser.Package p; 6135 final String targetInstructionSet; 6136 synchronized (mPackages) { 6137 p = mPackages.get(packageName); 6138 if (p == null) { 6139 return false; 6140 } 6141 if (updateUsage) { 6142 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6143 } 6144 mPackageUsage.write(false); 6145 if (!dexopt) { 6146 // We aren't going to dexopt, so bail early. 6147 return false; 6148 } 6149 6150 targetInstructionSet = instructionSet != null ? instructionSet : 6151 getPrimaryInstructionSet(p.applicationInfo); 6152 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6153 return false; 6154 } 6155 } 6156 6157 synchronized (mInstallLock) { 6158 final String[] instructionSets = new String[] { targetInstructionSet }; 6159 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6160 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6161 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6162 } 6163 } 6164 6165 public ArraySet<String> getPackagesThatNeedDexOpt() { 6166 ArraySet<String> pkgs = null; 6167 synchronized (mPackages) { 6168 for (PackageParser.Package p : mPackages.values()) { 6169 if (DEBUG_DEXOPT) { 6170 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6171 } 6172 if (!p.mDexOptPerformed.isEmpty()) { 6173 continue; 6174 } 6175 if (pkgs == null) { 6176 pkgs = new ArraySet<String>(); 6177 } 6178 pkgs.add(p.packageName); 6179 } 6180 } 6181 return pkgs; 6182 } 6183 6184 public void shutdown() { 6185 mPackageUsage.write(true); 6186 } 6187 6188 @Override 6189 public void forceDexOpt(String packageName) { 6190 enforceSystemOrRoot("forceDexOpt"); 6191 6192 PackageParser.Package pkg; 6193 synchronized (mPackages) { 6194 pkg = mPackages.get(packageName); 6195 if (pkg == null) { 6196 throw new IllegalArgumentException("Missing package: " + packageName); 6197 } 6198 } 6199 6200 synchronized (mInstallLock) { 6201 final String[] instructionSets = new String[] { 6202 getPrimaryInstructionSet(pkg.applicationInfo) }; 6203 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6204 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6205 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6206 throw new IllegalStateException("Failed to dexopt: " + res); 6207 } 6208 } 6209 } 6210 6211 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6212 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6213 Slog.w(TAG, "Unable to update from " + oldPkg.name 6214 + " to " + newPkg.packageName 6215 + ": old package not in system partition"); 6216 return false; 6217 } else if (mPackages.get(oldPkg.name) != null) { 6218 Slog.w(TAG, "Unable to update from " + oldPkg.name 6219 + " to " + newPkg.packageName 6220 + ": old package still exists"); 6221 return false; 6222 } 6223 return true; 6224 } 6225 6226 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6227 int[] users = sUserManager.getUserIds(); 6228 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6229 if (res < 0) { 6230 return res; 6231 } 6232 for (int user : users) { 6233 if (user != 0) { 6234 res = mInstaller.createUserData(volumeUuid, packageName, 6235 UserHandle.getUid(user, uid), user, seinfo); 6236 if (res < 0) { 6237 return res; 6238 } 6239 } 6240 } 6241 return res; 6242 } 6243 6244 private int removeDataDirsLI(String volumeUuid, String packageName) { 6245 int[] users = sUserManager.getUserIds(); 6246 int res = 0; 6247 for (int user : users) { 6248 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6249 if (resInner < 0) { 6250 res = resInner; 6251 } 6252 } 6253 6254 return res; 6255 } 6256 6257 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6258 int[] users = sUserManager.getUserIds(); 6259 int res = 0; 6260 for (int user : users) { 6261 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6262 if (resInner < 0) { 6263 res = resInner; 6264 } 6265 } 6266 return res; 6267 } 6268 6269 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6270 PackageParser.Package changingLib) { 6271 if (file.path != null) { 6272 usesLibraryFiles.add(file.path); 6273 return; 6274 } 6275 PackageParser.Package p = mPackages.get(file.apk); 6276 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6277 // If we are doing this while in the middle of updating a library apk, 6278 // then we need to make sure to use that new apk for determining the 6279 // dependencies here. (We haven't yet finished committing the new apk 6280 // to the package manager state.) 6281 if (p == null || p.packageName.equals(changingLib.packageName)) { 6282 p = changingLib; 6283 } 6284 } 6285 if (p != null) { 6286 usesLibraryFiles.addAll(p.getAllCodePaths()); 6287 } 6288 } 6289 6290 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6291 PackageParser.Package changingLib) throws PackageManagerException { 6292 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6293 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6294 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6295 for (int i=0; i<N; i++) { 6296 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6297 if (file == null) { 6298 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6299 "Package " + pkg.packageName + " requires unavailable shared library " 6300 + pkg.usesLibraries.get(i) + "; failing!"); 6301 } 6302 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6303 } 6304 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6305 for (int i=0; i<N; i++) { 6306 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6307 if (file == null) { 6308 Slog.w(TAG, "Package " + pkg.packageName 6309 + " desires unavailable shared library " 6310 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6311 } else { 6312 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6313 } 6314 } 6315 N = usesLibraryFiles.size(); 6316 if (N > 0) { 6317 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6318 } else { 6319 pkg.usesLibraryFiles = null; 6320 } 6321 } 6322 } 6323 6324 private static boolean hasString(List<String> list, List<String> which) { 6325 if (list == null) { 6326 return false; 6327 } 6328 for (int i=list.size()-1; i>=0; i--) { 6329 for (int j=which.size()-1; j>=0; j--) { 6330 if (which.get(j).equals(list.get(i))) { 6331 return true; 6332 } 6333 } 6334 } 6335 return false; 6336 } 6337 6338 private void updateAllSharedLibrariesLPw() { 6339 for (PackageParser.Package pkg : mPackages.values()) { 6340 try { 6341 updateSharedLibrariesLPw(pkg, null); 6342 } catch (PackageManagerException e) { 6343 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6344 } 6345 } 6346 } 6347 6348 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6349 PackageParser.Package changingPkg) { 6350 ArrayList<PackageParser.Package> res = null; 6351 for (PackageParser.Package pkg : mPackages.values()) { 6352 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6353 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6354 if (res == null) { 6355 res = new ArrayList<PackageParser.Package>(); 6356 } 6357 res.add(pkg); 6358 try { 6359 updateSharedLibrariesLPw(pkg, changingPkg); 6360 } catch (PackageManagerException e) { 6361 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6362 } 6363 } 6364 } 6365 return res; 6366 } 6367 6368 /** 6369 * Derive the value of the {@code cpuAbiOverride} based on the provided 6370 * value and an optional stored value from the package settings. 6371 */ 6372 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6373 String cpuAbiOverride = null; 6374 6375 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6376 cpuAbiOverride = null; 6377 } else if (abiOverride != null) { 6378 cpuAbiOverride = abiOverride; 6379 } else if (settings != null) { 6380 cpuAbiOverride = settings.cpuAbiOverrideString; 6381 } 6382 6383 return cpuAbiOverride; 6384 } 6385 6386 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6387 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6388 boolean success = false; 6389 try { 6390 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6391 currentTime, user); 6392 success = true; 6393 return res; 6394 } finally { 6395 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6396 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6397 } 6398 } 6399 } 6400 6401 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6402 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6403 final File scanFile = new File(pkg.codePath); 6404 if (pkg.applicationInfo.getCodePath() == null || 6405 pkg.applicationInfo.getResourcePath() == null) { 6406 // Bail out. The resource and code paths haven't been set. 6407 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6408 "Code and resource paths haven't been set correctly"); 6409 } 6410 6411 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6412 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6413 } else { 6414 // Only allow system apps to be flagged as core apps. 6415 pkg.coreApp = false; 6416 } 6417 6418 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6419 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6420 } 6421 6422 if (mCustomResolverComponentName != null && 6423 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6424 setUpCustomResolverActivity(pkg); 6425 } 6426 6427 if (pkg.packageName.equals("android")) { 6428 synchronized (mPackages) { 6429 if (mAndroidApplication != null) { 6430 Slog.w(TAG, "*************************************************"); 6431 Slog.w(TAG, "Core android package being redefined. Skipping."); 6432 Slog.w(TAG, " file=" + scanFile); 6433 Slog.w(TAG, "*************************************************"); 6434 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6435 "Core android package being redefined. Skipping."); 6436 } 6437 6438 // Set up information for our fall-back user intent resolution activity. 6439 mPlatformPackage = pkg; 6440 pkg.mVersionCode = mSdkVersion; 6441 mAndroidApplication = pkg.applicationInfo; 6442 6443 if (!mResolverReplaced) { 6444 mResolveActivity.applicationInfo = mAndroidApplication; 6445 mResolveActivity.name = ResolverActivity.class.getName(); 6446 mResolveActivity.packageName = mAndroidApplication.packageName; 6447 mResolveActivity.processName = "system:ui"; 6448 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6449 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6450 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6451 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6452 mResolveActivity.exported = true; 6453 mResolveActivity.enabled = true; 6454 mResolveInfo.activityInfo = mResolveActivity; 6455 mResolveInfo.priority = 0; 6456 mResolveInfo.preferredOrder = 0; 6457 mResolveInfo.match = 0; 6458 mResolveComponentName = new ComponentName( 6459 mAndroidApplication.packageName, mResolveActivity.name); 6460 } 6461 } 6462 } 6463 6464 if (DEBUG_PACKAGE_SCANNING) { 6465 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6466 Log.d(TAG, "Scanning package " + pkg.packageName); 6467 } 6468 6469 if (mPackages.containsKey(pkg.packageName) 6470 || mSharedLibraries.containsKey(pkg.packageName)) { 6471 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6472 "Application package " + pkg.packageName 6473 + " already installed. Skipping duplicate."); 6474 } 6475 6476 // If we're only installing presumed-existing packages, require that the 6477 // scanned APK is both already known and at the path previously established 6478 // for it. Previously unknown packages we pick up normally, but if we have an 6479 // a priori expectation about this package's install presence, enforce it. 6480 // With a singular exception for new system packages. When an OTA contains 6481 // a new system package, we allow the codepath to change from a system location 6482 // to the user-installed location. If we don't allow this change, any newer, 6483 // user-installed version of the application will be ignored. 6484 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6485 if (mExpectingBetter.containsKey(pkg.packageName)) { 6486 logCriticalInfo(Log.WARN, 6487 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6488 } else { 6489 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6490 if (known != null) { 6491 if (DEBUG_PACKAGE_SCANNING) { 6492 Log.d(TAG, "Examining " + pkg.codePath 6493 + " and requiring known paths " + known.codePathString 6494 + " & " + known.resourcePathString); 6495 } 6496 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6497 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6498 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6499 "Application package " + pkg.packageName 6500 + " found at " + pkg.applicationInfo.getCodePath() 6501 + " but expected at " + known.codePathString + "; ignoring."); 6502 } 6503 } 6504 } 6505 } 6506 6507 // Initialize package source and resource directories 6508 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6509 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6510 6511 SharedUserSetting suid = null; 6512 PackageSetting pkgSetting = null; 6513 6514 if (!isSystemApp(pkg)) { 6515 // Only system apps can use these features. 6516 pkg.mOriginalPackages = null; 6517 pkg.mRealPackage = null; 6518 pkg.mAdoptPermissions = null; 6519 } 6520 6521 // writer 6522 synchronized (mPackages) { 6523 if (pkg.mSharedUserId != null) { 6524 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6525 if (suid == null) { 6526 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6527 "Creating application package " + pkg.packageName 6528 + " for shared user failed"); 6529 } 6530 if (DEBUG_PACKAGE_SCANNING) { 6531 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6532 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6533 + "): packages=" + suid.packages); 6534 } 6535 } 6536 6537 // Check if we are renaming from an original package name. 6538 PackageSetting origPackage = null; 6539 String realName = null; 6540 if (pkg.mOriginalPackages != null) { 6541 // This package may need to be renamed to a previously 6542 // installed name. Let's check on that... 6543 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6544 if (pkg.mOriginalPackages.contains(renamed)) { 6545 // This package had originally been installed as the 6546 // original name, and we have already taken care of 6547 // transitioning to the new one. Just update the new 6548 // one to continue using the old name. 6549 realName = pkg.mRealPackage; 6550 if (!pkg.packageName.equals(renamed)) { 6551 // Callers into this function may have already taken 6552 // care of renaming the package; only do it here if 6553 // it is not already done. 6554 pkg.setPackageName(renamed); 6555 } 6556 6557 } else { 6558 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6559 if ((origPackage = mSettings.peekPackageLPr( 6560 pkg.mOriginalPackages.get(i))) != null) { 6561 // We do have the package already installed under its 6562 // original name... should we use it? 6563 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6564 // New package is not compatible with original. 6565 origPackage = null; 6566 continue; 6567 } else if (origPackage.sharedUser != null) { 6568 // Make sure uid is compatible between packages. 6569 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6570 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6571 + " to " + pkg.packageName + ": old uid " 6572 + origPackage.sharedUser.name 6573 + " differs from " + pkg.mSharedUserId); 6574 origPackage = null; 6575 continue; 6576 } 6577 } else { 6578 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6579 + pkg.packageName + " to old name " + origPackage.name); 6580 } 6581 break; 6582 } 6583 } 6584 } 6585 } 6586 6587 if (mTransferedPackages.contains(pkg.packageName)) { 6588 Slog.w(TAG, "Package " + pkg.packageName 6589 + " was transferred to another, but its .apk remains"); 6590 } 6591 6592 // Just create the setting, don't add it yet. For already existing packages 6593 // the PkgSetting exists already and doesn't have to be created. 6594 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6595 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6596 pkg.applicationInfo.primaryCpuAbi, 6597 pkg.applicationInfo.secondaryCpuAbi, 6598 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6599 user, false); 6600 if (pkgSetting == null) { 6601 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6602 "Creating application package " + pkg.packageName + " failed"); 6603 } 6604 6605 if (pkgSetting.origPackage != null) { 6606 // If we are first transitioning from an original package, 6607 // fix up the new package's name now. We need to do this after 6608 // looking up the package under its new name, so getPackageLP 6609 // can take care of fiddling things correctly. 6610 pkg.setPackageName(origPackage.name); 6611 6612 // File a report about this. 6613 String msg = "New package " + pkgSetting.realName 6614 + " renamed to replace old package " + pkgSetting.name; 6615 reportSettingsProblem(Log.WARN, msg); 6616 6617 // Make a note of it. 6618 mTransferedPackages.add(origPackage.name); 6619 6620 // No longer need to retain this. 6621 pkgSetting.origPackage = null; 6622 } 6623 6624 if (realName != null) { 6625 // Make a note of it. 6626 mTransferedPackages.add(pkg.packageName); 6627 } 6628 6629 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6630 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6631 } 6632 6633 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6634 // Check all shared libraries and map to their actual file path. 6635 // We only do this here for apps not on a system dir, because those 6636 // are the only ones that can fail an install due to this. We 6637 // will take care of the system apps by updating all of their 6638 // library paths after the scan is done. 6639 updateSharedLibrariesLPw(pkg, null); 6640 } 6641 6642 if (mFoundPolicyFile) { 6643 SELinuxMMAC.assignSeinfoValue(pkg); 6644 } 6645 6646 pkg.applicationInfo.uid = pkgSetting.appId; 6647 pkg.mExtras = pkgSetting; 6648 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6649 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6650 // We just determined the app is signed correctly, so bring 6651 // over the latest parsed certs. 6652 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6653 } else { 6654 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6655 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6656 "Package " + pkg.packageName + " upgrade keys do not match the " 6657 + "previously installed version"); 6658 } else { 6659 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6660 String msg = "System package " + pkg.packageName 6661 + " signature changed; retaining data."; 6662 reportSettingsProblem(Log.WARN, msg); 6663 } 6664 } 6665 } else { 6666 try { 6667 verifySignaturesLP(pkgSetting, pkg); 6668 // We just determined the app is signed correctly, so bring 6669 // over the latest parsed certs. 6670 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6671 } catch (PackageManagerException e) { 6672 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6673 throw e; 6674 } 6675 // The signature has changed, but this package is in the system 6676 // image... let's recover! 6677 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6678 // However... if this package is part of a shared user, but it 6679 // doesn't match the signature of the shared user, let's fail. 6680 // What this means is that you can't change the signatures 6681 // associated with an overall shared user, which doesn't seem all 6682 // that unreasonable. 6683 if (pkgSetting.sharedUser != null) { 6684 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6685 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6686 throw new PackageManagerException( 6687 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6688 "Signature mismatch for shared user : " 6689 + pkgSetting.sharedUser); 6690 } 6691 } 6692 // File a report about this. 6693 String msg = "System package " + pkg.packageName 6694 + " signature changed; retaining data."; 6695 reportSettingsProblem(Log.WARN, msg); 6696 } 6697 } 6698 // Verify that this new package doesn't have any content providers 6699 // that conflict with existing packages. Only do this if the 6700 // package isn't already installed, since we don't want to break 6701 // things that are installed. 6702 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6703 final int N = pkg.providers.size(); 6704 int i; 6705 for (i=0; i<N; i++) { 6706 PackageParser.Provider p = pkg.providers.get(i); 6707 if (p.info.authority != null) { 6708 String names[] = p.info.authority.split(";"); 6709 for (int j = 0; j < names.length; j++) { 6710 if (mProvidersByAuthority.containsKey(names[j])) { 6711 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6712 final String otherPackageName = 6713 ((other != null && other.getComponentName() != null) ? 6714 other.getComponentName().getPackageName() : "?"); 6715 throw new PackageManagerException( 6716 INSTALL_FAILED_CONFLICTING_PROVIDER, 6717 "Can't install because provider name " + names[j] 6718 + " (in package " + pkg.applicationInfo.packageName 6719 + ") is already used by " + otherPackageName); 6720 } 6721 } 6722 } 6723 } 6724 } 6725 6726 if (pkg.mAdoptPermissions != null) { 6727 // This package wants to adopt ownership of permissions from 6728 // another package. 6729 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6730 final String origName = pkg.mAdoptPermissions.get(i); 6731 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6732 if (orig != null) { 6733 if (verifyPackageUpdateLPr(orig, pkg)) { 6734 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6735 + pkg.packageName); 6736 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6737 } 6738 } 6739 } 6740 } 6741 } 6742 6743 final String pkgName = pkg.packageName; 6744 6745 final long scanFileTime = scanFile.lastModified(); 6746 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6747 pkg.applicationInfo.processName = fixProcessName( 6748 pkg.applicationInfo.packageName, 6749 pkg.applicationInfo.processName, 6750 pkg.applicationInfo.uid); 6751 6752 File dataPath; 6753 if (mPlatformPackage == pkg) { 6754 // The system package is special. 6755 dataPath = new File(Environment.getDataDirectory(), "system"); 6756 6757 pkg.applicationInfo.dataDir = dataPath.getPath(); 6758 6759 } else { 6760 // This is a normal package, need to make its data directory. 6761 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6762 UserHandle.USER_OWNER, pkg.packageName); 6763 6764 boolean uidError = false; 6765 if (dataPath.exists()) { 6766 int currentUid = 0; 6767 try { 6768 StructStat stat = Os.stat(dataPath.getPath()); 6769 currentUid = stat.st_uid; 6770 } catch (ErrnoException e) { 6771 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6772 } 6773 6774 // If we have mismatched owners for the data path, we have a problem. 6775 if (currentUid != pkg.applicationInfo.uid) { 6776 boolean recovered = false; 6777 if (currentUid == 0) { 6778 // The directory somehow became owned by root. Wow. 6779 // This is probably because the system was stopped while 6780 // installd was in the middle of messing with its libs 6781 // directory. Ask installd to fix that. 6782 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6783 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6784 if (ret >= 0) { 6785 recovered = true; 6786 String msg = "Package " + pkg.packageName 6787 + " unexpectedly changed to uid 0; recovered to " + 6788 + pkg.applicationInfo.uid; 6789 reportSettingsProblem(Log.WARN, msg); 6790 } 6791 } 6792 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6793 || (scanFlags&SCAN_BOOTING) != 0)) { 6794 // If this is a system app, we can at least delete its 6795 // current data so the application will still work. 6796 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6797 if (ret >= 0) { 6798 // TODO: Kill the processes first 6799 // Old data gone! 6800 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6801 ? "System package " : "Third party package "; 6802 String msg = prefix + pkg.packageName 6803 + " has changed from uid: " 6804 + currentUid + " to " 6805 + pkg.applicationInfo.uid + "; old data erased"; 6806 reportSettingsProblem(Log.WARN, msg); 6807 recovered = true; 6808 6809 // And now re-install the app. 6810 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6811 pkg.applicationInfo.seinfo); 6812 if (ret == -1) { 6813 // Ack should not happen! 6814 msg = prefix + pkg.packageName 6815 + " could not have data directory re-created after delete."; 6816 reportSettingsProblem(Log.WARN, msg); 6817 throw new PackageManagerException( 6818 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6819 } 6820 } 6821 if (!recovered) { 6822 mHasSystemUidErrors = true; 6823 } 6824 } else if (!recovered) { 6825 // If we allow this install to proceed, we will be broken. 6826 // Abort, abort! 6827 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6828 "scanPackageLI"); 6829 } 6830 if (!recovered) { 6831 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6832 + pkg.applicationInfo.uid + "/fs_" 6833 + currentUid; 6834 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6835 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6836 String msg = "Package " + pkg.packageName 6837 + " has mismatched uid: " 6838 + currentUid + " on disk, " 6839 + pkg.applicationInfo.uid + " in settings"; 6840 // writer 6841 synchronized (mPackages) { 6842 mSettings.mReadMessages.append(msg); 6843 mSettings.mReadMessages.append('\n'); 6844 uidError = true; 6845 if (!pkgSetting.uidError) { 6846 reportSettingsProblem(Log.ERROR, msg); 6847 } 6848 } 6849 } 6850 } 6851 pkg.applicationInfo.dataDir = dataPath.getPath(); 6852 if (mShouldRestoreconData) { 6853 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6854 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6855 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6856 } 6857 } else { 6858 if (DEBUG_PACKAGE_SCANNING) { 6859 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6860 Log.v(TAG, "Want this data dir: " + dataPath); 6861 } 6862 //invoke installer to do the actual installation 6863 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6864 pkg.applicationInfo.seinfo); 6865 if (ret < 0) { 6866 // Error from installer 6867 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6868 "Unable to create data dirs [errorCode=" + ret + "]"); 6869 } 6870 6871 if (dataPath.exists()) { 6872 pkg.applicationInfo.dataDir = dataPath.getPath(); 6873 } else { 6874 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6875 pkg.applicationInfo.dataDir = null; 6876 } 6877 } 6878 6879 pkgSetting.uidError = uidError; 6880 } 6881 6882 final String path = scanFile.getPath(); 6883 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6884 6885 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6886 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6887 6888 // Some system apps still use directory structure for native libraries 6889 // in which case we might end up not detecting abi solely based on apk 6890 // structure. Try to detect abi based on directory structure. 6891 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6892 pkg.applicationInfo.primaryCpuAbi == null) { 6893 setBundledAppAbisAndRoots(pkg, pkgSetting); 6894 setNativeLibraryPaths(pkg); 6895 } 6896 6897 } else { 6898 if ((scanFlags & SCAN_MOVE) != 0) { 6899 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6900 // but we already have this packages package info in the PackageSetting. We just 6901 // use that and derive the native library path based on the new codepath. 6902 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6903 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6904 } 6905 6906 // Set native library paths again. For moves, the path will be updated based on the 6907 // ABIs we've determined above. For non-moves, the path will be updated based on the 6908 // ABIs we determined during compilation, but the path will depend on the final 6909 // package path (after the rename away from the stage path). 6910 setNativeLibraryPaths(pkg); 6911 } 6912 6913 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6914 final int[] userIds = sUserManager.getUserIds(); 6915 synchronized (mInstallLock) { 6916 // Make sure all user data directories are ready to roll; we're okay 6917 // if they already exist 6918 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6919 for (int userId : userIds) { 6920 if (userId != 0) { 6921 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6922 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6923 pkg.applicationInfo.seinfo); 6924 } 6925 } 6926 } 6927 6928 // Create a native library symlink only if we have native libraries 6929 // and if the native libraries are 32 bit libraries. We do not provide 6930 // this symlink for 64 bit libraries. 6931 if (pkg.applicationInfo.primaryCpuAbi != null && 6932 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6933 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6934 for (int userId : userIds) { 6935 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6936 nativeLibPath, userId) < 0) { 6937 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6938 "Failed linking native library dir (user=" + userId + ")"); 6939 } 6940 } 6941 } 6942 } 6943 6944 // This is a special case for the "system" package, where the ABI is 6945 // dictated by the zygote configuration (and init.rc). We should keep track 6946 // of this ABI so that we can deal with "normal" applications that run under 6947 // the same UID correctly. 6948 if (mPlatformPackage == pkg) { 6949 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6950 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6951 } 6952 6953 // If there's a mismatch between the abi-override in the package setting 6954 // and the abiOverride specified for the install. Warn about this because we 6955 // would've already compiled the app without taking the package setting into 6956 // account. 6957 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6958 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6959 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6960 " for package: " + pkg.packageName); 6961 } 6962 } 6963 6964 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6965 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6966 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6967 6968 // Copy the derived override back to the parsed package, so that we can 6969 // update the package settings accordingly. 6970 pkg.cpuAbiOverride = cpuAbiOverride; 6971 6972 if (DEBUG_ABI_SELECTION) { 6973 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6974 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6975 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6976 } 6977 6978 // Push the derived path down into PackageSettings so we know what to 6979 // clean up at uninstall time. 6980 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6981 6982 if (DEBUG_ABI_SELECTION) { 6983 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6984 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6985 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6986 } 6987 6988 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6989 // We don't do this here during boot because we can do it all 6990 // at once after scanning all existing packages. 6991 // 6992 // We also do this *before* we perform dexopt on this package, so that 6993 // we can avoid redundant dexopts, and also to make sure we've got the 6994 // code and package path correct. 6995 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6996 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6997 } 6998 6999 if ((scanFlags & SCAN_NO_DEX) == 0) { 7000 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7001 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7002 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7003 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7004 } 7005 } 7006 if (mFactoryTest && pkg.requestedPermissions.contains( 7007 android.Manifest.permission.FACTORY_TEST)) { 7008 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7009 } 7010 7011 ArrayList<PackageParser.Package> clientLibPkgs = null; 7012 7013 // writer 7014 synchronized (mPackages) { 7015 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7016 // Only system apps can add new shared libraries. 7017 if (pkg.libraryNames != null) { 7018 for (int i=0; i<pkg.libraryNames.size(); i++) { 7019 String name = pkg.libraryNames.get(i); 7020 boolean allowed = false; 7021 if (pkg.isUpdatedSystemApp()) { 7022 // New library entries can only be added through the 7023 // system image. This is important to get rid of a lot 7024 // of nasty edge cases: for example if we allowed a non- 7025 // system update of the app to add a library, then uninstalling 7026 // the update would make the library go away, and assumptions 7027 // we made such as through app install filtering would now 7028 // have allowed apps on the device which aren't compatible 7029 // with it. Better to just have the restriction here, be 7030 // conservative, and create many fewer cases that can negatively 7031 // impact the user experience. 7032 final PackageSetting sysPs = mSettings 7033 .getDisabledSystemPkgLPr(pkg.packageName); 7034 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7035 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7036 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7037 allowed = true; 7038 allowed = true; 7039 break; 7040 } 7041 } 7042 } 7043 } else { 7044 allowed = true; 7045 } 7046 if (allowed) { 7047 if (!mSharedLibraries.containsKey(name)) { 7048 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7049 } else if (!name.equals(pkg.packageName)) { 7050 Slog.w(TAG, "Package " + pkg.packageName + " library " 7051 + name + " already exists; skipping"); 7052 } 7053 } else { 7054 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7055 + name + " that is not declared on system image; skipping"); 7056 } 7057 } 7058 if ((scanFlags&SCAN_BOOTING) == 0) { 7059 // If we are not booting, we need to update any applications 7060 // that are clients of our shared library. If we are booting, 7061 // this will all be done once the scan is complete. 7062 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7063 } 7064 } 7065 } 7066 } 7067 7068 // We also need to dexopt any apps that are dependent on this library. Note that 7069 // if these fail, we should abort the install since installing the library will 7070 // result in some apps being broken. 7071 if (clientLibPkgs != null) { 7072 if ((scanFlags & SCAN_NO_DEX) == 0) { 7073 for (int i = 0; i < clientLibPkgs.size(); i++) { 7074 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7075 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7076 null /* instruction sets */, forceDex, 7077 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7078 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7079 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7080 "scanPackageLI failed to dexopt clientLibPkgs"); 7081 } 7082 } 7083 } 7084 } 7085 7086 // Also need to kill any apps that are dependent on the library. 7087 if (clientLibPkgs != null) { 7088 for (int i=0; i<clientLibPkgs.size(); i++) { 7089 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7090 killApplication(clientPkg.applicationInfo.packageName, 7091 clientPkg.applicationInfo.uid, "update lib"); 7092 } 7093 } 7094 7095 // Make sure we're not adding any bogus keyset info 7096 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7097 ksms.assertScannedPackageValid(pkg); 7098 7099 // writer 7100 synchronized (mPackages) { 7101 // We don't expect installation to fail beyond this point 7102 7103 // Add the new setting to mSettings 7104 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7105 // Add the new setting to mPackages 7106 mPackages.put(pkg.applicationInfo.packageName, pkg); 7107 // Make sure we don't accidentally delete its data. 7108 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7109 while (iter.hasNext()) { 7110 PackageCleanItem item = iter.next(); 7111 if (pkgName.equals(item.packageName)) { 7112 iter.remove(); 7113 } 7114 } 7115 7116 // Take care of first install / last update times. 7117 if (currentTime != 0) { 7118 if (pkgSetting.firstInstallTime == 0) { 7119 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7120 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7121 pkgSetting.lastUpdateTime = currentTime; 7122 } 7123 } else if (pkgSetting.firstInstallTime == 0) { 7124 // We need *something*. Take time time stamp of the file. 7125 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7126 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7127 if (scanFileTime != pkgSetting.timeStamp) { 7128 // A package on the system image has changed; consider this 7129 // to be an update. 7130 pkgSetting.lastUpdateTime = scanFileTime; 7131 } 7132 } 7133 7134 // Add the package's KeySets to the global KeySetManagerService 7135 ksms.addScannedPackageLPw(pkg); 7136 7137 int N = pkg.providers.size(); 7138 StringBuilder r = null; 7139 int i; 7140 for (i=0; i<N; i++) { 7141 PackageParser.Provider p = pkg.providers.get(i); 7142 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7143 p.info.processName, pkg.applicationInfo.uid); 7144 mProviders.addProvider(p); 7145 p.syncable = p.info.isSyncable; 7146 if (p.info.authority != null) { 7147 String names[] = p.info.authority.split(";"); 7148 p.info.authority = null; 7149 for (int j = 0; j < names.length; j++) { 7150 if (j == 1 && p.syncable) { 7151 // We only want the first authority for a provider to possibly be 7152 // syncable, so if we already added this provider using a different 7153 // authority clear the syncable flag. We copy the provider before 7154 // changing it because the mProviders object contains a reference 7155 // to a provider that we don't want to change. 7156 // Only do this for the second authority since the resulting provider 7157 // object can be the same for all future authorities for this provider. 7158 p = new PackageParser.Provider(p); 7159 p.syncable = false; 7160 } 7161 if (!mProvidersByAuthority.containsKey(names[j])) { 7162 mProvidersByAuthority.put(names[j], p); 7163 if (p.info.authority == null) { 7164 p.info.authority = names[j]; 7165 } else { 7166 p.info.authority = p.info.authority + ";" + names[j]; 7167 } 7168 if (DEBUG_PACKAGE_SCANNING) { 7169 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7170 Log.d(TAG, "Registered content provider: " + names[j] 7171 + ", className = " + p.info.name + ", isSyncable = " 7172 + p.info.isSyncable); 7173 } 7174 } else { 7175 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7176 Slog.w(TAG, "Skipping provider name " + names[j] + 7177 " (in package " + pkg.applicationInfo.packageName + 7178 "): name already used by " 7179 + ((other != null && other.getComponentName() != null) 7180 ? other.getComponentName().getPackageName() : "?")); 7181 } 7182 } 7183 } 7184 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7185 if (r == null) { 7186 r = new StringBuilder(256); 7187 } else { 7188 r.append(' '); 7189 } 7190 r.append(p.info.name); 7191 } 7192 } 7193 if (r != null) { 7194 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7195 } 7196 7197 N = pkg.services.size(); 7198 r = null; 7199 for (i=0; i<N; i++) { 7200 PackageParser.Service s = pkg.services.get(i); 7201 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7202 s.info.processName, pkg.applicationInfo.uid); 7203 mServices.addService(s); 7204 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7205 if (r == null) { 7206 r = new StringBuilder(256); 7207 } else { 7208 r.append(' '); 7209 } 7210 r.append(s.info.name); 7211 } 7212 } 7213 if (r != null) { 7214 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7215 } 7216 7217 N = pkg.receivers.size(); 7218 r = null; 7219 for (i=0; i<N; i++) { 7220 PackageParser.Activity a = pkg.receivers.get(i); 7221 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7222 a.info.processName, pkg.applicationInfo.uid); 7223 mReceivers.addActivity(a, "receiver"); 7224 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7225 if (r == null) { 7226 r = new StringBuilder(256); 7227 } else { 7228 r.append(' '); 7229 } 7230 r.append(a.info.name); 7231 } 7232 } 7233 if (r != null) { 7234 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7235 } 7236 7237 N = pkg.activities.size(); 7238 r = null; 7239 for (i=0; i<N; i++) { 7240 PackageParser.Activity a = pkg.activities.get(i); 7241 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7242 a.info.processName, pkg.applicationInfo.uid); 7243 mActivities.addActivity(a, "activity"); 7244 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7245 if (r == null) { 7246 r = new StringBuilder(256); 7247 } else { 7248 r.append(' '); 7249 } 7250 r.append(a.info.name); 7251 } 7252 } 7253 if (r != null) { 7254 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7255 } 7256 7257 N = pkg.permissionGroups.size(); 7258 r = null; 7259 for (i=0; i<N; i++) { 7260 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7261 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7262 if (cur == null) { 7263 mPermissionGroups.put(pg.info.name, pg); 7264 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7265 if (r == null) { 7266 r = new StringBuilder(256); 7267 } else { 7268 r.append(' '); 7269 } 7270 r.append(pg.info.name); 7271 } 7272 } else { 7273 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7274 + pg.info.packageName + " ignored: original from " 7275 + cur.info.packageName); 7276 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7277 if (r == null) { 7278 r = new StringBuilder(256); 7279 } else { 7280 r.append(' '); 7281 } 7282 r.append("DUP:"); 7283 r.append(pg.info.name); 7284 } 7285 } 7286 } 7287 if (r != null) { 7288 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7289 } 7290 7291 N = pkg.permissions.size(); 7292 r = null; 7293 for (i=0; i<N; i++) { 7294 PackageParser.Permission p = pkg.permissions.get(i); 7295 7296 // Now that permission groups have a special meaning, we ignore permission 7297 // groups for legacy apps to prevent unexpected behavior. In particular, 7298 // permissions for one app being granted to someone just becuase they happen 7299 // to be in a group defined by another app (before this had no implications). 7300 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7301 p.group = mPermissionGroups.get(p.info.group); 7302 // Warn for a permission in an unknown group. 7303 if (p.info.group != null && p.group == null) { 7304 Slog.w(TAG, "Permission " + p.info.name + " from package " 7305 + p.info.packageName + " in an unknown group " + p.info.group); 7306 } 7307 } 7308 7309 ArrayMap<String, BasePermission> permissionMap = 7310 p.tree ? mSettings.mPermissionTrees 7311 : mSettings.mPermissions; 7312 BasePermission bp = permissionMap.get(p.info.name); 7313 7314 // Allow system apps to redefine non-system permissions 7315 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7316 final boolean currentOwnerIsSystem = (bp.perm != null 7317 && isSystemApp(bp.perm.owner)); 7318 if (isSystemApp(p.owner)) { 7319 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7320 // It's a built-in permission and no owner, take ownership now 7321 bp.packageSetting = pkgSetting; 7322 bp.perm = p; 7323 bp.uid = pkg.applicationInfo.uid; 7324 bp.sourcePackage = p.info.packageName; 7325 } else if (!currentOwnerIsSystem) { 7326 String msg = "New decl " + p.owner + " of permission " 7327 + p.info.name + " is system; overriding " + bp.sourcePackage; 7328 reportSettingsProblem(Log.WARN, msg); 7329 bp = null; 7330 } 7331 } 7332 } 7333 7334 if (bp == null) { 7335 bp = new BasePermission(p.info.name, p.info.packageName, 7336 BasePermission.TYPE_NORMAL); 7337 permissionMap.put(p.info.name, bp); 7338 } 7339 7340 if (bp.perm == null) { 7341 if (bp.sourcePackage == null 7342 || bp.sourcePackage.equals(p.info.packageName)) { 7343 BasePermission tree = findPermissionTreeLP(p.info.name); 7344 if (tree == null 7345 || tree.sourcePackage.equals(p.info.packageName)) { 7346 bp.packageSetting = pkgSetting; 7347 bp.perm = p; 7348 bp.uid = pkg.applicationInfo.uid; 7349 bp.sourcePackage = p.info.packageName; 7350 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7351 if (r == null) { 7352 r = new StringBuilder(256); 7353 } else { 7354 r.append(' '); 7355 } 7356 r.append(p.info.name); 7357 } 7358 } else { 7359 Slog.w(TAG, "Permission " + p.info.name + " from package " 7360 + p.info.packageName + " ignored: base tree " 7361 + tree.name + " is from package " 7362 + tree.sourcePackage); 7363 } 7364 } else { 7365 Slog.w(TAG, "Permission " + p.info.name + " from package " 7366 + p.info.packageName + " ignored: original from " 7367 + bp.sourcePackage); 7368 } 7369 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7370 if (r == null) { 7371 r = new StringBuilder(256); 7372 } else { 7373 r.append(' '); 7374 } 7375 r.append("DUP:"); 7376 r.append(p.info.name); 7377 } 7378 if (bp.perm == p) { 7379 bp.protectionLevel = p.info.protectionLevel; 7380 } 7381 } 7382 7383 if (r != null) { 7384 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7385 } 7386 7387 N = pkg.instrumentation.size(); 7388 r = null; 7389 for (i=0; i<N; i++) { 7390 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7391 a.info.packageName = pkg.applicationInfo.packageName; 7392 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7393 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7394 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7395 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7396 a.info.dataDir = pkg.applicationInfo.dataDir; 7397 7398 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7399 // need other information about the application, like the ABI and what not ? 7400 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7401 mInstrumentation.put(a.getComponentName(), a); 7402 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7403 if (r == null) { 7404 r = new StringBuilder(256); 7405 } else { 7406 r.append(' '); 7407 } 7408 r.append(a.info.name); 7409 } 7410 } 7411 if (r != null) { 7412 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7413 } 7414 7415 if (pkg.protectedBroadcasts != null) { 7416 N = pkg.protectedBroadcasts.size(); 7417 for (i=0; i<N; i++) { 7418 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7419 } 7420 } 7421 7422 pkgSetting.setTimeStamp(scanFileTime); 7423 7424 // Create idmap files for pairs of (packages, overlay packages). 7425 // Note: "android", ie framework-res.apk, is handled by native layers. 7426 if (pkg.mOverlayTarget != null) { 7427 // This is an overlay package. 7428 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7429 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7430 mOverlays.put(pkg.mOverlayTarget, 7431 new ArrayMap<String, PackageParser.Package>()); 7432 } 7433 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7434 map.put(pkg.packageName, pkg); 7435 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7436 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7437 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7438 "scanPackageLI failed to createIdmap"); 7439 } 7440 } 7441 } else if (mOverlays.containsKey(pkg.packageName) && 7442 !pkg.packageName.equals("android")) { 7443 // This is a regular package, with one or more known overlay packages. 7444 createIdmapsForPackageLI(pkg); 7445 } 7446 } 7447 7448 return pkg; 7449 } 7450 7451 /** 7452 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7453 * is derived purely on the basis of the contents of {@code scanFile} and 7454 * {@code cpuAbiOverride}. 7455 * 7456 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7457 */ 7458 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7459 String cpuAbiOverride, boolean extractLibs) 7460 throws PackageManagerException { 7461 // TODO: We can probably be smarter about this stuff. For installed apps, 7462 // we can calculate this information at install time once and for all. For 7463 // system apps, we can probably assume that this information doesn't change 7464 // after the first boot scan. As things stand, we do lots of unnecessary work. 7465 7466 // Give ourselves some initial paths; we'll come back for another 7467 // pass once we've determined ABI below. 7468 setNativeLibraryPaths(pkg); 7469 7470 // We would never need to extract libs for forward-locked and external packages, 7471 // since the container service will do it for us. We shouldn't attempt to 7472 // extract libs from system app when it was not updated. 7473 if (pkg.isForwardLocked() || isExternal(pkg) || 7474 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7475 extractLibs = false; 7476 } 7477 7478 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7479 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7480 7481 NativeLibraryHelper.Handle handle = null; 7482 try { 7483 handle = NativeLibraryHelper.Handle.create(pkg); 7484 // TODO(multiArch): This can be null for apps that didn't go through the 7485 // usual installation process. We can calculate it again, like we 7486 // do during install time. 7487 // 7488 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7489 // unnecessary. 7490 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7491 7492 // Null out the abis so that they can be recalculated. 7493 pkg.applicationInfo.primaryCpuAbi = null; 7494 pkg.applicationInfo.secondaryCpuAbi = null; 7495 if (isMultiArch(pkg.applicationInfo)) { 7496 // Warn if we've set an abiOverride for multi-lib packages.. 7497 // By definition, we need to copy both 32 and 64 bit libraries for 7498 // such packages. 7499 if (pkg.cpuAbiOverride != null 7500 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7501 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7502 } 7503 7504 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7505 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7506 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7507 if (extractLibs) { 7508 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7509 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7510 useIsaSpecificSubdirs); 7511 } else { 7512 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7513 } 7514 } 7515 7516 maybeThrowExceptionForMultiArchCopy( 7517 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7518 7519 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7520 if (extractLibs) { 7521 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7522 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7523 useIsaSpecificSubdirs); 7524 } else { 7525 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7526 } 7527 } 7528 7529 maybeThrowExceptionForMultiArchCopy( 7530 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7531 7532 if (abi64 >= 0) { 7533 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7534 } 7535 7536 if (abi32 >= 0) { 7537 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7538 if (abi64 >= 0) { 7539 pkg.applicationInfo.secondaryCpuAbi = abi; 7540 } else { 7541 pkg.applicationInfo.primaryCpuAbi = abi; 7542 } 7543 } 7544 } else { 7545 String[] abiList = (cpuAbiOverride != null) ? 7546 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7547 7548 // Enable gross and lame hacks for apps that are built with old 7549 // SDK tools. We must scan their APKs for renderscript bitcode and 7550 // not launch them if it's present. Don't bother checking on devices 7551 // that don't have 64 bit support. 7552 boolean needsRenderScriptOverride = false; 7553 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7554 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7555 abiList = Build.SUPPORTED_32_BIT_ABIS; 7556 needsRenderScriptOverride = true; 7557 } 7558 7559 final int copyRet; 7560 if (extractLibs) { 7561 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7562 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7563 } else { 7564 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7565 } 7566 7567 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7568 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7569 "Error unpackaging native libs for app, errorCode=" + copyRet); 7570 } 7571 7572 if (copyRet >= 0) { 7573 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7574 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7575 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7576 } else if (needsRenderScriptOverride) { 7577 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7578 } 7579 } 7580 } catch (IOException ioe) { 7581 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7582 } finally { 7583 IoUtils.closeQuietly(handle); 7584 } 7585 7586 // Now that we've calculated the ABIs and determined if it's an internal app, 7587 // we will go ahead and populate the nativeLibraryPath. 7588 setNativeLibraryPaths(pkg); 7589 } 7590 7591 /** 7592 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7593 * i.e, so that all packages can be run inside a single process if required. 7594 * 7595 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7596 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7597 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7598 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7599 * updating a package that belongs to a shared user. 7600 * 7601 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7602 * adds unnecessary complexity. 7603 */ 7604 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7605 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7606 String requiredInstructionSet = null; 7607 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7608 requiredInstructionSet = VMRuntime.getInstructionSet( 7609 scannedPackage.applicationInfo.primaryCpuAbi); 7610 } 7611 7612 PackageSetting requirer = null; 7613 for (PackageSetting ps : packagesForUser) { 7614 // If packagesForUser contains scannedPackage, we skip it. This will happen 7615 // when scannedPackage is an update of an existing package. Without this check, 7616 // we will never be able to change the ABI of any package belonging to a shared 7617 // user, even if it's compatible with other packages. 7618 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7619 if (ps.primaryCpuAbiString == null) { 7620 continue; 7621 } 7622 7623 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7624 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7625 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7626 // this but there's not much we can do. 7627 String errorMessage = "Instruction set mismatch, " 7628 + ((requirer == null) ? "[caller]" : requirer) 7629 + " requires " + requiredInstructionSet + " whereas " + ps 7630 + " requires " + instructionSet; 7631 Slog.w(TAG, errorMessage); 7632 } 7633 7634 if (requiredInstructionSet == null) { 7635 requiredInstructionSet = instructionSet; 7636 requirer = ps; 7637 } 7638 } 7639 } 7640 7641 if (requiredInstructionSet != null) { 7642 String adjustedAbi; 7643 if (requirer != null) { 7644 // requirer != null implies that either scannedPackage was null or that scannedPackage 7645 // did not require an ABI, in which case we have to adjust scannedPackage to match 7646 // the ABI of the set (which is the same as requirer's ABI) 7647 adjustedAbi = requirer.primaryCpuAbiString; 7648 if (scannedPackage != null) { 7649 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7650 } 7651 } else { 7652 // requirer == null implies that we're updating all ABIs in the set to 7653 // match scannedPackage. 7654 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7655 } 7656 7657 for (PackageSetting ps : packagesForUser) { 7658 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7659 if (ps.primaryCpuAbiString != null) { 7660 continue; 7661 } 7662 7663 ps.primaryCpuAbiString = adjustedAbi; 7664 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7665 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7666 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7667 7668 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7669 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7670 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7671 ps.primaryCpuAbiString = null; 7672 ps.pkg.applicationInfo.primaryCpuAbi = null; 7673 return; 7674 } else { 7675 mInstaller.rmdex(ps.codePathString, 7676 getDexCodeInstructionSet(getPreferredInstructionSet())); 7677 } 7678 } 7679 } 7680 } 7681 } 7682 } 7683 7684 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7685 synchronized (mPackages) { 7686 mResolverReplaced = true; 7687 // Set up information for custom user intent resolution activity. 7688 mResolveActivity.applicationInfo = pkg.applicationInfo; 7689 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7690 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7691 mResolveActivity.processName = pkg.applicationInfo.packageName; 7692 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7693 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7694 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7695 mResolveActivity.theme = 0; 7696 mResolveActivity.exported = true; 7697 mResolveActivity.enabled = true; 7698 mResolveInfo.activityInfo = mResolveActivity; 7699 mResolveInfo.priority = 0; 7700 mResolveInfo.preferredOrder = 0; 7701 mResolveInfo.match = 0; 7702 mResolveComponentName = mCustomResolverComponentName; 7703 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7704 mResolveComponentName); 7705 } 7706 } 7707 7708 private static String calculateBundledApkRoot(final String codePathString) { 7709 final File codePath = new File(codePathString); 7710 final File codeRoot; 7711 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7712 codeRoot = Environment.getRootDirectory(); 7713 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7714 codeRoot = Environment.getOemDirectory(); 7715 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7716 codeRoot = Environment.getVendorDirectory(); 7717 } else { 7718 // Unrecognized code path; take its top real segment as the apk root: 7719 // e.g. /something/app/blah.apk => /something 7720 try { 7721 File f = codePath.getCanonicalFile(); 7722 File parent = f.getParentFile(); // non-null because codePath is a file 7723 File tmp; 7724 while ((tmp = parent.getParentFile()) != null) { 7725 f = parent; 7726 parent = tmp; 7727 } 7728 codeRoot = f; 7729 Slog.w(TAG, "Unrecognized code path " 7730 + codePath + " - using " + codeRoot); 7731 } catch (IOException e) { 7732 // Can't canonicalize the code path -- shenanigans? 7733 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7734 return Environment.getRootDirectory().getPath(); 7735 } 7736 } 7737 return codeRoot.getPath(); 7738 } 7739 7740 /** 7741 * Derive and set the location of native libraries for the given package, 7742 * which varies depending on where and how the package was installed. 7743 */ 7744 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7745 final ApplicationInfo info = pkg.applicationInfo; 7746 final String codePath = pkg.codePath; 7747 final File codeFile = new File(codePath); 7748 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7749 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7750 7751 info.nativeLibraryRootDir = null; 7752 info.nativeLibraryRootRequiresIsa = false; 7753 info.nativeLibraryDir = null; 7754 info.secondaryNativeLibraryDir = null; 7755 7756 if (isApkFile(codeFile)) { 7757 // Monolithic install 7758 if (bundledApp) { 7759 // If "/system/lib64/apkname" exists, assume that is the per-package 7760 // native library directory to use; otherwise use "/system/lib/apkname". 7761 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7762 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7763 getPrimaryInstructionSet(info)); 7764 7765 // This is a bundled system app so choose the path based on the ABI. 7766 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7767 // is just the default path. 7768 final String apkName = deriveCodePathName(codePath); 7769 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7770 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7771 apkName).getAbsolutePath(); 7772 7773 if (info.secondaryCpuAbi != null) { 7774 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7775 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7776 secondaryLibDir, apkName).getAbsolutePath(); 7777 } 7778 } else if (asecApp) { 7779 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7780 .getAbsolutePath(); 7781 } else { 7782 final String apkName = deriveCodePathName(codePath); 7783 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7784 .getAbsolutePath(); 7785 } 7786 7787 info.nativeLibraryRootRequiresIsa = false; 7788 info.nativeLibraryDir = info.nativeLibraryRootDir; 7789 } else { 7790 // Cluster install 7791 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7792 info.nativeLibraryRootRequiresIsa = true; 7793 7794 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7795 getPrimaryInstructionSet(info)).getAbsolutePath(); 7796 7797 if (info.secondaryCpuAbi != null) { 7798 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7799 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7800 } 7801 } 7802 } 7803 7804 /** 7805 * Calculate the abis and roots for a bundled app. These can uniquely 7806 * be determined from the contents of the system partition, i.e whether 7807 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7808 * of this information, and instead assume that the system was built 7809 * sensibly. 7810 */ 7811 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7812 PackageSetting pkgSetting) { 7813 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7814 7815 // If "/system/lib64/apkname" exists, assume that is the per-package 7816 // native library directory to use; otherwise use "/system/lib/apkname". 7817 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7818 setBundledAppAbi(pkg, apkRoot, apkName); 7819 // pkgSetting might be null during rescan following uninstall of updates 7820 // to a bundled app, so accommodate that possibility. The settings in 7821 // that case will be established later from the parsed package. 7822 // 7823 // If the settings aren't null, sync them up with what we've just derived. 7824 // note that apkRoot isn't stored in the package settings. 7825 if (pkgSetting != null) { 7826 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7827 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7828 } 7829 } 7830 7831 /** 7832 * Deduces the ABI of a bundled app and sets the relevant fields on the 7833 * parsed pkg object. 7834 * 7835 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7836 * under which system libraries are installed. 7837 * @param apkName the name of the installed package. 7838 */ 7839 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7840 final File codeFile = new File(pkg.codePath); 7841 7842 final boolean has64BitLibs; 7843 final boolean has32BitLibs; 7844 if (isApkFile(codeFile)) { 7845 // Monolithic install 7846 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7847 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7848 } else { 7849 // Cluster install 7850 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7851 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7852 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7853 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7854 has64BitLibs = (new File(rootDir, isa)).exists(); 7855 } else { 7856 has64BitLibs = false; 7857 } 7858 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7859 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7860 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7861 has32BitLibs = (new File(rootDir, isa)).exists(); 7862 } else { 7863 has32BitLibs = false; 7864 } 7865 } 7866 7867 if (has64BitLibs && !has32BitLibs) { 7868 // The package has 64 bit libs, but not 32 bit libs. Its primary 7869 // ABI should be 64 bit. We can safely assume here that the bundled 7870 // native libraries correspond to the most preferred ABI in the list. 7871 7872 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7873 pkg.applicationInfo.secondaryCpuAbi = null; 7874 } else if (has32BitLibs && !has64BitLibs) { 7875 // The package has 32 bit libs but not 64 bit libs. Its primary 7876 // ABI should be 32 bit. 7877 7878 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7879 pkg.applicationInfo.secondaryCpuAbi = null; 7880 } else if (has32BitLibs && has64BitLibs) { 7881 // The application has both 64 and 32 bit bundled libraries. We check 7882 // here that the app declares multiArch support, and warn if it doesn't. 7883 // 7884 // We will be lenient here and record both ABIs. The primary will be the 7885 // ABI that's higher on the list, i.e, a device that's configured to prefer 7886 // 64 bit apps will see a 64 bit primary ABI, 7887 7888 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7889 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7890 } 7891 7892 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7893 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7894 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7895 } else { 7896 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7897 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7898 } 7899 } else { 7900 pkg.applicationInfo.primaryCpuAbi = null; 7901 pkg.applicationInfo.secondaryCpuAbi = null; 7902 } 7903 } 7904 7905 private void killApplication(String pkgName, int appId, String reason) { 7906 // Request the ActivityManager to kill the process(only for existing packages) 7907 // so that we do not end up in a confused state while the user is still using the older 7908 // version of the application while the new one gets installed. 7909 IActivityManager am = ActivityManagerNative.getDefault(); 7910 if (am != null) { 7911 try { 7912 am.killApplicationWithAppId(pkgName, appId, reason); 7913 } catch (RemoteException e) { 7914 } 7915 } 7916 } 7917 7918 void removePackageLI(PackageSetting ps, boolean chatty) { 7919 if (DEBUG_INSTALL) { 7920 if (chatty) 7921 Log.d(TAG, "Removing package " + ps.name); 7922 } 7923 7924 // writer 7925 synchronized (mPackages) { 7926 mPackages.remove(ps.name); 7927 final PackageParser.Package pkg = ps.pkg; 7928 if (pkg != null) { 7929 cleanPackageDataStructuresLILPw(pkg, chatty); 7930 } 7931 } 7932 } 7933 7934 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7935 if (DEBUG_INSTALL) { 7936 if (chatty) 7937 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7938 } 7939 7940 // writer 7941 synchronized (mPackages) { 7942 mPackages.remove(pkg.applicationInfo.packageName); 7943 cleanPackageDataStructuresLILPw(pkg, chatty); 7944 } 7945 } 7946 7947 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7948 int N = pkg.providers.size(); 7949 StringBuilder r = null; 7950 int i; 7951 for (i=0; i<N; i++) { 7952 PackageParser.Provider p = pkg.providers.get(i); 7953 mProviders.removeProvider(p); 7954 if (p.info.authority == null) { 7955 7956 /* There was another ContentProvider with this authority when 7957 * this app was installed so this authority is null, 7958 * Ignore it as we don't have to unregister the provider. 7959 */ 7960 continue; 7961 } 7962 String names[] = p.info.authority.split(";"); 7963 for (int j = 0; j < names.length; j++) { 7964 if (mProvidersByAuthority.get(names[j]) == p) { 7965 mProvidersByAuthority.remove(names[j]); 7966 if (DEBUG_REMOVE) { 7967 if (chatty) 7968 Log.d(TAG, "Unregistered content provider: " + names[j] 7969 + ", className = " + p.info.name + ", isSyncable = " 7970 + p.info.isSyncable); 7971 } 7972 } 7973 } 7974 if (DEBUG_REMOVE && chatty) { 7975 if (r == null) { 7976 r = new StringBuilder(256); 7977 } else { 7978 r.append(' '); 7979 } 7980 r.append(p.info.name); 7981 } 7982 } 7983 if (r != null) { 7984 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7985 } 7986 7987 N = pkg.services.size(); 7988 r = null; 7989 for (i=0; i<N; i++) { 7990 PackageParser.Service s = pkg.services.get(i); 7991 mServices.removeService(s); 7992 if (chatty) { 7993 if (r == null) { 7994 r = new StringBuilder(256); 7995 } else { 7996 r.append(' '); 7997 } 7998 r.append(s.info.name); 7999 } 8000 } 8001 if (r != null) { 8002 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8003 } 8004 8005 N = pkg.receivers.size(); 8006 r = null; 8007 for (i=0; i<N; i++) { 8008 PackageParser.Activity a = pkg.receivers.get(i); 8009 mReceivers.removeActivity(a, "receiver"); 8010 if (DEBUG_REMOVE && chatty) { 8011 if (r == null) { 8012 r = new StringBuilder(256); 8013 } else { 8014 r.append(' '); 8015 } 8016 r.append(a.info.name); 8017 } 8018 } 8019 if (r != null) { 8020 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8021 } 8022 8023 N = pkg.activities.size(); 8024 r = null; 8025 for (i=0; i<N; i++) { 8026 PackageParser.Activity a = pkg.activities.get(i); 8027 mActivities.removeActivity(a, "activity"); 8028 if (DEBUG_REMOVE && chatty) { 8029 if (r == null) { 8030 r = new StringBuilder(256); 8031 } else { 8032 r.append(' '); 8033 } 8034 r.append(a.info.name); 8035 } 8036 } 8037 if (r != null) { 8038 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8039 } 8040 8041 N = pkg.permissions.size(); 8042 r = null; 8043 for (i=0; i<N; i++) { 8044 PackageParser.Permission p = pkg.permissions.get(i); 8045 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8046 if (bp == null) { 8047 bp = mSettings.mPermissionTrees.get(p.info.name); 8048 } 8049 if (bp != null && bp.perm == p) { 8050 bp.perm = null; 8051 if (DEBUG_REMOVE && chatty) { 8052 if (r == null) { 8053 r = new StringBuilder(256); 8054 } else { 8055 r.append(' '); 8056 } 8057 r.append(p.info.name); 8058 } 8059 } 8060 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8061 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8062 if (appOpPerms != null) { 8063 appOpPerms.remove(pkg.packageName); 8064 } 8065 } 8066 } 8067 if (r != null) { 8068 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8069 } 8070 8071 N = pkg.requestedPermissions.size(); 8072 r = null; 8073 for (i=0; i<N; i++) { 8074 String perm = pkg.requestedPermissions.get(i); 8075 BasePermission bp = mSettings.mPermissions.get(perm); 8076 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8077 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8078 if (appOpPerms != null) { 8079 appOpPerms.remove(pkg.packageName); 8080 if (appOpPerms.isEmpty()) { 8081 mAppOpPermissionPackages.remove(perm); 8082 } 8083 } 8084 } 8085 } 8086 if (r != null) { 8087 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8088 } 8089 8090 N = pkg.instrumentation.size(); 8091 r = null; 8092 for (i=0; i<N; i++) { 8093 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8094 mInstrumentation.remove(a.getComponentName()); 8095 if (DEBUG_REMOVE && chatty) { 8096 if (r == null) { 8097 r = new StringBuilder(256); 8098 } else { 8099 r.append(' '); 8100 } 8101 r.append(a.info.name); 8102 } 8103 } 8104 if (r != null) { 8105 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8106 } 8107 8108 r = null; 8109 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8110 // Only system apps can hold shared libraries. 8111 if (pkg.libraryNames != null) { 8112 for (i=0; i<pkg.libraryNames.size(); i++) { 8113 String name = pkg.libraryNames.get(i); 8114 SharedLibraryEntry cur = mSharedLibraries.get(name); 8115 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8116 mSharedLibraries.remove(name); 8117 if (DEBUG_REMOVE && chatty) { 8118 if (r == null) { 8119 r = new StringBuilder(256); 8120 } else { 8121 r.append(' '); 8122 } 8123 r.append(name); 8124 } 8125 } 8126 } 8127 } 8128 } 8129 if (r != null) { 8130 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8131 } 8132 } 8133 8134 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8135 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8136 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8137 return true; 8138 } 8139 } 8140 return false; 8141 } 8142 8143 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8144 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8145 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8146 8147 private void updatePermissionsLPw(String changingPkg, 8148 PackageParser.Package pkgInfo, int flags) { 8149 // Make sure there are no dangling permission trees. 8150 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8151 while (it.hasNext()) { 8152 final BasePermission bp = it.next(); 8153 if (bp.packageSetting == null) { 8154 // We may not yet have parsed the package, so just see if 8155 // we still know about its settings. 8156 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8157 } 8158 if (bp.packageSetting == null) { 8159 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8160 + " from package " + bp.sourcePackage); 8161 it.remove(); 8162 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8163 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8164 Slog.i(TAG, "Removing old permission tree: " + bp.name 8165 + " from package " + bp.sourcePackage); 8166 flags |= UPDATE_PERMISSIONS_ALL; 8167 it.remove(); 8168 } 8169 } 8170 } 8171 8172 // Make sure all dynamic permissions have been assigned to a package, 8173 // and make sure there are no dangling permissions. 8174 it = mSettings.mPermissions.values().iterator(); 8175 while (it.hasNext()) { 8176 final BasePermission bp = it.next(); 8177 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8178 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8179 + bp.name + " pkg=" + bp.sourcePackage 8180 + " info=" + bp.pendingInfo); 8181 if (bp.packageSetting == null && bp.pendingInfo != null) { 8182 final BasePermission tree = findPermissionTreeLP(bp.name); 8183 if (tree != null && tree.perm != null) { 8184 bp.packageSetting = tree.packageSetting; 8185 bp.perm = new PackageParser.Permission(tree.perm.owner, 8186 new PermissionInfo(bp.pendingInfo)); 8187 bp.perm.info.packageName = tree.perm.info.packageName; 8188 bp.perm.info.name = bp.name; 8189 bp.uid = tree.uid; 8190 } 8191 } 8192 } 8193 if (bp.packageSetting == null) { 8194 // We may not yet have parsed the package, so just see if 8195 // we still know about its settings. 8196 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8197 } 8198 if (bp.packageSetting == null) { 8199 Slog.w(TAG, "Removing dangling permission: " + bp.name 8200 + " from package " + bp.sourcePackage); 8201 it.remove(); 8202 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8203 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8204 Slog.i(TAG, "Removing old permission: " + bp.name 8205 + " from package " + bp.sourcePackage); 8206 flags |= UPDATE_PERMISSIONS_ALL; 8207 it.remove(); 8208 } 8209 } 8210 } 8211 8212 // Now update the permissions for all packages, in particular 8213 // replace the granted permissions of the system packages. 8214 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8215 for (PackageParser.Package pkg : mPackages.values()) { 8216 if (pkg != pkgInfo) { 8217 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8218 changingPkg); 8219 } 8220 } 8221 } 8222 8223 if (pkgInfo != null) { 8224 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8225 } 8226 } 8227 8228 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8229 String packageOfInterest) { 8230 // IMPORTANT: There are two types of permissions: install and runtime. 8231 // Install time permissions are granted when the app is installed to 8232 // all device users and users added in the future. Runtime permissions 8233 // are granted at runtime explicitly to specific users. Normal and signature 8234 // protected permissions are install time permissions. Dangerous permissions 8235 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8236 // otherwise they are runtime permissions. This function does not manage 8237 // runtime permissions except for the case an app targeting Lollipop MR1 8238 // being upgraded to target a newer SDK, in which case dangerous permissions 8239 // are transformed from install time to runtime ones. 8240 8241 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8242 if (ps == null) { 8243 return; 8244 } 8245 8246 PermissionsState permissionsState = ps.getPermissionsState(); 8247 PermissionsState origPermissions = permissionsState; 8248 8249 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8250 8251 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8252 8253 boolean changedInstallPermission = false; 8254 8255 if (replace) { 8256 ps.installPermissionsFixed = false; 8257 if (!ps.isSharedUser()) { 8258 origPermissions = new PermissionsState(permissionsState); 8259 permissionsState.reset(); 8260 } 8261 } 8262 8263 permissionsState.setGlobalGids(mGlobalGids); 8264 8265 final int N = pkg.requestedPermissions.size(); 8266 for (int i=0; i<N; i++) { 8267 final String name = pkg.requestedPermissions.get(i); 8268 final BasePermission bp = mSettings.mPermissions.get(name); 8269 8270 if (DEBUG_INSTALL) { 8271 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8272 } 8273 8274 if (bp == null || bp.packageSetting == null) { 8275 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8276 Slog.w(TAG, "Unknown permission " + name 8277 + " in package " + pkg.packageName); 8278 } 8279 continue; 8280 } 8281 8282 final String perm = bp.name; 8283 boolean allowedSig = false; 8284 int grant = GRANT_DENIED; 8285 8286 // Keep track of app op permissions. 8287 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8288 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8289 if (pkgs == null) { 8290 pkgs = new ArraySet<>(); 8291 mAppOpPermissionPackages.put(bp.name, pkgs); 8292 } 8293 pkgs.add(pkg.packageName); 8294 } 8295 8296 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8297 switch (level) { 8298 case PermissionInfo.PROTECTION_NORMAL: { 8299 // For all apps normal permissions are install time ones. 8300 grant = GRANT_INSTALL; 8301 } break; 8302 8303 case PermissionInfo.PROTECTION_DANGEROUS: { 8304 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8305 // For legacy apps dangerous permissions are install time ones. 8306 grant = GRANT_INSTALL_LEGACY; 8307 } else if (origPermissions.hasInstallPermission(bp.name)) { 8308 // For legacy apps that became modern, install becomes runtime. 8309 grant = GRANT_UPGRADE; 8310 } else { 8311 // For modern apps keep runtime permissions unchanged. 8312 grant = GRANT_RUNTIME; 8313 } 8314 } break; 8315 8316 case PermissionInfo.PROTECTION_SIGNATURE: { 8317 // For all apps signature permissions are install time ones. 8318 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8319 if (allowedSig) { 8320 grant = GRANT_INSTALL; 8321 } 8322 } break; 8323 } 8324 8325 if (DEBUG_INSTALL) { 8326 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8327 } 8328 8329 if (grant != GRANT_DENIED) { 8330 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8331 // If this is an existing, non-system package, then 8332 // we can't add any new permissions to it. 8333 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8334 // Except... if this is a permission that was added 8335 // to the platform (note: need to only do this when 8336 // updating the platform). 8337 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8338 grant = GRANT_DENIED; 8339 } 8340 } 8341 } 8342 8343 switch (grant) { 8344 case GRANT_INSTALL: { 8345 // Revoke this as runtime permission to handle the case of 8346 // a runtime permission being downgraded to an install one. 8347 for (int userId : UserManagerService.getInstance().getUserIds()) { 8348 if (origPermissions.getRuntimePermissionState( 8349 bp.name, userId) != null) { 8350 // Revoke the runtime permission and clear the flags. 8351 origPermissions.revokeRuntimePermission(bp, userId); 8352 origPermissions.updatePermissionFlags(bp, userId, 8353 PackageManager.MASK_PERMISSION_FLAGS, 0); 8354 // If we revoked a permission permission, we have to write. 8355 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8356 changedRuntimePermissionUserIds, userId); 8357 } 8358 } 8359 // Grant an install permission. 8360 if (permissionsState.grantInstallPermission(bp) != 8361 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8362 changedInstallPermission = true; 8363 } 8364 } break; 8365 8366 case GRANT_INSTALL_LEGACY: { 8367 // Grant an install permission. 8368 if (permissionsState.grantInstallPermission(bp) != 8369 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8370 changedInstallPermission = true; 8371 } 8372 } break; 8373 8374 case GRANT_RUNTIME: { 8375 // Grant previously granted runtime permissions. 8376 for (int userId : UserManagerService.getInstance().getUserIds()) { 8377 PermissionState permissionState = origPermissions 8378 .getRuntimePermissionState(bp.name, userId); 8379 final int flags = permissionState != null 8380 ? permissionState.getFlags() : 0; 8381 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8382 if (permissionsState.grantRuntimePermission(bp, userId) == 8383 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8384 // If we cannot put the permission as it was, we have to write. 8385 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8386 changedRuntimePermissionUserIds, userId); 8387 } 8388 } 8389 // Propagate the permission flags. 8390 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8391 } 8392 } break; 8393 8394 case GRANT_UPGRADE: { 8395 // Grant runtime permissions for a previously held install permission. 8396 PermissionState permissionState = origPermissions 8397 .getInstallPermissionState(bp.name); 8398 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8399 8400 if (origPermissions.revokeInstallPermission(bp) 8401 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8402 // We will be transferring the permission flags, so clear them. 8403 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8404 PackageManager.MASK_PERMISSION_FLAGS, 0); 8405 changedInstallPermission = true; 8406 } 8407 8408 // If the permission is not to be promoted to runtime we ignore it and 8409 // also its other flags as they are not applicable to install permissions. 8410 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8411 for (int userId : currentUserIds) { 8412 if (permissionsState.grantRuntimePermission(bp, userId) != 8413 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8414 // Transfer the permission flags. 8415 permissionsState.updatePermissionFlags(bp, userId, 8416 flags, flags); 8417 // If we granted the permission, we have to write. 8418 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8419 changedRuntimePermissionUserIds, userId); 8420 } 8421 } 8422 } 8423 } break; 8424 8425 default: { 8426 if (packageOfInterest == null 8427 || packageOfInterest.equals(pkg.packageName)) { 8428 Slog.w(TAG, "Not granting permission " + perm 8429 + " to package " + pkg.packageName 8430 + " because it was previously installed without"); 8431 } 8432 } break; 8433 } 8434 } else { 8435 if (permissionsState.revokeInstallPermission(bp) != 8436 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8437 // Also drop the permission flags. 8438 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8439 PackageManager.MASK_PERMISSION_FLAGS, 0); 8440 changedInstallPermission = true; 8441 Slog.i(TAG, "Un-granting permission " + perm 8442 + " from package " + pkg.packageName 8443 + " (protectionLevel=" + bp.protectionLevel 8444 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8445 + ")"); 8446 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8447 // Don't print warning for app op permissions, since it is fine for them 8448 // not to be granted, there is a UI for the user to decide. 8449 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8450 Slog.w(TAG, "Not granting permission " + perm 8451 + " to package " + pkg.packageName 8452 + " (protectionLevel=" + bp.protectionLevel 8453 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8454 + ")"); 8455 } 8456 } 8457 } 8458 } 8459 8460 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8461 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8462 // This is the first that we have heard about this package, so the 8463 // permissions we have now selected are fixed until explicitly 8464 // changed. 8465 ps.installPermissionsFixed = true; 8466 } 8467 8468 // Persist the runtime permissions state for users with changes. 8469 for (int userId : changedRuntimePermissionUserIds) { 8470 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8471 } 8472 } 8473 8474 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8475 boolean allowed = false; 8476 final int NP = PackageParser.NEW_PERMISSIONS.length; 8477 for (int ip=0; ip<NP; ip++) { 8478 final PackageParser.NewPermissionInfo npi 8479 = PackageParser.NEW_PERMISSIONS[ip]; 8480 if (npi.name.equals(perm) 8481 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8482 allowed = true; 8483 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8484 + pkg.packageName); 8485 break; 8486 } 8487 } 8488 return allowed; 8489 } 8490 8491 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8492 BasePermission bp, PermissionsState origPermissions) { 8493 boolean allowed; 8494 allowed = (compareSignatures( 8495 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8496 == PackageManager.SIGNATURE_MATCH) 8497 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8498 == PackageManager.SIGNATURE_MATCH); 8499 if (!allowed && (bp.protectionLevel 8500 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8501 if (isSystemApp(pkg)) { 8502 // For updated system applications, a system permission 8503 // is granted only if it had been defined by the original application. 8504 if (pkg.isUpdatedSystemApp()) { 8505 final PackageSetting sysPs = mSettings 8506 .getDisabledSystemPkgLPr(pkg.packageName); 8507 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8508 // If the original was granted this permission, we take 8509 // that grant decision as read and propagate it to the 8510 // update. 8511 if (sysPs.isPrivileged()) { 8512 allowed = true; 8513 } 8514 } else { 8515 // The system apk may have been updated with an older 8516 // version of the one on the data partition, but which 8517 // granted a new system permission that it didn't have 8518 // before. In this case we do want to allow the app to 8519 // now get the new permission if the ancestral apk is 8520 // privileged to get it. 8521 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8522 for (int j=0; 8523 j<sysPs.pkg.requestedPermissions.size(); j++) { 8524 if (perm.equals( 8525 sysPs.pkg.requestedPermissions.get(j))) { 8526 allowed = true; 8527 break; 8528 } 8529 } 8530 } 8531 } 8532 } else { 8533 allowed = isPrivilegedApp(pkg); 8534 } 8535 } 8536 } 8537 if (!allowed) { 8538 if (!allowed && (bp.protectionLevel 8539 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8540 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8541 // If this was a previously normal/dangerous permission that got moved 8542 // to a system permission as part of the runtime permission redesign, then 8543 // we still want to blindly grant it to old apps. 8544 allowed = true; 8545 } 8546 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8547 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8548 // If this permission is to be granted to the system installer and 8549 // this app is an installer, then it gets the permission. 8550 allowed = true; 8551 } 8552 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8553 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8554 // If this permission is to be granted to the system verifier and 8555 // this app is a verifier, then it gets the permission. 8556 allowed = true; 8557 } 8558 if (!allowed && (bp.protectionLevel 8559 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8560 && isSystemApp(pkg)) { 8561 // Any pre-installed system app is allowed to get this permission. 8562 allowed = true; 8563 } 8564 if (!allowed && (bp.protectionLevel 8565 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8566 // For development permissions, a development permission 8567 // is granted only if it was already granted. 8568 allowed = origPermissions.hasInstallPermission(perm); 8569 } 8570 } 8571 return allowed; 8572 } 8573 8574 final class ActivityIntentResolver 8575 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8576 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8577 boolean defaultOnly, int userId) { 8578 if (!sUserManager.exists(userId)) return null; 8579 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8580 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8581 } 8582 8583 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8584 int userId) { 8585 if (!sUserManager.exists(userId)) return null; 8586 mFlags = flags; 8587 return super.queryIntent(intent, resolvedType, 8588 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8589 } 8590 8591 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8592 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8593 if (!sUserManager.exists(userId)) return null; 8594 if (packageActivities == null) { 8595 return null; 8596 } 8597 mFlags = flags; 8598 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8599 final int N = packageActivities.size(); 8600 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8601 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8602 8603 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8604 for (int i = 0; i < N; ++i) { 8605 intentFilters = packageActivities.get(i).intents; 8606 if (intentFilters != null && intentFilters.size() > 0) { 8607 PackageParser.ActivityIntentInfo[] array = 8608 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8609 intentFilters.toArray(array); 8610 listCut.add(array); 8611 } 8612 } 8613 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8614 } 8615 8616 public final void addActivity(PackageParser.Activity a, String type) { 8617 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8618 mActivities.put(a.getComponentName(), a); 8619 if (DEBUG_SHOW_INFO) 8620 Log.v( 8621 TAG, " " + type + " " + 8622 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8623 if (DEBUG_SHOW_INFO) 8624 Log.v(TAG, " Class=" + a.info.name); 8625 final int NI = a.intents.size(); 8626 for (int j=0; j<NI; j++) { 8627 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8628 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8629 intent.setPriority(0); 8630 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8631 + a.className + " with priority > 0, forcing to 0"); 8632 } 8633 if (DEBUG_SHOW_INFO) { 8634 Log.v(TAG, " IntentFilter:"); 8635 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8636 } 8637 if (!intent.debugCheck()) { 8638 Log.w(TAG, "==> For Activity " + a.info.name); 8639 } 8640 addFilter(intent); 8641 } 8642 } 8643 8644 public final void removeActivity(PackageParser.Activity a, String type) { 8645 mActivities.remove(a.getComponentName()); 8646 if (DEBUG_SHOW_INFO) { 8647 Log.v(TAG, " " + type + " " 8648 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8649 : a.info.name) + ":"); 8650 Log.v(TAG, " Class=" + a.info.name); 8651 } 8652 final int NI = a.intents.size(); 8653 for (int j=0; j<NI; j++) { 8654 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8655 if (DEBUG_SHOW_INFO) { 8656 Log.v(TAG, " IntentFilter:"); 8657 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8658 } 8659 removeFilter(intent); 8660 } 8661 } 8662 8663 @Override 8664 protected boolean allowFilterResult( 8665 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8666 ActivityInfo filterAi = filter.activity.info; 8667 for (int i=dest.size()-1; i>=0; i--) { 8668 ActivityInfo destAi = dest.get(i).activityInfo; 8669 if (destAi.name == filterAi.name 8670 && destAi.packageName == filterAi.packageName) { 8671 return false; 8672 } 8673 } 8674 return true; 8675 } 8676 8677 @Override 8678 protected ActivityIntentInfo[] newArray(int size) { 8679 return new ActivityIntentInfo[size]; 8680 } 8681 8682 @Override 8683 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8684 if (!sUserManager.exists(userId)) return true; 8685 PackageParser.Package p = filter.activity.owner; 8686 if (p != null) { 8687 PackageSetting ps = (PackageSetting)p.mExtras; 8688 if (ps != null) { 8689 // System apps are never considered stopped for purposes of 8690 // filtering, because there may be no way for the user to 8691 // actually re-launch them. 8692 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8693 && ps.getStopped(userId); 8694 } 8695 } 8696 return false; 8697 } 8698 8699 @Override 8700 protected boolean isPackageForFilter(String packageName, 8701 PackageParser.ActivityIntentInfo info) { 8702 return packageName.equals(info.activity.owner.packageName); 8703 } 8704 8705 @Override 8706 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8707 int match, int userId) { 8708 if (!sUserManager.exists(userId)) return null; 8709 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8710 return null; 8711 } 8712 final PackageParser.Activity activity = info.activity; 8713 if (mSafeMode && (activity.info.applicationInfo.flags 8714 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8715 return null; 8716 } 8717 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8718 if (ps == null) { 8719 return null; 8720 } 8721 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8722 ps.readUserState(userId), userId); 8723 if (ai == null) { 8724 return null; 8725 } 8726 final ResolveInfo res = new ResolveInfo(); 8727 res.activityInfo = ai; 8728 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8729 res.filter = info; 8730 } 8731 if (info != null) { 8732 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8733 } 8734 res.priority = info.getPriority(); 8735 res.preferredOrder = activity.owner.mPreferredOrder; 8736 //System.out.println("Result: " + res.activityInfo.className + 8737 // " = " + res.priority); 8738 res.match = match; 8739 res.isDefault = info.hasDefault; 8740 res.labelRes = info.labelRes; 8741 res.nonLocalizedLabel = info.nonLocalizedLabel; 8742 if (userNeedsBadging(userId)) { 8743 res.noResourceId = true; 8744 } else { 8745 res.icon = info.icon; 8746 } 8747 res.iconResourceId = info.icon; 8748 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8749 return res; 8750 } 8751 8752 @Override 8753 protected void sortResults(List<ResolveInfo> results) { 8754 Collections.sort(results, mResolvePrioritySorter); 8755 } 8756 8757 @Override 8758 protected void dumpFilter(PrintWriter out, String prefix, 8759 PackageParser.ActivityIntentInfo filter) { 8760 out.print(prefix); out.print( 8761 Integer.toHexString(System.identityHashCode(filter.activity))); 8762 out.print(' '); 8763 filter.activity.printComponentShortName(out); 8764 out.print(" filter "); 8765 out.println(Integer.toHexString(System.identityHashCode(filter))); 8766 } 8767 8768 @Override 8769 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8770 return filter.activity; 8771 } 8772 8773 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8774 PackageParser.Activity activity = (PackageParser.Activity)label; 8775 out.print(prefix); out.print( 8776 Integer.toHexString(System.identityHashCode(activity))); 8777 out.print(' '); 8778 activity.printComponentShortName(out); 8779 if (count > 1) { 8780 out.print(" ("); out.print(count); out.print(" filters)"); 8781 } 8782 out.println(); 8783 } 8784 8785// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8786// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8787// final List<ResolveInfo> retList = Lists.newArrayList(); 8788// while (i.hasNext()) { 8789// final ResolveInfo resolveInfo = i.next(); 8790// if (isEnabledLP(resolveInfo.activityInfo)) { 8791// retList.add(resolveInfo); 8792// } 8793// } 8794// return retList; 8795// } 8796 8797 // Keys are String (activity class name), values are Activity. 8798 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8799 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8800 private int mFlags; 8801 } 8802 8803 private final class ServiceIntentResolver 8804 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8805 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8806 boolean defaultOnly, int userId) { 8807 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8808 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8809 } 8810 8811 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8812 int userId) { 8813 if (!sUserManager.exists(userId)) return null; 8814 mFlags = flags; 8815 return super.queryIntent(intent, resolvedType, 8816 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8817 } 8818 8819 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8820 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8821 if (!sUserManager.exists(userId)) return null; 8822 if (packageServices == null) { 8823 return null; 8824 } 8825 mFlags = flags; 8826 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8827 final int N = packageServices.size(); 8828 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8829 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8830 8831 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8832 for (int i = 0; i < N; ++i) { 8833 intentFilters = packageServices.get(i).intents; 8834 if (intentFilters != null && intentFilters.size() > 0) { 8835 PackageParser.ServiceIntentInfo[] array = 8836 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8837 intentFilters.toArray(array); 8838 listCut.add(array); 8839 } 8840 } 8841 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8842 } 8843 8844 public final void addService(PackageParser.Service s) { 8845 mServices.put(s.getComponentName(), s); 8846 if (DEBUG_SHOW_INFO) { 8847 Log.v(TAG, " " 8848 + (s.info.nonLocalizedLabel != null 8849 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8850 Log.v(TAG, " Class=" + s.info.name); 8851 } 8852 final int NI = s.intents.size(); 8853 int j; 8854 for (j=0; j<NI; j++) { 8855 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8856 if (DEBUG_SHOW_INFO) { 8857 Log.v(TAG, " IntentFilter:"); 8858 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8859 } 8860 if (!intent.debugCheck()) { 8861 Log.w(TAG, "==> For Service " + s.info.name); 8862 } 8863 addFilter(intent); 8864 } 8865 } 8866 8867 public final void removeService(PackageParser.Service s) { 8868 mServices.remove(s.getComponentName()); 8869 if (DEBUG_SHOW_INFO) { 8870 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8871 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8872 Log.v(TAG, " Class=" + s.info.name); 8873 } 8874 final int NI = s.intents.size(); 8875 int j; 8876 for (j=0; j<NI; j++) { 8877 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8878 if (DEBUG_SHOW_INFO) { 8879 Log.v(TAG, " IntentFilter:"); 8880 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8881 } 8882 removeFilter(intent); 8883 } 8884 } 8885 8886 @Override 8887 protected boolean allowFilterResult( 8888 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8889 ServiceInfo filterSi = filter.service.info; 8890 for (int i=dest.size()-1; i>=0; i--) { 8891 ServiceInfo destAi = dest.get(i).serviceInfo; 8892 if (destAi.name == filterSi.name 8893 && destAi.packageName == filterSi.packageName) { 8894 return false; 8895 } 8896 } 8897 return true; 8898 } 8899 8900 @Override 8901 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8902 return new PackageParser.ServiceIntentInfo[size]; 8903 } 8904 8905 @Override 8906 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8907 if (!sUserManager.exists(userId)) return true; 8908 PackageParser.Package p = filter.service.owner; 8909 if (p != null) { 8910 PackageSetting ps = (PackageSetting)p.mExtras; 8911 if (ps != null) { 8912 // System apps are never considered stopped for purposes of 8913 // filtering, because there may be no way for the user to 8914 // actually re-launch them. 8915 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8916 && ps.getStopped(userId); 8917 } 8918 } 8919 return false; 8920 } 8921 8922 @Override 8923 protected boolean isPackageForFilter(String packageName, 8924 PackageParser.ServiceIntentInfo info) { 8925 return packageName.equals(info.service.owner.packageName); 8926 } 8927 8928 @Override 8929 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8930 int match, int userId) { 8931 if (!sUserManager.exists(userId)) return null; 8932 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8933 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8934 return null; 8935 } 8936 final PackageParser.Service service = info.service; 8937 if (mSafeMode && (service.info.applicationInfo.flags 8938 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8939 return null; 8940 } 8941 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8942 if (ps == null) { 8943 return null; 8944 } 8945 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8946 ps.readUserState(userId), userId); 8947 if (si == null) { 8948 return null; 8949 } 8950 final ResolveInfo res = new ResolveInfo(); 8951 res.serviceInfo = si; 8952 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8953 res.filter = filter; 8954 } 8955 res.priority = info.getPriority(); 8956 res.preferredOrder = service.owner.mPreferredOrder; 8957 res.match = match; 8958 res.isDefault = info.hasDefault; 8959 res.labelRes = info.labelRes; 8960 res.nonLocalizedLabel = info.nonLocalizedLabel; 8961 res.icon = info.icon; 8962 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8963 return res; 8964 } 8965 8966 @Override 8967 protected void sortResults(List<ResolveInfo> results) { 8968 Collections.sort(results, mResolvePrioritySorter); 8969 } 8970 8971 @Override 8972 protected void dumpFilter(PrintWriter out, String prefix, 8973 PackageParser.ServiceIntentInfo filter) { 8974 out.print(prefix); out.print( 8975 Integer.toHexString(System.identityHashCode(filter.service))); 8976 out.print(' '); 8977 filter.service.printComponentShortName(out); 8978 out.print(" filter "); 8979 out.println(Integer.toHexString(System.identityHashCode(filter))); 8980 } 8981 8982 @Override 8983 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8984 return filter.service; 8985 } 8986 8987 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8988 PackageParser.Service service = (PackageParser.Service)label; 8989 out.print(prefix); out.print( 8990 Integer.toHexString(System.identityHashCode(service))); 8991 out.print(' '); 8992 service.printComponentShortName(out); 8993 if (count > 1) { 8994 out.print(" ("); out.print(count); out.print(" filters)"); 8995 } 8996 out.println(); 8997 } 8998 8999// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9000// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9001// final List<ResolveInfo> retList = Lists.newArrayList(); 9002// while (i.hasNext()) { 9003// final ResolveInfo resolveInfo = (ResolveInfo) i; 9004// if (isEnabledLP(resolveInfo.serviceInfo)) { 9005// retList.add(resolveInfo); 9006// } 9007// } 9008// return retList; 9009// } 9010 9011 // Keys are String (activity class name), values are Activity. 9012 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9013 = new ArrayMap<ComponentName, PackageParser.Service>(); 9014 private int mFlags; 9015 }; 9016 9017 private final class ProviderIntentResolver 9018 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9019 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9020 boolean defaultOnly, int userId) { 9021 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9022 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9023 } 9024 9025 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9026 int userId) { 9027 if (!sUserManager.exists(userId)) 9028 return null; 9029 mFlags = flags; 9030 return super.queryIntent(intent, resolvedType, 9031 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9032 } 9033 9034 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9035 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9036 if (!sUserManager.exists(userId)) 9037 return null; 9038 if (packageProviders == null) { 9039 return null; 9040 } 9041 mFlags = flags; 9042 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9043 final int N = packageProviders.size(); 9044 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9045 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9046 9047 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9048 for (int i = 0; i < N; ++i) { 9049 intentFilters = packageProviders.get(i).intents; 9050 if (intentFilters != null && intentFilters.size() > 0) { 9051 PackageParser.ProviderIntentInfo[] array = 9052 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9053 intentFilters.toArray(array); 9054 listCut.add(array); 9055 } 9056 } 9057 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9058 } 9059 9060 public final void addProvider(PackageParser.Provider p) { 9061 if (mProviders.containsKey(p.getComponentName())) { 9062 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9063 return; 9064 } 9065 9066 mProviders.put(p.getComponentName(), p); 9067 if (DEBUG_SHOW_INFO) { 9068 Log.v(TAG, " " 9069 + (p.info.nonLocalizedLabel != null 9070 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9071 Log.v(TAG, " Class=" + p.info.name); 9072 } 9073 final int NI = p.intents.size(); 9074 int j; 9075 for (j = 0; j < NI; j++) { 9076 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9077 if (DEBUG_SHOW_INFO) { 9078 Log.v(TAG, " IntentFilter:"); 9079 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9080 } 9081 if (!intent.debugCheck()) { 9082 Log.w(TAG, "==> For Provider " + p.info.name); 9083 } 9084 addFilter(intent); 9085 } 9086 } 9087 9088 public final void removeProvider(PackageParser.Provider p) { 9089 mProviders.remove(p.getComponentName()); 9090 if (DEBUG_SHOW_INFO) { 9091 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9092 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9093 Log.v(TAG, " Class=" + p.info.name); 9094 } 9095 final int NI = p.intents.size(); 9096 int j; 9097 for (j = 0; j < NI; j++) { 9098 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9099 if (DEBUG_SHOW_INFO) { 9100 Log.v(TAG, " IntentFilter:"); 9101 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9102 } 9103 removeFilter(intent); 9104 } 9105 } 9106 9107 @Override 9108 protected boolean allowFilterResult( 9109 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9110 ProviderInfo filterPi = filter.provider.info; 9111 for (int i = dest.size() - 1; i >= 0; i--) { 9112 ProviderInfo destPi = dest.get(i).providerInfo; 9113 if (destPi.name == filterPi.name 9114 && destPi.packageName == filterPi.packageName) { 9115 return false; 9116 } 9117 } 9118 return true; 9119 } 9120 9121 @Override 9122 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9123 return new PackageParser.ProviderIntentInfo[size]; 9124 } 9125 9126 @Override 9127 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9128 if (!sUserManager.exists(userId)) 9129 return true; 9130 PackageParser.Package p = filter.provider.owner; 9131 if (p != null) { 9132 PackageSetting ps = (PackageSetting) p.mExtras; 9133 if (ps != null) { 9134 // System apps are never considered stopped for purposes of 9135 // filtering, because there may be no way for the user to 9136 // actually re-launch them. 9137 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9138 && ps.getStopped(userId); 9139 } 9140 } 9141 return false; 9142 } 9143 9144 @Override 9145 protected boolean isPackageForFilter(String packageName, 9146 PackageParser.ProviderIntentInfo info) { 9147 return packageName.equals(info.provider.owner.packageName); 9148 } 9149 9150 @Override 9151 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9152 int match, int userId) { 9153 if (!sUserManager.exists(userId)) 9154 return null; 9155 final PackageParser.ProviderIntentInfo info = filter; 9156 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9157 return null; 9158 } 9159 final PackageParser.Provider provider = info.provider; 9160 if (mSafeMode && (provider.info.applicationInfo.flags 9161 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9162 return null; 9163 } 9164 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9165 if (ps == null) { 9166 return null; 9167 } 9168 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9169 ps.readUserState(userId), userId); 9170 if (pi == null) { 9171 return null; 9172 } 9173 final ResolveInfo res = new ResolveInfo(); 9174 res.providerInfo = pi; 9175 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9176 res.filter = filter; 9177 } 9178 res.priority = info.getPriority(); 9179 res.preferredOrder = provider.owner.mPreferredOrder; 9180 res.match = match; 9181 res.isDefault = info.hasDefault; 9182 res.labelRes = info.labelRes; 9183 res.nonLocalizedLabel = info.nonLocalizedLabel; 9184 res.icon = info.icon; 9185 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9186 return res; 9187 } 9188 9189 @Override 9190 protected void sortResults(List<ResolveInfo> results) { 9191 Collections.sort(results, mResolvePrioritySorter); 9192 } 9193 9194 @Override 9195 protected void dumpFilter(PrintWriter out, String prefix, 9196 PackageParser.ProviderIntentInfo filter) { 9197 out.print(prefix); 9198 out.print( 9199 Integer.toHexString(System.identityHashCode(filter.provider))); 9200 out.print(' '); 9201 filter.provider.printComponentShortName(out); 9202 out.print(" filter "); 9203 out.println(Integer.toHexString(System.identityHashCode(filter))); 9204 } 9205 9206 @Override 9207 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9208 return filter.provider; 9209 } 9210 9211 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9212 PackageParser.Provider provider = (PackageParser.Provider)label; 9213 out.print(prefix); out.print( 9214 Integer.toHexString(System.identityHashCode(provider))); 9215 out.print(' '); 9216 provider.printComponentShortName(out); 9217 if (count > 1) { 9218 out.print(" ("); out.print(count); out.print(" filters)"); 9219 } 9220 out.println(); 9221 } 9222 9223 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9224 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9225 private int mFlags; 9226 }; 9227 9228 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9229 new Comparator<ResolveInfo>() { 9230 public int compare(ResolveInfo r1, ResolveInfo r2) { 9231 int v1 = r1.priority; 9232 int v2 = r2.priority; 9233 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9234 if (v1 != v2) { 9235 return (v1 > v2) ? -1 : 1; 9236 } 9237 v1 = r1.preferredOrder; 9238 v2 = r2.preferredOrder; 9239 if (v1 != v2) { 9240 return (v1 > v2) ? -1 : 1; 9241 } 9242 if (r1.isDefault != r2.isDefault) { 9243 return r1.isDefault ? -1 : 1; 9244 } 9245 v1 = r1.match; 9246 v2 = r2.match; 9247 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9248 if (v1 != v2) { 9249 return (v1 > v2) ? -1 : 1; 9250 } 9251 if (r1.system != r2.system) { 9252 return r1.system ? -1 : 1; 9253 } 9254 return 0; 9255 } 9256 }; 9257 9258 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9259 new Comparator<ProviderInfo>() { 9260 public int compare(ProviderInfo p1, ProviderInfo p2) { 9261 final int v1 = p1.initOrder; 9262 final int v2 = p2.initOrder; 9263 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9264 } 9265 }; 9266 9267 final void sendPackageBroadcast(final String action, final String pkg, 9268 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9269 final int[] userIds) { 9270 mHandler.post(new Runnable() { 9271 @Override 9272 public void run() { 9273 try { 9274 final IActivityManager am = ActivityManagerNative.getDefault(); 9275 if (am == null) return; 9276 final int[] resolvedUserIds; 9277 if (userIds == null) { 9278 resolvedUserIds = am.getRunningUserIds(); 9279 } else { 9280 resolvedUserIds = userIds; 9281 } 9282 for (int id : resolvedUserIds) { 9283 final Intent intent = new Intent(action, 9284 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9285 if (extras != null) { 9286 intent.putExtras(extras); 9287 } 9288 if (targetPkg != null) { 9289 intent.setPackage(targetPkg); 9290 } 9291 // Modify the UID when posting to other users 9292 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9293 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9294 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9295 intent.putExtra(Intent.EXTRA_UID, uid); 9296 } 9297 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9298 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9299 if (DEBUG_BROADCASTS) { 9300 RuntimeException here = new RuntimeException("here"); 9301 here.fillInStackTrace(); 9302 Slog.d(TAG, "Sending to user " + id + ": " 9303 + intent.toShortString(false, true, false, false) 9304 + " " + intent.getExtras(), here); 9305 } 9306 am.broadcastIntent(null, intent, null, finishedReceiver, 9307 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9308 null, finishedReceiver != null, false, id); 9309 } 9310 } catch (RemoteException ex) { 9311 } 9312 } 9313 }); 9314 } 9315 9316 /** 9317 * Check if the external storage media is available. This is true if there 9318 * is a mounted external storage medium or if the external storage is 9319 * emulated. 9320 */ 9321 private boolean isExternalMediaAvailable() { 9322 return mMediaMounted || Environment.isExternalStorageEmulated(); 9323 } 9324 9325 @Override 9326 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9327 // writer 9328 synchronized (mPackages) { 9329 if (!isExternalMediaAvailable()) { 9330 // If the external storage is no longer mounted at this point, 9331 // the caller may not have been able to delete all of this 9332 // packages files and can not delete any more. Bail. 9333 return null; 9334 } 9335 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9336 if (lastPackage != null) { 9337 pkgs.remove(lastPackage); 9338 } 9339 if (pkgs.size() > 0) { 9340 return pkgs.get(0); 9341 } 9342 } 9343 return null; 9344 } 9345 9346 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9347 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9348 userId, andCode ? 1 : 0, packageName); 9349 if (mSystemReady) { 9350 msg.sendToTarget(); 9351 } else { 9352 if (mPostSystemReadyMessages == null) { 9353 mPostSystemReadyMessages = new ArrayList<>(); 9354 } 9355 mPostSystemReadyMessages.add(msg); 9356 } 9357 } 9358 9359 void startCleaningPackages() { 9360 // reader 9361 synchronized (mPackages) { 9362 if (!isExternalMediaAvailable()) { 9363 return; 9364 } 9365 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9366 return; 9367 } 9368 } 9369 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9370 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9371 IActivityManager am = ActivityManagerNative.getDefault(); 9372 if (am != null) { 9373 try { 9374 am.startService(null, intent, null, mContext.getOpPackageName(), 9375 UserHandle.USER_OWNER); 9376 } catch (RemoteException e) { 9377 } 9378 } 9379 } 9380 9381 @Override 9382 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9383 int installFlags, String installerPackageName, VerificationParams verificationParams, 9384 String packageAbiOverride) { 9385 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9386 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9387 } 9388 9389 @Override 9390 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9391 int installFlags, String installerPackageName, VerificationParams verificationParams, 9392 String packageAbiOverride, int userId) { 9393 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9394 9395 final int callingUid = Binder.getCallingUid(); 9396 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9397 9398 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9399 try { 9400 if (observer != null) { 9401 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9402 } 9403 } catch (RemoteException re) { 9404 } 9405 return; 9406 } 9407 9408 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9409 installFlags |= PackageManager.INSTALL_FROM_ADB; 9410 9411 } else { 9412 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9413 // about installerPackageName. 9414 9415 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9416 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9417 } 9418 9419 UserHandle user; 9420 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9421 user = UserHandle.ALL; 9422 } else { 9423 user = new UserHandle(userId); 9424 } 9425 9426 // Only system components can circumvent runtime permissions when installing. 9427 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9428 && mContext.checkCallingOrSelfPermission(Manifest.permission 9429 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9430 throw new SecurityException("You need the " 9431 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9432 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9433 } 9434 9435 verificationParams.setInstallerUid(callingUid); 9436 9437 final File originFile = new File(originPath); 9438 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9439 9440 final Message msg = mHandler.obtainMessage(INIT_COPY); 9441 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9442 null, verificationParams, user, packageAbiOverride); 9443 mHandler.sendMessage(msg); 9444 } 9445 9446 void installStage(String packageName, File stagedDir, String stagedCid, 9447 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9448 String installerPackageName, int installerUid, UserHandle user) { 9449 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9450 params.referrerUri, installerUid, null); 9451 verifParams.setInstallerUid(installerUid); 9452 9453 final OriginInfo origin; 9454 if (stagedDir != null) { 9455 origin = OriginInfo.fromStagedFile(stagedDir); 9456 } else { 9457 origin = OriginInfo.fromStagedContainer(stagedCid); 9458 } 9459 9460 final Message msg = mHandler.obtainMessage(INIT_COPY); 9461 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9462 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9463 mHandler.sendMessage(msg); 9464 } 9465 9466 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9467 Bundle extras = new Bundle(1); 9468 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9469 9470 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9471 packageName, extras, null, null, new int[] {userId}); 9472 try { 9473 IActivityManager am = ActivityManagerNative.getDefault(); 9474 final boolean isSystem = 9475 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9476 if (isSystem && am.isUserRunning(userId, false)) { 9477 // The just-installed/enabled app is bundled on the system, so presumed 9478 // to be able to run automatically without needing an explicit launch. 9479 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9480 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9481 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9482 .setPackage(packageName); 9483 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9484 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9485 } 9486 } catch (RemoteException e) { 9487 // shouldn't happen 9488 Slog.w(TAG, "Unable to bootstrap installed package", e); 9489 } 9490 } 9491 9492 @Override 9493 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9494 int userId) { 9495 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9496 PackageSetting pkgSetting; 9497 final int uid = Binder.getCallingUid(); 9498 enforceCrossUserPermission(uid, userId, true, true, 9499 "setApplicationHiddenSetting for user " + userId); 9500 9501 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9502 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9503 return false; 9504 } 9505 9506 long callingId = Binder.clearCallingIdentity(); 9507 try { 9508 boolean sendAdded = false; 9509 boolean sendRemoved = false; 9510 // writer 9511 synchronized (mPackages) { 9512 pkgSetting = mSettings.mPackages.get(packageName); 9513 if (pkgSetting == null) { 9514 return false; 9515 } 9516 if (pkgSetting.getHidden(userId) != hidden) { 9517 pkgSetting.setHidden(hidden, userId); 9518 mSettings.writePackageRestrictionsLPr(userId); 9519 if (hidden) { 9520 sendRemoved = true; 9521 } else { 9522 sendAdded = true; 9523 } 9524 } 9525 } 9526 if (sendAdded) { 9527 sendPackageAddedForUser(packageName, pkgSetting, userId); 9528 return true; 9529 } 9530 if (sendRemoved) { 9531 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9532 "hiding pkg"); 9533 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9534 } 9535 } finally { 9536 Binder.restoreCallingIdentity(callingId); 9537 } 9538 return false; 9539 } 9540 9541 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9542 int userId) { 9543 final PackageRemovedInfo info = new PackageRemovedInfo(); 9544 info.removedPackage = packageName; 9545 info.removedUsers = new int[] {userId}; 9546 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9547 info.sendBroadcast(false, false, false); 9548 } 9549 9550 /** 9551 * Returns true if application is not found or there was an error. Otherwise it returns 9552 * the hidden state of the package for the given user. 9553 */ 9554 @Override 9555 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9556 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9557 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9558 false, "getApplicationHidden for user " + userId); 9559 PackageSetting pkgSetting; 9560 long callingId = Binder.clearCallingIdentity(); 9561 try { 9562 // writer 9563 synchronized (mPackages) { 9564 pkgSetting = mSettings.mPackages.get(packageName); 9565 if (pkgSetting == null) { 9566 return true; 9567 } 9568 return pkgSetting.getHidden(userId); 9569 } 9570 } finally { 9571 Binder.restoreCallingIdentity(callingId); 9572 } 9573 } 9574 9575 /** 9576 * @hide 9577 */ 9578 @Override 9579 public int installExistingPackageAsUser(String packageName, int userId) { 9580 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9581 null); 9582 PackageSetting pkgSetting; 9583 final int uid = Binder.getCallingUid(); 9584 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9585 + userId); 9586 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9587 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9588 } 9589 9590 long callingId = Binder.clearCallingIdentity(); 9591 try { 9592 boolean sendAdded = false; 9593 9594 // writer 9595 synchronized (mPackages) { 9596 pkgSetting = mSettings.mPackages.get(packageName); 9597 if (pkgSetting == null) { 9598 return PackageManager.INSTALL_FAILED_INVALID_URI; 9599 } 9600 if (!pkgSetting.getInstalled(userId)) { 9601 pkgSetting.setInstalled(true, userId); 9602 pkgSetting.setHidden(false, userId); 9603 mSettings.writePackageRestrictionsLPr(userId); 9604 sendAdded = true; 9605 } 9606 } 9607 9608 if (sendAdded) { 9609 sendPackageAddedForUser(packageName, pkgSetting, userId); 9610 } 9611 } finally { 9612 Binder.restoreCallingIdentity(callingId); 9613 } 9614 9615 return PackageManager.INSTALL_SUCCEEDED; 9616 } 9617 9618 boolean isUserRestricted(int userId, String restrictionKey) { 9619 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9620 if (restrictions.getBoolean(restrictionKey, false)) { 9621 Log.w(TAG, "User is restricted: " + restrictionKey); 9622 return true; 9623 } 9624 return false; 9625 } 9626 9627 @Override 9628 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9629 mContext.enforceCallingOrSelfPermission( 9630 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9631 "Only package verification agents can verify applications"); 9632 9633 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9634 final PackageVerificationResponse response = new PackageVerificationResponse( 9635 verificationCode, Binder.getCallingUid()); 9636 msg.arg1 = id; 9637 msg.obj = response; 9638 mHandler.sendMessage(msg); 9639 } 9640 9641 @Override 9642 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9643 long millisecondsToDelay) { 9644 mContext.enforceCallingOrSelfPermission( 9645 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9646 "Only package verification agents can extend verification timeouts"); 9647 9648 final PackageVerificationState state = mPendingVerification.get(id); 9649 final PackageVerificationResponse response = new PackageVerificationResponse( 9650 verificationCodeAtTimeout, Binder.getCallingUid()); 9651 9652 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9653 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9654 } 9655 if (millisecondsToDelay < 0) { 9656 millisecondsToDelay = 0; 9657 } 9658 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9659 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9660 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9661 } 9662 9663 if ((state != null) && !state.timeoutExtended()) { 9664 state.extendTimeout(); 9665 9666 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9667 msg.arg1 = id; 9668 msg.obj = response; 9669 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9670 } 9671 } 9672 9673 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9674 int verificationCode, UserHandle user) { 9675 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9676 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9677 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9678 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9679 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9680 9681 mContext.sendBroadcastAsUser(intent, user, 9682 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9683 } 9684 9685 private ComponentName matchComponentForVerifier(String packageName, 9686 List<ResolveInfo> receivers) { 9687 ActivityInfo targetReceiver = null; 9688 9689 final int NR = receivers.size(); 9690 for (int i = 0; i < NR; i++) { 9691 final ResolveInfo info = receivers.get(i); 9692 if (info.activityInfo == null) { 9693 continue; 9694 } 9695 9696 if (packageName.equals(info.activityInfo.packageName)) { 9697 targetReceiver = info.activityInfo; 9698 break; 9699 } 9700 } 9701 9702 if (targetReceiver == null) { 9703 return null; 9704 } 9705 9706 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9707 } 9708 9709 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9710 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9711 if (pkgInfo.verifiers.length == 0) { 9712 return null; 9713 } 9714 9715 final int N = pkgInfo.verifiers.length; 9716 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9717 for (int i = 0; i < N; i++) { 9718 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9719 9720 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9721 receivers); 9722 if (comp == null) { 9723 continue; 9724 } 9725 9726 final int verifierUid = getUidForVerifier(verifierInfo); 9727 if (verifierUid == -1) { 9728 continue; 9729 } 9730 9731 if (DEBUG_VERIFY) { 9732 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9733 + " with the correct signature"); 9734 } 9735 sufficientVerifiers.add(comp); 9736 verificationState.addSufficientVerifier(verifierUid); 9737 } 9738 9739 return sufficientVerifiers; 9740 } 9741 9742 private int getUidForVerifier(VerifierInfo verifierInfo) { 9743 synchronized (mPackages) { 9744 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9745 if (pkg == null) { 9746 return -1; 9747 } else if (pkg.mSignatures.length != 1) { 9748 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9749 + " has more than one signature; ignoring"); 9750 return -1; 9751 } 9752 9753 /* 9754 * If the public key of the package's signature does not match 9755 * our expected public key, then this is a different package and 9756 * we should skip. 9757 */ 9758 9759 final byte[] expectedPublicKey; 9760 try { 9761 final Signature verifierSig = pkg.mSignatures[0]; 9762 final PublicKey publicKey = verifierSig.getPublicKey(); 9763 expectedPublicKey = publicKey.getEncoded(); 9764 } catch (CertificateException e) { 9765 return -1; 9766 } 9767 9768 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9769 9770 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9771 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9772 + " does not have the expected public key; ignoring"); 9773 return -1; 9774 } 9775 9776 return pkg.applicationInfo.uid; 9777 } 9778 } 9779 9780 @Override 9781 public void finishPackageInstall(int token) { 9782 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9783 9784 if (DEBUG_INSTALL) { 9785 Slog.v(TAG, "BM finishing package install for " + token); 9786 } 9787 9788 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9789 mHandler.sendMessage(msg); 9790 } 9791 9792 /** 9793 * Get the verification agent timeout. 9794 * 9795 * @return verification timeout in milliseconds 9796 */ 9797 private long getVerificationTimeout() { 9798 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9799 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9800 DEFAULT_VERIFICATION_TIMEOUT); 9801 } 9802 9803 /** 9804 * Get the default verification agent response code. 9805 * 9806 * @return default verification response code 9807 */ 9808 private int getDefaultVerificationResponse() { 9809 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9810 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9811 DEFAULT_VERIFICATION_RESPONSE); 9812 } 9813 9814 /** 9815 * Check whether or not package verification has been enabled. 9816 * 9817 * @return true if verification should be performed 9818 */ 9819 private boolean isVerificationEnabled(int userId, int installFlags) { 9820 if (!DEFAULT_VERIFY_ENABLE) { 9821 return false; 9822 } 9823 9824 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9825 9826 // Check if installing from ADB 9827 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9828 // Do not run verification in a test harness environment 9829 if (ActivityManager.isRunningInTestHarness()) { 9830 return false; 9831 } 9832 if (ensureVerifyAppsEnabled) { 9833 return true; 9834 } 9835 // Check if the developer does not want package verification for ADB installs 9836 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9837 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9838 return false; 9839 } 9840 } 9841 9842 if (ensureVerifyAppsEnabled) { 9843 return true; 9844 } 9845 9846 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9847 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9848 } 9849 9850 @Override 9851 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9852 throws RemoteException { 9853 mContext.enforceCallingOrSelfPermission( 9854 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9855 "Only intentfilter verification agents can verify applications"); 9856 9857 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9858 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9859 Binder.getCallingUid(), verificationCode, failedDomains); 9860 msg.arg1 = id; 9861 msg.obj = response; 9862 mHandler.sendMessage(msg); 9863 } 9864 9865 @Override 9866 public int getIntentVerificationStatus(String packageName, int userId) { 9867 synchronized (mPackages) { 9868 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9869 } 9870 } 9871 9872 @Override 9873 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9874 mContext.enforceCallingOrSelfPermission( 9875 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9876 9877 boolean result = false; 9878 synchronized (mPackages) { 9879 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9880 } 9881 if (result) { 9882 scheduleWritePackageRestrictionsLocked(userId); 9883 } 9884 return result; 9885 } 9886 9887 @Override 9888 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9889 synchronized (mPackages) { 9890 return mSettings.getIntentFilterVerificationsLPr(packageName); 9891 } 9892 } 9893 9894 @Override 9895 public List<IntentFilter> getAllIntentFilters(String packageName) { 9896 if (TextUtils.isEmpty(packageName)) { 9897 return Collections.<IntentFilter>emptyList(); 9898 } 9899 synchronized (mPackages) { 9900 PackageParser.Package pkg = mPackages.get(packageName); 9901 if (pkg == null || pkg.activities == null) { 9902 return Collections.<IntentFilter>emptyList(); 9903 } 9904 final int count = pkg.activities.size(); 9905 ArrayList<IntentFilter> result = new ArrayList<>(); 9906 for (int n=0; n<count; n++) { 9907 PackageParser.Activity activity = pkg.activities.get(n); 9908 if (activity.intents != null || activity.intents.size() > 0) { 9909 result.addAll(activity.intents); 9910 } 9911 } 9912 return result; 9913 } 9914 } 9915 9916 @Override 9917 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9918 mContext.enforceCallingOrSelfPermission( 9919 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9920 9921 synchronized (mPackages) { 9922 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9923 if (packageName != null) { 9924 result |= updateIntentVerificationStatus(packageName, 9925 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9926 userId); 9927 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9928 packageName, userId); 9929 } 9930 return result; 9931 } 9932 } 9933 9934 @Override 9935 public String getDefaultBrowserPackageName(int userId) { 9936 synchronized (mPackages) { 9937 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9938 } 9939 } 9940 9941 /** 9942 * Get the "allow unknown sources" setting. 9943 * 9944 * @return the current "allow unknown sources" setting 9945 */ 9946 private int getUnknownSourcesSettings() { 9947 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9948 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9949 -1); 9950 } 9951 9952 @Override 9953 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9954 final int uid = Binder.getCallingUid(); 9955 // writer 9956 synchronized (mPackages) { 9957 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9958 if (targetPackageSetting == null) { 9959 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9960 } 9961 9962 PackageSetting installerPackageSetting; 9963 if (installerPackageName != null) { 9964 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9965 if (installerPackageSetting == null) { 9966 throw new IllegalArgumentException("Unknown installer package: " 9967 + installerPackageName); 9968 } 9969 } else { 9970 installerPackageSetting = null; 9971 } 9972 9973 Signature[] callerSignature; 9974 Object obj = mSettings.getUserIdLPr(uid); 9975 if (obj != null) { 9976 if (obj instanceof SharedUserSetting) { 9977 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9978 } else if (obj instanceof PackageSetting) { 9979 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9980 } else { 9981 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9982 } 9983 } else { 9984 throw new SecurityException("Unknown calling uid " + uid); 9985 } 9986 9987 // Verify: can't set installerPackageName to a package that is 9988 // not signed with the same cert as the caller. 9989 if (installerPackageSetting != null) { 9990 if (compareSignatures(callerSignature, 9991 installerPackageSetting.signatures.mSignatures) 9992 != PackageManager.SIGNATURE_MATCH) { 9993 throw new SecurityException( 9994 "Caller does not have same cert as new installer package " 9995 + installerPackageName); 9996 } 9997 } 9998 9999 // Verify: if target already has an installer package, it must 10000 // be signed with the same cert as the caller. 10001 if (targetPackageSetting.installerPackageName != null) { 10002 PackageSetting setting = mSettings.mPackages.get( 10003 targetPackageSetting.installerPackageName); 10004 // If the currently set package isn't valid, then it's always 10005 // okay to change it. 10006 if (setting != null) { 10007 if (compareSignatures(callerSignature, 10008 setting.signatures.mSignatures) 10009 != PackageManager.SIGNATURE_MATCH) { 10010 throw new SecurityException( 10011 "Caller does not have same cert as old installer package " 10012 + targetPackageSetting.installerPackageName); 10013 } 10014 } 10015 } 10016 10017 // Okay! 10018 targetPackageSetting.installerPackageName = installerPackageName; 10019 scheduleWriteSettingsLocked(); 10020 } 10021 } 10022 10023 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10024 // Queue up an async operation since the package installation may take a little while. 10025 mHandler.post(new Runnable() { 10026 public void run() { 10027 mHandler.removeCallbacks(this); 10028 // Result object to be returned 10029 PackageInstalledInfo res = new PackageInstalledInfo(); 10030 res.returnCode = currentStatus; 10031 res.uid = -1; 10032 res.pkg = null; 10033 res.removedInfo = new PackageRemovedInfo(); 10034 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10035 args.doPreInstall(res.returnCode); 10036 synchronized (mInstallLock) { 10037 installPackageLI(args, res); 10038 } 10039 args.doPostInstall(res.returnCode, res.uid); 10040 } 10041 10042 // A restore should be performed at this point if (a) the install 10043 // succeeded, (b) the operation is not an update, and (c) the new 10044 // package has not opted out of backup participation. 10045 final boolean update = res.removedInfo.removedPackage != null; 10046 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10047 boolean doRestore = !update 10048 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10049 10050 // Set up the post-install work request bookkeeping. This will be used 10051 // and cleaned up by the post-install event handling regardless of whether 10052 // there's a restore pass performed. Token values are >= 1. 10053 int token; 10054 if (mNextInstallToken < 0) mNextInstallToken = 1; 10055 token = mNextInstallToken++; 10056 10057 PostInstallData data = new PostInstallData(args, res); 10058 mRunningInstalls.put(token, data); 10059 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10060 10061 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10062 // Pass responsibility to the Backup Manager. It will perform a 10063 // restore if appropriate, then pass responsibility back to the 10064 // Package Manager to run the post-install observer callbacks 10065 // and broadcasts. 10066 IBackupManager bm = IBackupManager.Stub.asInterface( 10067 ServiceManager.getService(Context.BACKUP_SERVICE)); 10068 if (bm != null) { 10069 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10070 + " to BM for possible restore"); 10071 try { 10072 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10073 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10074 } else { 10075 doRestore = false; 10076 } 10077 } catch (RemoteException e) { 10078 // can't happen; the backup manager is local 10079 } catch (Exception e) { 10080 Slog.e(TAG, "Exception trying to enqueue restore", e); 10081 doRestore = false; 10082 } 10083 } else { 10084 Slog.e(TAG, "Backup Manager not found!"); 10085 doRestore = false; 10086 } 10087 } 10088 10089 if (!doRestore) { 10090 // No restore possible, or the Backup Manager was mysteriously not 10091 // available -- just fire the post-install work request directly. 10092 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10093 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10094 mHandler.sendMessage(msg); 10095 } 10096 } 10097 }); 10098 } 10099 10100 private abstract class HandlerParams { 10101 private static final int MAX_RETRIES = 4; 10102 10103 /** 10104 * Number of times startCopy() has been attempted and had a non-fatal 10105 * error. 10106 */ 10107 private int mRetries = 0; 10108 10109 /** User handle for the user requesting the information or installation. */ 10110 private final UserHandle mUser; 10111 10112 HandlerParams(UserHandle user) { 10113 mUser = user; 10114 } 10115 10116 UserHandle getUser() { 10117 return mUser; 10118 } 10119 10120 final boolean startCopy() { 10121 boolean res; 10122 try { 10123 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10124 10125 if (++mRetries > MAX_RETRIES) { 10126 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10127 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10128 handleServiceError(); 10129 return false; 10130 } else { 10131 handleStartCopy(); 10132 res = true; 10133 } 10134 } catch (RemoteException e) { 10135 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10136 mHandler.sendEmptyMessage(MCS_RECONNECT); 10137 res = false; 10138 } 10139 handleReturnCode(); 10140 return res; 10141 } 10142 10143 final void serviceError() { 10144 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10145 handleServiceError(); 10146 handleReturnCode(); 10147 } 10148 10149 abstract void handleStartCopy() throws RemoteException; 10150 abstract void handleServiceError(); 10151 abstract void handleReturnCode(); 10152 } 10153 10154 class MeasureParams extends HandlerParams { 10155 private final PackageStats mStats; 10156 private boolean mSuccess; 10157 10158 private final IPackageStatsObserver mObserver; 10159 10160 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10161 super(new UserHandle(stats.userHandle)); 10162 mObserver = observer; 10163 mStats = stats; 10164 } 10165 10166 @Override 10167 public String toString() { 10168 return "MeasureParams{" 10169 + Integer.toHexString(System.identityHashCode(this)) 10170 + " " + mStats.packageName + "}"; 10171 } 10172 10173 @Override 10174 void handleStartCopy() throws RemoteException { 10175 synchronized (mInstallLock) { 10176 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10177 } 10178 10179 if (mSuccess) { 10180 final boolean mounted; 10181 if (Environment.isExternalStorageEmulated()) { 10182 mounted = true; 10183 } else { 10184 final String status = Environment.getExternalStorageState(); 10185 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10186 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10187 } 10188 10189 if (mounted) { 10190 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10191 10192 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10193 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10194 10195 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10196 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10197 10198 // Always subtract cache size, since it's a subdirectory 10199 mStats.externalDataSize -= mStats.externalCacheSize; 10200 10201 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10202 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10203 10204 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10205 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10206 } 10207 } 10208 } 10209 10210 @Override 10211 void handleReturnCode() { 10212 if (mObserver != null) { 10213 try { 10214 mObserver.onGetStatsCompleted(mStats, mSuccess); 10215 } catch (RemoteException e) { 10216 Slog.i(TAG, "Observer no longer exists."); 10217 } 10218 } 10219 } 10220 10221 @Override 10222 void handleServiceError() { 10223 Slog.e(TAG, "Could not measure application " + mStats.packageName 10224 + " external storage"); 10225 } 10226 } 10227 10228 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10229 throws RemoteException { 10230 long result = 0; 10231 for (File path : paths) { 10232 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10233 } 10234 return result; 10235 } 10236 10237 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10238 for (File path : paths) { 10239 try { 10240 mcs.clearDirectory(path.getAbsolutePath()); 10241 } catch (RemoteException e) { 10242 } 10243 } 10244 } 10245 10246 static class OriginInfo { 10247 /** 10248 * Location where install is coming from, before it has been 10249 * copied/renamed into place. This could be a single monolithic APK 10250 * file, or a cluster directory. This location may be untrusted. 10251 */ 10252 final File file; 10253 final String cid; 10254 10255 /** 10256 * Flag indicating that {@link #file} or {@link #cid} has already been 10257 * staged, meaning downstream users don't need to defensively copy the 10258 * contents. 10259 */ 10260 final boolean staged; 10261 10262 /** 10263 * Flag indicating that {@link #file} or {@link #cid} is an already 10264 * installed app that is being moved. 10265 */ 10266 final boolean existing; 10267 10268 final String resolvedPath; 10269 final File resolvedFile; 10270 10271 static OriginInfo fromNothing() { 10272 return new OriginInfo(null, null, false, false); 10273 } 10274 10275 static OriginInfo fromUntrustedFile(File file) { 10276 return new OriginInfo(file, null, false, false); 10277 } 10278 10279 static OriginInfo fromExistingFile(File file) { 10280 return new OriginInfo(file, null, false, true); 10281 } 10282 10283 static OriginInfo fromStagedFile(File file) { 10284 return new OriginInfo(file, null, true, false); 10285 } 10286 10287 static OriginInfo fromStagedContainer(String cid) { 10288 return new OriginInfo(null, cid, true, false); 10289 } 10290 10291 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10292 this.file = file; 10293 this.cid = cid; 10294 this.staged = staged; 10295 this.existing = existing; 10296 10297 if (cid != null) { 10298 resolvedPath = PackageHelper.getSdDir(cid); 10299 resolvedFile = new File(resolvedPath); 10300 } else if (file != null) { 10301 resolvedPath = file.getAbsolutePath(); 10302 resolvedFile = file; 10303 } else { 10304 resolvedPath = null; 10305 resolvedFile = null; 10306 } 10307 } 10308 } 10309 10310 class MoveInfo { 10311 final int moveId; 10312 final String fromUuid; 10313 final String toUuid; 10314 final String packageName; 10315 final String dataAppName; 10316 final int appId; 10317 final String seinfo; 10318 10319 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10320 String dataAppName, int appId, String seinfo) { 10321 this.moveId = moveId; 10322 this.fromUuid = fromUuid; 10323 this.toUuid = toUuid; 10324 this.packageName = packageName; 10325 this.dataAppName = dataAppName; 10326 this.appId = appId; 10327 this.seinfo = seinfo; 10328 } 10329 } 10330 10331 class InstallParams extends HandlerParams { 10332 final OriginInfo origin; 10333 final MoveInfo move; 10334 final IPackageInstallObserver2 observer; 10335 int installFlags; 10336 final String installerPackageName; 10337 final String volumeUuid; 10338 final VerificationParams verificationParams; 10339 private InstallArgs mArgs; 10340 private int mRet; 10341 final String packageAbiOverride; 10342 10343 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10344 int installFlags, String installerPackageName, String volumeUuid, 10345 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10346 super(user); 10347 this.origin = origin; 10348 this.move = move; 10349 this.observer = observer; 10350 this.installFlags = installFlags; 10351 this.installerPackageName = installerPackageName; 10352 this.volumeUuid = volumeUuid; 10353 this.verificationParams = verificationParams; 10354 this.packageAbiOverride = packageAbiOverride; 10355 } 10356 10357 @Override 10358 public String toString() { 10359 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10360 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10361 } 10362 10363 public ManifestDigest getManifestDigest() { 10364 if (verificationParams == null) { 10365 return null; 10366 } 10367 return verificationParams.getManifestDigest(); 10368 } 10369 10370 private int installLocationPolicy(PackageInfoLite pkgLite) { 10371 String packageName = pkgLite.packageName; 10372 int installLocation = pkgLite.installLocation; 10373 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10374 // reader 10375 synchronized (mPackages) { 10376 PackageParser.Package pkg = mPackages.get(packageName); 10377 if (pkg != null) { 10378 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10379 // Check for downgrading. 10380 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10381 try { 10382 checkDowngrade(pkg, pkgLite); 10383 } catch (PackageManagerException e) { 10384 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10385 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10386 } 10387 } 10388 // Check for updated system application. 10389 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10390 if (onSd) { 10391 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10392 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10393 } 10394 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10395 } else { 10396 if (onSd) { 10397 // Install flag overrides everything. 10398 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10399 } 10400 // If current upgrade specifies particular preference 10401 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10402 // Application explicitly specified internal. 10403 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10404 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10405 // App explictly prefers external. Let policy decide 10406 } else { 10407 // Prefer previous location 10408 if (isExternal(pkg)) { 10409 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10410 } 10411 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10412 } 10413 } 10414 } else { 10415 // Invalid install. Return error code 10416 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10417 } 10418 } 10419 } 10420 // All the special cases have been taken care of. 10421 // Return result based on recommended install location. 10422 if (onSd) { 10423 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10424 } 10425 return pkgLite.recommendedInstallLocation; 10426 } 10427 10428 /* 10429 * Invoke remote method to get package information and install 10430 * location values. Override install location based on default 10431 * policy if needed and then create install arguments based 10432 * on the install location. 10433 */ 10434 public void handleStartCopy() throws RemoteException { 10435 int ret = PackageManager.INSTALL_SUCCEEDED; 10436 10437 // If we're already staged, we've firmly committed to an install location 10438 if (origin.staged) { 10439 if (origin.file != null) { 10440 installFlags |= PackageManager.INSTALL_INTERNAL; 10441 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10442 } else if (origin.cid != null) { 10443 installFlags |= PackageManager.INSTALL_EXTERNAL; 10444 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10445 } else { 10446 throw new IllegalStateException("Invalid stage location"); 10447 } 10448 } 10449 10450 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10451 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10452 10453 PackageInfoLite pkgLite = null; 10454 10455 if (onInt && onSd) { 10456 // Check if both bits are set. 10457 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10458 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10459 } else { 10460 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10461 packageAbiOverride); 10462 10463 /* 10464 * If we have too little free space, try to free cache 10465 * before giving up. 10466 */ 10467 if (!origin.staged && pkgLite.recommendedInstallLocation 10468 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10469 // TODO: focus freeing disk space on the target device 10470 final StorageManager storage = StorageManager.from(mContext); 10471 final long lowThreshold = storage.getStorageLowBytes( 10472 Environment.getDataDirectory()); 10473 10474 final long sizeBytes = mContainerService.calculateInstalledSize( 10475 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10476 10477 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10478 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10479 installFlags, packageAbiOverride); 10480 } 10481 10482 /* 10483 * The cache free must have deleted the file we 10484 * downloaded to install. 10485 * 10486 * TODO: fix the "freeCache" call to not delete 10487 * the file we care about. 10488 */ 10489 if (pkgLite.recommendedInstallLocation 10490 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10491 pkgLite.recommendedInstallLocation 10492 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10493 } 10494 } 10495 } 10496 10497 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10498 int loc = pkgLite.recommendedInstallLocation; 10499 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10500 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10501 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10502 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10503 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10504 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10505 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10506 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10507 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10508 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10509 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10510 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10511 } else { 10512 // Override with defaults if needed. 10513 loc = installLocationPolicy(pkgLite); 10514 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10515 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10516 } else if (!onSd && !onInt) { 10517 // Override install location with flags 10518 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10519 // Set the flag to install on external media. 10520 installFlags |= PackageManager.INSTALL_EXTERNAL; 10521 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10522 } else { 10523 // Make sure the flag for installing on external 10524 // media is unset 10525 installFlags |= PackageManager.INSTALL_INTERNAL; 10526 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10527 } 10528 } 10529 } 10530 } 10531 10532 final InstallArgs args = createInstallArgs(this); 10533 mArgs = args; 10534 10535 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10536 /* 10537 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10538 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10539 */ 10540 int userIdentifier = getUser().getIdentifier(); 10541 if (userIdentifier == UserHandle.USER_ALL 10542 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10543 userIdentifier = UserHandle.USER_OWNER; 10544 } 10545 10546 /* 10547 * Determine if we have any installed package verifiers. If we 10548 * do, then we'll defer to them to verify the packages. 10549 */ 10550 final int requiredUid = mRequiredVerifierPackage == null ? -1 10551 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10552 if (!origin.existing && requiredUid != -1 10553 && isVerificationEnabled(userIdentifier, installFlags)) { 10554 final Intent verification = new Intent( 10555 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10556 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10557 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10558 PACKAGE_MIME_TYPE); 10559 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10560 10561 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10562 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10563 0 /* TODO: Which userId? */); 10564 10565 if (DEBUG_VERIFY) { 10566 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10567 + verification.toString() + " with " + pkgLite.verifiers.length 10568 + " optional verifiers"); 10569 } 10570 10571 final int verificationId = mPendingVerificationToken++; 10572 10573 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10574 10575 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10576 installerPackageName); 10577 10578 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10579 installFlags); 10580 10581 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10582 pkgLite.packageName); 10583 10584 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10585 pkgLite.versionCode); 10586 10587 if (verificationParams != null) { 10588 if (verificationParams.getVerificationURI() != null) { 10589 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10590 verificationParams.getVerificationURI()); 10591 } 10592 if (verificationParams.getOriginatingURI() != null) { 10593 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10594 verificationParams.getOriginatingURI()); 10595 } 10596 if (verificationParams.getReferrer() != null) { 10597 verification.putExtra(Intent.EXTRA_REFERRER, 10598 verificationParams.getReferrer()); 10599 } 10600 if (verificationParams.getOriginatingUid() >= 0) { 10601 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10602 verificationParams.getOriginatingUid()); 10603 } 10604 if (verificationParams.getInstallerUid() >= 0) { 10605 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10606 verificationParams.getInstallerUid()); 10607 } 10608 } 10609 10610 final PackageVerificationState verificationState = new PackageVerificationState( 10611 requiredUid, args); 10612 10613 mPendingVerification.append(verificationId, verificationState); 10614 10615 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10616 receivers, verificationState); 10617 10618 /* 10619 * If any sufficient verifiers were listed in the package 10620 * manifest, attempt to ask them. 10621 */ 10622 if (sufficientVerifiers != null) { 10623 final int N = sufficientVerifiers.size(); 10624 if (N == 0) { 10625 Slog.i(TAG, "Additional verifiers required, but none installed."); 10626 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10627 } else { 10628 for (int i = 0; i < N; i++) { 10629 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10630 10631 final Intent sufficientIntent = new Intent(verification); 10632 sufficientIntent.setComponent(verifierComponent); 10633 10634 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10635 } 10636 } 10637 } 10638 10639 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10640 mRequiredVerifierPackage, receivers); 10641 if (ret == PackageManager.INSTALL_SUCCEEDED 10642 && mRequiredVerifierPackage != null) { 10643 /* 10644 * Send the intent to the required verification agent, 10645 * but only start the verification timeout after the 10646 * target BroadcastReceivers have run. 10647 */ 10648 verification.setComponent(requiredVerifierComponent); 10649 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10650 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10651 new BroadcastReceiver() { 10652 @Override 10653 public void onReceive(Context context, Intent intent) { 10654 final Message msg = mHandler 10655 .obtainMessage(CHECK_PENDING_VERIFICATION); 10656 msg.arg1 = verificationId; 10657 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10658 } 10659 }, null, 0, null, null); 10660 10661 /* 10662 * We don't want the copy to proceed until verification 10663 * succeeds, so null out this field. 10664 */ 10665 mArgs = null; 10666 } 10667 } else { 10668 /* 10669 * No package verification is enabled, so immediately start 10670 * the remote call to initiate copy using temporary file. 10671 */ 10672 ret = args.copyApk(mContainerService, true); 10673 } 10674 } 10675 10676 mRet = ret; 10677 } 10678 10679 @Override 10680 void handleReturnCode() { 10681 // If mArgs is null, then MCS couldn't be reached. When it 10682 // reconnects, it will try again to install. At that point, this 10683 // will succeed. 10684 if (mArgs != null) { 10685 processPendingInstall(mArgs, mRet); 10686 } 10687 } 10688 10689 @Override 10690 void handleServiceError() { 10691 mArgs = createInstallArgs(this); 10692 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10693 } 10694 10695 public boolean isForwardLocked() { 10696 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10697 } 10698 } 10699 10700 /** 10701 * Used during creation of InstallArgs 10702 * 10703 * @param installFlags package installation flags 10704 * @return true if should be installed on external storage 10705 */ 10706 private static boolean installOnExternalAsec(int installFlags) { 10707 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10708 return false; 10709 } 10710 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10711 return true; 10712 } 10713 return false; 10714 } 10715 10716 /** 10717 * Used during creation of InstallArgs 10718 * 10719 * @param installFlags package installation flags 10720 * @return true if should be installed as forward locked 10721 */ 10722 private static boolean installForwardLocked(int installFlags) { 10723 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10724 } 10725 10726 private InstallArgs createInstallArgs(InstallParams params) { 10727 if (params.move != null) { 10728 return new MoveInstallArgs(params); 10729 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10730 return new AsecInstallArgs(params); 10731 } else { 10732 return new FileInstallArgs(params); 10733 } 10734 } 10735 10736 /** 10737 * Create args that describe an existing installed package. Typically used 10738 * when cleaning up old installs, or used as a move source. 10739 */ 10740 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10741 String resourcePath, String[] instructionSets) { 10742 final boolean isInAsec; 10743 if (installOnExternalAsec(installFlags)) { 10744 /* Apps on SD card are always in ASEC containers. */ 10745 isInAsec = true; 10746 } else if (installForwardLocked(installFlags) 10747 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10748 /* 10749 * Forward-locked apps are only in ASEC containers if they're the 10750 * new style 10751 */ 10752 isInAsec = true; 10753 } else { 10754 isInAsec = false; 10755 } 10756 10757 if (isInAsec) { 10758 return new AsecInstallArgs(codePath, instructionSets, 10759 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10760 } else { 10761 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10762 } 10763 } 10764 10765 static abstract class InstallArgs { 10766 /** @see InstallParams#origin */ 10767 final OriginInfo origin; 10768 /** @see InstallParams#move */ 10769 final MoveInfo move; 10770 10771 final IPackageInstallObserver2 observer; 10772 // Always refers to PackageManager flags only 10773 final int installFlags; 10774 final String installerPackageName; 10775 final String volumeUuid; 10776 final ManifestDigest manifestDigest; 10777 final UserHandle user; 10778 final String abiOverride; 10779 10780 // The list of instruction sets supported by this app. This is currently 10781 // only used during the rmdex() phase to clean up resources. We can get rid of this 10782 // if we move dex files under the common app path. 10783 /* nullable */ String[] instructionSets; 10784 10785 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10786 int installFlags, String installerPackageName, String volumeUuid, 10787 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10788 String abiOverride) { 10789 this.origin = origin; 10790 this.move = move; 10791 this.installFlags = installFlags; 10792 this.observer = observer; 10793 this.installerPackageName = installerPackageName; 10794 this.volumeUuid = volumeUuid; 10795 this.manifestDigest = manifestDigest; 10796 this.user = user; 10797 this.instructionSets = instructionSets; 10798 this.abiOverride = abiOverride; 10799 } 10800 10801 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10802 abstract int doPreInstall(int status); 10803 10804 /** 10805 * Rename package into final resting place. All paths on the given 10806 * scanned package should be updated to reflect the rename. 10807 */ 10808 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10809 abstract int doPostInstall(int status, int uid); 10810 10811 /** @see PackageSettingBase#codePathString */ 10812 abstract String getCodePath(); 10813 /** @see PackageSettingBase#resourcePathString */ 10814 abstract String getResourcePath(); 10815 10816 // Need installer lock especially for dex file removal. 10817 abstract void cleanUpResourcesLI(); 10818 abstract boolean doPostDeleteLI(boolean delete); 10819 10820 /** 10821 * Called before the source arguments are copied. This is used mostly 10822 * for MoveParams when it needs to read the source file to put it in the 10823 * destination. 10824 */ 10825 int doPreCopy() { 10826 return PackageManager.INSTALL_SUCCEEDED; 10827 } 10828 10829 /** 10830 * Called after the source arguments are copied. This is used mostly for 10831 * MoveParams when it needs to read the source file to put it in the 10832 * destination. 10833 * 10834 * @return 10835 */ 10836 int doPostCopy(int uid) { 10837 return PackageManager.INSTALL_SUCCEEDED; 10838 } 10839 10840 protected boolean isFwdLocked() { 10841 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10842 } 10843 10844 protected boolean isExternalAsec() { 10845 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10846 } 10847 10848 UserHandle getUser() { 10849 return user; 10850 } 10851 } 10852 10853 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10854 if (!allCodePaths.isEmpty()) { 10855 if (instructionSets == null) { 10856 throw new IllegalStateException("instructionSet == null"); 10857 } 10858 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10859 for (String codePath : allCodePaths) { 10860 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10861 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10862 if (retCode < 0) { 10863 Slog.w(TAG, "Couldn't remove dex file for package: " 10864 + " at location " + codePath + ", retcode=" + retCode); 10865 // we don't consider this to be a failure of the core package deletion 10866 } 10867 } 10868 } 10869 } 10870 } 10871 10872 /** 10873 * Logic to handle installation of non-ASEC applications, including copying 10874 * and renaming logic. 10875 */ 10876 class FileInstallArgs extends InstallArgs { 10877 private File codeFile; 10878 private File resourceFile; 10879 10880 // Example topology: 10881 // /data/app/com.example/base.apk 10882 // /data/app/com.example/split_foo.apk 10883 // /data/app/com.example/lib/arm/libfoo.so 10884 // /data/app/com.example/lib/arm64/libfoo.so 10885 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10886 10887 /** New install */ 10888 FileInstallArgs(InstallParams params) { 10889 super(params.origin, params.move, params.observer, params.installFlags, 10890 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10891 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10892 if (isFwdLocked()) { 10893 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10894 } 10895 } 10896 10897 /** Existing install */ 10898 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10899 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10900 null); 10901 this.codeFile = (codePath != null) ? new File(codePath) : null; 10902 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10903 } 10904 10905 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10906 if (origin.staged) { 10907 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10908 codeFile = origin.file; 10909 resourceFile = origin.file; 10910 return PackageManager.INSTALL_SUCCEEDED; 10911 } 10912 10913 try { 10914 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10915 codeFile = tempDir; 10916 resourceFile = tempDir; 10917 } catch (IOException e) { 10918 Slog.w(TAG, "Failed to create copy file: " + e); 10919 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10920 } 10921 10922 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10923 @Override 10924 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10925 if (!FileUtils.isValidExtFilename(name)) { 10926 throw new IllegalArgumentException("Invalid filename: " + name); 10927 } 10928 try { 10929 final File file = new File(codeFile, name); 10930 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10931 O_RDWR | O_CREAT, 0644); 10932 Os.chmod(file.getAbsolutePath(), 0644); 10933 return new ParcelFileDescriptor(fd); 10934 } catch (ErrnoException e) { 10935 throw new RemoteException("Failed to open: " + e.getMessage()); 10936 } 10937 } 10938 }; 10939 10940 int ret = PackageManager.INSTALL_SUCCEEDED; 10941 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10942 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10943 Slog.e(TAG, "Failed to copy package"); 10944 return ret; 10945 } 10946 10947 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10948 NativeLibraryHelper.Handle handle = null; 10949 try { 10950 handle = NativeLibraryHelper.Handle.create(codeFile); 10951 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10952 abiOverride); 10953 } catch (IOException e) { 10954 Slog.e(TAG, "Copying native libraries failed", e); 10955 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10956 } finally { 10957 IoUtils.closeQuietly(handle); 10958 } 10959 10960 return ret; 10961 } 10962 10963 int doPreInstall(int status) { 10964 if (status != PackageManager.INSTALL_SUCCEEDED) { 10965 cleanUp(); 10966 } 10967 return status; 10968 } 10969 10970 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10971 if (status != PackageManager.INSTALL_SUCCEEDED) { 10972 cleanUp(); 10973 return false; 10974 } 10975 10976 final File targetDir = codeFile.getParentFile(); 10977 final File beforeCodeFile = codeFile; 10978 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10979 10980 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10981 try { 10982 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10983 } catch (ErrnoException e) { 10984 Slog.w(TAG, "Failed to rename", e); 10985 return false; 10986 } 10987 10988 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10989 Slog.w(TAG, "Failed to restorecon"); 10990 return false; 10991 } 10992 10993 // Reflect the rename internally 10994 codeFile = afterCodeFile; 10995 resourceFile = afterCodeFile; 10996 10997 // Reflect the rename in scanned details 10998 pkg.codePath = afterCodeFile.getAbsolutePath(); 10999 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11000 pkg.baseCodePath); 11001 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11002 pkg.splitCodePaths); 11003 11004 // Reflect the rename in app info 11005 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11006 pkg.applicationInfo.setCodePath(pkg.codePath); 11007 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11008 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11009 pkg.applicationInfo.setResourcePath(pkg.codePath); 11010 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11011 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11012 11013 return true; 11014 } 11015 11016 int doPostInstall(int status, int uid) { 11017 if (status != PackageManager.INSTALL_SUCCEEDED) { 11018 cleanUp(); 11019 } 11020 return status; 11021 } 11022 11023 @Override 11024 String getCodePath() { 11025 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11026 } 11027 11028 @Override 11029 String getResourcePath() { 11030 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11031 } 11032 11033 private boolean cleanUp() { 11034 if (codeFile == null || !codeFile.exists()) { 11035 return false; 11036 } 11037 11038 if (codeFile.isDirectory()) { 11039 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11040 } else { 11041 codeFile.delete(); 11042 } 11043 11044 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11045 resourceFile.delete(); 11046 } 11047 11048 return true; 11049 } 11050 11051 void cleanUpResourcesLI() { 11052 // Try enumerating all code paths before deleting 11053 List<String> allCodePaths = Collections.EMPTY_LIST; 11054 if (codeFile != null && codeFile.exists()) { 11055 try { 11056 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11057 allCodePaths = pkg.getAllCodePaths(); 11058 } catch (PackageParserException e) { 11059 // Ignored; we tried our best 11060 } 11061 } 11062 11063 cleanUp(); 11064 removeDexFiles(allCodePaths, instructionSets); 11065 } 11066 11067 boolean doPostDeleteLI(boolean delete) { 11068 // XXX err, shouldn't we respect the delete flag? 11069 cleanUpResourcesLI(); 11070 return true; 11071 } 11072 } 11073 11074 private boolean isAsecExternal(String cid) { 11075 final String asecPath = PackageHelper.getSdFilesystem(cid); 11076 return !asecPath.startsWith(mAsecInternalPath); 11077 } 11078 11079 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11080 PackageManagerException { 11081 if (copyRet < 0) { 11082 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11083 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11084 throw new PackageManagerException(copyRet, message); 11085 } 11086 } 11087 } 11088 11089 /** 11090 * Extract the MountService "container ID" from the full code path of an 11091 * .apk. 11092 */ 11093 static String cidFromCodePath(String fullCodePath) { 11094 int eidx = fullCodePath.lastIndexOf("/"); 11095 String subStr1 = fullCodePath.substring(0, eidx); 11096 int sidx = subStr1.lastIndexOf("/"); 11097 return subStr1.substring(sidx+1, eidx); 11098 } 11099 11100 /** 11101 * Logic to handle installation of ASEC applications, including copying and 11102 * renaming logic. 11103 */ 11104 class AsecInstallArgs extends InstallArgs { 11105 static final String RES_FILE_NAME = "pkg.apk"; 11106 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11107 11108 String cid; 11109 String packagePath; 11110 String resourcePath; 11111 11112 /** New install */ 11113 AsecInstallArgs(InstallParams params) { 11114 super(params.origin, params.move, params.observer, params.installFlags, 11115 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11116 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11117 } 11118 11119 /** Existing install */ 11120 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11121 boolean isExternal, boolean isForwardLocked) { 11122 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11123 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11124 instructionSets, null); 11125 // Hackily pretend we're still looking at a full code path 11126 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11127 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11128 } 11129 11130 // Extract cid from fullCodePath 11131 int eidx = fullCodePath.lastIndexOf("/"); 11132 String subStr1 = fullCodePath.substring(0, eidx); 11133 int sidx = subStr1.lastIndexOf("/"); 11134 cid = subStr1.substring(sidx+1, eidx); 11135 setMountPath(subStr1); 11136 } 11137 11138 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11139 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11140 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11141 instructionSets, null); 11142 this.cid = cid; 11143 setMountPath(PackageHelper.getSdDir(cid)); 11144 } 11145 11146 void createCopyFile() { 11147 cid = mInstallerService.allocateExternalStageCidLegacy(); 11148 } 11149 11150 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11151 if (origin.staged) { 11152 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11153 cid = origin.cid; 11154 setMountPath(PackageHelper.getSdDir(cid)); 11155 return PackageManager.INSTALL_SUCCEEDED; 11156 } 11157 11158 if (temp) { 11159 createCopyFile(); 11160 } else { 11161 /* 11162 * Pre-emptively destroy the container since it's destroyed if 11163 * copying fails due to it existing anyway. 11164 */ 11165 PackageHelper.destroySdDir(cid); 11166 } 11167 11168 final String newMountPath = imcs.copyPackageToContainer( 11169 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11170 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11171 11172 if (newMountPath != null) { 11173 setMountPath(newMountPath); 11174 return PackageManager.INSTALL_SUCCEEDED; 11175 } else { 11176 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11177 } 11178 } 11179 11180 @Override 11181 String getCodePath() { 11182 return packagePath; 11183 } 11184 11185 @Override 11186 String getResourcePath() { 11187 return resourcePath; 11188 } 11189 11190 int doPreInstall(int status) { 11191 if (status != PackageManager.INSTALL_SUCCEEDED) { 11192 // Destroy container 11193 PackageHelper.destroySdDir(cid); 11194 } else { 11195 boolean mounted = PackageHelper.isContainerMounted(cid); 11196 if (!mounted) { 11197 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11198 Process.SYSTEM_UID); 11199 if (newMountPath != null) { 11200 setMountPath(newMountPath); 11201 } else { 11202 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11203 } 11204 } 11205 } 11206 return status; 11207 } 11208 11209 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11210 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11211 String newMountPath = null; 11212 if (PackageHelper.isContainerMounted(cid)) { 11213 // Unmount the container 11214 if (!PackageHelper.unMountSdDir(cid)) { 11215 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11216 return false; 11217 } 11218 } 11219 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11220 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11221 " which might be stale. Will try to clean up."); 11222 // Clean up the stale container and proceed to recreate. 11223 if (!PackageHelper.destroySdDir(newCacheId)) { 11224 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11225 return false; 11226 } 11227 // Successfully cleaned up stale container. Try to rename again. 11228 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11229 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11230 + " inspite of cleaning it up."); 11231 return false; 11232 } 11233 } 11234 if (!PackageHelper.isContainerMounted(newCacheId)) { 11235 Slog.w(TAG, "Mounting container " + newCacheId); 11236 newMountPath = PackageHelper.mountSdDir(newCacheId, 11237 getEncryptKey(), Process.SYSTEM_UID); 11238 } else { 11239 newMountPath = PackageHelper.getSdDir(newCacheId); 11240 } 11241 if (newMountPath == null) { 11242 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11243 return false; 11244 } 11245 Log.i(TAG, "Succesfully renamed " + cid + 11246 " to " + newCacheId + 11247 " at new path: " + newMountPath); 11248 cid = newCacheId; 11249 11250 final File beforeCodeFile = new File(packagePath); 11251 setMountPath(newMountPath); 11252 final File afterCodeFile = new File(packagePath); 11253 11254 // Reflect the rename in scanned details 11255 pkg.codePath = afterCodeFile.getAbsolutePath(); 11256 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11257 pkg.baseCodePath); 11258 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11259 pkg.splitCodePaths); 11260 11261 // Reflect the rename in app info 11262 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11263 pkg.applicationInfo.setCodePath(pkg.codePath); 11264 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11265 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11266 pkg.applicationInfo.setResourcePath(pkg.codePath); 11267 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11268 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11269 11270 return true; 11271 } 11272 11273 private void setMountPath(String mountPath) { 11274 final File mountFile = new File(mountPath); 11275 11276 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11277 if (monolithicFile.exists()) { 11278 packagePath = monolithicFile.getAbsolutePath(); 11279 if (isFwdLocked()) { 11280 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11281 } else { 11282 resourcePath = packagePath; 11283 } 11284 } else { 11285 packagePath = mountFile.getAbsolutePath(); 11286 resourcePath = packagePath; 11287 } 11288 } 11289 11290 int doPostInstall(int status, int uid) { 11291 if (status != PackageManager.INSTALL_SUCCEEDED) { 11292 cleanUp(); 11293 } else { 11294 final int groupOwner; 11295 final String protectedFile; 11296 if (isFwdLocked()) { 11297 groupOwner = UserHandle.getSharedAppGid(uid); 11298 protectedFile = RES_FILE_NAME; 11299 } else { 11300 groupOwner = -1; 11301 protectedFile = null; 11302 } 11303 11304 if (uid < Process.FIRST_APPLICATION_UID 11305 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11306 Slog.e(TAG, "Failed to finalize " + cid); 11307 PackageHelper.destroySdDir(cid); 11308 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11309 } 11310 11311 boolean mounted = PackageHelper.isContainerMounted(cid); 11312 if (!mounted) { 11313 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11314 } 11315 } 11316 return status; 11317 } 11318 11319 private void cleanUp() { 11320 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11321 11322 // Destroy secure container 11323 PackageHelper.destroySdDir(cid); 11324 } 11325 11326 private List<String> getAllCodePaths() { 11327 final File codeFile = new File(getCodePath()); 11328 if (codeFile != null && codeFile.exists()) { 11329 try { 11330 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11331 return pkg.getAllCodePaths(); 11332 } catch (PackageParserException e) { 11333 // Ignored; we tried our best 11334 } 11335 } 11336 return Collections.EMPTY_LIST; 11337 } 11338 11339 void cleanUpResourcesLI() { 11340 // Enumerate all code paths before deleting 11341 cleanUpResourcesLI(getAllCodePaths()); 11342 } 11343 11344 private void cleanUpResourcesLI(List<String> allCodePaths) { 11345 cleanUp(); 11346 removeDexFiles(allCodePaths, instructionSets); 11347 } 11348 11349 String getPackageName() { 11350 return getAsecPackageName(cid); 11351 } 11352 11353 boolean doPostDeleteLI(boolean delete) { 11354 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11355 final List<String> allCodePaths = getAllCodePaths(); 11356 boolean mounted = PackageHelper.isContainerMounted(cid); 11357 if (mounted) { 11358 // Unmount first 11359 if (PackageHelper.unMountSdDir(cid)) { 11360 mounted = false; 11361 } 11362 } 11363 if (!mounted && delete) { 11364 cleanUpResourcesLI(allCodePaths); 11365 } 11366 return !mounted; 11367 } 11368 11369 @Override 11370 int doPreCopy() { 11371 if (isFwdLocked()) { 11372 if (!PackageHelper.fixSdPermissions(cid, 11373 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11374 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11375 } 11376 } 11377 11378 return PackageManager.INSTALL_SUCCEEDED; 11379 } 11380 11381 @Override 11382 int doPostCopy(int uid) { 11383 if (isFwdLocked()) { 11384 if (uid < Process.FIRST_APPLICATION_UID 11385 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11386 RES_FILE_NAME)) { 11387 Slog.e(TAG, "Failed to finalize " + cid); 11388 PackageHelper.destroySdDir(cid); 11389 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11390 } 11391 } 11392 11393 return PackageManager.INSTALL_SUCCEEDED; 11394 } 11395 } 11396 11397 /** 11398 * Logic to handle movement of existing installed applications. 11399 */ 11400 class MoveInstallArgs extends InstallArgs { 11401 private File codeFile; 11402 private File resourceFile; 11403 11404 /** New install */ 11405 MoveInstallArgs(InstallParams params) { 11406 super(params.origin, params.move, params.observer, params.installFlags, 11407 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11408 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11409 } 11410 11411 int copyApk(IMediaContainerService imcs, boolean temp) { 11412 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11413 + move.fromUuid + " to " + move.toUuid); 11414 synchronized (mInstaller) { 11415 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11416 move.dataAppName, move.appId, move.seinfo) != 0) { 11417 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11418 } 11419 } 11420 11421 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11422 resourceFile = codeFile; 11423 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11424 11425 return PackageManager.INSTALL_SUCCEEDED; 11426 } 11427 11428 int doPreInstall(int status) { 11429 if (status != PackageManager.INSTALL_SUCCEEDED) { 11430 cleanUp(move.toUuid); 11431 } 11432 return status; 11433 } 11434 11435 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11436 if (status != PackageManager.INSTALL_SUCCEEDED) { 11437 cleanUp(move.toUuid); 11438 return false; 11439 } 11440 11441 // Reflect the move in app info 11442 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11443 pkg.applicationInfo.setCodePath(pkg.codePath); 11444 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11445 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11446 pkg.applicationInfo.setResourcePath(pkg.codePath); 11447 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11448 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11449 11450 return true; 11451 } 11452 11453 int doPostInstall(int status, int uid) { 11454 if (status == PackageManager.INSTALL_SUCCEEDED) { 11455 cleanUp(move.fromUuid); 11456 } else { 11457 cleanUp(move.toUuid); 11458 } 11459 return status; 11460 } 11461 11462 @Override 11463 String getCodePath() { 11464 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11465 } 11466 11467 @Override 11468 String getResourcePath() { 11469 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11470 } 11471 11472 private boolean cleanUp(String volumeUuid) { 11473 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11474 move.dataAppName); 11475 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11476 synchronized (mInstallLock) { 11477 // Clean up both app data and code 11478 removeDataDirsLI(volumeUuid, move.packageName); 11479 if (codeFile.isDirectory()) { 11480 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11481 } else { 11482 codeFile.delete(); 11483 } 11484 } 11485 return true; 11486 } 11487 11488 void cleanUpResourcesLI() { 11489 throw new UnsupportedOperationException(); 11490 } 11491 11492 boolean doPostDeleteLI(boolean delete) { 11493 throw new UnsupportedOperationException(); 11494 } 11495 } 11496 11497 static String getAsecPackageName(String packageCid) { 11498 int idx = packageCid.lastIndexOf("-"); 11499 if (idx == -1) { 11500 return packageCid; 11501 } 11502 return packageCid.substring(0, idx); 11503 } 11504 11505 // Utility method used to create code paths based on package name and available index. 11506 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11507 String idxStr = ""; 11508 int idx = 1; 11509 // Fall back to default value of idx=1 if prefix is not 11510 // part of oldCodePath 11511 if (oldCodePath != null) { 11512 String subStr = oldCodePath; 11513 // Drop the suffix right away 11514 if (suffix != null && subStr.endsWith(suffix)) { 11515 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11516 } 11517 // If oldCodePath already contains prefix find out the 11518 // ending index to either increment or decrement. 11519 int sidx = subStr.lastIndexOf(prefix); 11520 if (sidx != -1) { 11521 subStr = subStr.substring(sidx + prefix.length()); 11522 if (subStr != null) { 11523 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11524 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11525 } 11526 try { 11527 idx = Integer.parseInt(subStr); 11528 if (idx <= 1) { 11529 idx++; 11530 } else { 11531 idx--; 11532 } 11533 } catch(NumberFormatException e) { 11534 } 11535 } 11536 } 11537 } 11538 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11539 return prefix + idxStr; 11540 } 11541 11542 private File getNextCodePath(File targetDir, String packageName) { 11543 int suffix = 1; 11544 File result; 11545 do { 11546 result = new File(targetDir, packageName + "-" + suffix); 11547 suffix++; 11548 } while (result.exists()); 11549 return result; 11550 } 11551 11552 // Utility method that returns the relative package path with respect 11553 // to the installation directory. Like say for /data/data/com.test-1.apk 11554 // string com.test-1 is returned. 11555 static String deriveCodePathName(String codePath) { 11556 if (codePath == null) { 11557 return null; 11558 } 11559 final File codeFile = new File(codePath); 11560 final String name = codeFile.getName(); 11561 if (codeFile.isDirectory()) { 11562 return name; 11563 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11564 final int lastDot = name.lastIndexOf('.'); 11565 return name.substring(0, lastDot); 11566 } else { 11567 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11568 return null; 11569 } 11570 } 11571 11572 class PackageInstalledInfo { 11573 String name; 11574 int uid; 11575 // The set of users that originally had this package installed. 11576 int[] origUsers; 11577 // The set of users that now have this package installed. 11578 int[] newUsers; 11579 PackageParser.Package pkg; 11580 int returnCode; 11581 String returnMsg; 11582 PackageRemovedInfo removedInfo; 11583 11584 public void setError(int code, String msg) { 11585 returnCode = code; 11586 returnMsg = msg; 11587 Slog.w(TAG, msg); 11588 } 11589 11590 public void setError(String msg, PackageParserException e) { 11591 returnCode = e.error; 11592 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11593 Slog.w(TAG, msg, e); 11594 } 11595 11596 public void setError(String msg, PackageManagerException e) { 11597 returnCode = e.error; 11598 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11599 Slog.w(TAG, msg, e); 11600 } 11601 11602 // In some error cases we want to convey more info back to the observer 11603 String origPackage; 11604 String origPermission; 11605 } 11606 11607 /* 11608 * Install a non-existing package. 11609 */ 11610 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11611 UserHandle user, String installerPackageName, String volumeUuid, 11612 PackageInstalledInfo res) { 11613 // Remember this for later, in case we need to rollback this install 11614 String pkgName = pkg.packageName; 11615 11616 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11617 final boolean dataDirExists = Environment 11618 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11619 synchronized(mPackages) { 11620 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11621 // A package with the same name is already installed, though 11622 // it has been renamed to an older name. The package we 11623 // are trying to install should be installed as an update to 11624 // the existing one, but that has not been requested, so bail. 11625 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11626 + " without first uninstalling package running as " 11627 + mSettings.mRenamedPackages.get(pkgName)); 11628 return; 11629 } 11630 if (mPackages.containsKey(pkgName)) { 11631 // Don't allow installation over an existing package with the same name. 11632 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11633 + " without first uninstalling."); 11634 return; 11635 } 11636 } 11637 11638 try { 11639 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11640 System.currentTimeMillis(), user); 11641 11642 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11643 // delete the partially installed application. the data directory will have to be 11644 // restored if it was already existing 11645 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11646 // remove package from internal structures. Note that we want deletePackageX to 11647 // delete the package data and cache directories that it created in 11648 // scanPackageLocked, unless those directories existed before we even tried to 11649 // install. 11650 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11651 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11652 res.removedInfo, true); 11653 } 11654 11655 } catch (PackageManagerException e) { 11656 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11657 } 11658 } 11659 11660 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11661 // Can't rotate keys during boot or if sharedUser. 11662 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11663 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11664 return false; 11665 } 11666 // app is using upgradeKeySets; make sure all are valid 11667 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11668 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11669 for (int i = 0; i < upgradeKeySets.length; i++) { 11670 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11671 Slog.wtf(TAG, "Package " 11672 + (oldPs.name != null ? oldPs.name : "<null>") 11673 + " contains upgrade-key-set reference to unknown key-set: " 11674 + upgradeKeySets[i] 11675 + " reverting to signatures check."); 11676 return false; 11677 } 11678 } 11679 return true; 11680 } 11681 11682 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11683 // Upgrade keysets are being used. Determine if new package has a superset of the 11684 // required keys. 11685 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11686 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11687 for (int i = 0; i < upgradeKeySets.length; i++) { 11688 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11689 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11690 return true; 11691 } 11692 } 11693 return false; 11694 } 11695 11696 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11697 UserHandle user, String installerPackageName, String volumeUuid, 11698 PackageInstalledInfo res) { 11699 final PackageParser.Package oldPackage; 11700 final String pkgName = pkg.packageName; 11701 final int[] allUsers; 11702 final boolean[] perUserInstalled; 11703 final boolean weFroze; 11704 11705 // First find the old package info and check signatures 11706 synchronized(mPackages) { 11707 oldPackage = mPackages.get(pkgName); 11708 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11709 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11710 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11711 if(!checkUpgradeKeySetLP(ps, pkg)) { 11712 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11713 "New package not signed by keys specified by upgrade-keysets: " 11714 + pkgName); 11715 return; 11716 } 11717 } else { 11718 // default to original signature matching 11719 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11720 != PackageManager.SIGNATURE_MATCH) { 11721 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11722 "New package has a different signature: " + pkgName); 11723 return; 11724 } 11725 } 11726 11727 // In case of rollback, remember per-user/profile install state 11728 allUsers = sUserManager.getUserIds(); 11729 perUserInstalled = new boolean[allUsers.length]; 11730 for (int i = 0; i < allUsers.length; i++) { 11731 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11732 } 11733 11734 // Mark the app as frozen to prevent launching during the upgrade 11735 // process, and then kill all running instances 11736 if (!ps.frozen) { 11737 ps.frozen = true; 11738 weFroze = true; 11739 } else { 11740 weFroze = false; 11741 } 11742 } 11743 11744 // Now that we're guarded by frozen state, kill app during upgrade 11745 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11746 11747 try { 11748 boolean sysPkg = (isSystemApp(oldPackage)); 11749 if (sysPkg) { 11750 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11751 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11752 } else { 11753 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11754 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11755 } 11756 } finally { 11757 // Regardless of success or failure of upgrade steps above, always 11758 // unfreeze the package if we froze it 11759 if (weFroze) { 11760 unfreezePackage(pkgName); 11761 } 11762 } 11763 } 11764 11765 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11766 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11767 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11768 String volumeUuid, PackageInstalledInfo res) { 11769 String pkgName = deletedPackage.packageName; 11770 boolean deletedPkg = true; 11771 boolean updatedSettings = false; 11772 11773 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11774 + deletedPackage); 11775 long origUpdateTime; 11776 if (pkg.mExtras != null) { 11777 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11778 } else { 11779 origUpdateTime = 0; 11780 } 11781 11782 // First delete the existing package while retaining the data directory 11783 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11784 res.removedInfo, true)) { 11785 // If the existing package wasn't successfully deleted 11786 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11787 deletedPkg = false; 11788 } else { 11789 // Successfully deleted the old package; proceed with replace. 11790 11791 // If deleted package lived in a container, give users a chance to 11792 // relinquish resources before killing. 11793 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11794 if (DEBUG_INSTALL) { 11795 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11796 } 11797 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11798 final ArrayList<String> pkgList = new ArrayList<String>(1); 11799 pkgList.add(deletedPackage.applicationInfo.packageName); 11800 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11801 } 11802 11803 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11804 try { 11805 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11806 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11807 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11808 perUserInstalled, res, user); 11809 updatedSettings = true; 11810 } catch (PackageManagerException e) { 11811 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11812 } 11813 } 11814 11815 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11816 // remove package from internal structures. Note that we want deletePackageX to 11817 // delete the package data and cache directories that it created in 11818 // scanPackageLocked, unless those directories existed before we even tried to 11819 // install. 11820 if(updatedSettings) { 11821 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11822 deletePackageLI( 11823 pkgName, null, true, allUsers, perUserInstalled, 11824 PackageManager.DELETE_KEEP_DATA, 11825 res.removedInfo, true); 11826 } 11827 // Since we failed to install the new package we need to restore the old 11828 // package that we deleted. 11829 if (deletedPkg) { 11830 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11831 File restoreFile = new File(deletedPackage.codePath); 11832 // Parse old package 11833 boolean oldExternal = isExternal(deletedPackage); 11834 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11835 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11836 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11837 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11838 try { 11839 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11840 } catch (PackageManagerException e) { 11841 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11842 + e.getMessage()); 11843 return; 11844 } 11845 // Restore of old package succeeded. Update permissions. 11846 // writer 11847 synchronized (mPackages) { 11848 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11849 UPDATE_PERMISSIONS_ALL); 11850 // can downgrade to reader 11851 mSettings.writeLPr(); 11852 } 11853 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11854 } 11855 } 11856 } 11857 11858 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11859 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11860 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11861 String volumeUuid, PackageInstalledInfo res) { 11862 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11863 + ", old=" + deletedPackage); 11864 boolean disabledSystem = false; 11865 boolean updatedSettings = false; 11866 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11867 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11868 != 0) { 11869 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11870 } 11871 String packageName = deletedPackage.packageName; 11872 if (packageName == null) { 11873 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11874 "Attempt to delete null packageName."); 11875 return; 11876 } 11877 PackageParser.Package oldPkg; 11878 PackageSetting oldPkgSetting; 11879 // reader 11880 synchronized (mPackages) { 11881 oldPkg = mPackages.get(packageName); 11882 oldPkgSetting = mSettings.mPackages.get(packageName); 11883 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11884 (oldPkgSetting == null)) { 11885 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11886 "Couldn't find package:" + packageName + " information"); 11887 return; 11888 } 11889 } 11890 11891 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11892 res.removedInfo.removedPackage = packageName; 11893 // Remove existing system package 11894 removePackageLI(oldPkgSetting, true); 11895 // writer 11896 synchronized (mPackages) { 11897 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11898 if (!disabledSystem && deletedPackage != null) { 11899 // We didn't need to disable the .apk as a current system package, 11900 // which means we are replacing another update that is already 11901 // installed. We need to make sure to delete the older one's .apk. 11902 res.removedInfo.args = createInstallArgsForExisting(0, 11903 deletedPackage.applicationInfo.getCodePath(), 11904 deletedPackage.applicationInfo.getResourcePath(), 11905 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11906 } else { 11907 res.removedInfo.args = null; 11908 } 11909 } 11910 11911 // Successfully disabled the old package. Now proceed with re-installation 11912 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11913 11914 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11915 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11916 11917 PackageParser.Package newPackage = null; 11918 try { 11919 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11920 if (newPackage.mExtras != null) { 11921 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11922 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11923 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11924 11925 // is the update attempting to change shared user? that isn't going to work... 11926 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11927 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11928 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11929 + " to " + newPkgSetting.sharedUser); 11930 updatedSettings = true; 11931 } 11932 } 11933 11934 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11935 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11936 perUserInstalled, res, user); 11937 updatedSettings = true; 11938 } 11939 11940 } catch (PackageManagerException e) { 11941 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11942 } 11943 11944 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11945 // Re installation failed. Restore old information 11946 // Remove new pkg information 11947 if (newPackage != null) { 11948 removeInstalledPackageLI(newPackage, true); 11949 } 11950 // Add back the old system package 11951 try { 11952 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11953 } catch (PackageManagerException e) { 11954 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11955 } 11956 // Restore the old system information in Settings 11957 synchronized (mPackages) { 11958 if (disabledSystem) { 11959 mSettings.enableSystemPackageLPw(packageName); 11960 } 11961 if (updatedSettings) { 11962 mSettings.setInstallerPackageName(packageName, 11963 oldPkgSetting.installerPackageName); 11964 } 11965 mSettings.writeLPr(); 11966 } 11967 } 11968 } 11969 11970 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11971 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11972 UserHandle user) { 11973 String pkgName = newPackage.packageName; 11974 synchronized (mPackages) { 11975 //write settings. the installStatus will be incomplete at this stage. 11976 //note that the new package setting would have already been 11977 //added to mPackages. It hasn't been persisted yet. 11978 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11979 mSettings.writeLPr(); 11980 } 11981 11982 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11983 11984 synchronized (mPackages) { 11985 updatePermissionsLPw(newPackage.packageName, newPackage, 11986 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11987 ? UPDATE_PERMISSIONS_ALL : 0)); 11988 // For system-bundled packages, we assume that installing an upgraded version 11989 // of the package implies that the user actually wants to run that new code, 11990 // so we enable the package. 11991 PackageSetting ps = mSettings.mPackages.get(pkgName); 11992 if (ps != null) { 11993 if (isSystemApp(newPackage)) { 11994 // NB: implicit assumption that system package upgrades apply to all users 11995 if (DEBUG_INSTALL) { 11996 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11997 } 11998 if (res.origUsers != null) { 11999 for (int userHandle : res.origUsers) { 12000 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12001 userHandle, installerPackageName); 12002 } 12003 } 12004 // Also convey the prior install/uninstall state 12005 if (allUsers != null && perUserInstalled != null) { 12006 for (int i = 0; i < allUsers.length; i++) { 12007 if (DEBUG_INSTALL) { 12008 Slog.d(TAG, " user " + allUsers[i] 12009 + " => " + perUserInstalled[i]); 12010 } 12011 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12012 } 12013 // these install state changes will be persisted in the 12014 // upcoming call to mSettings.writeLPr(). 12015 } 12016 } 12017 // It's implied that when a user requests installation, they want the app to be 12018 // installed and enabled. 12019 int userId = user.getIdentifier(); 12020 if (userId != UserHandle.USER_ALL) { 12021 ps.setInstalled(true, userId); 12022 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12023 } 12024 } 12025 res.name = pkgName; 12026 res.uid = newPackage.applicationInfo.uid; 12027 res.pkg = newPackage; 12028 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12029 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12030 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12031 //to update install status 12032 mSettings.writeLPr(); 12033 } 12034 } 12035 12036 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12037 final int installFlags = args.installFlags; 12038 final String installerPackageName = args.installerPackageName; 12039 final String volumeUuid = args.volumeUuid; 12040 final File tmpPackageFile = new File(args.getCodePath()); 12041 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12042 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12043 || (args.volumeUuid != null)); 12044 boolean replace = false; 12045 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12046 if (args.move != null) { 12047 // moving a complete application; perfom an initial scan on the new install location 12048 scanFlags |= SCAN_INITIAL; 12049 } 12050 // Result object to be returned 12051 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12052 12053 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12054 // Retrieve PackageSettings and parse package 12055 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12056 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12057 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12058 PackageParser pp = new PackageParser(); 12059 pp.setSeparateProcesses(mSeparateProcesses); 12060 pp.setDisplayMetrics(mMetrics); 12061 12062 final PackageParser.Package pkg; 12063 try { 12064 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12065 } catch (PackageParserException e) { 12066 res.setError("Failed parse during installPackageLI", e); 12067 return; 12068 } 12069 12070 // Mark that we have an install time CPU ABI override. 12071 pkg.cpuAbiOverride = args.abiOverride; 12072 12073 String pkgName = res.name = pkg.packageName; 12074 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12075 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12076 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12077 return; 12078 } 12079 } 12080 12081 try { 12082 pp.collectCertificates(pkg, parseFlags); 12083 pp.collectManifestDigest(pkg); 12084 } catch (PackageParserException e) { 12085 res.setError("Failed collect during installPackageLI", e); 12086 return; 12087 } 12088 12089 /* If the installer passed in a manifest digest, compare it now. */ 12090 if (args.manifestDigest != null) { 12091 if (DEBUG_INSTALL) { 12092 final String parsedManifest = pkg.manifestDigest == null ? "null" 12093 : pkg.manifestDigest.toString(); 12094 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12095 + parsedManifest); 12096 } 12097 12098 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12099 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12100 return; 12101 } 12102 } else if (DEBUG_INSTALL) { 12103 final String parsedManifest = pkg.manifestDigest == null 12104 ? "null" : pkg.manifestDigest.toString(); 12105 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12106 } 12107 12108 // Get rid of all references to package scan path via parser. 12109 pp = null; 12110 String oldCodePath = null; 12111 boolean systemApp = false; 12112 synchronized (mPackages) { 12113 // Check if installing already existing package 12114 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12115 String oldName = mSettings.mRenamedPackages.get(pkgName); 12116 if (pkg.mOriginalPackages != null 12117 && pkg.mOriginalPackages.contains(oldName) 12118 && mPackages.containsKey(oldName)) { 12119 // This package is derived from an original package, 12120 // and this device has been updating from that original 12121 // name. We must continue using the original name, so 12122 // rename the new package here. 12123 pkg.setPackageName(oldName); 12124 pkgName = pkg.packageName; 12125 replace = true; 12126 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12127 + oldName + " pkgName=" + pkgName); 12128 } else if (mPackages.containsKey(pkgName)) { 12129 // This package, under its official name, already exists 12130 // on the device; we should replace it. 12131 replace = true; 12132 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12133 } 12134 12135 // Prevent apps opting out from runtime permissions 12136 if (replace) { 12137 PackageParser.Package oldPackage = mPackages.get(pkgName); 12138 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12139 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12140 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12141 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12142 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12143 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12144 + " doesn't support runtime permissions but the old" 12145 + " target SDK " + oldTargetSdk + " does."); 12146 return; 12147 } 12148 } 12149 } 12150 12151 PackageSetting ps = mSettings.mPackages.get(pkgName); 12152 if (ps != null) { 12153 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12154 12155 // Quick sanity check that we're signed correctly if updating; 12156 // we'll check this again later when scanning, but we want to 12157 // bail early here before tripping over redefined permissions. 12158 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12159 if (!checkUpgradeKeySetLP(ps, pkg)) { 12160 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12161 + pkg.packageName + " upgrade keys do not match the " 12162 + "previously installed version"); 12163 return; 12164 } 12165 } else { 12166 try { 12167 verifySignaturesLP(ps, pkg); 12168 } catch (PackageManagerException e) { 12169 res.setError(e.error, e.getMessage()); 12170 return; 12171 } 12172 } 12173 12174 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12175 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12176 systemApp = (ps.pkg.applicationInfo.flags & 12177 ApplicationInfo.FLAG_SYSTEM) != 0; 12178 } 12179 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12180 } 12181 12182 // Check whether the newly-scanned package wants to define an already-defined perm 12183 int N = pkg.permissions.size(); 12184 for (int i = N-1; i >= 0; i--) { 12185 PackageParser.Permission perm = pkg.permissions.get(i); 12186 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12187 if (bp != null) { 12188 // If the defining package is signed with our cert, it's okay. This 12189 // also includes the "updating the same package" case, of course. 12190 // "updating same package" could also involve key-rotation. 12191 final boolean sigsOk; 12192 if (bp.sourcePackage.equals(pkg.packageName) 12193 && (bp.packageSetting instanceof PackageSetting) 12194 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12195 scanFlags))) { 12196 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12197 } else { 12198 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12199 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12200 } 12201 if (!sigsOk) { 12202 // If the owning package is the system itself, we log but allow 12203 // install to proceed; we fail the install on all other permission 12204 // redefinitions. 12205 if (!bp.sourcePackage.equals("android")) { 12206 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12207 + pkg.packageName + " attempting to redeclare permission " 12208 + perm.info.name + " already owned by " + bp.sourcePackage); 12209 res.origPermission = perm.info.name; 12210 res.origPackage = bp.sourcePackage; 12211 return; 12212 } else { 12213 Slog.w(TAG, "Package " + pkg.packageName 12214 + " attempting to redeclare system permission " 12215 + perm.info.name + "; ignoring new declaration"); 12216 pkg.permissions.remove(i); 12217 } 12218 } 12219 } 12220 } 12221 12222 } 12223 12224 if (systemApp && onExternal) { 12225 // Disable updates to system apps on sdcard 12226 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12227 "Cannot install updates to system apps on sdcard"); 12228 return; 12229 } 12230 12231 if (args.move != null) { 12232 // We did an in-place move, so dex is ready to roll 12233 scanFlags |= SCAN_NO_DEX; 12234 scanFlags |= SCAN_MOVE; 12235 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12236 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12237 scanFlags |= SCAN_NO_DEX; 12238 12239 try { 12240 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12241 true /* extract libs */); 12242 } catch (PackageManagerException pme) { 12243 Slog.e(TAG, "Error deriving application ABI", pme); 12244 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12245 return; 12246 } 12247 12248 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12249 int result = mPackageDexOptimizer 12250 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12251 false /* defer */, false /* inclDependencies */); 12252 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12253 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12254 return; 12255 } 12256 } 12257 12258 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12259 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12260 return; 12261 } 12262 12263 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12264 12265 if (replace) { 12266 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12267 installerPackageName, volumeUuid, res); 12268 } else { 12269 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12270 args.user, installerPackageName, volumeUuid, res); 12271 } 12272 synchronized (mPackages) { 12273 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12274 if (ps != null) { 12275 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12276 } 12277 } 12278 } 12279 12280 private void startIntentFilterVerifications(int userId, boolean replacing, 12281 PackageParser.Package pkg) { 12282 if (mIntentFilterVerifierComponent == null) { 12283 Slog.w(TAG, "No IntentFilter verification will not be done as " 12284 + "there is no IntentFilterVerifier available!"); 12285 return; 12286 } 12287 12288 final int verifierUid = getPackageUid( 12289 mIntentFilterVerifierComponent.getPackageName(), 12290 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12291 12292 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12293 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12294 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12295 mHandler.sendMessage(msg); 12296 } 12297 12298 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12299 PackageParser.Package pkg) { 12300 int size = pkg.activities.size(); 12301 if (size == 0) { 12302 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12303 "No activity, so no need to verify any IntentFilter!"); 12304 return; 12305 } 12306 12307 final boolean hasDomainURLs = hasDomainURLs(pkg); 12308 if (!hasDomainURLs) { 12309 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12310 "No domain URLs, so no need to verify any IntentFilter!"); 12311 return; 12312 } 12313 12314 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12315 + " if any IntentFilter from the " + size 12316 + " Activities needs verification ..."); 12317 12318 int count = 0; 12319 final String packageName = pkg.packageName; 12320 12321 synchronized (mPackages) { 12322 // If this is a new install and we see that we've already run verification for this 12323 // package, we have nothing to do: it means the state was restored from backup. 12324 if (!replacing) { 12325 IntentFilterVerificationInfo ivi = 12326 mSettings.getIntentFilterVerificationLPr(packageName); 12327 if (ivi != null) { 12328 if (DEBUG_DOMAIN_VERIFICATION) { 12329 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12330 + ivi.getStatusString()); 12331 } 12332 return; 12333 } 12334 } 12335 12336 // If any filters need to be verified, then all need to be. 12337 boolean needToVerify = false; 12338 for (PackageParser.Activity a : pkg.activities) { 12339 for (ActivityIntentInfo filter : a.intents) { 12340 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12341 if (DEBUG_DOMAIN_VERIFICATION) { 12342 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12343 } 12344 needToVerify = true; 12345 break; 12346 } 12347 } 12348 } 12349 12350 if (needToVerify) { 12351 final int verificationId = mIntentFilterVerificationToken++; 12352 for (PackageParser.Activity a : pkg.activities) { 12353 for (ActivityIntentInfo filter : a.intents) { 12354 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12355 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12356 "Verification needed for IntentFilter:" + filter.toString()); 12357 mIntentFilterVerifier.addOneIntentFilterVerification( 12358 verifierUid, userId, verificationId, filter, packageName); 12359 count++; 12360 } 12361 } 12362 } 12363 } 12364 } 12365 12366 if (count > 0) { 12367 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12368 + " IntentFilter verification" + (count > 1 ? "s" : "") 12369 + " for userId:" + userId); 12370 mIntentFilterVerifier.startVerifications(userId); 12371 } else { 12372 if (DEBUG_DOMAIN_VERIFICATION) { 12373 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12374 } 12375 } 12376 } 12377 12378 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12379 final ComponentName cn = filter.activity.getComponentName(); 12380 final String packageName = cn.getPackageName(); 12381 12382 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12383 packageName); 12384 if (ivi == null) { 12385 return true; 12386 } 12387 int status = ivi.getStatus(); 12388 switch (status) { 12389 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12390 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12391 return true; 12392 12393 default: 12394 // Nothing to do 12395 return false; 12396 } 12397 } 12398 12399 private static boolean isMultiArch(PackageSetting ps) { 12400 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12401 } 12402 12403 private static boolean isMultiArch(ApplicationInfo info) { 12404 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12405 } 12406 12407 private static boolean isExternal(PackageParser.Package pkg) { 12408 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12409 } 12410 12411 private static boolean isExternal(PackageSetting ps) { 12412 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12413 } 12414 12415 private static boolean isExternal(ApplicationInfo info) { 12416 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12417 } 12418 12419 private static boolean isSystemApp(PackageParser.Package pkg) { 12420 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12421 } 12422 12423 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12424 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12425 } 12426 12427 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12428 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12429 } 12430 12431 private static boolean isSystemApp(PackageSetting ps) { 12432 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12433 } 12434 12435 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12436 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12437 } 12438 12439 private int packageFlagsToInstallFlags(PackageSetting ps) { 12440 int installFlags = 0; 12441 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12442 // This existing package was an external ASEC install when we have 12443 // the external flag without a UUID 12444 installFlags |= PackageManager.INSTALL_EXTERNAL; 12445 } 12446 if (ps.isForwardLocked()) { 12447 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12448 } 12449 return installFlags; 12450 } 12451 12452 private void deleteTempPackageFiles() { 12453 final FilenameFilter filter = new FilenameFilter() { 12454 public boolean accept(File dir, String name) { 12455 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12456 } 12457 }; 12458 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12459 file.delete(); 12460 } 12461 } 12462 12463 @Override 12464 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12465 int flags) { 12466 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12467 flags); 12468 } 12469 12470 @Override 12471 public void deletePackage(final String packageName, 12472 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12473 mContext.enforceCallingOrSelfPermission( 12474 android.Manifest.permission.DELETE_PACKAGES, null); 12475 Preconditions.checkNotNull(packageName); 12476 Preconditions.checkNotNull(observer); 12477 final int uid = Binder.getCallingUid(); 12478 if (UserHandle.getUserId(uid) != userId) { 12479 mContext.enforceCallingPermission( 12480 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12481 "deletePackage for user " + userId); 12482 } 12483 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12484 try { 12485 observer.onPackageDeleted(packageName, 12486 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12487 } catch (RemoteException re) { 12488 } 12489 return; 12490 } 12491 12492 boolean uninstallBlocked = false; 12493 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12494 int[] users = sUserManager.getUserIds(); 12495 for (int i = 0; i < users.length; ++i) { 12496 if (getBlockUninstallForUser(packageName, users[i])) { 12497 uninstallBlocked = true; 12498 break; 12499 } 12500 } 12501 } else { 12502 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12503 } 12504 if (uninstallBlocked) { 12505 try { 12506 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12507 null); 12508 } catch (RemoteException re) { 12509 } 12510 return; 12511 } 12512 12513 if (DEBUG_REMOVE) { 12514 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12515 } 12516 // Queue up an async operation since the package deletion may take a little while. 12517 mHandler.post(new Runnable() { 12518 public void run() { 12519 mHandler.removeCallbacks(this); 12520 final int returnCode = deletePackageX(packageName, userId, flags); 12521 if (observer != null) { 12522 try { 12523 observer.onPackageDeleted(packageName, returnCode, null); 12524 } catch (RemoteException e) { 12525 Log.i(TAG, "Observer no longer exists."); 12526 } //end catch 12527 } //end if 12528 } //end run 12529 }); 12530 } 12531 12532 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12533 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12534 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12535 try { 12536 if (dpm != null) { 12537 if (dpm.isDeviceOwner(packageName)) { 12538 return true; 12539 } 12540 int[] users; 12541 if (userId == UserHandle.USER_ALL) { 12542 users = sUserManager.getUserIds(); 12543 } else { 12544 users = new int[]{userId}; 12545 } 12546 for (int i = 0; i < users.length; ++i) { 12547 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12548 return true; 12549 } 12550 } 12551 } 12552 } catch (RemoteException e) { 12553 } 12554 return false; 12555 } 12556 12557 /** 12558 * This method is an internal method that could be get invoked either 12559 * to delete an installed package or to clean up a failed installation. 12560 * After deleting an installed package, a broadcast is sent to notify any 12561 * listeners that the package has been installed. For cleaning up a failed 12562 * installation, the broadcast is not necessary since the package's 12563 * installation wouldn't have sent the initial broadcast either 12564 * The key steps in deleting a package are 12565 * deleting the package information in internal structures like mPackages, 12566 * deleting the packages base directories through installd 12567 * updating mSettings to reflect current status 12568 * persisting settings for later use 12569 * sending a broadcast if necessary 12570 */ 12571 private int deletePackageX(String packageName, int userId, int flags) { 12572 final PackageRemovedInfo info = new PackageRemovedInfo(); 12573 final boolean res; 12574 12575 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12576 ? UserHandle.ALL : new UserHandle(userId); 12577 12578 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12579 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12580 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12581 } 12582 12583 boolean removedForAllUsers = false; 12584 boolean systemUpdate = false; 12585 12586 // for the uninstall-updates case and restricted profiles, remember the per- 12587 // userhandle installed state 12588 int[] allUsers; 12589 boolean[] perUserInstalled; 12590 synchronized (mPackages) { 12591 PackageSetting ps = mSettings.mPackages.get(packageName); 12592 allUsers = sUserManager.getUserIds(); 12593 perUserInstalled = new boolean[allUsers.length]; 12594 for (int i = 0; i < allUsers.length; i++) { 12595 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12596 } 12597 } 12598 12599 synchronized (mInstallLock) { 12600 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12601 res = deletePackageLI(packageName, removeForUser, 12602 true, allUsers, perUserInstalled, 12603 flags | REMOVE_CHATTY, info, true); 12604 systemUpdate = info.isRemovedPackageSystemUpdate; 12605 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12606 removedForAllUsers = true; 12607 } 12608 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12609 + " removedForAllUsers=" + removedForAllUsers); 12610 } 12611 12612 if (res) { 12613 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12614 12615 // If the removed package was a system update, the old system package 12616 // was re-enabled; we need to broadcast this information 12617 if (systemUpdate) { 12618 Bundle extras = new Bundle(1); 12619 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12620 ? info.removedAppId : info.uid); 12621 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12622 12623 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12624 extras, null, null, null); 12625 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12626 extras, null, null, null); 12627 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12628 null, packageName, null, null); 12629 } 12630 } 12631 // Force a gc here. 12632 Runtime.getRuntime().gc(); 12633 // Delete the resources here after sending the broadcast to let 12634 // other processes clean up before deleting resources. 12635 if (info.args != null) { 12636 synchronized (mInstallLock) { 12637 info.args.doPostDeleteLI(true); 12638 } 12639 } 12640 12641 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12642 } 12643 12644 class PackageRemovedInfo { 12645 String removedPackage; 12646 int uid = -1; 12647 int removedAppId = -1; 12648 int[] removedUsers = null; 12649 boolean isRemovedPackageSystemUpdate = false; 12650 // Clean up resources deleted packages. 12651 InstallArgs args = null; 12652 12653 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12654 Bundle extras = new Bundle(1); 12655 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12656 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12657 if (replacing) { 12658 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12659 } 12660 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12661 if (removedPackage != null) { 12662 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12663 extras, null, null, removedUsers); 12664 if (fullRemove && !replacing) { 12665 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12666 extras, null, null, removedUsers); 12667 } 12668 } 12669 if (removedAppId >= 0) { 12670 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12671 removedUsers); 12672 } 12673 } 12674 } 12675 12676 /* 12677 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12678 * flag is not set, the data directory is removed as well. 12679 * make sure this flag is set for partially installed apps. If not its meaningless to 12680 * delete a partially installed application. 12681 */ 12682 private void removePackageDataLI(PackageSetting ps, 12683 int[] allUserHandles, boolean[] perUserInstalled, 12684 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12685 String packageName = ps.name; 12686 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12687 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12688 // Retrieve object to delete permissions for shared user later on 12689 final PackageSetting deletedPs; 12690 // reader 12691 synchronized (mPackages) { 12692 deletedPs = mSettings.mPackages.get(packageName); 12693 if (outInfo != null) { 12694 outInfo.removedPackage = packageName; 12695 outInfo.removedUsers = deletedPs != null 12696 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12697 : null; 12698 } 12699 } 12700 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12701 removeDataDirsLI(ps.volumeUuid, packageName); 12702 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12703 } 12704 // writer 12705 synchronized (mPackages) { 12706 if (deletedPs != null) { 12707 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12708 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12709 clearDefaultBrowserIfNeeded(packageName); 12710 if (outInfo != null) { 12711 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12712 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12713 } 12714 updatePermissionsLPw(deletedPs.name, null, 0); 12715 if (deletedPs.sharedUser != null) { 12716 // Remove permissions associated with package. Since runtime 12717 // permissions are per user we have to kill the removed package 12718 // or packages running under the shared user of the removed 12719 // package if revoking the permissions requested only by the removed 12720 // package is successful and this causes a change in gids. 12721 for (int userId : UserManagerService.getInstance().getUserIds()) { 12722 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12723 userId); 12724 if (userIdToKill == UserHandle.USER_ALL 12725 || userIdToKill >= UserHandle.USER_OWNER) { 12726 // If gids changed for this user, kill all affected packages. 12727 mHandler.post(new Runnable() { 12728 @Override 12729 public void run() { 12730 // This has to happen with no lock held. 12731 killSettingPackagesForUser(deletedPs, userIdToKill, 12732 KILL_APP_REASON_GIDS_CHANGED); 12733 } 12734 }); 12735 break; 12736 } 12737 } 12738 } 12739 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12740 } 12741 // make sure to preserve per-user disabled state if this removal was just 12742 // a downgrade of a system app to the factory package 12743 if (allUserHandles != null && perUserInstalled != null) { 12744 if (DEBUG_REMOVE) { 12745 Slog.d(TAG, "Propagating install state across downgrade"); 12746 } 12747 for (int i = 0; i < allUserHandles.length; i++) { 12748 if (DEBUG_REMOVE) { 12749 Slog.d(TAG, " user " + allUserHandles[i] 12750 + " => " + perUserInstalled[i]); 12751 } 12752 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12753 } 12754 } 12755 } 12756 // can downgrade to reader 12757 if (writeSettings) { 12758 // Save settings now 12759 mSettings.writeLPr(); 12760 } 12761 } 12762 if (outInfo != null) { 12763 // A user ID was deleted here. Go through all users and remove it 12764 // from KeyStore. 12765 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12766 } 12767 } 12768 12769 static boolean locationIsPrivileged(File path) { 12770 try { 12771 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12772 .getCanonicalPath(); 12773 return path.getCanonicalPath().startsWith(privilegedAppDir); 12774 } catch (IOException e) { 12775 Slog.e(TAG, "Unable to access code path " + path); 12776 } 12777 return false; 12778 } 12779 12780 /* 12781 * Tries to delete system package. 12782 */ 12783 private boolean deleteSystemPackageLI(PackageSetting newPs, 12784 int[] allUserHandles, boolean[] perUserInstalled, 12785 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12786 final boolean applyUserRestrictions 12787 = (allUserHandles != null) && (perUserInstalled != null); 12788 PackageSetting disabledPs = null; 12789 // Confirm if the system package has been updated 12790 // An updated system app can be deleted. This will also have to restore 12791 // the system pkg from system partition 12792 // reader 12793 synchronized (mPackages) { 12794 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12795 } 12796 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12797 + " disabledPs=" + disabledPs); 12798 if (disabledPs == null) { 12799 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12800 return false; 12801 } else if (DEBUG_REMOVE) { 12802 Slog.d(TAG, "Deleting system pkg from data partition"); 12803 } 12804 if (DEBUG_REMOVE) { 12805 if (applyUserRestrictions) { 12806 Slog.d(TAG, "Remembering install states:"); 12807 for (int i = 0; i < allUserHandles.length; i++) { 12808 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12809 } 12810 } 12811 } 12812 // Delete the updated package 12813 outInfo.isRemovedPackageSystemUpdate = true; 12814 if (disabledPs.versionCode < newPs.versionCode) { 12815 // Delete data for downgrades 12816 flags &= ~PackageManager.DELETE_KEEP_DATA; 12817 } else { 12818 // Preserve data by setting flag 12819 flags |= PackageManager.DELETE_KEEP_DATA; 12820 } 12821 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12822 allUserHandles, perUserInstalled, outInfo, writeSettings); 12823 if (!ret) { 12824 return false; 12825 } 12826 // writer 12827 synchronized (mPackages) { 12828 // Reinstate the old system package 12829 mSettings.enableSystemPackageLPw(newPs.name); 12830 // Remove any native libraries from the upgraded package. 12831 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12832 } 12833 // Install the system package 12834 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12835 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12836 if (locationIsPrivileged(disabledPs.codePath)) { 12837 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12838 } 12839 12840 final PackageParser.Package newPkg; 12841 try { 12842 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12843 } catch (PackageManagerException e) { 12844 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12845 return false; 12846 } 12847 12848 // writer 12849 synchronized (mPackages) { 12850 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12851 12852 // Propagate the permissions state as we do want to drop on the floor 12853 // runtime permissions. The update permissions method below will take 12854 // care of removing obsolete permissions and grant install permissions. 12855 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12856 updatePermissionsLPw(newPkg.packageName, newPkg, 12857 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12858 12859 if (applyUserRestrictions) { 12860 if (DEBUG_REMOVE) { 12861 Slog.d(TAG, "Propagating install state across reinstall"); 12862 } 12863 for (int i = 0; i < allUserHandles.length; i++) { 12864 if (DEBUG_REMOVE) { 12865 Slog.d(TAG, " user " + allUserHandles[i] 12866 + " => " + perUserInstalled[i]); 12867 } 12868 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12869 } 12870 // Regardless of writeSettings we need to ensure that this restriction 12871 // state propagation is persisted 12872 mSettings.writeAllUsersPackageRestrictionsLPr(); 12873 } 12874 // can downgrade to reader here 12875 if (writeSettings) { 12876 mSettings.writeLPr(); 12877 } 12878 } 12879 return true; 12880 } 12881 12882 private boolean deleteInstalledPackageLI(PackageSetting ps, 12883 boolean deleteCodeAndResources, int flags, 12884 int[] allUserHandles, boolean[] perUserInstalled, 12885 PackageRemovedInfo outInfo, boolean writeSettings) { 12886 if (outInfo != null) { 12887 outInfo.uid = ps.appId; 12888 } 12889 12890 // Delete package data from internal structures and also remove data if flag is set 12891 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12892 12893 // Delete application code and resources 12894 if (deleteCodeAndResources && (outInfo != null)) { 12895 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12896 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12897 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12898 } 12899 return true; 12900 } 12901 12902 @Override 12903 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12904 int userId) { 12905 mContext.enforceCallingOrSelfPermission( 12906 android.Manifest.permission.DELETE_PACKAGES, null); 12907 synchronized (mPackages) { 12908 PackageSetting ps = mSettings.mPackages.get(packageName); 12909 if (ps == null) { 12910 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12911 return false; 12912 } 12913 if (!ps.getInstalled(userId)) { 12914 // Can't block uninstall for an app that is not installed or enabled. 12915 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12916 return false; 12917 } 12918 ps.setBlockUninstall(blockUninstall, userId); 12919 mSettings.writePackageRestrictionsLPr(userId); 12920 } 12921 return true; 12922 } 12923 12924 @Override 12925 public boolean getBlockUninstallForUser(String packageName, int userId) { 12926 synchronized (mPackages) { 12927 PackageSetting ps = mSettings.mPackages.get(packageName); 12928 if (ps == null) { 12929 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12930 return false; 12931 } 12932 return ps.getBlockUninstall(userId); 12933 } 12934 } 12935 12936 /* 12937 * This method handles package deletion in general 12938 */ 12939 private boolean deletePackageLI(String packageName, UserHandle user, 12940 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12941 int flags, PackageRemovedInfo outInfo, 12942 boolean writeSettings) { 12943 if (packageName == null) { 12944 Slog.w(TAG, "Attempt to delete null packageName."); 12945 return false; 12946 } 12947 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12948 PackageSetting ps; 12949 boolean dataOnly = false; 12950 int removeUser = -1; 12951 int appId = -1; 12952 synchronized (mPackages) { 12953 ps = mSettings.mPackages.get(packageName); 12954 if (ps == null) { 12955 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12956 return false; 12957 } 12958 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12959 && user.getIdentifier() != UserHandle.USER_ALL) { 12960 // The caller is asking that the package only be deleted for a single 12961 // user. To do this, we just mark its uninstalled state and delete 12962 // its data. If this is a system app, we only allow this to happen if 12963 // they have set the special DELETE_SYSTEM_APP which requests different 12964 // semantics than normal for uninstalling system apps. 12965 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12966 ps.setUserState(user.getIdentifier(), 12967 COMPONENT_ENABLED_STATE_DEFAULT, 12968 false, //installed 12969 true, //stopped 12970 true, //notLaunched 12971 false, //hidden 12972 null, null, null, 12973 false, // blockUninstall 12974 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 12975 if (!isSystemApp(ps)) { 12976 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12977 // Other user still have this package installed, so all 12978 // we need to do is clear this user's data and save that 12979 // it is uninstalled. 12980 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12981 removeUser = user.getIdentifier(); 12982 appId = ps.appId; 12983 scheduleWritePackageRestrictionsLocked(removeUser); 12984 } else { 12985 // We need to set it back to 'installed' so the uninstall 12986 // broadcasts will be sent correctly. 12987 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12988 ps.setInstalled(true, user.getIdentifier()); 12989 } 12990 } else { 12991 // This is a system app, so we assume that the 12992 // other users still have this package installed, so all 12993 // we need to do is clear this user's data and save that 12994 // it is uninstalled. 12995 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12996 removeUser = user.getIdentifier(); 12997 appId = ps.appId; 12998 scheduleWritePackageRestrictionsLocked(removeUser); 12999 } 13000 } 13001 } 13002 13003 if (removeUser >= 0) { 13004 // From above, we determined that we are deleting this only 13005 // for a single user. Continue the work here. 13006 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13007 if (outInfo != null) { 13008 outInfo.removedPackage = packageName; 13009 outInfo.removedAppId = appId; 13010 outInfo.removedUsers = new int[] {removeUser}; 13011 } 13012 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13013 removeKeystoreDataIfNeeded(removeUser, appId); 13014 schedulePackageCleaning(packageName, removeUser, false); 13015 synchronized (mPackages) { 13016 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13017 scheduleWritePackageRestrictionsLocked(removeUser); 13018 } 13019 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13020 } 13021 return true; 13022 } 13023 13024 if (dataOnly) { 13025 // Delete application data first 13026 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13027 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13028 return true; 13029 } 13030 13031 boolean ret = false; 13032 if (isSystemApp(ps)) { 13033 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13034 // When an updated system application is deleted we delete the existing resources as well and 13035 // fall back to existing code in system partition 13036 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13037 flags, outInfo, writeSettings); 13038 } else { 13039 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13040 // Kill application pre-emptively especially for apps on sd. 13041 killApplication(packageName, ps.appId, "uninstall pkg"); 13042 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13043 allUserHandles, perUserInstalled, 13044 outInfo, writeSettings); 13045 } 13046 13047 return ret; 13048 } 13049 13050 private final class ClearStorageConnection implements ServiceConnection { 13051 IMediaContainerService mContainerService; 13052 13053 @Override 13054 public void onServiceConnected(ComponentName name, IBinder service) { 13055 synchronized (this) { 13056 mContainerService = IMediaContainerService.Stub.asInterface(service); 13057 notifyAll(); 13058 } 13059 } 13060 13061 @Override 13062 public void onServiceDisconnected(ComponentName name) { 13063 } 13064 } 13065 13066 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13067 final boolean mounted; 13068 if (Environment.isExternalStorageEmulated()) { 13069 mounted = true; 13070 } else { 13071 final String status = Environment.getExternalStorageState(); 13072 13073 mounted = status.equals(Environment.MEDIA_MOUNTED) 13074 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13075 } 13076 13077 if (!mounted) { 13078 return; 13079 } 13080 13081 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13082 int[] users; 13083 if (userId == UserHandle.USER_ALL) { 13084 users = sUserManager.getUserIds(); 13085 } else { 13086 users = new int[] { userId }; 13087 } 13088 final ClearStorageConnection conn = new ClearStorageConnection(); 13089 if (mContext.bindServiceAsUser( 13090 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13091 try { 13092 for (int curUser : users) { 13093 long timeout = SystemClock.uptimeMillis() + 5000; 13094 synchronized (conn) { 13095 long now = SystemClock.uptimeMillis(); 13096 while (conn.mContainerService == null && now < timeout) { 13097 try { 13098 conn.wait(timeout - now); 13099 } catch (InterruptedException e) { 13100 } 13101 } 13102 } 13103 if (conn.mContainerService == null) { 13104 return; 13105 } 13106 13107 final UserEnvironment userEnv = new UserEnvironment(curUser); 13108 clearDirectory(conn.mContainerService, 13109 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13110 if (allData) { 13111 clearDirectory(conn.mContainerService, 13112 userEnv.buildExternalStorageAppDataDirs(packageName)); 13113 clearDirectory(conn.mContainerService, 13114 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13115 } 13116 } 13117 } finally { 13118 mContext.unbindService(conn); 13119 } 13120 } 13121 } 13122 13123 @Override 13124 public void clearApplicationUserData(final String packageName, 13125 final IPackageDataObserver observer, final int userId) { 13126 mContext.enforceCallingOrSelfPermission( 13127 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13128 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13129 // Queue up an async operation since the package deletion may take a little while. 13130 mHandler.post(new Runnable() { 13131 public void run() { 13132 mHandler.removeCallbacks(this); 13133 final boolean succeeded; 13134 synchronized (mInstallLock) { 13135 succeeded = clearApplicationUserDataLI(packageName, userId); 13136 } 13137 clearExternalStorageDataSync(packageName, userId, true); 13138 if (succeeded) { 13139 // invoke DeviceStorageMonitor's update method to clear any notifications 13140 DeviceStorageMonitorInternal 13141 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13142 if (dsm != null) { 13143 dsm.checkMemory(); 13144 } 13145 } 13146 if(observer != null) { 13147 try { 13148 observer.onRemoveCompleted(packageName, succeeded); 13149 } catch (RemoteException e) { 13150 Log.i(TAG, "Observer no longer exists."); 13151 } 13152 } //end if observer 13153 } //end run 13154 }); 13155 } 13156 13157 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13158 if (packageName == null) { 13159 Slog.w(TAG, "Attempt to delete null packageName."); 13160 return false; 13161 } 13162 13163 // Try finding details about the requested package 13164 PackageParser.Package pkg; 13165 synchronized (mPackages) { 13166 pkg = mPackages.get(packageName); 13167 if (pkg == null) { 13168 final PackageSetting ps = mSettings.mPackages.get(packageName); 13169 if (ps != null) { 13170 pkg = ps.pkg; 13171 } 13172 } 13173 13174 if (pkg == null) { 13175 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13176 return false; 13177 } 13178 13179 PackageSetting ps = (PackageSetting) pkg.mExtras; 13180 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13181 } 13182 13183 // Always delete data directories for package, even if we found no other 13184 // record of app. This helps users recover from UID mismatches without 13185 // resorting to a full data wipe. 13186 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13187 if (retCode < 0) { 13188 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13189 return false; 13190 } 13191 13192 final int appId = pkg.applicationInfo.uid; 13193 removeKeystoreDataIfNeeded(userId, appId); 13194 13195 // Create a native library symlink only if we have native libraries 13196 // and if the native libraries are 32 bit libraries. We do not provide 13197 // this symlink for 64 bit libraries. 13198 if (pkg.applicationInfo.primaryCpuAbi != null && 13199 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13200 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13201 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13202 nativeLibPath, userId) < 0) { 13203 Slog.w(TAG, "Failed linking native library dir"); 13204 return false; 13205 } 13206 } 13207 13208 return true; 13209 } 13210 13211 /** 13212 * Reverts user permission state changes (permissions and flags). 13213 * 13214 * @param ps The package for which to reset. 13215 * @param userId The device user for which to do a reset. 13216 */ 13217 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13218 final PackageSetting ps, final int userId) { 13219 if (ps.pkg == null) { 13220 return; 13221 } 13222 13223 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13224 | FLAG_PERMISSION_USER_FIXED 13225 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13226 13227 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13228 | FLAG_PERMISSION_POLICY_FIXED; 13229 13230 boolean writeInstallPermissions = false; 13231 boolean writeRuntimePermissions = false; 13232 13233 final int permissionCount = ps.pkg.requestedPermissions.size(); 13234 for (int i = 0; i < permissionCount; i++) { 13235 String permission = ps.pkg.requestedPermissions.get(i); 13236 13237 BasePermission bp = mSettings.mPermissions.get(permission); 13238 if (bp == null) { 13239 continue; 13240 } 13241 13242 // If shared user we just reset the state to which only this app contributed. 13243 if (ps.sharedUser != null) { 13244 boolean used = false; 13245 final int packageCount = ps.sharedUser.packages.size(); 13246 for (int j = 0; j < packageCount; j++) { 13247 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13248 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13249 && pkg.pkg.requestedPermissions.contains(permission)) { 13250 used = true; 13251 break; 13252 } 13253 } 13254 if (used) { 13255 continue; 13256 } 13257 } 13258 13259 PermissionsState permissionsState = ps.getPermissionsState(); 13260 13261 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13262 13263 // Always clear the user settable flags. 13264 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13265 bp.name) != null; 13266 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13267 if (hasInstallState) { 13268 writeInstallPermissions = true; 13269 } else { 13270 writeRuntimePermissions = true; 13271 } 13272 } 13273 13274 // Below is only runtime permission handling. 13275 if (!bp.isRuntime()) { 13276 continue; 13277 } 13278 13279 // Never clobber system or policy. 13280 if ((oldFlags & policyOrSystemFlags) != 0) { 13281 continue; 13282 } 13283 13284 // If this permission was granted by default, make sure it is. 13285 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13286 if (permissionsState.grantRuntimePermission(bp, userId) 13287 != PERMISSION_OPERATION_FAILURE) { 13288 writeRuntimePermissions = true; 13289 } 13290 } else { 13291 // Otherwise, reset the permission. 13292 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13293 switch (revokeResult) { 13294 case PERMISSION_OPERATION_SUCCESS: { 13295 writeRuntimePermissions = true; 13296 } break; 13297 13298 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13299 writeRuntimePermissions = true; 13300 // If gids changed for this user, kill all affected packages. 13301 mHandler.post(new Runnable() { 13302 @Override 13303 public void run() { 13304 // This has to happen with no lock held. 13305 killSettingPackagesForUser(ps, userId, 13306 KILL_APP_REASON_GIDS_CHANGED); 13307 } 13308 }); 13309 } break; 13310 } 13311 } 13312 } 13313 13314 // Synchronously write as we are taking permissions away. 13315 if (writeRuntimePermissions) { 13316 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13317 } 13318 13319 // Synchronously write as we are taking permissions away. 13320 if (writeInstallPermissions) { 13321 mSettings.writeLPr(); 13322 } 13323 } 13324 13325 /** 13326 * Remove entries from the keystore daemon. Will only remove it if the 13327 * {@code appId} is valid. 13328 */ 13329 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13330 if (appId < 0) { 13331 return; 13332 } 13333 13334 final KeyStore keyStore = KeyStore.getInstance(); 13335 if (keyStore != null) { 13336 if (userId == UserHandle.USER_ALL) { 13337 for (final int individual : sUserManager.getUserIds()) { 13338 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13339 } 13340 } else { 13341 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13342 } 13343 } else { 13344 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13345 } 13346 } 13347 13348 @Override 13349 public void deleteApplicationCacheFiles(final String packageName, 13350 final IPackageDataObserver observer) { 13351 mContext.enforceCallingOrSelfPermission( 13352 android.Manifest.permission.DELETE_CACHE_FILES, null); 13353 // Queue up an async operation since the package deletion may take a little while. 13354 final int userId = UserHandle.getCallingUserId(); 13355 mHandler.post(new Runnable() { 13356 public void run() { 13357 mHandler.removeCallbacks(this); 13358 final boolean succeded; 13359 synchronized (mInstallLock) { 13360 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13361 } 13362 clearExternalStorageDataSync(packageName, userId, false); 13363 if (observer != null) { 13364 try { 13365 observer.onRemoveCompleted(packageName, succeded); 13366 } catch (RemoteException e) { 13367 Log.i(TAG, "Observer no longer exists."); 13368 } 13369 } //end if observer 13370 } //end run 13371 }); 13372 } 13373 13374 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13375 if (packageName == null) { 13376 Slog.w(TAG, "Attempt to delete null packageName."); 13377 return false; 13378 } 13379 PackageParser.Package p; 13380 synchronized (mPackages) { 13381 p = mPackages.get(packageName); 13382 } 13383 if (p == null) { 13384 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13385 return false; 13386 } 13387 final ApplicationInfo applicationInfo = p.applicationInfo; 13388 if (applicationInfo == null) { 13389 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13390 return false; 13391 } 13392 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13393 if (retCode < 0) { 13394 Slog.w(TAG, "Couldn't remove cache files for package: " 13395 + packageName + " u" + userId); 13396 return false; 13397 } 13398 return true; 13399 } 13400 13401 @Override 13402 public void getPackageSizeInfo(final String packageName, int userHandle, 13403 final IPackageStatsObserver observer) { 13404 mContext.enforceCallingOrSelfPermission( 13405 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13406 if (packageName == null) { 13407 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13408 } 13409 13410 PackageStats stats = new PackageStats(packageName, userHandle); 13411 13412 /* 13413 * Queue up an async operation since the package measurement may take a 13414 * little while. 13415 */ 13416 Message msg = mHandler.obtainMessage(INIT_COPY); 13417 msg.obj = new MeasureParams(stats, observer); 13418 mHandler.sendMessage(msg); 13419 } 13420 13421 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13422 PackageStats pStats) { 13423 if (packageName == null) { 13424 Slog.w(TAG, "Attempt to get size of null packageName."); 13425 return false; 13426 } 13427 PackageParser.Package p; 13428 boolean dataOnly = false; 13429 String libDirRoot = null; 13430 String asecPath = null; 13431 PackageSetting ps = null; 13432 synchronized (mPackages) { 13433 p = mPackages.get(packageName); 13434 ps = mSettings.mPackages.get(packageName); 13435 if(p == null) { 13436 dataOnly = true; 13437 if((ps == null) || (ps.pkg == null)) { 13438 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13439 return false; 13440 } 13441 p = ps.pkg; 13442 } 13443 if (ps != null) { 13444 libDirRoot = ps.legacyNativeLibraryPathString; 13445 } 13446 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13447 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13448 if (secureContainerId != null) { 13449 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13450 } 13451 } 13452 } 13453 String publicSrcDir = null; 13454 if(!dataOnly) { 13455 final ApplicationInfo applicationInfo = p.applicationInfo; 13456 if (applicationInfo == null) { 13457 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13458 return false; 13459 } 13460 if (p.isForwardLocked()) { 13461 publicSrcDir = applicationInfo.getBaseResourcePath(); 13462 } 13463 } 13464 // TODO: extend to measure size of split APKs 13465 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13466 // not just the first level. 13467 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13468 // just the primary. 13469 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13470 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13471 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13472 if (res < 0) { 13473 return false; 13474 } 13475 13476 // Fix-up for forward-locked applications in ASEC containers. 13477 if (!isExternal(p)) { 13478 pStats.codeSize += pStats.externalCodeSize; 13479 pStats.externalCodeSize = 0L; 13480 } 13481 13482 return true; 13483 } 13484 13485 13486 @Override 13487 public void addPackageToPreferred(String packageName) { 13488 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13489 } 13490 13491 @Override 13492 public void removePackageFromPreferred(String packageName) { 13493 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13494 } 13495 13496 @Override 13497 public List<PackageInfo> getPreferredPackages(int flags) { 13498 return new ArrayList<PackageInfo>(); 13499 } 13500 13501 private int getUidTargetSdkVersionLockedLPr(int uid) { 13502 Object obj = mSettings.getUserIdLPr(uid); 13503 if (obj instanceof SharedUserSetting) { 13504 final SharedUserSetting sus = (SharedUserSetting) obj; 13505 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13506 final Iterator<PackageSetting> it = sus.packages.iterator(); 13507 while (it.hasNext()) { 13508 final PackageSetting ps = it.next(); 13509 if (ps.pkg != null) { 13510 int v = ps.pkg.applicationInfo.targetSdkVersion; 13511 if (v < vers) vers = v; 13512 } 13513 } 13514 return vers; 13515 } else if (obj instanceof PackageSetting) { 13516 final PackageSetting ps = (PackageSetting) obj; 13517 if (ps.pkg != null) { 13518 return ps.pkg.applicationInfo.targetSdkVersion; 13519 } 13520 } 13521 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13522 } 13523 13524 @Override 13525 public void addPreferredActivity(IntentFilter filter, int match, 13526 ComponentName[] set, ComponentName activity, int userId) { 13527 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13528 "Adding preferred"); 13529 } 13530 13531 private void addPreferredActivityInternal(IntentFilter filter, int match, 13532 ComponentName[] set, ComponentName activity, boolean always, int userId, 13533 String opname) { 13534 // writer 13535 int callingUid = Binder.getCallingUid(); 13536 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13537 if (filter.countActions() == 0) { 13538 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13539 return; 13540 } 13541 synchronized (mPackages) { 13542 if (mContext.checkCallingOrSelfPermission( 13543 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13544 != PackageManager.PERMISSION_GRANTED) { 13545 if (getUidTargetSdkVersionLockedLPr(callingUid) 13546 < Build.VERSION_CODES.FROYO) { 13547 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13548 + callingUid); 13549 return; 13550 } 13551 mContext.enforceCallingOrSelfPermission( 13552 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13553 } 13554 13555 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13556 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13557 + userId + ":"); 13558 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13559 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13560 scheduleWritePackageRestrictionsLocked(userId); 13561 } 13562 } 13563 13564 @Override 13565 public void replacePreferredActivity(IntentFilter filter, int match, 13566 ComponentName[] set, ComponentName activity, int userId) { 13567 if (filter.countActions() != 1) { 13568 throw new IllegalArgumentException( 13569 "replacePreferredActivity expects filter to have only 1 action."); 13570 } 13571 if (filter.countDataAuthorities() != 0 13572 || filter.countDataPaths() != 0 13573 || filter.countDataSchemes() > 1 13574 || filter.countDataTypes() != 0) { 13575 throw new IllegalArgumentException( 13576 "replacePreferredActivity expects filter to have no data authorities, " + 13577 "paths, or types; and at most one scheme."); 13578 } 13579 13580 final int callingUid = Binder.getCallingUid(); 13581 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13582 synchronized (mPackages) { 13583 if (mContext.checkCallingOrSelfPermission( 13584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13585 != PackageManager.PERMISSION_GRANTED) { 13586 if (getUidTargetSdkVersionLockedLPr(callingUid) 13587 < Build.VERSION_CODES.FROYO) { 13588 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13589 + Binder.getCallingUid()); 13590 return; 13591 } 13592 mContext.enforceCallingOrSelfPermission( 13593 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13594 } 13595 13596 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13597 if (pir != null) { 13598 // Get all of the existing entries that exactly match this filter. 13599 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13600 if (existing != null && existing.size() == 1) { 13601 PreferredActivity cur = existing.get(0); 13602 if (DEBUG_PREFERRED) { 13603 Slog.i(TAG, "Checking replace of preferred:"); 13604 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13605 if (!cur.mPref.mAlways) { 13606 Slog.i(TAG, " -- CUR; not mAlways!"); 13607 } else { 13608 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13609 Slog.i(TAG, " -- CUR: mSet=" 13610 + Arrays.toString(cur.mPref.mSetComponents)); 13611 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13612 Slog.i(TAG, " -- NEW: mMatch=" 13613 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13614 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13615 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13616 } 13617 } 13618 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13619 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13620 && cur.mPref.sameSet(set)) { 13621 // Setting the preferred activity to what it happens to be already 13622 if (DEBUG_PREFERRED) { 13623 Slog.i(TAG, "Replacing with same preferred activity " 13624 + cur.mPref.mShortComponent + " for user " 13625 + userId + ":"); 13626 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13627 } 13628 return; 13629 } 13630 } 13631 13632 if (existing != null) { 13633 if (DEBUG_PREFERRED) { 13634 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13635 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13636 } 13637 for (int i = 0; i < existing.size(); i++) { 13638 PreferredActivity pa = existing.get(i); 13639 if (DEBUG_PREFERRED) { 13640 Slog.i(TAG, "Removing existing preferred activity " 13641 + pa.mPref.mComponent + ":"); 13642 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13643 } 13644 pir.removeFilter(pa); 13645 } 13646 } 13647 } 13648 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13649 "Replacing preferred"); 13650 } 13651 } 13652 13653 @Override 13654 public void clearPackagePreferredActivities(String packageName) { 13655 final int uid = Binder.getCallingUid(); 13656 // writer 13657 synchronized (mPackages) { 13658 PackageParser.Package pkg = mPackages.get(packageName); 13659 if (pkg == null || pkg.applicationInfo.uid != uid) { 13660 if (mContext.checkCallingOrSelfPermission( 13661 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13662 != PackageManager.PERMISSION_GRANTED) { 13663 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13664 < Build.VERSION_CODES.FROYO) { 13665 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13666 + Binder.getCallingUid()); 13667 return; 13668 } 13669 mContext.enforceCallingOrSelfPermission( 13670 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13671 } 13672 } 13673 13674 int user = UserHandle.getCallingUserId(); 13675 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13676 scheduleWritePackageRestrictionsLocked(user); 13677 } 13678 } 13679 } 13680 13681 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13682 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13683 ArrayList<PreferredActivity> removed = null; 13684 boolean changed = false; 13685 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13686 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13687 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13688 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13689 continue; 13690 } 13691 Iterator<PreferredActivity> it = pir.filterIterator(); 13692 while (it.hasNext()) { 13693 PreferredActivity pa = it.next(); 13694 // Mark entry for removal only if it matches the package name 13695 // and the entry is of type "always". 13696 if (packageName == null || 13697 (pa.mPref.mComponent.getPackageName().equals(packageName) 13698 && pa.mPref.mAlways)) { 13699 if (removed == null) { 13700 removed = new ArrayList<PreferredActivity>(); 13701 } 13702 removed.add(pa); 13703 } 13704 } 13705 if (removed != null) { 13706 for (int j=0; j<removed.size(); j++) { 13707 PreferredActivity pa = removed.get(j); 13708 pir.removeFilter(pa); 13709 } 13710 changed = true; 13711 } 13712 } 13713 return changed; 13714 } 13715 13716 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13717 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13718 if (userId == UserHandle.USER_ALL) { 13719 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13720 sUserManager.getUserIds())) { 13721 for (int oneUserId : sUserManager.getUserIds()) { 13722 scheduleWritePackageRestrictionsLocked(oneUserId); 13723 } 13724 } 13725 } else { 13726 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13727 scheduleWritePackageRestrictionsLocked(userId); 13728 } 13729 } 13730 } 13731 13732 13733 void clearDefaultBrowserIfNeeded(String packageName) { 13734 for (int oneUserId : sUserManager.getUserIds()) { 13735 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13736 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13737 if (packageName.equals(defaultBrowserPackageName)) { 13738 setDefaultBrowserPackageName(null, oneUserId); 13739 } 13740 } 13741 } 13742 13743 @Override 13744 public void resetPreferredActivities(int userId) { 13745 mContext.enforceCallingOrSelfPermission( 13746 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13747 // writer 13748 synchronized (mPackages) { 13749 clearPackagePreferredActivitiesLPw(null, userId); 13750 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13751 applyFactoryDefaultBrowserLPw(userId); 13752 primeDomainVerificationsLPw(userId); 13753 13754 scheduleWritePackageRestrictionsLocked(userId); 13755 } 13756 } 13757 13758 @Override 13759 public int getPreferredActivities(List<IntentFilter> outFilters, 13760 List<ComponentName> outActivities, String packageName) { 13761 13762 int num = 0; 13763 final int userId = UserHandle.getCallingUserId(); 13764 // reader 13765 synchronized (mPackages) { 13766 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13767 if (pir != null) { 13768 final Iterator<PreferredActivity> it = pir.filterIterator(); 13769 while (it.hasNext()) { 13770 final PreferredActivity pa = it.next(); 13771 if (packageName == null 13772 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13773 && pa.mPref.mAlways)) { 13774 if (outFilters != null) { 13775 outFilters.add(new IntentFilter(pa)); 13776 } 13777 if (outActivities != null) { 13778 outActivities.add(pa.mPref.mComponent); 13779 } 13780 } 13781 } 13782 } 13783 } 13784 13785 return num; 13786 } 13787 13788 @Override 13789 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13790 int userId) { 13791 int callingUid = Binder.getCallingUid(); 13792 if (callingUid != Process.SYSTEM_UID) { 13793 throw new SecurityException( 13794 "addPersistentPreferredActivity can only be run by the system"); 13795 } 13796 if (filter.countActions() == 0) { 13797 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13798 return; 13799 } 13800 synchronized (mPackages) { 13801 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13802 " :"); 13803 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13804 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13805 new PersistentPreferredActivity(filter, activity)); 13806 scheduleWritePackageRestrictionsLocked(userId); 13807 } 13808 } 13809 13810 @Override 13811 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13812 int callingUid = Binder.getCallingUid(); 13813 if (callingUid != Process.SYSTEM_UID) { 13814 throw new SecurityException( 13815 "clearPackagePersistentPreferredActivities can only be run by the system"); 13816 } 13817 ArrayList<PersistentPreferredActivity> removed = null; 13818 boolean changed = false; 13819 synchronized (mPackages) { 13820 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13821 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13822 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13823 .valueAt(i); 13824 if (userId != thisUserId) { 13825 continue; 13826 } 13827 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13828 while (it.hasNext()) { 13829 PersistentPreferredActivity ppa = it.next(); 13830 // Mark entry for removal only if it matches the package name. 13831 if (ppa.mComponent.getPackageName().equals(packageName)) { 13832 if (removed == null) { 13833 removed = new ArrayList<PersistentPreferredActivity>(); 13834 } 13835 removed.add(ppa); 13836 } 13837 } 13838 if (removed != null) { 13839 for (int j=0; j<removed.size(); j++) { 13840 PersistentPreferredActivity ppa = removed.get(j); 13841 ppir.removeFilter(ppa); 13842 } 13843 changed = true; 13844 } 13845 } 13846 13847 if (changed) { 13848 scheduleWritePackageRestrictionsLocked(userId); 13849 } 13850 } 13851 } 13852 13853 /** 13854 * Common machinery for picking apart a restored XML blob and passing 13855 * it to a caller-supplied functor to be applied to the running system. 13856 */ 13857 private void restoreFromXml(XmlPullParser parser, int userId, 13858 String expectedStartTag, BlobXmlRestorer functor) 13859 throws IOException, XmlPullParserException { 13860 int type; 13861 while ((type = parser.next()) != XmlPullParser.START_TAG 13862 && type != XmlPullParser.END_DOCUMENT) { 13863 } 13864 if (type != XmlPullParser.START_TAG) { 13865 // oops didn't find a start tag?! 13866 if (DEBUG_BACKUP) { 13867 Slog.e(TAG, "Didn't find start tag during restore"); 13868 } 13869 return; 13870 } 13871 13872 // this is supposed to be TAG_PREFERRED_BACKUP 13873 if (!expectedStartTag.equals(parser.getName())) { 13874 if (DEBUG_BACKUP) { 13875 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13876 } 13877 return; 13878 } 13879 13880 // skip interfering stuff, then we're aligned with the backing implementation 13881 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13882 functor.apply(parser, userId); 13883 } 13884 13885 private interface BlobXmlRestorer { 13886 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13887 } 13888 13889 /** 13890 * Non-Binder method, support for the backup/restore mechanism: write the 13891 * full set of preferred activities in its canonical XML format. Returns the 13892 * XML output as a byte array, or null if there is none. 13893 */ 13894 @Override 13895 public byte[] getPreferredActivityBackup(int userId) { 13896 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13897 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13898 } 13899 13900 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13901 try { 13902 final XmlSerializer serializer = new FastXmlSerializer(); 13903 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13904 serializer.startDocument(null, true); 13905 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13906 13907 synchronized (mPackages) { 13908 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13909 } 13910 13911 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13912 serializer.endDocument(); 13913 serializer.flush(); 13914 } catch (Exception e) { 13915 if (DEBUG_BACKUP) { 13916 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13917 } 13918 return null; 13919 } 13920 13921 return dataStream.toByteArray(); 13922 } 13923 13924 @Override 13925 public void restorePreferredActivities(byte[] backup, int userId) { 13926 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13927 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13928 } 13929 13930 try { 13931 final XmlPullParser parser = Xml.newPullParser(); 13932 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13933 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13934 new BlobXmlRestorer() { 13935 @Override 13936 public void apply(XmlPullParser parser, int userId) 13937 throws XmlPullParserException, IOException { 13938 synchronized (mPackages) { 13939 mSettings.readPreferredActivitiesLPw(parser, userId); 13940 } 13941 } 13942 } ); 13943 } catch (Exception e) { 13944 if (DEBUG_BACKUP) { 13945 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13946 } 13947 } 13948 } 13949 13950 /** 13951 * Non-Binder method, support for the backup/restore mechanism: write the 13952 * default browser (etc) settings in its canonical XML format. Returns the default 13953 * browser XML representation as a byte array, or null if there is none. 13954 */ 13955 @Override 13956 public byte[] getDefaultAppsBackup(int userId) { 13957 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13958 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13959 } 13960 13961 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13962 try { 13963 final XmlSerializer serializer = new FastXmlSerializer(); 13964 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13965 serializer.startDocument(null, true); 13966 serializer.startTag(null, TAG_DEFAULT_APPS); 13967 13968 synchronized (mPackages) { 13969 mSettings.writeDefaultAppsLPr(serializer, userId); 13970 } 13971 13972 serializer.endTag(null, TAG_DEFAULT_APPS); 13973 serializer.endDocument(); 13974 serializer.flush(); 13975 } catch (Exception e) { 13976 if (DEBUG_BACKUP) { 13977 Slog.e(TAG, "Unable to write default apps for backup", e); 13978 } 13979 return null; 13980 } 13981 13982 return dataStream.toByteArray(); 13983 } 13984 13985 @Override 13986 public void restoreDefaultApps(byte[] backup, int userId) { 13987 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13988 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13989 } 13990 13991 try { 13992 final XmlPullParser parser = Xml.newPullParser(); 13993 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13994 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13995 new BlobXmlRestorer() { 13996 @Override 13997 public void apply(XmlPullParser parser, int userId) 13998 throws XmlPullParserException, IOException { 13999 synchronized (mPackages) { 14000 mSettings.readDefaultAppsLPw(parser, userId); 14001 } 14002 } 14003 } ); 14004 } catch (Exception e) { 14005 if (DEBUG_BACKUP) { 14006 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14007 } 14008 } 14009 } 14010 14011 @Override 14012 public byte[] getIntentFilterVerificationBackup(int userId) { 14013 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14014 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14015 } 14016 14017 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14018 try { 14019 final XmlSerializer serializer = new FastXmlSerializer(); 14020 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14021 serializer.startDocument(null, true); 14022 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14023 14024 synchronized (mPackages) { 14025 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14026 } 14027 14028 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14029 serializer.endDocument(); 14030 serializer.flush(); 14031 } catch (Exception e) { 14032 if (DEBUG_BACKUP) { 14033 Slog.e(TAG, "Unable to write default apps for backup", e); 14034 } 14035 return null; 14036 } 14037 14038 return dataStream.toByteArray(); 14039 } 14040 14041 @Override 14042 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14043 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14044 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14045 } 14046 14047 try { 14048 final XmlPullParser parser = Xml.newPullParser(); 14049 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14050 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14051 new BlobXmlRestorer() { 14052 @Override 14053 public void apply(XmlPullParser parser, int userId) 14054 throws XmlPullParserException, IOException { 14055 synchronized (mPackages) { 14056 mSettings.readAllDomainVerificationsLPr(parser, userId); 14057 mSettings.writeLPr(); 14058 } 14059 } 14060 } ); 14061 } catch (Exception e) { 14062 if (DEBUG_BACKUP) { 14063 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14064 } 14065 } 14066 } 14067 14068 @Override 14069 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14070 int sourceUserId, int targetUserId, int flags) { 14071 mContext.enforceCallingOrSelfPermission( 14072 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14073 int callingUid = Binder.getCallingUid(); 14074 enforceOwnerRights(ownerPackage, callingUid); 14075 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14076 if (intentFilter.countActions() == 0) { 14077 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14078 return; 14079 } 14080 synchronized (mPackages) { 14081 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14082 ownerPackage, targetUserId, flags); 14083 CrossProfileIntentResolver resolver = 14084 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14085 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14086 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14087 if (existing != null) { 14088 int size = existing.size(); 14089 for (int i = 0; i < size; i++) { 14090 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14091 return; 14092 } 14093 } 14094 } 14095 resolver.addFilter(newFilter); 14096 scheduleWritePackageRestrictionsLocked(sourceUserId); 14097 } 14098 } 14099 14100 @Override 14101 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14102 mContext.enforceCallingOrSelfPermission( 14103 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14104 int callingUid = Binder.getCallingUid(); 14105 enforceOwnerRights(ownerPackage, callingUid); 14106 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14107 synchronized (mPackages) { 14108 CrossProfileIntentResolver resolver = 14109 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14110 ArraySet<CrossProfileIntentFilter> set = 14111 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14112 for (CrossProfileIntentFilter filter : set) { 14113 if (filter.getOwnerPackage().equals(ownerPackage)) { 14114 resolver.removeFilter(filter); 14115 } 14116 } 14117 scheduleWritePackageRestrictionsLocked(sourceUserId); 14118 } 14119 } 14120 14121 // Enforcing that callingUid is owning pkg on userId 14122 private void enforceOwnerRights(String pkg, int callingUid) { 14123 // The system owns everything. 14124 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14125 return; 14126 } 14127 int callingUserId = UserHandle.getUserId(callingUid); 14128 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14129 if (pi == null) { 14130 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14131 + callingUserId); 14132 } 14133 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14134 throw new SecurityException("Calling uid " + callingUid 14135 + " does not own package " + pkg); 14136 } 14137 } 14138 14139 @Override 14140 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14141 Intent intent = new Intent(Intent.ACTION_MAIN); 14142 intent.addCategory(Intent.CATEGORY_HOME); 14143 14144 final int callingUserId = UserHandle.getCallingUserId(); 14145 List<ResolveInfo> list = queryIntentActivities(intent, null, 14146 PackageManager.GET_META_DATA, callingUserId); 14147 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14148 true, false, false, callingUserId); 14149 14150 allHomeCandidates.clear(); 14151 if (list != null) { 14152 for (ResolveInfo ri : list) { 14153 allHomeCandidates.add(ri); 14154 } 14155 } 14156 return (preferred == null || preferred.activityInfo == null) 14157 ? null 14158 : new ComponentName(preferred.activityInfo.packageName, 14159 preferred.activityInfo.name); 14160 } 14161 14162 @Override 14163 public void setApplicationEnabledSetting(String appPackageName, 14164 int newState, int flags, int userId, String callingPackage) { 14165 if (!sUserManager.exists(userId)) return; 14166 if (callingPackage == null) { 14167 callingPackage = Integer.toString(Binder.getCallingUid()); 14168 } 14169 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14170 } 14171 14172 @Override 14173 public void setComponentEnabledSetting(ComponentName componentName, 14174 int newState, int flags, int userId) { 14175 if (!sUserManager.exists(userId)) return; 14176 setEnabledSetting(componentName.getPackageName(), 14177 componentName.getClassName(), newState, flags, userId, null); 14178 } 14179 14180 private void setEnabledSetting(final String packageName, String className, int newState, 14181 final int flags, int userId, String callingPackage) { 14182 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14183 || newState == COMPONENT_ENABLED_STATE_ENABLED 14184 || newState == COMPONENT_ENABLED_STATE_DISABLED 14185 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14186 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14187 throw new IllegalArgumentException("Invalid new component state: " 14188 + newState); 14189 } 14190 PackageSetting pkgSetting; 14191 final int uid = Binder.getCallingUid(); 14192 final int permission = mContext.checkCallingOrSelfPermission( 14193 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14194 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14195 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14196 boolean sendNow = false; 14197 boolean isApp = (className == null); 14198 String componentName = isApp ? packageName : className; 14199 int packageUid = -1; 14200 ArrayList<String> components; 14201 14202 // writer 14203 synchronized (mPackages) { 14204 pkgSetting = mSettings.mPackages.get(packageName); 14205 if (pkgSetting == null) { 14206 if (className == null) { 14207 throw new IllegalArgumentException( 14208 "Unknown package: " + packageName); 14209 } 14210 throw new IllegalArgumentException( 14211 "Unknown component: " + packageName 14212 + "/" + className); 14213 } 14214 // Allow root and verify that userId is not being specified by a different user 14215 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14216 throw new SecurityException( 14217 "Permission Denial: attempt to change component state from pid=" 14218 + Binder.getCallingPid() 14219 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14220 } 14221 if (className == null) { 14222 // We're dealing with an application/package level state change 14223 if (pkgSetting.getEnabled(userId) == newState) { 14224 // Nothing to do 14225 return; 14226 } 14227 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14228 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14229 // Don't care about who enables an app. 14230 callingPackage = null; 14231 } 14232 pkgSetting.setEnabled(newState, userId, callingPackage); 14233 // pkgSetting.pkg.mSetEnabled = newState; 14234 } else { 14235 // We're dealing with a component level state change 14236 // First, verify that this is a valid class name. 14237 PackageParser.Package pkg = pkgSetting.pkg; 14238 if (pkg == null || !pkg.hasComponentClassName(className)) { 14239 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14240 throw new IllegalArgumentException("Component class " + className 14241 + " does not exist in " + packageName); 14242 } else { 14243 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14244 + className + " does not exist in " + packageName); 14245 } 14246 } 14247 switch (newState) { 14248 case COMPONENT_ENABLED_STATE_ENABLED: 14249 if (!pkgSetting.enableComponentLPw(className, userId)) { 14250 return; 14251 } 14252 break; 14253 case COMPONENT_ENABLED_STATE_DISABLED: 14254 if (!pkgSetting.disableComponentLPw(className, userId)) { 14255 return; 14256 } 14257 break; 14258 case COMPONENT_ENABLED_STATE_DEFAULT: 14259 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14260 return; 14261 } 14262 break; 14263 default: 14264 Slog.e(TAG, "Invalid new component state: " + newState); 14265 return; 14266 } 14267 } 14268 scheduleWritePackageRestrictionsLocked(userId); 14269 components = mPendingBroadcasts.get(userId, packageName); 14270 final boolean newPackage = components == null; 14271 if (newPackage) { 14272 components = new ArrayList<String>(); 14273 } 14274 if (!components.contains(componentName)) { 14275 components.add(componentName); 14276 } 14277 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14278 sendNow = true; 14279 // Purge entry from pending broadcast list if another one exists already 14280 // since we are sending one right away. 14281 mPendingBroadcasts.remove(userId, packageName); 14282 } else { 14283 if (newPackage) { 14284 mPendingBroadcasts.put(userId, packageName, components); 14285 } 14286 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14287 // Schedule a message 14288 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14289 } 14290 } 14291 } 14292 14293 long callingId = Binder.clearCallingIdentity(); 14294 try { 14295 if (sendNow) { 14296 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14297 sendPackageChangedBroadcast(packageName, 14298 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14299 } 14300 } finally { 14301 Binder.restoreCallingIdentity(callingId); 14302 } 14303 } 14304 14305 private void sendPackageChangedBroadcast(String packageName, 14306 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14307 if (DEBUG_INSTALL) 14308 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14309 + componentNames); 14310 Bundle extras = new Bundle(4); 14311 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14312 String nameList[] = new String[componentNames.size()]; 14313 componentNames.toArray(nameList); 14314 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14315 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14316 extras.putInt(Intent.EXTRA_UID, packageUid); 14317 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14318 new int[] {UserHandle.getUserId(packageUid)}); 14319 } 14320 14321 @Override 14322 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14323 if (!sUserManager.exists(userId)) return; 14324 final int uid = Binder.getCallingUid(); 14325 final int permission = mContext.checkCallingOrSelfPermission( 14326 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14327 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14328 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14329 // writer 14330 synchronized (mPackages) { 14331 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14332 allowedByPermission, uid, userId)) { 14333 scheduleWritePackageRestrictionsLocked(userId); 14334 } 14335 } 14336 } 14337 14338 @Override 14339 public String getInstallerPackageName(String packageName) { 14340 // reader 14341 synchronized (mPackages) { 14342 return mSettings.getInstallerPackageNameLPr(packageName); 14343 } 14344 } 14345 14346 @Override 14347 public int getApplicationEnabledSetting(String packageName, int userId) { 14348 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14349 int uid = Binder.getCallingUid(); 14350 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14351 // reader 14352 synchronized (mPackages) { 14353 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14354 } 14355 } 14356 14357 @Override 14358 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14359 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14360 int uid = Binder.getCallingUid(); 14361 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14362 // reader 14363 synchronized (mPackages) { 14364 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14365 } 14366 } 14367 14368 @Override 14369 public void enterSafeMode() { 14370 enforceSystemOrRoot("Only the system can request entering safe mode"); 14371 14372 if (!mSystemReady) { 14373 mSafeMode = true; 14374 } 14375 } 14376 14377 @Override 14378 public void systemReady() { 14379 mSystemReady = true; 14380 14381 // Read the compatibilty setting when the system is ready. 14382 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14383 mContext.getContentResolver(), 14384 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14385 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14386 if (DEBUG_SETTINGS) { 14387 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14388 } 14389 14390 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14391 14392 synchronized (mPackages) { 14393 // Verify that all of the preferred activity components actually 14394 // exist. It is possible for applications to be updated and at 14395 // that point remove a previously declared activity component that 14396 // had been set as a preferred activity. We try to clean this up 14397 // the next time we encounter that preferred activity, but it is 14398 // possible for the user flow to never be able to return to that 14399 // situation so here we do a sanity check to make sure we haven't 14400 // left any junk around. 14401 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14402 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14403 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14404 removed.clear(); 14405 for (PreferredActivity pa : pir.filterSet()) { 14406 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14407 removed.add(pa); 14408 } 14409 } 14410 if (removed.size() > 0) { 14411 for (int r=0; r<removed.size(); r++) { 14412 PreferredActivity pa = removed.get(r); 14413 Slog.w(TAG, "Removing dangling preferred activity: " 14414 + pa.mPref.mComponent); 14415 pir.removeFilter(pa); 14416 } 14417 mSettings.writePackageRestrictionsLPr( 14418 mSettings.mPreferredActivities.keyAt(i)); 14419 } 14420 } 14421 14422 for (int userId : UserManagerService.getInstance().getUserIds()) { 14423 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14424 grantPermissionsUserIds = ArrayUtils.appendInt( 14425 grantPermissionsUserIds, userId); 14426 } 14427 } 14428 } 14429 sUserManager.systemReady(); 14430 14431 // If we upgraded grant all default permissions before kicking off. 14432 for (int userId : grantPermissionsUserIds) { 14433 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14434 } 14435 14436 // Kick off any messages waiting for system ready 14437 if (mPostSystemReadyMessages != null) { 14438 for (Message msg : mPostSystemReadyMessages) { 14439 msg.sendToTarget(); 14440 } 14441 mPostSystemReadyMessages = null; 14442 } 14443 14444 // Watch for external volumes that come and go over time 14445 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14446 storage.registerListener(mStorageListener); 14447 14448 mInstallerService.systemReady(); 14449 mPackageDexOptimizer.systemReady(); 14450 14451 MountServiceInternal mountServiceInternal = LocalServices.getService( 14452 MountServiceInternal.class); 14453 mountServiceInternal.addExternalStoragePolicy( 14454 new MountServiceInternal.ExternalStorageMountPolicy() { 14455 @Override 14456 public int getMountMode(int uid, String packageName) { 14457 if (Process.isIsolated(uid)) { 14458 return Zygote.MOUNT_EXTERNAL_NONE; 14459 } 14460 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14461 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14462 } 14463 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14464 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14465 } 14466 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14467 return Zygote.MOUNT_EXTERNAL_READ; 14468 } 14469 return Zygote.MOUNT_EXTERNAL_WRITE; 14470 } 14471 14472 @Override 14473 public boolean hasExternalStorage(int uid, String packageName) { 14474 return true; 14475 } 14476 }); 14477 } 14478 14479 @Override 14480 public boolean isSafeMode() { 14481 return mSafeMode; 14482 } 14483 14484 @Override 14485 public boolean hasSystemUidErrors() { 14486 return mHasSystemUidErrors; 14487 } 14488 14489 static String arrayToString(int[] array) { 14490 StringBuffer buf = new StringBuffer(128); 14491 buf.append('['); 14492 if (array != null) { 14493 for (int i=0; i<array.length; i++) { 14494 if (i > 0) buf.append(", "); 14495 buf.append(array[i]); 14496 } 14497 } 14498 buf.append(']'); 14499 return buf.toString(); 14500 } 14501 14502 static class DumpState { 14503 public static final int DUMP_LIBS = 1 << 0; 14504 public static final int DUMP_FEATURES = 1 << 1; 14505 public static final int DUMP_RESOLVERS = 1 << 2; 14506 public static final int DUMP_PERMISSIONS = 1 << 3; 14507 public static final int DUMP_PACKAGES = 1 << 4; 14508 public static final int DUMP_SHARED_USERS = 1 << 5; 14509 public static final int DUMP_MESSAGES = 1 << 6; 14510 public static final int DUMP_PROVIDERS = 1 << 7; 14511 public static final int DUMP_VERIFIERS = 1 << 8; 14512 public static final int DUMP_PREFERRED = 1 << 9; 14513 public static final int DUMP_PREFERRED_XML = 1 << 10; 14514 public static final int DUMP_KEYSETS = 1 << 11; 14515 public static final int DUMP_VERSION = 1 << 12; 14516 public static final int DUMP_INSTALLS = 1 << 13; 14517 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14518 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14519 14520 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14521 14522 private int mTypes; 14523 14524 private int mOptions; 14525 14526 private boolean mTitlePrinted; 14527 14528 private SharedUserSetting mSharedUser; 14529 14530 public boolean isDumping(int type) { 14531 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14532 return true; 14533 } 14534 14535 return (mTypes & type) != 0; 14536 } 14537 14538 public void setDump(int type) { 14539 mTypes |= type; 14540 } 14541 14542 public boolean isOptionEnabled(int option) { 14543 return (mOptions & option) != 0; 14544 } 14545 14546 public void setOptionEnabled(int option) { 14547 mOptions |= option; 14548 } 14549 14550 public boolean onTitlePrinted() { 14551 final boolean printed = mTitlePrinted; 14552 mTitlePrinted = true; 14553 return printed; 14554 } 14555 14556 public boolean getTitlePrinted() { 14557 return mTitlePrinted; 14558 } 14559 14560 public void setTitlePrinted(boolean enabled) { 14561 mTitlePrinted = enabled; 14562 } 14563 14564 public SharedUserSetting getSharedUser() { 14565 return mSharedUser; 14566 } 14567 14568 public void setSharedUser(SharedUserSetting user) { 14569 mSharedUser = user; 14570 } 14571 } 14572 14573 @Override 14574 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14575 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14576 != PackageManager.PERMISSION_GRANTED) { 14577 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14578 + Binder.getCallingPid() 14579 + ", uid=" + Binder.getCallingUid() 14580 + " without permission " 14581 + android.Manifest.permission.DUMP); 14582 return; 14583 } 14584 14585 DumpState dumpState = new DumpState(); 14586 boolean fullPreferred = false; 14587 boolean checkin = false; 14588 14589 String packageName = null; 14590 ArraySet<String> permissionNames = null; 14591 14592 int opti = 0; 14593 while (opti < args.length) { 14594 String opt = args[opti]; 14595 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14596 break; 14597 } 14598 opti++; 14599 14600 if ("-a".equals(opt)) { 14601 // Right now we only know how to print all. 14602 } else if ("-h".equals(opt)) { 14603 pw.println("Package manager dump options:"); 14604 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14605 pw.println(" --checkin: dump for a checkin"); 14606 pw.println(" -f: print details of intent filters"); 14607 pw.println(" -h: print this help"); 14608 pw.println(" cmd may be one of:"); 14609 pw.println(" l[ibraries]: list known shared libraries"); 14610 pw.println(" f[ibraries]: list device features"); 14611 pw.println(" k[eysets]: print known keysets"); 14612 pw.println(" r[esolvers]: dump intent resolvers"); 14613 pw.println(" perm[issions]: dump permissions"); 14614 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14615 pw.println(" pref[erred]: print preferred package settings"); 14616 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14617 pw.println(" prov[iders]: dump content providers"); 14618 pw.println(" p[ackages]: dump installed packages"); 14619 pw.println(" s[hared-users]: dump shared user IDs"); 14620 pw.println(" m[essages]: print collected runtime messages"); 14621 pw.println(" v[erifiers]: print package verifier info"); 14622 pw.println(" version: print database version info"); 14623 pw.println(" write: write current settings now"); 14624 pw.println(" <package.name>: info about given package"); 14625 pw.println(" installs: details about install sessions"); 14626 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14627 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14628 return; 14629 } else if ("--checkin".equals(opt)) { 14630 checkin = true; 14631 } else if ("-f".equals(opt)) { 14632 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14633 } else { 14634 pw.println("Unknown argument: " + opt + "; use -h for help"); 14635 } 14636 } 14637 14638 // Is the caller requesting to dump a particular piece of data? 14639 if (opti < args.length) { 14640 String cmd = args[opti]; 14641 opti++; 14642 // Is this a package name? 14643 if ("android".equals(cmd) || cmd.contains(".")) { 14644 packageName = cmd; 14645 // When dumping a single package, we always dump all of its 14646 // filter information since the amount of data will be reasonable. 14647 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14648 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14649 dumpState.setDump(DumpState.DUMP_LIBS); 14650 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14651 dumpState.setDump(DumpState.DUMP_FEATURES); 14652 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14653 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14654 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14655 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14656 } else if ("permission".equals(cmd)) { 14657 if (opti >= args.length) { 14658 pw.println("Error: permission requires permission name"); 14659 return; 14660 } 14661 permissionNames = new ArraySet<>(); 14662 while (opti < args.length) { 14663 permissionNames.add(args[opti]); 14664 opti++; 14665 } 14666 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14667 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14668 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14669 dumpState.setDump(DumpState.DUMP_PREFERRED); 14670 } else if ("preferred-xml".equals(cmd)) { 14671 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14672 if (opti < args.length && "--full".equals(args[opti])) { 14673 fullPreferred = true; 14674 opti++; 14675 } 14676 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14677 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14678 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14679 dumpState.setDump(DumpState.DUMP_PACKAGES); 14680 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14681 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14682 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14683 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14684 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14685 dumpState.setDump(DumpState.DUMP_MESSAGES); 14686 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14687 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14688 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14689 || "intent-filter-verifiers".equals(cmd)) { 14690 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14691 } else if ("version".equals(cmd)) { 14692 dumpState.setDump(DumpState.DUMP_VERSION); 14693 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14694 dumpState.setDump(DumpState.DUMP_KEYSETS); 14695 } else if ("installs".equals(cmd)) { 14696 dumpState.setDump(DumpState.DUMP_INSTALLS); 14697 } else if ("write".equals(cmd)) { 14698 synchronized (mPackages) { 14699 mSettings.writeLPr(); 14700 pw.println("Settings written."); 14701 return; 14702 } 14703 } 14704 } 14705 14706 if (checkin) { 14707 pw.println("vers,1"); 14708 } 14709 14710 // reader 14711 synchronized (mPackages) { 14712 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14713 if (!checkin) { 14714 if (dumpState.onTitlePrinted()) 14715 pw.println(); 14716 pw.println("Database versions:"); 14717 pw.print(" SDK Version:"); 14718 pw.print(" internal="); 14719 pw.print(mSettings.mInternalSdkPlatform); 14720 pw.print(" external="); 14721 pw.println(mSettings.mExternalSdkPlatform); 14722 pw.print(" DB Version:"); 14723 pw.print(" internal="); 14724 pw.print(mSettings.mInternalDatabaseVersion); 14725 pw.print(" external="); 14726 pw.println(mSettings.mExternalDatabaseVersion); 14727 } 14728 } 14729 14730 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14731 if (!checkin) { 14732 if (dumpState.onTitlePrinted()) 14733 pw.println(); 14734 pw.println("Verifiers:"); 14735 pw.print(" Required: "); 14736 pw.print(mRequiredVerifierPackage); 14737 pw.print(" (uid="); 14738 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14739 pw.println(")"); 14740 } else if (mRequiredVerifierPackage != null) { 14741 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14742 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14743 } 14744 } 14745 14746 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14747 packageName == null) { 14748 if (mIntentFilterVerifierComponent != null) { 14749 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14750 if (!checkin) { 14751 if (dumpState.onTitlePrinted()) 14752 pw.println(); 14753 pw.println("Intent Filter Verifier:"); 14754 pw.print(" Using: "); 14755 pw.print(verifierPackageName); 14756 pw.print(" (uid="); 14757 pw.print(getPackageUid(verifierPackageName, 0)); 14758 pw.println(")"); 14759 } else if (verifierPackageName != null) { 14760 pw.print("ifv,"); pw.print(verifierPackageName); 14761 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14762 } 14763 } else { 14764 pw.println(); 14765 pw.println("No Intent Filter Verifier available!"); 14766 } 14767 } 14768 14769 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14770 boolean printedHeader = false; 14771 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14772 while (it.hasNext()) { 14773 String name = it.next(); 14774 SharedLibraryEntry ent = mSharedLibraries.get(name); 14775 if (!checkin) { 14776 if (!printedHeader) { 14777 if (dumpState.onTitlePrinted()) 14778 pw.println(); 14779 pw.println("Libraries:"); 14780 printedHeader = true; 14781 } 14782 pw.print(" "); 14783 } else { 14784 pw.print("lib,"); 14785 } 14786 pw.print(name); 14787 if (!checkin) { 14788 pw.print(" -> "); 14789 } 14790 if (ent.path != null) { 14791 if (!checkin) { 14792 pw.print("(jar) "); 14793 pw.print(ent.path); 14794 } else { 14795 pw.print(",jar,"); 14796 pw.print(ent.path); 14797 } 14798 } else { 14799 if (!checkin) { 14800 pw.print("(apk) "); 14801 pw.print(ent.apk); 14802 } else { 14803 pw.print(",apk,"); 14804 pw.print(ent.apk); 14805 } 14806 } 14807 pw.println(); 14808 } 14809 } 14810 14811 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14812 if (dumpState.onTitlePrinted()) 14813 pw.println(); 14814 if (!checkin) { 14815 pw.println("Features:"); 14816 } 14817 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14818 while (it.hasNext()) { 14819 String name = it.next(); 14820 if (!checkin) { 14821 pw.print(" "); 14822 } else { 14823 pw.print("feat,"); 14824 } 14825 pw.println(name); 14826 } 14827 } 14828 14829 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14830 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14831 : "Activity Resolver Table:", " ", packageName, 14832 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14833 dumpState.setTitlePrinted(true); 14834 } 14835 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14836 : "Receiver Resolver Table:", " ", packageName, 14837 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14838 dumpState.setTitlePrinted(true); 14839 } 14840 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14841 : "Service Resolver Table:", " ", packageName, 14842 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14843 dumpState.setTitlePrinted(true); 14844 } 14845 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14846 : "Provider Resolver Table:", " ", packageName, 14847 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14848 dumpState.setTitlePrinted(true); 14849 } 14850 } 14851 14852 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14853 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14854 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14855 int user = mSettings.mPreferredActivities.keyAt(i); 14856 if (pir.dump(pw, 14857 dumpState.getTitlePrinted() 14858 ? "\nPreferred Activities User " + user + ":" 14859 : "Preferred Activities User " + user + ":", " ", 14860 packageName, true, false)) { 14861 dumpState.setTitlePrinted(true); 14862 } 14863 } 14864 } 14865 14866 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14867 pw.flush(); 14868 FileOutputStream fout = new FileOutputStream(fd); 14869 BufferedOutputStream str = new BufferedOutputStream(fout); 14870 XmlSerializer serializer = new FastXmlSerializer(); 14871 try { 14872 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14873 serializer.startDocument(null, true); 14874 serializer.setFeature( 14875 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14876 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14877 serializer.endDocument(); 14878 serializer.flush(); 14879 } catch (IllegalArgumentException e) { 14880 pw.println("Failed writing: " + e); 14881 } catch (IllegalStateException e) { 14882 pw.println("Failed writing: " + e); 14883 } catch (IOException e) { 14884 pw.println("Failed writing: " + e); 14885 } 14886 } 14887 14888 if (!checkin 14889 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14890 && packageName == null) { 14891 pw.println(); 14892 int count = mSettings.mPackages.size(); 14893 if (count == 0) { 14894 pw.println("No applications!"); 14895 pw.println(); 14896 } else { 14897 final String prefix = " "; 14898 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14899 if (allPackageSettings.size() == 0) { 14900 pw.println("No domain preferred apps!"); 14901 pw.println(); 14902 } else { 14903 pw.println("App verification status:"); 14904 pw.println(); 14905 count = 0; 14906 for (PackageSetting ps : allPackageSettings) { 14907 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14908 if (ivi == null || ivi.getPackageName() == null) continue; 14909 pw.println(prefix + "Package: " + ivi.getPackageName()); 14910 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14911 pw.println(prefix + "Status: " + ivi.getStatusString()); 14912 pw.println(); 14913 count++; 14914 } 14915 if (count == 0) { 14916 pw.println(prefix + "No app verification established."); 14917 pw.println(); 14918 } 14919 for (int userId : sUserManager.getUserIds()) { 14920 pw.println("App linkages for user " + userId + ":"); 14921 pw.println(); 14922 count = 0; 14923 for (PackageSetting ps : allPackageSettings) { 14924 final long status = ps.getDomainVerificationStatusForUser(userId); 14925 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14926 continue; 14927 } 14928 pw.println(prefix + "Package: " + ps.name); 14929 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14930 String statusStr = IntentFilterVerificationInfo. 14931 getStatusStringFromValue(status); 14932 pw.println(prefix + "Status: " + statusStr); 14933 pw.println(); 14934 count++; 14935 } 14936 if (count == 0) { 14937 pw.println(prefix + "No configured app linkages."); 14938 pw.println(); 14939 } 14940 } 14941 } 14942 } 14943 } 14944 14945 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14946 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14947 if (packageName == null && permissionNames == null) { 14948 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14949 if (iperm == 0) { 14950 if (dumpState.onTitlePrinted()) 14951 pw.println(); 14952 pw.println("AppOp Permissions:"); 14953 } 14954 pw.print(" AppOp Permission "); 14955 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14956 pw.println(":"); 14957 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14958 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14959 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14960 } 14961 } 14962 } 14963 } 14964 14965 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14966 boolean printedSomething = false; 14967 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14968 if (packageName != null && !packageName.equals(p.info.packageName)) { 14969 continue; 14970 } 14971 if (!printedSomething) { 14972 if (dumpState.onTitlePrinted()) 14973 pw.println(); 14974 pw.println("Registered ContentProviders:"); 14975 printedSomething = true; 14976 } 14977 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14978 pw.print(" "); pw.println(p.toString()); 14979 } 14980 printedSomething = false; 14981 for (Map.Entry<String, PackageParser.Provider> entry : 14982 mProvidersByAuthority.entrySet()) { 14983 PackageParser.Provider p = entry.getValue(); 14984 if (packageName != null && !packageName.equals(p.info.packageName)) { 14985 continue; 14986 } 14987 if (!printedSomething) { 14988 if (dumpState.onTitlePrinted()) 14989 pw.println(); 14990 pw.println("ContentProvider Authorities:"); 14991 printedSomething = true; 14992 } 14993 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14994 pw.print(" "); pw.println(p.toString()); 14995 if (p.info != null && p.info.applicationInfo != null) { 14996 final String appInfo = p.info.applicationInfo.toString(); 14997 pw.print(" applicationInfo="); pw.println(appInfo); 14998 } 14999 } 15000 } 15001 15002 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15003 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15004 } 15005 15006 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15007 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15008 } 15009 15010 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15011 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15012 } 15013 15014 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15015 // XXX should handle packageName != null by dumping only install data that 15016 // the given package is involved with. 15017 if (dumpState.onTitlePrinted()) pw.println(); 15018 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15019 } 15020 15021 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15022 if (dumpState.onTitlePrinted()) pw.println(); 15023 mSettings.dumpReadMessagesLPr(pw, dumpState); 15024 15025 pw.println(); 15026 pw.println("Package warning messages:"); 15027 BufferedReader in = null; 15028 String line = null; 15029 try { 15030 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15031 while ((line = in.readLine()) != null) { 15032 if (line.contains("ignored: updated version")) continue; 15033 pw.println(line); 15034 } 15035 } catch (IOException ignored) { 15036 } finally { 15037 IoUtils.closeQuietly(in); 15038 } 15039 } 15040 15041 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15042 BufferedReader in = null; 15043 String line = null; 15044 try { 15045 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15046 while ((line = in.readLine()) != null) { 15047 if (line.contains("ignored: updated version")) continue; 15048 pw.print("msg,"); 15049 pw.println(line); 15050 } 15051 } catch (IOException ignored) { 15052 } finally { 15053 IoUtils.closeQuietly(in); 15054 } 15055 } 15056 } 15057 } 15058 15059 private String dumpDomainString(String packageName) { 15060 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15061 List<IntentFilter> filters = getAllIntentFilters(packageName); 15062 15063 ArraySet<String> result = new ArraySet<>(); 15064 if (iviList.size() > 0) { 15065 for (IntentFilterVerificationInfo ivi : iviList) { 15066 for (String host : ivi.getDomains()) { 15067 result.add(host); 15068 } 15069 } 15070 } 15071 if (filters != null && filters.size() > 0) { 15072 for (IntentFilter filter : filters) { 15073 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15074 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15075 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15076 result.addAll(filter.getHostsList()); 15077 } 15078 } 15079 } 15080 15081 StringBuilder sb = new StringBuilder(result.size() * 16); 15082 for (String domain : result) { 15083 if (sb.length() > 0) sb.append(" "); 15084 sb.append(domain); 15085 } 15086 return sb.toString(); 15087 } 15088 15089 // ------- apps on sdcard specific code ------- 15090 static final boolean DEBUG_SD_INSTALL = false; 15091 15092 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15093 15094 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15095 15096 private boolean mMediaMounted = false; 15097 15098 static String getEncryptKey() { 15099 try { 15100 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15101 SD_ENCRYPTION_KEYSTORE_NAME); 15102 if (sdEncKey == null) { 15103 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15104 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15105 if (sdEncKey == null) { 15106 Slog.e(TAG, "Failed to create encryption keys"); 15107 return null; 15108 } 15109 } 15110 return sdEncKey; 15111 } catch (NoSuchAlgorithmException nsae) { 15112 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15113 return null; 15114 } catch (IOException ioe) { 15115 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15116 return null; 15117 } 15118 } 15119 15120 /* 15121 * Update media status on PackageManager. 15122 */ 15123 @Override 15124 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15125 int callingUid = Binder.getCallingUid(); 15126 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15127 throw new SecurityException("Media status can only be updated by the system"); 15128 } 15129 // reader; this apparently protects mMediaMounted, but should probably 15130 // be a different lock in that case. 15131 synchronized (mPackages) { 15132 Log.i(TAG, "Updating external media status from " 15133 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15134 + (mediaStatus ? "mounted" : "unmounted")); 15135 if (DEBUG_SD_INSTALL) 15136 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15137 + ", mMediaMounted=" + mMediaMounted); 15138 if (mediaStatus == mMediaMounted) { 15139 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15140 : 0, -1); 15141 mHandler.sendMessage(msg); 15142 return; 15143 } 15144 mMediaMounted = mediaStatus; 15145 } 15146 // Queue up an async operation since the package installation may take a 15147 // little while. 15148 mHandler.post(new Runnable() { 15149 public void run() { 15150 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15151 } 15152 }); 15153 } 15154 15155 /** 15156 * Called by MountService when the initial ASECs to scan are available. 15157 * Should block until all the ASEC containers are finished being scanned. 15158 */ 15159 public void scanAvailableAsecs() { 15160 updateExternalMediaStatusInner(true, false, false); 15161 if (mShouldRestoreconData) { 15162 SELinuxMMAC.setRestoreconDone(); 15163 mShouldRestoreconData = false; 15164 } 15165 } 15166 15167 /* 15168 * Collect information of applications on external media, map them against 15169 * existing containers and update information based on current mount status. 15170 * Please note that we always have to report status if reportStatus has been 15171 * set to true especially when unloading packages. 15172 */ 15173 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15174 boolean externalStorage) { 15175 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15176 int[] uidArr = EmptyArray.INT; 15177 15178 final String[] list = PackageHelper.getSecureContainerList(); 15179 if (ArrayUtils.isEmpty(list)) { 15180 Log.i(TAG, "No secure containers found"); 15181 } else { 15182 // Process list of secure containers and categorize them 15183 // as active or stale based on their package internal state. 15184 15185 // reader 15186 synchronized (mPackages) { 15187 for (String cid : list) { 15188 // Leave stages untouched for now; installer service owns them 15189 if (PackageInstallerService.isStageName(cid)) continue; 15190 15191 if (DEBUG_SD_INSTALL) 15192 Log.i(TAG, "Processing container " + cid); 15193 String pkgName = getAsecPackageName(cid); 15194 if (pkgName == null) { 15195 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15196 continue; 15197 } 15198 if (DEBUG_SD_INSTALL) 15199 Log.i(TAG, "Looking for pkg : " + pkgName); 15200 15201 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15202 if (ps == null) { 15203 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15204 continue; 15205 } 15206 15207 /* 15208 * Skip packages that are not external if we're unmounting 15209 * external storage. 15210 */ 15211 if (externalStorage && !isMounted && !isExternal(ps)) { 15212 continue; 15213 } 15214 15215 final AsecInstallArgs args = new AsecInstallArgs(cid, 15216 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15217 // The package status is changed only if the code path 15218 // matches between settings and the container id. 15219 if (ps.codePathString != null 15220 && ps.codePathString.startsWith(args.getCodePath())) { 15221 if (DEBUG_SD_INSTALL) { 15222 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15223 + " at code path: " + ps.codePathString); 15224 } 15225 15226 // We do have a valid package installed on sdcard 15227 processCids.put(args, ps.codePathString); 15228 final int uid = ps.appId; 15229 if (uid != -1) { 15230 uidArr = ArrayUtils.appendInt(uidArr, uid); 15231 } 15232 } else { 15233 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15234 + ps.codePathString); 15235 } 15236 } 15237 } 15238 15239 Arrays.sort(uidArr); 15240 } 15241 15242 // Process packages with valid entries. 15243 if (isMounted) { 15244 if (DEBUG_SD_INSTALL) 15245 Log.i(TAG, "Loading packages"); 15246 loadMediaPackages(processCids, uidArr); 15247 startCleaningPackages(); 15248 mInstallerService.onSecureContainersAvailable(); 15249 } else { 15250 if (DEBUG_SD_INSTALL) 15251 Log.i(TAG, "Unloading packages"); 15252 unloadMediaPackages(processCids, uidArr, reportStatus); 15253 } 15254 } 15255 15256 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15257 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15258 final int size = infos.size(); 15259 final String[] packageNames = new String[size]; 15260 final int[] packageUids = new int[size]; 15261 for (int i = 0; i < size; i++) { 15262 final ApplicationInfo info = infos.get(i); 15263 packageNames[i] = info.packageName; 15264 packageUids[i] = info.uid; 15265 } 15266 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15267 finishedReceiver); 15268 } 15269 15270 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15271 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15272 sendResourcesChangedBroadcast(mediaStatus, replacing, 15273 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15274 } 15275 15276 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15277 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15278 int size = pkgList.length; 15279 if (size > 0) { 15280 // Send broadcasts here 15281 Bundle extras = new Bundle(); 15282 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15283 if (uidArr != null) { 15284 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15285 } 15286 if (replacing) { 15287 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15288 } 15289 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15290 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15291 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15292 } 15293 } 15294 15295 /* 15296 * Look at potentially valid container ids from processCids If package 15297 * information doesn't match the one on record or package scanning fails, 15298 * the cid is added to list of removeCids. We currently don't delete stale 15299 * containers. 15300 */ 15301 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15302 ArrayList<String> pkgList = new ArrayList<String>(); 15303 Set<AsecInstallArgs> keys = processCids.keySet(); 15304 15305 for (AsecInstallArgs args : keys) { 15306 String codePath = processCids.get(args); 15307 if (DEBUG_SD_INSTALL) 15308 Log.i(TAG, "Loading container : " + args.cid); 15309 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15310 try { 15311 // Make sure there are no container errors first. 15312 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15313 Slog.e(TAG, "Failed to mount cid : " + args.cid 15314 + " when installing from sdcard"); 15315 continue; 15316 } 15317 // Check code path here. 15318 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15319 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15320 + " does not match one in settings " + codePath); 15321 continue; 15322 } 15323 // Parse package 15324 int parseFlags = mDefParseFlags; 15325 if (args.isExternalAsec()) { 15326 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15327 } 15328 if (args.isFwdLocked()) { 15329 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15330 } 15331 15332 synchronized (mInstallLock) { 15333 PackageParser.Package pkg = null; 15334 try { 15335 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15336 } catch (PackageManagerException e) { 15337 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15338 } 15339 // Scan the package 15340 if (pkg != null) { 15341 /* 15342 * TODO why is the lock being held? doPostInstall is 15343 * called in other places without the lock. This needs 15344 * to be straightened out. 15345 */ 15346 // writer 15347 synchronized (mPackages) { 15348 retCode = PackageManager.INSTALL_SUCCEEDED; 15349 pkgList.add(pkg.packageName); 15350 // Post process args 15351 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15352 pkg.applicationInfo.uid); 15353 } 15354 } else { 15355 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15356 } 15357 } 15358 15359 } finally { 15360 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15361 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15362 } 15363 } 15364 } 15365 // writer 15366 synchronized (mPackages) { 15367 // If the platform SDK has changed since the last time we booted, 15368 // we need to re-grant app permission to catch any new ones that 15369 // appear. This is really a hack, and means that apps can in some 15370 // cases get permissions that the user didn't initially explicitly 15371 // allow... it would be nice to have some better way to handle 15372 // this situation. 15373 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15374 if (regrantPermissions) 15375 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15376 + mSdkVersion + "; regranting permissions for external storage"); 15377 mSettings.mExternalSdkPlatform = mSdkVersion; 15378 15379 // Make sure group IDs have been assigned, and any permission 15380 // changes in other apps are accounted for 15381 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15382 | (regrantPermissions 15383 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15384 : 0)); 15385 15386 mSettings.updateExternalDatabaseVersion(); 15387 15388 // can downgrade to reader 15389 // Persist settings 15390 mSettings.writeLPr(); 15391 } 15392 // Send a broadcast to let everyone know we are done processing 15393 if (pkgList.size() > 0) { 15394 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15395 } 15396 } 15397 15398 /* 15399 * Utility method to unload a list of specified containers 15400 */ 15401 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15402 // Just unmount all valid containers. 15403 for (AsecInstallArgs arg : cidArgs) { 15404 synchronized (mInstallLock) { 15405 arg.doPostDeleteLI(false); 15406 } 15407 } 15408 } 15409 15410 /* 15411 * Unload packages mounted on external media. This involves deleting package 15412 * data from internal structures, sending broadcasts about diabled packages, 15413 * gc'ing to free up references, unmounting all secure containers 15414 * corresponding to packages on external media, and posting a 15415 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15416 * that we always have to post this message if status has been requested no 15417 * matter what. 15418 */ 15419 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15420 final boolean reportStatus) { 15421 if (DEBUG_SD_INSTALL) 15422 Log.i(TAG, "unloading media packages"); 15423 ArrayList<String> pkgList = new ArrayList<String>(); 15424 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15425 final Set<AsecInstallArgs> keys = processCids.keySet(); 15426 for (AsecInstallArgs args : keys) { 15427 String pkgName = args.getPackageName(); 15428 if (DEBUG_SD_INSTALL) 15429 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15430 // Delete package internally 15431 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15432 synchronized (mInstallLock) { 15433 boolean res = deletePackageLI(pkgName, null, false, null, null, 15434 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15435 if (res) { 15436 pkgList.add(pkgName); 15437 } else { 15438 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15439 failedList.add(args); 15440 } 15441 } 15442 } 15443 15444 // reader 15445 synchronized (mPackages) { 15446 // We didn't update the settings after removing each package; 15447 // write them now for all packages. 15448 mSettings.writeLPr(); 15449 } 15450 15451 // We have to absolutely send UPDATED_MEDIA_STATUS only 15452 // after confirming that all the receivers processed the ordered 15453 // broadcast when packages get disabled, force a gc to clean things up. 15454 // and unload all the containers. 15455 if (pkgList.size() > 0) { 15456 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15457 new IIntentReceiver.Stub() { 15458 public void performReceive(Intent intent, int resultCode, String data, 15459 Bundle extras, boolean ordered, boolean sticky, 15460 int sendingUser) throws RemoteException { 15461 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15462 reportStatus ? 1 : 0, 1, keys); 15463 mHandler.sendMessage(msg); 15464 } 15465 }); 15466 } else { 15467 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15468 keys); 15469 mHandler.sendMessage(msg); 15470 } 15471 } 15472 15473 private void loadPrivatePackages(VolumeInfo vol) { 15474 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15475 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15476 synchronized (mInstallLock) { 15477 synchronized (mPackages) { 15478 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15479 for (PackageSetting ps : packages) { 15480 final PackageParser.Package pkg; 15481 try { 15482 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15483 loaded.add(pkg.applicationInfo); 15484 } catch (PackageManagerException e) { 15485 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15486 } 15487 } 15488 15489 // TODO: regrant any permissions that changed based since original install 15490 15491 mSettings.writeLPr(); 15492 } 15493 } 15494 15495 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15496 sendResourcesChangedBroadcast(true, false, loaded, null); 15497 } 15498 15499 private void unloadPrivatePackages(VolumeInfo vol) { 15500 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15501 synchronized (mInstallLock) { 15502 synchronized (mPackages) { 15503 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15504 for (PackageSetting ps : packages) { 15505 if (ps.pkg == null) continue; 15506 15507 final ApplicationInfo info = ps.pkg.applicationInfo; 15508 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15509 if (deletePackageLI(ps.name, null, false, null, null, 15510 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15511 unloaded.add(info); 15512 } else { 15513 Slog.w(TAG, "Failed to unload " + ps.codePath); 15514 } 15515 } 15516 15517 mSettings.writeLPr(); 15518 } 15519 } 15520 15521 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15522 sendResourcesChangedBroadcast(false, false, unloaded, null); 15523 } 15524 15525 /** 15526 * Examine all users present on given mounted volume, and destroy data 15527 * belonging to users that are no longer valid, or whose user ID has been 15528 * recycled. 15529 */ 15530 private void reconcileUsers(String volumeUuid) { 15531 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15532 if (ArrayUtils.isEmpty(files)) { 15533 Slog.d(TAG, "No users found on " + volumeUuid); 15534 return; 15535 } 15536 15537 for (File file : files) { 15538 if (!file.isDirectory()) continue; 15539 15540 final int userId; 15541 final UserInfo info; 15542 try { 15543 userId = Integer.parseInt(file.getName()); 15544 info = sUserManager.getUserInfo(userId); 15545 } catch (NumberFormatException e) { 15546 Slog.w(TAG, "Invalid user directory " + file); 15547 continue; 15548 } 15549 15550 boolean destroyUser = false; 15551 if (info == null) { 15552 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15553 + " because no matching user was found"); 15554 destroyUser = true; 15555 } else { 15556 try { 15557 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15558 } catch (IOException e) { 15559 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15560 + " because we failed to enforce serial number: " + e); 15561 destroyUser = true; 15562 } 15563 } 15564 15565 if (destroyUser) { 15566 synchronized (mInstallLock) { 15567 mInstaller.removeUserDataDirs(volumeUuid, userId); 15568 } 15569 } 15570 } 15571 15572 final UserManager um = mContext.getSystemService(UserManager.class); 15573 for (UserInfo user : um.getUsers()) { 15574 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15575 if (userDir.exists()) continue; 15576 15577 try { 15578 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15579 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15580 } catch (IOException e) { 15581 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15582 } 15583 } 15584 } 15585 15586 /** 15587 * Examine all apps present on given mounted volume, and destroy apps that 15588 * aren't expected, either due to uninstallation or reinstallation on 15589 * another volume. 15590 */ 15591 private void reconcileApps(String volumeUuid) { 15592 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15593 if (ArrayUtils.isEmpty(files)) { 15594 Slog.d(TAG, "No apps found on " + volumeUuid); 15595 return; 15596 } 15597 15598 for (File file : files) { 15599 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15600 && !PackageInstallerService.isStageName(file.getName()); 15601 if (!isPackage) { 15602 // Ignore entries which are not packages 15603 continue; 15604 } 15605 15606 boolean destroyApp = false; 15607 String packageName = null; 15608 try { 15609 final PackageLite pkg = PackageParser.parsePackageLite(file, 15610 PackageParser.PARSE_MUST_BE_APK); 15611 packageName = pkg.packageName; 15612 15613 synchronized (mPackages) { 15614 final PackageSetting ps = mSettings.mPackages.get(packageName); 15615 if (ps == null) { 15616 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15617 + volumeUuid + " because we found no install record"); 15618 destroyApp = true; 15619 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15620 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15621 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15622 destroyApp = true; 15623 } 15624 } 15625 15626 } catch (PackageParserException e) { 15627 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15628 destroyApp = true; 15629 } 15630 15631 if (destroyApp) { 15632 synchronized (mInstallLock) { 15633 if (packageName != null) { 15634 removeDataDirsLI(volumeUuid, packageName); 15635 } 15636 if (file.isDirectory()) { 15637 mInstaller.rmPackageDir(file.getAbsolutePath()); 15638 } else { 15639 file.delete(); 15640 } 15641 } 15642 } 15643 } 15644 } 15645 15646 private void unfreezePackage(String packageName) { 15647 synchronized (mPackages) { 15648 final PackageSetting ps = mSettings.mPackages.get(packageName); 15649 if (ps != null) { 15650 ps.frozen = false; 15651 } 15652 } 15653 } 15654 15655 @Override 15656 public int movePackage(final String packageName, final String volumeUuid) { 15657 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15658 15659 final int moveId = mNextMoveId.getAndIncrement(); 15660 try { 15661 movePackageInternal(packageName, volumeUuid, moveId); 15662 } catch (PackageManagerException e) { 15663 Slog.w(TAG, "Failed to move " + packageName, e); 15664 mMoveCallbacks.notifyStatusChanged(moveId, 15665 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15666 } 15667 return moveId; 15668 } 15669 15670 private void movePackageInternal(final String packageName, final String volumeUuid, 15671 final int moveId) throws PackageManagerException { 15672 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15673 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15674 final PackageManager pm = mContext.getPackageManager(); 15675 15676 final boolean currentAsec; 15677 final String currentVolumeUuid; 15678 final File codeFile; 15679 final String installerPackageName; 15680 final String packageAbiOverride; 15681 final int appId; 15682 final String seinfo; 15683 final String label; 15684 15685 // reader 15686 synchronized (mPackages) { 15687 final PackageParser.Package pkg = mPackages.get(packageName); 15688 final PackageSetting ps = mSettings.mPackages.get(packageName); 15689 if (pkg == null || ps == null) { 15690 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15691 } 15692 15693 if (pkg.applicationInfo.isSystemApp()) { 15694 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15695 "Cannot move system application"); 15696 } 15697 15698 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15699 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15700 "Package already moved to " + volumeUuid); 15701 } 15702 15703 final File probe = new File(pkg.codePath); 15704 final File probeOat = new File(probe, "oat"); 15705 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15706 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15707 "Move only supported for modern cluster style installs"); 15708 } 15709 15710 if (ps.frozen) { 15711 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15712 "Failed to move already frozen package"); 15713 } 15714 ps.frozen = true; 15715 15716 currentAsec = pkg.applicationInfo.isForwardLocked() 15717 || pkg.applicationInfo.isExternalAsec(); 15718 currentVolumeUuid = ps.volumeUuid; 15719 codeFile = new File(pkg.codePath); 15720 installerPackageName = ps.installerPackageName; 15721 packageAbiOverride = ps.cpuAbiOverrideString; 15722 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15723 seinfo = pkg.applicationInfo.seinfo; 15724 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15725 } 15726 15727 // Now that we're guarded by frozen state, kill app during move 15728 killApplication(packageName, appId, "move pkg"); 15729 15730 final Bundle extras = new Bundle(); 15731 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15732 extras.putString(Intent.EXTRA_TITLE, label); 15733 mMoveCallbacks.notifyCreated(moveId, extras); 15734 15735 int installFlags; 15736 final boolean moveCompleteApp; 15737 final File measurePath; 15738 15739 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15740 installFlags = INSTALL_INTERNAL; 15741 moveCompleteApp = !currentAsec; 15742 measurePath = Environment.getDataAppDirectory(volumeUuid); 15743 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15744 installFlags = INSTALL_EXTERNAL; 15745 moveCompleteApp = false; 15746 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15747 } else { 15748 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15749 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15750 || !volume.isMountedWritable()) { 15751 unfreezePackage(packageName); 15752 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15753 "Move location not mounted private volume"); 15754 } 15755 15756 Preconditions.checkState(!currentAsec); 15757 15758 installFlags = INSTALL_INTERNAL; 15759 moveCompleteApp = true; 15760 measurePath = Environment.getDataAppDirectory(volumeUuid); 15761 } 15762 15763 final PackageStats stats = new PackageStats(null, -1); 15764 synchronized (mInstaller) { 15765 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15766 unfreezePackage(packageName); 15767 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15768 "Failed to measure package size"); 15769 } 15770 } 15771 15772 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15773 + stats.dataSize); 15774 15775 final long startFreeBytes = measurePath.getFreeSpace(); 15776 final long sizeBytes; 15777 if (moveCompleteApp) { 15778 sizeBytes = stats.codeSize + stats.dataSize; 15779 } else { 15780 sizeBytes = stats.codeSize; 15781 } 15782 15783 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15784 unfreezePackage(packageName); 15785 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15786 "Not enough free space to move"); 15787 } 15788 15789 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15790 15791 final CountDownLatch installedLatch = new CountDownLatch(1); 15792 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15793 @Override 15794 public void onUserActionRequired(Intent intent) throws RemoteException { 15795 throw new IllegalStateException(); 15796 } 15797 15798 @Override 15799 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15800 Bundle extras) throws RemoteException { 15801 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15802 + PackageManager.installStatusToString(returnCode, msg)); 15803 15804 installedLatch.countDown(); 15805 15806 // Regardless of success or failure of the move operation, 15807 // always unfreeze the package 15808 unfreezePackage(packageName); 15809 15810 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15811 switch (status) { 15812 case PackageInstaller.STATUS_SUCCESS: 15813 mMoveCallbacks.notifyStatusChanged(moveId, 15814 PackageManager.MOVE_SUCCEEDED); 15815 break; 15816 case PackageInstaller.STATUS_FAILURE_STORAGE: 15817 mMoveCallbacks.notifyStatusChanged(moveId, 15818 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15819 break; 15820 default: 15821 mMoveCallbacks.notifyStatusChanged(moveId, 15822 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15823 break; 15824 } 15825 } 15826 }; 15827 15828 final MoveInfo move; 15829 if (moveCompleteApp) { 15830 // Kick off a thread to report progress estimates 15831 new Thread() { 15832 @Override 15833 public void run() { 15834 while (true) { 15835 try { 15836 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15837 break; 15838 } 15839 } catch (InterruptedException ignored) { 15840 } 15841 15842 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15843 final int progress = 10 + (int) MathUtils.constrain( 15844 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15845 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15846 } 15847 } 15848 }.start(); 15849 15850 final String dataAppName = codeFile.getName(); 15851 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15852 dataAppName, appId, seinfo); 15853 } else { 15854 move = null; 15855 } 15856 15857 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15858 15859 final Message msg = mHandler.obtainMessage(INIT_COPY); 15860 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15861 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15862 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15863 mHandler.sendMessage(msg); 15864 } 15865 15866 @Override 15867 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15868 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15869 15870 final int realMoveId = mNextMoveId.getAndIncrement(); 15871 final Bundle extras = new Bundle(); 15872 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15873 mMoveCallbacks.notifyCreated(realMoveId, extras); 15874 15875 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15876 @Override 15877 public void onCreated(int moveId, Bundle extras) { 15878 // Ignored 15879 } 15880 15881 @Override 15882 public void onStatusChanged(int moveId, int status, long estMillis) { 15883 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15884 } 15885 }; 15886 15887 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15888 storage.setPrimaryStorageUuid(volumeUuid, callback); 15889 return realMoveId; 15890 } 15891 15892 @Override 15893 public int getMoveStatus(int moveId) { 15894 mContext.enforceCallingOrSelfPermission( 15895 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15896 return mMoveCallbacks.mLastStatus.get(moveId); 15897 } 15898 15899 @Override 15900 public void registerMoveCallback(IPackageMoveObserver callback) { 15901 mContext.enforceCallingOrSelfPermission( 15902 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15903 mMoveCallbacks.register(callback); 15904 } 15905 15906 @Override 15907 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15908 mContext.enforceCallingOrSelfPermission( 15909 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15910 mMoveCallbacks.unregister(callback); 15911 } 15912 15913 @Override 15914 public boolean setInstallLocation(int loc) { 15915 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15916 null); 15917 if (getInstallLocation() == loc) { 15918 return true; 15919 } 15920 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15921 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15922 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15923 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15924 return true; 15925 } 15926 return false; 15927 } 15928 15929 @Override 15930 public int getInstallLocation() { 15931 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15932 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15933 PackageHelper.APP_INSTALL_AUTO); 15934 } 15935 15936 /** Called by UserManagerService */ 15937 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15938 mDirtyUsers.remove(userHandle); 15939 mSettings.removeUserLPw(userHandle); 15940 mPendingBroadcasts.remove(userHandle); 15941 if (mInstaller != null) { 15942 // Technically, we shouldn't be doing this with the package lock 15943 // held. However, this is very rare, and there is already so much 15944 // other disk I/O going on, that we'll let it slide for now. 15945 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15946 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15947 final String volumeUuid = vol.getFsUuid(); 15948 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15949 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15950 } 15951 } 15952 mUserNeedsBadging.delete(userHandle); 15953 removeUnusedPackagesLILPw(userManager, userHandle); 15954 } 15955 15956 /** 15957 * We're removing userHandle and would like to remove any downloaded packages 15958 * that are no longer in use by any other user. 15959 * @param userHandle the user being removed 15960 */ 15961 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15962 final boolean DEBUG_CLEAN_APKS = false; 15963 int [] users = userManager.getUserIdsLPr(); 15964 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15965 while (psit.hasNext()) { 15966 PackageSetting ps = psit.next(); 15967 if (ps.pkg == null) { 15968 continue; 15969 } 15970 final String packageName = ps.pkg.packageName; 15971 // Skip over if system app 15972 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15973 continue; 15974 } 15975 if (DEBUG_CLEAN_APKS) { 15976 Slog.i(TAG, "Checking package " + packageName); 15977 } 15978 boolean keep = false; 15979 for (int i = 0; i < users.length; i++) { 15980 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15981 keep = true; 15982 if (DEBUG_CLEAN_APKS) { 15983 Slog.i(TAG, " Keeping package " + packageName + " for user " 15984 + users[i]); 15985 } 15986 break; 15987 } 15988 } 15989 if (!keep) { 15990 if (DEBUG_CLEAN_APKS) { 15991 Slog.i(TAG, " Removing package " + packageName); 15992 } 15993 mHandler.post(new Runnable() { 15994 public void run() { 15995 deletePackageX(packageName, userHandle, 0); 15996 } //end run 15997 }); 15998 } 15999 } 16000 } 16001 16002 /** Called by UserManagerService */ 16003 void createNewUserLILPw(int userHandle) { 16004 if (mInstaller != null) { 16005 mInstaller.createUserConfig(userHandle); 16006 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16007 applyFactoryDefaultBrowserLPw(userHandle); 16008 primeDomainVerificationsLPw(userHandle); 16009 } 16010 } 16011 16012 void newUserCreated(final int userHandle) { 16013 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16014 } 16015 16016 @Override 16017 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16018 mContext.enforceCallingOrSelfPermission( 16019 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16020 "Only package verification agents can read the verifier device identity"); 16021 16022 synchronized (mPackages) { 16023 return mSettings.getVerifierDeviceIdentityLPw(); 16024 } 16025 } 16026 16027 @Override 16028 public void setPermissionEnforced(String permission, boolean enforced) { 16029 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 16030 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16031 synchronized (mPackages) { 16032 if (mSettings.mReadExternalStorageEnforced == null 16033 || mSettings.mReadExternalStorageEnforced != enforced) { 16034 mSettings.mReadExternalStorageEnforced = enforced; 16035 mSettings.writeLPr(); 16036 } 16037 } 16038 // kill any non-foreground processes so we restart them and 16039 // grant/revoke the GID. 16040 final IActivityManager am = ActivityManagerNative.getDefault(); 16041 if (am != null) { 16042 final long token = Binder.clearCallingIdentity(); 16043 try { 16044 am.killProcessesBelowForeground("setPermissionEnforcement"); 16045 } catch (RemoteException e) { 16046 } finally { 16047 Binder.restoreCallingIdentity(token); 16048 } 16049 } 16050 } else { 16051 throw new IllegalArgumentException("No selective enforcement for " + permission); 16052 } 16053 } 16054 16055 @Override 16056 @Deprecated 16057 public boolean isPermissionEnforced(String permission) { 16058 return true; 16059 } 16060 16061 @Override 16062 public boolean isStorageLow() { 16063 final long token = Binder.clearCallingIdentity(); 16064 try { 16065 final DeviceStorageMonitorInternal 16066 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16067 if (dsm != null) { 16068 return dsm.isMemoryLow(); 16069 } else { 16070 return false; 16071 } 16072 } finally { 16073 Binder.restoreCallingIdentity(token); 16074 } 16075 } 16076 16077 @Override 16078 public IPackageInstaller getPackageInstaller() { 16079 return mInstallerService; 16080 } 16081 16082 private boolean userNeedsBadging(int userId) { 16083 int index = mUserNeedsBadging.indexOfKey(userId); 16084 if (index < 0) { 16085 final UserInfo userInfo; 16086 final long token = Binder.clearCallingIdentity(); 16087 try { 16088 userInfo = sUserManager.getUserInfo(userId); 16089 } finally { 16090 Binder.restoreCallingIdentity(token); 16091 } 16092 final boolean b; 16093 if (userInfo != null && userInfo.isManagedProfile()) { 16094 b = true; 16095 } else { 16096 b = false; 16097 } 16098 mUserNeedsBadging.put(userId, b); 16099 return b; 16100 } 16101 return mUserNeedsBadging.valueAt(index); 16102 } 16103 16104 @Override 16105 public KeySet getKeySetByAlias(String packageName, String alias) { 16106 if (packageName == null || alias == null) { 16107 return null; 16108 } 16109 synchronized(mPackages) { 16110 final PackageParser.Package pkg = mPackages.get(packageName); 16111 if (pkg == null) { 16112 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16113 throw new IllegalArgumentException("Unknown package: " + packageName); 16114 } 16115 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16116 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16117 } 16118 } 16119 16120 @Override 16121 public KeySet getSigningKeySet(String packageName) { 16122 if (packageName == null) { 16123 return null; 16124 } 16125 synchronized(mPackages) { 16126 final PackageParser.Package pkg = mPackages.get(packageName); 16127 if (pkg == null) { 16128 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16129 throw new IllegalArgumentException("Unknown package: " + packageName); 16130 } 16131 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16132 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16133 throw new SecurityException("May not access signing KeySet of other apps."); 16134 } 16135 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16136 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16137 } 16138 } 16139 16140 @Override 16141 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16142 if (packageName == null || ks == null) { 16143 return false; 16144 } 16145 synchronized(mPackages) { 16146 final PackageParser.Package pkg = mPackages.get(packageName); 16147 if (pkg == null) { 16148 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16149 throw new IllegalArgumentException("Unknown package: " + packageName); 16150 } 16151 IBinder ksh = ks.getToken(); 16152 if (ksh instanceof KeySetHandle) { 16153 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16154 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16155 } 16156 return false; 16157 } 16158 } 16159 16160 @Override 16161 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16162 if (packageName == null || ks == null) { 16163 return false; 16164 } 16165 synchronized(mPackages) { 16166 final PackageParser.Package pkg = mPackages.get(packageName); 16167 if (pkg == null) { 16168 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16169 throw new IllegalArgumentException("Unknown package: " + packageName); 16170 } 16171 IBinder ksh = ks.getToken(); 16172 if (ksh instanceof KeySetHandle) { 16173 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16174 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16175 } 16176 return false; 16177 } 16178 } 16179 16180 public void getUsageStatsIfNoPackageUsageInfo() { 16181 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16182 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16183 if (usm == null) { 16184 throw new IllegalStateException("UsageStatsManager must be initialized"); 16185 } 16186 long now = System.currentTimeMillis(); 16187 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16188 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16189 String packageName = entry.getKey(); 16190 PackageParser.Package pkg = mPackages.get(packageName); 16191 if (pkg == null) { 16192 continue; 16193 } 16194 UsageStats usage = entry.getValue(); 16195 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16196 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16197 } 16198 } 16199 } 16200 16201 /** 16202 * Check and throw if the given before/after packages would be considered a 16203 * downgrade. 16204 */ 16205 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16206 throws PackageManagerException { 16207 if (after.versionCode < before.mVersionCode) { 16208 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16209 "Update version code " + after.versionCode + " is older than current " 16210 + before.mVersionCode); 16211 } else if (after.versionCode == before.mVersionCode) { 16212 if (after.baseRevisionCode < before.baseRevisionCode) { 16213 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16214 "Update base revision code " + after.baseRevisionCode 16215 + " is older than current " + before.baseRevisionCode); 16216 } 16217 16218 if (!ArrayUtils.isEmpty(after.splitNames)) { 16219 for (int i = 0; i < after.splitNames.length; i++) { 16220 final String splitName = after.splitNames[i]; 16221 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16222 if (j != -1) { 16223 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16224 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16225 "Update split " + splitName + " revision code " 16226 + after.splitRevisionCodes[i] + " is older than current " 16227 + before.splitRevisionCodes[j]); 16228 } 16229 } 16230 } 16231 } 16232 } 16233 } 16234 16235 private static class MoveCallbacks extends Handler { 16236 private static final int MSG_CREATED = 1; 16237 private static final int MSG_STATUS_CHANGED = 2; 16238 16239 private final RemoteCallbackList<IPackageMoveObserver> 16240 mCallbacks = new RemoteCallbackList<>(); 16241 16242 private final SparseIntArray mLastStatus = new SparseIntArray(); 16243 16244 public MoveCallbacks(Looper looper) { 16245 super(looper); 16246 } 16247 16248 public void register(IPackageMoveObserver callback) { 16249 mCallbacks.register(callback); 16250 } 16251 16252 public void unregister(IPackageMoveObserver callback) { 16253 mCallbacks.unregister(callback); 16254 } 16255 16256 @Override 16257 public void handleMessage(Message msg) { 16258 final SomeArgs args = (SomeArgs) msg.obj; 16259 final int n = mCallbacks.beginBroadcast(); 16260 for (int i = 0; i < n; i++) { 16261 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16262 try { 16263 invokeCallback(callback, msg.what, args); 16264 } catch (RemoteException ignored) { 16265 } 16266 } 16267 mCallbacks.finishBroadcast(); 16268 args.recycle(); 16269 } 16270 16271 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16272 throws RemoteException { 16273 switch (what) { 16274 case MSG_CREATED: { 16275 callback.onCreated(args.argi1, (Bundle) args.arg2); 16276 break; 16277 } 16278 case MSG_STATUS_CHANGED: { 16279 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16280 break; 16281 } 16282 } 16283 } 16284 16285 private void notifyCreated(int moveId, Bundle extras) { 16286 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16287 16288 final SomeArgs args = SomeArgs.obtain(); 16289 args.argi1 = moveId; 16290 args.arg2 = extras; 16291 obtainMessage(MSG_CREATED, args).sendToTarget(); 16292 } 16293 16294 private void notifyStatusChanged(int moveId, int status) { 16295 notifyStatusChanged(moveId, status, -1); 16296 } 16297 16298 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16299 Slog.v(TAG, "Move " + moveId + " status " + status); 16300 16301 final SomeArgs args = SomeArgs.obtain(); 16302 args.argi1 = moveId; 16303 args.argi2 = status; 16304 args.arg3 = estMillis; 16305 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16306 16307 synchronized (mLastStatus) { 16308 mLastStatus.put(moveId, status); 16309 } 16310 } 16311 } 16312 16313 private final class OnPermissionChangeListeners extends Handler { 16314 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16315 16316 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16317 new RemoteCallbackList<>(); 16318 16319 public OnPermissionChangeListeners(Looper looper) { 16320 super(looper); 16321 } 16322 16323 @Override 16324 public void handleMessage(Message msg) { 16325 switch (msg.what) { 16326 case MSG_ON_PERMISSIONS_CHANGED: { 16327 final int uid = msg.arg1; 16328 handleOnPermissionsChanged(uid); 16329 } break; 16330 } 16331 } 16332 16333 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16334 mPermissionListeners.register(listener); 16335 16336 } 16337 16338 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16339 mPermissionListeners.unregister(listener); 16340 } 16341 16342 public void onPermissionsChanged(int uid) { 16343 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16344 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16345 } 16346 } 16347 16348 private void handleOnPermissionsChanged(int uid) { 16349 final int count = mPermissionListeners.beginBroadcast(); 16350 try { 16351 for (int i = 0; i < count; i++) { 16352 IOnPermissionsChangeListener callback = mPermissionListeners 16353 .getBroadcastItem(i); 16354 try { 16355 callback.onPermissionsChanged(uid); 16356 } catch (RemoteException e) { 16357 Log.e(TAG, "Permission listener is dead", e); 16358 } 16359 } 16360 } finally { 16361 mPermissionListeners.finishBroadcast(); 16362 } 16363 } 16364 } 16365 16366 private class PackageManagerInternalImpl extends PackageManagerInternal { 16367 @Override 16368 public void setLocationPackagesProvider(PackagesProvider provider) { 16369 synchronized (mPackages) { 16370 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16371 } 16372 } 16373 16374 @Override 16375 public void setImePackagesProvider(PackagesProvider provider) { 16376 synchronized (mPackages) { 16377 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16378 } 16379 } 16380 16381 @Override 16382 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16383 synchronized (mPackages) { 16384 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16385 } 16386 } 16387 16388 @Override 16389 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16390 synchronized (mPackages) { 16391 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16392 } 16393 } 16394 16395 @Override 16396 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16397 synchronized (mPackages) { 16398 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16399 } 16400 } 16401 16402 @Override 16403 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16404 synchronized (mPackages) { 16405 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16406 } 16407 } 16408 16409 @Override 16410 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16411 synchronized (mPackages) { 16412 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16413 packageName, userId); 16414 } 16415 } 16416 16417 @Override 16418 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16419 synchronized (mPackages) { 16420 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16421 packageName, userId); 16422 } 16423 } 16424 } 16425 16426 @Override 16427 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16428 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16429 synchronized (mPackages) { 16430 final long identity = Binder.clearCallingIdentity(); 16431 try { 16432 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16433 packageNames, userId); 16434 } finally { 16435 Binder.restoreCallingIdentity(identity); 16436 } 16437 } 16438 } 16439 16440 private static void enforceSystemOrPhoneCaller(String tag) { 16441 int callingUid = Binder.getCallingUid(); 16442 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16443 throw new SecurityException( 16444 "Cannot call " + tag + " from UID " + callingUid); 16445 } 16446 } 16447} 16448