PackageManagerService.java revision a17b7f8c4be93d3cc60b75bf4977a98b8d3192d0
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_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.system.OsConstants.O_CREAT; 70import static android.system.OsConstants.O_RDWR; 71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 75import static com.android.internal.util.ArrayUtils.appendInt; 76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 84 85import android.Manifest; 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.AppGlobals; 89import android.app.IActivityManager; 90import android.app.admin.IDevicePolicyManager; 91import android.app.backup.IBackupManager; 92import android.app.usage.UsageStats; 93import android.app.usage.UsageStatsManager; 94import android.content.BroadcastReceiver; 95import android.content.ComponentName; 96import android.content.Context; 97import android.content.IIntentReceiver; 98import android.content.Intent; 99import android.content.IntentFilter; 100import android.content.IntentSender; 101import android.content.IntentSender.SendIntentException; 102import android.content.ServiceConnection; 103import android.content.pm.ActivityInfo; 104import android.content.pm.ApplicationInfo; 105import android.content.pm.FeatureInfo; 106import android.content.pm.IOnPermissionsChangeListener; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.IntentFilterVerificationInfo; 117import android.content.pm.KeySet; 118import android.content.pm.ManifestDigest; 119import android.content.pm.PackageCleanItem; 120import android.content.pm.PackageInfo; 121import android.content.pm.PackageInfoLite; 122import android.content.pm.PackageInstaller; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 125import android.content.pm.PackageManagerInternal; 126import android.content.pm.PackageParser; 127import android.content.pm.PackageParser.ActivityIntentInfo; 128import android.content.pm.PackageParser.PackageLite; 129import android.content.pm.PackageParser.PackageParserException; 130import android.content.pm.PackageStats; 131import android.content.pm.PackageUserState; 132import android.content.pm.ParceledListSlice; 133import android.content.pm.PermissionGroupInfo; 134import android.content.pm.PermissionInfo; 135import android.content.pm.ProviderInfo; 136import android.content.pm.ResolveInfo; 137import android.content.pm.ServiceInfo; 138import android.content.pm.Signature; 139import android.content.pm.UserInfo; 140import android.content.pm.VerificationParams; 141import android.content.pm.VerifierDeviceIdentity; 142import android.content.pm.VerifierInfo; 143import android.content.res.Resources; 144import android.hardware.display.DisplayManager; 145import android.net.Uri; 146import android.os.Binder; 147import android.os.Build; 148import android.os.Bundle; 149import android.os.Debug; 150import android.os.Environment; 151import android.os.Environment.UserEnvironment; 152import android.os.FileUtils; 153import android.os.Handler; 154import android.os.IBinder; 155import android.os.Looper; 156import android.os.Message; 157import android.os.Parcel; 158import android.os.ParcelFileDescriptor; 159import android.os.Process; 160import android.os.RemoteCallbackList; 161import android.os.RemoteException; 162import android.os.SELinux; 163import android.os.ServiceManager; 164import android.os.SystemClock; 165import android.os.SystemProperties; 166import android.os.UserHandle; 167import android.os.UserManager; 168import android.os.storage.IMountService; 169import android.os.storage.StorageEventListener; 170import android.os.storage.StorageManager; 171import android.os.storage.VolumeInfo; 172import android.os.storage.VolumeRecord; 173import android.security.KeyStore; 174import android.security.SystemKeyStore; 175import android.system.ErrnoException; 176import android.system.Os; 177import android.system.StructStat; 178import android.text.TextUtils; 179import android.text.format.DateUtils; 180import android.util.ArrayMap; 181import android.util.ArraySet; 182import android.util.AtomicFile; 183import android.util.DisplayMetrics; 184import android.util.EventLog; 185import android.util.ExceptionUtils; 186import android.util.Log; 187import android.util.LogPrinter; 188import android.util.MathUtils; 189import android.util.PrintStreamPrinter; 190import android.util.Slog; 191import android.util.SparseArray; 192import android.util.SparseBooleanArray; 193import android.util.SparseIntArray; 194import android.util.Xml; 195import android.view.Display; 196 197import dalvik.system.DexFile; 198import dalvik.system.VMRuntime; 199 200import libcore.io.IoUtils; 201import libcore.util.EmptyArray; 202 203import com.android.internal.R; 204import com.android.internal.annotations.GuardedBy; 205import com.android.internal.app.IMediaContainerService; 206import com.android.internal.app.ResolverActivity; 207import com.android.internal.content.NativeLibraryHelper; 208import com.android.internal.content.PackageHelper; 209import com.android.internal.os.IParcelFileDescriptorFactory; 210import com.android.internal.os.SomeArgs; 211import com.android.internal.os.Zygote; 212import com.android.internal.util.ArrayUtils; 213import com.android.internal.util.FastPrintWriter; 214import com.android.internal.util.FastXmlSerializer; 215import com.android.internal.util.IndentingPrintWriter; 216import com.android.internal.util.Preconditions; 217import com.android.server.EventLogTags; 218import com.android.server.FgThread; 219import com.android.server.IntentResolver; 220import com.android.server.LocalServices; 221import com.android.server.ServiceThread; 222import com.android.server.SystemConfig; 223import com.android.server.Watchdog; 224import com.android.server.pm.PermissionsState.PermissionState; 225import com.android.server.pm.Settings.DatabaseVersion; 226import com.android.server.storage.DeviceStorageMonitorInternal; 227 228import org.xmlpull.v1.XmlPullParser; 229import org.xmlpull.v1.XmlPullParserException; 230import org.xmlpull.v1.XmlSerializer; 231 232import java.io.BufferedInputStream; 233import java.io.BufferedOutputStream; 234import java.io.BufferedReader; 235import java.io.ByteArrayInputStream; 236import java.io.ByteArrayOutputStream; 237import java.io.File; 238import java.io.FileDescriptor; 239import java.io.FileNotFoundException; 240import java.io.FileOutputStream; 241import java.io.FileReader; 242import java.io.FilenameFilter; 243import java.io.IOException; 244import java.io.InputStream; 245import java.io.PrintWriter; 246import java.nio.charset.StandardCharsets; 247import java.security.NoSuchAlgorithmException; 248import java.security.PublicKey; 249import java.security.cert.CertificateEncodingException; 250import java.security.cert.CertificateException; 251import java.text.SimpleDateFormat; 252import java.util.ArrayList; 253import java.util.Arrays; 254import java.util.Collection; 255import java.util.Collections; 256import java.util.Comparator; 257import java.util.Date; 258import java.util.Iterator; 259import java.util.List; 260import java.util.Map; 261import java.util.Objects; 262import java.util.Set; 263import java.util.concurrent.CountDownLatch; 264import java.util.concurrent.TimeUnit; 265import java.util.concurrent.atomic.AtomicBoolean; 266import java.util.concurrent.atomic.AtomicInteger; 267import java.util.concurrent.atomic.AtomicLong; 268 269/** 270 * Keep track of all those .apks everywhere. 271 * 272 * This is very central to the platform's security; please run the unit 273 * tests whenever making modifications here: 274 * 275runtest -c android.content.pm.PackageManagerTests frameworks-core 276 * 277 * {@hide} 278 */ 279public class PackageManagerService extends IPackageManager.Stub { 280 static final String TAG = "PackageManager"; 281 static final boolean DEBUG_SETTINGS = false; 282 static final boolean DEBUG_PREFERRED = false; 283 static final boolean DEBUG_UPGRADE = false; 284 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 285 private static final boolean DEBUG_BACKUP = true; 286 private static final boolean DEBUG_INSTALL = false; 287 private static final boolean DEBUG_REMOVE = false; 288 private static final boolean DEBUG_BROADCASTS = false; 289 private static final boolean DEBUG_SHOW_INFO = false; 290 private static final boolean DEBUG_PACKAGE_INFO = false; 291 private static final boolean DEBUG_INTENT_MATCHING = false; 292 private static final boolean DEBUG_PACKAGE_SCANNING = false; 293 private static final boolean DEBUG_VERIFY = false; 294 private static final boolean DEBUG_DEXOPT = false; 295 private static final boolean DEBUG_ABI_SELECTION = false; 296 297 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 298 299 private static final int RADIO_UID = Process.PHONE_UID; 300 private static final int LOG_UID = Process.LOG_UID; 301 private static final int NFC_UID = Process.NFC_UID; 302 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 303 private static final int SHELL_UID = Process.SHELL_UID; 304 305 // Cap the size of permission trees that 3rd party apps can define 306 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 307 308 // Suffix used during package installation when copying/moving 309 // package apks to install directory. 310 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 311 312 static final int SCAN_NO_DEX = 1<<1; 313 static final int SCAN_FORCE_DEX = 1<<2; 314 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 315 static final int SCAN_NEW_INSTALL = 1<<4; 316 static final int SCAN_NO_PATHS = 1<<5; 317 static final int SCAN_UPDATE_TIME = 1<<6; 318 static final int SCAN_DEFER_DEX = 1<<7; 319 static final int SCAN_BOOTING = 1<<8; 320 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 321 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 322 static final int SCAN_REQUIRE_KNOWN = 1<<12; 323 static final int SCAN_MOVE = 1<<13; 324 static final int SCAN_INITIAL = 1<<14; 325 326 static final int REMOVE_CHATTY = 1<<16; 327 328 private static final int[] EMPTY_INT_ARRAY = new int[0]; 329 330 /** 331 * Timeout (in milliseconds) after which the watchdog should declare that 332 * our handler thread is wedged. The usual default for such things is one 333 * minute but we sometimes do very lengthy I/O operations on this thread, 334 * such as installing multi-gigabyte applications, so ours needs to be longer. 335 */ 336 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 337 338 /** 339 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 340 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 341 * settings entry if available, otherwise we use the hardcoded default. If it's been 342 * more than this long since the last fstrim, we force one during the boot sequence. 343 * 344 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 345 * one gets run at the next available charging+idle time. This final mandatory 346 * no-fstrim check kicks in only of the other scheduling criteria is never met. 347 */ 348 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 349 350 /** 351 * Whether verification is enabled by default. 352 */ 353 private static final boolean DEFAULT_VERIFY_ENABLE = true; 354 355 /** 356 * The default maximum time to wait for the verification agent to return in 357 * milliseconds. 358 */ 359 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 360 361 /** 362 * The default response for package verification timeout. 363 * 364 * This can be either PackageManager.VERIFICATION_ALLOW or 365 * PackageManager.VERIFICATION_REJECT. 366 */ 367 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 368 369 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 370 371 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 372 DEFAULT_CONTAINER_PACKAGE, 373 "com.android.defcontainer.DefaultContainerService"); 374 375 private static final String KILL_APP_REASON_GIDS_CHANGED = 376 "permission grant or revoke changed gids"; 377 378 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 379 "permissions revoked"; 380 381 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 382 383 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 384 385 /** Permission grant: not grant the permission. */ 386 private static final int GRANT_DENIED = 1; 387 388 /** Permission grant: grant the permission as an install permission. */ 389 private static final int GRANT_INSTALL = 2; 390 391 /** Permission grant: grant the permission as an install permission for a legacy app. */ 392 private static final int GRANT_INSTALL_LEGACY = 3; 393 394 /** Permission grant: grant the permission as a runtime one. */ 395 private static final int GRANT_RUNTIME = 4; 396 397 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 398 private static final int GRANT_UPGRADE = 5; 399 400 /** Canonical intent used to identify what counts as a "web browser" app */ 401 private static final Intent sBrowserIntent; 402 static { 403 sBrowserIntent = new Intent(); 404 sBrowserIntent.setAction(Intent.ACTION_VIEW); 405 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 406 sBrowserIntent.setData(Uri.parse("http:")); 407 } 408 409 final ServiceThread mHandlerThread; 410 411 final PackageHandler mHandler; 412 413 /** 414 * Messages for {@link #mHandler} that need to wait for system ready before 415 * being dispatched. 416 */ 417 private ArrayList<Message> mPostSystemReadyMessages; 418 419 final int mSdkVersion = Build.VERSION.SDK_INT; 420 421 final Context mContext; 422 final boolean mFactoryTest; 423 final boolean mOnlyCore; 424 final boolean mLazyDexOpt; 425 final long mDexOptLRUThresholdInMills; 426 final DisplayMetrics mMetrics; 427 final int mDefParseFlags; 428 final String[] mSeparateProcesses; 429 final boolean mIsUpgrade; 430 431 // This is where all application persistent data goes. 432 final File mAppDataDir; 433 434 // This is where all application persistent data goes for secondary users. 435 final File mUserAppDataDir; 436 437 /** The location for ASEC container files on internal storage. */ 438 final String mAsecInternalPath; 439 440 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 441 // LOCK HELD. Can be called with mInstallLock held. 442 @GuardedBy("mInstallLock") 443 final Installer mInstaller; 444 445 /** Directory where installed third-party apps stored */ 446 final File mAppInstallDir; 447 448 /** 449 * Directory to which applications installed internally have their 450 * 32 bit native libraries copied. 451 */ 452 private File mAppLib32InstallDir; 453 454 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 455 // apps. 456 final File mDrmAppPrivateInstallDir; 457 458 // ---------------------------------------------------------------- 459 460 // Lock for state used when installing and doing other long running 461 // operations. Methods that must be called with this lock held have 462 // the suffix "LI". 463 final Object mInstallLock = new Object(); 464 465 // ---------------------------------------------------------------- 466 467 // Keys are String (package name), values are Package. This also serves 468 // as the lock for the global state. Methods that must be called with 469 // this lock held have the prefix "LP". 470 @GuardedBy("mPackages") 471 final ArrayMap<String, PackageParser.Package> mPackages = 472 new ArrayMap<String, PackageParser.Package>(); 473 474 // Tracks available target package names -> overlay package paths. 475 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 476 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 477 478 /** 479 * Tracks new system packages [receiving in an OTA] that we expect to 480 * find updated user-installed versions. Keys are package name, values 481 * are package location. 482 */ 483 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 484 485 final Settings mSettings; 486 boolean mRestoredSettings; 487 488 // System configuration read by SystemConfig. 489 final int[] mGlobalGids; 490 final SparseArray<ArraySet<String>> mSystemPermissions; 491 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 492 493 // If mac_permissions.xml was found for seinfo labeling. 494 boolean mFoundPolicyFile; 495 496 // If a recursive restorecon of /data/data/<pkg> is needed. 497 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 498 499 public static final class SharedLibraryEntry { 500 public final String path; 501 public final String apk; 502 503 SharedLibraryEntry(String _path, String _apk) { 504 path = _path; 505 apk = _apk; 506 } 507 } 508 509 // Currently known shared libraries. 510 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 511 new ArrayMap<String, SharedLibraryEntry>(); 512 513 // All available activities, for your resolving pleasure. 514 final ActivityIntentResolver mActivities = 515 new ActivityIntentResolver(); 516 517 // All available receivers, for your resolving pleasure. 518 final ActivityIntentResolver mReceivers = 519 new ActivityIntentResolver(); 520 521 // All available services, for your resolving pleasure. 522 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 523 524 // All available providers, for your resolving pleasure. 525 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 526 527 // Mapping from provider base names (first directory in content URI codePath) 528 // to the provider information. 529 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 530 new ArrayMap<String, PackageParser.Provider>(); 531 532 // Mapping from instrumentation class names to info about them. 533 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 534 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 535 536 // Mapping from permission names to info about them. 537 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 538 new ArrayMap<String, PackageParser.PermissionGroup>(); 539 540 // Packages whose data we have transfered into another package, thus 541 // should no longer exist. 542 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 543 544 // Broadcast actions that are only available to the system. 545 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 546 547 /** List of packages waiting for verification. */ 548 final SparseArray<PackageVerificationState> mPendingVerification 549 = new SparseArray<PackageVerificationState>(); 550 551 /** Set of packages associated with each app op permission. */ 552 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 553 554 final PackageInstallerService mInstallerService; 555 556 private final PackageDexOptimizer mPackageDexOptimizer; 557 558 private AtomicInteger mNextMoveId = new AtomicInteger(); 559 private final MoveCallbacks mMoveCallbacks; 560 561 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 562 563 // Cache of users who need badging. 564 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 565 566 /** Token for keys in mPendingVerification. */ 567 private int mPendingVerificationToken = 0; 568 569 volatile boolean mSystemReady; 570 volatile boolean mSafeMode; 571 volatile boolean mHasSystemUidErrors; 572 573 ApplicationInfo mAndroidApplication; 574 final ActivityInfo mResolveActivity = new ActivityInfo(); 575 final ResolveInfo mResolveInfo = new ResolveInfo(); 576 ComponentName mResolveComponentName; 577 PackageParser.Package mPlatformPackage; 578 ComponentName mCustomResolverComponentName; 579 580 boolean mResolverReplaced = false; 581 582 private final ComponentName mIntentFilterVerifierComponent; 583 private int mIntentFilterVerificationToken = 0; 584 585 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 586 = new SparseArray<IntentFilterVerificationState>(); 587 588 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 589 new DefaultPermissionGrantPolicy(this); 590 591 private static class IFVerificationParams { 592 PackageParser.Package pkg; 593 boolean replacing; 594 int userId; 595 int verifierUid; 596 597 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 598 int _userId, int _verifierUid) { 599 pkg = _pkg; 600 replacing = _replacing; 601 userId = _userId; 602 replacing = _replacing; 603 verifierUid = _verifierUid; 604 } 605 } 606 607 private interface IntentFilterVerifier<T extends IntentFilter> { 608 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 609 T filter, String packageName); 610 void startVerifications(int userId); 611 void receiveVerificationResponse(int verificationId); 612 } 613 614 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 615 private Context mContext; 616 private ComponentName mIntentFilterVerifierComponent; 617 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 618 619 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 620 mContext = context; 621 mIntentFilterVerifierComponent = verifierComponent; 622 } 623 624 private String getDefaultScheme() { 625 return IntentFilter.SCHEME_HTTPS; 626 } 627 628 @Override 629 public void startVerifications(int userId) { 630 // Launch verifications requests 631 int count = mCurrentIntentFilterVerifications.size(); 632 for (int n=0; n<count; n++) { 633 int verificationId = mCurrentIntentFilterVerifications.get(n); 634 final IntentFilterVerificationState ivs = 635 mIntentFilterVerificationStates.get(verificationId); 636 637 String packageName = ivs.getPackageName(); 638 639 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 640 final int filterCount = filters.size(); 641 ArraySet<String> domainsSet = new ArraySet<>(); 642 for (int m=0; m<filterCount; m++) { 643 PackageParser.ActivityIntentInfo filter = filters.get(m); 644 domainsSet.addAll(filter.getHostsList()); 645 } 646 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 647 synchronized (mPackages) { 648 if (mSettings.createIntentFilterVerificationIfNeededLPw( 649 packageName, domainsList) != null) { 650 scheduleWriteSettingsLocked(); 651 } 652 } 653 sendVerificationRequest(userId, verificationId, ivs); 654 } 655 mCurrentIntentFilterVerifications.clear(); 656 } 657 658 private void sendVerificationRequest(int userId, int verificationId, 659 IntentFilterVerificationState ivs) { 660 661 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 662 verificationIntent.putExtra( 663 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 664 verificationId); 665 verificationIntent.putExtra( 666 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 667 getDefaultScheme()); 668 verificationIntent.putExtra( 669 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 670 ivs.getHostsString()); 671 verificationIntent.putExtra( 672 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 673 ivs.getPackageName()); 674 verificationIntent.setComponent(mIntentFilterVerifierComponent); 675 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 676 677 UserHandle user = new UserHandle(userId); 678 mContext.sendBroadcastAsUser(verificationIntent, user); 679 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 680 "Sending IntentFilter verification broadcast"); 681 } 682 683 public void receiveVerificationResponse(int verificationId) { 684 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 685 686 final boolean verified = ivs.isVerified(); 687 688 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 689 final int count = filters.size(); 690 if (DEBUG_DOMAIN_VERIFICATION) { 691 Slog.i(TAG, "Received verification response " + verificationId 692 + " for " + count + " filters, verified=" + verified); 693 } 694 for (int n=0; n<count; n++) { 695 PackageParser.ActivityIntentInfo filter = filters.get(n); 696 filter.setVerified(verified); 697 698 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 699 + " verified with result:" + verified + " and hosts:" 700 + ivs.getHostsString()); 701 } 702 703 mIntentFilterVerificationStates.remove(verificationId); 704 705 final String packageName = ivs.getPackageName(); 706 IntentFilterVerificationInfo ivi = null; 707 708 synchronized (mPackages) { 709 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 710 } 711 if (ivi == null) { 712 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 713 + verificationId + " packageName:" + packageName); 714 return; 715 } 716 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 717 "Updating IntentFilterVerificationInfo for package " + packageName 718 +" verificationId:" + verificationId); 719 720 synchronized (mPackages) { 721 if (verified) { 722 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 723 } else { 724 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 725 } 726 scheduleWriteSettingsLocked(); 727 728 final int userId = ivs.getUserId(); 729 if (userId != UserHandle.USER_ALL) { 730 final int userStatus = 731 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 732 733 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 734 boolean needUpdate = false; 735 736 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 737 // already been set by the User thru the Disambiguation dialog 738 switch (userStatus) { 739 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 740 if (verified) { 741 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 742 } else { 743 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 744 } 745 needUpdate = true; 746 break; 747 748 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 749 if (verified) { 750 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 751 needUpdate = true; 752 } 753 break; 754 755 default: 756 // Nothing to do 757 } 758 759 if (needUpdate) { 760 mSettings.updateIntentFilterVerificationStatusLPw( 761 packageName, updatedStatus, userId); 762 scheduleWritePackageRestrictionsLocked(userId); 763 } 764 } 765 } 766 } 767 768 @Override 769 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 770 ActivityIntentInfo filter, String packageName) { 771 if (!hasValidDomains(filter)) { 772 return false; 773 } 774 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 775 if (ivs == null) { 776 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 777 packageName); 778 } 779 if (DEBUG_DOMAIN_VERIFICATION) { 780 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 781 } 782 ivs.addFilter(filter); 783 return true; 784 } 785 786 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 787 int userId, int verificationId, String packageName) { 788 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 789 verifierUid, userId, packageName); 790 ivs.setPendingState(); 791 synchronized (mPackages) { 792 mIntentFilterVerificationStates.append(verificationId, ivs); 793 mCurrentIntentFilterVerifications.add(verificationId); 794 } 795 return ivs; 796 } 797 } 798 799 private static boolean hasValidDomains(ActivityIntentInfo filter) { 800 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 801 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 802 if (!hasHTTPorHTTPS) { 803 return false; 804 } 805 return true; 806 } 807 808 private IntentFilterVerifier mIntentFilterVerifier; 809 810 // Set of pending broadcasts for aggregating enable/disable of components. 811 static class PendingPackageBroadcasts { 812 // for each user id, a map of <package name -> components within that package> 813 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 814 815 public PendingPackageBroadcasts() { 816 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 817 } 818 819 public ArrayList<String> get(int userId, String packageName) { 820 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 821 return packages.get(packageName); 822 } 823 824 public void put(int userId, String packageName, ArrayList<String> components) { 825 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 826 packages.put(packageName, components); 827 } 828 829 public void remove(int userId, String packageName) { 830 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 831 if (packages != null) { 832 packages.remove(packageName); 833 } 834 } 835 836 public void remove(int userId) { 837 mUidMap.remove(userId); 838 } 839 840 public int userIdCount() { 841 return mUidMap.size(); 842 } 843 844 public int userIdAt(int n) { 845 return mUidMap.keyAt(n); 846 } 847 848 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 849 return mUidMap.get(userId); 850 } 851 852 public int size() { 853 // total number of pending broadcast entries across all userIds 854 int num = 0; 855 for (int i = 0; i< mUidMap.size(); i++) { 856 num += mUidMap.valueAt(i).size(); 857 } 858 return num; 859 } 860 861 public void clear() { 862 mUidMap.clear(); 863 } 864 865 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 866 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 867 if (map == null) { 868 map = new ArrayMap<String, ArrayList<String>>(); 869 mUidMap.put(userId, map); 870 } 871 return map; 872 } 873 } 874 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 875 876 // Service Connection to remote media container service to copy 877 // package uri's from external media onto secure containers 878 // or internal storage. 879 private IMediaContainerService mContainerService = null; 880 881 static final int SEND_PENDING_BROADCAST = 1; 882 static final int MCS_BOUND = 3; 883 static final int END_COPY = 4; 884 static final int INIT_COPY = 5; 885 static final int MCS_UNBIND = 6; 886 static final int START_CLEANING_PACKAGE = 7; 887 static final int FIND_INSTALL_LOC = 8; 888 static final int POST_INSTALL = 9; 889 static final int MCS_RECONNECT = 10; 890 static final int MCS_GIVE_UP = 11; 891 static final int UPDATED_MEDIA_STATUS = 12; 892 static final int WRITE_SETTINGS = 13; 893 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 894 static final int PACKAGE_VERIFIED = 15; 895 static final int CHECK_PENDING_VERIFICATION = 16; 896 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 897 static final int INTENT_FILTER_VERIFIED = 18; 898 899 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 900 901 // Delay time in millisecs 902 static final int BROADCAST_DELAY = 10 * 1000; 903 904 static UserManagerService sUserManager; 905 906 // Stores a list of users whose package restrictions file needs to be updated 907 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 908 909 final private DefaultContainerConnection mDefContainerConn = 910 new DefaultContainerConnection(); 911 class DefaultContainerConnection implements ServiceConnection { 912 public void onServiceConnected(ComponentName name, IBinder service) { 913 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 914 IMediaContainerService imcs = 915 IMediaContainerService.Stub.asInterface(service); 916 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 917 } 918 919 public void onServiceDisconnected(ComponentName name) { 920 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 921 } 922 } 923 924 // Recordkeeping of restore-after-install operations that are currently in flight 925 // between the Package Manager and the Backup Manager 926 class PostInstallData { 927 public InstallArgs args; 928 public PackageInstalledInfo res; 929 930 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 931 args = _a; 932 res = _r; 933 } 934 } 935 936 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 937 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 938 939 // XML tags for backup/restore of various bits of state 940 private static final String TAG_PREFERRED_BACKUP = "pa"; 941 private static final String TAG_DEFAULT_APPS = "da"; 942 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 943 944 final String mRequiredVerifierPackage; 945 final String mRequiredInstallerPackage; 946 947 private final PackageUsage mPackageUsage = new PackageUsage(); 948 949 private class PackageUsage { 950 private static final int WRITE_INTERVAL 951 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 952 953 private final Object mFileLock = new Object(); 954 private final AtomicLong mLastWritten = new AtomicLong(0); 955 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 956 957 private boolean mIsHistoricalPackageUsageAvailable = true; 958 959 boolean isHistoricalPackageUsageAvailable() { 960 return mIsHistoricalPackageUsageAvailable; 961 } 962 963 void write(boolean force) { 964 if (force) { 965 writeInternal(); 966 return; 967 } 968 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 969 && !DEBUG_DEXOPT) { 970 return; 971 } 972 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 973 new Thread("PackageUsage_DiskWriter") { 974 @Override 975 public void run() { 976 try { 977 writeInternal(); 978 } finally { 979 mBackgroundWriteRunning.set(false); 980 } 981 } 982 }.start(); 983 } 984 } 985 986 private void writeInternal() { 987 synchronized (mPackages) { 988 synchronized (mFileLock) { 989 AtomicFile file = getFile(); 990 FileOutputStream f = null; 991 try { 992 f = file.startWrite(); 993 BufferedOutputStream out = new BufferedOutputStream(f); 994 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 995 StringBuilder sb = new StringBuilder(); 996 for (PackageParser.Package pkg : mPackages.values()) { 997 if (pkg.mLastPackageUsageTimeInMills == 0) { 998 continue; 999 } 1000 sb.setLength(0); 1001 sb.append(pkg.packageName); 1002 sb.append(' '); 1003 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1004 sb.append('\n'); 1005 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1006 } 1007 out.flush(); 1008 file.finishWrite(f); 1009 } catch (IOException e) { 1010 if (f != null) { 1011 file.failWrite(f); 1012 } 1013 Log.e(TAG, "Failed to write package usage times", e); 1014 } 1015 } 1016 } 1017 mLastWritten.set(SystemClock.elapsedRealtime()); 1018 } 1019 1020 void readLP() { 1021 synchronized (mFileLock) { 1022 AtomicFile file = getFile(); 1023 BufferedInputStream in = null; 1024 try { 1025 in = new BufferedInputStream(file.openRead()); 1026 StringBuffer sb = new StringBuffer(); 1027 while (true) { 1028 String packageName = readToken(in, sb, ' '); 1029 if (packageName == null) { 1030 break; 1031 } 1032 String timeInMillisString = readToken(in, sb, '\n'); 1033 if (timeInMillisString == null) { 1034 throw new IOException("Failed to find last usage time for package " 1035 + packageName); 1036 } 1037 PackageParser.Package pkg = mPackages.get(packageName); 1038 if (pkg == null) { 1039 continue; 1040 } 1041 long timeInMillis; 1042 try { 1043 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1044 } catch (NumberFormatException e) { 1045 throw new IOException("Failed to parse " + timeInMillisString 1046 + " as a long.", e); 1047 } 1048 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1049 } 1050 } catch (FileNotFoundException expected) { 1051 mIsHistoricalPackageUsageAvailable = false; 1052 } catch (IOException e) { 1053 Log.w(TAG, "Failed to read package usage times", e); 1054 } finally { 1055 IoUtils.closeQuietly(in); 1056 } 1057 } 1058 mLastWritten.set(SystemClock.elapsedRealtime()); 1059 } 1060 1061 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1062 throws IOException { 1063 sb.setLength(0); 1064 while (true) { 1065 int ch = in.read(); 1066 if (ch == -1) { 1067 if (sb.length() == 0) { 1068 return null; 1069 } 1070 throw new IOException("Unexpected EOF"); 1071 } 1072 if (ch == endOfToken) { 1073 return sb.toString(); 1074 } 1075 sb.append((char)ch); 1076 } 1077 } 1078 1079 private AtomicFile getFile() { 1080 File dataDir = Environment.getDataDirectory(); 1081 File systemDir = new File(dataDir, "system"); 1082 File fname = new File(systemDir, "package-usage.list"); 1083 return new AtomicFile(fname); 1084 } 1085 } 1086 1087 class PackageHandler extends Handler { 1088 private boolean mBound = false; 1089 final ArrayList<HandlerParams> mPendingInstalls = 1090 new ArrayList<HandlerParams>(); 1091 1092 private boolean connectToService() { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1094 " DefaultContainerService"); 1095 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1096 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1097 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1098 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1099 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1100 mBound = true; 1101 return true; 1102 } 1103 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1104 return false; 1105 } 1106 1107 private void disconnectService() { 1108 mContainerService = null; 1109 mBound = false; 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1111 mContext.unbindService(mDefContainerConn); 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 } 1114 1115 PackageHandler(Looper looper) { 1116 super(looper); 1117 } 1118 1119 public void handleMessage(Message msg) { 1120 try { 1121 doHandleMessage(msg); 1122 } finally { 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1124 } 1125 } 1126 1127 void doHandleMessage(Message msg) { 1128 switch (msg.what) { 1129 case INIT_COPY: { 1130 HandlerParams params = (HandlerParams) msg.obj; 1131 int idx = mPendingInstalls.size(); 1132 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1133 // If a bind was already initiated we dont really 1134 // need to do anything. The pending install 1135 // will be processed later on. 1136 if (!mBound) { 1137 // If this is the only one pending we might 1138 // have to bind to the service again. 1139 if (!connectToService()) { 1140 Slog.e(TAG, "Failed to bind to media container service"); 1141 params.serviceError(); 1142 return; 1143 } else { 1144 // Once we bind to the service, the first 1145 // pending request will be processed. 1146 mPendingInstalls.add(idx, params); 1147 } 1148 } else { 1149 mPendingInstalls.add(idx, params); 1150 // Already bound to the service. Just make 1151 // sure we trigger off processing the first request. 1152 if (idx == 0) { 1153 mHandler.sendEmptyMessage(MCS_BOUND); 1154 } 1155 } 1156 break; 1157 } 1158 case MCS_BOUND: { 1159 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1160 if (msg.obj != null) { 1161 mContainerService = (IMediaContainerService) msg.obj; 1162 } 1163 if (mContainerService == null) { 1164 if (!mBound) { 1165 // Something seriously wrong since we are not bound and we are not 1166 // waiting for connection. Bail out. 1167 Slog.e(TAG, "Cannot bind to media container service"); 1168 for (HandlerParams params : mPendingInstalls) { 1169 // Indicate service bind error 1170 params.serviceError(); 1171 } 1172 mPendingInstalls.clear(); 1173 } else { 1174 Slog.w(TAG, "Waiting to connect to media container service"); 1175 } 1176 } else if (mPendingInstalls.size() > 0) { 1177 HandlerParams params = mPendingInstalls.get(0); 1178 if (params != null) { 1179 if (params.startCopy()) { 1180 // We are done... look for more work or to 1181 // go idle. 1182 if (DEBUG_SD_INSTALL) Log.i(TAG, 1183 "Checking for more work or unbind..."); 1184 // Delete pending install 1185 if (mPendingInstalls.size() > 0) { 1186 mPendingInstalls.remove(0); 1187 } 1188 if (mPendingInstalls.size() == 0) { 1189 if (mBound) { 1190 if (DEBUG_SD_INSTALL) Log.i(TAG, 1191 "Posting delayed MCS_UNBIND"); 1192 removeMessages(MCS_UNBIND); 1193 Message ubmsg = obtainMessage(MCS_UNBIND); 1194 // Unbind after a little delay, to avoid 1195 // continual thrashing. 1196 sendMessageDelayed(ubmsg, 10000); 1197 } 1198 } else { 1199 // There are more pending requests in queue. 1200 // Just post MCS_BOUND message to trigger processing 1201 // of next pending install. 1202 if (DEBUG_SD_INSTALL) Log.i(TAG, 1203 "Posting MCS_BOUND for next work"); 1204 mHandler.sendEmptyMessage(MCS_BOUND); 1205 } 1206 } 1207 } 1208 } else { 1209 // Should never happen ideally. 1210 Slog.w(TAG, "Empty queue"); 1211 } 1212 break; 1213 } 1214 case MCS_RECONNECT: { 1215 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1216 if (mPendingInstalls.size() > 0) { 1217 if (mBound) { 1218 disconnectService(); 1219 } 1220 if (!connectToService()) { 1221 Slog.e(TAG, "Failed to bind to media container service"); 1222 for (HandlerParams params : mPendingInstalls) { 1223 // Indicate service bind error 1224 params.serviceError(); 1225 } 1226 mPendingInstalls.clear(); 1227 } 1228 } 1229 break; 1230 } 1231 case MCS_UNBIND: { 1232 // If there is no actual work left, then time to unbind. 1233 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1234 1235 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1236 if (mBound) { 1237 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1238 1239 disconnectService(); 1240 } 1241 } else if (mPendingInstalls.size() > 0) { 1242 // There are more pending requests in queue. 1243 // Just post MCS_BOUND message to trigger processing 1244 // of next pending install. 1245 mHandler.sendEmptyMessage(MCS_BOUND); 1246 } 1247 1248 break; 1249 } 1250 case MCS_GIVE_UP: { 1251 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1252 mPendingInstalls.remove(0); 1253 break; 1254 } 1255 case SEND_PENDING_BROADCAST: { 1256 String packages[]; 1257 ArrayList<String> components[]; 1258 int size = 0; 1259 int uids[]; 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1261 synchronized (mPackages) { 1262 if (mPendingBroadcasts == null) { 1263 return; 1264 } 1265 size = mPendingBroadcasts.size(); 1266 if (size <= 0) { 1267 // Nothing to be done. Just return 1268 return; 1269 } 1270 packages = new String[size]; 1271 components = new ArrayList[size]; 1272 uids = new int[size]; 1273 int i = 0; // filling out the above arrays 1274 1275 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1276 int packageUserId = mPendingBroadcasts.userIdAt(n); 1277 Iterator<Map.Entry<String, ArrayList<String>>> it 1278 = mPendingBroadcasts.packagesForUserId(packageUserId) 1279 .entrySet().iterator(); 1280 while (it.hasNext() && i < size) { 1281 Map.Entry<String, ArrayList<String>> ent = it.next(); 1282 packages[i] = ent.getKey(); 1283 components[i] = ent.getValue(); 1284 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1285 uids[i] = (ps != null) 1286 ? UserHandle.getUid(packageUserId, ps.appId) 1287 : -1; 1288 i++; 1289 } 1290 } 1291 size = i; 1292 mPendingBroadcasts.clear(); 1293 } 1294 // Send broadcasts 1295 for (int i = 0; i < size; i++) { 1296 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1297 } 1298 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1299 break; 1300 } 1301 case START_CLEANING_PACKAGE: { 1302 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1303 final String packageName = (String)msg.obj; 1304 final int userId = msg.arg1; 1305 final boolean andCode = msg.arg2 != 0; 1306 synchronized (mPackages) { 1307 if (userId == UserHandle.USER_ALL) { 1308 int[] users = sUserManager.getUserIds(); 1309 for (int user : users) { 1310 mSettings.addPackageToCleanLPw( 1311 new PackageCleanItem(user, packageName, andCode)); 1312 } 1313 } else { 1314 mSettings.addPackageToCleanLPw( 1315 new PackageCleanItem(userId, packageName, andCode)); 1316 } 1317 } 1318 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1319 startCleaningPackages(); 1320 } break; 1321 case POST_INSTALL: { 1322 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1323 PostInstallData data = mRunningInstalls.get(msg.arg1); 1324 mRunningInstalls.delete(msg.arg1); 1325 boolean deleteOld = false; 1326 1327 if (data != null) { 1328 InstallArgs args = data.args; 1329 PackageInstalledInfo res = data.res; 1330 1331 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1332 final String packageName = res.pkg.applicationInfo.packageName; 1333 res.removedInfo.sendBroadcast(false, true, false); 1334 Bundle extras = new Bundle(1); 1335 extras.putInt(Intent.EXTRA_UID, res.uid); 1336 1337 // Now that we successfully installed the package, grant runtime 1338 // permissions if requested before broadcasting the install. 1339 if ((args.installFlags 1340 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1341 grantRequestedRuntimePermissions(res.pkg, 1342 args.user.getIdentifier()); 1343 } 1344 1345 // Determine the set of users who are adding this 1346 // package for the first time vs. those who are seeing 1347 // an update. 1348 int[] firstUsers; 1349 int[] updateUsers = new int[0]; 1350 if (res.origUsers == null || res.origUsers.length == 0) { 1351 firstUsers = res.newUsers; 1352 } else { 1353 firstUsers = new int[0]; 1354 for (int i=0; i<res.newUsers.length; i++) { 1355 int user = res.newUsers[i]; 1356 boolean isNew = true; 1357 for (int j=0; j<res.origUsers.length; j++) { 1358 if (res.origUsers[j] == user) { 1359 isNew = false; 1360 break; 1361 } 1362 } 1363 if (isNew) { 1364 int[] newFirst = new int[firstUsers.length+1]; 1365 System.arraycopy(firstUsers, 0, newFirst, 0, 1366 firstUsers.length); 1367 newFirst[firstUsers.length] = user; 1368 firstUsers = newFirst; 1369 } else { 1370 int[] newUpdate = new int[updateUsers.length+1]; 1371 System.arraycopy(updateUsers, 0, newUpdate, 0, 1372 updateUsers.length); 1373 newUpdate[updateUsers.length] = user; 1374 updateUsers = newUpdate; 1375 } 1376 } 1377 } 1378 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1379 packageName, extras, null, null, firstUsers); 1380 final boolean update = res.removedInfo.removedPackage != null; 1381 if (update) { 1382 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1383 } 1384 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1385 packageName, extras, null, null, updateUsers); 1386 if (update) { 1387 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1388 packageName, extras, null, null, updateUsers); 1389 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1390 null, null, packageName, null, updateUsers); 1391 1392 // treat asec-hosted packages like removable media on upgrade 1393 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1394 if (DEBUG_INSTALL) { 1395 Slog.i(TAG, "upgrading pkg " + res.pkg 1396 + " is ASEC-hosted -> AVAILABLE"); 1397 } 1398 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1399 ArrayList<String> pkgList = new ArrayList<String>(1); 1400 pkgList.add(packageName); 1401 sendResourcesChangedBroadcast(true, true, 1402 pkgList,uidArray, null); 1403 } 1404 } 1405 if (res.removedInfo.args != null) { 1406 // Remove the replaced package's older resources safely now 1407 deleteOld = true; 1408 } 1409 1410 // If this app is a browser and it's newly-installed for some 1411 // users, clear any default-browser state in those users 1412 if (firstUsers.length > 0) { 1413 // the app's nature doesn't depend on the user, so we can just 1414 // check its browser nature in any user and generalize. 1415 if (packageIsBrowser(packageName, firstUsers[0])) { 1416 synchronized (mPackages) { 1417 for (int userId : firstUsers) { 1418 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1419 } 1420 } 1421 } 1422 } 1423 // Log current value of "unknown sources" setting 1424 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1425 getUnknownSourcesSettings()); 1426 } 1427 // Force a gc to clear up things 1428 Runtime.getRuntime().gc(); 1429 // We delete after a gc for applications on sdcard. 1430 if (deleteOld) { 1431 synchronized (mInstallLock) { 1432 res.removedInfo.args.doPostDeleteLI(true); 1433 } 1434 } 1435 if (args.observer != null) { 1436 try { 1437 Bundle extras = extrasForInstallResult(res); 1438 args.observer.onPackageInstalled(res.name, res.returnCode, 1439 res.returnMsg, extras); 1440 } catch (RemoteException e) { 1441 Slog.i(TAG, "Observer no longer exists."); 1442 } 1443 } 1444 } else { 1445 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1446 } 1447 } break; 1448 case UPDATED_MEDIA_STATUS: { 1449 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1450 boolean reportStatus = msg.arg1 == 1; 1451 boolean doGc = msg.arg2 == 1; 1452 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1453 if (doGc) { 1454 // Force a gc to clear up stale containers. 1455 Runtime.getRuntime().gc(); 1456 } 1457 if (msg.obj != null) { 1458 @SuppressWarnings("unchecked") 1459 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1460 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1461 // Unload containers 1462 unloadAllContainers(args); 1463 } 1464 if (reportStatus) { 1465 try { 1466 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1467 PackageHelper.getMountService().finishMediaUpdate(); 1468 } catch (RemoteException e) { 1469 Log.e(TAG, "MountService not running?"); 1470 } 1471 } 1472 } break; 1473 case WRITE_SETTINGS: { 1474 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1475 synchronized (mPackages) { 1476 removeMessages(WRITE_SETTINGS); 1477 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1478 mSettings.writeLPr(); 1479 mDirtyUsers.clear(); 1480 } 1481 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1482 } break; 1483 case WRITE_PACKAGE_RESTRICTIONS: { 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1485 synchronized (mPackages) { 1486 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1487 for (int userId : mDirtyUsers) { 1488 mSettings.writePackageRestrictionsLPr(userId); 1489 } 1490 mDirtyUsers.clear(); 1491 } 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1493 } break; 1494 case CHECK_PENDING_VERIFICATION: { 1495 final int verificationId = msg.arg1; 1496 final PackageVerificationState state = mPendingVerification.get(verificationId); 1497 1498 if ((state != null) && !state.timeoutExtended()) { 1499 final InstallArgs args = state.getInstallArgs(); 1500 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1501 1502 Slog.i(TAG, "Verification timed out for " + originUri); 1503 mPendingVerification.remove(verificationId); 1504 1505 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1506 1507 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1508 Slog.i(TAG, "Continuing with installation of " + originUri); 1509 state.setVerifierResponse(Binder.getCallingUid(), 1510 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1511 broadcastPackageVerified(verificationId, originUri, 1512 PackageManager.VERIFICATION_ALLOW, 1513 state.getInstallArgs().getUser()); 1514 try { 1515 ret = args.copyApk(mContainerService, true); 1516 } catch (RemoteException e) { 1517 Slog.e(TAG, "Could not contact the ContainerService"); 1518 } 1519 } else { 1520 broadcastPackageVerified(verificationId, originUri, 1521 PackageManager.VERIFICATION_REJECT, 1522 state.getInstallArgs().getUser()); 1523 } 1524 1525 processPendingInstall(args, ret); 1526 mHandler.sendEmptyMessage(MCS_UNBIND); 1527 } 1528 break; 1529 } 1530 case PACKAGE_VERIFIED: { 1531 final int verificationId = msg.arg1; 1532 1533 final PackageVerificationState state = mPendingVerification.get(verificationId); 1534 if (state == null) { 1535 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1536 break; 1537 } 1538 1539 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1540 1541 state.setVerifierResponse(response.callerUid, response.code); 1542 1543 if (state.isVerificationComplete()) { 1544 mPendingVerification.remove(verificationId); 1545 1546 final InstallArgs args = state.getInstallArgs(); 1547 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1548 1549 int ret; 1550 if (state.isInstallAllowed()) { 1551 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1552 broadcastPackageVerified(verificationId, originUri, 1553 response.code, state.getInstallArgs().getUser()); 1554 try { 1555 ret = args.copyApk(mContainerService, true); 1556 } catch (RemoteException e) { 1557 Slog.e(TAG, "Could not contact the ContainerService"); 1558 } 1559 } else { 1560 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1561 } 1562 1563 processPendingInstall(args, ret); 1564 1565 mHandler.sendEmptyMessage(MCS_UNBIND); 1566 } 1567 1568 break; 1569 } 1570 case START_INTENT_FILTER_VERIFICATIONS: { 1571 IFVerificationParams params = (IFVerificationParams) msg.obj; 1572 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1573 params.replacing, params.pkg); 1574 break; 1575 } 1576 case INTENT_FILTER_VERIFIED: { 1577 final int verificationId = msg.arg1; 1578 1579 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1580 verificationId); 1581 if (state == null) { 1582 Slog.w(TAG, "Invalid IntentFilter verification token " 1583 + verificationId + " received"); 1584 break; 1585 } 1586 1587 final int userId = state.getUserId(); 1588 1589 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1590 "Processing IntentFilter verification with token:" 1591 + verificationId + " and userId:" + userId); 1592 1593 final IntentFilterVerificationResponse response = 1594 (IntentFilterVerificationResponse) msg.obj; 1595 1596 state.setVerifierResponse(response.callerUid, response.code); 1597 1598 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1599 "IntentFilter verification with token:" + verificationId 1600 + " and userId:" + userId 1601 + " is settings verifier response with response code:" 1602 + response.code); 1603 1604 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1605 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1606 + response.getFailedDomainsString()); 1607 } 1608 1609 if (state.isVerificationComplete()) { 1610 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1611 } else { 1612 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1613 "IntentFilter verification with token:" + verificationId 1614 + " was not said to be complete"); 1615 } 1616 1617 break; 1618 } 1619 } 1620 } 1621 } 1622 1623 private StorageEventListener mStorageListener = new StorageEventListener() { 1624 @Override 1625 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1626 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1627 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1628 final String volumeUuid = vol.getFsUuid(); 1629 1630 // Clean up any users or apps that were removed or recreated 1631 // while this volume was missing 1632 reconcileUsers(volumeUuid); 1633 reconcileApps(volumeUuid); 1634 1635 // Clean up any install sessions that expired or were 1636 // cancelled while this volume was missing 1637 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1638 1639 loadPrivatePackages(vol); 1640 1641 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1642 unloadPrivatePackages(vol); 1643 } 1644 } 1645 1646 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1647 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1648 updateExternalMediaStatus(true, false); 1649 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1650 updateExternalMediaStatus(false, false); 1651 } 1652 } 1653 } 1654 1655 @Override 1656 public void onVolumeForgotten(String fsUuid) { 1657 // Remove any apps installed on the forgotten volume 1658 synchronized (mPackages) { 1659 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1660 for (PackageSetting ps : packages) { 1661 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1662 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1663 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1664 } 1665 1666 mSettings.writeLPr(); 1667 } 1668 } 1669 }; 1670 1671 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1672 if (userId >= UserHandle.USER_OWNER) { 1673 grantRequestedRuntimePermissionsForUser(pkg, userId); 1674 } else if (userId == UserHandle.USER_ALL) { 1675 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1676 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1677 } 1678 } 1679 1680 // We could have touched GID membership, so flush out packages.list 1681 synchronized (mPackages) { 1682 mSettings.writePackageListLPr(); 1683 } 1684 } 1685 1686 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1687 SettingBase sb = (SettingBase) pkg.mExtras; 1688 if (sb == null) { 1689 return; 1690 } 1691 1692 PermissionsState permissionsState = sb.getPermissionsState(); 1693 1694 for (String permission : pkg.requestedPermissions) { 1695 BasePermission bp = mSettings.mPermissions.get(permission); 1696 if (bp != null && bp.isRuntime()) { 1697 permissionsState.grantRuntimePermission(bp, userId); 1698 } 1699 } 1700 } 1701 1702 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1703 Bundle extras = null; 1704 switch (res.returnCode) { 1705 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1706 extras = new Bundle(); 1707 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1708 res.origPermission); 1709 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1710 res.origPackage); 1711 break; 1712 } 1713 case PackageManager.INSTALL_SUCCEEDED: { 1714 extras = new Bundle(); 1715 extras.putBoolean(Intent.EXTRA_REPLACING, 1716 res.removedInfo != null && res.removedInfo.removedPackage != null); 1717 break; 1718 } 1719 } 1720 return extras; 1721 } 1722 1723 void scheduleWriteSettingsLocked() { 1724 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1725 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1726 } 1727 } 1728 1729 void scheduleWritePackageRestrictionsLocked(int userId) { 1730 if (!sUserManager.exists(userId)) return; 1731 mDirtyUsers.add(userId); 1732 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1733 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1734 } 1735 } 1736 1737 public static PackageManagerService main(Context context, Installer installer, 1738 boolean factoryTest, boolean onlyCore) { 1739 PackageManagerService m = new PackageManagerService(context, installer, 1740 factoryTest, onlyCore); 1741 ServiceManager.addService("package", m); 1742 return m; 1743 } 1744 1745 static String[] splitString(String str, char sep) { 1746 int count = 1; 1747 int i = 0; 1748 while ((i=str.indexOf(sep, i)) >= 0) { 1749 count++; 1750 i++; 1751 } 1752 1753 String[] res = new String[count]; 1754 i=0; 1755 count = 0; 1756 int lastI=0; 1757 while ((i=str.indexOf(sep, i)) >= 0) { 1758 res[count] = str.substring(lastI, i); 1759 count++; 1760 i++; 1761 lastI = i; 1762 } 1763 res[count] = str.substring(lastI, str.length()); 1764 return res; 1765 } 1766 1767 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1768 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1769 Context.DISPLAY_SERVICE); 1770 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1771 } 1772 1773 public PackageManagerService(Context context, Installer installer, 1774 boolean factoryTest, boolean onlyCore) { 1775 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1776 SystemClock.uptimeMillis()); 1777 1778 if (mSdkVersion <= 0) { 1779 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1780 } 1781 1782 mContext = context; 1783 mFactoryTest = factoryTest; 1784 mOnlyCore = onlyCore; 1785 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1786 mMetrics = new DisplayMetrics(); 1787 mSettings = new Settings(mPackages); 1788 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1789 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1790 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1791 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1792 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1793 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1794 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1795 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1796 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1797 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1798 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1799 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1800 1801 // TODO: add a property to control this? 1802 long dexOptLRUThresholdInMinutes; 1803 if (mLazyDexOpt) { 1804 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1805 } else { 1806 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1807 } 1808 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1809 1810 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1811 if (separateProcesses != null && separateProcesses.length() > 0) { 1812 if ("*".equals(separateProcesses)) { 1813 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1814 mSeparateProcesses = null; 1815 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1816 } else { 1817 mDefParseFlags = 0; 1818 mSeparateProcesses = separateProcesses.split(","); 1819 Slog.w(TAG, "Running with debug.separate_processes: " 1820 + separateProcesses); 1821 } 1822 } else { 1823 mDefParseFlags = 0; 1824 mSeparateProcesses = null; 1825 } 1826 1827 mInstaller = installer; 1828 mPackageDexOptimizer = new PackageDexOptimizer(this); 1829 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1830 1831 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1832 FgThread.get().getLooper()); 1833 1834 getDefaultDisplayMetrics(context, mMetrics); 1835 1836 SystemConfig systemConfig = SystemConfig.getInstance(); 1837 mGlobalGids = systemConfig.getGlobalGids(); 1838 mSystemPermissions = systemConfig.getSystemPermissions(); 1839 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1840 1841 synchronized (mInstallLock) { 1842 // writer 1843 synchronized (mPackages) { 1844 mHandlerThread = new ServiceThread(TAG, 1845 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1846 mHandlerThread.start(); 1847 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1848 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1849 1850 File dataDir = Environment.getDataDirectory(); 1851 mAppDataDir = new File(dataDir, "data"); 1852 mAppInstallDir = new File(dataDir, "app"); 1853 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1854 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1855 mUserAppDataDir = new File(dataDir, "user"); 1856 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1857 1858 sUserManager = new UserManagerService(context, this, 1859 mInstallLock, mPackages); 1860 1861 // Propagate permission configuration in to package manager. 1862 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1863 = systemConfig.getPermissions(); 1864 for (int i=0; i<permConfig.size(); i++) { 1865 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1866 BasePermission bp = mSettings.mPermissions.get(perm.name); 1867 if (bp == null) { 1868 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1869 mSettings.mPermissions.put(perm.name, bp); 1870 } 1871 if (perm.gids != null) { 1872 bp.setGids(perm.gids, perm.perUser); 1873 } 1874 } 1875 1876 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1877 for (int i=0; i<libConfig.size(); i++) { 1878 mSharedLibraries.put(libConfig.keyAt(i), 1879 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1880 } 1881 1882 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1883 1884 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1885 mSdkVersion, mOnlyCore); 1886 1887 String customResolverActivity = Resources.getSystem().getString( 1888 R.string.config_customResolverActivity); 1889 if (TextUtils.isEmpty(customResolverActivity)) { 1890 customResolverActivity = null; 1891 } else { 1892 mCustomResolverComponentName = ComponentName.unflattenFromString( 1893 customResolverActivity); 1894 } 1895 1896 long startTime = SystemClock.uptimeMillis(); 1897 1898 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1899 startTime); 1900 1901 // Set flag to monitor and not change apk file paths when 1902 // scanning install directories. 1903 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1904 1905 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1906 1907 /** 1908 * Add everything in the in the boot class path to the 1909 * list of process files because dexopt will have been run 1910 * if necessary during zygote startup. 1911 */ 1912 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1913 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1914 1915 if (bootClassPath != null) { 1916 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1917 for (String element : bootClassPathElements) { 1918 alreadyDexOpted.add(element); 1919 } 1920 } else { 1921 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1922 } 1923 1924 if (systemServerClassPath != null) { 1925 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1926 for (String element : systemServerClassPathElements) { 1927 alreadyDexOpted.add(element); 1928 } 1929 } else { 1930 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1931 } 1932 1933 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1934 final String[] dexCodeInstructionSets = 1935 getDexCodeInstructionSets( 1936 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1937 1938 /** 1939 * Ensure all external libraries have had dexopt run on them. 1940 */ 1941 if (mSharedLibraries.size() > 0) { 1942 // NOTE: For now, we're compiling these system "shared libraries" 1943 // (and framework jars) into all available architectures. It's possible 1944 // to compile them only when we come across an app that uses them (there's 1945 // already logic for that in scanPackageLI) but that adds some complexity. 1946 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1947 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1948 final String lib = libEntry.path; 1949 if (lib == null) { 1950 continue; 1951 } 1952 1953 try { 1954 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1955 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1956 alreadyDexOpted.add(lib); 1957 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1958 } 1959 } catch (FileNotFoundException e) { 1960 Slog.w(TAG, "Library not found: " + lib); 1961 } catch (IOException e) { 1962 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1963 + e.getMessage()); 1964 } 1965 } 1966 } 1967 } 1968 1969 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1970 1971 // Gross hack for now: we know this file doesn't contain any 1972 // code, so don't dexopt it to avoid the resulting log spew. 1973 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1974 1975 // Gross hack for now: we know this file is only part of 1976 // the boot class path for art, so don't dexopt it to 1977 // avoid the resulting log spew. 1978 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1979 1980 /** 1981 * There are a number of commands implemented in Java, which 1982 * we currently need to do the dexopt on so that they can be 1983 * run from a non-root shell. 1984 */ 1985 String[] frameworkFiles = frameworkDir.list(); 1986 if (frameworkFiles != null) { 1987 // TODO: We could compile these only for the most preferred ABI. We should 1988 // first double check that the dex files for these commands are not referenced 1989 // by other system apps. 1990 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1991 for (int i=0; i<frameworkFiles.length; i++) { 1992 File libPath = new File(frameworkDir, frameworkFiles[i]); 1993 String path = libPath.getPath(); 1994 // Skip the file if we already did it. 1995 if (alreadyDexOpted.contains(path)) { 1996 continue; 1997 } 1998 // Skip the file if it is not a type we want to dexopt. 1999 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2000 continue; 2001 } 2002 try { 2003 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2004 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2005 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2006 } 2007 } catch (FileNotFoundException e) { 2008 Slog.w(TAG, "Jar not found: " + path); 2009 } catch (IOException e) { 2010 Slog.w(TAG, "Exception reading jar: " + path, e); 2011 } 2012 } 2013 } 2014 } 2015 2016 // Collect vendor overlay packages. 2017 // (Do this before scanning any apps.) 2018 // For security and version matching reason, only consider 2019 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2020 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2021 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2022 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2023 2024 // Find base frameworks (resource packages without code). 2025 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2026 | PackageParser.PARSE_IS_SYSTEM_DIR 2027 | PackageParser.PARSE_IS_PRIVILEGED, 2028 scanFlags | SCAN_NO_DEX, 0); 2029 2030 // Collected privileged system packages. 2031 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2032 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2033 | PackageParser.PARSE_IS_SYSTEM_DIR 2034 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2035 2036 // Collect ordinary system packages. 2037 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2038 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2039 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2040 2041 // Collect all vendor packages. 2042 File vendorAppDir = new File("/vendor/app"); 2043 try { 2044 vendorAppDir = vendorAppDir.getCanonicalFile(); 2045 } catch (IOException e) { 2046 // failed to look up canonical path, continue with original one 2047 } 2048 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2049 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2050 2051 // Collect all OEM packages. 2052 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2053 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2054 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2055 2056 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2057 mInstaller.moveFiles(); 2058 2059 // Prune any system packages that no longer exist. 2060 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2061 if (!mOnlyCore) { 2062 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2063 while (psit.hasNext()) { 2064 PackageSetting ps = psit.next(); 2065 2066 /* 2067 * If this is not a system app, it can't be a 2068 * disable system app. 2069 */ 2070 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2071 continue; 2072 } 2073 2074 /* 2075 * If the package is scanned, it's not erased. 2076 */ 2077 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2078 if (scannedPkg != null) { 2079 /* 2080 * If the system app is both scanned and in the 2081 * disabled packages list, then it must have been 2082 * added via OTA. Remove it from the currently 2083 * scanned package so the previously user-installed 2084 * application can be scanned. 2085 */ 2086 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2087 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2088 + ps.name + "; removing system app. Last known codePath=" 2089 + ps.codePathString + ", installStatus=" + ps.installStatus 2090 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2091 + scannedPkg.mVersionCode); 2092 removePackageLI(ps, true); 2093 mExpectingBetter.put(ps.name, ps.codePath); 2094 } 2095 2096 continue; 2097 } 2098 2099 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2100 psit.remove(); 2101 logCriticalInfo(Log.WARN, "System package " + ps.name 2102 + " no longer exists; wiping its data"); 2103 removeDataDirsLI(null, ps.name); 2104 } else { 2105 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2106 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2107 possiblyDeletedUpdatedSystemApps.add(ps.name); 2108 } 2109 } 2110 } 2111 } 2112 2113 //look for any incomplete package installations 2114 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2115 //clean up list 2116 for(int i = 0; i < deletePkgsList.size(); i++) { 2117 //clean up here 2118 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2119 } 2120 //delete tmp files 2121 deleteTempPackageFiles(); 2122 2123 // Remove any shared userIDs that have no associated packages 2124 mSettings.pruneSharedUsersLPw(); 2125 2126 if (!mOnlyCore) { 2127 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2128 SystemClock.uptimeMillis()); 2129 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2130 2131 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2132 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2133 2134 /** 2135 * Remove disable package settings for any updated system 2136 * apps that were removed via an OTA. If they're not a 2137 * previously-updated app, remove them completely. 2138 * Otherwise, just revoke their system-level permissions. 2139 */ 2140 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2141 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2142 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2143 2144 String msg; 2145 if (deletedPkg == null) { 2146 msg = "Updated system package " + deletedAppName 2147 + " no longer exists; wiping its data"; 2148 removeDataDirsLI(null, deletedAppName); 2149 } else { 2150 msg = "Updated system app + " + deletedAppName 2151 + " no longer present; removing system privileges for " 2152 + deletedAppName; 2153 2154 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2155 2156 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2157 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2158 } 2159 logCriticalInfo(Log.WARN, msg); 2160 } 2161 2162 /** 2163 * Make sure all system apps that we expected to appear on 2164 * the userdata partition actually showed up. If they never 2165 * appeared, crawl back and revive the system version. 2166 */ 2167 for (int i = 0; i < mExpectingBetter.size(); i++) { 2168 final String packageName = mExpectingBetter.keyAt(i); 2169 if (!mPackages.containsKey(packageName)) { 2170 final File scanFile = mExpectingBetter.valueAt(i); 2171 2172 logCriticalInfo(Log.WARN, "Expected better " + packageName 2173 + " but never showed up; reverting to system"); 2174 2175 final int reparseFlags; 2176 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2177 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2178 | PackageParser.PARSE_IS_SYSTEM_DIR 2179 | PackageParser.PARSE_IS_PRIVILEGED; 2180 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2181 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2182 | PackageParser.PARSE_IS_SYSTEM_DIR; 2183 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2184 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2185 | PackageParser.PARSE_IS_SYSTEM_DIR; 2186 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2187 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2188 | PackageParser.PARSE_IS_SYSTEM_DIR; 2189 } else { 2190 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2191 continue; 2192 } 2193 2194 mSettings.enableSystemPackageLPw(packageName); 2195 2196 try { 2197 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2198 } catch (PackageManagerException e) { 2199 Slog.e(TAG, "Failed to parse original system package: " 2200 + e.getMessage()); 2201 } 2202 } 2203 } 2204 } 2205 mExpectingBetter.clear(); 2206 2207 // Now that we know all of the shared libraries, update all clients to have 2208 // the correct library paths. 2209 updateAllSharedLibrariesLPw(); 2210 2211 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2212 // NOTE: We ignore potential failures here during a system scan (like 2213 // the rest of the commands above) because there's precious little we 2214 // can do about it. A settings error is reported, though. 2215 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2216 false /* force dexopt */, false /* defer dexopt */); 2217 } 2218 2219 // Now that we know all the packages we are keeping, 2220 // read and update their last usage times. 2221 mPackageUsage.readLP(); 2222 2223 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2224 SystemClock.uptimeMillis()); 2225 Slog.i(TAG, "Time to scan packages: " 2226 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2227 + " seconds"); 2228 2229 // If the platform SDK has changed since the last time we booted, 2230 // we need to re-grant app permission to catch any new ones that 2231 // appear. This is really a hack, and means that apps can in some 2232 // cases get permissions that the user didn't initially explicitly 2233 // allow... it would be nice to have some better way to handle 2234 // this situation. 2235 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2236 != mSdkVersion; 2237 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2238 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2239 + "; regranting permissions for internal storage"); 2240 mSettings.mInternalSdkPlatform = mSdkVersion; 2241 2242 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2243 | (regrantPermissions 2244 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2245 : 0)); 2246 2247 // If this is the first boot, and it is a normal boot, then 2248 // we need to initialize the default preferred apps. 2249 if (!mRestoredSettings && !onlyCore) { 2250 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2251 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2252 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2253 } 2254 2255 // If this is first boot after an OTA, and a normal boot, then 2256 // we need to clear code cache directories. 2257 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2258 if (mIsUpgrade && !onlyCore) { 2259 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2260 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2261 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2262 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2263 } 2264 mSettings.mFingerprint = Build.FINGERPRINT; 2265 } 2266 2267 checkDefaultBrowser(); 2268 2269 // All the changes are done during package scanning. 2270 mSettings.updateInternalDatabaseVersion(); 2271 2272 // can downgrade to reader 2273 mSettings.writeLPr(); 2274 2275 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2276 SystemClock.uptimeMillis()); 2277 2278 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2279 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2280 2281 mInstallerService = new PackageInstallerService(context, this); 2282 2283 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2284 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2285 mIntentFilterVerifierComponent); 2286 2287 } // synchronized (mPackages) 2288 } // synchronized (mInstallLock) 2289 2290 // Now after opening every single application zip, make sure they 2291 // are all flushed. Not really needed, but keeps things nice and 2292 // tidy. 2293 Runtime.getRuntime().gc(); 2294 2295 // Expose private service for system components to use. 2296 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2297 } 2298 2299 @Override 2300 public boolean isFirstBoot() { 2301 return !mRestoredSettings; 2302 } 2303 2304 @Override 2305 public boolean isOnlyCoreApps() { 2306 return mOnlyCore; 2307 } 2308 2309 @Override 2310 public boolean isUpgrade() { 2311 return mIsUpgrade; 2312 } 2313 2314 private String getRequiredVerifierLPr() { 2315 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2316 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2317 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2318 2319 String requiredVerifier = null; 2320 2321 final int N = receivers.size(); 2322 for (int i = 0; i < N; i++) { 2323 final ResolveInfo info = receivers.get(i); 2324 2325 if (info.activityInfo == null) { 2326 continue; 2327 } 2328 2329 final String packageName = info.activityInfo.packageName; 2330 2331 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2332 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2333 continue; 2334 } 2335 2336 if (requiredVerifier != null) { 2337 throw new RuntimeException("There can be only one required verifier"); 2338 } 2339 2340 requiredVerifier = packageName; 2341 } 2342 2343 return requiredVerifier; 2344 } 2345 2346 private String getRequiredInstallerLPr() { 2347 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2348 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2349 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2350 2351 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2352 PACKAGE_MIME_TYPE, 0, 0); 2353 2354 String requiredInstaller = null; 2355 2356 final int N = installers.size(); 2357 for (int i = 0; i < N; i++) { 2358 final ResolveInfo info = installers.get(i); 2359 final String packageName = info.activityInfo.packageName; 2360 2361 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2362 continue; 2363 } 2364 2365 if (requiredInstaller != null) { 2366 throw new RuntimeException("There must be one required installer"); 2367 } 2368 2369 requiredInstaller = packageName; 2370 } 2371 2372 if (requiredInstaller == null) { 2373 throw new RuntimeException("There must be one required installer"); 2374 } 2375 2376 return requiredInstaller; 2377 } 2378 2379 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2380 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2381 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2382 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2383 2384 ComponentName verifierComponentName = null; 2385 2386 int priority = -1000; 2387 final int N = receivers.size(); 2388 for (int i = 0; i < N; i++) { 2389 final ResolveInfo info = receivers.get(i); 2390 2391 if (info.activityInfo == null) { 2392 continue; 2393 } 2394 2395 final String packageName = info.activityInfo.packageName; 2396 2397 final PackageSetting ps = mSettings.mPackages.get(packageName); 2398 if (ps == null) { 2399 continue; 2400 } 2401 2402 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2403 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2404 continue; 2405 } 2406 2407 // Select the IntentFilterVerifier with the highest priority 2408 if (priority < info.priority) { 2409 priority = info.priority; 2410 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2411 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2412 + verifierComponentName + " with priority: " + info.priority); 2413 } 2414 } 2415 2416 return verifierComponentName; 2417 } 2418 2419 private void primeDomainVerificationsLPw(int userId) { 2420 if (DEBUG_DOMAIN_VERIFICATION) { 2421 Slog.d(TAG, "Priming domain verifications in user " + userId); 2422 } 2423 2424 SystemConfig systemConfig = SystemConfig.getInstance(); 2425 ArraySet<String> packages = systemConfig.getLinkedApps(); 2426 ArraySet<String> domains = new ArraySet<String>(); 2427 2428 for (String packageName : packages) { 2429 PackageParser.Package pkg = mPackages.get(packageName); 2430 if (pkg != null) { 2431 if (!pkg.isSystemApp()) { 2432 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2433 continue; 2434 } 2435 2436 domains.clear(); 2437 for (PackageParser.Activity a : pkg.activities) { 2438 for (ActivityIntentInfo filter : a.intents) { 2439 if (hasValidDomains(filter)) { 2440 domains.addAll(filter.getHostsList()); 2441 } 2442 } 2443 } 2444 2445 if (domains.size() > 0) { 2446 if (DEBUG_DOMAIN_VERIFICATION) { 2447 Slog.v(TAG, " + " + packageName); 2448 } 2449 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2450 // state w.r.t. the formal app-linkage "no verification attempted" state; 2451 // and then 'always' in the per-user state actually used for intent resolution. 2452 final IntentFilterVerificationInfo ivi; 2453 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2454 new ArrayList<String>(domains)); 2455 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2456 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2457 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2458 } else { 2459 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2460 + "' does not handle web links"); 2461 } 2462 } else { 2463 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2464 } 2465 } 2466 2467 scheduleWritePackageRestrictionsLocked(userId); 2468 scheduleWriteSettingsLocked(); 2469 } 2470 2471 private void applyFactoryDefaultBrowserLPw(int userId) { 2472 // The default browser app's package name is stored in a string resource, 2473 // with a product-specific overlay used for vendor customization. 2474 String browserPkg = mContext.getResources().getString( 2475 com.android.internal.R.string.default_browser); 2476 if (!TextUtils.isEmpty(browserPkg)) { 2477 // non-empty string => required to be a known package 2478 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2479 if (ps == null) { 2480 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2481 browserPkg = null; 2482 } else { 2483 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2484 } 2485 } 2486 2487 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2488 // default. If there's more than one, just leave everything alone. 2489 if (browserPkg == null) { 2490 calculateDefaultBrowserLPw(userId); 2491 } 2492 } 2493 2494 private void calculateDefaultBrowserLPw(int userId) { 2495 List<String> allBrowsers = resolveAllBrowserApps(userId); 2496 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2497 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2498 } 2499 2500 private List<String> resolveAllBrowserApps(int userId) { 2501 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2502 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2503 PackageManager.MATCH_ALL, userId); 2504 2505 final int count = list.size(); 2506 List<String> result = new ArrayList<String>(count); 2507 for (int i=0; i<count; i++) { 2508 ResolveInfo info = list.get(i); 2509 if (info.activityInfo == null 2510 || !info.handleAllWebDataURI 2511 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2512 || result.contains(info.activityInfo.packageName)) { 2513 continue; 2514 } 2515 result.add(info.activityInfo.packageName); 2516 } 2517 2518 return result; 2519 } 2520 2521 private boolean packageIsBrowser(String packageName, int userId) { 2522 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2523 PackageManager.MATCH_ALL, userId); 2524 final int N = list.size(); 2525 for (int i = 0; i < N; i++) { 2526 ResolveInfo info = list.get(i); 2527 if (packageName.equals(info.activityInfo.packageName)) { 2528 return true; 2529 } 2530 } 2531 return false; 2532 } 2533 2534 private void checkDefaultBrowser() { 2535 final int myUserId = UserHandle.myUserId(); 2536 final String packageName = getDefaultBrowserPackageName(myUserId); 2537 if (packageName != null) { 2538 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2539 if (info == null) { 2540 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2541 synchronized (mPackages) { 2542 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2543 } 2544 } 2545 } 2546 } 2547 2548 @Override 2549 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2550 throws RemoteException { 2551 try { 2552 return super.onTransact(code, data, reply, flags); 2553 } catch (RuntimeException e) { 2554 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2555 Slog.wtf(TAG, "Package Manager Crash", e); 2556 } 2557 throw e; 2558 } 2559 } 2560 2561 void cleanupInstallFailedPackage(PackageSetting ps) { 2562 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2563 2564 removeDataDirsLI(ps.volumeUuid, ps.name); 2565 if (ps.codePath != null) { 2566 if (ps.codePath.isDirectory()) { 2567 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2568 } else { 2569 ps.codePath.delete(); 2570 } 2571 } 2572 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2573 if (ps.resourcePath.isDirectory()) { 2574 FileUtils.deleteContents(ps.resourcePath); 2575 } 2576 ps.resourcePath.delete(); 2577 } 2578 mSettings.removePackageLPw(ps.name); 2579 } 2580 2581 static int[] appendInts(int[] cur, int[] add) { 2582 if (add == null) return cur; 2583 if (cur == null) return add; 2584 final int N = add.length; 2585 for (int i=0; i<N; i++) { 2586 cur = appendInt(cur, add[i]); 2587 } 2588 return cur; 2589 } 2590 2591 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2592 if (!sUserManager.exists(userId)) return null; 2593 final PackageSetting ps = (PackageSetting) p.mExtras; 2594 if (ps == null) { 2595 return null; 2596 } 2597 2598 final PermissionsState permissionsState = ps.getPermissionsState(); 2599 2600 final int[] gids = permissionsState.computeGids(userId); 2601 final Set<String> permissions = permissionsState.getPermissions(userId); 2602 final PackageUserState state = ps.readUserState(userId); 2603 2604 return PackageParser.generatePackageInfo(p, gids, flags, 2605 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2606 } 2607 2608 @Override 2609 public boolean isPackageFrozen(String packageName) { 2610 synchronized (mPackages) { 2611 final PackageSetting ps = mSettings.mPackages.get(packageName); 2612 if (ps != null) { 2613 return ps.frozen; 2614 } 2615 } 2616 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2617 return true; 2618 } 2619 2620 @Override 2621 public boolean isPackageAvailable(String packageName, int userId) { 2622 if (!sUserManager.exists(userId)) return false; 2623 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2624 synchronized (mPackages) { 2625 PackageParser.Package p = mPackages.get(packageName); 2626 if (p != null) { 2627 final PackageSetting ps = (PackageSetting) p.mExtras; 2628 if (ps != null) { 2629 final PackageUserState state = ps.readUserState(userId); 2630 if (state != null) { 2631 return PackageParser.isAvailable(state); 2632 } 2633 } 2634 } 2635 } 2636 return false; 2637 } 2638 2639 @Override 2640 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2641 if (!sUserManager.exists(userId)) return null; 2642 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2643 // reader 2644 synchronized (mPackages) { 2645 PackageParser.Package p = mPackages.get(packageName); 2646 if (DEBUG_PACKAGE_INFO) 2647 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2648 if (p != null) { 2649 return generatePackageInfo(p, flags, userId); 2650 } 2651 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2652 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2653 } 2654 } 2655 return null; 2656 } 2657 2658 @Override 2659 public String[] currentToCanonicalPackageNames(String[] names) { 2660 String[] out = new String[names.length]; 2661 // reader 2662 synchronized (mPackages) { 2663 for (int i=names.length-1; i>=0; i--) { 2664 PackageSetting ps = mSettings.mPackages.get(names[i]); 2665 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2666 } 2667 } 2668 return out; 2669 } 2670 2671 @Override 2672 public String[] canonicalToCurrentPackageNames(String[] names) { 2673 String[] out = new String[names.length]; 2674 // reader 2675 synchronized (mPackages) { 2676 for (int i=names.length-1; i>=0; i--) { 2677 String cur = mSettings.mRenamedPackages.get(names[i]); 2678 out[i] = cur != null ? cur : names[i]; 2679 } 2680 } 2681 return out; 2682 } 2683 2684 @Override 2685 public int getPackageUid(String packageName, int userId) { 2686 if (!sUserManager.exists(userId)) return -1; 2687 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2688 2689 // reader 2690 synchronized (mPackages) { 2691 PackageParser.Package p = mPackages.get(packageName); 2692 if(p != null) { 2693 return UserHandle.getUid(userId, p.applicationInfo.uid); 2694 } 2695 PackageSetting ps = mSettings.mPackages.get(packageName); 2696 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2697 return -1; 2698 } 2699 p = ps.pkg; 2700 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2701 } 2702 } 2703 2704 @Override 2705 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2706 if (!sUserManager.exists(userId)) { 2707 return null; 2708 } 2709 2710 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2711 "getPackageGids"); 2712 2713 // reader 2714 synchronized (mPackages) { 2715 PackageParser.Package p = mPackages.get(packageName); 2716 if (DEBUG_PACKAGE_INFO) { 2717 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2718 } 2719 if (p != null) { 2720 PackageSetting ps = (PackageSetting) p.mExtras; 2721 return ps.getPermissionsState().computeGids(userId); 2722 } 2723 } 2724 2725 return null; 2726 } 2727 2728 @Override 2729 public int getMountExternalMode(int uid) { 2730 if (Process.isIsolated(uid)) { 2731 return Zygote.MOUNT_EXTERNAL_NONE; 2732 } else { 2733 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 2734 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2735 } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2736 return Zygote.MOUNT_EXTERNAL_WRITE; 2737 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2738 return Zygote.MOUNT_EXTERNAL_READ; 2739 } else { 2740 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2741 } 2742 } 2743 } 2744 2745 static PermissionInfo generatePermissionInfo( 2746 BasePermission bp, int flags) { 2747 if (bp.perm != null) { 2748 return PackageParser.generatePermissionInfo(bp.perm, flags); 2749 } 2750 PermissionInfo pi = new PermissionInfo(); 2751 pi.name = bp.name; 2752 pi.packageName = bp.sourcePackage; 2753 pi.nonLocalizedLabel = bp.name; 2754 pi.protectionLevel = bp.protectionLevel; 2755 return pi; 2756 } 2757 2758 @Override 2759 public PermissionInfo getPermissionInfo(String name, int flags) { 2760 // reader 2761 synchronized (mPackages) { 2762 final BasePermission p = mSettings.mPermissions.get(name); 2763 if (p != null) { 2764 return generatePermissionInfo(p, flags); 2765 } 2766 return null; 2767 } 2768 } 2769 2770 @Override 2771 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2772 // reader 2773 synchronized (mPackages) { 2774 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2775 for (BasePermission p : mSettings.mPermissions.values()) { 2776 if (group == null) { 2777 if (p.perm == null || p.perm.info.group == null) { 2778 out.add(generatePermissionInfo(p, flags)); 2779 } 2780 } else { 2781 if (p.perm != null && group.equals(p.perm.info.group)) { 2782 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2783 } 2784 } 2785 } 2786 2787 if (out.size() > 0) { 2788 return out; 2789 } 2790 return mPermissionGroups.containsKey(group) ? out : null; 2791 } 2792 } 2793 2794 @Override 2795 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2796 // reader 2797 synchronized (mPackages) { 2798 return PackageParser.generatePermissionGroupInfo( 2799 mPermissionGroups.get(name), flags); 2800 } 2801 } 2802 2803 @Override 2804 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2805 // reader 2806 synchronized (mPackages) { 2807 final int N = mPermissionGroups.size(); 2808 ArrayList<PermissionGroupInfo> out 2809 = new ArrayList<PermissionGroupInfo>(N); 2810 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2811 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2812 } 2813 return out; 2814 } 2815 } 2816 2817 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2818 int userId) { 2819 if (!sUserManager.exists(userId)) return null; 2820 PackageSetting ps = mSettings.mPackages.get(packageName); 2821 if (ps != null) { 2822 if (ps.pkg == null) { 2823 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2824 flags, userId); 2825 if (pInfo != null) { 2826 return pInfo.applicationInfo; 2827 } 2828 return null; 2829 } 2830 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2831 ps.readUserState(userId), userId); 2832 } 2833 return null; 2834 } 2835 2836 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2837 int userId) { 2838 if (!sUserManager.exists(userId)) return null; 2839 PackageSetting ps = mSettings.mPackages.get(packageName); 2840 if (ps != null) { 2841 PackageParser.Package pkg = ps.pkg; 2842 if (pkg == null) { 2843 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2844 return null; 2845 } 2846 // Only data remains, so we aren't worried about code paths 2847 pkg = new PackageParser.Package(packageName); 2848 pkg.applicationInfo.packageName = packageName; 2849 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2850 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2851 pkg.applicationInfo.dataDir = Environment 2852 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2853 .getAbsolutePath(); 2854 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2855 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2856 } 2857 return generatePackageInfo(pkg, flags, userId); 2858 } 2859 return null; 2860 } 2861 2862 @Override 2863 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2864 if (!sUserManager.exists(userId)) return null; 2865 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2866 // writer 2867 synchronized (mPackages) { 2868 PackageParser.Package p = mPackages.get(packageName); 2869 if (DEBUG_PACKAGE_INFO) Log.v( 2870 TAG, "getApplicationInfo " + packageName 2871 + ": " + p); 2872 if (p != null) { 2873 PackageSetting ps = mSettings.mPackages.get(packageName); 2874 if (ps == null) return null; 2875 // Note: isEnabledLP() does not apply here - always return info 2876 return PackageParser.generateApplicationInfo( 2877 p, flags, ps.readUserState(userId), userId); 2878 } 2879 if ("android".equals(packageName)||"system".equals(packageName)) { 2880 return mAndroidApplication; 2881 } 2882 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2883 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2884 } 2885 } 2886 return null; 2887 } 2888 2889 @Override 2890 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2891 final IPackageDataObserver observer) { 2892 mContext.enforceCallingOrSelfPermission( 2893 android.Manifest.permission.CLEAR_APP_CACHE, null); 2894 // Queue up an async operation since clearing cache may take a little while. 2895 mHandler.post(new Runnable() { 2896 public void run() { 2897 mHandler.removeCallbacks(this); 2898 int retCode = -1; 2899 synchronized (mInstallLock) { 2900 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2901 if (retCode < 0) { 2902 Slog.w(TAG, "Couldn't clear application caches"); 2903 } 2904 } 2905 if (observer != null) { 2906 try { 2907 observer.onRemoveCompleted(null, (retCode >= 0)); 2908 } catch (RemoteException e) { 2909 Slog.w(TAG, "RemoveException when invoking call back"); 2910 } 2911 } 2912 } 2913 }); 2914 } 2915 2916 @Override 2917 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2918 final IntentSender pi) { 2919 mContext.enforceCallingOrSelfPermission( 2920 android.Manifest.permission.CLEAR_APP_CACHE, null); 2921 // Queue up an async operation since clearing cache may take a little while. 2922 mHandler.post(new Runnable() { 2923 public void run() { 2924 mHandler.removeCallbacks(this); 2925 int retCode = -1; 2926 synchronized (mInstallLock) { 2927 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2928 if (retCode < 0) { 2929 Slog.w(TAG, "Couldn't clear application caches"); 2930 } 2931 } 2932 if(pi != null) { 2933 try { 2934 // Callback via pending intent 2935 int code = (retCode >= 0) ? 1 : 0; 2936 pi.sendIntent(null, code, null, 2937 null, null); 2938 } catch (SendIntentException e1) { 2939 Slog.i(TAG, "Failed to send pending intent"); 2940 } 2941 } 2942 } 2943 }); 2944 } 2945 2946 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2947 synchronized (mInstallLock) { 2948 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2949 throw new IOException("Failed to free enough space"); 2950 } 2951 } 2952 } 2953 2954 @Override 2955 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2956 if (!sUserManager.exists(userId)) return null; 2957 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2958 synchronized (mPackages) { 2959 PackageParser.Activity a = mActivities.mActivities.get(component); 2960 2961 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2962 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2963 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2964 if (ps == null) return null; 2965 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2966 userId); 2967 } 2968 if (mResolveComponentName.equals(component)) { 2969 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2970 new PackageUserState(), userId); 2971 } 2972 } 2973 return null; 2974 } 2975 2976 @Override 2977 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2978 String resolvedType) { 2979 synchronized (mPackages) { 2980 PackageParser.Activity a = mActivities.mActivities.get(component); 2981 if (a == null) { 2982 return false; 2983 } 2984 for (int i=0; i<a.intents.size(); i++) { 2985 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2986 intent.getData(), intent.getCategories(), TAG) >= 0) { 2987 return true; 2988 } 2989 } 2990 return false; 2991 } 2992 } 2993 2994 @Override 2995 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2996 if (!sUserManager.exists(userId)) return null; 2997 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2998 synchronized (mPackages) { 2999 PackageParser.Activity a = mReceivers.mActivities.get(component); 3000 if (DEBUG_PACKAGE_INFO) Log.v( 3001 TAG, "getReceiverInfo " + component + ": " + a); 3002 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3003 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3004 if (ps == null) return null; 3005 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3006 userId); 3007 } 3008 } 3009 return null; 3010 } 3011 3012 @Override 3013 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3014 if (!sUserManager.exists(userId)) return null; 3015 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3016 synchronized (mPackages) { 3017 PackageParser.Service s = mServices.mServices.get(component); 3018 if (DEBUG_PACKAGE_INFO) Log.v( 3019 TAG, "getServiceInfo " + component + ": " + s); 3020 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3021 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3022 if (ps == null) return null; 3023 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3024 userId); 3025 } 3026 } 3027 return null; 3028 } 3029 3030 @Override 3031 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3032 if (!sUserManager.exists(userId)) return null; 3033 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3034 synchronized (mPackages) { 3035 PackageParser.Provider p = mProviders.mProviders.get(component); 3036 if (DEBUG_PACKAGE_INFO) Log.v( 3037 TAG, "getProviderInfo " + component + ": " + p); 3038 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3039 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3040 if (ps == null) return null; 3041 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3042 userId); 3043 } 3044 } 3045 return null; 3046 } 3047 3048 @Override 3049 public String[] getSystemSharedLibraryNames() { 3050 Set<String> libSet; 3051 synchronized (mPackages) { 3052 libSet = mSharedLibraries.keySet(); 3053 int size = libSet.size(); 3054 if (size > 0) { 3055 String[] libs = new String[size]; 3056 libSet.toArray(libs); 3057 return libs; 3058 } 3059 } 3060 return null; 3061 } 3062 3063 /** 3064 * @hide 3065 */ 3066 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3067 synchronized (mPackages) { 3068 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3069 if (lib != null && lib.apk != null) { 3070 return mPackages.get(lib.apk); 3071 } 3072 } 3073 return null; 3074 } 3075 3076 @Override 3077 public FeatureInfo[] getSystemAvailableFeatures() { 3078 Collection<FeatureInfo> featSet; 3079 synchronized (mPackages) { 3080 featSet = mAvailableFeatures.values(); 3081 int size = featSet.size(); 3082 if (size > 0) { 3083 FeatureInfo[] features = new FeatureInfo[size+1]; 3084 featSet.toArray(features); 3085 FeatureInfo fi = new FeatureInfo(); 3086 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3087 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3088 features[size] = fi; 3089 return features; 3090 } 3091 } 3092 return null; 3093 } 3094 3095 @Override 3096 public boolean hasSystemFeature(String name) { 3097 synchronized (mPackages) { 3098 return mAvailableFeatures.containsKey(name); 3099 } 3100 } 3101 3102 private void checkValidCaller(int uid, int userId) { 3103 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3104 return; 3105 3106 throw new SecurityException("Caller uid=" + uid 3107 + " is not privileged to communicate with user=" + userId); 3108 } 3109 3110 @Override 3111 public int checkPermission(String permName, String pkgName, int userId) { 3112 if (!sUserManager.exists(userId)) { 3113 return PackageManager.PERMISSION_DENIED; 3114 } 3115 3116 synchronized (mPackages) { 3117 final PackageParser.Package p = mPackages.get(pkgName); 3118 if (p != null && p.mExtras != null) { 3119 final PackageSetting ps = (PackageSetting) p.mExtras; 3120 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3121 return PackageManager.PERMISSION_GRANTED; 3122 } 3123 } 3124 } 3125 3126 return PackageManager.PERMISSION_DENIED; 3127 } 3128 3129 @Override 3130 public int checkUidPermission(String permName, int uid) { 3131 final int userId = UserHandle.getUserId(uid); 3132 3133 if (!sUserManager.exists(userId)) { 3134 return PackageManager.PERMISSION_DENIED; 3135 } 3136 3137 synchronized (mPackages) { 3138 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3139 if (obj != null) { 3140 final SettingBase ps = (SettingBase) obj; 3141 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3142 return PackageManager.PERMISSION_GRANTED; 3143 } 3144 } else { 3145 ArraySet<String> perms = mSystemPermissions.get(uid); 3146 if (perms != null && perms.contains(permName)) { 3147 return PackageManager.PERMISSION_GRANTED; 3148 } 3149 } 3150 } 3151 3152 return PackageManager.PERMISSION_DENIED; 3153 } 3154 3155 /** 3156 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3157 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3158 * @param checkShell TODO(yamasani): 3159 * @param message the message to log on security exception 3160 */ 3161 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3162 boolean checkShell, String message) { 3163 if (userId < 0) { 3164 throw new IllegalArgumentException("Invalid userId " + userId); 3165 } 3166 if (checkShell) { 3167 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3168 } 3169 if (userId == UserHandle.getUserId(callingUid)) return; 3170 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3171 if (requireFullPermission) { 3172 mContext.enforceCallingOrSelfPermission( 3173 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3174 } else { 3175 try { 3176 mContext.enforceCallingOrSelfPermission( 3177 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3178 } catch (SecurityException se) { 3179 mContext.enforceCallingOrSelfPermission( 3180 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3181 } 3182 } 3183 } 3184 } 3185 3186 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3187 if (callingUid == Process.SHELL_UID) { 3188 if (userHandle >= 0 3189 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3190 throw new SecurityException("Shell does not have permission to access user " 3191 + userHandle); 3192 } else if (userHandle < 0) { 3193 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3194 + Debug.getCallers(3)); 3195 } 3196 } 3197 } 3198 3199 private BasePermission findPermissionTreeLP(String permName) { 3200 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3201 if (permName.startsWith(bp.name) && 3202 permName.length() > bp.name.length() && 3203 permName.charAt(bp.name.length()) == '.') { 3204 return bp; 3205 } 3206 } 3207 return null; 3208 } 3209 3210 private BasePermission checkPermissionTreeLP(String permName) { 3211 if (permName != null) { 3212 BasePermission bp = findPermissionTreeLP(permName); 3213 if (bp != null) { 3214 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3215 return bp; 3216 } 3217 throw new SecurityException("Calling uid " 3218 + Binder.getCallingUid() 3219 + " is not allowed to add to permission tree " 3220 + bp.name + " owned by uid " + bp.uid); 3221 } 3222 } 3223 throw new SecurityException("No permission tree found for " + permName); 3224 } 3225 3226 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3227 if (s1 == null) { 3228 return s2 == null; 3229 } 3230 if (s2 == null) { 3231 return false; 3232 } 3233 if (s1.getClass() != s2.getClass()) { 3234 return false; 3235 } 3236 return s1.equals(s2); 3237 } 3238 3239 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3240 if (pi1.icon != pi2.icon) return false; 3241 if (pi1.logo != pi2.logo) return false; 3242 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3243 if (!compareStrings(pi1.name, pi2.name)) return false; 3244 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3245 // We'll take care of setting this one. 3246 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3247 // These are not currently stored in settings. 3248 //if (!compareStrings(pi1.group, pi2.group)) return false; 3249 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3250 //if (pi1.labelRes != pi2.labelRes) return false; 3251 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3252 return true; 3253 } 3254 3255 int permissionInfoFootprint(PermissionInfo info) { 3256 int size = info.name.length(); 3257 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3258 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3259 return size; 3260 } 3261 3262 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3263 int size = 0; 3264 for (BasePermission perm : mSettings.mPermissions.values()) { 3265 if (perm.uid == tree.uid) { 3266 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3267 } 3268 } 3269 return size; 3270 } 3271 3272 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3273 // We calculate the max size of permissions defined by this uid and throw 3274 // if that plus the size of 'info' would exceed our stated maximum. 3275 if (tree.uid != Process.SYSTEM_UID) { 3276 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3277 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3278 throw new SecurityException("Permission tree size cap exceeded"); 3279 } 3280 } 3281 } 3282 3283 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3284 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3285 throw new SecurityException("Label must be specified in permission"); 3286 } 3287 BasePermission tree = checkPermissionTreeLP(info.name); 3288 BasePermission bp = mSettings.mPermissions.get(info.name); 3289 boolean added = bp == null; 3290 boolean changed = true; 3291 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3292 if (added) { 3293 enforcePermissionCapLocked(info, tree); 3294 bp = new BasePermission(info.name, tree.sourcePackage, 3295 BasePermission.TYPE_DYNAMIC); 3296 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3297 throw new SecurityException( 3298 "Not allowed to modify non-dynamic permission " 3299 + info.name); 3300 } else { 3301 if (bp.protectionLevel == fixedLevel 3302 && bp.perm.owner.equals(tree.perm.owner) 3303 && bp.uid == tree.uid 3304 && comparePermissionInfos(bp.perm.info, info)) { 3305 changed = false; 3306 } 3307 } 3308 bp.protectionLevel = fixedLevel; 3309 info = new PermissionInfo(info); 3310 info.protectionLevel = fixedLevel; 3311 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3312 bp.perm.info.packageName = tree.perm.info.packageName; 3313 bp.uid = tree.uid; 3314 if (added) { 3315 mSettings.mPermissions.put(info.name, bp); 3316 } 3317 if (changed) { 3318 if (!async) { 3319 mSettings.writeLPr(); 3320 } else { 3321 scheduleWriteSettingsLocked(); 3322 } 3323 } 3324 return added; 3325 } 3326 3327 @Override 3328 public boolean addPermission(PermissionInfo info) { 3329 synchronized (mPackages) { 3330 return addPermissionLocked(info, false); 3331 } 3332 } 3333 3334 @Override 3335 public boolean addPermissionAsync(PermissionInfo info) { 3336 synchronized (mPackages) { 3337 return addPermissionLocked(info, true); 3338 } 3339 } 3340 3341 @Override 3342 public void removePermission(String name) { 3343 synchronized (mPackages) { 3344 checkPermissionTreeLP(name); 3345 BasePermission bp = mSettings.mPermissions.get(name); 3346 if (bp != null) { 3347 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3348 throw new SecurityException( 3349 "Not allowed to modify non-dynamic permission " 3350 + name); 3351 } 3352 mSettings.mPermissions.remove(name); 3353 mSettings.writeLPr(); 3354 } 3355 } 3356 } 3357 3358 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3359 BasePermission bp) { 3360 int index = pkg.requestedPermissions.indexOf(bp.name); 3361 if (index == -1) { 3362 throw new SecurityException("Package " + pkg.packageName 3363 + " has not requested permission " + bp.name); 3364 } 3365 if (!bp.isRuntime()) { 3366 throw new SecurityException("Permission " + bp.name 3367 + " is not a changeable permission type"); 3368 } 3369 } 3370 3371 @Override 3372 public void grantRuntimePermission(String packageName, String name, final int userId) { 3373 if (!sUserManager.exists(userId)) { 3374 Log.e(TAG, "No such user:" + userId); 3375 return; 3376 } 3377 3378 mContext.enforceCallingOrSelfPermission( 3379 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3380 "grantRuntimePermission"); 3381 3382 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3383 "grantRuntimePermission"); 3384 3385 final int uid; 3386 final SettingBase sb; 3387 3388 synchronized (mPackages) { 3389 final PackageParser.Package pkg = mPackages.get(packageName); 3390 if (pkg == null) { 3391 throw new IllegalArgumentException("Unknown package: " + packageName); 3392 } 3393 3394 final BasePermission bp = mSettings.mPermissions.get(name); 3395 if (bp == null) { 3396 throw new IllegalArgumentException("Unknown permission: " + name); 3397 } 3398 3399 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3400 3401 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3402 sb = (SettingBase) pkg.mExtras; 3403 if (sb == null) { 3404 throw new IllegalArgumentException("Unknown package: " + packageName); 3405 } 3406 3407 final PermissionsState permissionsState = sb.getPermissionsState(); 3408 3409 final int flags = permissionsState.getPermissionFlags(name, userId); 3410 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3411 throw new SecurityException("Cannot grant system fixed permission: " 3412 + name + " for package: " + packageName); 3413 } 3414 3415 final int result = permissionsState.grantRuntimePermission(bp, userId); 3416 switch (result) { 3417 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3418 return; 3419 } 3420 3421 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3422 mHandler.post(new Runnable() { 3423 @Override 3424 public void run() { 3425 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3426 } 3427 }); 3428 } break; 3429 } 3430 3431 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3432 3433 // Not critical if that is lost - app has to request again. 3434 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3435 } 3436 3437 if (READ_EXTERNAL_STORAGE.equals(name) 3438 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3439 final long token = Binder.clearCallingIdentity(); 3440 try { 3441 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3442 storage.remountUid(uid); 3443 } finally { 3444 Binder.restoreCallingIdentity(token); 3445 } 3446 } 3447 } 3448 3449 @Override 3450 public void revokeRuntimePermission(String packageName, String name, int userId) { 3451 if (!sUserManager.exists(userId)) { 3452 Log.e(TAG, "No such user:" + userId); 3453 return; 3454 } 3455 3456 mContext.enforceCallingOrSelfPermission( 3457 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3458 "revokeRuntimePermission"); 3459 3460 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3461 "revokeRuntimePermission"); 3462 3463 final SettingBase sb; 3464 3465 synchronized (mPackages) { 3466 final PackageParser.Package pkg = mPackages.get(packageName); 3467 if (pkg == null) { 3468 throw new IllegalArgumentException("Unknown package: " + packageName); 3469 } 3470 3471 final BasePermission bp = mSettings.mPermissions.get(name); 3472 if (bp == null) { 3473 throw new IllegalArgumentException("Unknown permission: " + name); 3474 } 3475 3476 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3477 3478 sb = (SettingBase) pkg.mExtras; 3479 if (sb == null) { 3480 throw new IllegalArgumentException("Unknown package: " + packageName); 3481 } 3482 3483 final PermissionsState permissionsState = sb.getPermissionsState(); 3484 3485 final int flags = permissionsState.getPermissionFlags(name, userId); 3486 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3487 throw new SecurityException("Cannot revoke system fixed permission: " 3488 + name + " for package: " + packageName); 3489 } 3490 3491 if (permissionsState.revokeRuntimePermission(bp, userId) == 3492 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3493 return; 3494 } 3495 3496 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3497 3498 // Critical, after this call app should never have the permission. 3499 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3500 } 3501 3502 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3503 } 3504 3505 @Override 3506 public void resetRuntimePermissions() { 3507 mContext.enforceCallingOrSelfPermission( 3508 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3509 "revokeRuntimePermission"); 3510 3511 int callingUid = Binder.getCallingUid(); 3512 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3513 mContext.enforceCallingOrSelfPermission( 3514 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3515 "resetRuntimePermissions"); 3516 } 3517 3518 final int[] userIds; 3519 3520 synchronized (mPackages) { 3521 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3522 final int userCount = UserManagerService.getInstance().getUserIds().length; 3523 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3524 } 3525 3526 for (int userId : userIds) { 3527 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3528 } 3529 } 3530 3531 @Override 3532 public int getPermissionFlags(String name, String packageName, int userId) { 3533 if (!sUserManager.exists(userId)) { 3534 return 0; 3535 } 3536 3537 mContext.enforceCallingOrSelfPermission( 3538 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3539 "getPermissionFlags"); 3540 3541 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3542 "getPermissionFlags"); 3543 3544 synchronized (mPackages) { 3545 final PackageParser.Package pkg = mPackages.get(packageName); 3546 if (pkg == null) { 3547 throw new IllegalArgumentException("Unknown package: " + packageName); 3548 } 3549 3550 final BasePermission bp = mSettings.mPermissions.get(name); 3551 if (bp == null) { 3552 throw new IllegalArgumentException("Unknown permission: " + name); 3553 } 3554 3555 SettingBase sb = (SettingBase) pkg.mExtras; 3556 if (sb == null) { 3557 throw new IllegalArgumentException("Unknown package: " + packageName); 3558 } 3559 3560 PermissionsState permissionsState = sb.getPermissionsState(); 3561 return permissionsState.getPermissionFlags(name, userId); 3562 } 3563 } 3564 3565 @Override 3566 public void updatePermissionFlags(String name, String packageName, int flagMask, 3567 int flagValues, int userId) { 3568 if (!sUserManager.exists(userId)) { 3569 return; 3570 } 3571 3572 mContext.enforceCallingOrSelfPermission( 3573 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3574 "updatePermissionFlags"); 3575 3576 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3577 "updatePermissionFlags"); 3578 3579 // Only the system can change system fixed flags. 3580 if (getCallingUid() != Process.SYSTEM_UID) { 3581 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3582 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3583 } 3584 3585 synchronized (mPackages) { 3586 final PackageParser.Package pkg = mPackages.get(packageName); 3587 if (pkg == null) { 3588 throw new IllegalArgumentException("Unknown package: " + packageName); 3589 } 3590 3591 final BasePermission bp = mSettings.mPermissions.get(name); 3592 if (bp == null) { 3593 throw new IllegalArgumentException("Unknown permission: " + name); 3594 } 3595 3596 SettingBase sb = (SettingBase) pkg.mExtras; 3597 if (sb == null) { 3598 throw new IllegalArgumentException("Unknown package: " + packageName); 3599 } 3600 3601 PermissionsState permissionsState = sb.getPermissionsState(); 3602 3603 // Only the package manager can change flags for system component permissions. 3604 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3605 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3606 return; 3607 } 3608 3609 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3610 3611 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3612 // Install and runtime permissions are stored in different places, 3613 // so figure out what permission changed and persist the change. 3614 if (permissionsState.getInstallPermissionState(name) != null) { 3615 scheduleWriteSettingsLocked(); 3616 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3617 || hadState) { 3618 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3619 } 3620 } 3621 } 3622 } 3623 3624 /** 3625 * Update the permission flags for all packages and runtime permissions of a user in order 3626 * to allow device or profile owner to remove POLICY_FIXED. 3627 */ 3628 @Override 3629 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3630 if (!sUserManager.exists(userId)) { 3631 return; 3632 } 3633 3634 mContext.enforceCallingOrSelfPermission( 3635 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3636 "updatePermissionFlagsForAllApps"); 3637 3638 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3639 "updatePermissionFlagsForAllApps"); 3640 3641 // Only the system can change system fixed flags. 3642 if (getCallingUid() != Process.SYSTEM_UID) { 3643 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3644 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3645 } 3646 3647 synchronized (mPackages) { 3648 boolean changed = false; 3649 final int packageCount = mPackages.size(); 3650 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3651 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3652 SettingBase sb = (SettingBase) pkg.mExtras; 3653 if (sb == null) { 3654 continue; 3655 } 3656 PermissionsState permissionsState = sb.getPermissionsState(); 3657 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3658 userId, flagMask, flagValues); 3659 } 3660 if (changed) { 3661 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3662 } 3663 } 3664 } 3665 3666 @Override 3667 public boolean shouldShowRequestPermissionRationale(String permissionName, 3668 String packageName, int userId) { 3669 if (UserHandle.getCallingUserId() != userId) { 3670 mContext.enforceCallingPermission( 3671 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3672 "canShowRequestPermissionRationale for user " + userId); 3673 } 3674 3675 final int uid = getPackageUid(packageName, userId); 3676 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3677 return false; 3678 } 3679 3680 if (checkPermission(permissionName, packageName, userId) 3681 == PackageManager.PERMISSION_GRANTED) { 3682 return false; 3683 } 3684 3685 final int flags; 3686 3687 final long identity = Binder.clearCallingIdentity(); 3688 try { 3689 flags = getPermissionFlags(permissionName, 3690 packageName, userId); 3691 } finally { 3692 Binder.restoreCallingIdentity(identity); 3693 } 3694 3695 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3696 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3697 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3698 3699 if ((flags & fixedFlags) != 0) { 3700 return false; 3701 } 3702 3703 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3704 } 3705 3706 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3707 BasePermission bp = mSettings.mPermissions.get(permission); 3708 if (bp == null) { 3709 throw new SecurityException("Missing " + permission + " permission"); 3710 } 3711 3712 SettingBase sb = (SettingBase) pkg.mExtras; 3713 PermissionsState permissionsState = sb.getPermissionsState(); 3714 3715 if (permissionsState.grantInstallPermission(bp) != 3716 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3717 scheduleWriteSettingsLocked(); 3718 } 3719 } 3720 3721 @Override 3722 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3723 mContext.enforceCallingOrSelfPermission( 3724 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3725 "addOnPermissionsChangeListener"); 3726 3727 synchronized (mPackages) { 3728 mOnPermissionChangeListeners.addListenerLocked(listener); 3729 } 3730 } 3731 3732 @Override 3733 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3734 synchronized (mPackages) { 3735 mOnPermissionChangeListeners.removeListenerLocked(listener); 3736 } 3737 } 3738 3739 @Override 3740 public boolean isProtectedBroadcast(String actionName) { 3741 synchronized (mPackages) { 3742 return mProtectedBroadcasts.contains(actionName); 3743 } 3744 } 3745 3746 @Override 3747 public int checkSignatures(String pkg1, String pkg2) { 3748 synchronized (mPackages) { 3749 final PackageParser.Package p1 = mPackages.get(pkg1); 3750 final PackageParser.Package p2 = mPackages.get(pkg2); 3751 if (p1 == null || p1.mExtras == null 3752 || p2 == null || p2.mExtras == null) { 3753 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3754 } 3755 return compareSignatures(p1.mSignatures, p2.mSignatures); 3756 } 3757 } 3758 3759 @Override 3760 public int checkUidSignatures(int uid1, int uid2) { 3761 // Map to base uids. 3762 uid1 = UserHandle.getAppId(uid1); 3763 uid2 = UserHandle.getAppId(uid2); 3764 // reader 3765 synchronized (mPackages) { 3766 Signature[] s1; 3767 Signature[] s2; 3768 Object obj = mSettings.getUserIdLPr(uid1); 3769 if (obj != null) { 3770 if (obj instanceof SharedUserSetting) { 3771 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3772 } else if (obj instanceof PackageSetting) { 3773 s1 = ((PackageSetting)obj).signatures.mSignatures; 3774 } else { 3775 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3776 } 3777 } else { 3778 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3779 } 3780 obj = mSettings.getUserIdLPr(uid2); 3781 if (obj != null) { 3782 if (obj instanceof SharedUserSetting) { 3783 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3784 } else if (obj instanceof PackageSetting) { 3785 s2 = ((PackageSetting)obj).signatures.mSignatures; 3786 } else { 3787 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3788 } 3789 } else { 3790 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3791 } 3792 return compareSignatures(s1, s2); 3793 } 3794 } 3795 3796 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3797 final long identity = Binder.clearCallingIdentity(); 3798 try { 3799 if (sb instanceof SharedUserSetting) { 3800 SharedUserSetting sus = (SharedUserSetting) sb; 3801 final int packageCount = sus.packages.size(); 3802 for (int i = 0; i < packageCount; i++) { 3803 PackageSetting susPs = sus.packages.valueAt(i); 3804 if (userId == UserHandle.USER_ALL) { 3805 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3806 } else { 3807 final int uid = UserHandle.getUid(userId, susPs.appId); 3808 killUid(uid, reason); 3809 } 3810 } 3811 } else if (sb instanceof PackageSetting) { 3812 PackageSetting ps = (PackageSetting) sb; 3813 if (userId == UserHandle.USER_ALL) { 3814 killApplication(ps.pkg.packageName, ps.appId, reason); 3815 } else { 3816 final int uid = UserHandle.getUid(userId, ps.appId); 3817 killUid(uid, reason); 3818 } 3819 } 3820 } finally { 3821 Binder.restoreCallingIdentity(identity); 3822 } 3823 } 3824 3825 private static void killUid(int uid, String reason) { 3826 IActivityManager am = ActivityManagerNative.getDefault(); 3827 if (am != null) { 3828 try { 3829 am.killUid(uid, reason); 3830 } catch (RemoteException e) { 3831 /* ignore - same process */ 3832 } 3833 } 3834 } 3835 3836 /** 3837 * Compares two sets of signatures. Returns: 3838 * <br /> 3839 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3840 * <br /> 3841 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3842 * <br /> 3843 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3844 * <br /> 3845 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3846 * <br /> 3847 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3848 */ 3849 static int compareSignatures(Signature[] s1, Signature[] s2) { 3850 if (s1 == null) { 3851 return s2 == null 3852 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3853 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3854 } 3855 3856 if (s2 == null) { 3857 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3858 } 3859 3860 if (s1.length != s2.length) { 3861 return PackageManager.SIGNATURE_NO_MATCH; 3862 } 3863 3864 // Since both signature sets are of size 1, we can compare without HashSets. 3865 if (s1.length == 1) { 3866 return s1[0].equals(s2[0]) ? 3867 PackageManager.SIGNATURE_MATCH : 3868 PackageManager.SIGNATURE_NO_MATCH; 3869 } 3870 3871 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3872 for (Signature sig : s1) { 3873 set1.add(sig); 3874 } 3875 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3876 for (Signature sig : s2) { 3877 set2.add(sig); 3878 } 3879 // Make sure s2 contains all signatures in s1. 3880 if (set1.equals(set2)) { 3881 return PackageManager.SIGNATURE_MATCH; 3882 } 3883 return PackageManager.SIGNATURE_NO_MATCH; 3884 } 3885 3886 /** 3887 * If the database version for this type of package (internal storage or 3888 * external storage) is less than the version where package signatures 3889 * were updated, return true. 3890 */ 3891 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3892 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3893 DatabaseVersion.SIGNATURE_END_ENTITY)) 3894 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3895 DatabaseVersion.SIGNATURE_END_ENTITY)); 3896 } 3897 3898 /** 3899 * Used for backward compatibility to make sure any packages with 3900 * certificate chains get upgraded to the new style. {@code existingSigs} 3901 * will be in the old format (since they were stored on disk from before the 3902 * system upgrade) and {@code scannedSigs} will be in the newer format. 3903 */ 3904 private int compareSignaturesCompat(PackageSignatures existingSigs, 3905 PackageParser.Package scannedPkg) { 3906 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3907 return PackageManager.SIGNATURE_NO_MATCH; 3908 } 3909 3910 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3911 for (Signature sig : existingSigs.mSignatures) { 3912 existingSet.add(sig); 3913 } 3914 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3915 for (Signature sig : scannedPkg.mSignatures) { 3916 try { 3917 Signature[] chainSignatures = sig.getChainSignatures(); 3918 for (Signature chainSig : chainSignatures) { 3919 scannedCompatSet.add(chainSig); 3920 } 3921 } catch (CertificateEncodingException e) { 3922 scannedCompatSet.add(sig); 3923 } 3924 } 3925 /* 3926 * Make sure the expanded scanned set contains all signatures in the 3927 * existing one. 3928 */ 3929 if (scannedCompatSet.equals(existingSet)) { 3930 // Migrate the old signatures to the new scheme. 3931 existingSigs.assignSignatures(scannedPkg.mSignatures); 3932 // The new KeySets will be re-added later in the scanning process. 3933 synchronized (mPackages) { 3934 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3935 } 3936 return PackageManager.SIGNATURE_MATCH; 3937 } 3938 return PackageManager.SIGNATURE_NO_MATCH; 3939 } 3940 3941 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3942 if (isExternal(scannedPkg)) { 3943 return mSettings.isExternalDatabaseVersionOlderThan( 3944 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3945 } else { 3946 return mSettings.isInternalDatabaseVersionOlderThan( 3947 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3948 } 3949 } 3950 3951 private int compareSignaturesRecover(PackageSignatures existingSigs, 3952 PackageParser.Package scannedPkg) { 3953 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3954 return PackageManager.SIGNATURE_NO_MATCH; 3955 } 3956 3957 String msg = null; 3958 try { 3959 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3960 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3961 + scannedPkg.packageName); 3962 return PackageManager.SIGNATURE_MATCH; 3963 } 3964 } catch (CertificateException e) { 3965 msg = e.getMessage(); 3966 } 3967 3968 logCriticalInfo(Log.INFO, 3969 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3970 return PackageManager.SIGNATURE_NO_MATCH; 3971 } 3972 3973 @Override 3974 public String[] getPackagesForUid(int uid) { 3975 uid = UserHandle.getAppId(uid); 3976 // reader 3977 synchronized (mPackages) { 3978 Object obj = mSettings.getUserIdLPr(uid); 3979 if (obj instanceof SharedUserSetting) { 3980 final SharedUserSetting sus = (SharedUserSetting) obj; 3981 final int N = sus.packages.size(); 3982 final String[] res = new String[N]; 3983 final Iterator<PackageSetting> it = sus.packages.iterator(); 3984 int i = 0; 3985 while (it.hasNext()) { 3986 res[i++] = it.next().name; 3987 } 3988 return res; 3989 } else if (obj instanceof PackageSetting) { 3990 final PackageSetting ps = (PackageSetting) obj; 3991 return new String[] { ps.name }; 3992 } 3993 } 3994 return null; 3995 } 3996 3997 @Override 3998 public String getNameForUid(int uid) { 3999 // reader 4000 synchronized (mPackages) { 4001 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4002 if (obj instanceof SharedUserSetting) { 4003 final SharedUserSetting sus = (SharedUserSetting) obj; 4004 return sus.name + ":" + sus.userId; 4005 } else if (obj instanceof PackageSetting) { 4006 final PackageSetting ps = (PackageSetting) obj; 4007 return ps.name; 4008 } 4009 } 4010 return null; 4011 } 4012 4013 @Override 4014 public int getUidForSharedUser(String sharedUserName) { 4015 if(sharedUserName == null) { 4016 return -1; 4017 } 4018 // reader 4019 synchronized (mPackages) { 4020 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4021 if (suid == null) { 4022 return -1; 4023 } 4024 return suid.userId; 4025 } 4026 } 4027 4028 @Override 4029 public int getFlagsForUid(int uid) { 4030 synchronized (mPackages) { 4031 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4032 if (obj instanceof SharedUserSetting) { 4033 final SharedUserSetting sus = (SharedUserSetting) obj; 4034 return sus.pkgFlags; 4035 } else if (obj instanceof PackageSetting) { 4036 final PackageSetting ps = (PackageSetting) obj; 4037 return ps.pkgFlags; 4038 } 4039 } 4040 return 0; 4041 } 4042 4043 @Override 4044 public int getPrivateFlagsForUid(int uid) { 4045 synchronized (mPackages) { 4046 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4047 if (obj instanceof SharedUserSetting) { 4048 final SharedUserSetting sus = (SharedUserSetting) obj; 4049 return sus.pkgPrivateFlags; 4050 } else if (obj instanceof PackageSetting) { 4051 final PackageSetting ps = (PackageSetting) obj; 4052 return ps.pkgPrivateFlags; 4053 } 4054 } 4055 return 0; 4056 } 4057 4058 @Override 4059 public boolean isUidPrivileged(int uid) { 4060 uid = UserHandle.getAppId(uid); 4061 // reader 4062 synchronized (mPackages) { 4063 Object obj = mSettings.getUserIdLPr(uid); 4064 if (obj instanceof SharedUserSetting) { 4065 final SharedUserSetting sus = (SharedUserSetting) obj; 4066 final Iterator<PackageSetting> it = sus.packages.iterator(); 4067 while (it.hasNext()) { 4068 if (it.next().isPrivileged()) { 4069 return true; 4070 } 4071 } 4072 } else if (obj instanceof PackageSetting) { 4073 final PackageSetting ps = (PackageSetting) obj; 4074 return ps.isPrivileged(); 4075 } 4076 } 4077 return false; 4078 } 4079 4080 @Override 4081 public String[] getAppOpPermissionPackages(String permissionName) { 4082 synchronized (mPackages) { 4083 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4084 if (pkgs == null) { 4085 return null; 4086 } 4087 return pkgs.toArray(new String[pkgs.size()]); 4088 } 4089 } 4090 4091 @Override 4092 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4093 int flags, int userId) { 4094 if (!sUserManager.exists(userId)) return null; 4095 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4096 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4097 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4098 } 4099 4100 @Override 4101 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4102 IntentFilter filter, int match, ComponentName activity) { 4103 final int userId = UserHandle.getCallingUserId(); 4104 if (DEBUG_PREFERRED) { 4105 Log.v(TAG, "setLastChosenActivity intent=" + intent 4106 + " resolvedType=" + resolvedType 4107 + " flags=" + flags 4108 + " filter=" + filter 4109 + " match=" + match 4110 + " activity=" + activity); 4111 filter.dump(new PrintStreamPrinter(System.out), " "); 4112 } 4113 intent.setComponent(null); 4114 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4115 // Find any earlier preferred or last chosen entries and nuke them 4116 findPreferredActivity(intent, resolvedType, 4117 flags, query, 0, false, true, false, userId); 4118 // Add the new activity as the last chosen for this filter 4119 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4120 "Setting last chosen"); 4121 } 4122 4123 @Override 4124 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4125 final int userId = UserHandle.getCallingUserId(); 4126 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4127 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4128 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4129 false, false, false, userId); 4130 } 4131 4132 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4133 int flags, List<ResolveInfo> query, int userId) { 4134 if (query != null) { 4135 final int N = query.size(); 4136 if (N == 1) { 4137 return query.get(0); 4138 } else if (N > 1) { 4139 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4140 // If there is more than one activity with the same priority, 4141 // then let the user decide between them. 4142 ResolveInfo r0 = query.get(0); 4143 ResolveInfo r1 = query.get(1); 4144 if (DEBUG_INTENT_MATCHING || debug) { 4145 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4146 + r1.activityInfo.name + "=" + r1.priority); 4147 } 4148 // If the first activity has a higher priority, or a different 4149 // default, then it is always desireable to pick it. 4150 if (r0.priority != r1.priority 4151 || r0.preferredOrder != r1.preferredOrder 4152 || r0.isDefault != r1.isDefault) { 4153 return query.get(0); 4154 } 4155 // If we have saved a preference for a preferred activity for 4156 // this Intent, use that. 4157 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4158 flags, query, r0.priority, true, false, debug, userId); 4159 if (ri != null) { 4160 return ri; 4161 } 4162 if (userId != 0) { 4163 ri = new ResolveInfo(mResolveInfo); 4164 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4165 ri.activityInfo.applicationInfo = new ApplicationInfo( 4166 ri.activityInfo.applicationInfo); 4167 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4168 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4169 return ri; 4170 } 4171 return mResolveInfo; 4172 } 4173 } 4174 return null; 4175 } 4176 4177 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4178 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4179 final int N = query.size(); 4180 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4181 .get(userId); 4182 // Get the list of persistent preferred activities that handle the intent 4183 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4184 List<PersistentPreferredActivity> pprefs = ppir != null 4185 ? ppir.queryIntent(intent, resolvedType, 4186 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4187 : null; 4188 if (pprefs != null && pprefs.size() > 0) { 4189 final int M = pprefs.size(); 4190 for (int i=0; i<M; i++) { 4191 final PersistentPreferredActivity ppa = pprefs.get(i); 4192 if (DEBUG_PREFERRED || debug) { 4193 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4194 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4195 + "\n component=" + ppa.mComponent); 4196 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4197 } 4198 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4199 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4200 if (DEBUG_PREFERRED || debug) { 4201 Slog.v(TAG, "Found persistent preferred activity:"); 4202 if (ai != null) { 4203 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4204 } else { 4205 Slog.v(TAG, " null"); 4206 } 4207 } 4208 if (ai == null) { 4209 // This previously registered persistent preferred activity 4210 // component is no longer known. Ignore it and do NOT remove it. 4211 continue; 4212 } 4213 for (int j=0; j<N; j++) { 4214 final ResolveInfo ri = query.get(j); 4215 if (!ri.activityInfo.applicationInfo.packageName 4216 .equals(ai.applicationInfo.packageName)) { 4217 continue; 4218 } 4219 if (!ri.activityInfo.name.equals(ai.name)) { 4220 continue; 4221 } 4222 // Found a persistent preference that can handle the intent. 4223 if (DEBUG_PREFERRED || debug) { 4224 Slog.v(TAG, "Returning persistent preferred activity: " + 4225 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4226 } 4227 return ri; 4228 } 4229 } 4230 } 4231 return null; 4232 } 4233 4234 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4235 List<ResolveInfo> query, int priority, boolean always, 4236 boolean removeMatches, boolean debug, int userId) { 4237 if (!sUserManager.exists(userId)) return null; 4238 // writer 4239 synchronized (mPackages) { 4240 if (intent.getSelector() != null) { 4241 intent = intent.getSelector(); 4242 } 4243 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4244 4245 // Try to find a matching persistent preferred activity. 4246 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4247 debug, userId); 4248 4249 // If a persistent preferred activity matched, use it. 4250 if (pri != null) { 4251 return pri; 4252 } 4253 4254 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4255 // Get the list of preferred activities that handle the intent 4256 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4257 List<PreferredActivity> prefs = pir != null 4258 ? pir.queryIntent(intent, resolvedType, 4259 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4260 : null; 4261 if (prefs != null && prefs.size() > 0) { 4262 boolean changed = false; 4263 try { 4264 // First figure out how good the original match set is. 4265 // We will only allow preferred activities that came 4266 // from the same match quality. 4267 int match = 0; 4268 4269 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4270 4271 final int N = query.size(); 4272 for (int j=0; j<N; j++) { 4273 final ResolveInfo ri = query.get(j); 4274 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4275 + ": 0x" + Integer.toHexString(match)); 4276 if (ri.match > match) { 4277 match = ri.match; 4278 } 4279 } 4280 4281 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4282 + Integer.toHexString(match)); 4283 4284 match &= IntentFilter.MATCH_CATEGORY_MASK; 4285 final int M = prefs.size(); 4286 for (int i=0; i<M; i++) { 4287 final PreferredActivity pa = prefs.get(i); 4288 if (DEBUG_PREFERRED || debug) { 4289 Slog.v(TAG, "Checking PreferredActivity ds=" 4290 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4291 + "\n component=" + pa.mPref.mComponent); 4292 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4293 } 4294 if (pa.mPref.mMatch != match) { 4295 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4296 + Integer.toHexString(pa.mPref.mMatch)); 4297 continue; 4298 } 4299 // If it's not an "always" type preferred activity and that's what we're 4300 // looking for, skip it. 4301 if (always && !pa.mPref.mAlways) { 4302 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4303 continue; 4304 } 4305 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4306 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4307 if (DEBUG_PREFERRED || debug) { 4308 Slog.v(TAG, "Found preferred activity:"); 4309 if (ai != null) { 4310 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4311 } else { 4312 Slog.v(TAG, " null"); 4313 } 4314 } 4315 if (ai == null) { 4316 // This previously registered preferred activity 4317 // component is no longer known. Most likely an update 4318 // to the app was installed and in the new version this 4319 // component no longer exists. Clean it up by removing 4320 // it from the preferred activities list, and skip it. 4321 Slog.w(TAG, "Removing dangling preferred activity: " 4322 + pa.mPref.mComponent); 4323 pir.removeFilter(pa); 4324 changed = true; 4325 continue; 4326 } 4327 for (int j=0; j<N; j++) { 4328 final ResolveInfo ri = query.get(j); 4329 if (!ri.activityInfo.applicationInfo.packageName 4330 .equals(ai.applicationInfo.packageName)) { 4331 continue; 4332 } 4333 if (!ri.activityInfo.name.equals(ai.name)) { 4334 continue; 4335 } 4336 4337 if (removeMatches) { 4338 pir.removeFilter(pa); 4339 changed = true; 4340 if (DEBUG_PREFERRED) { 4341 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4342 } 4343 break; 4344 } 4345 4346 // Okay we found a previously set preferred or last chosen app. 4347 // If the result set is different from when this 4348 // was created, we need to clear it and re-ask the 4349 // user their preference, if we're looking for an "always" type entry. 4350 if (always && !pa.mPref.sameSet(query)) { 4351 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4352 + intent + " type " + resolvedType); 4353 if (DEBUG_PREFERRED) { 4354 Slog.v(TAG, "Removing preferred activity since set changed " 4355 + pa.mPref.mComponent); 4356 } 4357 pir.removeFilter(pa); 4358 // Re-add the filter as a "last chosen" entry (!always) 4359 PreferredActivity lastChosen = new PreferredActivity( 4360 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4361 pir.addFilter(lastChosen); 4362 changed = true; 4363 return null; 4364 } 4365 4366 // Yay! Either the set matched or we're looking for the last chosen 4367 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4368 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4369 return ri; 4370 } 4371 } 4372 } finally { 4373 if (changed) { 4374 if (DEBUG_PREFERRED) { 4375 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4376 } 4377 scheduleWritePackageRestrictionsLocked(userId); 4378 } 4379 } 4380 } 4381 } 4382 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4383 return null; 4384 } 4385 4386 /* 4387 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4388 */ 4389 @Override 4390 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4391 int targetUserId) { 4392 mContext.enforceCallingOrSelfPermission( 4393 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4394 List<CrossProfileIntentFilter> matches = 4395 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4396 if (matches != null) { 4397 int size = matches.size(); 4398 for (int i = 0; i < size; i++) { 4399 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4400 } 4401 } 4402 if (hasWebURI(intent)) { 4403 // cross-profile app linking works only towards the parent. 4404 final UserInfo parent = getProfileParent(sourceUserId); 4405 synchronized(mPackages) { 4406 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4407 parent.id) != null; 4408 } 4409 } 4410 return false; 4411 } 4412 4413 private UserInfo getProfileParent(int userId) { 4414 final long identity = Binder.clearCallingIdentity(); 4415 try { 4416 return sUserManager.getProfileParent(userId); 4417 } finally { 4418 Binder.restoreCallingIdentity(identity); 4419 } 4420 } 4421 4422 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4423 String resolvedType, int userId) { 4424 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4425 if (resolver != null) { 4426 return resolver.queryIntent(intent, resolvedType, false, userId); 4427 } 4428 return null; 4429 } 4430 4431 @Override 4432 public List<ResolveInfo> queryIntentActivities(Intent intent, 4433 String resolvedType, int flags, int userId) { 4434 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4435 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4436 ComponentName comp = intent.getComponent(); 4437 if (comp == null) { 4438 if (intent.getSelector() != null) { 4439 intent = intent.getSelector(); 4440 comp = intent.getComponent(); 4441 } 4442 } 4443 4444 if (comp != null) { 4445 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4446 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4447 if (ai != null) { 4448 final ResolveInfo ri = new ResolveInfo(); 4449 ri.activityInfo = ai; 4450 list.add(ri); 4451 } 4452 return list; 4453 } 4454 4455 // reader 4456 synchronized (mPackages) { 4457 final String pkgName = intent.getPackage(); 4458 if (pkgName == null) { 4459 List<CrossProfileIntentFilter> matchingFilters = 4460 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4461 // Check for results that need to skip the current profile. 4462 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4463 resolvedType, flags, userId); 4464 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4465 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4466 result.add(xpResolveInfo); 4467 return filterIfNotPrimaryUser(result, userId); 4468 } 4469 4470 // Check for results in the current profile. 4471 List<ResolveInfo> result = mActivities.queryIntent( 4472 intent, resolvedType, flags, userId); 4473 4474 // Check for cross profile results. 4475 xpResolveInfo = queryCrossProfileIntents( 4476 matchingFilters, intent, resolvedType, flags, userId); 4477 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4478 result.add(xpResolveInfo); 4479 Collections.sort(result, mResolvePrioritySorter); 4480 } 4481 result = filterIfNotPrimaryUser(result, userId); 4482 if (hasWebURI(intent)) { 4483 CrossProfileDomainInfo xpDomainInfo = null; 4484 final UserInfo parent = getProfileParent(userId); 4485 if (parent != null) { 4486 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4487 flags, userId, parent.id); 4488 } 4489 if (xpDomainInfo != null) { 4490 if (xpResolveInfo != null) { 4491 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4492 // in the result. 4493 result.remove(xpResolveInfo); 4494 } 4495 if (result.size() == 0) { 4496 result.add(xpDomainInfo.resolveInfo); 4497 return result; 4498 } 4499 } else if (result.size() <= 1) { 4500 return result; 4501 } 4502 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4503 xpDomainInfo); 4504 Collections.sort(result, mResolvePrioritySorter); 4505 } 4506 return result; 4507 } 4508 final PackageParser.Package pkg = mPackages.get(pkgName); 4509 if (pkg != null) { 4510 return filterIfNotPrimaryUser( 4511 mActivities.queryIntentForPackage( 4512 intent, resolvedType, flags, pkg.activities, userId), 4513 userId); 4514 } 4515 return new ArrayList<ResolveInfo>(); 4516 } 4517 } 4518 4519 private static class CrossProfileDomainInfo { 4520 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4521 ResolveInfo resolveInfo; 4522 /* Best domain verification status of the activities found in the other profile */ 4523 int bestDomainVerificationStatus; 4524 } 4525 4526 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4527 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4528 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4529 sourceUserId)) { 4530 return null; 4531 } 4532 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4533 resolvedType, flags, parentUserId); 4534 4535 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4536 return null; 4537 } 4538 CrossProfileDomainInfo result = null; 4539 int size = resultTargetUser.size(); 4540 for (int i = 0; i < size; i++) { 4541 ResolveInfo riTargetUser = resultTargetUser.get(i); 4542 // Intent filter verification is only for filters that specify a host. So don't return 4543 // those that handle all web uris. 4544 if (riTargetUser.handleAllWebDataURI) { 4545 continue; 4546 } 4547 String packageName = riTargetUser.activityInfo.packageName; 4548 PackageSetting ps = mSettings.mPackages.get(packageName); 4549 if (ps == null) { 4550 continue; 4551 } 4552 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4553 if (result == null) { 4554 result = new CrossProfileDomainInfo(); 4555 result.resolveInfo = 4556 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4557 result.bestDomainVerificationStatus = status; 4558 } else { 4559 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4560 result.bestDomainVerificationStatus); 4561 } 4562 } 4563 return result; 4564 } 4565 4566 /** 4567 * Verification statuses are ordered from the worse to the best, except for 4568 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4569 */ 4570 private int bestDomainVerificationStatus(int status1, int status2) { 4571 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4572 return status2; 4573 } 4574 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4575 return status1; 4576 } 4577 return (int) MathUtils.max(status1, status2); 4578 } 4579 4580 private boolean isUserEnabled(int userId) { 4581 long callingId = Binder.clearCallingIdentity(); 4582 try { 4583 UserInfo userInfo = sUserManager.getUserInfo(userId); 4584 return userInfo != null && userInfo.isEnabled(); 4585 } finally { 4586 Binder.restoreCallingIdentity(callingId); 4587 } 4588 } 4589 4590 /** 4591 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4592 * 4593 * @return filtered list 4594 */ 4595 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4596 if (userId == UserHandle.USER_OWNER) { 4597 return resolveInfos; 4598 } 4599 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4600 ResolveInfo info = resolveInfos.get(i); 4601 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4602 resolveInfos.remove(i); 4603 } 4604 } 4605 return resolveInfos; 4606 } 4607 4608 private static boolean hasWebURI(Intent intent) { 4609 if (intent.getData() == null) { 4610 return false; 4611 } 4612 final String scheme = intent.getScheme(); 4613 if (TextUtils.isEmpty(scheme)) { 4614 return false; 4615 } 4616 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4617 } 4618 4619 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4620 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4621 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4622 Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " + 4623 candidates.size()); 4624 } 4625 4626 final int userId = UserHandle.getCallingUserId(); 4627 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4628 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4629 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4630 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4631 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4632 4633 synchronized (mPackages) { 4634 final int count = candidates.size(); 4635 // First, try to use linked apps. Partition the candidates into four lists: 4636 // one for the final results, one for the "do not use ever", one for "undefined status" 4637 // and finally one for "browser app type". 4638 for (int n=0; n<count; n++) { 4639 ResolveInfo info = candidates.get(n); 4640 String packageName = info.activityInfo.packageName; 4641 PackageSetting ps = mSettings.mPackages.get(packageName); 4642 if (ps != null) { 4643 // Add to the special match all list (Browser use case) 4644 if (info.handleAllWebDataURI) { 4645 matchAllList.add(info); 4646 continue; 4647 } 4648 // Try to get the status from User settings first 4649 int status = getDomainVerificationStatusLPr(ps, userId); 4650 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4651 if (DEBUG_DOMAIN_VERIFICATION) { 4652 Slog.i(TAG, " + always: " + info.activityInfo.packageName); 4653 } 4654 alwaysList.add(info); 4655 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4656 if (DEBUG_DOMAIN_VERIFICATION) { 4657 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4658 } 4659 neverList.add(info); 4660 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4661 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4662 if (DEBUG_DOMAIN_VERIFICATION) { 4663 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4664 } 4665 undefinedList.add(info); 4666 } 4667 } 4668 } 4669 // First try to add the "always" resolution for the current user if there is any 4670 if (alwaysList.size() > 0) { 4671 result.addAll(alwaysList); 4672 // if there is an "always" for the parent user, add it. 4673 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4674 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4675 result.add(xpDomainInfo.resolveInfo); 4676 } else { 4677 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4678 result.addAll(undefinedList); 4679 if (xpDomainInfo != null && ( 4680 xpDomainInfo.bestDomainVerificationStatus 4681 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4682 || xpDomainInfo.bestDomainVerificationStatus 4683 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4684 result.add(xpDomainInfo.resolveInfo); 4685 } 4686 // Also add Browsers (all of them or only the default one) 4687 if ((flags & MATCH_ALL) != 0) { 4688 result.addAll(matchAllList); 4689 } else { 4690 // Try to add the Default Browser if we can 4691 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4692 UserHandle.myUserId()); 4693 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4694 boolean defaultBrowserFound = false; 4695 final int browserCount = matchAllList.size(); 4696 for (int n=0; n<browserCount; n++) { 4697 ResolveInfo browser = matchAllList.get(n); 4698 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4699 result.add(browser); 4700 defaultBrowserFound = true; 4701 break; 4702 } 4703 } 4704 if (!defaultBrowserFound) { 4705 result.addAll(matchAllList); 4706 } 4707 } else { 4708 result.addAll(matchAllList); 4709 } 4710 } 4711 4712 // If there is nothing selected, add all candidates and remove the ones that the user 4713 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4714 if (result.size() == 0) { 4715 result.addAll(candidates); 4716 result.removeAll(neverList); 4717 } 4718 } 4719 } 4720 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4721 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4722 result.size()); 4723 for (ResolveInfo info : result) { 4724 Slog.v(TAG, " + " + info.activityInfo); 4725 } 4726 } 4727 return result; 4728 } 4729 4730 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4731 int status = ps.getDomainVerificationStatusForUser(userId); 4732 // if none available, get the master status 4733 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4734 if (ps.getIntentFilterVerificationInfo() != null) { 4735 status = ps.getIntentFilterVerificationInfo().getStatus(); 4736 } 4737 } 4738 return status; 4739 } 4740 4741 private ResolveInfo querySkipCurrentProfileIntents( 4742 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4743 int flags, int sourceUserId) { 4744 if (matchingFilters != null) { 4745 int size = matchingFilters.size(); 4746 for (int i = 0; i < size; i ++) { 4747 CrossProfileIntentFilter filter = matchingFilters.get(i); 4748 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4749 // Checking if there are activities in the target user that can handle the 4750 // intent. 4751 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4752 flags, sourceUserId); 4753 if (resolveInfo != null) { 4754 return resolveInfo; 4755 } 4756 } 4757 } 4758 } 4759 return null; 4760 } 4761 4762 // Return matching ResolveInfo if any for skip current profile intent filters. 4763 private ResolveInfo queryCrossProfileIntents( 4764 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4765 int flags, int sourceUserId) { 4766 if (matchingFilters != null) { 4767 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4768 // match the same intent. For performance reasons, it is better not to 4769 // run queryIntent twice for the same userId 4770 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4771 int size = matchingFilters.size(); 4772 for (int i = 0; i < size; i++) { 4773 CrossProfileIntentFilter filter = matchingFilters.get(i); 4774 int targetUserId = filter.getTargetUserId(); 4775 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4776 && !alreadyTriedUserIds.get(targetUserId)) { 4777 // Checking if there are activities in the target user that can handle the 4778 // intent. 4779 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4780 flags, sourceUserId); 4781 if (resolveInfo != null) return resolveInfo; 4782 alreadyTriedUserIds.put(targetUserId, true); 4783 } 4784 } 4785 } 4786 return null; 4787 } 4788 4789 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4790 String resolvedType, int flags, int sourceUserId) { 4791 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4792 resolvedType, flags, filter.getTargetUserId()); 4793 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4794 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4795 } 4796 return null; 4797 } 4798 4799 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4800 int sourceUserId, int targetUserId) { 4801 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4802 String className; 4803 if (targetUserId == UserHandle.USER_OWNER) { 4804 className = FORWARD_INTENT_TO_USER_OWNER; 4805 } else { 4806 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4807 } 4808 ComponentName forwardingActivityComponentName = new ComponentName( 4809 mAndroidApplication.packageName, className); 4810 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4811 sourceUserId); 4812 if (targetUserId == UserHandle.USER_OWNER) { 4813 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4814 forwardingResolveInfo.noResourceId = true; 4815 } 4816 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4817 forwardingResolveInfo.priority = 0; 4818 forwardingResolveInfo.preferredOrder = 0; 4819 forwardingResolveInfo.match = 0; 4820 forwardingResolveInfo.isDefault = true; 4821 forwardingResolveInfo.filter = filter; 4822 forwardingResolveInfo.targetUserId = targetUserId; 4823 return forwardingResolveInfo; 4824 } 4825 4826 @Override 4827 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4828 Intent[] specifics, String[] specificTypes, Intent intent, 4829 String resolvedType, int flags, int userId) { 4830 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4831 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4832 false, "query intent activity options"); 4833 final String resultsAction = intent.getAction(); 4834 4835 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4836 | PackageManager.GET_RESOLVED_FILTER, userId); 4837 4838 if (DEBUG_INTENT_MATCHING) { 4839 Log.v(TAG, "Query " + intent + ": " + results); 4840 } 4841 4842 int specificsPos = 0; 4843 int N; 4844 4845 // todo: note that the algorithm used here is O(N^2). This 4846 // isn't a problem in our current environment, but if we start running 4847 // into situations where we have more than 5 or 10 matches then this 4848 // should probably be changed to something smarter... 4849 4850 // First we go through and resolve each of the specific items 4851 // that were supplied, taking care of removing any corresponding 4852 // duplicate items in the generic resolve list. 4853 if (specifics != null) { 4854 for (int i=0; i<specifics.length; i++) { 4855 final Intent sintent = specifics[i]; 4856 if (sintent == null) { 4857 continue; 4858 } 4859 4860 if (DEBUG_INTENT_MATCHING) { 4861 Log.v(TAG, "Specific #" + i + ": " + sintent); 4862 } 4863 4864 String action = sintent.getAction(); 4865 if (resultsAction != null && resultsAction.equals(action)) { 4866 // If this action was explicitly requested, then don't 4867 // remove things that have it. 4868 action = null; 4869 } 4870 4871 ResolveInfo ri = null; 4872 ActivityInfo ai = null; 4873 4874 ComponentName comp = sintent.getComponent(); 4875 if (comp == null) { 4876 ri = resolveIntent( 4877 sintent, 4878 specificTypes != null ? specificTypes[i] : null, 4879 flags, userId); 4880 if (ri == null) { 4881 continue; 4882 } 4883 if (ri == mResolveInfo) { 4884 // ACK! Must do something better with this. 4885 } 4886 ai = ri.activityInfo; 4887 comp = new ComponentName(ai.applicationInfo.packageName, 4888 ai.name); 4889 } else { 4890 ai = getActivityInfo(comp, flags, userId); 4891 if (ai == null) { 4892 continue; 4893 } 4894 } 4895 4896 // Look for any generic query activities that are duplicates 4897 // of this specific one, and remove them from the results. 4898 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4899 N = results.size(); 4900 int j; 4901 for (j=specificsPos; j<N; j++) { 4902 ResolveInfo sri = results.get(j); 4903 if ((sri.activityInfo.name.equals(comp.getClassName()) 4904 && sri.activityInfo.applicationInfo.packageName.equals( 4905 comp.getPackageName())) 4906 || (action != null && sri.filter.matchAction(action))) { 4907 results.remove(j); 4908 if (DEBUG_INTENT_MATCHING) Log.v( 4909 TAG, "Removing duplicate item from " + j 4910 + " due to specific " + specificsPos); 4911 if (ri == null) { 4912 ri = sri; 4913 } 4914 j--; 4915 N--; 4916 } 4917 } 4918 4919 // Add this specific item to its proper place. 4920 if (ri == null) { 4921 ri = new ResolveInfo(); 4922 ri.activityInfo = ai; 4923 } 4924 results.add(specificsPos, ri); 4925 ri.specificIndex = i; 4926 specificsPos++; 4927 } 4928 } 4929 4930 // Now we go through the remaining generic results and remove any 4931 // duplicate actions that are found here. 4932 N = results.size(); 4933 for (int i=specificsPos; i<N-1; i++) { 4934 final ResolveInfo rii = results.get(i); 4935 if (rii.filter == null) { 4936 continue; 4937 } 4938 4939 // Iterate over all of the actions of this result's intent 4940 // filter... typically this should be just one. 4941 final Iterator<String> it = rii.filter.actionsIterator(); 4942 if (it == null) { 4943 continue; 4944 } 4945 while (it.hasNext()) { 4946 final String action = it.next(); 4947 if (resultsAction != null && resultsAction.equals(action)) { 4948 // If this action was explicitly requested, then don't 4949 // remove things that have it. 4950 continue; 4951 } 4952 for (int j=i+1; j<N; j++) { 4953 final ResolveInfo rij = results.get(j); 4954 if (rij.filter != null && rij.filter.hasAction(action)) { 4955 results.remove(j); 4956 if (DEBUG_INTENT_MATCHING) Log.v( 4957 TAG, "Removing duplicate item from " + j 4958 + " due to action " + action + " at " + i); 4959 j--; 4960 N--; 4961 } 4962 } 4963 } 4964 4965 // If the caller didn't request filter information, drop it now 4966 // so we don't have to marshall/unmarshall it. 4967 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4968 rii.filter = null; 4969 } 4970 } 4971 4972 // Filter out the caller activity if so requested. 4973 if (caller != null) { 4974 N = results.size(); 4975 for (int i=0; i<N; i++) { 4976 ActivityInfo ainfo = results.get(i).activityInfo; 4977 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4978 && caller.getClassName().equals(ainfo.name)) { 4979 results.remove(i); 4980 break; 4981 } 4982 } 4983 } 4984 4985 // If the caller didn't request filter information, 4986 // drop them now so we don't have to 4987 // marshall/unmarshall it. 4988 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4989 N = results.size(); 4990 for (int i=0; i<N; i++) { 4991 results.get(i).filter = null; 4992 } 4993 } 4994 4995 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4996 return results; 4997 } 4998 4999 @Override 5000 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5001 int userId) { 5002 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5003 ComponentName comp = intent.getComponent(); 5004 if (comp == null) { 5005 if (intent.getSelector() != null) { 5006 intent = intent.getSelector(); 5007 comp = intent.getComponent(); 5008 } 5009 } 5010 if (comp != null) { 5011 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5012 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5013 if (ai != null) { 5014 ResolveInfo ri = new ResolveInfo(); 5015 ri.activityInfo = ai; 5016 list.add(ri); 5017 } 5018 return list; 5019 } 5020 5021 // reader 5022 synchronized (mPackages) { 5023 String pkgName = intent.getPackage(); 5024 if (pkgName == null) { 5025 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5026 } 5027 final PackageParser.Package pkg = mPackages.get(pkgName); 5028 if (pkg != null) { 5029 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5030 userId); 5031 } 5032 return null; 5033 } 5034 } 5035 5036 @Override 5037 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5038 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5039 if (!sUserManager.exists(userId)) return null; 5040 if (query != null) { 5041 if (query.size() >= 1) { 5042 // If there is more than one service with the same priority, 5043 // just arbitrarily pick the first one. 5044 return query.get(0); 5045 } 5046 } 5047 return null; 5048 } 5049 5050 @Override 5051 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5052 int userId) { 5053 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5054 ComponentName comp = intent.getComponent(); 5055 if (comp == null) { 5056 if (intent.getSelector() != null) { 5057 intent = intent.getSelector(); 5058 comp = intent.getComponent(); 5059 } 5060 } 5061 if (comp != null) { 5062 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5063 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5064 if (si != null) { 5065 final ResolveInfo ri = new ResolveInfo(); 5066 ri.serviceInfo = si; 5067 list.add(ri); 5068 } 5069 return list; 5070 } 5071 5072 // reader 5073 synchronized (mPackages) { 5074 String pkgName = intent.getPackage(); 5075 if (pkgName == null) { 5076 return mServices.queryIntent(intent, resolvedType, flags, userId); 5077 } 5078 final PackageParser.Package pkg = mPackages.get(pkgName); 5079 if (pkg != null) { 5080 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5081 userId); 5082 } 5083 return null; 5084 } 5085 } 5086 5087 @Override 5088 public List<ResolveInfo> queryIntentContentProviders( 5089 Intent intent, String resolvedType, int flags, int userId) { 5090 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5091 ComponentName comp = intent.getComponent(); 5092 if (comp == null) { 5093 if (intent.getSelector() != null) { 5094 intent = intent.getSelector(); 5095 comp = intent.getComponent(); 5096 } 5097 } 5098 if (comp != null) { 5099 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5100 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5101 if (pi != null) { 5102 final ResolveInfo ri = new ResolveInfo(); 5103 ri.providerInfo = pi; 5104 list.add(ri); 5105 } 5106 return list; 5107 } 5108 5109 // reader 5110 synchronized (mPackages) { 5111 String pkgName = intent.getPackage(); 5112 if (pkgName == null) { 5113 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5114 } 5115 final PackageParser.Package pkg = mPackages.get(pkgName); 5116 if (pkg != null) { 5117 return mProviders.queryIntentForPackage( 5118 intent, resolvedType, flags, pkg.providers, userId); 5119 } 5120 return null; 5121 } 5122 } 5123 5124 @Override 5125 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5126 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5127 5128 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5129 5130 // writer 5131 synchronized (mPackages) { 5132 ArrayList<PackageInfo> list; 5133 if (listUninstalled) { 5134 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5135 for (PackageSetting ps : mSettings.mPackages.values()) { 5136 PackageInfo pi; 5137 if (ps.pkg != null) { 5138 pi = generatePackageInfo(ps.pkg, flags, userId); 5139 } else { 5140 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5141 } 5142 if (pi != null) { 5143 list.add(pi); 5144 } 5145 } 5146 } else { 5147 list = new ArrayList<PackageInfo>(mPackages.size()); 5148 for (PackageParser.Package p : mPackages.values()) { 5149 PackageInfo pi = generatePackageInfo(p, flags, userId); 5150 if (pi != null) { 5151 list.add(pi); 5152 } 5153 } 5154 } 5155 5156 return new ParceledListSlice<PackageInfo>(list); 5157 } 5158 } 5159 5160 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5161 String[] permissions, boolean[] tmp, int flags, int userId) { 5162 int numMatch = 0; 5163 final PermissionsState permissionsState = ps.getPermissionsState(); 5164 for (int i=0; i<permissions.length; i++) { 5165 final String permission = permissions[i]; 5166 if (permissionsState.hasPermission(permission, userId)) { 5167 tmp[i] = true; 5168 numMatch++; 5169 } else { 5170 tmp[i] = false; 5171 } 5172 } 5173 if (numMatch == 0) { 5174 return; 5175 } 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 // The above might return null in cases of uninstalled apps or install-state 5183 // skew across users/profiles. 5184 if (pi != null) { 5185 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5186 if (numMatch == permissions.length) { 5187 pi.requestedPermissions = permissions; 5188 } else { 5189 pi.requestedPermissions = new String[numMatch]; 5190 numMatch = 0; 5191 for (int i=0; i<permissions.length; i++) { 5192 if (tmp[i]) { 5193 pi.requestedPermissions[numMatch] = permissions[i]; 5194 numMatch++; 5195 } 5196 } 5197 } 5198 } 5199 list.add(pi); 5200 } 5201 } 5202 5203 @Override 5204 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5205 String[] permissions, int flags, int userId) { 5206 if (!sUserManager.exists(userId)) return null; 5207 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5208 5209 // writer 5210 synchronized (mPackages) { 5211 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5212 boolean[] tmpBools = new boolean[permissions.length]; 5213 if (listUninstalled) { 5214 for (PackageSetting ps : mSettings.mPackages.values()) { 5215 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5216 } 5217 } else { 5218 for (PackageParser.Package pkg : mPackages.values()) { 5219 PackageSetting ps = (PackageSetting)pkg.mExtras; 5220 if (ps != null) { 5221 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5222 userId); 5223 } 5224 } 5225 } 5226 5227 return new ParceledListSlice<PackageInfo>(list); 5228 } 5229 } 5230 5231 @Override 5232 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5233 if (!sUserManager.exists(userId)) return null; 5234 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5235 5236 // writer 5237 synchronized (mPackages) { 5238 ArrayList<ApplicationInfo> list; 5239 if (listUninstalled) { 5240 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5241 for (PackageSetting ps : mSettings.mPackages.values()) { 5242 ApplicationInfo ai; 5243 if (ps.pkg != null) { 5244 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5245 ps.readUserState(userId), userId); 5246 } else { 5247 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5248 } 5249 if (ai != null) { 5250 list.add(ai); 5251 } 5252 } 5253 } else { 5254 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5255 for (PackageParser.Package p : mPackages.values()) { 5256 if (p.mExtras != null) { 5257 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5258 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5259 if (ai != null) { 5260 list.add(ai); 5261 } 5262 } 5263 } 5264 } 5265 5266 return new ParceledListSlice<ApplicationInfo>(list); 5267 } 5268 } 5269 5270 public List<ApplicationInfo> getPersistentApplications(int flags) { 5271 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5272 5273 // reader 5274 synchronized (mPackages) { 5275 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5276 final int userId = UserHandle.getCallingUserId(); 5277 while (i.hasNext()) { 5278 final PackageParser.Package p = i.next(); 5279 if (p.applicationInfo != null 5280 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5281 && (!mSafeMode || isSystemApp(p))) { 5282 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5283 if (ps != null) { 5284 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5285 ps.readUserState(userId), userId); 5286 if (ai != null) { 5287 finalList.add(ai); 5288 } 5289 } 5290 } 5291 } 5292 } 5293 5294 return finalList; 5295 } 5296 5297 @Override 5298 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5299 if (!sUserManager.exists(userId)) return null; 5300 // reader 5301 synchronized (mPackages) { 5302 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5303 PackageSetting ps = provider != null 5304 ? mSettings.mPackages.get(provider.owner.packageName) 5305 : null; 5306 return ps != null 5307 && mSettings.isEnabledLPr(provider.info, flags, userId) 5308 && (!mSafeMode || (provider.info.applicationInfo.flags 5309 &ApplicationInfo.FLAG_SYSTEM) != 0) 5310 ? PackageParser.generateProviderInfo(provider, flags, 5311 ps.readUserState(userId), userId) 5312 : null; 5313 } 5314 } 5315 5316 /** 5317 * @deprecated 5318 */ 5319 @Deprecated 5320 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5321 // reader 5322 synchronized (mPackages) { 5323 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5324 .entrySet().iterator(); 5325 final int userId = UserHandle.getCallingUserId(); 5326 while (i.hasNext()) { 5327 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5328 PackageParser.Provider p = entry.getValue(); 5329 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5330 5331 if (ps != null && p.syncable 5332 && (!mSafeMode || (p.info.applicationInfo.flags 5333 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5334 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5335 ps.readUserState(userId), userId); 5336 if (info != null) { 5337 outNames.add(entry.getKey()); 5338 outInfo.add(info); 5339 } 5340 } 5341 } 5342 } 5343 } 5344 5345 @Override 5346 public List<ProviderInfo> queryContentProviders(String processName, 5347 int uid, int flags) { 5348 ArrayList<ProviderInfo> finalList = null; 5349 // reader 5350 synchronized (mPackages) { 5351 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5352 final int userId = processName != null ? 5353 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5354 while (i.hasNext()) { 5355 final PackageParser.Provider p = i.next(); 5356 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5357 if (ps != null && p.info.authority != null 5358 && (processName == null 5359 || (p.info.processName.equals(processName) 5360 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5361 && mSettings.isEnabledLPr(p.info, flags, userId) 5362 && (!mSafeMode 5363 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5364 if (finalList == null) { 5365 finalList = new ArrayList<ProviderInfo>(3); 5366 } 5367 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5368 ps.readUserState(userId), userId); 5369 if (info != null) { 5370 finalList.add(info); 5371 } 5372 } 5373 } 5374 } 5375 5376 if (finalList != null) { 5377 Collections.sort(finalList, mProviderInitOrderSorter); 5378 } 5379 5380 return finalList; 5381 } 5382 5383 @Override 5384 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5385 int flags) { 5386 // reader 5387 synchronized (mPackages) { 5388 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5389 return PackageParser.generateInstrumentationInfo(i, flags); 5390 } 5391 } 5392 5393 @Override 5394 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5395 int flags) { 5396 ArrayList<InstrumentationInfo> finalList = 5397 new ArrayList<InstrumentationInfo>(); 5398 5399 // reader 5400 synchronized (mPackages) { 5401 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5402 while (i.hasNext()) { 5403 final PackageParser.Instrumentation p = i.next(); 5404 if (targetPackage == null 5405 || targetPackage.equals(p.info.targetPackage)) { 5406 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5407 flags); 5408 if (ii != null) { 5409 finalList.add(ii); 5410 } 5411 } 5412 } 5413 } 5414 5415 return finalList; 5416 } 5417 5418 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5419 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5420 if (overlays == null) { 5421 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5422 return; 5423 } 5424 for (PackageParser.Package opkg : overlays.values()) { 5425 // Not much to do if idmap fails: we already logged the error 5426 // and we certainly don't want to abort installation of pkg simply 5427 // because an overlay didn't fit properly. For these reasons, 5428 // ignore the return value of createIdmapForPackagePairLI. 5429 createIdmapForPackagePairLI(pkg, opkg); 5430 } 5431 } 5432 5433 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5434 PackageParser.Package opkg) { 5435 if (!opkg.mTrustedOverlay) { 5436 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5437 opkg.baseCodePath + ": overlay not trusted"); 5438 return false; 5439 } 5440 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5441 if (overlaySet == null) { 5442 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5443 opkg.baseCodePath + " but target package has no known overlays"); 5444 return false; 5445 } 5446 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5447 // TODO: generate idmap for split APKs 5448 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5449 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5450 + opkg.baseCodePath); 5451 return false; 5452 } 5453 PackageParser.Package[] overlayArray = 5454 overlaySet.values().toArray(new PackageParser.Package[0]); 5455 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5456 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5457 return p1.mOverlayPriority - p2.mOverlayPriority; 5458 } 5459 }; 5460 Arrays.sort(overlayArray, cmp); 5461 5462 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5463 int i = 0; 5464 for (PackageParser.Package p : overlayArray) { 5465 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5466 } 5467 return true; 5468 } 5469 5470 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5471 final File[] files = dir.listFiles(); 5472 if (ArrayUtils.isEmpty(files)) { 5473 Log.d(TAG, "No files in app dir " + dir); 5474 return; 5475 } 5476 5477 if (DEBUG_PACKAGE_SCANNING) { 5478 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5479 + " flags=0x" + Integer.toHexString(parseFlags)); 5480 } 5481 5482 for (File file : files) { 5483 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5484 && !PackageInstallerService.isStageName(file.getName()); 5485 if (!isPackage) { 5486 // Ignore entries which are not packages 5487 continue; 5488 } 5489 try { 5490 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5491 scanFlags, currentTime, null); 5492 } catch (PackageManagerException e) { 5493 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5494 5495 // Delete invalid userdata apps 5496 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5497 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5498 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5499 if (file.isDirectory()) { 5500 mInstaller.rmPackageDir(file.getAbsolutePath()); 5501 } else { 5502 file.delete(); 5503 } 5504 } 5505 } 5506 } 5507 } 5508 5509 private static File getSettingsProblemFile() { 5510 File dataDir = Environment.getDataDirectory(); 5511 File systemDir = new File(dataDir, "system"); 5512 File fname = new File(systemDir, "uiderrors.txt"); 5513 return fname; 5514 } 5515 5516 static void reportSettingsProblem(int priority, String msg) { 5517 logCriticalInfo(priority, msg); 5518 } 5519 5520 static void logCriticalInfo(int priority, String msg) { 5521 Slog.println(priority, TAG, msg); 5522 EventLogTags.writePmCriticalInfo(msg); 5523 try { 5524 File fname = getSettingsProblemFile(); 5525 FileOutputStream out = new FileOutputStream(fname, true); 5526 PrintWriter pw = new FastPrintWriter(out); 5527 SimpleDateFormat formatter = new SimpleDateFormat(); 5528 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5529 pw.println(dateString + ": " + msg); 5530 pw.close(); 5531 FileUtils.setPermissions( 5532 fname.toString(), 5533 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5534 -1, -1); 5535 } catch (java.io.IOException e) { 5536 } 5537 } 5538 5539 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5540 PackageParser.Package pkg, File srcFile, int parseFlags) 5541 throws PackageManagerException { 5542 if (ps != null 5543 && ps.codePath.equals(srcFile) 5544 && ps.timeStamp == srcFile.lastModified() 5545 && !isCompatSignatureUpdateNeeded(pkg) 5546 && !isRecoverSignatureUpdateNeeded(pkg)) { 5547 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5548 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5549 ArraySet<PublicKey> signingKs; 5550 synchronized (mPackages) { 5551 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5552 } 5553 if (ps.signatures.mSignatures != null 5554 && ps.signatures.mSignatures.length != 0 5555 && signingKs != null) { 5556 // Optimization: reuse the existing cached certificates 5557 // if the package appears to be unchanged. 5558 pkg.mSignatures = ps.signatures.mSignatures; 5559 pkg.mSigningKeys = signingKs; 5560 return; 5561 } 5562 5563 Slog.w(TAG, "PackageSetting for " + ps.name 5564 + " is missing signatures. Collecting certs again to recover them."); 5565 } else { 5566 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5567 } 5568 5569 try { 5570 pp.collectCertificates(pkg, parseFlags); 5571 pp.collectManifestDigest(pkg); 5572 } catch (PackageParserException e) { 5573 throw PackageManagerException.from(e); 5574 } 5575 } 5576 5577 /* 5578 * Scan a package and return the newly parsed package. 5579 * Returns null in case of errors and the error code is stored in mLastScanError 5580 */ 5581 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5582 long currentTime, UserHandle user) throws PackageManagerException { 5583 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5584 parseFlags |= mDefParseFlags; 5585 PackageParser pp = new PackageParser(); 5586 pp.setSeparateProcesses(mSeparateProcesses); 5587 pp.setOnlyCoreApps(mOnlyCore); 5588 pp.setDisplayMetrics(mMetrics); 5589 5590 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5591 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5592 } 5593 5594 final PackageParser.Package pkg; 5595 try { 5596 pkg = pp.parsePackage(scanFile, parseFlags); 5597 } catch (PackageParserException e) { 5598 throw PackageManagerException.from(e); 5599 } 5600 5601 PackageSetting ps = null; 5602 PackageSetting updatedPkg; 5603 // reader 5604 synchronized (mPackages) { 5605 // Look to see if we already know about this package. 5606 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5607 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5608 // This package has been renamed to its original name. Let's 5609 // use that. 5610 ps = mSettings.peekPackageLPr(oldName); 5611 } 5612 // If there was no original package, see one for the real package name. 5613 if (ps == null) { 5614 ps = mSettings.peekPackageLPr(pkg.packageName); 5615 } 5616 // Check to see if this package could be hiding/updating a system 5617 // package. Must look for it either under the original or real 5618 // package name depending on our state. 5619 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5620 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5621 } 5622 boolean updatedPkgBetter = false; 5623 // First check if this is a system package that may involve an update 5624 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5625 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5626 // it needs to drop FLAG_PRIVILEGED. 5627 if (locationIsPrivileged(scanFile)) { 5628 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5629 } else { 5630 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5631 } 5632 5633 if (ps != null && !ps.codePath.equals(scanFile)) { 5634 // The path has changed from what was last scanned... check the 5635 // version of the new path against what we have stored to determine 5636 // what to do. 5637 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5638 if (pkg.mVersionCode <= ps.versionCode) { 5639 // The system package has been updated and the code path does not match 5640 // Ignore entry. Skip it. 5641 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5642 + " ignored: updated version " + ps.versionCode 5643 + " better than this " + pkg.mVersionCode); 5644 if (!updatedPkg.codePath.equals(scanFile)) { 5645 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5646 + ps.name + " changing from " + updatedPkg.codePathString 5647 + " to " + scanFile); 5648 updatedPkg.codePath = scanFile; 5649 updatedPkg.codePathString = scanFile.toString(); 5650 updatedPkg.resourcePath = scanFile; 5651 updatedPkg.resourcePathString = scanFile.toString(); 5652 } 5653 updatedPkg.pkg = pkg; 5654 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5655 "Package " + ps.name + " at " + scanFile 5656 + " ignored: updated version " + ps.versionCode 5657 + " better than this " + pkg.mVersionCode); 5658 } else { 5659 // The current app on the system partition is better than 5660 // what we have updated to on the data partition; switch 5661 // back to the system partition version. 5662 // At this point, its safely assumed that package installation for 5663 // apps in system partition will go through. If not there won't be a working 5664 // version of the app 5665 // writer 5666 synchronized (mPackages) { 5667 // Just remove the loaded entries from package lists. 5668 mPackages.remove(ps.name); 5669 } 5670 5671 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5672 + " reverting from " + ps.codePathString 5673 + ": new version " + pkg.mVersionCode 5674 + " better than installed " + ps.versionCode); 5675 5676 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5677 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5678 synchronized (mInstallLock) { 5679 args.cleanUpResourcesLI(); 5680 } 5681 synchronized (mPackages) { 5682 mSettings.enableSystemPackageLPw(ps.name); 5683 } 5684 updatedPkgBetter = true; 5685 } 5686 } 5687 } 5688 5689 if (updatedPkg != null) { 5690 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5691 // initially 5692 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5693 5694 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5695 // flag set initially 5696 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5697 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5698 } 5699 } 5700 5701 // Verify certificates against what was last scanned 5702 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5703 5704 /* 5705 * A new system app appeared, but we already had a non-system one of the 5706 * same name installed earlier. 5707 */ 5708 boolean shouldHideSystemApp = false; 5709 if (updatedPkg == null && ps != null 5710 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5711 /* 5712 * Check to make sure the signatures match first. If they don't, 5713 * wipe the installed application and its data. 5714 */ 5715 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5716 != PackageManager.SIGNATURE_MATCH) { 5717 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5718 + " signatures don't match existing userdata copy; removing"); 5719 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5720 ps = null; 5721 } else { 5722 /* 5723 * If the newly-added system app is an older version than the 5724 * already installed version, hide it. It will be scanned later 5725 * and re-added like an update. 5726 */ 5727 if (pkg.mVersionCode <= ps.versionCode) { 5728 shouldHideSystemApp = true; 5729 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5730 + " but new version " + pkg.mVersionCode + " better than installed " 5731 + ps.versionCode + "; hiding system"); 5732 } else { 5733 /* 5734 * The newly found system app is a newer version that the 5735 * one previously installed. Simply remove the 5736 * already-installed application and replace it with our own 5737 * while keeping the application data. 5738 */ 5739 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5740 + " reverting from " + ps.codePathString + ": new version " 5741 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5742 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5743 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5744 synchronized (mInstallLock) { 5745 args.cleanUpResourcesLI(); 5746 } 5747 } 5748 } 5749 } 5750 5751 // The apk is forward locked (not public) if its code and resources 5752 // are kept in different files. (except for app in either system or 5753 // vendor path). 5754 // TODO grab this value from PackageSettings 5755 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5756 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5757 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5758 } 5759 } 5760 5761 // TODO: extend to support forward-locked splits 5762 String resourcePath = null; 5763 String baseResourcePath = null; 5764 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5765 if (ps != null && ps.resourcePathString != null) { 5766 resourcePath = ps.resourcePathString; 5767 baseResourcePath = ps.resourcePathString; 5768 } else { 5769 // Should not happen at all. Just log an error. 5770 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5771 } 5772 } else { 5773 resourcePath = pkg.codePath; 5774 baseResourcePath = pkg.baseCodePath; 5775 } 5776 5777 // Set application objects path explicitly. 5778 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5779 pkg.applicationInfo.setCodePath(pkg.codePath); 5780 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5781 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5782 pkg.applicationInfo.setResourcePath(resourcePath); 5783 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5784 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5785 5786 // Note that we invoke the following method only if we are about to unpack an application 5787 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5788 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5789 5790 /* 5791 * If the system app should be overridden by a previously installed 5792 * data, hide the system app now and let the /data/app scan pick it up 5793 * again. 5794 */ 5795 if (shouldHideSystemApp) { 5796 synchronized (mPackages) { 5797 /* 5798 * We have to grant systems permissions before we hide, because 5799 * grantPermissions will assume the package update is trying to 5800 * expand its permissions. 5801 */ 5802 grantPermissionsLPw(pkg, true, pkg.packageName); 5803 mSettings.disableSystemPackageLPw(pkg.packageName); 5804 } 5805 } 5806 5807 return scannedPkg; 5808 } 5809 5810 private static String fixProcessName(String defProcessName, 5811 String processName, int uid) { 5812 if (processName == null) { 5813 return defProcessName; 5814 } 5815 return processName; 5816 } 5817 5818 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5819 throws PackageManagerException { 5820 if (pkgSetting.signatures.mSignatures != null) { 5821 // Already existing package. Make sure signatures match 5822 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5823 == PackageManager.SIGNATURE_MATCH; 5824 if (!match) { 5825 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5826 == PackageManager.SIGNATURE_MATCH; 5827 } 5828 if (!match) { 5829 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5830 == PackageManager.SIGNATURE_MATCH; 5831 } 5832 if (!match) { 5833 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5834 + pkg.packageName + " signatures do not match the " 5835 + "previously installed version; ignoring!"); 5836 } 5837 } 5838 5839 // Check for shared user signatures 5840 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5841 // Already existing package. Make sure signatures match 5842 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5843 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5844 if (!match) { 5845 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5846 == PackageManager.SIGNATURE_MATCH; 5847 } 5848 if (!match) { 5849 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5850 == PackageManager.SIGNATURE_MATCH; 5851 } 5852 if (!match) { 5853 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5854 "Package " + pkg.packageName 5855 + " has no signatures that match those in shared user " 5856 + pkgSetting.sharedUser.name + "; ignoring!"); 5857 } 5858 } 5859 } 5860 5861 /** 5862 * Enforces that only the system UID or root's UID can call a method exposed 5863 * via Binder. 5864 * 5865 * @param message used as message if SecurityException is thrown 5866 * @throws SecurityException if the caller is not system or root 5867 */ 5868 private static final void enforceSystemOrRoot(String message) { 5869 final int uid = Binder.getCallingUid(); 5870 if (uid != Process.SYSTEM_UID && uid != 0) { 5871 throw new SecurityException(message); 5872 } 5873 } 5874 5875 @Override 5876 public void performBootDexOpt() { 5877 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5878 5879 // Before everything else, see whether we need to fstrim. 5880 try { 5881 IMountService ms = PackageHelper.getMountService(); 5882 if (ms != null) { 5883 final boolean isUpgrade = isUpgrade(); 5884 boolean doTrim = isUpgrade; 5885 if (doTrim) { 5886 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5887 } else { 5888 final long interval = android.provider.Settings.Global.getLong( 5889 mContext.getContentResolver(), 5890 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5891 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5892 if (interval > 0) { 5893 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5894 if (timeSinceLast > interval) { 5895 doTrim = true; 5896 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5897 + "; running immediately"); 5898 } 5899 } 5900 } 5901 if (doTrim) { 5902 if (!isFirstBoot()) { 5903 try { 5904 ActivityManagerNative.getDefault().showBootMessage( 5905 mContext.getResources().getString( 5906 R.string.android_upgrading_fstrim), true); 5907 } catch (RemoteException e) { 5908 } 5909 } 5910 ms.runMaintenance(); 5911 } 5912 } else { 5913 Slog.e(TAG, "Mount service unavailable!"); 5914 } 5915 } catch (RemoteException e) { 5916 // Can't happen; MountService is local 5917 } 5918 5919 final ArraySet<PackageParser.Package> pkgs; 5920 synchronized (mPackages) { 5921 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5922 } 5923 5924 if (pkgs != null) { 5925 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5926 // in case the device runs out of space. 5927 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5928 // Give priority to core apps. 5929 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5930 PackageParser.Package pkg = it.next(); 5931 if (pkg.coreApp) { 5932 if (DEBUG_DEXOPT) { 5933 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5934 } 5935 sortedPkgs.add(pkg); 5936 it.remove(); 5937 } 5938 } 5939 // Give priority to system apps that listen for pre boot complete. 5940 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5941 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5942 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5943 PackageParser.Package pkg = it.next(); 5944 if (pkgNames.contains(pkg.packageName)) { 5945 if (DEBUG_DEXOPT) { 5946 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5947 } 5948 sortedPkgs.add(pkg); 5949 it.remove(); 5950 } 5951 } 5952 // Give priority to system apps. 5953 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5954 PackageParser.Package pkg = it.next(); 5955 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5956 if (DEBUG_DEXOPT) { 5957 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5958 } 5959 sortedPkgs.add(pkg); 5960 it.remove(); 5961 } 5962 } 5963 // Give priority to updated system apps. 5964 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5965 PackageParser.Package pkg = it.next(); 5966 if (pkg.isUpdatedSystemApp()) { 5967 if (DEBUG_DEXOPT) { 5968 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5969 } 5970 sortedPkgs.add(pkg); 5971 it.remove(); 5972 } 5973 } 5974 // Give priority to apps that listen for boot complete. 5975 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5976 pkgNames = getPackageNamesForIntent(intent); 5977 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5978 PackageParser.Package pkg = it.next(); 5979 if (pkgNames.contains(pkg.packageName)) { 5980 if (DEBUG_DEXOPT) { 5981 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5982 } 5983 sortedPkgs.add(pkg); 5984 it.remove(); 5985 } 5986 } 5987 // Filter out packages that aren't recently used. 5988 filterRecentlyUsedApps(pkgs); 5989 // Add all remaining apps. 5990 for (PackageParser.Package pkg : pkgs) { 5991 if (DEBUG_DEXOPT) { 5992 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5993 } 5994 sortedPkgs.add(pkg); 5995 } 5996 5997 // If we want to be lazy, filter everything that wasn't recently used. 5998 if (mLazyDexOpt) { 5999 filterRecentlyUsedApps(sortedPkgs); 6000 } 6001 6002 int i = 0; 6003 int total = sortedPkgs.size(); 6004 File dataDir = Environment.getDataDirectory(); 6005 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6006 if (lowThreshold == 0) { 6007 throw new IllegalStateException("Invalid low memory threshold"); 6008 } 6009 for (PackageParser.Package pkg : sortedPkgs) { 6010 long usableSpace = dataDir.getUsableSpace(); 6011 if (usableSpace < lowThreshold) { 6012 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6013 break; 6014 } 6015 performBootDexOpt(pkg, ++i, total); 6016 } 6017 } 6018 } 6019 6020 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6021 // Filter out packages that aren't recently used. 6022 // 6023 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6024 // should do a full dexopt. 6025 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6026 int total = pkgs.size(); 6027 int skipped = 0; 6028 long now = System.currentTimeMillis(); 6029 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6030 PackageParser.Package pkg = i.next(); 6031 long then = pkg.mLastPackageUsageTimeInMills; 6032 if (then + mDexOptLRUThresholdInMills < now) { 6033 if (DEBUG_DEXOPT) { 6034 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6035 ((then == 0) ? "never" : new Date(then))); 6036 } 6037 i.remove(); 6038 skipped++; 6039 } 6040 } 6041 if (DEBUG_DEXOPT) { 6042 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6043 } 6044 } 6045 } 6046 6047 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6048 List<ResolveInfo> ris = null; 6049 try { 6050 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6051 intent, null, 0, UserHandle.USER_OWNER); 6052 } catch (RemoteException e) { 6053 } 6054 ArraySet<String> pkgNames = new ArraySet<String>(); 6055 if (ris != null) { 6056 for (ResolveInfo ri : ris) { 6057 pkgNames.add(ri.activityInfo.packageName); 6058 } 6059 } 6060 return pkgNames; 6061 } 6062 6063 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6064 if (DEBUG_DEXOPT) { 6065 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6066 } 6067 if (!isFirstBoot()) { 6068 try { 6069 ActivityManagerNative.getDefault().showBootMessage( 6070 mContext.getResources().getString(R.string.android_upgrading_apk, 6071 curr, total), true); 6072 } catch (RemoteException e) { 6073 } 6074 } 6075 PackageParser.Package p = pkg; 6076 synchronized (mInstallLock) { 6077 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6078 false /* force dex */, false /* defer */, true /* include dependencies */); 6079 } 6080 } 6081 6082 @Override 6083 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6084 return performDexOpt(packageName, instructionSet, false); 6085 } 6086 6087 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6088 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6089 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6090 if (!dexopt && !updateUsage) { 6091 // We aren't going to dexopt or update usage, so bail early. 6092 return false; 6093 } 6094 PackageParser.Package p; 6095 final String targetInstructionSet; 6096 synchronized (mPackages) { 6097 p = mPackages.get(packageName); 6098 if (p == null) { 6099 return false; 6100 } 6101 if (updateUsage) { 6102 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6103 } 6104 mPackageUsage.write(false); 6105 if (!dexopt) { 6106 // We aren't going to dexopt, so bail early. 6107 return false; 6108 } 6109 6110 targetInstructionSet = instructionSet != null ? instructionSet : 6111 getPrimaryInstructionSet(p.applicationInfo); 6112 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6113 return false; 6114 } 6115 } 6116 6117 synchronized (mInstallLock) { 6118 final String[] instructionSets = new String[] { targetInstructionSet }; 6119 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6120 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6121 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6122 } 6123 } 6124 6125 public ArraySet<String> getPackagesThatNeedDexOpt() { 6126 ArraySet<String> pkgs = null; 6127 synchronized (mPackages) { 6128 for (PackageParser.Package p : mPackages.values()) { 6129 if (DEBUG_DEXOPT) { 6130 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6131 } 6132 if (!p.mDexOptPerformed.isEmpty()) { 6133 continue; 6134 } 6135 if (pkgs == null) { 6136 pkgs = new ArraySet<String>(); 6137 } 6138 pkgs.add(p.packageName); 6139 } 6140 } 6141 return pkgs; 6142 } 6143 6144 public void shutdown() { 6145 mPackageUsage.write(true); 6146 } 6147 6148 @Override 6149 public void forceDexOpt(String packageName) { 6150 enforceSystemOrRoot("forceDexOpt"); 6151 6152 PackageParser.Package pkg; 6153 synchronized (mPackages) { 6154 pkg = mPackages.get(packageName); 6155 if (pkg == null) { 6156 throw new IllegalArgumentException("Missing package: " + packageName); 6157 } 6158 } 6159 6160 synchronized (mInstallLock) { 6161 final String[] instructionSets = new String[] { 6162 getPrimaryInstructionSet(pkg.applicationInfo) }; 6163 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6164 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6165 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6166 throw new IllegalStateException("Failed to dexopt: " + res); 6167 } 6168 } 6169 } 6170 6171 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6172 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6173 Slog.w(TAG, "Unable to update from " + oldPkg.name 6174 + " to " + newPkg.packageName 6175 + ": old package not in system partition"); 6176 return false; 6177 } else if (mPackages.get(oldPkg.name) != null) { 6178 Slog.w(TAG, "Unable to update from " + oldPkg.name 6179 + " to " + newPkg.packageName 6180 + ": old package still exists"); 6181 return false; 6182 } 6183 return true; 6184 } 6185 6186 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6187 int[] users = sUserManager.getUserIds(); 6188 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6189 if (res < 0) { 6190 return res; 6191 } 6192 for (int user : users) { 6193 if (user != 0) { 6194 res = mInstaller.createUserData(volumeUuid, packageName, 6195 UserHandle.getUid(user, uid), user, seinfo); 6196 if (res < 0) { 6197 return res; 6198 } 6199 } 6200 } 6201 return res; 6202 } 6203 6204 private int removeDataDirsLI(String volumeUuid, String packageName) { 6205 int[] users = sUserManager.getUserIds(); 6206 int res = 0; 6207 for (int user : users) { 6208 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6209 if (resInner < 0) { 6210 res = resInner; 6211 } 6212 } 6213 6214 return res; 6215 } 6216 6217 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6218 int[] users = sUserManager.getUserIds(); 6219 int res = 0; 6220 for (int user : users) { 6221 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6222 if (resInner < 0) { 6223 res = resInner; 6224 } 6225 } 6226 return res; 6227 } 6228 6229 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6230 PackageParser.Package changingLib) { 6231 if (file.path != null) { 6232 usesLibraryFiles.add(file.path); 6233 return; 6234 } 6235 PackageParser.Package p = mPackages.get(file.apk); 6236 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6237 // If we are doing this while in the middle of updating a library apk, 6238 // then we need to make sure to use that new apk for determining the 6239 // dependencies here. (We haven't yet finished committing the new apk 6240 // to the package manager state.) 6241 if (p == null || p.packageName.equals(changingLib.packageName)) { 6242 p = changingLib; 6243 } 6244 } 6245 if (p != null) { 6246 usesLibraryFiles.addAll(p.getAllCodePaths()); 6247 } 6248 } 6249 6250 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6251 PackageParser.Package changingLib) throws PackageManagerException { 6252 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6253 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6254 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6255 for (int i=0; i<N; i++) { 6256 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6257 if (file == null) { 6258 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6259 "Package " + pkg.packageName + " requires unavailable shared library " 6260 + pkg.usesLibraries.get(i) + "; failing!"); 6261 } 6262 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6263 } 6264 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6265 for (int i=0; i<N; i++) { 6266 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6267 if (file == null) { 6268 Slog.w(TAG, "Package " + pkg.packageName 6269 + " desires unavailable shared library " 6270 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6271 } else { 6272 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6273 } 6274 } 6275 N = usesLibraryFiles.size(); 6276 if (N > 0) { 6277 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6278 } else { 6279 pkg.usesLibraryFiles = null; 6280 } 6281 } 6282 } 6283 6284 private static boolean hasString(List<String> list, List<String> which) { 6285 if (list == null) { 6286 return false; 6287 } 6288 for (int i=list.size()-1; i>=0; i--) { 6289 for (int j=which.size()-1; j>=0; j--) { 6290 if (which.get(j).equals(list.get(i))) { 6291 return true; 6292 } 6293 } 6294 } 6295 return false; 6296 } 6297 6298 private void updateAllSharedLibrariesLPw() { 6299 for (PackageParser.Package pkg : mPackages.values()) { 6300 try { 6301 updateSharedLibrariesLPw(pkg, null); 6302 } catch (PackageManagerException e) { 6303 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6304 } 6305 } 6306 } 6307 6308 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6309 PackageParser.Package changingPkg) { 6310 ArrayList<PackageParser.Package> res = null; 6311 for (PackageParser.Package pkg : mPackages.values()) { 6312 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6313 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6314 if (res == null) { 6315 res = new ArrayList<PackageParser.Package>(); 6316 } 6317 res.add(pkg); 6318 try { 6319 updateSharedLibrariesLPw(pkg, changingPkg); 6320 } catch (PackageManagerException e) { 6321 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6322 } 6323 } 6324 } 6325 return res; 6326 } 6327 6328 /** 6329 * Derive the value of the {@code cpuAbiOverride} based on the provided 6330 * value and an optional stored value from the package settings. 6331 */ 6332 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6333 String cpuAbiOverride = null; 6334 6335 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6336 cpuAbiOverride = null; 6337 } else if (abiOverride != null) { 6338 cpuAbiOverride = abiOverride; 6339 } else if (settings != null) { 6340 cpuAbiOverride = settings.cpuAbiOverrideString; 6341 } 6342 6343 return cpuAbiOverride; 6344 } 6345 6346 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6347 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6348 boolean success = false; 6349 try { 6350 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6351 currentTime, user); 6352 success = true; 6353 return res; 6354 } finally { 6355 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6356 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6357 } 6358 } 6359 } 6360 6361 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6362 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6363 final File scanFile = new File(pkg.codePath); 6364 if (pkg.applicationInfo.getCodePath() == null || 6365 pkg.applicationInfo.getResourcePath() == null) { 6366 // Bail out. The resource and code paths haven't been set. 6367 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6368 "Code and resource paths haven't been set correctly"); 6369 } 6370 6371 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6372 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6373 } else { 6374 // Only allow system apps to be flagged as core apps. 6375 pkg.coreApp = false; 6376 } 6377 6378 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6379 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6380 } 6381 6382 if (mCustomResolverComponentName != null && 6383 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6384 setUpCustomResolverActivity(pkg); 6385 } 6386 6387 if (pkg.packageName.equals("android")) { 6388 synchronized (mPackages) { 6389 if (mAndroidApplication != null) { 6390 Slog.w(TAG, "*************************************************"); 6391 Slog.w(TAG, "Core android package being redefined. Skipping."); 6392 Slog.w(TAG, " file=" + scanFile); 6393 Slog.w(TAG, "*************************************************"); 6394 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6395 "Core android package being redefined. Skipping."); 6396 } 6397 6398 // Set up information for our fall-back user intent resolution activity. 6399 mPlatformPackage = pkg; 6400 pkg.mVersionCode = mSdkVersion; 6401 mAndroidApplication = pkg.applicationInfo; 6402 6403 if (!mResolverReplaced) { 6404 mResolveActivity.applicationInfo = mAndroidApplication; 6405 mResolveActivity.name = ResolverActivity.class.getName(); 6406 mResolveActivity.packageName = mAndroidApplication.packageName; 6407 mResolveActivity.processName = "system:ui"; 6408 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6409 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6410 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6411 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6412 mResolveActivity.exported = true; 6413 mResolveActivity.enabled = true; 6414 mResolveInfo.activityInfo = mResolveActivity; 6415 mResolveInfo.priority = 0; 6416 mResolveInfo.preferredOrder = 0; 6417 mResolveInfo.match = 0; 6418 mResolveComponentName = new ComponentName( 6419 mAndroidApplication.packageName, mResolveActivity.name); 6420 } 6421 } 6422 } 6423 6424 if (DEBUG_PACKAGE_SCANNING) { 6425 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6426 Log.d(TAG, "Scanning package " + pkg.packageName); 6427 } 6428 6429 if (mPackages.containsKey(pkg.packageName) 6430 || mSharedLibraries.containsKey(pkg.packageName)) { 6431 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6432 "Application package " + pkg.packageName 6433 + " already installed. Skipping duplicate."); 6434 } 6435 6436 // If we're only installing presumed-existing packages, require that the 6437 // scanned APK is both already known and at the path previously established 6438 // for it. Previously unknown packages we pick up normally, but if we have an 6439 // a priori expectation about this package's install presence, enforce it. 6440 // With a singular exception for new system packages. When an OTA contains 6441 // a new system package, we allow the codepath to change from a system location 6442 // to the user-installed location. If we don't allow this change, any newer, 6443 // user-installed version of the application will be ignored. 6444 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6445 if (mExpectingBetter.containsKey(pkg.packageName)) { 6446 logCriticalInfo(Log.WARN, 6447 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6448 } else { 6449 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6450 if (known != null) { 6451 if (DEBUG_PACKAGE_SCANNING) { 6452 Log.d(TAG, "Examining " + pkg.codePath 6453 + " and requiring known paths " + known.codePathString 6454 + " & " + known.resourcePathString); 6455 } 6456 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6457 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6458 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6459 "Application package " + pkg.packageName 6460 + " found at " + pkg.applicationInfo.getCodePath() 6461 + " but expected at " + known.codePathString + "; ignoring."); 6462 } 6463 } 6464 } 6465 } 6466 6467 // Initialize package source and resource directories 6468 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6469 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6470 6471 SharedUserSetting suid = null; 6472 PackageSetting pkgSetting = null; 6473 6474 if (!isSystemApp(pkg)) { 6475 // Only system apps can use these features. 6476 pkg.mOriginalPackages = null; 6477 pkg.mRealPackage = null; 6478 pkg.mAdoptPermissions = null; 6479 } 6480 6481 // writer 6482 synchronized (mPackages) { 6483 if (pkg.mSharedUserId != null) { 6484 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6485 if (suid == null) { 6486 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6487 "Creating application package " + pkg.packageName 6488 + " for shared user failed"); 6489 } 6490 if (DEBUG_PACKAGE_SCANNING) { 6491 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6492 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6493 + "): packages=" + suid.packages); 6494 } 6495 } 6496 6497 // Check if we are renaming from an original package name. 6498 PackageSetting origPackage = null; 6499 String realName = null; 6500 if (pkg.mOriginalPackages != null) { 6501 // This package may need to be renamed to a previously 6502 // installed name. Let's check on that... 6503 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6504 if (pkg.mOriginalPackages.contains(renamed)) { 6505 // This package had originally been installed as the 6506 // original name, and we have already taken care of 6507 // transitioning to the new one. Just update the new 6508 // one to continue using the old name. 6509 realName = pkg.mRealPackage; 6510 if (!pkg.packageName.equals(renamed)) { 6511 // Callers into this function may have already taken 6512 // care of renaming the package; only do it here if 6513 // it is not already done. 6514 pkg.setPackageName(renamed); 6515 } 6516 6517 } else { 6518 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6519 if ((origPackage = mSettings.peekPackageLPr( 6520 pkg.mOriginalPackages.get(i))) != null) { 6521 // We do have the package already installed under its 6522 // original name... should we use it? 6523 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6524 // New package is not compatible with original. 6525 origPackage = null; 6526 continue; 6527 } else if (origPackage.sharedUser != null) { 6528 // Make sure uid is compatible between packages. 6529 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6530 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6531 + " to " + pkg.packageName + ": old uid " 6532 + origPackage.sharedUser.name 6533 + " differs from " + pkg.mSharedUserId); 6534 origPackage = null; 6535 continue; 6536 } 6537 } else { 6538 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6539 + pkg.packageName + " to old name " + origPackage.name); 6540 } 6541 break; 6542 } 6543 } 6544 } 6545 } 6546 6547 if (mTransferedPackages.contains(pkg.packageName)) { 6548 Slog.w(TAG, "Package " + pkg.packageName 6549 + " was transferred to another, but its .apk remains"); 6550 } 6551 6552 // Just create the setting, don't add it yet. For already existing packages 6553 // the PkgSetting exists already and doesn't have to be created. 6554 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6555 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6556 pkg.applicationInfo.primaryCpuAbi, 6557 pkg.applicationInfo.secondaryCpuAbi, 6558 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6559 user, false); 6560 if (pkgSetting == null) { 6561 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6562 "Creating application package " + pkg.packageName + " failed"); 6563 } 6564 6565 if (pkgSetting.origPackage != null) { 6566 // If we are first transitioning from an original package, 6567 // fix up the new package's name now. We need to do this after 6568 // looking up the package under its new name, so getPackageLP 6569 // can take care of fiddling things correctly. 6570 pkg.setPackageName(origPackage.name); 6571 6572 // File a report about this. 6573 String msg = "New package " + pkgSetting.realName 6574 + " renamed to replace old package " + pkgSetting.name; 6575 reportSettingsProblem(Log.WARN, msg); 6576 6577 // Make a note of it. 6578 mTransferedPackages.add(origPackage.name); 6579 6580 // No longer need to retain this. 6581 pkgSetting.origPackage = null; 6582 } 6583 6584 if (realName != null) { 6585 // Make a note of it. 6586 mTransferedPackages.add(pkg.packageName); 6587 } 6588 6589 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6590 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6591 } 6592 6593 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6594 // Check all shared libraries and map to their actual file path. 6595 // We only do this here for apps not on a system dir, because those 6596 // are the only ones that can fail an install due to this. We 6597 // will take care of the system apps by updating all of their 6598 // library paths after the scan is done. 6599 updateSharedLibrariesLPw(pkg, null); 6600 } 6601 6602 if (mFoundPolicyFile) { 6603 SELinuxMMAC.assignSeinfoValue(pkg); 6604 } 6605 6606 pkg.applicationInfo.uid = pkgSetting.appId; 6607 pkg.mExtras = pkgSetting; 6608 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6609 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6610 // We just determined the app is signed correctly, so bring 6611 // over the latest parsed certs. 6612 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6613 } else { 6614 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6615 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6616 "Package " + pkg.packageName + " upgrade keys do not match the " 6617 + "previously installed version"); 6618 } else { 6619 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6620 String msg = "System package " + pkg.packageName 6621 + " signature changed; retaining data."; 6622 reportSettingsProblem(Log.WARN, msg); 6623 } 6624 } 6625 } else { 6626 try { 6627 verifySignaturesLP(pkgSetting, pkg); 6628 // We just determined the app is signed correctly, so bring 6629 // over the latest parsed certs. 6630 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6631 } catch (PackageManagerException e) { 6632 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6633 throw e; 6634 } 6635 // The signature has changed, but this package is in the system 6636 // image... let's recover! 6637 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6638 // However... if this package is part of a shared user, but it 6639 // doesn't match the signature of the shared user, let's fail. 6640 // What this means is that you can't change the signatures 6641 // associated with an overall shared user, which doesn't seem all 6642 // that unreasonable. 6643 if (pkgSetting.sharedUser != null) { 6644 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6645 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6646 throw new PackageManagerException( 6647 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6648 "Signature mismatch for shared user : " 6649 + pkgSetting.sharedUser); 6650 } 6651 } 6652 // File a report about this. 6653 String msg = "System package " + pkg.packageName 6654 + " signature changed; retaining data."; 6655 reportSettingsProblem(Log.WARN, msg); 6656 } 6657 } 6658 // Verify that this new package doesn't have any content providers 6659 // that conflict with existing packages. Only do this if the 6660 // package isn't already installed, since we don't want to break 6661 // things that are installed. 6662 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6663 final int N = pkg.providers.size(); 6664 int i; 6665 for (i=0; i<N; i++) { 6666 PackageParser.Provider p = pkg.providers.get(i); 6667 if (p.info.authority != null) { 6668 String names[] = p.info.authority.split(";"); 6669 for (int j = 0; j < names.length; j++) { 6670 if (mProvidersByAuthority.containsKey(names[j])) { 6671 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6672 final String otherPackageName = 6673 ((other != null && other.getComponentName() != null) ? 6674 other.getComponentName().getPackageName() : "?"); 6675 throw new PackageManagerException( 6676 INSTALL_FAILED_CONFLICTING_PROVIDER, 6677 "Can't install because provider name " + names[j] 6678 + " (in package " + pkg.applicationInfo.packageName 6679 + ") is already used by " + otherPackageName); 6680 } 6681 } 6682 } 6683 } 6684 } 6685 6686 if (pkg.mAdoptPermissions != null) { 6687 // This package wants to adopt ownership of permissions from 6688 // another package. 6689 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6690 final String origName = pkg.mAdoptPermissions.get(i); 6691 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6692 if (orig != null) { 6693 if (verifyPackageUpdateLPr(orig, pkg)) { 6694 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6695 + pkg.packageName); 6696 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6697 } 6698 } 6699 } 6700 } 6701 } 6702 6703 final String pkgName = pkg.packageName; 6704 6705 final long scanFileTime = scanFile.lastModified(); 6706 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6707 pkg.applicationInfo.processName = fixProcessName( 6708 pkg.applicationInfo.packageName, 6709 pkg.applicationInfo.processName, 6710 pkg.applicationInfo.uid); 6711 6712 File dataPath; 6713 if (mPlatformPackage == pkg) { 6714 // The system package is special. 6715 dataPath = new File(Environment.getDataDirectory(), "system"); 6716 6717 pkg.applicationInfo.dataDir = dataPath.getPath(); 6718 6719 } else { 6720 // This is a normal package, need to make its data directory. 6721 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6722 UserHandle.USER_OWNER, pkg.packageName); 6723 6724 boolean uidError = false; 6725 if (dataPath.exists()) { 6726 int currentUid = 0; 6727 try { 6728 StructStat stat = Os.stat(dataPath.getPath()); 6729 currentUid = stat.st_uid; 6730 } catch (ErrnoException e) { 6731 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6732 } 6733 6734 // If we have mismatched owners for the data path, we have a problem. 6735 if (currentUid != pkg.applicationInfo.uid) { 6736 boolean recovered = false; 6737 if (currentUid == 0) { 6738 // The directory somehow became owned by root. Wow. 6739 // This is probably because the system was stopped while 6740 // installd was in the middle of messing with its libs 6741 // directory. Ask installd to fix that. 6742 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6743 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6744 if (ret >= 0) { 6745 recovered = true; 6746 String msg = "Package " + pkg.packageName 6747 + " unexpectedly changed to uid 0; recovered to " + 6748 + pkg.applicationInfo.uid; 6749 reportSettingsProblem(Log.WARN, msg); 6750 } 6751 } 6752 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6753 || (scanFlags&SCAN_BOOTING) != 0)) { 6754 // If this is a system app, we can at least delete its 6755 // current data so the application will still work. 6756 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6757 if (ret >= 0) { 6758 // TODO: Kill the processes first 6759 // Old data gone! 6760 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6761 ? "System package " : "Third party package "; 6762 String msg = prefix + pkg.packageName 6763 + " has changed from uid: " 6764 + currentUid + " to " 6765 + pkg.applicationInfo.uid + "; old data erased"; 6766 reportSettingsProblem(Log.WARN, msg); 6767 recovered = true; 6768 6769 // And now re-install the app. 6770 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6771 pkg.applicationInfo.seinfo); 6772 if (ret == -1) { 6773 // Ack should not happen! 6774 msg = prefix + pkg.packageName 6775 + " could not have data directory re-created after delete."; 6776 reportSettingsProblem(Log.WARN, msg); 6777 throw new PackageManagerException( 6778 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6779 } 6780 } 6781 if (!recovered) { 6782 mHasSystemUidErrors = true; 6783 } 6784 } else if (!recovered) { 6785 // If we allow this install to proceed, we will be broken. 6786 // Abort, abort! 6787 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6788 "scanPackageLI"); 6789 } 6790 if (!recovered) { 6791 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6792 + pkg.applicationInfo.uid + "/fs_" 6793 + currentUid; 6794 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6795 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6796 String msg = "Package " + pkg.packageName 6797 + " has mismatched uid: " 6798 + currentUid + " on disk, " 6799 + pkg.applicationInfo.uid + " in settings"; 6800 // writer 6801 synchronized (mPackages) { 6802 mSettings.mReadMessages.append(msg); 6803 mSettings.mReadMessages.append('\n'); 6804 uidError = true; 6805 if (!pkgSetting.uidError) { 6806 reportSettingsProblem(Log.ERROR, msg); 6807 } 6808 } 6809 } 6810 } 6811 pkg.applicationInfo.dataDir = dataPath.getPath(); 6812 if (mShouldRestoreconData) { 6813 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6814 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6815 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6816 } 6817 } else { 6818 if (DEBUG_PACKAGE_SCANNING) { 6819 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6820 Log.v(TAG, "Want this data dir: " + dataPath); 6821 } 6822 //invoke installer to do the actual installation 6823 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6824 pkg.applicationInfo.seinfo); 6825 if (ret < 0) { 6826 // Error from installer 6827 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6828 "Unable to create data dirs [errorCode=" + ret + "]"); 6829 } 6830 6831 if (dataPath.exists()) { 6832 pkg.applicationInfo.dataDir = dataPath.getPath(); 6833 } else { 6834 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6835 pkg.applicationInfo.dataDir = null; 6836 } 6837 } 6838 6839 pkgSetting.uidError = uidError; 6840 } 6841 6842 final String path = scanFile.getPath(); 6843 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6844 6845 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6846 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6847 6848 // Some system apps still use directory structure for native libraries 6849 // in which case we might end up not detecting abi solely based on apk 6850 // structure. Try to detect abi based on directory structure. 6851 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6852 pkg.applicationInfo.primaryCpuAbi == null) { 6853 setBundledAppAbisAndRoots(pkg, pkgSetting); 6854 setNativeLibraryPaths(pkg); 6855 } 6856 6857 } else { 6858 if ((scanFlags & SCAN_MOVE) != 0) { 6859 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6860 // but we already have this packages package info in the PackageSetting. We just 6861 // use that and derive the native library path based on the new codepath. 6862 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6863 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6864 } 6865 6866 // Set native library paths again. For moves, the path will be updated based on the 6867 // ABIs we've determined above. For non-moves, the path will be updated based on the 6868 // ABIs we determined during compilation, but the path will depend on the final 6869 // package path (after the rename away from the stage path). 6870 setNativeLibraryPaths(pkg); 6871 } 6872 6873 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6874 final int[] userIds = sUserManager.getUserIds(); 6875 synchronized (mInstallLock) { 6876 // Make sure all user data directories are ready to roll; we're okay 6877 // if they already exist 6878 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6879 for (int userId : userIds) { 6880 if (userId != 0) { 6881 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6882 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6883 pkg.applicationInfo.seinfo); 6884 } 6885 } 6886 } 6887 6888 // Create a native library symlink only if we have native libraries 6889 // and if the native libraries are 32 bit libraries. We do not provide 6890 // this symlink for 64 bit libraries. 6891 if (pkg.applicationInfo.primaryCpuAbi != null && 6892 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6893 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6894 for (int userId : userIds) { 6895 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6896 nativeLibPath, userId) < 0) { 6897 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6898 "Failed linking native library dir (user=" + userId + ")"); 6899 } 6900 } 6901 } 6902 } 6903 6904 // This is a special case for the "system" package, where the ABI is 6905 // dictated by the zygote configuration (and init.rc). We should keep track 6906 // of this ABI so that we can deal with "normal" applications that run under 6907 // the same UID correctly. 6908 if (mPlatformPackage == pkg) { 6909 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6910 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6911 } 6912 6913 // If there's a mismatch between the abi-override in the package setting 6914 // and the abiOverride specified for the install. Warn about this because we 6915 // would've already compiled the app without taking the package setting into 6916 // account. 6917 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6918 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6919 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6920 " for package: " + pkg.packageName); 6921 } 6922 } 6923 6924 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6925 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6926 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6927 6928 // Copy the derived override back to the parsed package, so that we can 6929 // update the package settings accordingly. 6930 pkg.cpuAbiOverride = cpuAbiOverride; 6931 6932 if (DEBUG_ABI_SELECTION) { 6933 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6934 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6935 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6936 } 6937 6938 // Push the derived path down into PackageSettings so we know what to 6939 // clean up at uninstall time. 6940 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6941 6942 if (DEBUG_ABI_SELECTION) { 6943 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6944 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6945 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6946 } 6947 6948 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6949 // We don't do this here during boot because we can do it all 6950 // at once after scanning all existing packages. 6951 // 6952 // We also do this *before* we perform dexopt on this package, so that 6953 // we can avoid redundant dexopts, and also to make sure we've got the 6954 // code and package path correct. 6955 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6956 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6957 } 6958 6959 if ((scanFlags & SCAN_NO_DEX) == 0) { 6960 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6961 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6962 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6963 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6964 } 6965 } 6966 if (mFactoryTest && pkg.requestedPermissions.contains( 6967 android.Manifest.permission.FACTORY_TEST)) { 6968 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6969 } 6970 6971 ArrayList<PackageParser.Package> clientLibPkgs = null; 6972 6973 // writer 6974 synchronized (mPackages) { 6975 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6976 // Only system apps can add new shared libraries. 6977 if (pkg.libraryNames != null) { 6978 for (int i=0; i<pkg.libraryNames.size(); i++) { 6979 String name = pkg.libraryNames.get(i); 6980 boolean allowed = false; 6981 if (pkg.isUpdatedSystemApp()) { 6982 // New library entries can only be added through the 6983 // system image. This is important to get rid of a lot 6984 // of nasty edge cases: for example if we allowed a non- 6985 // system update of the app to add a library, then uninstalling 6986 // the update would make the library go away, and assumptions 6987 // we made such as through app install filtering would now 6988 // have allowed apps on the device which aren't compatible 6989 // with it. Better to just have the restriction here, be 6990 // conservative, and create many fewer cases that can negatively 6991 // impact the user experience. 6992 final PackageSetting sysPs = mSettings 6993 .getDisabledSystemPkgLPr(pkg.packageName); 6994 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6995 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6996 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6997 allowed = true; 6998 allowed = true; 6999 break; 7000 } 7001 } 7002 } 7003 } else { 7004 allowed = true; 7005 } 7006 if (allowed) { 7007 if (!mSharedLibraries.containsKey(name)) { 7008 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7009 } else if (!name.equals(pkg.packageName)) { 7010 Slog.w(TAG, "Package " + pkg.packageName + " library " 7011 + name + " already exists; skipping"); 7012 } 7013 } else { 7014 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7015 + name + " that is not declared on system image; skipping"); 7016 } 7017 } 7018 if ((scanFlags&SCAN_BOOTING) == 0) { 7019 // If we are not booting, we need to update any applications 7020 // that are clients of our shared library. If we are booting, 7021 // this will all be done once the scan is complete. 7022 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7023 } 7024 } 7025 } 7026 } 7027 7028 // We also need to dexopt any apps that are dependent on this library. Note that 7029 // if these fail, we should abort the install since installing the library will 7030 // result in some apps being broken. 7031 if (clientLibPkgs != null) { 7032 if ((scanFlags & SCAN_NO_DEX) == 0) { 7033 for (int i = 0; i < clientLibPkgs.size(); i++) { 7034 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7035 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7036 null /* instruction sets */, forceDex, 7037 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7038 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7039 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7040 "scanPackageLI failed to dexopt clientLibPkgs"); 7041 } 7042 } 7043 } 7044 } 7045 7046 // Also need to kill any apps that are dependent on the library. 7047 if (clientLibPkgs != null) { 7048 for (int i=0; i<clientLibPkgs.size(); i++) { 7049 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7050 killApplication(clientPkg.applicationInfo.packageName, 7051 clientPkg.applicationInfo.uid, "update lib"); 7052 } 7053 } 7054 7055 // Make sure we're not adding any bogus keyset info 7056 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7057 ksms.assertScannedPackageValid(pkg); 7058 7059 // writer 7060 synchronized (mPackages) { 7061 // We don't expect installation to fail beyond this point 7062 7063 // Add the new setting to mSettings 7064 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7065 // Add the new setting to mPackages 7066 mPackages.put(pkg.applicationInfo.packageName, pkg); 7067 // Make sure we don't accidentally delete its data. 7068 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7069 while (iter.hasNext()) { 7070 PackageCleanItem item = iter.next(); 7071 if (pkgName.equals(item.packageName)) { 7072 iter.remove(); 7073 } 7074 } 7075 7076 // Take care of first install / last update times. 7077 if (currentTime != 0) { 7078 if (pkgSetting.firstInstallTime == 0) { 7079 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7080 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7081 pkgSetting.lastUpdateTime = currentTime; 7082 } 7083 } else if (pkgSetting.firstInstallTime == 0) { 7084 // We need *something*. Take time time stamp of the file. 7085 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7086 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7087 if (scanFileTime != pkgSetting.timeStamp) { 7088 // A package on the system image has changed; consider this 7089 // to be an update. 7090 pkgSetting.lastUpdateTime = scanFileTime; 7091 } 7092 } 7093 7094 // Add the package's KeySets to the global KeySetManagerService 7095 ksms.addScannedPackageLPw(pkg); 7096 7097 int N = pkg.providers.size(); 7098 StringBuilder r = null; 7099 int i; 7100 for (i=0; i<N; i++) { 7101 PackageParser.Provider p = pkg.providers.get(i); 7102 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7103 p.info.processName, pkg.applicationInfo.uid); 7104 mProviders.addProvider(p); 7105 p.syncable = p.info.isSyncable; 7106 if (p.info.authority != null) { 7107 String names[] = p.info.authority.split(";"); 7108 p.info.authority = null; 7109 for (int j = 0; j < names.length; j++) { 7110 if (j == 1 && p.syncable) { 7111 // We only want the first authority for a provider to possibly be 7112 // syncable, so if we already added this provider using a different 7113 // authority clear the syncable flag. We copy the provider before 7114 // changing it because the mProviders object contains a reference 7115 // to a provider that we don't want to change. 7116 // Only do this for the second authority since the resulting provider 7117 // object can be the same for all future authorities for this provider. 7118 p = new PackageParser.Provider(p); 7119 p.syncable = false; 7120 } 7121 if (!mProvidersByAuthority.containsKey(names[j])) { 7122 mProvidersByAuthority.put(names[j], p); 7123 if (p.info.authority == null) { 7124 p.info.authority = names[j]; 7125 } else { 7126 p.info.authority = p.info.authority + ";" + names[j]; 7127 } 7128 if (DEBUG_PACKAGE_SCANNING) { 7129 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7130 Log.d(TAG, "Registered content provider: " + names[j] 7131 + ", className = " + p.info.name + ", isSyncable = " 7132 + p.info.isSyncable); 7133 } 7134 } else { 7135 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7136 Slog.w(TAG, "Skipping provider name " + names[j] + 7137 " (in package " + pkg.applicationInfo.packageName + 7138 "): name already used by " 7139 + ((other != null && other.getComponentName() != null) 7140 ? other.getComponentName().getPackageName() : "?")); 7141 } 7142 } 7143 } 7144 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7145 if (r == null) { 7146 r = new StringBuilder(256); 7147 } else { 7148 r.append(' '); 7149 } 7150 r.append(p.info.name); 7151 } 7152 } 7153 if (r != null) { 7154 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7155 } 7156 7157 N = pkg.services.size(); 7158 r = null; 7159 for (i=0; i<N; i++) { 7160 PackageParser.Service s = pkg.services.get(i); 7161 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7162 s.info.processName, pkg.applicationInfo.uid); 7163 mServices.addService(s); 7164 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7165 if (r == null) { 7166 r = new StringBuilder(256); 7167 } else { 7168 r.append(' '); 7169 } 7170 r.append(s.info.name); 7171 } 7172 } 7173 if (r != null) { 7174 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7175 } 7176 7177 N = pkg.receivers.size(); 7178 r = null; 7179 for (i=0; i<N; i++) { 7180 PackageParser.Activity a = pkg.receivers.get(i); 7181 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7182 a.info.processName, pkg.applicationInfo.uid); 7183 mReceivers.addActivity(a, "receiver"); 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(a.info.name); 7191 } 7192 } 7193 if (r != null) { 7194 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7195 } 7196 7197 N = pkg.activities.size(); 7198 r = null; 7199 for (i=0; i<N; i++) { 7200 PackageParser.Activity a = pkg.activities.get(i); 7201 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7202 a.info.processName, pkg.applicationInfo.uid); 7203 mActivities.addActivity(a, "activity"); 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(a.info.name); 7211 } 7212 } 7213 if (r != null) { 7214 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7215 } 7216 7217 N = pkg.permissionGroups.size(); 7218 r = null; 7219 for (i=0; i<N; i++) { 7220 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7221 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7222 if (cur == null) { 7223 mPermissionGroups.put(pg.info.name, pg); 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(pg.info.name); 7231 } 7232 } else { 7233 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7234 + pg.info.packageName + " ignored: original from " 7235 + cur.info.packageName); 7236 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7237 if (r == null) { 7238 r = new StringBuilder(256); 7239 } else { 7240 r.append(' '); 7241 } 7242 r.append("DUP:"); 7243 r.append(pg.info.name); 7244 } 7245 } 7246 } 7247 if (r != null) { 7248 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7249 } 7250 7251 N = pkg.permissions.size(); 7252 r = null; 7253 for (i=0; i<N; i++) { 7254 PackageParser.Permission p = pkg.permissions.get(i); 7255 7256 // Now that permission groups have a special meaning, we ignore permission 7257 // groups for legacy apps to prevent unexpected behavior. In particular, 7258 // permissions for one app being granted to someone just becuase they happen 7259 // to be in a group defined by another app (before this had no implications). 7260 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7261 p.group = mPermissionGroups.get(p.info.group); 7262 // Warn for a permission in an unknown group. 7263 if (p.info.group != null && p.group == null) { 7264 Slog.w(TAG, "Permission " + p.info.name + " from package " 7265 + p.info.packageName + " in an unknown group " + p.info.group); 7266 } 7267 } 7268 7269 ArrayMap<String, BasePermission> permissionMap = 7270 p.tree ? mSettings.mPermissionTrees 7271 : mSettings.mPermissions; 7272 BasePermission bp = permissionMap.get(p.info.name); 7273 7274 // Allow system apps to redefine non-system permissions 7275 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7276 final boolean currentOwnerIsSystem = (bp.perm != null 7277 && isSystemApp(bp.perm.owner)); 7278 if (isSystemApp(p.owner)) { 7279 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7280 // It's a built-in permission and no owner, take ownership now 7281 bp.packageSetting = pkgSetting; 7282 bp.perm = p; 7283 bp.uid = pkg.applicationInfo.uid; 7284 bp.sourcePackage = p.info.packageName; 7285 } else if (!currentOwnerIsSystem) { 7286 String msg = "New decl " + p.owner + " of permission " 7287 + p.info.name + " is system; overriding " + bp.sourcePackage; 7288 reportSettingsProblem(Log.WARN, msg); 7289 bp = null; 7290 } 7291 } 7292 } 7293 7294 if (bp == null) { 7295 bp = new BasePermission(p.info.name, p.info.packageName, 7296 BasePermission.TYPE_NORMAL); 7297 permissionMap.put(p.info.name, bp); 7298 } 7299 7300 if (bp.perm == null) { 7301 if (bp.sourcePackage == null 7302 || bp.sourcePackage.equals(p.info.packageName)) { 7303 BasePermission tree = findPermissionTreeLP(p.info.name); 7304 if (tree == null 7305 || tree.sourcePackage.equals(p.info.packageName)) { 7306 bp.packageSetting = pkgSetting; 7307 bp.perm = p; 7308 bp.uid = pkg.applicationInfo.uid; 7309 bp.sourcePackage = p.info.packageName; 7310 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7311 if (r == null) { 7312 r = new StringBuilder(256); 7313 } else { 7314 r.append(' '); 7315 } 7316 r.append(p.info.name); 7317 } 7318 } else { 7319 Slog.w(TAG, "Permission " + p.info.name + " from package " 7320 + p.info.packageName + " ignored: base tree " 7321 + tree.name + " is from package " 7322 + tree.sourcePackage); 7323 } 7324 } else { 7325 Slog.w(TAG, "Permission " + p.info.name + " from package " 7326 + p.info.packageName + " ignored: original from " 7327 + bp.sourcePackage); 7328 } 7329 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7330 if (r == null) { 7331 r = new StringBuilder(256); 7332 } else { 7333 r.append(' '); 7334 } 7335 r.append("DUP:"); 7336 r.append(p.info.name); 7337 } 7338 if (bp.perm == p) { 7339 bp.protectionLevel = p.info.protectionLevel; 7340 } 7341 } 7342 7343 if (r != null) { 7344 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7345 } 7346 7347 N = pkg.instrumentation.size(); 7348 r = null; 7349 for (i=0; i<N; i++) { 7350 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7351 a.info.packageName = pkg.applicationInfo.packageName; 7352 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7353 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7354 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7355 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7356 a.info.dataDir = pkg.applicationInfo.dataDir; 7357 7358 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7359 // need other information about the application, like the ABI and what not ? 7360 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7361 mInstrumentation.put(a.getComponentName(), a); 7362 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7363 if (r == null) { 7364 r = new StringBuilder(256); 7365 } else { 7366 r.append(' '); 7367 } 7368 r.append(a.info.name); 7369 } 7370 } 7371 if (r != null) { 7372 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7373 } 7374 7375 if (pkg.protectedBroadcasts != null) { 7376 N = pkg.protectedBroadcasts.size(); 7377 for (i=0; i<N; i++) { 7378 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7379 } 7380 } 7381 7382 pkgSetting.setTimeStamp(scanFileTime); 7383 7384 // Create idmap files for pairs of (packages, overlay packages). 7385 // Note: "android", ie framework-res.apk, is handled by native layers. 7386 if (pkg.mOverlayTarget != null) { 7387 // This is an overlay package. 7388 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7389 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7390 mOverlays.put(pkg.mOverlayTarget, 7391 new ArrayMap<String, PackageParser.Package>()); 7392 } 7393 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7394 map.put(pkg.packageName, pkg); 7395 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7396 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7397 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7398 "scanPackageLI failed to createIdmap"); 7399 } 7400 } 7401 } else if (mOverlays.containsKey(pkg.packageName) && 7402 !pkg.packageName.equals("android")) { 7403 // This is a regular package, with one or more known overlay packages. 7404 createIdmapsForPackageLI(pkg); 7405 } 7406 } 7407 7408 return pkg; 7409 } 7410 7411 /** 7412 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7413 * is derived purely on the basis of the contents of {@code scanFile} and 7414 * {@code cpuAbiOverride}. 7415 * 7416 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7417 */ 7418 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7419 String cpuAbiOverride, boolean extractLibs) 7420 throws PackageManagerException { 7421 // TODO: We can probably be smarter about this stuff. For installed apps, 7422 // we can calculate this information at install time once and for all. For 7423 // system apps, we can probably assume that this information doesn't change 7424 // after the first boot scan. As things stand, we do lots of unnecessary work. 7425 7426 // Give ourselves some initial paths; we'll come back for another 7427 // pass once we've determined ABI below. 7428 setNativeLibraryPaths(pkg); 7429 7430 // We would never need to extract libs for forward-locked and external packages, 7431 // since the container service will do it for us. We shouldn't attempt to 7432 // extract libs from system app when it was not updated. 7433 if (pkg.isForwardLocked() || isExternal(pkg) || 7434 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7435 extractLibs = false; 7436 } 7437 7438 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7439 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7440 7441 NativeLibraryHelper.Handle handle = null; 7442 try { 7443 handle = NativeLibraryHelper.Handle.create(pkg); 7444 // TODO(multiArch): This can be null for apps that didn't go through the 7445 // usual installation process. We can calculate it again, like we 7446 // do during install time. 7447 // 7448 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7449 // unnecessary. 7450 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7451 7452 // Null out the abis so that they can be recalculated. 7453 pkg.applicationInfo.primaryCpuAbi = null; 7454 pkg.applicationInfo.secondaryCpuAbi = null; 7455 if (isMultiArch(pkg.applicationInfo)) { 7456 // Warn if we've set an abiOverride for multi-lib packages.. 7457 // By definition, we need to copy both 32 and 64 bit libraries for 7458 // such packages. 7459 if (pkg.cpuAbiOverride != null 7460 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7461 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7462 } 7463 7464 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7465 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7466 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7467 if (extractLibs) { 7468 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7469 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7470 useIsaSpecificSubdirs); 7471 } else { 7472 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7473 } 7474 } 7475 7476 maybeThrowExceptionForMultiArchCopy( 7477 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7478 7479 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7480 if (extractLibs) { 7481 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7482 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7483 useIsaSpecificSubdirs); 7484 } else { 7485 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7486 } 7487 } 7488 7489 maybeThrowExceptionForMultiArchCopy( 7490 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7491 7492 if (abi64 >= 0) { 7493 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7494 } 7495 7496 if (abi32 >= 0) { 7497 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7498 if (abi64 >= 0) { 7499 pkg.applicationInfo.secondaryCpuAbi = abi; 7500 } else { 7501 pkg.applicationInfo.primaryCpuAbi = abi; 7502 } 7503 } 7504 } else { 7505 String[] abiList = (cpuAbiOverride != null) ? 7506 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7507 7508 // Enable gross and lame hacks for apps that are built with old 7509 // SDK tools. We must scan their APKs for renderscript bitcode and 7510 // not launch them if it's present. Don't bother checking on devices 7511 // that don't have 64 bit support. 7512 boolean needsRenderScriptOverride = false; 7513 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7514 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7515 abiList = Build.SUPPORTED_32_BIT_ABIS; 7516 needsRenderScriptOverride = true; 7517 } 7518 7519 final int copyRet; 7520 if (extractLibs) { 7521 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7522 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7523 } else { 7524 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7525 } 7526 7527 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7528 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7529 "Error unpackaging native libs for app, errorCode=" + copyRet); 7530 } 7531 7532 if (copyRet >= 0) { 7533 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7534 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7535 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7536 } else if (needsRenderScriptOverride) { 7537 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7538 } 7539 } 7540 } catch (IOException ioe) { 7541 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7542 } finally { 7543 IoUtils.closeQuietly(handle); 7544 } 7545 7546 // Now that we've calculated the ABIs and determined if it's an internal app, 7547 // we will go ahead and populate the nativeLibraryPath. 7548 setNativeLibraryPaths(pkg); 7549 } 7550 7551 /** 7552 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7553 * i.e, so that all packages can be run inside a single process if required. 7554 * 7555 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7556 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7557 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7558 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7559 * updating a package that belongs to a shared user. 7560 * 7561 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7562 * adds unnecessary complexity. 7563 */ 7564 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7565 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7566 String requiredInstructionSet = null; 7567 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7568 requiredInstructionSet = VMRuntime.getInstructionSet( 7569 scannedPackage.applicationInfo.primaryCpuAbi); 7570 } 7571 7572 PackageSetting requirer = null; 7573 for (PackageSetting ps : packagesForUser) { 7574 // If packagesForUser contains scannedPackage, we skip it. This will happen 7575 // when scannedPackage is an update of an existing package. Without this check, 7576 // we will never be able to change the ABI of any package belonging to a shared 7577 // user, even if it's compatible with other packages. 7578 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7579 if (ps.primaryCpuAbiString == null) { 7580 continue; 7581 } 7582 7583 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7584 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7585 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7586 // this but there's not much we can do. 7587 String errorMessage = "Instruction set mismatch, " 7588 + ((requirer == null) ? "[caller]" : requirer) 7589 + " requires " + requiredInstructionSet + " whereas " + ps 7590 + " requires " + instructionSet; 7591 Slog.w(TAG, errorMessage); 7592 } 7593 7594 if (requiredInstructionSet == null) { 7595 requiredInstructionSet = instructionSet; 7596 requirer = ps; 7597 } 7598 } 7599 } 7600 7601 if (requiredInstructionSet != null) { 7602 String adjustedAbi; 7603 if (requirer != null) { 7604 // requirer != null implies that either scannedPackage was null or that scannedPackage 7605 // did not require an ABI, in which case we have to adjust scannedPackage to match 7606 // the ABI of the set (which is the same as requirer's ABI) 7607 adjustedAbi = requirer.primaryCpuAbiString; 7608 if (scannedPackage != null) { 7609 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7610 } 7611 } else { 7612 // requirer == null implies that we're updating all ABIs in the set to 7613 // match scannedPackage. 7614 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7615 } 7616 7617 for (PackageSetting ps : packagesForUser) { 7618 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7619 if (ps.primaryCpuAbiString != null) { 7620 continue; 7621 } 7622 7623 ps.primaryCpuAbiString = adjustedAbi; 7624 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7625 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7626 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7627 7628 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7629 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7630 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7631 ps.primaryCpuAbiString = null; 7632 ps.pkg.applicationInfo.primaryCpuAbi = null; 7633 return; 7634 } else { 7635 mInstaller.rmdex(ps.codePathString, 7636 getDexCodeInstructionSet(getPreferredInstructionSet())); 7637 } 7638 } 7639 } 7640 } 7641 } 7642 } 7643 7644 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7645 synchronized (mPackages) { 7646 mResolverReplaced = true; 7647 // Set up information for custom user intent resolution activity. 7648 mResolveActivity.applicationInfo = pkg.applicationInfo; 7649 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7650 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7651 mResolveActivity.processName = pkg.applicationInfo.packageName; 7652 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7653 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7654 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7655 mResolveActivity.theme = 0; 7656 mResolveActivity.exported = true; 7657 mResolveActivity.enabled = true; 7658 mResolveInfo.activityInfo = mResolveActivity; 7659 mResolveInfo.priority = 0; 7660 mResolveInfo.preferredOrder = 0; 7661 mResolveInfo.match = 0; 7662 mResolveComponentName = mCustomResolverComponentName; 7663 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7664 mResolveComponentName); 7665 } 7666 } 7667 7668 private static String calculateBundledApkRoot(final String codePathString) { 7669 final File codePath = new File(codePathString); 7670 final File codeRoot; 7671 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7672 codeRoot = Environment.getRootDirectory(); 7673 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7674 codeRoot = Environment.getOemDirectory(); 7675 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7676 codeRoot = Environment.getVendorDirectory(); 7677 } else { 7678 // Unrecognized code path; take its top real segment as the apk root: 7679 // e.g. /something/app/blah.apk => /something 7680 try { 7681 File f = codePath.getCanonicalFile(); 7682 File parent = f.getParentFile(); // non-null because codePath is a file 7683 File tmp; 7684 while ((tmp = parent.getParentFile()) != null) { 7685 f = parent; 7686 parent = tmp; 7687 } 7688 codeRoot = f; 7689 Slog.w(TAG, "Unrecognized code path " 7690 + codePath + " - using " + codeRoot); 7691 } catch (IOException e) { 7692 // Can't canonicalize the code path -- shenanigans? 7693 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7694 return Environment.getRootDirectory().getPath(); 7695 } 7696 } 7697 return codeRoot.getPath(); 7698 } 7699 7700 /** 7701 * Derive and set the location of native libraries for the given package, 7702 * which varies depending on where and how the package was installed. 7703 */ 7704 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7705 final ApplicationInfo info = pkg.applicationInfo; 7706 final String codePath = pkg.codePath; 7707 final File codeFile = new File(codePath); 7708 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7709 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7710 7711 info.nativeLibraryRootDir = null; 7712 info.nativeLibraryRootRequiresIsa = false; 7713 info.nativeLibraryDir = null; 7714 info.secondaryNativeLibraryDir = null; 7715 7716 if (isApkFile(codeFile)) { 7717 // Monolithic install 7718 if (bundledApp) { 7719 // If "/system/lib64/apkname" exists, assume that is the per-package 7720 // native library directory to use; otherwise use "/system/lib/apkname". 7721 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7722 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7723 getPrimaryInstructionSet(info)); 7724 7725 // This is a bundled system app so choose the path based on the ABI. 7726 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7727 // is just the default path. 7728 final String apkName = deriveCodePathName(codePath); 7729 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7730 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7731 apkName).getAbsolutePath(); 7732 7733 if (info.secondaryCpuAbi != null) { 7734 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7735 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7736 secondaryLibDir, apkName).getAbsolutePath(); 7737 } 7738 } else if (asecApp) { 7739 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7740 .getAbsolutePath(); 7741 } else { 7742 final String apkName = deriveCodePathName(codePath); 7743 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7744 .getAbsolutePath(); 7745 } 7746 7747 info.nativeLibraryRootRequiresIsa = false; 7748 info.nativeLibraryDir = info.nativeLibraryRootDir; 7749 } else { 7750 // Cluster install 7751 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7752 info.nativeLibraryRootRequiresIsa = true; 7753 7754 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7755 getPrimaryInstructionSet(info)).getAbsolutePath(); 7756 7757 if (info.secondaryCpuAbi != null) { 7758 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7759 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7760 } 7761 } 7762 } 7763 7764 /** 7765 * Calculate the abis and roots for a bundled app. These can uniquely 7766 * be determined from the contents of the system partition, i.e whether 7767 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7768 * of this information, and instead assume that the system was built 7769 * sensibly. 7770 */ 7771 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7772 PackageSetting pkgSetting) { 7773 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7774 7775 // If "/system/lib64/apkname" exists, assume that is the per-package 7776 // native library directory to use; otherwise use "/system/lib/apkname". 7777 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7778 setBundledAppAbi(pkg, apkRoot, apkName); 7779 // pkgSetting might be null during rescan following uninstall of updates 7780 // to a bundled app, so accommodate that possibility. The settings in 7781 // that case will be established later from the parsed package. 7782 // 7783 // If the settings aren't null, sync them up with what we've just derived. 7784 // note that apkRoot isn't stored in the package settings. 7785 if (pkgSetting != null) { 7786 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7787 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7788 } 7789 } 7790 7791 /** 7792 * Deduces the ABI of a bundled app and sets the relevant fields on the 7793 * parsed pkg object. 7794 * 7795 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7796 * under which system libraries are installed. 7797 * @param apkName the name of the installed package. 7798 */ 7799 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7800 final File codeFile = new File(pkg.codePath); 7801 7802 final boolean has64BitLibs; 7803 final boolean has32BitLibs; 7804 if (isApkFile(codeFile)) { 7805 // Monolithic install 7806 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7807 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7808 } else { 7809 // Cluster install 7810 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7811 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7812 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7813 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7814 has64BitLibs = (new File(rootDir, isa)).exists(); 7815 } else { 7816 has64BitLibs = false; 7817 } 7818 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7819 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7820 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7821 has32BitLibs = (new File(rootDir, isa)).exists(); 7822 } else { 7823 has32BitLibs = false; 7824 } 7825 } 7826 7827 if (has64BitLibs && !has32BitLibs) { 7828 // The package has 64 bit libs, but not 32 bit libs. Its primary 7829 // ABI should be 64 bit. We can safely assume here that the bundled 7830 // native libraries correspond to the most preferred ABI in the list. 7831 7832 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7833 pkg.applicationInfo.secondaryCpuAbi = null; 7834 } else if (has32BitLibs && !has64BitLibs) { 7835 // The package has 32 bit libs but not 64 bit libs. Its primary 7836 // ABI should be 32 bit. 7837 7838 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7839 pkg.applicationInfo.secondaryCpuAbi = null; 7840 } else if (has32BitLibs && has64BitLibs) { 7841 // The application has both 64 and 32 bit bundled libraries. We check 7842 // here that the app declares multiArch support, and warn if it doesn't. 7843 // 7844 // We will be lenient here and record both ABIs. The primary will be the 7845 // ABI that's higher on the list, i.e, a device that's configured to prefer 7846 // 64 bit apps will see a 64 bit primary ABI, 7847 7848 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7849 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7850 } 7851 7852 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7853 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7854 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7855 } else { 7856 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7857 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7858 } 7859 } else { 7860 pkg.applicationInfo.primaryCpuAbi = null; 7861 pkg.applicationInfo.secondaryCpuAbi = null; 7862 } 7863 } 7864 7865 private void killApplication(String pkgName, int appId, String reason) { 7866 // Request the ActivityManager to kill the process(only for existing packages) 7867 // so that we do not end up in a confused state while the user is still using the older 7868 // version of the application while the new one gets installed. 7869 IActivityManager am = ActivityManagerNative.getDefault(); 7870 if (am != null) { 7871 try { 7872 am.killApplicationWithAppId(pkgName, appId, reason); 7873 } catch (RemoteException e) { 7874 } 7875 } 7876 } 7877 7878 void removePackageLI(PackageSetting ps, boolean chatty) { 7879 if (DEBUG_INSTALL) { 7880 if (chatty) 7881 Log.d(TAG, "Removing package " + ps.name); 7882 } 7883 7884 // writer 7885 synchronized (mPackages) { 7886 mPackages.remove(ps.name); 7887 final PackageParser.Package pkg = ps.pkg; 7888 if (pkg != null) { 7889 cleanPackageDataStructuresLILPw(pkg, chatty); 7890 } 7891 } 7892 } 7893 7894 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7895 if (DEBUG_INSTALL) { 7896 if (chatty) 7897 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7898 } 7899 7900 // writer 7901 synchronized (mPackages) { 7902 mPackages.remove(pkg.applicationInfo.packageName); 7903 cleanPackageDataStructuresLILPw(pkg, chatty); 7904 } 7905 } 7906 7907 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7908 int N = pkg.providers.size(); 7909 StringBuilder r = null; 7910 int i; 7911 for (i=0; i<N; i++) { 7912 PackageParser.Provider p = pkg.providers.get(i); 7913 mProviders.removeProvider(p); 7914 if (p.info.authority == null) { 7915 7916 /* There was another ContentProvider with this authority when 7917 * this app was installed so this authority is null, 7918 * Ignore it as we don't have to unregister the provider. 7919 */ 7920 continue; 7921 } 7922 String names[] = p.info.authority.split(";"); 7923 for (int j = 0; j < names.length; j++) { 7924 if (mProvidersByAuthority.get(names[j]) == p) { 7925 mProvidersByAuthority.remove(names[j]); 7926 if (DEBUG_REMOVE) { 7927 if (chatty) 7928 Log.d(TAG, "Unregistered content provider: " + names[j] 7929 + ", className = " + p.info.name + ", isSyncable = " 7930 + p.info.isSyncable); 7931 } 7932 } 7933 } 7934 if (DEBUG_REMOVE && chatty) { 7935 if (r == null) { 7936 r = new StringBuilder(256); 7937 } else { 7938 r.append(' '); 7939 } 7940 r.append(p.info.name); 7941 } 7942 } 7943 if (r != null) { 7944 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7945 } 7946 7947 N = pkg.services.size(); 7948 r = null; 7949 for (i=0; i<N; i++) { 7950 PackageParser.Service s = pkg.services.get(i); 7951 mServices.removeService(s); 7952 if (chatty) { 7953 if (r == null) { 7954 r = new StringBuilder(256); 7955 } else { 7956 r.append(' '); 7957 } 7958 r.append(s.info.name); 7959 } 7960 } 7961 if (r != null) { 7962 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7963 } 7964 7965 N = pkg.receivers.size(); 7966 r = null; 7967 for (i=0; i<N; i++) { 7968 PackageParser.Activity a = pkg.receivers.get(i); 7969 mReceivers.removeActivity(a, "receiver"); 7970 if (DEBUG_REMOVE && chatty) { 7971 if (r == null) { 7972 r = new StringBuilder(256); 7973 } else { 7974 r.append(' '); 7975 } 7976 r.append(a.info.name); 7977 } 7978 } 7979 if (r != null) { 7980 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7981 } 7982 7983 N = pkg.activities.size(); 7984 r = null; 7985 for (i=0; i<N; i++) { 7986 PackageParser.Activity a = pkg.activities.get(i); 7987 mActivities.removeActivity(a, "activity"); 7988 if (DEBUG_REMOVE && chatty) { 7989 if (r == null) { 7990 r = new StringBuilder(256); 7991 } else { 7992 r.append(' '); 7993 } 7994 r.append(a.info.name); 7995 } 7996 } 7997 if (r != null) { 7998 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7999 } 8000 8001 N = pkg.permissions.size(); 8002 r = null; 8003 for (i=0; i<N; i++) { 8004 PackageParser.Permission p = pkg.permissions.get(i); 8005 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8006 if (bp == null) { 8007 bp = mSettings.mPermissionTrees.get(p.info.name); 8008 } 8009 if (bp != null && bp.perm == p) { 8010 bp.perm = null; 8011 if (DEBUG_REMOVE && chatty) { 8012 if (r == null) { 8013 r = new StringBuilder(256); 8014 } else { 8015 r.append(' '); 8016 } 8017 r.append(p.info.name); 8018 } 8019 } 8020 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8021 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8022 if (appOpPerms != null) { 8023 appOpPerms.remove(pkg.packageName); 8024 } 8025 } 8026 } 8027 if (r != null) { 8028 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8029 } 8030 8031 N = pkg.requestedPermissions.size(); 8032 r = null; 8033 for (i=0; i<N; i++) { 8034 String perm = pkg.requestedPermissions.get(i); 8035 BasePermission bp = mSettings.mPermissions.get(perm); 8036 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8037 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8038 if (appOpPerms != null) { 8039 appOpPerms.remove(pkg.packageName); 8040 if (appOpPerms.isEmpty()) { 8041 mAppOpPermissionPackages.remove(perm); 8042 } 8043 } 8044 } 8045 } 8046 if (r != null) { 8047 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8048 } 8049 8050 N = pkg.instrumentation.size(); 8051 r = null; 8052 for (i=0; i<N; i++) { 8053 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8054 mInstrumentation.remove(a.getComponentName()); 8055 if (DEBUG_REMOVE && chatty) { 8056 if (r == null) { 8057 r = new StringBuilder(256); 8058 } else { 8059 r.append(' '); 8060 } 8061 r.append(a.info.name); 8062 } 8063 } 8064 if (r != null) { 8065 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8066 } 8067 8068 r = null; 8069 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8070 // Only system apps can hold shared libraries. 8071 if (pkg.libraryNames != null) { 8072 for (i=0; i<pkg.libraryNames.size(); i++) { 8073 String name = pkg.libraryNames.get(i); 8074 SharedLibraryEntry cur = mSharedLibraries.get(name); 8075 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8076 mSharedLibraries.remove(name); 8077 if (DEBUG_REMOVE && chatty) { 8078 if (r == null) { 8079 r = new StringBuilder(256); 8080 } else { 8081 r.append(' '); 8082 } 8083 r.append(name); 8084 } 8085 } 8086 } 8087 } 8088 } 8089 if (r != null) { 8090 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8091 } 8092 } 8093 8094 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8095 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8096 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8097 return true; 8098 } 8099 } 8100 return false; 8101 } 8102 8103 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8104 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8105 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8106 8107 private void updatePermissionsLPw(String changingPkg, 8108 PackageParser.Package pkgInfo, int flags) { 8109 // Make sure there are no dangling permission trees. 8110 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8111 while (it.hasNext()) { 8112 final BasePermission bp = it.next(); 8113 if (bp.packageSetting == null) { 8114 // We may not yet have parsed the package, so just see if 8115 // we still know about its settings. 8116 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8117 } 8118 if (bp.packageSetting == null) { 8119 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8120 + " from package " + bp.sourcePackage); 8121 it.remove(); 8122 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8123 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8124 Slog.i(TAG, "Removing old permission tree: " + bp.name 8125 + " from package " + bp.sourcePackage); 8126 flags |= UPDATE_PERMISSIONS_ALL; 8127 it.remove(); 8128 } 8129 } 8130 } 8131 8132 // Make sure all dynamic permissions have been assigned to a package, 8133 // and make sure there are no dangling permissions. 8134 it = mSettings.mPermissions.values().iterator(); 8135 while (it.hasNext()) { 8136 final BasePermission bp = it.next(); 8137 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8138 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8139 + bp.name + " pkg=" + bp.sourcePackage 8140 + " info=" + bp.pendingInfo); 8141 if (bp.packageSetting == null && bp.pendingInfo != null) { 8142 final BasePermission tree = findPermissionTreeLP(bp.name); 8143 if (tree != null && tree.perm != null) { 8144 bp.packageSetting = tree.packageSetting; 8145 bp.perm = new PackageParser.Permission(tree.perm.owner, 8146 new PermissionInfo(bp.pendingInfo)); 8147 bp.perm.info.packageName = tree.perm.info.packageName; 8148 bp.perm.info.name = bp.name; 8149 bp.uid = tree.uid; 8150 } 8151 } 8152 } 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: " + 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: " + bp.name 8165 + " from package " + bp.sourcePackage); 8166 flags |= UPDATE_PERMISSIONS_ALL; 8167 it.remove(); 8168 } 8169 } 8170 } 8171 8172 // Now update the permissions for all packages, in particular 8173 // replace the granted permissions of the system packages. 8174 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8175 for (PackageParser.Package pkg : mPackages.values()) { 8176 if (pkg != pkgInfo) { 8177 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8178 changingPkg); 8179 } 8180 } 8181 } 8182 8183 if (pkgInfo != null) { 8184 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8185 } 8186 } 8187 8188 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8189 String packageOfInterest) { 8190 // IMPORTANT: There are two types of permissions: install and runtime. 8191 // Install time permissions are granted when the app is installed to 8192 // all device users and users added in the future. Runtime permissions 8193 // are granted at runtime explicitly to specific users. Normal and signature 8194 // protected permissions are install time permissions. Dangerous permissions 8195 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8196 // otherwise they are runtime permissions. This function does not manage 8197 // runtime permissions except for the case an app targeting Lollipop MR1 8198 // being upgraded to target a newer SDK, in which case dangerous permissions 8199 // are transformed from install time to runtime ones. 8200 8201 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8202 if (ps == null) { 8203 return; 8204 } 8205 8206 PermissionsState permissionsState = ps.getPermissionsState(); 8207 PermissionsState origPermissions = permissionsState; 8208 8209 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8210 8211 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8212 8213 boolean changedInstallPermission = false; 8214 8215 if (replace) { 8216 ps.installPermissionsFixed = false; 8217 if (!ps.isSharedUser()) { 8218 origPermissions = new PermissionsState(permissionsState); 8219 permissionsState.reset(); 8220 } 8221 } 8222 8223 permissionsState.setGlobalGids(mGlobalGids); 8224 8225 final int N = pkg.requestedPermissions.size(); 8226 for (int i=0; i<N; i++) { 8227 final String name = pkg.requestedPermissions.get(i); 8228 final BasePermission bp = mSettings.mPermissions.get(name); 8229 8230 if (DEBUG_INSTALL) { 8231 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8232 } 8233 8234 if (bp == null || bp.packageSetting == null) { 8235 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8236 Slog.w(TAG, "Unknown permission " + name 8237 + " in package " + pkg.packageName); 8238 } 8239 continue; 8240 } 8241 8242 final String perm = bp.name; 8243 boolean allowedSig = false; 8244 int grant = GRANT_DENIED; 8245 8246 // Keep track of app op permissions. 8247 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8248 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8249 if (pkgs == null) { 8250 pkgs = new ArraySet<>(); 8251 mAppOpPermissionPackages.put(bp.name, pkgs); 8252 } 8253 pkgs.add(pkg.packageName); 8254 } 8255 8256 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8257 switch (level) { 8258 case PermissionInfo.PROTECTION_NORMAL: { 8259 // For all apps normal permissions are install time ones. 8260 grant = GRANT_INSTALL; 8261 } break; 8262 8263 case PermissionInfo.PROTECTION_DANGEROUS: { 8264 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8265 // For legacy apps dangerous permissions are install time ones. 8266 grant = GRANT_INSTALL_LEGACY; 8267 } else if (origPermissions.hasInstallPermission(bp.name)) { 8268 // For legacy apps that became modern, install becomes runtime. 8269 grant = GRANT_UPGRADE; 8270 } else { 8271 // For modern apps keep runtime permissions unchanged. 8272 grant = GRANT_RUNTIME; 8273 } 8274 } break; 8275 8276 case PermissionInfo.PROTECTION_SIGNATURE: { 8277 // For all apps signature permissions are install time ones. 8278 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8279 if (allowedSig) { 8280 grant = GRANT_INSTALL; 8281 } 8282 } break; 8283 } 8284 8285 if (DEBUG_INSTALL) { 8286 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8287 } 8288 8289 if (grant != GRANT_DENIED) { 8290 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8291 // If this is an existing, non-system package, then 8292 // we can't add any new permissions to it. 8293 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8294 // Except... if this is a permission that was added 8295 // to the platform (note: need to only do this when 8296 // updating the platform). 8297 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8298 grant = GRANT_DENIED; 8299 } 8300 } 8301 } 8302 8303 switch (grant) { 8304 case GRANT_INSTALL: { 8305 // Revoke this as runtime permission to handle the case of 8306 // a runtime permission being downgraded to an install one. 8307 for (int userId : UserManagerService.getInstance().getUserIds()) { 8308 if (origPermissions.getRuntimePermissionState( 8309 bp.name, userId) != null) { 8310 // Revoke the runtime permission and clear the flags. 8311 origPermissions.revokeRuntimePermission(bp, userId); 8312 origPermissions.updatePermissionFlags(bp, userId, 8313 PackageManager.MASK_PERMISSION_FLAGS, 0); 8314 // If we revoked a permission permission, we have to write. 8315 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8316 changedRuntimePermissionUserIds, userId); 8317 } 8318 } 8319 // Grant an install permission. 8320 if (permissionsState.grantInstallPermission(bp) != 8321 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8322 changedInstallPermission = true; 8323 } 8324 } break; 8325 8326 case GRANT_INSTALL_LEGACY: { 8327 // Grant an install permission. 8328 if (permissionsState.grantInstallPermission(bp) != 8329 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8330 changedInstallPermission = true; 8331 } 8332 } break; 8333 8334 case GRANT_RUNTIME: { 8335 // Grant previously granted runtime permissions. 8336 for (int userId : UserManagerService.getInstance().getUserIds()) { 8337 PermissionState permissionState = origPermissions 8338 .getRuntimePermissionState(bp.name, userId); 8339 final int flags = permissionState != null 8340 ? permissionState.getFlags() : 0; 8341 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8342 if (permissionsState.grantRuntimePermission(bp, userId) == 8343 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8344 // If we cannot put the permission as it was, we have to write. 8345 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8346 changedRuntimePermissionUserIds, userId); 8347 } 8348 } 8349 // Propagate the permission flags. 8350 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8351 } 8352 } break; 8353 8354 case GRANT_UPGRADE: { 8355 // Grant runtime permissions for a previously held install permission. 8356 PermissionState permissionState = origPermissions 8357 .getInstallPermissionState(bp.name); 8358 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8359 8360 if (origPermissions.revokeInstallPermission(bp) 8361 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8362 // We will be transferring the permission flags, so clear them. 8363 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8364 PackageManager.MASK_PERMISSION_FLAGS, 0); 8365 changedInstallPermission = true; 8366 } 8367 8368 // If the permission is not to be promoted to runtime we ignore it and 8369 // also its other flags as they are not applicable to install permissions. 8370 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8371 for (int userId : currentUserIds) { 8372 if (permissionsState.grantRuntimePermission(bp, userId) != 8373 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8374 // Transfer the permission flags. 8375 permissionsState.updatePermissionFlags(bp, userId, 8376 flags, flags); 8377 // If we granted the permission, we have to write. 8378 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8379 changedRuntimePermissionUserIds, userId); 8380 } 8381 } 8382 } 8383 } break; 8384 8385 default: { 8386 if (packageOfInterest == null 8387 || packageOfInterest.equals(pkg.packageName)) { 8388 Slog.w(TAG, "Not granting permission " + perm 8389 + " to package " + pkg.packageName 8390 + " because it was previously installed without"); 8391 } 8392 } break; 8393 } 8394 } else { 8395 if (permissionsState.revokeInstallPermission(bp) != 8396 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8397 // Also drop the permission flags. 8398 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8399 PackageManager.MASK_PERMISSION_FLAGS, 0); 8400 changedInstallPermission = true; 8401 Slog.i(TAG, "Un-granting permission " + perm 8402 + " from package " + pkg.packageName 8403 + " (protectionLevel=" + bp.protectionLevel 8404 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8405 + ")"); 8406 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8407 // Don't print warning for app op permissions, since it is fine for them 8408 // not to be granted, there is a UI for the user to decide. 8409 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8410 Slog.w(TAG, "Not granting permission " + perm 8411 + " to package " + pkg.packageName 8412 + " (protectionLevel=" + bp.protectionLevel 8413 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8414 + ")"); 8415 } 8416 } 8417 } 8418 } 8419 8420 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8421 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8422 // This is the first that we have heard about this package, so the 8423 // permissions we have now selected are fixed until explicitly 8424 // changed. 8425 ps.installPermissionsFixed = true; 8426 } 8427 8428 // Persist the runtime permissions state for users with changes. 8429 for (int userId : changedRuntimePermissionUserIds) { 8430 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8431 } 8432 } 8433 8434 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8435 boolean allowed = false; 8436 final int NP = PackageParser.NEW_PERMISSIONS.length; 8437 for (int ip=0; ip<NP; ip++) { 8438 final PackageParser.NewPermissionInfo npi 8439 = PackageParser.NEW_PERMISSIONS[ip]; 8440 if (npi.name.equals(perm) 8441 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8442 allowed = true; 8443 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8444 + pkg.packageName); 8445 break; 8446 } 8447 } 8448 return allowed; 8449 } 8450 8451 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8452 BasePermission bp, PermissionsState origPermissions) { 8453 boolean allowed; 8454 allowed = (compareSignatures( 8455 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8456 == PackageManager.SIGNATURE_MATCH) 8457 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8458 == PackageManager.SIGNATURE_MATCH); 8459 if (!allowed && (bp.protectionLevel 8460 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8461 if (isSystemApp(pkg)) { 8462 // For updated system applications, a system permission 8463 // is granted only if it had been defined by the original application. 8464 if (pkg.isUpdatedSystemApp()) { 8465 final PackageSetting sysPs = mSettings 8466 .getDisabledSystemPkgLPr(pkg.packageName); 8467 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8468 // If the original was granted this permission, we take 8469 // that grant decision as read and propagate it to the 8470 // update. 8471 if (sysPs.isPrivileged()) { 8472 allowed = true; 8473 } 8474 } else { 8475 // The system apk may have been updated with an older 8476 // version of the one on the data partition, but which 8477 // granted a new system permission that it didn't have 8478 // before. In this case we do want to allow the app to 8479 // now get the new permission if the ancestral apk is 8480 // privileged to get it. 8481 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8482 for (int j=0; 8483 j<sysPs.pkg.requestedPermissions.size(); j++) { 8484 if (perm.equals( 8485 sysPs.pkg.requestedPermissions.get(j))) { 8486 allowed = true; 8487 break; 8488 } 8489 } 8490 } 8491 } 8492 } else { 8493 allowed = isPrivilegedApp(pkg); 8494 } 8495 } 8496 } 8497 if (!allowed) { 8498 if (!allowed && (bp.protectionLevel 8499 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8500 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8501 // If this was a previously normal/dangerous permission that got moved 8502 // to a system permission as part of the runtime permission redesign, then 8503 // we still want to blindly grant it to old apps. 8504 allowed = true; 8505 } 8506 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8507 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8508 // If this permission is to be granted to the system installer and 8509 // this app is an installer, then it gets the permission. 8510 allowed = true; 8511 } 8512 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8513 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8514 // If this permission is to be granted to the system verifier and 8515 // this app is a verifier, then it gets the permission. 8516 allowed = true; 8517 } 8518 if (!allowed && (bp.protectionLevel 8519 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8520 && isSystemApp(pkg)) { 8521 // Any pre-installed system app is allowed to get this permission. 8522 allowed = true; 8523 } 8524 if (!allowed && (bp.protectionLevel 8525 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8526 // For development permissions, a development permission 8527 // is granted only if it was already granted. 8528 allowed = origPermissions.hasInstallPermission(perm); 8529 } 8530 } 8531 return allowed; 8532 } 8533 8534 final class ActivityIntentResolver 8535 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8536 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8537 boolean defaultOnly, int userId) { 8538 if (!sUserManager.exists(userId)) return null; 8539 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8540 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8541 } 8542 8543 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8544 int userId) { 8545 if (!sUserManager.exists(userId)) return null; 8546 mFlags = flags; 8547 return super.queryIntent(intent, resolvedType, 8548 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8549 } 8550 8551 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8552 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8553 if (!sUserManager.exists(userId)) return null; 8554 if (packageActivities == null) { 8555 return null; 8556 } 8557 mFlags = flags; 8558 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8559 final int N = packageActivities.size(); 8560 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8561 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8562 8563 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8564 for (int i = 0; i < N; ++i) { 8565 intentFilters = packageActivities.get(i).intents; 8566 if (intentFilters != null && intentFilters.size() > 0) { 8567 PackageParser.ActivityIntentInfo[] array = 8568 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8569 intentFilters.toArray(array); 8570 listCut.add(array); 8571 } 8572 } 8573 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8574 } 8575 8576 public final void addActivity(PackageParser.Activity a, String type) { 8577 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8578 mActivities.put(a.getComponentName(), a); 8579 if (DEBUG_SHOW_INFO) 8580 Log.v( 8581 TAG, " " + type + " " + 8582 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8583 if (DEBUG_SHOW_INFO) 8584 Log.v(TAG, " Class=" + a.info.name); 8585 final int NI = a.intents.size(); 8586 for (int j=0; j<NI; j++) { 8587 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8588 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8589 intent.setPriority(0); 8590 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8591 + a.className + " with priority > 0, forcing to 0"); 8592 } 8593 if (DEBUG_SHOW_INFO) { 8594 Log.v(TAG, " IntentFilter:"); 8595 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8596 } 8597 if (!intent.debugCheck()) { 8598 Log.w(TAG, "==> For Activity " + a.info.name); 8599 } 8600 addFilter(intent); 8601 } 8602 } 8603 8604 public final void removeActivity(PackageParser.Activity a, String type) { 8605 mActivities.remove(a.getComponentName()); 8606 if (DEBUG_SHOW_INFO) { 8607 Log.v(TAG, " " + type + " " 8608 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8609 : a.info.name) + ":"); 8610 Log.v(TAG, " Class=" + a.info.name); 8611 } 8612 final int NI = a.intents.size(); 8613 for (int j=0; j<NI; j++) { 8614 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8615 if (DEBUG_SHOW_INFO) { 8616 Log.v(TAG, " IntentFilter:"); 8617 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8618 } 8619 removeFilter(intent); 8620 } 8621 } 8622 8623 @Override 8624 protected boolean allowFilterResult( 8625 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8626 ActivityInfo filterAi = filter.activity.info; 8627 for (int i=dest.size()-1; i>=0; i--) { 8628 ActivityInfo destAi = dest.get(i).activityInfo; 8629 if (destAi.name == filterAi.name 8630 && destAi.packageName == filterAi.packageName) { 8631 return false; 8632 } 8633 } 8634 return true; 8635 } 8636 8637 @Override 8638 protected ActivityIntentInfo[] newArray(int size) { 8639 return new ActivityIntentInfo[size]; 8640 } 8641 8642 @Override 8643 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8644 if (!sUserManager.exists(userId)) return true; 8645 PackageParser.Package p = filter.activity.owner; 8646 if (p != null) { 8647 PackageSetting ps = (PackageSetting)p.mExtras; 8648 if (ps != null) { 8649 // System apps are never considered stopped for purposes of 8650 // filtering, because there may be no way for the user to 8651 // actually re-launch them. 8652 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8653 && ps.getStopped(userId); 8654 } 8655 } 8656 return false; 8657 } 8658 8659 @Override 8660 protected boolean isPackageForFilter(String packageName, 8661 PackageParser.ActivityIntentInfo info) { 8662 return packageName.equals(info.activity.owner.packageName); 8663 } 8664 8665 @Override 8666 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8667 int match, int userId) { 8668 if (!sUserManager.exists(userId)) return null; 8669 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8670 return null; 8671 } 8672 final PackageParser.Activity activity = info.activity; 8673 if (mSafeMode && (activity.info.applicationInfo.flags 8674 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8675 return null; 8676 } 8677 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8678 if (ps == null) { 8679 return null; 8680 } 8681 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8682 ps.readUserState(userId), userId); 8683 if (ai == null) { 8684 return null; 8685 } 8686 final ResolveInfo res = new ResolveInfo(); 8687 res.activityInfo = ai; 8688 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8689 res.filter = info; 8690 } 8691 if (info != null) { 8692 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8693 } 8694 res.priority = info.getPriority(); 8695 res.preferredOrder = activity.owner.mPreferredOrder; 8696 //System.out.println("Result: " + res.activityInfo.className + 8697 // " = " + res.priority); 8698 res.match = match; 8699 res.isDefault = info.hasDefault; 8700 res.labelRes = info.labelRes; 8701 res.nonLocalizedLabel = info.nonLocalizedLabel; 8702 if (userNeedsBadging(userId)) { 8703 res.noResourceId = true; 8704 } else { 8705 res.icon = info.icon; 8706 } 8707 res.iconResourceId = info.icon; 8708 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8709 return res; 8710 } 8711 8712 @Override 8713 protected void sortResults(List<ResolveInfo> results) { 8714 Collections.sort(results, mResolvePrioritySorter); 8715 } 8716 8717 @Override 8718 protected void dumpFilter(PrintWriter out, String prefix, 8719 PackageParser.ActivityIntentInfo filter) { 8720 out.print(prefix); out.print( 8721 Integer.toHexString(System.identityHashCode(filter.activity))); 8722 out.print(' '); 8723 filter.activity.printComponentShortName(out); 8724 out.print(" filter "); 8725 out.println(Integer.toHexString(System.identityHashCode(filter))); 8726 } 8727 8728 @Override 8729 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8730 return filter.activity; 8731 } 8732 8733 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8734 PackageParser.Activity activity = (PackageParser.Activity)label; 8735 out.print(prefix); out.print( 8736 Integer.toHexString(System.identityHashCode(activity))); 8737 out.print(' '); 8738 activity.printComponentShortName(out); 8739 if (count > 1) { 8740 out.print(" ("); out.print(count); out.print(" filters)"); 8741 } 8742 out.println(); 8743 } 8744 8745// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8746// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8747// final List<ResolveInfo> retList = Lists.newArrayList(); 8748// while (i.hasNext()) { 8749// final ResolveInfo resolveInfo = i.next(); 8750// if (isEnabledLP(resolveInfo.activityInfo)) { 8751// retList.add(resolveInfo); 8752// } 8753// } 8754// return retList; 8755// } 8756 8757 // Keys are String (activity class name), values are Activity. 8758 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8759 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8760 private int mFlags; 8761 } 8762 8763 private final class ServiceIntentResolver 8764 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8765 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8766 boolean defaultOnly, int userId) { 8767 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8768 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8769 } 8770 8771 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8772 int userId) { 8773 if (!sUserManager.exists(userId)) return null; 8774 mFlags = flags; 8775 return super.queryIntent(intent, resolvedType, 8776 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8777 } 8778 8779 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8780 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8781 if (!sUserManager.exists(userId)) return null; 8782 if (packageServices == null) { 8783 return null; 8784 } 8785 mFlags = flags; 8786 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8787 final int N = packageServices.size(); 8788 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8789 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8790 8791 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8792 for (int i = 0; i < N; ++i) { 8793 intentFilters = packageServices.get(i).intents; 8794 if (intentFilters != null && intentFilters.size() > 0) { 8795 PackageParser.ServiceIntentInfo[] array = 8796 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8797 intentFilters.toArray(array); 8798 listCut.add(array); 8799 } 8800 } 8801 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8802 } 8803 8804 public final void addService(PackageParser.Service s) { 8805 mServices.put(s.getComponentName(), s); 8806 if (DEBUG_SHOW_INFO) { 8807 Log.v(TAG, " " 8808 + (s.info.nonLocalizedLabel != null 8809 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8810 Log.v(TAG, " Class=" + s.info.name); 8811 } 8812 final int NI = s.intents.size(); 8813 int j; 8814 for (j=0; j<NI; j++) { 8815 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8816 if (DEBUG_SHOW_INFO) { 8817 Log.v(TAG, " IntentFilter:"); 8818 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8819 } 8820 if (!intent.debugCheck()) { 8821 Log.w(TAG, "==> For Service " + s.info.name); 8822 } 8823 addFilter(intent); 8824 } 8825 } 8826 8827 public final void removeService(PackageParser.Service s) { 8828 mServices.remove(s.getComponentName()); 8829 if (DEBUG_SHOW_INFO) { 8830 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8831 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8832 Log.v(TAG, " Class=" + s.info.name); 8833 } 8834 final int NI = s.intents.size(); 8835 int j; 8836 for (j=0; j<NI; j++) { 8837 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8838 if (DEBUG_SHOW_INFO) { 8839 Log.v(TAG, " IntentFilter:"); 8840 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8841 } 8842 removeFilter(intent); 8843 } 8844 } 8845 8846 @Override 8847 protected boolean allowFilterResult( 8848 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8849 ServiceInfo filterSi = filter.service.info; 8850 for (int i=dest.size()-1; i>=0; i--) { 8851 ServiceInfo destAi = dest.get(i).serviceInfo; 8852 if (destAi.name == filterSi.name 8853 && destAi.packageName == filterSi.packageName) { 8854 return false; 8855 } 8856 } 8857 return true; 8858 } 8859 8860 @Override 8861 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8862 return new PackageParser.ServiceIntentInfo[size]; 8863 } 8864 8865 @Override 8866 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8867 if (!sUserManager.exists(userId)) return true; 8868 PackageParser.Package p = filter.service.owner; 8869 if (p != null) { 8870 PackageSetting ps = (PackageSetting)p.mExtras; 8871 if (ps != null) { 8872 // System apps are never considered stopped for purposes of 8873 // filtering, because there may be no way for the user to 8874 // actually re-launch them. 8875 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8876 && ps.getStopped(userId); 8877 } 8878 } 8879 return false; 8880 } 8881 8882 @Override 8883 protected boolean isPackageForFilter(String packageName, 8884 PackageParser.ServiceIntentInfo info) { 8885 return packageName.equals(info.service.owner.packageName); 8886 } 8887 8888 @Override 8889 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8890 int match, int userId) { 8891 if (!sUserManager.exists(userId)) return null; 8892 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8893 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8894 return null; 8895 } 8896 final PackageParser.Service service = info.service; 8897 if (mSafeMode && (service.info.applicationInfo.flags 8898 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8899 return null; 8900 } 8901 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8902 if (ps == null) { 8903 return null; 8904 } 8905 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8906 ps.readUserState(userId), userId); 8907 if (si == null) { 8908 return null; 8909 } 8910 final ResolveInfo res = new ResolveInfo(); 8911 res.serviceInfo = si; 8912 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8913 res.filter = filter; 8914 } 8915 res.priority = info.getPriority(); 8916 res.preferredOrder = service.owner.mPreferredOrder; 8917 res.match = match; 8918 res.isDefault = info.hasDefault; 8919 res.labelRes = info.labelRes; 8920 res.nonLocalizedLabel = info.nonLocalizedLabel; 8921 res.icon = info.icon; 8922 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8923 return res; 8924 } 8925 8926 @Override 8927 protected void sortResults(List<ResolveInfo> results) { 8928 Collections.sort(results, mResolvePrioritySorter); 8929 } 8930 8931 @Override 8932 protected void dumpFilter(PrintWriter out, String prefix, 8933 PackageParser.ServiceIntentInfo filter) { 8934 out.print(prefix); out.print( 8935 Integer.toHexString(System.identityHashCode(filter.service))); 8936 out.print(' '); 8937 filter.service.printComponentShortName(out); 8938 out.print(" filter "); 8939 out.println(Integer.toHexString(System.identityHashCode(filter))); 8940 } 8941 8942 @Override 8943 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8944 return filter.service; 8945 } 8946 8947 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8948 PackageParser.Service service = (PackageParser.Service)label; 8949 out.print(prefix); out.print( 8950 Integer.toHexString(System.identityHashCode(service))); 8951 out.print(' '); 8952 service.printComponentShortName(out); 8953 if (count > 1) { 8954 out.print(" ("); out.print(count); out.print(" filters)"); 8955 } 8956 out.println(); 8957 } 8958 8959// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8960// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8961// final List<ResolveInfo> retList = Lists.newArrayList(); 8962// while (i.hasNext()) { 8963// final ResolveInfo resolveInfo = (ResolveInfo) i; 8964// if (isEnabledLP(resolveInfo.serviceInfo)) { 8965// retList.add(resolveInfo); 8966// } 8967// } 8968// return retList; 8969// } 8970 8971 // Keys are String (activity class name), values are Activity. 8972 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8973 = new ArrayMap<ComponentName, PackageParser.Service>(); 8974 private int mFlags; 8975 }; 8976 8977 private final class ProviderIntentResolver 8978 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8979 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8980 boolean defaultOnly, int userId) { 8981 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8982 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8983 } 8984 8985 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8986 int userId) { 8987 if (!sUserManager.exists(userId)) 8988 return null; 8989 mFlags = flags; 8990 return super.queryIntent(intent, resolvedType, 8991 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8992 } 8993 8994 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8995 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8996 if (!sUserManager.exists(userId)) 8997 return null; 8998 if (packageProviders == null) { 8999 return null; 9000 } 9001 mFlags = flags; 9002 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9003 final int N = packageProviders.size(); 9004 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9005 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9006 9007 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9008 for (int i = 0; i < N; ++i) { 9009 intentFilters = packageProviders.get(i).intents; 9010 if (intentFilters != null && intentFilters.size() > 0) { 9011 PackageParser.ProviderIntentInfo[] array = 9012 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9013 intentFilters.toArray(array); 9014 listCut.add(array); 9015 } 9016 } 9017 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9018 } 9019 9020 public final void addProvider(PackageParser.Provider p) { 9021 if (mProviders.containsKey(p.getComponentName())) { 9022 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9023 return; 9024 } 9025 9026 mProviders.put(p.getComponentName(), p); 9027 if (DEBUG_SHOW_INFO) { 9028 Log.v(TAG, " " 9029 + (p.info.nonLocalizedLabel != null 9030 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9031 Log.v(TAG, " Class=" + p.info.name); 9032 } 9033 final int NI = p.intents.size(); 9034 int j; 9035 for (j = 0; j < NI; j++) { 9036 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9037 if (DEBUG_SHOW_INFO) { 9038 Log.v(TAG, " IntentFilter:"); 9039 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9040 } 9041 if (!intent.debugCheck()) { 9042 Log.w(TAG, "==> For Provider " + p.info.name); 9043 } 9044 addFilter(intent); 9045 } 9046 } 9047 9048 public final void removeProvider(PackageParser.Provider p) { 9049 mProviders.remove(p.getComponentName()); 9050 if (DEBUG_SHOW_INFO) { 9051 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9052 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9053 Log.v(TAG, " Class=" + p.info.name); 9054 } 9055 final int NI = p.intents.size(); 9056 int j; 9057 for (j = 0; j < NI; j++) { 9058 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9059 if (DEBUG_SHOW_INFO) { 9060 Log.v(TAG, " IntentFilter:"); 9061 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9062 } 9063 removeFilter(intent); 9064 } 9065 } 9066 9067 @Override 9068 protected boolean allowFilterResult( 9069 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9070 ProviderInfo filterPi = filter.provider.info; 9071 for (int i = dest.size() - 1; i >= 0; i--) { 9072 ProviderInfo destPi = dest.get(i).providerInfo; 9073 if (destPi.name == filterPi.name 9074 && destPi.packageName == filterPi.packageName) { 9075 return false; 9076 } 9077 } 9078 return true; 9079 } 9080 9081 @Override 9082 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9083 return new PackageParser.ProviderIntentInfo[size]; 9084 } 9085 9086 @Override 9087 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9088 if (!sUserManager.exists(userId)) 9089 return true; 9090 PackageParser.Package p = filter.provider.owner; 9091 if (p != null) { 9092 PackageSetting ps = (PackageSetting) p.mExtras; 9093 if (ps != null) { 9094 // System apps are never considered stopped for purposes of 9095 // filtering, because there may be no way for the user to 9096 // actually re-launch them. 9097 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9098 && ps.getStopped(userId); 9099 } 9100 } 9101 return false; 9102 } 9103 9104 @Override 9105 protected boolean isPackageForFilter(String packageName, 9106 PackageParser.ProviderIntentInfo info) { 9107 return packageName.equals(info.provider.owner.packageName); 9108 } 9109 9110 @Override 9111 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9112 int match, int userId) { 9113 if (!sUserManager.exists(userId)) 9114 return null; 9115 final PackageParser.ProviderIntentInfo info = filter; 9116 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9117 return null; 9118 } 9119 final PackageParser.Provider provider = info.provider; 9120 if (mSafeMode && (provider.info.applicationInfo.flags 9121 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9122 return null; 9123 } 9124 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9125 if (ps == null) { 9126 return null; 9127 } 9128 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9129 ps.readUserState(userId), userId); 9130 if (pi == null) { 9131 return null; 9132 } 9133 final ResolveInfo res = new ResolveInfo(); 9134 res.providerInfo = pi; 9135 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9136 res.filter = filter; 9137 } 9138 res.priority = info.getPriority(); 9139 res.preferredOrder = provider.owner.mPreferredOrder; 9140 res.match = match; 9141 res.isDefault = info.hasDefault; 9142 res.labelRes = info.labelRes; 9143 res.nonLocalizedLabel = info.nonLocalizedLabel; 9144 res.icon = info.icon; 9145 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9146 return res; 9147 } 9148 9149 @Override 9150 protected void sortResults(List<ResolveInfo> results) { 9151 Collections.sort(results, mResolvePrioritySorter); 9152 } 9153 9154 @Override 9155 protected void dumpFilter(PrintWriter out, String prefix, 9156 PackageParser.ProviderIntentInfo filter) { 9157 out.print(prefix); 9158 out.print( 9159 Integer.toHexString(System.identityHashCode(filter.provider))); 9160 out.print(' '); 9161 filter.provider.printComponentShortName(out); 9162 out.print(" filter "); 9163 out.println(Integer.toHexString(System.identityHashCode(filter))); 9164 } 9165 9166 @Override 9167 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9168 return filter.provider; 9169 } 9170 9171 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9172 PackageParser.Provider provider = (PackageParser.Provider)label; 9173 out.print(prefix); out.print( 9174 Integer.toHexString(System.identityHashCode(provider))); 9175 out.print(' '); 9176 provider.printComponentShortName(out); 9177 if (count > 1) { 9178 out.print(" ("); out.print(count); out.print(" filters)"); 9179 } 9180 out.println(); 9181 } 9182 9183 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9184 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9185 private int mFlags; 9186 }; 9187 9188 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9189 new Comparator<ResolveInfo>() { 9190 public int compare(ResolveInfo r1, ResolveInfo r2) { 9191 int v1 = r1.priority; 9192 int v2 = r2.priority; 9193 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9194 if (v1 != v2) { 9195 return (v1 > v2) ? -1 : 1; 9196 } 9197 v1 = r1.preferredOrder; 9198 v2 = r2.preferredOrder; 9199 if (v1 != v2) { 9200 return (v1 > v2) ? -1 : 1; 9201 } 9202 if (r1.isDefault != r2.isDefault) { 9203 return r1.isDefault ? -1 : 1; 9204 } 9205 v1 = r1.match; 9206 v2 = r2.match; 9207 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9208 if (v1 != v2) { 9209 return (v1 > v2) ? -1 : 1; 9210 } 9211 if (r1.system != r2.system) { 9212 return r1.system ? -1 : 1; 9213 } 9214 return 0; 9215 } 9216 }; 9217 9218 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9219 new Comparator<ProviderInfo>() { 9220 public int compare(ProviderInfo p1, ProviderInfo p2) { 9221 final int v1 = p1.initOrder; 9222 final int v2 = p2.initOrder; 9223 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9224 } 9225 }; 9226 9227 final void sendPackageBroadcast(final String action, final String pkg, 9228 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9229 final int[] userIds) { 9230 mHandler.post(new Runnable() { 9231 @Override 9232 public void run() { 9233 try { 9234 final IActivityManager am = ActivityManagerNative.getDefault(); 9235 if (am == null) return; 9236 final int[] resolvedUserIds; 9237 if (userIds == null) { 9238 resolvedUserIds = am.getRunningUserIds(); 9239 } else { 9240 resolvedUserIds = userIds; 9241 } 9242 for (int id : resolvedUserIds) { 9243 final Intent intent = new Intent(action, 9244 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9245 if (extras != null) { 9246 intent.putExtras(extras); 9247 } 9248 if (targetPkg != null) { 9249 intent.setPackage(targetPkg); 9250 } 9251 // Modify the UID when posting to other users 9252 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9253 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9254 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9255 intent.putExtra(Intent.EXTRA_UID, uid); 9256 } 9257 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9258 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9259 if (DEBUG_BROADCASTS) { 9260 RuntimeException here = new RuntimeException("here"); 9261 here.fillInStackTrace(); 9262 Slog.d(TAG, "Sending to user " + id + ": " 9263 + intent.toShortString(false, true, false, false) 9264 + " " + intent.getExtras(), here); 9265 } 9266 am.broadcastIntent(null, intent, null, finishedReceiver, 9267 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9268 null, finishedReceiver != null, false, id); 9269 } 9270 } catch (RemoteException ex) { 9271 } 9272 } 9273 }); 9274 } 9275 9276 /** 9277 * Check if the external storage media is available. This is true if there 9278 * is a mounted external storage medium or if the external storage is 9279 * emulated. 9280 */ 9281 private boolean isExternalMediaAvailable() { 9282 return mMediaMounted || Environment.isExternalStorageEmulated(); 9283 } 9284 9285 @Override 9286 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9287 // writer 9288 synchronized (mPackages) { 9289 if (!isExternalMediaAvailable()) { 9290 // If the external storage is no longer mounted at this point, 9291 // the caller may not have been able to delete all of this 9292 // packages files and can not delete any more. Bail. 9293 return null; 9294 } 9295 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9296 if (lastPackage != null) { 9297 pkgs.remove(lastPackage); 9298 } 9299 if (pkgs.size() > 0) { 9300 return pkgs.get(0); 9301 } 9302 } 9303 return null; 9304 } 9305 9306 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9307 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9308 userId, andCode ? 1 : 0, packageName); 9309 if (mSystemReady) { 9310 msg.sendToTarget(); 9311 } else { 9312 if (mPostSystemReadyMessages == null) { 9313 mPostSystemReadyMessages = new ArrayList<>(); 9314 } 9315 mPostSystemReadyMessages.add(msg); 9316 } 9317 } 9318 9319 void startCleaningPackages() { 9320 // reader 9321 synchronized (mPackages) { 9322 if (!isExternalMediaAvailable()) { 9323 return; 9324 } 9325 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9326 return; 9327 } 9328 } 9329 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9330 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9331 IActivityManager am = ActivityManagerNative.getDefault(); 9332 if (am != null) { 9333 try { 9334 am.startService(null, intent, null, mContext.getOpPackageName(), 9335 UserHandle.USER_OWNER); 9336 } catch (RemoteException e) { 9337 } 9338 } 9339 } 9340 9341 @Override 9342 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9343 int installFlags, String installerPackageName, VerificationParams verificationParams, 9344 String packageAbiOverride) { 9345 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9346 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9347 } 9348 9349 @Override 9350 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9351 int installFlags, String installerPackageName, VerificationParams verificationParams, 9352 String packageAbiOverride, int userId) { 9353 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9354 9355 final int callingUid = Binder.getCallingUid(); 9356 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9357 9358 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9359 try { 9360 if (observer != null) { 9361 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9362 } 9363 } catch (RemoteException re) { 9364 } 9365 return; 9366 } 9367 9368 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9369 installFlags |= PackageManager.INSTALL_FROM_ADB; 9370 9371 } else { 9372 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9373 // about installerPackageName. 9374 9375 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9376 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9377 } 9378 9379 UserHandle user; 9380 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9381 user = UserHandle.ALL; 9382 } else { 9383 user = new UserHandle(userId); 9384 } 9385 9386 // Only system components can circumvent runtime permissions when installing. 9387 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9388 && mContext.checkCallingOrSelfPermission(Manifest.permission 9389 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9390 throw new SecurityException("You need the " 9391 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9392 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9393 } 9394 9395 verificationParams.setInstallerUid(callingUid); 9396 9397 final File originFile = new File(originPath); 9398 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9399 9400 final Message msg = mHandler.obtainMessage(INIT_COPY); 9401 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9402 null, verificationParams, user, packageAbiOverride); 9403 mHandler.sendMessage(msg); 9404 } 9405 9406 void installStage(String packageName, File stagedDir, String stagedCid, 9407 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9408 String installerPackageName, int installerUid, UserHandle user) { 9409 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9410 params.referrerUri, installerUid, null); 9411 verifParams.setInstallerUid(installerUid); 9412 9413 final OriginInfo origin; 9414 if (stagedDir != null) { 9415 origin = OriginInfo.fromStagedFile(stagedDir); 9416 } else { 9417 origin = OriginInfo.fromStagedContainer(stagedCid); 9418 } 9419 9420 final Message msg = mHandler.obtainMessage(INIT_COPY); 9421 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9422 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9423 mHandler.sendMessage(msg); 9424 } 9425 9426 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9427 Bundle extras = new Bundle(1); 9428 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9429 9430 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9431 packageName, extras, null, null, new int[] {userId}); 9432 try { 9433 IActivityManager am = ActivityManagerNative.getDefault(); 9434 final boolean isSystem = 9435 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9436 if (isSystem && am.isUserRunning(userId, false)) { 9437 // The just-installed/enabled app is bundled on the system, so presumed 9438 // to be able to run automatically without needing an explicit launch. 9439 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9440 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9441 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9442 .setPackage(packageName); 9443 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9444 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9445 } 9446 } catch (RemoteException e) { 9447 // shouldn't happen 9448 Slog.w(TAG, "Unable to bootstrap installed package", e); 9449 } 9450 } 9451 9452 @Override 9453 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9454 int userId) { 9455 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9456 PackageSetting pkgSetting; 9457 final int uid = Binder.getCallingUid(); 9458 enforceCrossUserPermission(uid, userId, true, true, 9459 "setApplicationHiddenSetting for user " + userId); 9460 9461 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9462 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9463 return false; 9464 } 9465 9466 long callingId = Binder.clearCallingIdentity(); 9467 try { 9468 boolean sendAdded = false; 9469 boolean sendRemoved = false; 9470 // writer 9471 synchronized (mPackages) { 9472 pkgSetting = mSettings.mPackages.get(packageName); 9473 if (pkgSetting == null) { 9474 return false; 9475 } 9476 if (pkgSetting.getHidden(userId) != hidden) { 9477 pkgSetting.setHidden(hidden, userId); 9478 mSettings.writePackageRestrictionsLPr(userId); 9479 if (hidden) { 9480 sendRemoved = true; 9481 } else { 9482 sendAdded = true; 9483 } 9484 } 9485 } 9486 if (sendAdded) { 9487 sendPackageAddedForUser(packageName, pkgSetting, userId); 9488 return true; 9489 } 9490 if (sendRemoved) { 9491 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9492 "hiding pkg"); 9493 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9494 } 9495 } finally { 9496 Binder.restoreCallingIdentity(callingId); 9497 } 9498 return false; 9499 } 9500 9501 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9502 int userId) { 9503 final PackageRemovedInfo info = new PackageRemovedInfo(); 9504 info.removedPackage = packageName; 9505 info.removedUsers = new int[] {userId}; 9506 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9507 info.sendBroadcast(false, false, false); 9508 } 9509 9510 /** 9511 * Returns true if application is not found or there was an error. Otherwise it returns 9512 * the hidden state of the package for the given user. 9513 */ 9514 @Override 9515 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9516 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9517 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9518 false, "getApplicationHidden for user " + userId); 9519 PackageSetting pkgSetting; 9520 long callingId = Binder.clearCallingIdentity(); 9521 try { 9522 // writer 9523 synchronized (mPackages) { 9524 pkgSetting = mSettings.mPackages.get(packageName); 9525 if (pkgSetting == null) { 9526 return true; 9527 } 9528 return pkgSetting.getHidden(userId); 9529 } 9530 } finally { 9531 Binder.restoreCallingIdentity(callingId); 9532 } 9533 } 9534 9535 /** 9536 * @hide 9537 */ 9538 @Override 9539 public int installExistingPackageAsUser(String packageName, int userId) { 9540 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9541 null); 9542 PackageSetting pkgSetting; 9543 final int uid = Binder.getCallingUid(); 9544 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9545 + userId); 9546 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9547 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9548 } 9549 9550 long callingId = Binder.clearCallingIdentity(); 9551 try { 9552 boolean sendAdded = false; 9553 9554 // writer 9555 synchronized (mPackages) { 9556 pkgSetting = mSettings.mPackages.get(packageName); 9557 if (pkgSetting == null) { 9558 return PackageManager.INSTALL_FAILED_INVALID_URI; 9559 } 9560 if (!pkgSetting.getInstalled(userId)) { 9561 pkgSetting.setInstalled(true, userId); 9562 pkgSetting.setHidden(false, userId); 9563 mSettings.writePackageRestrictionsLPr(userId); 9564 sendAdded = true; 9565 } 9566 } 9567 9568 if (sendAdded) { 9569 sendPackageAddedForUser(packageName, pkgSetting, userId); 9570 } 9571 } finally { 9572 Binder.restoreCallingIdentity(callingId); 9573 } 9574 9575 return PackageManager.INSTALL_SUCCEEDED; 9576 } 9577 9578 boolean isUserRestricted(int userId, String restrictionKey) { 9579 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9580 if (restrictions.getBoolean(restrictionKey, false)) { 9581 Log.w(TAG, "User is restricted: " + restrictionKey); 9582 return true; 9583 } 9584 return false; 9585 } 9586 9587 @Override 9588 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9589 mContext.enforceCallingOrSelfPermission( 9590 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9591 "Only package verification agents can verify applications"); 9592 9593 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9594 final PackageVerificationResponse response = new PackageVerificationResponse( 9595 verificationCode, Binder.getCallingUid()); 9596 msg.arg1 = id; 9597 msg.obj = response; 9598 mHandler.sendMessage(msg); 9599 } 9600 9601 @Override 9602 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9603 long millisecondsToDelay) { 9604 mContext.enforceCallingOrSelfPermission( 9605 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9606 "Only package verification agents can extend verification timeouts"); 9607 9608 final PackageVerificationState state = mPendingVerification.get(id); 9609 final PackageVerificationResponse response = new PackageVerificationResponse( 9610 verificationCodeAtTimeout, Binder.getCallingUid()); 9611 9612 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9613 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9614 } 9615 if (millisecondsToDelay < 0) { 9616 millisecondsToDelay = 0; 9617 } 9618 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9619 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9620 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9621 } 9622 9623 if ((state != null) && !state.timeoutExtended()) { 9624 state.extendTimeout(); 9625 9626 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9627 msg.arg1 = id; 9628 msg.obj = response; 9629 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9630 } 9631 } 9632 9633 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9634 int verificationCode, UserHandle user) { 9635 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9636 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9637 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9638 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9639 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9640 9641 mContext.sendBroadcastAsUser(intent, user, 9642 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9643 } 9644 9645 private ComponentName matchComponentForVerifier(String packageName, 9646 List<ResolveInfo> receivers) { 9647 ActivityInfo targetReceiver = null; 9648 9649 final int NR = receivers.size(); 9650 for (int i = 0; i < NR; i++) { 9651 final ResolveInfo info = receivers.get(i); 9652 if (info.activityInfo == null) { 9653 continue; 9654 } 9655 9656 if (packageName.equals(info.activityInfo.packageName)) { 9657 targetReceiver = info.activityInfo; 9658 break; 9659 } 9660 } 9661 9662 if (targetReceiver == null) { 9663 return null; 9664 } 9665 9666 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9667 } 9668 9669 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9670 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9671 if (pkgInfo.verifiers.length == 0) { 9672 return null; 9673 } 9674 9675 final int N = pkgInfo.verifiers.length; 9676 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9677 for (int i = 0; i < N; i++) { 9678 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9679 9680 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9681 receivers); 9682 if (comp == null) { 9683 continue; 9684 } 9685 9686 final int verifierUid = getUidForVerifier(verifierInfo); 9687 if (verifierUid == -1) { 9688 continue; 9689 } 9690 9691 if (DEBUG_VERIFY) { 9692 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9693 + " with the correct signature"); 9694 } 9695 sufficientVerifiers.add(comp); 9696 verificationState.addSufficientVerifier(verifierUid); 9697 } 9698 9699 return sufficientVerifiers; 9700 } 9701 9702 private int getUidForVerifier(VerifierInfo verifierInfo) { 9703 synchronized (mPackages) { 9704 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9705 if (pkg == null) { 9706 return -1; 9707 } else if (pkg.mSignatures.length != 1) { 9708 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9709 + " has more than one signature; ignoring"); 9710 return -1; 9711 } 9712 9713 /* 9714 * If the public key of the package's signature does not match 9715 * our expected public key, then this is a different package and 9716 * we should skip. 9717 */ 9718 9719 final byte[] expectedPublicKey; 9720 try { 9721 final Signature verifierSig = pkg.mSignatures[0]; 9722 final PublicKey publicKey = verifierSig.getPublicKey(); 9723 expectedPublicKey = publicKey.getEncoded(); 9724 } catch (CertificateException e) { 9725 return -1; 9726 } 9727 9728 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9729 9730 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9731 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9732 + " does not have the expected public key; ignoring"); 9733 return -1; 9734 } 9735 9736 return pkg.applicationInfo.uid; 9737 } 9738 } 9739 9740 @Override 9741 public void finishPackageInstall(int token) { 9742 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9743 9744 if (DEBUG_INSTALL) { 9745 Slog.v(TAG, "BM finishing package install for " + token); 9746 } 9747 9748 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9749 mHandler.sendMessage(msg); 9750 } 9751 9752 /** 9753 * Get the verification agent timeout. 9754 * 9755 * @return verification timeout in milliseconds 9756 */ 9757 private long getVerificationTimeout() { 9758 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9759 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9760 DEFAULT_VERIFICATION_TIMEOUT); 9761 } 9762 9763 /** 9764 * Get the default verification agent response code. 9765 * 9766 * @return default verification response code 9767 */ 9768 private int getDefaultVerificationResponse() { 9769 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9770 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9771 DEFAULT_VERIFICATION_RESPONSE); 9772 } 9773 9774 /** 9775 * Check whether or not package verification has been enabled. 9776 * 9777 * @return true if verification should be performed 9778 */ 9779 private boolean isVerificationEnabled(int userId, int installFlags) { 9780 if (!DEFAULT_VERIFY_ENABLE) { 9781 return false; 9782 } 9783 9784 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9785 9786 // Check if installing from ADB 9787 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9788 // Do not run verification in a test harness environment 9789 if (ActivityManager.isRunningInTestHarness()) { 9790 return false; 9791 } 9792 if (ensureVerifyAppsEnabled) { 9793 return true; 9794 } 9795 // Check if the developer does not want package verification for ADB installs 9796 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9797 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9798 return false; 9799 } 9800 } 9801 9802 if (ensureVerifyAppsEnabled) { 9803 return true; 9804 } 9805 9806 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9807 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9808 } 9809 9810 @Override 9811 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9812 throws RemoteException { 9813 mContext.enforceCallingOrSelfPermission( 9814 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9815 "Only intentfilter verification agents can verify applications"); 9816 9817 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9818 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9819 Binder.getCallingUid(), verificationCode, failedDomains); 9820 msg.arg1 = id; 9821 msg.obj = response; 9822 mHandler.sendMessage(msg); 9823 } 9824 9825 @Override 9826 public int getIntentVerificationStatus(String packageName, int userId) { 9827 synchronized (mPackages) { 9828 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9829 } 9830 } 9831 9832 @Override 9833 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9834 mContext.enforceCallingOrSelfPermission( 9835 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9836 9837 boolean result = false; 9838 synchronized (mPackages) { 9839 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9840 } 9841 if (result) { 9842 scheduleWritePackageRestrictionsLocked(userId); 9843 } 9844 return result; 9845 } 9846 9847 @Override 9848 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9849 synchronized (mPackages) { 9850 return mSettings.getIntentFilterVerificationsLPr(packageName); 9851 } 9852 } 9853 9854 @Override 9855 public List<IntentFilter> getAllIntentFilters(String packageName) { 9856 if (TextUtils.isEmpty(packageName)) { 9857 return Collections.<IntentFilter>emptyList(); 9858 } 9859 synchronized (mPackages) { 9860 PackageParser.Package pkg = mPackages.get(packageName); 9861 if (pkg == null || pkg.activities == null) { 9862 return Collections.<IntentFilter>emptyList(); 9863 } 9864 final int count = pkg.activities.size(); 9865 ArrayList<IntentFilter> result = new ArrayList<>(); 9866 for (int n=0; n<count; n++) { 9867 PackageParser.Activity activity = pkg.activities.get(n); 9868 if (activity.intents != null || activity.intents.size() > 0) { 9869 result.addAll(activity.intents); 9870 } 9871 } 9872 return result; 9873 } 9874 } 9875 9876 @Override 9877 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9878 mContext.enforceCallingOrSelfPermission( 9879 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9880 9881 synchronized (mPackages) { 9882 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9883 if (packageName != null) { 9884 result |= updateIntentVerificationStatus(packageName, 9885 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9886 UserHandle.myUserId()); 9887 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9888 packageName, userId); 9889 } 9890 return result; 9891 } 9892 } 9893 9894 @Override 9895 public String getDefaultBrowserPackageName(int userId) { 9896 synchronized (mPackages) { 9897 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9898 } 9899 } 9900 9901 /** 9902 * Get the "allow unknown sources" setting. 9903 * 9904 * @return the current "allow unknown sources" setting 9905 */ 9906 private int getUnknownSourcesSettings() { 9907 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9908 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9909 -1); 9910 } 9911 9912 @Override 9913 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9914 final int uid = Binder.getCallingUid(); 9915 // writer 9916 synchronized (mPackages) { 9917 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9918 if (targetPackageSetting == null) { 9919 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9920 } 9921 9922 PackageSetting installerPackageSetting; 9923 if (installerPackageName != null) { 9924 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9925 if (installerPackageSetting == null) { 9926 throw new IllegalArgumentException("Unknown installer package: " 9927 + installerPackageName); 9928 } 9929 } else { 9930 installerPackageSetting = null; 9931 } 9932 9933 Signature[] callerSignature; 9934 Object obj = mSettings.getUserIdLPr(uid); 9935 if (obj != null) { 9936 if (obj instanceof SharedUserSetting) { 9937 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9938 } else if (obj instanceof PackageSetting) { 9939 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9940 } else { 9941 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9942 } 9943 } else { 9944 throw new SecurityException("Unknown calling uid " + uid); 9945 } 9946 9947 // Verify: can't set installerPackageName to a package that is 9948 // not signed with the same cert as the caller. 9949 if (installerPackageSetting != null) { 9950 if (compareSignatures(callerSignature, 9951 installerPackageSetting.signatures.mSignatures) 9952 != PackageManager.SIGNATURE_MATCH) { 9953 throw new SecurityException( 9954 "Caller does not have same cert as new installer package " 9955 + installerPackageName); 9956 } 9957 } 9958 9959 // Verify: if target already has an installer package, it must 9960 // be signed with the same cert as the caller. 9961 if (targetPackageSetting.installerPackageName != null) { 9962 PackageSetting setting = mSettings.mPackages.get( 9963 targetPackageSetting.installerPackageName); 9964 // If the currently set package isn't valid, then it's always 9965 // okay to change it. 9966 if (setting != null) { 9967 if (compareSignatures(callerSignature, 9968 setting.signatures.mSignatures) 9969 != PackageManager.SIGNATURE_MATCH) { 9970 throw new SecurityException( 9971 "Caller does not have same cert as old installer package " 9972 + targetPackageSetting.installerPackageName); 9973 } 9974 } 9975 } 9976 9977 // Okay! 9978 targetPackageSetting.installerPackageName = installerPackageName; 9979 scheduleWriteSettingsLocked(); 9980 } 9981 } 9982 9983 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9984 // Queue up an async operation since the package installation may take a little while. 9985 mHandler.post(new Runnable() { 9986 public void run() { 9987 mHandler.removeCallbacks(this); 9988 // Result object to be returned 9989 PackageInstalledInfo res = new PackageInstalledInfo(); 9990 res.returnCode = currentStatus; 9991 res.uid = -1; 9992 res.pkg = null; 9993 res.removedInfo = new PackageRemovedInfo(); 9994 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9995 args.doPreInstall(res.returnCode); 9996 synchronized (mInstallLock) { 9997 installPackageLI(args, res); 9998 } 9999 args.doPostInstall(res.returnCode, res.uid); 10000 } 10001 10002 // A restore should be performed at this point if (a) the install 10003 // succeeded, (b) the operation is not an update, and (c) the new 10004 // package has not opted out of backup participation. 10005 final boolean update = res.removedInfo.removedPackage != null; 10006 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10007 boolean doRestore = !update 10008 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10009 10010 // Set up the post-install work request bookkeeping. This will be used 10011 // and cleaned up by the post-install event handling regardless of whether 10012 // there's a restore pass performed. Token values are >= 1. 10013 int token; 10014 if (mNextInstallToken < 0) mNextInstallToken = 1; 10015 token = mNextInstallToken++; 10016 10017 PostInstallData data = new PostInstallData(args, res); 10018 mRunningInstalls.put(token, data); 10019 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10020 10021 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10022 // Pass responsibility to the Backup Manager. It will perform a 10023 // restore if appropriate, then pass responsibility back to the 10024 // Package Manager to run the post-install observer callbacks 10025 // and broadcasts. 10026 IBackupManager bm = IBackupManager.Stub.asInterface( 10027 ServiceManager.getService(Context.BACKUP_SERVICE)); 10028 if (bm != null) { 10029 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10030 + " to BM for possible restore"); 10031 try { 10032 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10033 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10034 } else { 10035 doRestore = false; 10036 } 10037 } catch (RemoteException e) { 10038 // can't happen; the backup manager is local 10039 } catch (Exception e) { 10040 Slog.e(TAG, "Exception trying to enqueue restore", e); 10041 doRestore = false; 10042 } 10043 } else { 10044 Slog.e(TAG, "Backup Manager not found!"); 10045 doRestore = false; 10046 } 10047 } 10048 10049 if (!doRestore) { 10050 // No restore possible, or the Backup Manager was mysteriously not 10051 // available -- just fire the post-install work request directly. 10052 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10053 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10054 mHandler.sendMessage(msg); 10055 } 10056 } 10057 }); 10058 } 10059 10060 private abstract class HandlerParams { 10061 private static final int MAX_RETRIES = 4; 10062 10063 /** 10064 * Number of times startCopy() has been attempted and had a non-fatal 10065 * error. 10066 */ 10067 private int mRetries = 0; 10068 10069 /** User handle for the user requesting the information or installation. */ 10070 private final UserHandle mUser; 10071 10072 HandlerParams(UserHandle user) { 10073 mUser = user; 10074 } 10075 10076 UserHandle getUser() { 10077 return mUser; 10078 } 10079 10080 final boolean startCopy() { 10081 boolean res; 10082 try { 10083 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10084 10085 if (++mRetries > MAX_RETRIES) { 10086 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10087 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10088 handleServiceError(); 10089 return false; 10090 } else { 10091 handleStartCopy(); 10092 res = true; 10093 } 10094 } catch (RemoteException e) { 10095 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10096 mHandler.sendEmptyMessage(MCS_RECONNECT); 10097 res = false; 10098 } 10099 handleReturnCode(); 10100 return res; 10101 } 10102 10103 final void serviceError() { 10104 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10105 handleServiceError(); 10106 handleReturnCode(); 10107 } 10108 10109 abstract void handleStartCopy() throws RemoteException; 10110 abstract void handleServiceError(); 10111 abstract void handleReturnCode(); 10112 } 10113 10114 class MeasureParams extends HandlerParams { 10115 private final PackageStats mStats; 10116 private boolean mSuccess; 10117 10118 private final IPackageStatsObserver mObserver; 10119 10120 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10121 super(new UserHandle(stats.userHandle)); 10122 mObserver = observer; 10123 mStats = stats; 10124 } 10125 10126 @Override 10127 public String toString() { 10128 return "MeasureParams{" 10129 + Integer.toHexString(System.identityHashCode(this)) 10130 + " " + mStats.packageName + "}"; 10131 } 10132 10133 @Override 10134 void handleStartCopy() throws RemoteException { 10135 synchronized (mInstallLock) { 10136 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10137 } 10138 10139 if (mSuccess) { 10140 final boolean mounted; 10141 if (Environment.isExternalStorageEmulated()) { 10142 mounted = true; 10143 } else { 10144 final String status = Environment.getExternalStorageState(); 10145 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10146 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10147 } 10148 10149 if (mounted) { 10150 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10151 10152 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10153 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10154 10155 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10156 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10157 10158 // Always subtract cache size, since it's a subdirectory 10159 mStats.externalDataSize -= mStats.externalCacheSize; 10160 10161 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10162 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10163 10164 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10165 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10166 } 10167 } 10168 } 10169 10170 @Override 10171 void handleReturnCode() { 10172 if (mObserver != null) { 10173 try { 10174 mObserver.onGetStatsCompleted(mStats, mSuccess); 10175 } catch (RemoteException e) { 10176 Slog.i(TAG, "Observer no longer exists."); 10177 } 10178 } 10179 } 10180 10181 @Override 10182 void handleServiceError() { 10183 Slog.e(TAG, "Could not measure application " + mStats.packageName 10184 + " external storage"); 10185 } 10186 } 10187 10188 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10189 throws RemoteException { 10190 long result = 0; 10191 for (File path : paths) { 10192 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10193 } 10194 return result; 10195 } 10196 10197 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10198 for (File path : paths) { 10199 try { 10200 mcs.clearDirectory(path.getAbsolutePath()); 10201 } catch (RemoteException e) { 10202 } 10203 } 10204 } 10205 10206 static class OriginInfo { 10207 /** 10208 * Location where install is coming from, before it has been 10209 * copied/renamed into place. This could be a single monolithic APK 10210 * file, or a cluster directory. This location may be untrusted. 10211 */ 10212 final File file; 10213 final String cid; 10214 10215 /** 10216 * Flag indicating that {@link #file} or {@link #cid} has already been 10217 * staged, meaning downstream users don't need to defensively copy the 10218 * contents. 10219 */ 10220 final boolean staged; 10221 10222 /** 10223 * Flag indicating that {@link #file} or {@link #cid} is an already 10224 * installed app that is being moved. 10225 */ 10226 final boolean existing; 10227 10228 final String resolvedPath; 10229 final File resolvedFile; 10230 10231 static OriginInfo fromNothing() { 10232 return new OriginInfo(null, null, false, false); 10233 } 10234 10235 static OriginInfo fromUntrustedFile(File file) { 10236 return new OriginInfo(file, null, false, false); 10237 } 10238 10239 static OriginInfo fromExistingFile(File file) { 10240 return new OriginInfo(file, null, false, true); 10241 } 10242 10243 static OriginInfo fromStagedFile(File file) { 10244 return new OriginInfo(file, null, true, false); 10245 } 10246 10247 static OriginInfo fromStagedContainer(String cid) { 10248 return new OriginInfo(null, cid, true, false); 10249 } 10250 10251 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10252 this.file = file; 10253 this.cid = cid; 10254 this.staged = staged; 10255 this.existing = existing; 10256 10257 if (cid != null) { 10258 resolvedPath = PackageHelper.getSdDir(cid); 10259 resolvedFile = new File(resolvedPath); 10260 } else if (file != null) { 10261 resolvedPath = file.getAbsolutePath(); 10262 resolvedFile = file; 10263 } else { 10264 resolvedPath = null; 10265 resolvedFile = null; 10266 } 10267 } 10268 } 10269 10270 class MoveInfo { 10271 final int moveId; 10272 final String fromUuid; 10273 final String toUuid; 10274 final String packageName; 10275 final String dataAppName; 10276 final int appId; 10277 final String seinfo; 10278 10279 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10280 String dataAppName, int appId, String seinfo) { 10281 this.moveId = moveId; 10282 this.fromUuid = fromUuid; 10283 this.toUuid = toUuid; 10284 this.packageName = packageName; 10285 this.dataAppName = dataAppName; 10286 this.appId = appId; 10287 this.seinfo = seinfo; 10288 } 10289 } 10290 10291 class InstallParams extends HandlerParams { 10292 final OriginInfo origin; 10293 final MoveInfo move; 10294 final IPackageInstallObserver2 observer; 10295 int installFlags; 10296 final String installerPackageName; 10297 final String volumeUuid; 10298 final VerificationParams verificationParams; 10299 private InstallArgs mArgs; 10300 private int mRet; 10301 final String packageAbiOverride; 10302 10303 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10304 int installFlags, String installerPackageName, String volumeUuid, 10305 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10306 super(user); 10307 this.origin = origin; 10308 this.move = move; 10309 this.observer = observer; 10310 this.installFlags = installFlags; 10311 this.installerPackageName = installerPackageName; 10312 this.volumeUuid = volumeUuid; 10313 this.verificationParams = verificationParams; 10314 this.packageAbiOverride = packageAbiOverride; 10315 } 10316 10317 @Override 10318 public String toString() { 10319 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10320 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10321 } 10322 10323 public ManifestDigest getManifestDigest() { 10324 if (verificationParams == null) { 10325 return null; 10326 } 10327 return verificationParams.getManifestDigest(); 10328 } 10329 10330 private int installLocationPolicy(PackageInfoLite pkgLite) { 10331 String packageName = pkgLite.packageName; 10332 int installLocation = pkgLite.installLocation; 10333 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10334 // reader 10335 synchronized (mPackages) { 10336 PackageParser.Package pkg = mPackages.get(packageName); 10337 if (pkg != null) { 10338 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10339 // Check for downgrading. 10340 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10341 try { 10342 checkDowngrade(pkg, pkgLite); 10343 } catch (PackageManagerException e) { 10344 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10345 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10346 } 10347 } 10348 // Check for updated system application. 10349 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10350 if (onSd) { 10351 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10352 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10353 } 10354 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10355 } else { 10356 if (onSd) { 10357 // Install flag overrides everything. 10358 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10359 } 10360 // If current upgrade specifies particular preference 10361 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10362 // Application explicitly specified internal. 10363 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10364 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10365 // App explictly prefers external. Let policy decide 10366 } else { 10367 // Prefer previous location 10368 if (isExternal(pkg)) { 10369 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10370 } 10371 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10372 } 10373 } 10374 } else { 10375 // Invalid install. Return error code 10376 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10377 } 10378 } 10379 } 10380 // All the special cases have been taken care of. 10381 // Return result based on recommended install location. 10382 if (onSd) { 10383 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10384 } 10385 return pkgLite.recommendedInstallLocation; 10386 } 10387 10388 /* 10389 * Invoke remote method to get package information and install 10390 * location values. Override install location based on default 10391 * policy if needed and then create install arguments based 10392 * on the install location. 10393 */ 10394 public void handleStartCopy() throws RemoteException { 10395 int ret = PackageManager.INSTALL_SUCCEEDED; 10396 10397 // If we're already staged, we've firmly committed to an install location 10398 if (origin.staged) { 10399 if (origin.file != null) { 10400 installFlags |= PackageManager.INSTALL_INTERNAL; 10401 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10402 } else if (origin.cid != null) { 10403 installFlags |= PackageManager.INSTALL_EXTERNAL; 10404 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10405 } else { 10406 throw new IllegalStateException("Invalid stage location"); 10407 } 10408 } 10409 10410 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10411 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10412 10413 PackageInfoLite pkgLite = null; 10414 10415 if (onInt && onSd) { 10416 // Check if both bits are set. 10417 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10418 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10419 } else { 10420 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10421 packageAbiOverride); 10422 10423 /* 10424 * If we have too little free space, try to free cache 10425 * before giving up. 10426 */ 10427 if (!origin.staged && pkgLite.recommendedInstallLocation 10428 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10429 // TODO: focus freeing disk space on the target device 10430 final StorageManager storage = StorageManager.from(mContext); 10431 final long lowThreshold = storage.getStorageLowBytes( 10432 Environment.getDataDirectory()); 10433 10434 final long sizeBytes = mContainerService.calculateInstalledSize( 10435 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10436 10437 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10438 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10439 installFlags, packageAbiOverride); 10440 } 10441 10442 /* 10443 * The cache free must have deleted the file we 10444 * downloaded to install. 10445 * 10446 * TODO: fix the "freeCache" call to not delete 10447 * the file we care about. 10448 */ 10449 if (pkgLite.recommendedInstallLocation 10450 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10451 pkgLite.recommendedInstallLocation 10452 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10453 } 10454 } 10455 } 10456 10457 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10458 int loc = pkgLite.recommendedInstallLocation; 10459 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10460 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10461 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10462 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10463 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10464 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10465 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10466 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10467 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10468 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10469 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10470 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10471 } else { 10472 // Override with defaults if needed. 10473 loc = installLocationPolicy(pkgLite); 10474 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10475 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10476 } else if (!onSd && !onInt) { 10477 // Override install location with flags 10478 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10479 // Set the flag to install on external media. 10480 installFlags |= PackageManager.INSTALL_EXTERNAL; 10481 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10482 } else { 10483 // Make sure the flag for installing on external 10484 // media is unset 10485 installFlags |= PackageManager.INSTALL_INTERNAL; 10486 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10487 } 10488 } 10489 } 10490 } 10491 10492 final InstallArgs args = createInstallArgs(this); 10493 mArgs = args; 10494 10495 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10496 /* 10497 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10498 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10499 */ 10500 int userIdentifier = getUser().getIdentifier(); 10501 if (userIdentifier == UserHandle.USER_ALL 10502 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10503 userIdentifier = UserHandle.USER_OWNER; 10504 } 10505 10506 /* 10507 * Determine if we have any installed package verifiers. If we 10508 * do, then we'll defer to them to verify the packages. 10509 */ 10510 final int requiredUid = mRequiredVerifierPackage == null ? -1 10511 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10512 if (!origin.existing && requiredUid != -1 10513 && isVerificationEnabled(userIdentifier, installFlags)) { 10514 final Intent verification = new Intent( 10515 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10516 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10517 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10518 PACKAGE_MIME_TYPE); 10519 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10520 10521 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10522 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10523 0 /* TODO: Which userId? */); 10524 10525 if (DEBUG_VERIFY) { 10526 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10527 + verification.toString() + " with " + pkgLite.verifiers.length 10528 + " optional verifiers"); 10529 } 10530 10531 final int verificationId = mPendingVerificationToken++; 10532 10533 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10534 10535 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10536 installerPackageName); 10537 10538 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10539 installFlags); 10540 10541 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10542 pkgLite.packageName); 10543 10544 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10545 pkgLite.versionCode); 10546 10547 if (verificationParams != null) { 10548 if (verificationParams.getVerificationURI() != null) { 10549 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10550 verificationParams.getVerificationURI()); 10551 } 10552 if (verificationParams.getOriginatingURI() != null) { 10553 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10554 verificationParams.getOriginatingURI()); 10555 } 10556 if (verificationParams.getReferrer() != null) { 10557 verification.putExtra(Intent.EXTRA_REFERRER, 10558 verificationParams.getReferrer()); 10559 } 10560 if (verificationParams.getOriginatingUid() >= 0) { 10561 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10562 verificationParams.getOriginatingUid()); 10563 } 10564 if (verificationParams.getInstallerUid() >= 0) { 10565 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10566 verificationParams.getInstallerUid()); 10567 } 10568 } 10569 10570 final PackageVerificationState verificationState = new PackageVerificationState( 10571 requiredUid, args); 10572 10573 mPendingVerification.append(verificationId, verificationState); 10574 10575 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10576 receivers, verificationState); 10577 10578 /* 10579 * If any sufficient verifiers were listed in the package 10580 * manifest, attempt to ask them. 10581 */ 10582 if (sufficientVerifiers != null) { 10583 final int N = sufficientVerifiers.size(); 10584 if (N == 0) { 10585 Slog.i(TAG, "Additional verifiers required, but none installed."); 10586 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10587 } else { 10588 for (int i = 0; i < N; i++) { 10589 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10590 10591 final Intent sufficientIntent = new Intent(verification); 10592 sufficientIntent.setComponent(verifierComponent); 10593 10594 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10595 } 10596 } 10597 } 10598 10599 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10600 mRequiredVerifierPackage, receivers); 10601 if (ret == PackageManager.INSTALL_SUCCEEDED 10602 && mRequiredVerifierPackage != null) { 10603 /* 10604 * Send the intent to the required verification agent, 10605 * but only start the verification timeout after the 10606 * target BroadcastReceivers have run. 10607 */ 10608 verification.setComponent(requiredVerifierComponent); 10609 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10610 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10611 new BroadcastReceiver() { 10612 @Override 10613 public void onReceive(Context context, Intent intent) { 10614 final Message msg = mHandler 10615 .obtainMessage(CHECK_PENDING_VERIFICATION); 10616 msg.arg1 = verificationId; 10617 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10618 } 10619 }, null, 0, null, null); 10620 10621 /* 10622 * We don't want the copy to proceed until verification 10623 * succeeds, so null out this field. 10624 */ 10625 mArgs = null; 10626 } 10627 } else { 10628 /* 10629 * No package verification is enabled, so immediately start 10630 * the remote call to initiate copy using temporary file. 10631 */ 10632 ret = args.copyApk(mContainerService, true); 10633 } 10634 } 10635 10636 mRet = ret; 10637 } 10638 10639 @Override 10640 void handleReturnCode() { 10641 // If mArgs is null, then MCS couldn't be reached. When it 10642 // reconnects, it will try again to install. At that point, this 10643 // will succeed. 10644 if (mArgs != null) { 10645 processPendingInstall(mArgs, mRet); 10646 } 10647 } 10648 10649 @Override 10650 void handleServiceError() { 10651 mArgs = createInstallArgs(this); 10652 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10653 } 10654 10655 public boolean isForwardLocked() { 10656 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10657 } 10658 } 10659 10660 /** 10661 * Used during creation of InstallArgs 10662 * 10663 * @param installFlags package installation flags 10664 * @return true if should be installed on external storage 10665 */ 10666 private static boolean installOnExternalAsec(int installFlags) { 10667 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10668 return false; 10669 } 10670 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10671 return true; 10672 } 10673 return false; 10674 } 10675 10676 /** 10677 * Used during creation of InstallArgs 10678 * 10679 * @param installFlags package installation flags 10680 * @return true if should be installed as forward locked 10681 */ 10682 private static boolean installForwardLocked(int installFlags) { 10683 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10684 } 10685 10686 private InstallArgs createInstallArgs(InstallParams params) { 10687 if (params.move != null) { 10688 return new MoveInstallArgs(params); 10689 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10690 return new AsecInstallArgs(params); 10691 } else { 10692 return new FileInstallArgs(params); 10693 } 10694 } 10695 10696 /** 10697 * Create args that describe an existing installed package. Typically used 10698 * when cleaning up old installs, or used as a move source. 10699 */ 10700 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10701 String resourcePath, String[] instructionSets) { 10702 final boolean isInAsec; 10703 if (installOnExternalAsec(installFlags)) { 10704 /* Apps on SD card are always in ASEC containers. */ 10705 isInAsec = true; 10706 } else if (installForwardLocked(installFlags) 10707 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10708 /* 10709 * Forward-locked apps are only in ASEC containers if they're the 10710 * new style 10711 */ 10712 isInAsec = true; 10713 } else { 10714 isInAsec = false; 10715 } 10716 10717 if (isInAsec) { 10718 return new AsecInstallArgs(codePath, instructionSets, 10719 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10720 } else { 10721 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10722 } 10723 } 10724 10725 static abstract class InstallArgs { 10726 /** @see InstallParams#origin */ 10727 final OriginInfo origin; 10728 /** @see InstallParams#move */ 10729 final MoveInfo move; 10730 10731 final IPackageInstallObserver2 observer; 10732 // Always refers to PackageManager flags only 10733 final int installFlags; 10734 final String installerPackageName; 10735 final String volumeUuid; 10736 final ManifestDigest manifestDigest; 10737 final UserHandle user; 10738 final String abiOverride; 10739 10740 // The list of instruction sets supported by this app. This is currently 10741 // only used during the rmdex() phase to clean up resources. We can get rid of this 10742 // if we move dex files under the common app path. 10743 /* nullable */ String[] instructionSets; 10744 10745 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10746 int installFlags, String installerPackageName, String volumeUuid, 10747 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10748 String abiOverride) { 10749 this.origin = origin; 10750 this.move = move; 10751 this.installFlags = installFlags; 10752 this.observer = observer; 10753 this.installerPackageName = installerPackageName; 10754 this.volumeUuid = volumeUuid; 10755 this.manifestDigest = manifestDigest; 10756 this.user = user; 10757 this.instructionSets = instructionSets; 10758 this.abiOverride = abiOverride; 10759 } 10760 10761 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10762 abstract int doPreInstall(int status); 10763 10764 /** 10765 * Rename package into final resting place. All paths on the given 10766 * scanned package should be updated to reflect the rename. 10767 */ 10768 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10769 abstract int doPostInstall(int status, int uid); 10770 10771 /** @see PackageSettingBase#codePathString */ 10772 abstract String getCodePath(); 10773 /** @see PackageSettingBase#resourcePathString */ 10774 abstract String getResourcePath(); 10775 10776 // Need installer lock especially for dex file removal. 10777 abstract void cleanUpResourcesLI(); 10778 abstract boolean doPostDeleteLI(boolean delete); 10779 10780 /** 10781 * Called before the source arguments are copied. This is used mostly 10782 * for MoveParams when it needs to read the source file to put it in the 10783 * destination. 10784 */ 10785 int doPreCopy() { 10786 return PackageManager.INSTALL_SUCCEEDED; 10787 } 10788 10789 /** 10790 * Called after the source arguments are copied. This is used mostly for 10791 * MoveParams when it needs to read the source file to put it in the 10792 * destination. 10793 * 10794 * @return 10795 */ 10796 int doPostCopy(int uid) { 10797 return PackageManager.INSTALL_SUCCEEDED; 10798 } 10799 10800 protected boolean isFwdLocked() { 10801 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10802 } 10803 10804 protected boolean isExternalAsec() { 10805 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10806 } 10807 10808 UserHandle getUser() { 10809 return user; 10810 } 10811 } 10812 10813 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10814 if (!allCodePaths.isEmpty()) { 10815 if (instructionSets == null) { 10816 throw new IllegalStateException("instructionSet == null"); 10817 } 10818 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10819 for (String codePath : allCodePaths) { 10820 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10821 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10822 if (retCode < 0) { 10823 Slog.w(TAG, "Couldn't remove dex file for package: " 10824 + " at location " + codePath + ", retcode=" + retCode); 10825 // we don't consider this to be a failure of the core package deletion 10826 } 10827 } 10828 } 10829 } 10830 } 10831 10832 /** 10833 * Logic to handle installation of non-ASEC applications, including copying 10834 * and renaming logic. 10835 */ 10836 class FileInstallArgs extends InstallArgs { 10837 private File codeFile; 10838 private File resourceFile; 10839 10840 // Example topology: 10841 // /data/app/com.example/base.apk 10842 // /data/app/com.example/split_foo.apk 10843 // /data/app/com.example/lib/arm/libfoo.so 10844 // /data/app/com.example/lib/arm64/libfoo.so 10845 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10846 10847 /** New install */ 10848 FileInstallArgs(InstallParams params) { 10849 super(params.origin, params.move, params.observer, params.installFlags, 10850 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10851 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10852 if (isFwdLocked()) { 10853 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10854 } 10855 } 10856 10857 /** Existing install */ 10858 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10859 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10860 null); 10861 this.codeFile = (codePath != null) ? new File(codePath) : null; 10862 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10863 } 10864 10865 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10866 if (origin.staged) { 10867 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10868 codeFile = origin.file; 10869 resourceFile = origin.file; 10870 return PackageManager.INSTALL_SUCCEEDED; 10871 } 10872 10873 try { 10874 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10875 codeFile = tempDir; 10876 resourceFile = tempDir; 10877 } catch (IOException e) { 10878 Slog.w(TAG, "Failed to create copy file: " + e); 10879 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10880 } 10881 10882 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10883 @Override 10884 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10885 if (!FileUtils.isValidExtFilename(name)) { 10886 throw new IllegalArgumentException("Invalid filename: " + name); 10887 } 10888 try { 10889 final File file = new File(codeFile, name); 10890 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10891 O_RDWR | O_CREAT, 0644); 10892 Os.chmod(file.getAbsolutePath(), 0644); 10893 return new ParcelFileDescriptor(fd); 10894 } catch (ErrnoException e) { 10895 throw new RemoteException("Failed to open: " + e.getMessage()); 10896 } 10897 } 10898 }; 10899 10900 int ret = PackageManager.INSTALL_SUCCEEDED; 10901 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10902 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10903 Slog.e(TAG, "Failed to copy package"); 10904 return ret; 10905 } 10906 10907 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10908 NativeLibraryHelper.Handle handle = null; 10909 try { 10910 handle = NativeLibraryHelper.Handle.create(codeFile); 10911 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10912 abiOverride); 10913 } catch (IOException e) { 10914 Slog.e(TAG, "Copying native libraries failed", e); 10915 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10916 } finally { 10917 IoUtils.closeQuietly(handle); 10918 } 10919 10920 return ret; 10921 } 10922 10923 int doPreInstall(int status) { 10924 if (status != PackageManager.INSTALL_SUCCEEDED) { 10925 cleanUp(); 10926 } 10927 return status; 10928 } 10929 10930 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10931 if (status != PackageManager.INSTALL_SUCCEEDED) { 10932 cleanUp(); 10933 return false; 10934 } 10935 10936 final File targetDir = codeFile.getParentFile(); 10937 final File beforeCodeFile = codeFile; 10938 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10939 10940 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10941 try { 10942 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10943 } catch (ErrnoException e) { 10944 Slog.w(TAG, "Failed to rename", e); 10945 return false; 10946 } 10947 10948 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10949 Slog.w(TAG, "Failed to restorecon"); 10950 return false; 10951 } 10952 10953 // Reflect the rename internally 10954 codeFile = afterCodeFile; 10955 resourceFile = afterCodeFile; 10956 10957 // Reflect the rename in scanned details 10958 pkg.codePath = afterCodeFile.getAbsolutePath(); 10959 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10960 pkg.baseCodePath); 10961 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10962 pkg.splitCodePaths); 10963 10964 // Reflect the rename in app info 10965 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10966 pkg.applicationInfo.setCodePath(pkg.codePath); 10967 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10968 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10969 pkg.applicationInfo.setResourcePath(pkg.codePath); 10970 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10971 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10972 10973 return true; 10974 } 10975 10976 int doPostInstall(int status, int uid) { 10977 if (status != PackageManager.INSTALL_SUCCEEDED) { 10978 cleanUp(); 10979 } 10980 return status; 10981 } 10982 10983 @Override 10984 String getCodePath() { 10985 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10986 } 10987 10988 @Override 10989 String getResourcePath() { 10990 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10991 } 10992 10993 private boolean cleanUp() { 10994 if (codeFile == null || !codeFile.exists()) { 10995 return false; 10996 } 10997 10998 if (codeFile.isDirectory()) { 10999 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11000 } else { 11001 codeFile.delete(); 11002 } 11003 11004 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11005 resourceFile.delete(); 11006 } 11007 11008 return true; 11009 } 11010 11011 void cleanUpResourcesLI() { 11012 // Try enumerating all code paths before deleting 11013 List<String> allCodePaths = Collections.EMPTY_LIST; 11014 if (codeFile != null && codeFile.exists()) { 11015 try { 11016 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11017 allCodePaths = pkg.getAllCodePaths(); 11018 } catch (PackageParserException e) { 11019 // Ignored; we tried our best 11020 } 11021 } 11022 11023 cleanUp(); 11024 removeDexFiles(allCodePaths, instructionSets); 11025 } 11026 11027 boolean doPostDeleteLI(boolean delete) { 11028 // XXX err, shouldn't we respect the delete flag? 11029 cleanUpResourcesLI(); 11030 return true; 11031 } 11032 } 11033 11034 private boolean isAsecExternal(String cid) { 11035 final String asecPath = PackageHelper.getSdFilesystem(cid); 11036 return !asecPath.startsWith(mAsecInternalPath); 11037 } 11038 11039 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11040 PackageManagerException { 11041 if (copyRet < 0) { 11042 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11043 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11044 throw new PackageManagerException(copyRet, message); 11045 } 11046 } 11047 } 11048 11049 /** 11050 * Extract the MountService "container ID" from the full code path of an 11051 * .apk. 11052 */ 11053 static String cidFromCodePath(String fullCodePath) { 11054 int eidx = fullCodePath.lastIndexOf("/"); 11055 String subStr1 = fullCodePath.substring(0, eidx); 11056 int sidx = subStr1.lastIndexOf("/"); 11057 return subStr1.substring(sidx+1, eidx); 11058 } 11059 11060 /** 11061 * Logic to handle installation of ASEC applications, including copying and 11062 * renaming logic. 11063 */ 11064 class AsecInstallArgs extends InstallArgs { 11065 static final String RES_FILE_NAME = "pkg.apk"; 11066 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11067 11068 String cid; 11069 String packagePath; 11070 String resourcePath; 11071 11072 /** New install */ 11073 AsecInstallArgs(InstallParams params) { 11074 super(params.origin, params.move, params.observer, params.installFlags, 11075 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11076 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11077 } 11078 11079 /** Existing install */ 11080 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11081 boolean isExternal, boolean isForwardLocked) { 11082 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11083 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11084 instructionSets, null); 11085 // Hackily pretend we're still looking at a full code path 11086 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11087 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11088 } 11089 11090 // Extract cid from fullCodePath 11091 int eidx = fullCodePath.lastIndexOf("/"); 11092 String subStr1 = fullCodePath.substring(0, eidx); 11093 int sidx = subStr1.lastIndexOf("/"); 11094 cid = subStr1.substring(sidx+1, eidx); 11095 setMountPath(subStr1); 11096 } 11097 11098 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11099 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11100 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11101 instructionSets, null); 11102 this.cid = cid; 11103 setMountPath(PackageHelper.getSdDir(cid)); 11104 } 11105 11106 void createCopyFile() { 11107 cid = mInstallerService.allocateExternalStageCidLegacy(); 11108 } 11109 11110 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11111 if (origin.staged) { 11112 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11113 cid = origin.cid; 11114 setMountPath(PackageHelper.getSdDir(cid)); 11115 return PackageManager.INSTALL_SUCCEEDED; 11116 } 11117 11118 if (temp) { 11119 createCopyFile(); 11120 } else { 11121 /* 11122 * Pre-emptively destroy the container since it's destroyed if 11123 * copying fails due to it existing anyway. 11124 */ 11125 PackageHelper.destroySdDir(cid); 11126 } 11127 11128 final String newMountPath = imcs.copyPackageToContainer( 11129 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11130 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11131 11132 if (newMountPath != null) { 11133 setMountPath(newMountPath); 11134 return PackageManager.INSTALL_SUCCEEDED; 11135 } else { 11136 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11137 } 11138 } 11139 11140 @Override 11141 String getCodePath() { 11142 return packagePath; 11143 } 11144 11145 @Override 11146 String getResourcePath() { 11147 return resourcePath; 11148 } 11149 11150 int doPreInstall(int status) { 11151 if (status != PackageManager.INSTALL_SUCCEEDED) { 11152 // Destroy container 11153 PackageHelper.destroySdDir(cid); 11154 } else { 11155 boolean mounted = PackageHelper.isContainerMounted(cid); 11156 if (!mounted) { 11157 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11158 Process.SYSTEM_UID); 11159 if (newMountPath != null) { 11160 setMountPath(newMountPath); 11161 } else { 11162 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11163 } 11164 } 11165 } 11166 return status; 11167 } 11168 11169 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11170 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11171 String newMountPath = null; 11172 if (PackageHelper.isContainerMounted(cid)) { 11173 // Unmount the container 11174 if (!PackageHelper.unMountSdDir(cid)) { 11175 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11176 return false; 11177 } 11178 } 11179 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11180 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11181 " which might be stale. Will try to clean up."); 11182 // Clean up the stale container and proceed to recreate. 11183 if (!PackageHelper.destroySdDir(newCacheId)) { 11184 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11185 return false; 11186 } 11187 // Successfully cleaned up stale container. Try to rename again. 11188 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11189 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11190 + " inspite of cleaning it up."); 11191 return false; 11192 } 11193 } 11194 if (!PackageHelper.isContainerMounted(newCacheId)) { 11195 Slog.w(TAG, "Mounting container " + newCacheId); 11196 newMountPath = PackageHelper.mountSdDir(newCacheId, 11197 getEncryptKey(), Process.SYSTEM_UID); 11198 } else { 11199 newMountPath = PackageHelper.getSdDir(newCacheId); 11200 } 11201 if (newMountPath == null) { 11202 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11203 return false; 11204 } 11205 Log.i(TAG, "Succesfully renamed " + cid + 11206 " to " + newCacheId + 11207 " at new path: " + newMountPath); 11208 cid = newCacheId; 11209 11210 final File beforeCodeFile = new File(packagePath); 11211 setMountPath(newMountPath); 11212 final File afterCodeFile = new File(packagePath); 11213 11214 // Reflect the rename in scanned details 11215 pkg.codePath = afterCodeFile.getAbsolutePath(); 11216 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11217 pkg.baseCodePath); 11218 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11219 pkg.splitCodePaths); 11220 11221 // Reflect the rename in app info 11222 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11223 pkg.applicationInfo.setCodePath(pkg.codePath); 11224 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11225 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11226 pkg.applicationInfo.setResourcePath(pkg.codePath); 11227 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11228 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11229 11230 return true; 11231 } 11232 11233 private void setMountPath(String mountPath) { 11234 final File mountFile = new File(mountPath); 11235 11236 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11237 if (monolithicFile.exists()) { 11238 packagePath = monolithicFile.getAbsolutePath(); 11239 if (isFwdLocked()) { 11240 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11241 } else { 11242 resourcePath = packagePath; 11243 } 11244 } else { 11245 packagePath = mountFile.getAbsolutePath(); 11246 resourcePath = packagePath; 11247 } 11248 } 11249 11250 int doPostInstall(int status, int uid) { 11251 if (status != PackageManager.INSTALL_SUCCEEDED) { 11252 cleanUp(); 11253 } else { 11254 final int groupOwner; 11255 final String protectedFile; 11256 if (isFwdLocked()) { 11257 groupOwner = UserHandle.getSharedAppGid(uid); 11258 protectedFile = RES_FILE_NAME; 11259 } else { 11260 groupOwner = -1; 11261 protectedFile = null; 11262 } 11263 11264 if (uid < Process.FIRST_APPLICATION_UID 11265 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11266 Slog.e(TAG, "Failed to finalize " + cid); 11267 PackageHelper.destroySdDir(cid); 11268 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11269 } 11270 11271 boolean mounted = PackageHelper.isContainerMounted(cid); 11272 if (!mounted) { 11273 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11274 } 11275 } 11276 return status; 11277 } 11278 11279 private void cleanUp() { 11280 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11281 11282 // Destroy secure container 11283 PackageHelper.destroySdDir(cid); 11284 } 11285 11286 private List<String> getAllCodePaths() { 11287 final File codeFile = new File(getCodePath()); 11288 if (codeFile != null && codeFile.exists()) { 11289 try { 11290 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11291 return pkg.getAllCodePaths(); 11292 } catch (PackageParserException e) { 11293 // Ignored; we tried our best 11294 } 11295 } 11296 return Collections.EMPTY_LIST; 11297 } 11298 11299 void cleanUpResourcesLI() { 11300 // Enumerate all code paths before deleting 11301 cleanUpResourcesLI(getAllCodePaths()); 11302 } 11303 11304 private void cleanUpResourcesLI(List<String> allCodePaths) { 11305 cleanUp(); 11306 removeDexFiles(allCodePaths, instructionSets); 11307 } 11308 11309 String getPackageName() { 11310 return getAsecPackageName(cid); 11311 } 11312 11313 boolean doPostDeleteLI(boolean delete) { 11314 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11315 final List<String> allCodePaths = getAllCodePaths(); 11316 boolean mounted = PackageHelper.isContainerMounted(cid); 11317 if (mounted) { 11318 // Unmount first 11319 if (PackageHelper.unMountSdDir(cid)) { 11320 mounted = false; 11321 } 11322 } 11323 if (!mounted && delete) { 11324 cleanUpResourcesLI(allCodePaths); 11325 } 11326 return !mounted; 11327 } 11328 11329 @Override 11330 int doPreCopy() { 11331 if (isFwdLocked()) { 11332 if (!PackageHelper.fixSdPermissions(cid, 11333 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11334 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11335 } 11336 } 11337 11338 return PackageManager.INSTALL_SUCCEEDED; 11339 } 11340 11341 @Override 11342 int doPostCopy(int uid) { 11343 if (isFwdLocked()) { 11344 if (uid < Process.FIRST_APPLICATION_UID 11345 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11346 RES_FILE_NAME)) { 11347 Slog.e(TAG, "Failed to finalize " + cid); 11348 PackageHelper.destroySdDir(cid); 11349 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11350 } 11351 } 11352 11353 return PackageManager.INSTALL_SUCCEEDED; 11354 } 11355 } 11356 11357 /** 11358 * Logic to handle movement of existing installed applications. 11359 */ 11360 class MoveInstallArgs extends InstallArgs { 11361 private File codeFile; 11362 private File resourceFile; 11363 11364 /** New install */ 11365 MoveInstallArgs(InstallParams params) { 11366 super(params.origin, params.move, params.observer, params.installFlags, 11367 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11368 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11369 } 11370 11371 int copyApk(IMediaContainerService imcs, boolean temp) { 11372 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11373 + move.fromUuid + " to " + move.toUuid); 11374 synchronized (mInstaller) { 11375 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11376 move.dataAppName, move.appId, move.seinfo) != 0) { 11377 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11378 } 11379 } 11380 11381 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11382 resourceFile = codeFile; 11383 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11384 11385 return PackageManager.INSTALL_SUCCEEDED; 11386 } 11387 11388 int doPreInstall(int status) { 11389 if (status != PackageManager.INSTALL_SUCCEEDED) { 11390 cleanUp(move.toUuid); 11391 } 11392 return status; 11393 } 11394 11395 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11396 if (status != PackageManager.INSTALL_SUCCEEDED) { 11397 cleanUp(move.toUuid); 11398 return false; 11399 } 11400 11401 // Reflect the move in app info 11402 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11403 pkg.applicationInfo.setCodePath(pkg.codePath); 11404 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11405 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11406 pkg.applicationInfo.setResourcePath(pkg.codePath); 11407 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11408 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11409 11410 return true; 11411 } 11412 11413 int doPostInstall(int status, int uid) { 11414 if (status == PackageManager.INSTALL_SUCCEEDED) { 11415 cleanUp(move.fromUuid); 11416 } else { 11417 cleanUp(move.toUuid); 11418 } 11419 return status; 11420 } 11421 11422 @Override 11423 String getCodePath() { 11424 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11425 } 11426 11427 @Override 11428 String getResourcePath() { 11429 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11430 } 11431 11432 private boolean cleanUp(String volumeUuid) { 11433 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11434 move.dataAppName); 11435 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11436 synchronized (mInstallLock) { 11437 // Clean up both app data and code 11438 removeDataDirsLI(volumeUuid, move.packageName); 11439 if (codeFile.isDirectory()) { 11440 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11441 } else { 11442 codeFile.delete(); 11443 } 11444 } 11445 return true; 11446 } 11447 11448 void cleanUpResourcesLI() { 11449 throw new UnsupportedOperationException(); 11450 } 11451 11452 boolean doPostDeleteLI(boolean delete) { 11453 throw new UnsupportedOperationException(); 11454 } 11455 } 11456 11457 static String getAsecPackageName(String packageCid) { 11458 int idx = packageCid.lastIndexOf("-"); 11459 if (idx == -1) { 11460 return packageCid; 11461 } 11462 return packageCid.substring(0, idx); 11463 } 11464 11465 // Utility method used to create code paths based on package name and available index. 11466 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11467 String idxStr = ""; 11468 int idx = 1; 11469 // Fall back to default value of idx=1 if prefix is not 11470 // part of oldCodePath 11471 if (oldCodePath != null) { 11472 String subStr = oldCodePath; 11473 // Drop the suffix right away 11474 if (suffix != null && subStr.endsWith(suffix)) { 11475 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11476 } 11477 // If oldCodePath already contains prefix find out the 11478 // ending index to either increment or decrement. 11479 int sidx = subStr.lastIndexOf(prefix); 11480 if (sidx != -1) { 11481 subStr = subStr.substring(sidx + prefix.length()); 11482 if (subStr != null) { 11483 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11484 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11485 } 11486 try { 11487 idx = Integer.parseInt(subStr); 11488 if (idx <= 1) { 11489 idx++; 11490 } else { 11491 idx--; 11492 } 11493 } catch(NumberFormatException e) { 11494 } 11495 } 11496 } 11497 } 11498 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11499 return prefix + idxStr; 11500 } 11501 11502 private File getNextCodePath(File targetDir, String packageName) { 11503 int suffix = 1; 11504 File result; 11505 do { 11506 result = new File(targetDir, packageName + "-" + suffix); 11507 suffix++; 11508 } while (result.exists()); 11509 return result; 11510 } 11511 11512 // Utility method that returns the relative package path with respect 11513 // to the installation directory. Like say for /data/data/com.test-1.apk 11514 // string com.test-1 is returned. 11515 static String deriveCodePathName(String codePath) { 11516 if (codePath == null) { 11517 return null; 11518 } 11519 final File codeFile = new File(codePath); 11520 final String name = codeFile.getName(); 11521 if (codeFile.isDirectory()) { 11522 return name; 11523 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11524 final int lastDot = name.lastIndexOf('.'); 11525 return name.substring(0, lastDot); 11526 } else { 11527 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11528 return null; 11529 } 11530 } 11531 11532 class PackageInstalledInfo { 11533 String name; 11534 int uid; 11535 // The set of users that originally had this package installed. 11536 int[] origUsers; 11537 // The set of users that now have this package installed. 11538 int[] newUsers; 11539 PackageParser.Package pkg; 11540 int returnCode; 11541 String returnMsg; 11542 PackageRemovedInfo removedInfo; 11543 11544 public void setError(int code, String msg) { 11545 returnCode = code; 11546 returnMsg = msg; 11547 Slog.w(TAG, msg); 11548 } 11549 11550 public void setError(String msg, PackageParserException e) { 11551 returnCode = e.error; 11552 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11553 Slog.w(TAG, msg, e); 11554 } 11555 11556 public void setError(String msg, PackageManagerException e) { 11557 returnCode = e.error; 11558 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11559 Slog.w(TAG, msg, e); 11560 } 11561 11562 // In some error cases we want to convey more info back to the observer 11563 String origPackage; 11564 String origPermission; 11565 } 11566 11567 /* 11568 * Install a non-existing package. 11569 */ 11570 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11571 UserHandle user, String installerPackageName, String volumeUuid, 11572 PackageInstalledInfo res) { 11573 // Remember this for later, in case we need to rollback this install 11574 String pkgName = pkg.packageName; 11575 11576 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11577 final boolean dataDirExists = Environment 11578 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11579 synchronized(mPackages) { 11580 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11581 // A package with the same name is already installed, though 11582 // it has been renamed to an older name. The package we 11583 // are trying to install should be installed as an update to 11584 // the existing one, but that has not been requested, so bail. 11585 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11586 + " without first uninstalling package running as " 11587 + mSettings.mRenamedPackages.get(pkgName)); 11588 return; 11589 } 11590 if (mPackages.containsKey(pkgName)) { 11591 // Don't allow installation over an existing package with the same name. 11592 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11593 + " without first uninstalling."); 11594 return; 11595 } 11596 } 11597 11598 try { 11599 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11600 System.currentTimeMillis(), user); 11601 11602 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11603 // delete the partially installed application. the data directory will have to be 11604 // restored if it was already existing 11605 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11606 // remove package from internal structures. Note that we want deletePackageX to 11607 // delete the package data and cache directories that it created in 11608 // scanPackageLocked, unless those directories existed before we even tried to 11609 // install. 11610 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11611 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11612 res.removedInfo, true); 11613 } 11614 11615 } catch (PackageManagerException e) { 11616 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11617 } 11618 } 11619 11620 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11621 // Can't rotate keys during boot or if sharedUser. 11622 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11623 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11624 return false; 11625 } 11626 // app is using upgradeKeySets; make sure all are valid 11627 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11628 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11629 for (int i = 0; i < upgradeKeySets.length; i++) { 11630 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11631 Slog.wtf(TAG, "Package " 11632 + (oldPs.name != null ? oldPs.name : "<null>") 11633 + " contains upgrade-key-set reference to unknown key-set: " 11634 + upgradeKeySets[i] 11635 + " reverting to signatures check."); 11636 return false; 11637 } 11638 } 11639 return true; 11640 } 11641 11642 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11643 // Upgrade keysets are being used. Determine if new package has a superset of the 11644 // required keys. 11645 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11646 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11647 for (int i = 0; i < upgradeKeySets.length; i++) { 11648 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11649 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11650 return true; 11651 } 11652 } 11653 return false; 11654 } 11655 11656 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11657 UserHandle user, String installerPackageName, String volumeUuid, 11658 PackageInstalledInfo res) { 11659 final PackageParser.Package oldPackage; 11660 final String pkgName = pkg.packageName; 11661 final int[] allUsers; 11662 final boolean[] perUserInstalled; 11663 final boolean weFroze; 11664 11665 // First find the old package info and check signatures 11666 synchronized(mPackages) { 11667 oldPackage = mPackages.get(pkgName); 11668 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11669 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11670 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11671 if(!checkUpgradeKeySetLP(ps, pkg)) { 11672 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11673 "New package not signed by keys specified by upgrade-keysets: " 11674 + pkgName); 11675 return; 11676 } 11677 } else { 11678 // default to original signature matching 11679 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11680 != PackageManager.SIGNATURE_MATCH) { 11681 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11682 "New package has a different signature: " + pkgName); 11683 return; 11684 } 11685 } 11686 11687 // In case of rollback, remember per-user/profile install state 11688 allUsers = sUserManager.getUserIds(); 11689 perUserInstalled = new boolean[allUsers.length]; 11690 for (int i = 0; i < allUsers.length; i++) { 11691 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11692 } 11693 11694 // Mark the app as frozen to prevent launching during the upgrade 11695 // process, and then kill all running instances 11696 if (!ps.frozen) { 11697 ps.frozen = true; 11698 weFroze = true; 11699 } else { 11700 weFroze = false; 11701 } 11702 } 11703 11704 // Now that we're guarded by frozen state, kill app during upgrade 11705 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11706 11707 try { 11708 boolean sysPkg = (isSystemApp(oldPackage)); 11709 if (sysPkg) { 11710 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11711 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11712 } else { 11713 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11714 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11715 } 11716 } finally { 11717 // Regardless of success or failure of upgrade steps above, always 11718 // unfreeze the package if we froze it 11719 if (weFroze) { 11720 unfreezePackage(pkgName); 11721 } 11722 } 11723 } 11724 11725 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11726 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11727 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11728 String volumeUuid, PackageInstalledInfo res) { 11729 String pkgName = deletedPackage.packageName; 11730 boolean deletedPkg = true; 11731 boolean updatedSettings = false; 11732 11733 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11734 + deletedPackage); 11735 long origUpdateTime; 11736 if (pkg.mExtras != null) { 11737 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11738 } else { 11739 origUpdateTime = 0; 11740 } 11741 11742 // First delete the existing package while retaining the data directory 11743 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11744 res.removedInfo, true)) { 11745 // If the existing package wasn't successfully deleted 11746 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11747 deletedPkg = false; 11748 } else { 11749 // Successfully deleted the old package; proceed with replace. 11750 11751 // If deleted package lived in a container, give users a chance to 11752 // relinquish resources before killing. 11753 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11754 if (DEBUG_INSTALL) { 11755 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11756 } 11757 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11758 final ArrayList<String> pkgList = new ArrayList<String>(1); 11759 pkgList.add(deletedPackage.applicationInfo.packageName); 11760 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11761 } 11762 11763 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11764 try { 11765 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11766 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11767 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11768 perUserInstalled, res, user); 11769 updatedSettings = true; 11770 } catch (PackageManagerException e) { 11771 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11772 } 11773 } 11774 11775 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11776 // remove package from internal structures. Note that we want deletePackageX to 11777 // delete the package data and cache directories that it created in 11778 // scanPackageLocked, unless those directories existed before we even tried to 11779 // install. 11780 if(updatedSettings) { 11781 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11782 deletePackageLI( 11783 pkgName, null, true, allUsers, perUserInstalled, 11784 PackageManager.DELETE_KEEP_DATA, 11785 res.removedInfo, true); 11786 } 11787 // Since we failed to install the new package we need to restore the old 11788 // package that we deleted. 11789 if (deletedPkg) { 11790 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11791 File restoreFile = new File(deletedPackage.codePath); 11792 // Parse old package 11793 boolean oldExternal = isExternal(deletedPackage); 11794 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11795 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11796 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11797 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11798 try { 11799 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11800 } catch (PackageManagerException e) { 11801 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11802 + e.getMessage()); 11803 return; 11804 } 11805 // Restore of old package succeeded. Update permissions. 11806 // writer 11807 synchronized (mPackages) { 11808 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11809 UPDATE_PERMISSIONS_ALL); 11810 // can downgrade to reader 11811 mSettings.writeLPr(); 11812 } 11813 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11814 } 11815 } 11816 } 11817 11818 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11819 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11820 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11821 String volumeUuid, PackageInstalledInfo res) { 11822 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11823 + ", old=" + deletedPackage); 11824 boolean disabledSystem = false; 11825 boolean updatedSettings = false; 11826 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11827 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11828 != 0) { 11829 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11830 } 11831 String packageName = deletedPackage.packageName; 11832 if (packageName == null) { 11833 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11834 "Attempt to delete null packageName."); 11835 return; 11836 } 11837 PackageParser.Package oldPkg; 11838 PackageSetting oldPkgSetting; 11839 // reader 11840 synchronized (mPackages) { 11841 oldPkg = mPackages.get(packageName); 11842 oldPkgSetting = mSettings.mPackages.get(packageName); 11843 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11844 (oldPkgSetting == null)) { 11845 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11846 "Couldn't find package:" + packageName + " information"); 11847 return; 11848 } 11849 } 11850 11851 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11852 res.removedInfo.removedPackage = packageName; 11853 // Remove existing system package 11854 removePackageLI(oldPkgSetting, true); 11855 // writer 11856 synchronized (mPackages) { 11857 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11858 if (!disabledSystem && deletedPackage != null) { 11859 // We didn't need to disable the .apk as a current system package, 11860 // which means we are replacing another update that is already 11861 // installed. We need to make sure to delete the older one's .apk. 11862 res.removedInfo.args = createInstallArgsForExisting(0, 11863 deletedPackage.applicationInfo.getCodePath(), 11864 deletedPackage.applicationInfo.getResourcePath(), 11865 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11866 } else { 11867 res.removedInfo.args = null; 11868 } 11869 } 11870 11871 // Successfully disabled the old package. Now proceed with re-installation 11872 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11873 11874 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11875 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11876 11877 PackageParser.Package newPackage = null; 11878 try { 11879 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11880 if (newPackage.mExtras != null) { 11881 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11882 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11883 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11884 11885 // is the update attempting to change shared user? that isn't going to work... 11886 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11887 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11888 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11889 + " to " + newPkgSetting.sharedUser); 11890 updatedSettings = true; 11891 } 11892 } 11893 11894 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11895 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11896 perUserInstalled, res, user); 11897 updatedSettings = true; 11898 } 11899 11900 } catch (PackageManagerException e) { 11901 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11902 } 11903 11904 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11905 // Re installation failed. Restore old information 11906 // Remove new pkg information 11907 if (newPackage != null) { 11908 removeInstalledPackageLI(newPackage, true); 11909 } 11910 // Add back the old system package 11911 try { 11912 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11913 } catch (PackageManagerException e) { 11914 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11915 } 11916 // Restore the old system information in Settings 11917 synchronized (mPackages) { 11918 if (disabledSystem) { 11919 mSettings.enableSystemPackageLPw(packageName); 11920 } 11921 if (updatedSettings) { 11922 mSettings.setInstallerPackageName(packageName, 11923 oldPkgSetting.installerPackageName); 11924 } 11925 mSettings.writeLPr(); 11926 } 11927 } 11928 } 11929 11930 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11931 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11932 UserHandle user) { 11933 String pkgName = newPackage.packageName; 11934 synchronized (mPackages) { 11935 //write settings. the installStatus will be incomplete at this stage. 11936 //note that the new package setting would have already been 11937 //added to mPackages. It hasn't been persisted yet. 11938 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11939 mSettings.writeLPr(); 11940 } 11941 11942 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11943 11944 synchronized (mPackages) { 11945 updatePermissionsLPw(newPackage.packageName, newPackage, 11946 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11947 ? UPDATE_PERMISSIONS_ALL : 0)); 11948 // For system-bundled packages, we assume that installing an upgraded version 11949 // of the package implies that the user actually wants to run that new code, 11950 // so we enable the package. 11951 PackageSetting ps = mSettings.mPackages.get(pkgName); 11952 if (ps != null) { 11953 if (isSystemApp(newPackage)) { 11954 // NB: implicit assumption that system package upgrades apply to all users 11955 if (DEBUG_INSTALL) { 11956 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11957 } 11958 if (res.origUsers != null) { 11959 for (int userHandle : res.origUsers) { 11960 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11961 userHandle, installerPackageName); 11962 } 11963 } 11964 // Also convey the prior install/uninstall state 11965 if (allUsers != null && perUserInstalled != null) { 11966 for (int i = 0; i < allUsers.length; i++) { 11967 if (DEBUG_INSTALL) { 11968 Slog.d(TAG, " user " + allUsers[i] 11969 + " => " + perUserInstalled[i]); 11970 } 11971 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11972 } 11973 // these install state changes will be persisted in the 11974 // upcoming call to mSettings.writeLPr(). 11975 } 11976 } 11977 // It's implied that when a user requests installation, they want the app to be 11978 // installed and enabled. 11979 int userId = user.getIdentifier(); 11980 if (userId != UserHandle.USER_ALL) { 11981 ps.setInstalled(true, userId); 11982 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11983 } 11984 } 11985 res.name = pkgName; 11986 res.uid = newPackage.applicationInfo.uid; 11987 res.pkg = newPackage; 11988 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11989 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11990 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11991 //to update install status 11992 mSettings.writeLPr(); 11993 } 11994 } 11995 11996 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11997 final int installFlags = args.installFlags; 11998 final String installerPackageName = args.installerPackageName; 11999 final String volumeUuid = args.volumeUuid; 12000 final File tmpPackageFile = new File(args.getCodePath()); 12001 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12002 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12003 || (args.volumeUuid != null)); 12004 boolean replace = false; 12005 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12006 if (args.move != null) { 12007 // moving a complete application; perfom an initial scan on the new install location 12008 scanFlags |= SCAN_INITIAL; 12009 } 12010 // Result object to be returned 12011 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12012 12013 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12014 // Retrieve PackageSettings and parse package 12015 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12016 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12017 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12018 PackageParser pp = new PackageParser(); 12019 pp.setSeparateProcesses(mSeparateProcesses); 12020 pp.setDisplayMetrics(mMetrics); 12021 12022 final PackageParser.Package pkg; 12023 try { 12024 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12025 } catch (PackageParserException e) { 12026 res.setError("Failed parse during installPackageLI", e); 12027 return; 12028 } 12029 12030 // Mark that we have an install time CPU ABI override. 12031 pkg.cpuAbiOverride = args.abiOverride; 12032 12033 String pkgName = res.name = pkg.packageName; 12034 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12035 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12036 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12037 return; 12038 } 12039 } 12040 12041 try { 12042 pp.collectCertificates(pkg, parseFlags); 12043 pp.collectManifestDigest(pkg); 12044 } catch (PackageParserException e) { 12045 res.setError("Failed collect during installPackageLI", e); 12046 return; 12047 } 12048 12049 /* If the installer passed in a manifest digest, compare it now. */ 12050 if (args.manifestDigest != null) { 12051 if (DEBUG_INSTALL) { 12052 final String parsedManifest = pkg.manifestDigest == null ? "null" 12053 : pkg.manifestDigest.toString(); 12054 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12055 + parsedManifest); 12056 } 12057 12058 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12059 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12060 return; 12061 } 12062 } else if (DEBUG_INSTALL) { 12063 final String parsedManifest = pkg.manifestDigest == null 12064 ? "null" : pkg.manifestDigest.toString(); 12065 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12066 } 12067 12068 // Get rid of all references to package scan path via parser. 12069 pp = null; 12070 String oldCodePath = null; 12071 boolean systemApp = false; 12072 synchronized (mPackages) { 12073 // Check if installing already existing package 12074 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12075 String oldName = mSettings.mRenamedPackages.get(pkgName); 12076 if (pkg.mOriginalPackages != null 12077 && pkg.mOriginalPackages.contains(oldName) 12078 && mPackages.containsKey(oldName)) { 12079 // This package is derived from an original package, 12080 // and this device has been updating from that original 12081 // name. We must continue using the original name, so 12082 // rename the new package here. 12083 pkg.setPackageName(oldName); 12084 pkgName = pkg.packageName; 12085 replace = true; 12086 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12087 + oldName + " pkgName=" + pkgName); 12088 } else if (mPackages.containsKey(pkgName)) { 12089 // This package, under its official name, already exists 12090 // on the device; we should replace it. 12091 replace = true; 12092 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12093 } 12094 12095 // Prevent apps opting out from runtime permissions 12096 if (replace) { 12097 PackageParser.Package oldPackage = mPackages.get(pkgName); 12098 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12099 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12100 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12101 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12102 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12103 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12104 + " doesn't support runtime permissions but the old" 12105 + " target SDK " + oldTargetSdk + " does."); 12106 return; 12107 } 12108 } 12109 } 12110 12111 PackageSetting ps = mSettings.mPackages.get(pkgName); 12112 if (ps != null) { 12113 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12114 12115 // Quick sanity check that we're signed correctly if updating; 12116 // we'll check this again later when scanning, but we want to 12117 // bail early here before tripping over redefined permissions. 12118 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12119 if (!checkUpgradeKeySetLP(ps, pkg)) { 12120 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12121 + pkg.packageName + " upgrade keys do not match the " 12122 + "previously installed version"); 12123 return; 12124 } 12125 } else { 12126 try { 12127 verifySignaturesLP(ps, pkg); 12128 } catch (PackageManagerException e) { 12129 res.setError(e.error, e.getMessage()); 12130 return; 12131 } 12132 } 12133 12134 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12135 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12136 systemApp = (ps.pkg.applicationInfo.flags & 12137 ApplicationInfo.FLAG_SYSTEM) != 0; 12138 } 12139 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12140 } 12141 12142 // Check whether the newly-scanned package wants to define an already-defined perm 12143 int N = pkg.permissions.size(); 12144 for (int i = N-1; i >= 0; i--) { 12145 PackageParser.Permission perm = pkg.permissions.get(i); 12146 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12147 if (bp != null) { 12148 // If the defining package is signed with our cert, it's okay. This 12149 // also includes the "updating the same package" case, of course. 12150 // "updating same package" could also involve key-rotation. 12151 final boolean sigsOk; 12152 if (bp.sourcePackage.equals(pkg.packageName) 12153 && (bp.packageSetting instanceof PackageSetting) 12154 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12155 scanFlags))) { 12156 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12157 } else { 12158 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12159 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12160 } 12161 if (!sigsOk) { 12162 // If the owning package is the system itself, we log but allow 12163 // install to proceed; we fail the install on all other permission 12164 // redefinitions. 12165 if (!bp.sourcePackage.equals("android")) { 12166 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12167 + pkg.packageName + " attempting to redeclare permission " 12168 + perm.info.name + " already owned by " + bp.sourcePackage); 12169 res.origPermission = perm.info.name; 12170 res.origPackage = bp.sourcePackage; 12171 return; 12172 } else { 12173 Slog.w(TAG, "Package " + pkg.packageName 12174 + " attempting to redeclare system permission " 12175 + perm.info.name + "; ignoring new declaration"); 12176 pkg.permissions.remove(i); 12177 } 12178 } 12179 } 12180 } 12181 12182 } 12183 12184 if (systemApp && onExternal) { 12185 // Disable updates to system apps on sdcard 12186 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12187 "Cannot install updates to system apps on sdcard"); 12188 return; 12189 } 12190 12191 if (args.move != null) { 12192 // We did an in-place move, so dex is ready to roll 12193 scanFlags |= SCAN_NO_DEX; 12194 scanFlags |= SCAN_MOVE; 12195 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12196 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12197 scanFlags |= SCAN_NO_DEX; 12198 12199 try { 12200 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12201 true /* extract libs */); 12202 } catch (PackageManagerException pme) { 12203 Slog.e(TAG, "Error deriving application ABI", pme); 12204 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12205 return; 12206 } 12207 12208 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12209 int result = mPackageDexOptimizer 12210 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12211 false /* defer */, false /* inclDependencies */); 12212 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12213 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12214 return; 12215 } 12216 } 12217 12218 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12219 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12220 return; 12221 } 12222 12223 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12224 12225 if (replace) { 12226 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12227 installerPackageName, volumeUuid, res); 12228 } else { 12229 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12230 args.user, installerPackageName, volumeUuid, res); 12231 } 12232 synchronized (mPackages) { 12233 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12234 if (ps != null) { 12235 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12236 } 12237 } 12238 } 12239 12240 private void startIntentFilterVerifications(int userId, boolean replacing, 12241 PackageParser.Package pkg) { 12242 if (mIntentFilterVerifierComponent == null) { 12243 Slog.w(TAG, "No IntentFilter verification will not be done as " 12244 + "there is no IntentFilterVerifier available!"); 12245 return; 12246 } 12247 12248 final int verifierUid = getPackageUid( 12249 mIntentFilterVerifierComponent.getPackageName(), 12250 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12251 12252 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12253 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12254 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12255 mHandler.sendMessage(msg); 12256 } 12257 12258 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12259 PackageParser.Package pkg) { 12260 int size = pkg.activities.size(); 12261 if (size == 0) { 12262 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12263 "No activity, so no need to verify any IntentFilter!"); 12264 return; 12265 } 12266 12267 final boolean hasDomainURLs = hasDomainURLs(pkg); 12268 if (!hasDomainURLs) { 12269 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12270 "No domain URLs, so no need to verify any IntentFilter!"); 12271 return; 12272 } 12273 12274 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12275 + " if any IntentFilter from the " + size 12276 + " Activities needs verification ..."); 12277 12278 int count = 0; 12279 final String packageName = pkg.packageName; 12280 12281 synchronized (mPackages) { 12282 // If this is a new install and we see that we've already run verification for this 12283 // package, we have nothing to do: it means the state was restored from backup. 12284 if (!replacing) { 12285 IntentFilterVerificationInfo ivi = 12286 mSettings.getIntentFilterVerificationLPr(packageName); 12287 if (ivi != null) { 12288 if (DEBUG_DOMAIN_VERIFICATION) { 12289 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12290 + ivi.getStatusString()); 12291 } 12292 return; 12293 } 12294 } 12295 12296 // If any filters need to be verified, then all need to be. 12297 boolean needToVerify = false; 12298 for (PackageParser.Activity a : pkg.activities) { 12299 for (ActivityIntentInfo filter : a.intents) { 12300 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12301 if (DEBUG_DOMAIN_VERIFICATION) { 12302 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12303 } 12304 needToVerify = true; 12305 break; 12306 } 12307 } 12308 } 12309 12310 if (needToVerify) { 12311 final int verificationId = mIntentFilterVerificationToken++; 12312 for (PackageParser.Activity a : pkg.activities) { 12313 for (ActivityIntentInfo filter : a.intents) { 12314 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12315 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12316 "Verification needed for IntentFilter:" + filter.toString()); 12317 mIntentFilterVerifier.addOneIntentFilterVerification( 12318 verifierUid, userId, verificationId, filter, packageName); 12319 count++; 12320 } 12321 } 12322 } 12323 } 12324 } 12325 12326 if (count > 0) { 12327 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12328 + " IntentFilter verification" + (count > 1 ? "s" : "") 12329 + " for userId:" + userId); 12330 mIntentFilterVerifier.startVerifications(userId); 12331 } else { 12332 if (DEBUG_DOMAIN_VERIFICATION) { 12333 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12334 } 12335 } 12336 } 12337 12338 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12339 final ComponentName cn = filter.activity.getComponentName(); 12340 final String packageName = cn.getPackageName(); 12341 12342 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12343 packageName); 12344 if (ivi == null) { 12345 return true; 12346 } 12347 int status = ivi.getStatus(); 12348 switch (status) { 12349 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12350 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12351 return true; 12352 12353 default: 12354 // Nothing to do 12355 return false; 12356 } 12357 } 12358 12359 private static boolean isMultiArch(PackageSetting ps) { 12360 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12361 } 12362 12363 private static boolean isMultiArch(ApplicationInfo info) { 12364 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12365 } 12366 12367 private static boolean isExternal(PackageParser.Package pkg) { 12368 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12369 } 12370 12371 private static boolean isExternal(PackageSetting ps) { 12372 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12373 } 12374 12375 private static boolean isExternal(ApplicationInfo info) { 12376 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12377 } 12378 12379 private static boolean isSystemApp(PackageParser.Package pkg) { 12380 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12381 } 12382 12383 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12384 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12385 } 12386 12387 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12388 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12389 } 12390 12391 private static boolean isSystemApp(PackageSetting ps) { 12392 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12393 } 12394 12395 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12396 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12397 } 12398 12399 private int packageFlagsToInstallFlags(PackageSetting ps) { 12400 int installFlags = 0; 12401 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12402 // This existing package was an external ASEC install when we have 12403 // the external flag without a UUID 12404 installFlags |= PackageManager.INSTALL_EXTERNAL; 12405 } 12406 if (ps.isForwardLocked()) { 12407 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12408 } 12409 return installFlags; 12410 } 12411 12412 private void deleteTempPackageFiles() { 12413 final FilenameFilter filter = new FilenameFilter() { 12414 public boolean accept(File dir, String name) { 12415 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12416 } 12417 }; 12418 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12419 file.delete(); 12420 } 12421 } 12422 12423 @Override 12424 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12425 int flags) { 12426 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12427 flags); 12428 } 12429 12430 @Override 12431 public void deletePackage(final String packageName, 12432 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12433 mContext.enforceCallingOrSelfPermission( 12434 android.Manifest.permission.DELETE_PACKAGES, null); 12435 Preconditions.checkNotNull(packageName); 12436 Preconditions.checkNotNull(observer); 12437 final int uid = Binder.getCallingUid(); 12438 if (UserHandle.getUserId(uid) != userId) { 12439 mContext.enforceCallingPermission( 12440 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12441 "deletePackage for user " + userId); 12442 } 12443 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12444 try { 12445 observer.onPackageDeleted(packageName, 12446 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12447 } catch (RemoteException re) { 12448 } 12449 return; 12450 } 12451 12452 boolean uninstallBlocked = false; 12453 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12454 int[] users = sUserManager.getUserIds(); 12455 for (int i = 0; i < users.length; ++i) { 12456 if (getBlockUninstallForUser(packageName, users[i])) { 12457 uninstallBlocked = true; 12458 break; 12459 } 12460 } 12461 } else { 12462 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12463 } 12464 if (uninstallBlocked) { 12465 try { 12466 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12467 null); 12468 } catch (RemoteException re) { 12469 } 12470 return; 12471 } 12472 12473 if (DEBUG_REMOVE) { 12474 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12475 } 12476 // Queue up an async operation since the package deletion may take a little while. 12477 mHandler.post(new Runnable() { 12478 public void run() { 12479 mHandler.removeCallbacks(this); 12480 final int returnCode = deletePackageX(packageName, userId, flags); 12481 if (observer != null) { 12482 try { 12483 observer.onPackageDeleted(packageName, returnCode, null); 12484 } catch (RemoteException e) { 12485 Log.i(TAG, "Observer no longer exists."); 12486 } //end catch 12487 } //end if 12488 } //end run 12489 }); 12490 } 12491 12492 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12493 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12494 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12495 try { 12496 if (dpm != null) { 12497 if (dpm.isDeviceOwner(packageName)) { 12498 return true; 12499 } 12500 int[] users; 12501 if (userId == UserHandle.USER_ALL) { 12502 users = sUserManager.getUserIds(); 12503 } else { 12504 users = new int[]{userId}; 12505 } 12506 for (int i = 0; i < users.length; ++i) { 12507 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12508 return true; 12509 } 12510 } 12511 } 12512 } catch (RemoteException e) { 12513 } 12514 return false; 12515 } 12516 12517 /** 12518 * This method is an internal method that could be get invoked either 12519 * to delete an installed package or to clean up a failed installation. 12520 * After deleting an installed package, a broadcast is sent to notify any 12521 * listeners that the package has been installed. For cleaning up a failed 12522 * installation, the broadcast is not necessary since the package's 12523 * installation wouldn't have sent the initial broadcast either 12524 * The key steps in deleting a package are 12525 * deleting the package information in internal structures like mPackages, 12526 * deleting the packages base directories through installd 12527 * updating mSettings to reflect current status 12528 * persisting settings for later use 12529 * sending a broadcast if necessary 12530 */ 12531 private int deletePackageX(String packageName, int userId, int flags) { 12532 final PackageRemovedInfo info = new PackageRemovedInfo(); 12533 final boolean res; 12534 12535 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12536 ? UserHandle.ALL : new UserHandle(userId); 12537 12538 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12539 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12540 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12541 } 12542 12543 boolean removedForAllUsers = false; 12544 boolean systemUpdate = false; 12545 12546 // for the uninstall-updates case and restricted profiles, remember the per- 12547 // userhandle installed state 12548 int[] allUsers; 12549 boolean[] perUserInstalled; 12550 synchronized (mPackages) { 12551 PackageSetting ps = mSettings.mPackages.get(packageName); 12552 allUsers = sUserManager.getUserIds(); 12553 perUserInstalled = new boolean[allUsers.length]; 12554 for (int i = 0; i < allUsers.length; i++) { 12555 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12556 } 12557 } 12558 12559 synchronized (mInstallLock) { 12560 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12561 res = deletePackageLI(packageName, removeForUser, 12562 true, allUsers, perUserInstalled, 12563 flags | REMOVE_CHATTY, info, true); 12564 systemUpdate = info.isRemovedPackageSystemUpdate; 12565 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12566 removedForAllUsers = true; 12567 } 12568 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12569 + " removedForAllUsers=" + removedForAllUsers); 12570 } 12571 12572 if (res) { 12573 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12574 12575 // If the removed package was a system update, the old system package 12576 // was re-enabled; we need to broadcast this information 12577 if (systemUpdate) { 12578 Bundle extras = new Bundle(1); 12579 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12580 ? info.removedAppId : info.uid); 12581 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12582 12583 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12584 extras, null, null, null); 12585 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12586 extras, null, null, null); 12587 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12588 null, packageName, null, null); 12589 } 12590 } 12591 // Force a gc here. 12592 Runtime.getRuntime().gc(); 12593 // Delete the resources here after sending the broadcast to let 12594 // other processes clean up before deleting resources. 12595 if (info.args != null) { 12596 synchronized (mInstallLock) { 12597 info.args.doPostDeleteLI(true); 12598 } 12599 } 12600 12601 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12602 } 12603 12604 class PackageRemovedInfo { 12605 String removedPackage; 12606 int uid = -1; 12607 int removedAppId = -1; 12608 int[] removedUsers = null; 12609 boolean isRemovedPackageSystemUpdate = false; 12610 // Clean up resources deleted packages. 12611 InstallArgs args = null; 12612 12613 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12614 Bundle extras = new Bundle(1); 12615 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12616 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12617 if (replacing) { 12618 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12619 } 12620 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12621 if (removedPackage != null) { 12622 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12623 extras, null, null, removedUsers); 12624 if (fullRemove && !replacing) { 12625 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12626 extras, null, null, removedUsers); 12627 } 12628 } 12629 if (removedAppId >= 0) { 12630 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12631 removedUsers); 12632 } 12633 } 12634 } 12635 12636 /* 12637 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12638 * flag is not set, the data directory is removed as well. 12639 * make sure this flag is set for partially installed apps. If not its meaningless to 12640 * delete a partially installed application. 12641 */ 12642 private void removePackageDataLI(PackageSetting ps, 12643 int[] allUserHandles, boolean[] perUserInstalled, 12644 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12645 String packageName = ps.name; 12646 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12647 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12648 // Retrieve object to delete permissions for shared user later on 12649 final PackageSetting deletedPs; 12650 // reader 12651 synchronized (mPackages) { 12652 deletedPs = mSettings.mPackages.get(packageName); 12653 if (outInfo != null) { 12654 outInfo.removedPackage = packageName; 12655 outInfo.removedUsers = deletedPs != null 12656 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12657 : null; 12658 } 12659 } 12660 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12661 removeDataDirsLI(ps.volumeUuid, packageName); 12662 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12663 } 12664 // writer 12665 synchronized (mPackages) { 12666 if (deletedPs != null) { 12667 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12668 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12669 clearDefaultBrowserIfNeeded(packageName); 12670 if (outInfo != null) { 12671 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12672 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12673 } 12674 updatePermissionsLPw(deletedPs.name, null, 0); 12675 if (deletedPs.sharedUser != null) { 12676 // Remove permissions associated with package. Since runtime 12677 // permissions are per user we have to kill the removed package 12678 // or packages running under the shared user of the removed 12679 // package if revoking the permissions requested only by the removed 12680 // package is successful and this causes a change in gids. 12681 for (int userId : UserManagerService.getInstance().getUserIds()) { 12682 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12683 userId); 12684 if (userIdToKill == UserHandle.USER_ALL 12685 || userIdToKill >= UserHandle.USER_OWNER) { 12686 // If gids changed for this user, kill all affected packages. 12687 mHandler.post(new Runnable() { 12688 @Override 12689 public void run() { 12690 // This has to happen with no lock held. 12691 killSettingPackagesForUser(deletedPs, userIdToKill, 12692 KILL_APP_REASON_GIDS_CHANGED); 12693 } 12694 }); 12695 break; 12696 } 12697 } 12698 } 12699 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12700 } 12701 // make sure to preserve per-user disabled state if this removal was just 12702 // a downgrade of a system app to the factory package 12703 if (allUserHandles != null && perUserInstalled != null) { 12704 if (DEBUG_REMOVE) { 12705 Slog.d(TAG, "Propagating install state across downgrade"); 12706 } 12707 for (int i = 0; i < allUserHandles.length; i++) { 12708 if (DEBUG_REMOVE) { 12709 Slog.d(TAG, " user " + allUserHandles[i] 12710 + " => " + perUserInstalled[i]); 12711 } 12712 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12713 } 12714 } 12715 } 12716 // can downgrade to reader 12717 if (writeSettings) { 12718 // Save settings now 12719 mSettings.writeLPr(); 12720 } 12721 } 12722 if (outInfo != null) { 12723 // A user ID was deleted here. Go through all users and remove it 12724 // from KeyStore. 12725 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12726 } 12727 } 12728 12729 static boolean locationIsPrivileged(File path) { 12730 try { 12731 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12732 .getCanonicalPath(); 12733 return path.getCanonicalPath().startsWith(privilegedAppDir); 12734 } catch (IOException e) { 12735 Slog.e(TAG, "Unable to access code path " + path); 12736 } 12737 return false; 12738 } 12739 12740 /* 12741 * Tries to delete system package. 12742 */ 12743 private boolean deleteSystemPackageLI(PackageSetting newPs, 12744 int[] allUserHandles, boolean[] perUserInstalled, 12745 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12746 final boolean applyUserRestrictions 12747 = (allUserHandles != null) && (perUserInstalled != null); 12748 PackageSetting disabledPs = null; 12749 // Confirm if the system package has been updated 12750 // An updated system app can be deleted. This will also have to restore 12751 // the system pkg from system partition 12752 // reader 12753 synchronized (mPackages) { 12754 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12755 } 12756 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12757 + " disabledPs=" + disabledPs); 12758 if (disabledPs == null) { 12759 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12760 return false; 12761 } else if (DEBUG_REMOVE) { 12762 Slog.d(TAG, "Deleting system pkg from data partition"); 12763 } 12764 if (DEBUG_REMOVE) { 12765 if (applyUserRestrictions) { 12766 Slog.d(TAG, "Remembering install states:"); 12767 for (int i = 0; i < allUserHandles.length; i++) { 12768 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12769 } 12770 } 12771 } 12772 // Delete the updated package 12773 outInfo.isRemovedPackageSystemUpdate = true; 12774 if (disabledPs.versionCode < newPs.versionCode) { 12775 // Delete data for downgrades 12776 flags &= ~PackageManager.DELETE_KEEP_DATA; 12777 } else { 12778 // Preserve data by setting flag 12779 flags |= PackageManager.DELETE_KEEP_DATA; 12780 } 12781 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12782 allUserHandles, perUserInstalled, outInfo, writeSettings); 12783 if (!ret) { 12784 return false; 12785 } 12786 // writer 12787 synchronized (mPackages) { 12788 // Reinstate the old system package 12789 mSettings.enableSystemPackageLPw(newPs.name); 12790 // Remove any native libraries from the upgraded package. 12791 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12792 } 12793 // Install the system package 12794 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12795 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12796 if (locationIsPrivileged(disabledPs.codePath)) { 12797 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12798 } 12799 12800 final PackageParser.Package newPkg; 12801 try { 12802 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12803 } catch (PackageManagerException e) { 12804 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12805 return false; 12806 } 12807 12808 // writer 12809 synchronized (mPackages) { 12810 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12811 12812 // Propagate the permissions state as we do want to drop on the floor 12813 // runtime permissions. The update permissions method below will take 12814 // care of removing obsolete permissions and grant install permissions. 12815 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12816 updatePermissionsLPw(newPkg.packageName, newPkg, 12817 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12818 12819 if (applyUserRestrictions) { 12820 if (DEBUG_REMOVE) { 12821 Slog.d(TAG, "Propagating install state across reinstall"); 12822 } 12823 for (int i = 0; i < allUserHandles.length; i++) { 12824 if (DEBUG_REMOVE) { 12825 Slog.d(TAG, " user " + allUserHandles[i] 12826 + " => " + perUserInstalled[i]); 12827 } 12828 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12829 } 12830 // Regardless of writeSettings we need to ensure that this restriction 12831 // state propagation is persisted 12832 mSettings.writeAllUsersPackageRestrictionsLPr(); 12833 } 12834 // can downgrade to reader here 12835 if (writeSettings) { 12836 mSettings.writeLPr(); 12837 } 12838 } 12839 return true; 12840 } 12841 12842 private boolean deleteInstalledPackageLI(PackageSetting ps, 12843 boolean deleteCodeAndResources, int flags, 12844 int[] allUserHandles, boolean[] perUserInstalled, 12845 PackageRemovedInfo outInfo, boolean writeSettings) { 12846 if (outInfo != null) { 12847 outInfo.uid = ps.appId; 12848 } 12849 12850 // Delete package data from internal structures and also remove data if flag is set 12851 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12852 12853 // Delete application code and resources 12854 if (deleteCodeAndResources && (outInfo != null)) { 12855 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12856 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12857 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12858 } 12859 return true; 12860 } 12861 12862 @Override 12863 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12864 int userId) { 12865 mContext.enforceCallingOrSelfPermission( 12866 android.Manifest.permission.DELETE_PACKAGES, null); 12867 synchronized (mPackages) { 12868 PackageSetting ps = mSettings.mPackages.get(packageName); 12869 if (ps == null) { 12870 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12871 return false; 12872 } 12873 if (!ps.getInstalled(userId)) { 12874 // Can't block uninstall for an app that is not installed or enabled. 12875 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12876 return false; 12877 } 12878 ps.setBlockUninstall(blockUninstall, userId); 12879 mSettings.writePackageRestrictionsLPr(userId); 12880 } 12881 return true; 12882 } 12883 12884 @Override 12885 public boolean getBlockUninstallForUser(String packageName, int userId) { 12886 synchronized (mPackages) { 12887 PackageSetting ps = mSettings.mPackages.get(packageName); 12888 if (ps == null) { 12889 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12890 return false; 12891 } 12892 return ps.getBlockUninstall(userId); 12893 } 12894 } 12895 12896 /* 12897 * This method handles package deletion in general 12898 */ 12899 private boolean deletePackageLI(String packageName, UserHandle user, 12900 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12901 int flags, PackageRemovedInfo outInfo, 12902 boolean writeSettings) { 12903 if (packageName == null) { 12904 Slog.w(TAG, "Attempt to delete null packageName."); 12905 return false; 12906 } 12907 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12908 PackageSetting ps; 12909 boolean dataOnly = false; 12910 int removeUser = -1; 12911 int appId = -1; 12912 synchronized (mPackages) { 12913 ps = mSettings.mPackages.get(packageName); 12914 if (ps == null) { 12915 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12916 return false; 12917 } 12918 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12919 && user.getIdentifier() != UserHandle.USER_ALL) { 12920 // The caller is asking that the package only be deleted for a single 12921 // user. To do this, we just mark its uninstalled state and delete 12922 // its data. If this is a system app, we only allow this to happen if 12923 // they have set the special DELETE_SYSTEM_APP which requests different 12924 // semantics than normal for uninstalling system apps. 12925 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12926 ps.setUserState(user.getIdentifier(), 12927 COMPONENT_ENABLED_STATE_DEFAULT, 12928 false, //installed 12929 true, //stopped 12930 true, //notLaunched 12931 false, //hidden 12932 null, null, null, 12933 false, // blockUninstall 12934 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12935 if (!isSystemApp(ps)) { 12936 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12937 // Other user still have this package installed, so all 12938 // we need to do is clear this user's data and save that 12939 // it is uninstalled. 12940 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12941 removeUser = user.getIdentifier(); 12942 appId = ps.appId; 12943 scheduleWritePackageRestrictionsLocked(removeUser); 12944 } else { 12945 // We need to set it back to 'installed' so the uninstall 12946 // broadcasts will be sent correctly. 12947 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12948 ps.setInstalled(true, user.getIdentifier()); 12949 } 12950 } else { 12951 // This is a system app, so we assume that the 12952 // other users still have this package installed, so all 12953 // we need to do is clear this user's data and save that 12954 // it is uninstalled. 12955 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12956 removeUser = user.getIdentifier(); 12957 appId = ps.appId; 12958 scheduleWritePackageRestrictionsLocked(removeUser); 12959 } 12960 } 12961 } 12962 12963 if (removeUser >= 0) { 12964 // From above, we determined that we are deleting this only 12965 // for a single user. Continue the work here. 12966 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12967 if (outInfo != null) { 12968 outInfo.removedPackage = packageName; 12969 outInfo.removedAppId = appId; 12970 outInfo.removedUsers = new int[] {removeUser}; 12971 } 12972 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12973 removeKeystoreDataIfNeeded(removeUser, appId); 12974 schedulePackageCleaning(packageName, removeUser, false); 12975 synchronized (mPackages) { 12976 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12977 scheduleWritePackageRestrictionsLocked(removeUser); 12978 } 12979 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 12980 } 12981 return true; 12982 } 12983 12984 if (dataOnly) { 12985 // Delete application data first 12986 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12987 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12988 return true; 12989 } 12990 12991 boolean ret = false; 12992 if (isSystemApp(ps)) { 12993 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12994 // When an updated system application is deleted we delete the existing resources as well and 12995 // fall back to existing code in system partition 12996 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12997 flags, outInfo, writeSettings); 12998 } else { 12999 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13000 // Kill application pre-emptively especially for apps on sd. 13001 killApplication(packageName, ps.appId, "uninstall pkg"); 13002 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13003 allUserHandles, perUserInstalled, 13004 outInfo, writeSettings); 13005 } 13006 13007 return ret; 13008 } 13009 13010 private final class ClearStorageConnection implements ServiceConnection { 13011 IMediaContainerService mContainerService; 13012 13013 @Override 13014 public void onServiceConnected(ComponentName name, IBinder service) { 13015 synchronized (this) { 13016 mContainerService = IMediaContainerService.Stub.asInterface(service); 13017 notifyAll(); 13018 } 13019 } 13020 13021 @Override 13022 public void onServiceDisconnected(ComponentName name) { 13023 } 13024 } 13025 13026 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13027 final boolean mounted; 13028 if (Environment.isExternalStorageEmulated()) { 13029 mounted = true; 13030 } else { 13031 final String status = Environment.getExternalStorageState(); 13032 13033 mounted = status.equals(Environment.MEDIA_MOUNTED) 13034 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13035 } 13036 13037 if (!mounted) { 13038 return; 13039 } 13040 13041 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13042 int[] users; 13043 if (userId == UserHandle.USER_ALL) { 13044 users = sUserManager.getUserIds(); 13045 } else { 13046 users = new int[] { userId }; 13047 } 13048 final ClearStorageConnection conn = new ClearStorageConnection(); 13049 if (mContext.bindServiceAsUser( 13050 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13051 try { 13052 for (int curUser : users) { 13053 long timeout = SystemClock.uptimeMillis() + 5000; 13054 synchronized (conn) { 13055 long now = SystemClock.uptimeMillis(); 13056 while (conn.mContainerService == null && now < timeout) { 13057 try { 13058 conn.wait(timeout - now); 13059 } catch (InterruptedException e) { 13060 } 13061 } 13062 } 13063 if (conn.mContainerService == null) { 13064 return; 13065 } 13066 13067 final UserEnvironment userEnv = new UserEnvironment(curUser); 13068 clearDirectory(conn.mContainerService, 13069 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13070 if (allData) { 13071 clearDirectory(conn.mContainerService, 13072 userEnv.buildExternalStorageAppDataDirs(packageName)); 13073 clearDirectory(conn.mContainerService, 13074 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13075 } 13076 } 13077 } finally { 13078 mContext.unbindService(conn); 13079 } 13080 } 13081 } 13082 13083 @Override 13084 public void clearApplicationUserData(final String packageName, 13085 final IPackageDataObserver observer, final int userId) { 13086 mContext.enforceCallingOrSelfPermission( 13087 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13088 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13089 // Queue up an async operation since the package deletion may take a little while. 13090 mHandler.post(new Runnable() { 13091 public void run() { 13092 mHandler.removeCallbacks(this); 13093 final boolean succeeded; 13094 synchronized (mInstallLock) { 13095 succeeded = clearApplicationUserDataLI(packageName, userId); 13096 } 13097 clearExternalStorageDataSync(packageName, userId, true); 13098 if (succeeded) { 13099 // invoke DeviceStorageMonitor's update method to clear any notifications 13100 DeviceStorageMonitorInternal 13101 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13102 if (dsm != null) { 13103 dsm.checkMemory(); 13104 } 13105 } 13106 if(observer != null) { 13107 try { 13108 observer.onRemoveCompleted(packageName, succeeded); 13109 } catch (RemoteException e) { 13110 Log.i(TAG, "Observer no longer exists."); 13111 } 13112 } //end if observer 13113 } //end run 13114 }); 13115 } 13116 13117 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13118 if (packageName == null) { 13119 Slog.w(TAG, "Attempt to delete null packageName."); 13120 return false; 13121 } 13122 13123 // Try finding details about the requested package 13124 PackageParser.Package pkg; 13125 synchronized (mPackages) { 13126 pkg = mPackages.get(packageName); 13127 if (pkg == null) { 13128 final PackageSetting ps = mSettings.mPackages.get(packageName); 13129 if (ps != null) { 13130 pkg = ps.pkg; 13131 } 13132 } 13133 13134 if (pkg == null) { 13135 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13136 return false; 13137 } 13138 13139 PackageSetting ps = (PackageSetting) pkg.mExtras; 13140 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13141 } 13142 13143 // Always delete data directories for package, even if we found no other 13144 // record of app. This helps users recover from UID mismatches without 13145 // resorting to a full data wipe. 13146 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13147 if (retCode < 0) { 13148 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13149 return false; 13150 } 13151 13152 final int appId = pkg.applicationInfo.uid; 13153 removeKeystoreDataIfNeeded(userId, appId); 13154 13155 // Create a native library symlink only if we have native libraries 13156 // and if the native libraries are 32 bit libraries. We do not provide 13157 // this symlink for 64 bit libraries. 13158 if (pkg.applicationInfo.primaryCpuAbi != null && 13159 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13160 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13161 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13162 nativeLibPath, userId) < 0) { 13163 Slog.w(TAG, "Failed linking native library dir"); 13164 return false; 13165 } 13166 } 13167 13168 return true; 13169 } 13170 13171 /** 13172 * Reverts user permission state changes (permissions and flags). 13173 * 13174 * @param ps The package for which to reset. 13175 * @param userId The device user for which to do a reset. 13176 */ 13177 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13178 final PackageSetting ps, final int userId) { 13179 if (ps.pkg == null) { 13180 return; 13181 } 13182 13183 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13184 | FLAG_PERMISSION_USER_FIXED 13185 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13186 13187 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13188 | FLAG_PERMISSION_POLICY_FIXED; 13189 13190 boolean writeInstallPermissions = false; 13191 boolean writeRuntimePermissions = false; 13192 13193 final int permissionCount = ps.pkg.requestedPermissions.size(); 13194 for (int i = 0; i < permissionCount; i++) { 13195 String permission = ps.pkg.requestedPermissions.get(i); 13196 13197 BasePermission bp = mSettings.mPermissions.get(permission); 13198 if (bp == null) { 13199 continue; 13200 } 13201 13202 // If shared user we just reset the state to which only this app contributed. 13203 if (ps.sharedUser != null) { 13204 boolean used = false; 13205 final int packageCount = ps.sharedUser.packages.size(); 13206 for (int j = 0; j < packageCount; j++) { 13207 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13208 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13209 && pkg.pkg.requestedPermissions.contains(permission)) { 13210 used = true; 13211 break; 13212 } 13213 } 13214 if (used) { 13215 continue; 13216 } 13217 } 13218 13219 PermissionsState permissionsState = ps.getPermissionsState(); 13220 13221 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13222 13223 // Always clear the user settable flags. 13224 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13225 bp.name) != null; 13226 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13227 if (hasInstallState) { 13228 writeInstallPermissions = true; 13229 } else { 13230 writeRuntimePermissions = true; 13231 } 13232 } 13233 13234 // Below is only runtime permission handling. 13235 if (!bp.isRuntime()) { 13236 continue; 13237 } 13238 13239 // Never clobber system or policy. 13240 if ((oldFlags & policyOrSystemFlags) != 0) { 13241 continue; 13242 } 13243 13244 // If this permission was granted by default, make sure it is. 13245 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13246 if (permissionsState.grantRuntimePermission(bp, userId) 13247 != PERMISSION_OPERATION_FAILURE) { 13248 writeRuntimePermissions = true; 13249 } 13250 } else { 13251 // Otherwise, reset the permission. 13252 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13253 switch (revokeResult) { 13254 case PERMISSION_OPERATION_SUCCESS: { 13255 writeRuntimePermissions = true; 13256 } break; 13257 13258 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13259 writeRuntimePermissions = true; 13260 // If gids changed for this user, kill all affected packages. 13261 mHandler.post(new Runnable() { 13262 @Override 13263 public void run() { 13264 // This has to happen with no lock held. 13265 killSettingPackagesForUser(ps, userId, 13266 KILL_APP_REASON_GIDS_CHANGED); 13267 } 13268 }); 13269 } break; 13270 } 13271 } 13272 } 13273 13274 // Synchronously write as we are taking permissions away. 13275 if (writeRuntimePermissions) { 13276 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13277 } 13278 13279 // Synchronously write as we are taking permissions away. 13280 if (writeInstallPermissions) { 13281 mSettings.writeLPr(); 13282 } 13283 } 13284 13285 /** 13286 * Remove entries from the keystore daemon. Will only remove it if the 13287 * {@code appId} is valid. 13288 */ 13289 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13290 if (appId < 0) { 13291 return; 13292 } 13293 13294 final KeyStore keyStore = KeyStore.getInstance(); 13295 if (keyStore != null) { 13296 if (userId == UserHandle.USER_ALL) { 13297 for (final int individual : sUserManager.getUserIds()) { 13298 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13299 } 13300 } else { 13301 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13302 } 13303 } else { 13304 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13305 } 13306 } 13307 13308 @Override 13309 public void deleteApplicationCacheFiles(final String packageName, 13310 final IPackageDataObserver observer) { 13311 mContext.enforceCallingOrSelfPermission( 13312 android.Manifest.permission.DELETE_CACHE_FILES, null); 13313 // Queue up an async operation since the package deletion may take a little while. 13314 final int userId = UserHandle.getCallingUserId(); 13315 mHandler.post(new Runnable() { 13316 public void run() { 13317 mHandler.removeCallbacks(this); 13318 final boolean succeded; 13319 synchronized (mInstallLock) { 13320 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13321 } 13322 clearExternalStorageDataSync(packageName, userId, false); 13323 if (observer != null) { 13324 try { 13325 observer.onRemoveCompleted(packageName, succeded); 13326 } catch (RemoteException e) { 13327 Log.i(TAG, "Observer no longer exists."); 13328 } 13329 } //end if observer 13330 } //end run 13331 }); 13332 } 13333 13334 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13335 if (packageName == null) { 13336 Slog.w(TAG, "Attempt to delete null packageName."); 13337 return false; 13338 } 13339 PackageParser.Package p; 13340 synchronized (mPackages) { 13341 p = mPackages.get(packageName); 13342 } 13343 if (p == null) { 13344 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13345 return false; 13346 } 13347 final ApplicationInfo applicationInfo = p.applicationInfo; 13348 if (applicationInfo == null) { 13349 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13350 return false; 13351 } 13352 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13353 if (retCode < 0) { 13354 Slog.w(TAG, "Couldn't remove cache files for package: " 13355 + packageName + " u" + userId); 13356 return false; 13357 } 13358 return true; 13359 } 13360 13361 @Override 13362 public void getPackageSizeInfo(final String packageName, int userHandle, 13363 final IPackageStatsObserver observer) { 13364 mContext.enforceCallingOrSelfPermission( 13365 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13366 if (packageName == null) { 13367 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13368 } 13369 13370 PackageStats stats = new PackageStats(packageName, userHandle); 13371 13372 /* 13373 * Queue up an async operation since the package measurement may take a 13374 * little while. 13375 */ 13376 Message msg = mHandler.obtainMessage(INIT_COPY); 13377 msg.obj = new MeasureParams(stats, observer); 13378 mHandler.sendMessage(msg); 13379 } 13380 13381 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13382 PackageStats pStats) { 13383 if (packageName == null) { 13384 Slog.w(TAG, "Attempt to get size of null packageName."); 13385 return false; 13386 } 13387 PackageParser.Package p; 13388 boolean dataOnly = false; 13389 String libDirRoot = null; 13390 String asecPath = null; 13391 PackageSetting ps = null; 13392 synchronized (mPackages) { 13393 p = mPackages.get(packageName); 13394 ps = mSettings.mPackages.get(packageName); 13395 if(p == null) { 13396 dataOnly = true; 13397 if((ps == null) || (ps.pkg == null)) { 13398 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13399 return false; 13400 } 13401 p = ps.pkg; 13402 } 13403 if (ps != null) { 13404 libDirRoot = ps.legacyNativeLibraryPathString; 13405 } 13406 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13407 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13408 if (secureContainerId != null) { 13409 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13410 } 13411 } 13412 } 13413 String publicSrcDir = null; 13414 if(!dataOnly) { 13415 final ApplicationInfo applicationInfo = p.applicationInfo; 13416 if (applicationInfo == null) { 13417 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13418 return false; 13419 } 13420 if (p.isForwardLocked()) { 13421 publicSrcDir = applicationInfo.getBaseResourcePath(); 13422 } 13423 } 13424 // TODO: extend to measure size of split APKs 13425 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13426 // not just the first level. 13427 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13428 // just the primary. 13429 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13430 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13431 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13432 if (res < 0) { 13433 return false; 13434 } 13435 13436 // Fix-up for forward-locked applications in ASEC containers. 13437 if (!isExternal(p)) { 13438 pStats.codeSize += pStats.externalCodeSize; 13439 pStats.externalCodeSize = 0L; 13440 } 13441 13442 return true; 13443 } 13444 13445 13446 @Override 13447 public void addPackageToPreferred(String packageName) { 13448 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13449 } 13450 13451 @Override 13452 public void removePackageFromPreferred(String packageName) { 13453 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13454 } 13455 13456 @Override 13457 public List<PackageInfo> getPreferredPackages(int flags) { 13458 return new ArrayList<PackageInfo>(); 13459 } 13460 13461 private int getUidTargetSdkVersionLockedLPr(int uid) { 13462 Object obj = mSettings.getUserIdLPr(uid); 13463 if (obj instanceof SharedUserSetting) { 13464 final SharedUserSetting sus = (SharedUserSetting) obj; 13465 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13466 final Iterator<PackageSetting> it = sus.packages.iterator(); 13467 while (it.hasNext()) { 13468 final PackageSetting ps = it.next(); 13469 if (ps.pkg != null) { 13470 int v = ps.pkg.applicationInfo.targetSdkVersion; 13471 if (v < vers) vers = v; 13472 } 13473 } 13474 return vers; 13475 } else if (obj instanceof PackageSetting) { 13476 final PackageSetting ps = (PackageSetting) obj; 13477 if (ps.pkg != null) { 13478 return ps.pkg.applicationInfo.targetSdkVersion; 13479 } 13480 } 13481 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13482 } 13483 13484 @Override 13485 public void addPreferredActivity(IntentFilter filter, int match, 13486 ComponentName[] set, ComponentName activity, int userId) { 13487 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13488 "Adding preferred"); 13489 } 13490 13491 private void addPreferredActivityInternal(IntentFilter filter, int match, 13492 ComponentName[] set, ComponentName activity, boolean always, int userId, 13493 String opname) { 13494 // writer 13495 int callingUid = Binder.getCallingUid(); 13496 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13497 if (filter.countActions() == 0) { 13498 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13499 return; 13500 } 13501 synchronized (mPackages) { 13502 if (mContext.checkCallingOrSelfPermission( 13503 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13504 != PackageManager.PERMISSION_GRANTED) { 13505 if (getUidTargetSdkVersionLockedLPr(callingUid) 13506 < Build.VERSION_CODES.FROYO) { 13507 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13508 + callingUid); 13509 return; 13510 } 13511 mContext.enforceCallingOrSelfPermission( 13512 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13513 } 13514 13515 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13516 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13517 + userId + ":"); 13518 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13519 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13520 scheduleWritePackageRestrictionsLocked(userId); 13521 } 13522 } 13523 13524 @Override 13525 public void replacePreferredActivity(IntentFilter filter, int match, 13526 ComponentName[] set, ComponentName activity, int userId) { 13527 if (filter.countActions() != 1) { 13528 throw new IllegalArgumentException( 13529 "replacePreferredActivity expects filter to have only 1 action."); 13530 } 13531 if (filter.countDataAuthorities() != 0 13532 || filter.countDataPaths() != 0 13533 || filter.countDataSchemes() > 1 13534 || filter.countDataTypes() != 0) { 13535 throw new IllegalArgumentException( 13536 "replacePreferredActivity expects filter to have no data authorities, " + 13537 "paths, or types; and at most one scheme."); 13538 } 13539 13540 final int callingUid = Binder.getCallingUid(); 13541 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13542 synchronized (mPackages) { 13543 if (mContext.checkCallingOrSelfPermission( 13544 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13545 != PackageManager.PERMISSION_GRANTED) { 13546 if (getUidTargetSdkVersionLockedLPr(callingUid) 13547 < Build.VERSION_CODES.FROYO) { 13548 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13549 + Binder.getCallingUid()); 13550 return; 13551 } 13552 mContext.enforceCallingOrSelfPermission( 13553 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13554 } 13555 13556 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13557 if (pir != null) { 13558 // Get all of the existing entries that exactly match this filter. 13559 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13560 if (existing != null && existing.size() == 1) { 13561 PreferredActivity cur = existing.get(0); 13562 if (DEBUG_PREFERRED) { 13563 Slog.i(TAG, "Checking replace of preferred:"); 13564 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13565 if (!cur.mPref.mAlways) { 13566 Slog.i(TAG, " -- CUR; not mAlways!"); 13567 } else { 13568 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13569 Slog.i(TAG, " -- CUR: mSet=" 13570 + Arrays.toString(cur.mPref.mSetComponents)); 13571 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13572 Slog.i(TAG, " -- NEW: mMatch=" 13573 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13574 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13575 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13576 } 13577 } 13578 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13579 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13580 && cur.mPref.sameSet(set)) { 13581 // Setting the preferred activity to what it happens to be already 13582 if (DEBUG_PREFERRED) { 13583 Slog.i(TAG, "Replacing with same preferred activity " 13584 + cur.mPref.mShortComponent + " for user " 13585 + userId + ":"); 13586 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13587 } 13588 return; 13589 } 13590 } 13591 13592 if (existing != null) { 13593 if (DEBUG_PREFERRED) { 13594 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13595 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13596 } 13597 for (int i = 0; i < existing.size(); i++) { 13598 PreferredActivity pa = existing.get(i); 13599 if (DEBUG_PREFERRED) { 13600 Slog.i(TAG, "Removing existing preferred activity " 13601 + pa.mPref.mComponent + ":"); 13602 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13603 } 13604 pir.removeFilter(pa); 13605 } 13606 } 13607 } 13608 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13609 "Replacing preferred"); 13610 } 13611 } 13612 13613 @Override 13614 public void clearPackagePreferredActivities(String packageName) { 13615 final int uid = Binder.getCallingUid(); 13616 // writer 13617 synchronized (mPackages) { 13618 PackageParser.Package pkg = mPackages.get(packageName); 13619 if (pkg == null || pkg.applicationInfo.uid != uid) { 13620 if (mContext.checkCallingOrSelfPermission( 13621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13622 != PackageManager.PERMISSION_GRANTED) { 13623 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13624 < Build.VERSION_CODES.FROYO) { 13625 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13626 + Binder.getCallingUid()); 13627 return; 13628 } 13629 mContext.enforceCallingOrSelfPermission( 13630 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13631 } 13632 } 13633 13634 int user = UserHandle.getCallingUserId(); 13635 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13636 scheduleWritePackageRestrictionsLocked(user); 13637 } 13638 } 13639 } 13640 13641 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13642 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13643 ArrayList<PreferredActivity> removed = null; 13644 boolean changed = false; 13645 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13646 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13647 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13648 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13649 continue; 13650 } 13651 Iterator<PreferredActivity> it = pir.filterIterator(); 13652 while (it.hasNext()) { 13653 PreferredActivity pa = it.next(); 13654 // Mark entry for removal only if it matches the package name 13655 // and the entry is of type "always". 13656 if (packageName == null || 13657 (pa.mPref.mComponent.getPackageName().equals(packageName) 13658 && pa.mPref.mAlways)) { 13659 if (removed == null) { 13660 removed = new ArrayList<PreferredActivity>(); 13661 } 13662 removed.add(pa); 13663 } 13664 } 13665 if (removed != null) { 13666 for (int j=0; j<removed.size(); j++) { 13667 PreferredActivity pa = removed.get(j); 13668 pir.removeFilter(pa); 13669 } 13670 changed = true; 13671 } 13672 } 13673 return changed; 13674 } 13675 13676 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13677 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13678 if (userId == UserHandle.USER_ALL) { 13679 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13680 sUserManager.getUserIds())) { 13681 for (int oneUserId : sUserManager.getUserIds()) { 13682 scheduleWritePackageRestrictionsLocked(oneUserId); 13683 } 13684 } 13685 } else { 13686 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13687 scheduleWritePackageRestrictionsLocked(userId); 13688 } 13689 } 13690 } 13691 13692 13693 void clearDefaultBrowserIfNeeded(String packageName) { 13694 for (int oneUserId : sUserManager.getUserIds()) { 13695 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13696 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13697 if (packageName.equals(defaultBrowserPackageName)) { 13698 setDefaultBrowserPackageName(null, oneUserId); 13699 } 13700 } 13701 } 13702 13703 @Override 13704 public void resetPreferredActivities(int userId) { 13705 mContext.enforceCallingOrSelfPermission( 13706 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13707 // writer 13708 synchronized (mPackages) { 13709 clearPackagePreferredActivitiesLPw(null, userId); 13710 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13711 applyFactoryDefaultBrowserLPw(userId); 13712 primeDomainVerificationsLPw(userId); 13713 13714 scheduleWritePackageRestrictionsLocked(userId); 13715 } 13716 } 13717 13718 @Override 13719 public int getPreferredActivities(List<IntentFilter> outFilters, 13720 List<ComponentName> outActivities, String packageName) { 13721 13722 int num = 0; 13723 final int userId = UserHandle.getCallingUserId(); 13724 // reader 13725 synchronized (mPackages) { 13726 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13727 if (pir != null) { 13728 final Iterator<PreferredActivity> it = pir.filterIterator(); 13729 while (it.hasNext()) { 13730 final PreferredActivity pa = it.next(); 13731 if (packageName == null 13732 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13733 && pa.mPref.mAlways)) { 13734 if (outFilters != null) { 13735 outFilters.add(new IntentFilter(pa)); 13736 } 13737 if (outActivities != null) { 13738 outActivities.add(pa.mPref.mComponent); 13739 } 13740 } 13741 } 13742 } 13743 } 13744 13745 return num; 13746 } 13747 13748 @Override 13749 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13750 int userId) { 13751 int callingUid = Binder.getCallingUid(); 13752 if (callingUid != Process.SYSTEM_UID) { 13753 throw new SecurityException( 13754 "addPersistentPreferredActivity can only be run by the system"); 13755 } 13756 if (filter.countActions() == 0) { 13757 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13758 return; 13759 } 13760 synchronized (mPackages) { 13761 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13762 " :"); 13763 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13764 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13765 new PersistentPreferredActivity(filter, activity)); 13766 scheduleWritePackageRestrictionsLocked(userId); 13767 } 13768 } 13769 13770 @Override 13771 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13772 int callingUid = Binder.getCallingUid(); 13773 if (callingUid != Process.SYSTEM_UID) { 13774 throw new SecurityException( 13775 "clearPackagePersistentPreferredActivities can only be run by the system"); 13776 } 13777 ArrayList<PersistentPreferredActivity> removed = null; 13778 boolean changed = false; 13779 synchronized (mPackages) { 13780 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13781 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13782 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13783 .valueAt(i); 13784 if (userId != thisUserId) { 13785 continue; 13786 } 13787 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13788 while (it.hasNext()) { 13789 PersistentPreferredActivity ppa = it.next(); 13790 // Mark entry for removal only if it matches the package name. 13791 if (ppa.mComponent.getPackageName().equals(packageName)) { 13792 if (removed == null) { 13793 removed = new ArrayList<PersistentPreferredActivity>(); 13794 } 13795 removed.add(ppa); 13796 } 13797 } 13798 if (removed != null) { 13799 for (int j=0; j<removed.size(); j++) { 13800 PersistentPreferredActivity ppa = removed.get(j); 13801 ppir.removeFilter(ppa); 13802 } 13803 changed = true; 13804 } 13805 } 13806 13807 if (changed) { 13808 scheduleWritePackageRestrictionsLocked(userId); 13809 } 13810 } 13811 } 13812 13813 /** 13814 * Common machinery for picking apart a restored XML blob and passing 13815 * it to a caller-supplied functor to be applied to the running system. 13816 */ 13817 private void restoreFromXml(XmlPullParser parser, int userId, 13818 String expectedStartTag, BlobXmlRestorer functor) 13819 throws IOException, XmlPullParserException { 13820 int type; 13821 while ((type = parser.next()) != XmlPullParser.START_TAG 13822 && type != XmlPullParser.END_DOCUMENT) { 13823 } 13824 if (type != XmlPullParser.START_TAG) { 13825 // oops didn't find a start tag?! 13826 if (DEBUG_BACKUP) { 13827 Slog.e(TAG, "Didn't find start tag during restore"); 13828 } 13829 return; 13830 } 13831 13832 // this is supposed to be TAG_PREFERRED_BACKUP 13833 if (!expectedStartTag.equals(parser.getName())) { 13834 if (DEBUG_BACKUP) { 13835 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13836 } 13837 return; 13838 } 13839 13840 // skip interfering stuff, then we're aligned with the backing implementation 13841 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13842 functor.apply(parser, userId); 13843 } 13844 13845 private interface BlobXmlRestorer { 13846 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13847 } 13848 13849 /** 13850 * Non-Binder method, support for the backup/restore mechanism: write the 13851 * full set of preferred activities in its canonical XML format. Returns the 13852 * XML output as a byte array, or null if there is none. 13853 */ 13854 @Override 13855 public byte[] getPreferredActivityBackup(int userId) { 13856 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13857 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13858 } 13859 13860 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13861 try { 13862 final XmlSerializer serializer = new FastXmlSerializer(); 13863 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13864 serializer.startDocument(null, true); 13865 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13866 13867 synchronized (mPackages) { 13868 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13869 } 13870 13871 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13872 serializer.endDocument(); 13873 serializer.flush(); 13874 } catch (Exception e) { 13875 if (DEBUG_BACKUP) { 13876 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13877 } 13878 return null; 13879 } 13880 13881 return dataStream.toByteArray(); 13882 } 13883 13884 @Override 13885 public void restorePreferredActivities(byte[] backup, int userId) { 13886 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13887 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13888 } 13889 13890 try { 13891 final XmlPullParser parser = Xml.newPullParser(); 13892 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13893 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13894 new BlobXmlRestorer() { 13895 @Override 13896 public void apply(XmlPullParser parser, int userId) 13897 throws XmlPullParserException, IOException { 13898 synchronized (mPackages) { 13899 mSettings.readPreferredActivitiesLPw(parser, userId); 13900 } 13901 } 13902 } ); 13903 } catch (Exception e) { 13904 if (DEBUG_BACKUP) { 13905 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13906 } 13907 } 13908 } 13909 13910 /** 13911 * Non-Binder method, support for the backup/restore mechanism: write the 13912 * default browser (etc) settings in its canonical XML format. Returns the default 13913 * browser XML representation as a byte array, or null if there is none. 13914 */ 13915 @Override 13916 public byte[] getDefaultAppsBackup(int userId) { 13917 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13918 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13919 } 13920 13921 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13922 try { 13923 final XmlSerializer serializer = new FastXmlSerializer(); 13924 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13925 serializer.startDocument(null, true); 13926 serializer.startTag(null, TAG_DEFAULT_APPS); 13927 13928 synchronized (mPackages) { 13929 mSettings.writeDefaultAppsLPr(serializer, userId); 13930 } 13931 13932 serializer.endTag(null, TAG_DEFAULT_APPS); 13933 serializer.endDocument(); 13934 serializer.flush(); 13935 } catch (Exception e) { 13936 if (DEBUG_BACKUP) { 13937 Slog.e(TAG, "Unable to write default apps for backup", e); 13938 } 13939 return null; 13940 } 13941 13942 return dataStream.toByteArray(); 13943 } 13944 13945 @Override 13946 public void restoreDefaultApps(byte[] backup, int userId) { 13947 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13948 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13949 } 13950 13951 try { 13952 final XmlPullParser parser = Xml.newPullParser(); 13953 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13954 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13955 new BlobXmlRestorer() { 13956 @Override 13957 public void apply(XmlPullParser parser, int userId) 13958 throws XmlPullParserException, IOException { 13959 synchronized (mPackages) { 13960 mSettings.readDefaultAppsLPw(parser, userId); 13961 } 13962 } 13963 } ); 13964 } catch (Exception e) { 13965 if (DEBUG_BACKUP) { 13966 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13967 } 13968 } 13969 } 13970 13971 @Override 13972 public byte[] getIntentFilterVerificationBackup(int userId) { 13973 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13974 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13975 } 13976 13977 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13978 try { 13979 final XmlSerializer serializer = new FastXmlSerializer(); 13980 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13981 serializer.startDocument(null, true); 13982 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13983 13984 synchronized (mPackages) { 13985 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13986 } 13987 13988 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13989 serializer.endDocument(); 13990 serializer.flush(); 13991 } catch (Exception e) { 13992 if (DEBUG_BACKUP) { 13993 Slog.e(TAG, "Unable to write default apps for backup", e); 13994 } 13995 return null; 13996 } 13997 13998 return dataStream.toByteArray(); 13999 } 14000 14001 @Override 14002 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14003 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14004 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14005 } 14006 14007 try { 14008 final XmlPullParser parser = Xml.newPullParser(); 14009 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14010 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14011 new BlobXmlRestorer() { 14012 @Override 14013 public void apply(XmlPullParser parser, int userId) 14014 throws XmlPullParserException, IOException { 14015 synchronized (mPackages) { 14016 mSettings.readAllDomainVerificationsLPr(parser, userId); 14017 mSettings.writeLPr(); 14018 } 14019 } 14020 } ); 14021 } catch (Exception e) { 14022 if (DEBUG_BACKUP) { 14023 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14024 } 14025 } 14026 } 14027 14028 @Override 14029 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14030 int sourceUserId, int targetUserId, int flags) { 14031 mContext.enforceCallingOrSelfPermission( 14032 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14033 int callingUid = Binder.getCallingUid(); 14034 enforceOwnerRights(ownerPackage, callingUid); 14035 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14036 if (intentFilter.countActions() == 0) { 14037 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14038 return; 14039 } 14040 synchronized (mPackages) { 14041 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14042 ownerPackage, targetUserId, flags); 14043 CrossProfileIntentResolver resolver = 14044 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14045 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14046 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14047 if (existing != null) { 14048 int size = existing.size(); 14049 for (int i = 0; i < size; i++) { 14050 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14051 return; 14052 } 14053 } 14054 } 14055 resolver.addFilter(newFilter); 14056 scheduleWritePackageRestrictionsLocked(sourceUserId); 14057 } 14058 } 14059 14060 @Override 14061 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14062 mContext.enforceCallingOrSelfPermission( 14063 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14064 int callingUid = Binder.getCallingUid(); 14065 enforceOwnerRights(ownerPackage, callingUid); 14066 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14067 synchronized (mPackages) { 14068 CrossProfileIntentResolver resolver = 14069 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14070 ArraySet<CrossProfileIntentFilter> set = 14071 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14072 for (CrossProfileIntentFilter filter : set) { 14073 if (filter.getOwnerPackage().equals(ownerPackage)) { 14074 resolver.removeFilter(filter); 14075 } 14076 } 14077 scheduleWritePackageRestrictionsLocked(sourceUserId); 14078 } 14079 } 14080 14081 // Enforcing that callingUid is owning pkg on userId 14082 private void enforceOwnerRights(String pkg, int callingUid) { 14083 // The system owns everything. 14084 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14085 return; 14086 } 14087 int callingUserId = UserHandle.getUserId(callingUid); 14088 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14089 if (pi == null) { 14090 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14091 + callingUserId); 14092 } 14093 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14094 throw new SecurityException("Calling uid " + callingUid 14095 + " does not own package " + pkg); 14096 } 14097 } 14098 14099 @Override 14100 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14101 Intent intent = new Intent(Intent.ACTION_MAIN); 14102 intent.addCategory(Intent.CATEGORY_HOME); 14103 14104 final int callingUserId = UserHandle.getCallingUserId(); 14105 List<ResolveInfo> list = queryIntentActivities(intent, null, 14106 PackageManager.GET_META_DATA, callingUserId); 14107 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14108 true, false, false, callingUserId); 14109 14110 allHomeCandidates.clear(); 14111 if (list != null) { 14112 for (ResolveInfo ri : list) { 14113 allHomeCandidates.add(ri); 14114 } 14115 } 14116 return (preferred == null || preferred.activityInfo == null) 14117 ? null 14118 : new ComponentName(preferred.activityInfo.packageName, 14119 preferred.activityInfo.name); 14120 } 14121 14122 @Override 14123 public void setApplicationEnabledSetting(String appPackageName, 14124 int newState, int flags, int userId, String callingPackage) { 14125 if (!sUserManager.exists(userId)) return; 14126 if (callingPackage == null) { 14127 callingPackage = Integer.toString(Binder.getCallingUid()); 14128 } 14129 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14130 } 14131 14132 @Override 14133 public void setComponentEnabledSetting(ComponentName componentName, 14134 int newState, int flags, int userId) { 14135 if (!sUserManager.exists(userId)) return; 14136 setEnabledSetting(componentName.getPackageName(), 14137 componentName.getClassName(), newState, flags, userId, null); 14138 } 14139 14140 private void setEnabledSetting(final String packageName, String className, int newState, 14141 final int flags, int userId, String callingPackage) { 14142 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14143 || newState == COMPONENT_ENABLED_STATE_ENABLED 14144 || newState == COMPONENT_ENABLED_STATE_DISABLED 14145 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14146 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14147 throw new IllegalArgumentException("Invalid new component state: " 14148 + newState); 14149 } 14150 PackageSetting pkgSetting; 14151 final int uid = Binder.getCallingUid(); 14152 final int permission = mContext.checkCallingOrSelfPermission( 14153 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14154 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14155 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14156 boolean sendNow = false; 14157 boolean isApp = (className == null); 14158 String componentName = isApp ? packageName : className; 14159 int packageUid = -1; 14160 ArrayList<String> components; 14161 14162 // writer 14163 synchronized (mPackages) { 14164 pkgSetting = mSettings.mPackages.get(packageName); 14165 if (pkgSetting == null) { 14166 if (className == null) { 14167 throw new IllegalArgumentException( 14168 "Unknown package: " + packageName); 14169 } 14170 throw new IllegalArgumentException( 14171 "Unknown component: " + packageName 14172 + "/" + className); 14173 } 14174 // Allow root and verify that userId is not being specified by a different user 14175 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14176 throw new SecurityException( 14177 "Permission Denial: attempt to change component state from pid=" 14178 + Binder.getCallingPid() 14179 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14180 } 14181 if (className == null) { 14182 // We're dealing with an application/package level state change 14183 if (pkgSetting.getEnabled(userId) == newState) { 14184 // Nothing to do 14185 return; 14186 } 14187 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14188 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14189 // Don't care about who enables an app. 14190 callingPackage = null; 14191 } 14192 pkgSetting.setEnabled(newState, userId, callingPackage); 14193 // pkgSetting.pkg.mSetEnabled = newState; 14194 } else { 14195 // We're dealing with a component level state change 14196 // First, verify that this is a valid class name. 14197 PackageParser.Package pkg = pkgSetting.pkg; 14198 if (pkg == null || !pkg.hasComponentClassName(className)) { 14199 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14200 throw new IllegalArgumentException("Component class " + className 14201 + " does not exist in " + packageName); 14202 } else { 14203 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14204 + className + " does not exist in " + packageName); 14205 } 14206 } 14207 switch (newState) { 14208 case COMPONENT_ENABLED_STATE_ENABLED: 14209 if (!pkgSetting.enableComponentLPw(className, userId)) { 14210 return; 14211 } 14212 break; 14213 case COMPONENT_ENABLED_STATE_DISABLED: 14214 if (!pkgSetting.disableComponentLPw(className, userId)) { 14215 return; 14216 } 14217 break; 14218 case COMPONENT_ENABLED_STATE_DEFAULT: 14219 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14220 return; 14221 } 14222 break; 14223 default: 14224 Slog.e(TAG, "Invalid new component state: " + newState); 14225 return; 14226 } 14227 } 14228 scheduleWritePackageRestrictionsLocked(userId); 14229 components = mPendingBroadcasts.get(userId, packageName); 14230 final boolean newPackage = components == null; 14231 if (newPackage) { 14232 components = new ArrayList<String>(); 14233 } 14234 if (!components.contains(componentName)) { 14235 components.add(componentName); 14236 } 14237 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14238 sendNow = true; 14239 // Purge entry from pending broadcast list if another one exists already 14240 // since we are sending one right away. 14241 mPendingBroadcasts.remove(userId, packageName); 14242 } else { 14243 if (newPackage) { 14244 mPendingBroadcasts.put(userId, packageName, components); 14245 } 14246 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14247 // Schedule a message 14248 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14249 } 14250 } 14251 } 14252 14253 long callingId = Binder.clearCallingIdentity(); 14254 try { 14255 if (sendNow) { 14256 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14257 sendPackageChangedBroadcast(packageName, 14258 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14259 } 14260 } finally { 14261 Binder.restoreCallingIdentity(callingId); 14262 } 14263 } 14264 14265 private void sendPackageChangedBroadcast(String packageName, 14266 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14267 if (DEBUG_INSTALL) 14268 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14269 + componentNames); 14270 Bundle extras = new Bundle(4); 14271 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14272 String nameList[] = new String[componentNames.size()]; 14273 componentNames.toArray(nameList); 14274 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14275 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14276 extras.putInt(Intent.EXTRA_UID, packageUid); 14277 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14278 new int[] {UserHandle.getUserId(packageUid)}); 14279 } 14280 14281 @Override 14282 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14283 if (!sUserManager.exists(userId)) return; 14284 final int uid = Binder.getCallingUid(); 14285 final int permission = mContext.checkCallingOrSelfPermission( 14286 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14287 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14288 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14289 // writer 14290 synchronized (mPackages) { 14291 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14292 allowedByPermission, uid, userId)) { 14293 scheduleWritePackageRestrictionsLocked(userId); 14294 } 14295 } 14296 } 14297 14298 @Override 14299 public String getInstallerPackageName(String packageName) { 14300 // reader 14301 synchronized (mPackages) { 14302 return mSettings.getInstallerPackageNameLPr(packageName); 14303 } 14304 } 14305 14306 @Override 14307 public int getApplicationEnabledSetting(String packageName, int userId) { 14308 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14309 int uid = Binder.getCallingUid(); 14310 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14311 // reader 14312 synchronized (mPackages) { 14313 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14314 } 14315 } 14316 14317 @Override 14318 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14319 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14320 int uid = Binder.getCallingUid(); 14321 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14322 // reader 14323 synchronized (mPackages) { 14324 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14325 } 14326 } 14327 14328 @Override 14329 public void enterSafeMode() { 14330 enforceSystemOrRoot("Only the system can request entering safe mode"); 14331 14332 if (!mSystemReady) { 14333 mSafeMode = true; 14334 } 14335 } 14336 14337 @Override 14338 public void systemReady() { 14339 mSystemReady = true; 14340 14341 // Read the compatibilty setting when the system is ready. 14342 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14343 mContext.getContentResolver(), 14344 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14345 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14346 if (DEBUG_SETTINGS) { 14347 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14348 } 14349 14350 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14351 14352 synchronized (mPackages) { 14353 // Verify that all of the preferred activity components actually 14354 // exist. It is possible for applications to be updated and at 14355 // that point remove a previously declared activity component that 14356 // had been set as a preferred activity. We try to clean this up 14357 // the next time we encounter that preferred activity, but it is 14358 // possible for the user flow to never be able to return to that 14359 // situation so here we do a sanity check to make sure we haven't 14360 // left any junk around. 14361 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14362 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14363 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14364 removed.clear(); 14365 for (PreferredActivity pa : pir.filterSet()) { 14366 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14367 removed.add(pa); 14368 } 14369 } 14370 if (removed.size() > 0) { 14371 for (int r=0; r<removed.size(); r++) { 14372 PreferredActivity pa = removed.get(r); 14373 Slog.w(TAG, "Removing dangling preferred activity: " 14374 + pa.mPref.mComponent); 14375 pir.removeFilter(pa); 14376 } 14377 mSettings.writePackageRestrictionsLPr( 14378 mSettings.mPreferredActivities.keyAt(i)); 14379 } 14380 } 14381 14382 for (int userId : UserManagerService.getInstance().getUserIds()) { 14383 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14384 grantPermissionsUserIds = ArrayUtils.appendInt( 14385 grantPermissionsUserIds, userId); 14386 } 14387 } 14388 } 14389 sUserManager.systemReady(); 14390 14391 // If we upgraded grant all default permissions before kicking off. 14392 for (int userId : grantPermissionsUserIds) { 14393 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14394 } 14395 14396 // Kick off any messages waiting for system ready 14397 if (mPostSystemReadyMessages != null) { 14398 for (Message msg : mPostSystemReadyMessages) { 14399 msg.sendToTarget(); 14400 } 14401 mPostSystemReadyMessages = null; 14402 } 14403 14404 // Watch for external volumes that come and go over time 14405 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14406 storage.registerListener(mStorageListener); 14407 14408 mInstallerService.systemReady(); 14409 mPackageDexOptimizer.systemReady(); 14410 } 14411 14412 @Override 14413 public boolean isSafeMode() { 14414 return mSafeMode; 14415 } 14416 14417 @Override 14418 public boolean hasSystemUidErrors() { 14419 return mHasSystemUidErrors; 14420 } 14421 14422 static String arrayToString(int[] array) { 14423 StringBuffer buf = new StringBuffer(128); 14424 buf.append('['); 14425 if (array != null) { 14426 for (int i=0; i<array.length; i++) { 14427 if (i > 0) buf.append(", "); 14428 buf.append(array[i]); 14429 } 14430 } 14431 buf.append(']'); 14432 return buf.toString(); 14433 } 14434 14435 static class DumpState { 14436 public static final int DUMP_LIBS = 1 << 0; 14437 public static final int DUMP_FEATURES = 1 << 1; 14438 public static final int DUMP_RESOLVERS = 1 << 2; 14439 public static final int DUMP_PERMISSIONS = 1 << 3; 14440 public static final int DUMP_PACKAGES = 1 << 4; 14441 public static final int DUMP_SHARED_USERS = 1 << 5; 14442 public static final int DUMP_MESSAGES = 1 << 6; 14443 public static final int DUMP_PROVIDERS = 1 << 7; 14444 public static final int DUMP_VERIFIERS = 1 << 8; 14445 public static final int DUMP_PREFERRED = 1 << 9; 14446 public static final int DUMP_PREFERRED_XML = 1 << 10; 14447 public static final int DUMP_KEYSETS = 1 << 11; 14448 public static final int DUMP_VERSION = 1 << 12; 14449 public static final int DUMP_INSTALLS = 1 << 13; 14450 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14451 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14452 14453 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14454 14455 private int mTypes; 14456 14457 private int mOptions; 14458 14459 private boolean mTitlePrinted; 14460 14461 private SharedUserSetting mSharedUser; 14462 14463 public boolean isDumping(int type) { 14464 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14465 return true; 14466 } 14467 14468 return (mTypes & type) != 0; 14469 } 14470 14471 public void setDump(int type) { 14472 mTypes |= type; 14473 } 14474 14475 public boolean isOptionEnabled(int option) { 14476 return (mOptions & option) != 0; 14477 } 14478 14479 public void setOptionEnabled(int option) { 14480 mOptions |= option; 14481 } 14482 14483 public boolean onTitlePrinted() { 14484 final boolean printed = mTitlePrinted; 14485 mTitlePrinted = true; 14486 return printed; 14487 } 14488 14489 public boolean getTitlePrinted() { 14490 return mTitlePrinted; 14491 } 14492 14493 public void setTitlePrinted(boolean enabled) { 14494 mTitlePrinted = enabled; 14495 } 14496 14497 public SharedUserSetting getSharedUser() { 14498 return mSharedUser; 14499 } 14500 14501 public void setSharedUser(SharedUserSetting user) { 14502 mSharedUser = user; 14503 } 14504 } 14505 14506 @Override 14507 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14508 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14509 != PackageManager.PERMISSION_GRANTED) { 14510 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14511 + Binder.getCallingPid() 14512 + ", uid=" + Binder.getCallingUid() 14513 + " without permission " 14514 + android.Manifest.permission.DUMP); 14515 return; 14516 } 14517 14518 DumpState dumpState = new DumpState(); 14519 boolean fullPreferred = false; 14520 boolean checkin = false; 14521 14522 String packageName = null; 14523 ArraySet<String> permissionNames = null; 14524 14525 int opti = 0; 14526 while (opti < args.length) { 14527 String opt = args[opti]; 14528 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14529 break; 14530 } 14531 opti++; 14532 14533 if ("-a".equals(opt)) { 14534 // Right now we only know how to print all. 14535 } else if ("-h".equals(opt)) { 14536 pw.println("Package manager dump options:"); 14537 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14538 pw.println(" --checkin: dump for a checkin"); 14539 pw.println(" -f: print details of intent filters"); 14540 pw.println(" -h: print this help"); 14541 pw.println(" cmd may be one of:"); 14542 pw.println(" l[ibraries]: list known shared libraries"); 14543 pw.println(" f[ibraries]: list device features"); 14544 pw.println(" k[eysets]: print known keysets"); 14545 pw.println(" r[esolvers]: dump intent resolvers"); 14546 pw.println(" perm[issions]: dump permissions"); 14547 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14548 pw.println(" pref[erred]: print preferred package settings"); 14549 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14550 pw.println(" prov[iders]: dump content providers"); 14551 pw.println(" p[ackages]: dump installed packages"); 14552 pw.println(" s[hared-users]: dump shared user IDs"); 14553 pw.println(" m[essages]: print collected runtime messages"); 14554 pw.println(" v[erifiers]: print package verifier info"); 14555 pw.println(" version: print database version info"); 14556 pw.println(" write: write current settings now"); 14557 pw.println(" <package.name>: info about given package"); 14558 pw.println(" installs: details about install sessions"); 14559 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14560 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14561 return; 14562 } else if ("--checkin".equals(opt)) { 14563 checkin = true; 14564 } else if ("-f".equals(opt)) { 14565 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14566 } else { 14567 pw.println("Unknown argument: " + opt + "; use -h for help"); 14568 } 14569 } 14570 14571 // Is the caller requesting to dump a particular piece of data? 14572 if (opti < args.length) { 14573 String cmd = args[opti]; 14574 opti++; 14575 // Is this a package name? 14576 if ("android".equals(cmd) || cmd.contains(".")) { 14577 packageName = cmd; 14578 // When dumping a single package, we always dump all of its 14579 // filter information since the amount of data will be reasonable. 14580 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14581 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14582 dumpState.setDump(DumpState.DUMP_LIBS); 14583 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14584 dumpState.setDump(DumpState.DUMP_FEATURES); 14585 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14586 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14587 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14588 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14589 } else if ("permission".equals(cmd)) { 14590 if (opti >= args.length) { 14591 pw.println("Error: permission requires permission name"); 14592 return; 14593 } 14594 permissionNames = new ArraySet<>(); 14595 while (opti < args.length) { 14596 permissionNames.add(args[opti]); 14597 opti++; 14598 } 14599 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14600 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14601 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14602 dumpState.setDump(DumpState.DUMP_PREFERRED); 14603 } else if ("preferred-xml".equals(cmd)) { 14604 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14605 if (opti < args.length && "--full".equals(args[opti])) { 14606 fullPreferred = true; 14607 opti++; 14608 } 14609 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14610 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14611 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14612 dumpState.setDump(DumpState.DUMP_PACKAGES); 14613 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14614 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14615 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14616 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14617 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14618 dumpState.setDump(DumpState.DUMP_MESSAGES); 14619 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14620 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14621 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14622 || "intent-filter-verifiers".equals(cmd)) { 14623 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14624 } else if ("version".equals(cmd)) { 14625 dumpState.setDump(DumpState.DUMP_VERSION); 14626 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14627 dumpState.setDump(DumpState.DUMP_KEYSETS); 14628 } else if ("installs".equals(cmd)) { 14629 dumpState.setDump(DumpState.DUMP_INSTALLS); 14630 } else if ("write".equals(cmd)) { 14631 synchronized (mPackages) { 14632 mSettings.writeLPr(); 14633 pw.println("Settings written."); 14634 return; 14635 } 14636 } 14637 } 14638 14639 if (checkin) { 14640 pw.println("vers,1"); 14641 } 14642 14643 // reader 14644 synchronized (mPackages) { 14645 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14646 if (!checkin) { 14647 if (dumpState.onTitlePrinted()) 14648 pw.println(); 14649 pw.println("Database versions:"); 14650 pw.print(" SDK Version:"); 14651 pw.print(" internal="); 14652 pw.print(mSettings.mInternalSdkPlatform); 14653 pw.print(" external="); 14654 pw.println(mSettings.mExternalSdkPlatform); 14655 pw.print(" DB Version:"); 14656 pw.print(" internal="); 14657 pw.print(mSettings.mInternalDatabaseVersion); 14658 pw.print(" external="); 14659 pw.println(mSettings.mExternalDatabaseVersion); 14660 } 14661 } 14662 14663 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14664 if (!checkin) { 14665 if (dumpState.onTitlePrinted()) 14666 pw.println(); 14667 pw.println("Verifiers:"); 14668 pw.print(" Required: "); 14669 pw.print(mRequiredVerifierPackage); 14670 pw.print(" (uid="); 14671 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14672 pw.println(")"); 14673 } else if (mRequiredVerifierPackage != null) { 14674 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14675 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14676 } 14677 } 14678 14679 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14680 packageName == null) { 14681 if (mIntentFilterVerifierComponent != null) { 14682 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14683 if (!checkin) { 14684 if (dumpState.onTitlePrinted()) 14685 pw.println(); 14686 pw.println("Intent Filter Verifier:"); 14687 pw.print(" Using: "); 14688 pw.print(verifierPackageName); 14689 pw.print(" (uid="); 14690 pw.print(getPackageUid(verifierPackageName, 0)); 14691 pw.println(")"); 14692 } else if (verifierPackageName != null) { 14693 pw.print("ifv,"); pw.print(verifierPackageName); 14694 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14695 } 14696 } else { 14697 pw.println(); 14698 pw.println("No Intent Filter Verifier available!"); 14699 } 14700 } 14701 14702 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14703 boolean printedHeader = false; 14704 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14705 while (it.hasNext()) { 14706 String name = it.next(); 14707 SharedLibraryEntry ent = mSharedLibraries.get(name); 14708 if (!checkin) { 14709 if (!printedHeader) { 14710 if (dumpState.onTitlePrinted()) 14711 pw.println(); 14712 pw.println("Libraries:"); 14713 printedHeader = true; 14714 } 14715 pw.print(" "); 14716 } else { 14717 pw.print("lib,"); 14718 } 14719 pw.print(name); 14720 if (!checkin) { 14721 pw.print(" -> "); 14722 } 14723 if (ent.path != null) { 14724 if (!checkin) { 14725 pw.print("(jar) "); 14726 pw.print(ent.path); 14727 } else { 14728 pw.print(",jar,"); 14729 pw.print(ent.path); 14730 } 14731 } else { 14732 if (!checkin) { 14733 pw.print("(apk) "); 14734 pw.print(ent.apk); 14735 } else { 14736 pw.print(",apk,"); 14737 pw.print(ent.apk); 14738 } 14739 } 14740 pw.println(); 14741 } 14742 } 14743 14744 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14745 if (dumpState.onTitlePrinted()) 14746 pw.println(); 14747 if (!checkin) { 14748 pw.println("Features:"); 14749 } 14750 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14751 while (it.hasNext()) { 14752 String name = it.next(); 14753 if (!checkin) { 14754 pw.print(" "); 14755 } else { 14756 pw.print("feat,"); 14757 } 14758 pw.println(name); 14759 } 14760 } 14761 14762 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14763 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14764 : "Activity Resolver Table:", " ", packageName, 14765 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14766 dumpState.setTitlePrinted(true); 14767 } 14768 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14769 : "Receiver Resolver Table:", " ", packageName, 14770 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14771 dumpState.setTitlePrinted(true); 14772 } 14773 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14774 : "Service Resolver Table:", " ", packageName, 14775 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14776 dumpState.setTitlePrinted(true); 14777 } 14778 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14779 : "Provider Resolver Table:", " ", packageName, 14780 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14781 dumpState.setTitlePrinted(true); 14782 } 14783 } 14784 14785 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14786 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14787 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14788 int user = mSettings.mPreferredActivities.keyAt(i); 14789 if (pir.dump(pw, 14790 dumpState.getTitlePrinted() 14791 ? "\nPreferred Activities User " + user + ":" 14792 : "Preferred Activities User " + user + ":", " ", 14793 packageName, true, false)) { 14794 dumpState.setTitlePrinted(true); 14795 } 14796 } 14797 } 14798 14799 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14800 pw.flush(); 14801 FileOutputStream fout = new FileOutputStream(fd); 14802 BufferedOutputStream str = new BufferedOutputStream(fout); 14803 XmlSerializer serializer = new FastXmlSerializer(); 14804 try { 14805 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14806 serializer.startDocument(null, true); 14807 serializer.setFeature( 14808 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14809 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14810 serializer.endDocument(); 14811 serializer.flush(); 14812 } catch (IllegalArgumentException e) { 14813 pw.println("Failed writing: " + e); 14814 } catch (IllegalStateException e) { 14815 pw.println("Failed writing: " + e); 14816 } catch (IOException e) { 14817 pw.println("Failed writing: " + e); 14818 } 14819 } 14820 14821 if (!checkin 14822 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14823 && packageName == null) { 14824 pw.println(); 14825 int count = mSettings.mPackages.size(); 14826 if (count == 0) { 14827 pw.println("No applications!"); 14828 pw.println(); 14829 } else { 14830 final String prefix = " "; 14831 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14832 if (allPackageSettings.size() == 0) { 14833 pw.println("No domain preferred apps!"); 14834 pw.println(); 14835 } else { 14836 pw.println("App verification status:"); 14837 pw.println(); 14838 count = 0; 14839 for (PackageSetting ps : allPackageSettings) { 14840 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14841 if (ivi == null || ivi.getPackageName() == null) continue; 14842 pw.println(prefix + "Package: " + ivi.getPackageName()); 14843 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14844 pw.println(prefix + "Status: " + ivi.getStatusString()); 14845 pw.println(); 14846 count++; 14847 } 14848 if (count == 0) { 14849 pw.println(prefix + "No app verification established."); 14850 pw.println(); 14851 } 14852 for (int userId : sUserManager.getUserIds()) { 14853 pw.println("App linkages for user " + userId + ":"); 14854 pw.println(); 14855 count = 0; 14856 for (PackageSetting ps : allPackageSettings) { 14857 final int status = ps.getDomainVerificationStatusForUser(userId); 14858 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14859 continue; 14860 } 14861 pw.println(prefix + "Package: " + ps.name); 14862 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14863 String statusStr = IntentFilterVerificationInfo. 14864 getStatusStringFromValue(status); 14865 pw.println(prefix + "Status: " + statusStr); 14866 pw.println(); 14867 count++; 14868 } 14869 if (count == 0) { 14870 pw.println(prefix + "No configured app linkages."); 14871 pw.println(); 14872 } 14873 } 14874 } 14875 } 14876 } 14877 14878 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14879 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14880 if (packageName == null && permissionNames == null) { 14881 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14882 if (iperm == 0) { 14883 if (dumpState.onTitlePrinted()) 14884 pw.println(); 14885 pw.println("AppOp Permissions:"); 14886 } 14887 pw.print(" AppOp Permission "); 14888 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14889 pw.println(":"); 14890 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14891 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14892 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14893 } 14894 } 14895 } 14896 } 14897 14898 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14899 boolean printedSomething = false; 14900 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14901 if (packageName != null && !packageName.equals(p.info.packageName)) { 14902 continue; 14903 } 14904 if (!printedSomething) { 14905 if (dumpState.onTitlePrinted()) 14906 pw.println(); 14907 pw.println("Registered ContentProviders:"); 14908 printedSomething = true; 14909 } 14910 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14911 pw.print(" "); pw.println(p.toString()); 14912 } 14913 printedSomething = false; 14914 for (Map.Entry<String, PackageParser.Provider> entry : 14915 mProvidersByAuthority.entrySet()) { 14916 PackageParser.Provider p = entry.getValue(); 14917 if (packageName != null && !packageName.equals(p.info.packageName)) { 14918 continue; 14919 } 14920 if (!printedSomething) { 14921 if (dumpState.onTitlePrinted()) 14922 pw.println(); 14923 pw.println("ContentProvider Authorities:"); 14924 printedSomething = true; 14925 } 14926 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14927 pw.print(" "); pw.println(p.toString()); 14928 if (p.info != null && p.info.applicationInfo != null) { 14929 final String appInfo = p.info.applicationInfo.toString(); 14930 pw.print(" applicationInfo="); pw.println(appInfo); 14931 } 14932 } 14933 } 14934 14935 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14936 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14937 } 14938 14939 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14940 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14941 } 14942 14943 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14944 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14945 } 14946 14947 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14948 // XXX should handle packageName != null by dumping only install data that 14949 // the given package is involved with. 14950 if (dumpState.onTitlePrinted()) pw.println(); 14951 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14952 } 14953 14954 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14955 if (dumpState.onTitlePrinted()) pw.println(); 14956 mSettings.dumpReadMessagesLPr(pw, dumpState); 14957 14958 pw.println(); 14959 pw.println("Package warning messages:"); 14960 BufferedReader in = null; 14961 String line = null; 14962 try { 14963 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14964 while ((line = in.readLine()) != null) { 14965 if (line.contains("ignored: updated version")) continue; 14966 pw.println(line); 14967 } 14968 } catch (IOException ignored) { 14969 } finally { 14970 IoUtils.closeQuietly(in); 14971 } 14972 } 14973 14974 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14975 BufferedReader in = null; 14976 String line = null; 14977 try { 14978 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14979 while ((line = in.readLine()) != null) { 14980 if (line.contains("ignored: updated version")) continue; 14981 pw.print("msg,"); 14982 pw.println(line); 14983 } 14984 } catch (IOException ignored) { 14985 } finally { 14986 IoUtils.closeQuietly(in); 14987 } 14988 } 14989 } 14990 } 14991 14992 private String dumpDomainString(String packageName) { 14993 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 14994 List<IntentFilter> filters = getAllIntentFilters(packageName); 14995 14996 ArraySet<String> result = new ArraySet<>(); 14997 if (iviList.size() > 0) { 14998 for (IntentFilterVerificationInfo ivi : iviList) { 14999 for (String host : ivi.getDomains()) { 15000 result.add(host); 15001 } 15002 } 15003 } 15004 if (filters != null && filters.size() > 0) { 15005 for (IntentFilter filter : filters) { 15006 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15007 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) { 15008 result.addAll(filter.getHostsList()); 15009 } 15010 } 15011 } 15012 15013 StringBuilder sb = new StringBuilder(result.size() * 16); 15014 for (String domain : result) { 15015 if (sb.length() > 0) sb.append(" "); 15016 sb.append(domain); 15017 } 15018 return sb.toString(); 15019 } 15020 15021 // ------- apps on sdcard specific code ------- 15022 static final boolean DEBUG_SD_INSTALL = false; 15023 15024 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15025 15026 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15027 15028 private boolean mMediaMounted = false; 15029 15030 static String getEncryptKey() { 15031 try { 15032 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15033 SD_ENCRYPTION_KEYSTORE_NAME); 15034 if (sdEncKey == null) { 15035 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15036 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15037 if (sdEncKey == null) { 15038 Slog.e(TAG, "Failed to create encryption keys"); 15039 return null; 15040 } 15041 } 15042 return sdEncKey; 15043 } catch (NoSuchAlgorithmException nsae) { 15044 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15045 return null; 15046 } catch (IOException ioe) { 15047 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15048 return null; 15049 } 15050 } 15051 15052 /* 15053 * Update media status on PackageManager. 15054 */ 15055 @Override 15056 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15057 int callingUid = Binder.getCallingUid(); 15058 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15059 throw new SecurityException("Media status can only be updated by the system"); 15060 } 15061 // reader; this apparently protects mMediaMounted, but should probably 15062 // be a different lock in that case. 15063 synchronized (mPackages) { 15064 Log.i(TAG, "Updating external media status from " 15065 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15066 + (mediaStatus ? "mounted" : "unmounted")); 15067 if (DEBUG_SD_INSTALL) 15068 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15069 + ", mMediaMounted=" + mMediaMounted); 15070 if (mediaStatus == mMediaMounted) { 15071 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15072 : 0, -1); 15073 mHandler.sendMessage(msg); 15074 return; 15075 } 15076 mMediaMounted = mediaStatus; 15077 } 15078 // Queue up an async operation since the package installation may take a 15079 // little while. 15080 mHandler.post(new Runnable() { 15081 public void run() { 15082 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15083 } 15084 }); 15085 } 15086 15087 /** 15088 * Called by MountService when the initial ASECs to scan are available. 15089 * Should block until all the ASEC containers are finished being scanned. 15090 */ 15091 public void scanAvailableAsecs() { 15092 updateExternalMediaStatusInner(true, false, false); 15093 if (mShouldRestoreconData) { 15094 SELinuxMMAC.setRestoreconDone(); 15095 mShouldRestoreconData = false; 15096 } 15097 } 15098 15099 /* 15100 * Collect information of applications on external media, map them against 15101 * existing containers and update information based on current mount status. 15102 * Please note that we always have to report status if reportStatus has been 15103 * set to true especially when unloading packages. 15104 */ 15105 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15106 boolean externalStorage) { 15107 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15108 int[] uidArr = EmptyArray.INT; 15109 15110 final String[] list = PackageHelper.getSecureContainerList(); 15111 if (ArrayUtils.isEmpty(list)) { 15112 Log.i(TAG, "No secure containers found"); 15113 } else { 15114 // Process list of secure containers and categorize them 15115 // as active or stale based on their package internal state. 15116 15117 // reader 15118 synchronized (mPackages) { 15119 for (String cid : list) { 15120 // Leave stages untouched for now; installer service owns them 15121 if (PackageInstallerService.isStageName(cid)) continue; 15122 15123 if (DEBUG_SD_INSTALL) 15124 Log.i(TAG, "Processing container " + cid); 15125 String pkgName = getAsecPackageName(cid); 15126 if (pkgName == null) { 15127 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15128 continue; 15129 } 15130 if (DEBUG_SD_INSTALL) 15131 Log.i(TAG, "Looking for pkg : " + pkgName); 15132 15133 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15134 if (ps == null) { 15135 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15136 continue; 15137 } 15138 15139 /* 15140 * Skip packages that are not external if we're unmounting 15141 * external storage. 15142 */ 15143 if (externalStorage && !isMounted && !isExternal(ps)) { 15144 continue; 15145 } 15146 15147 final AsecInstallArgs args = new AsecInstallArgs(cid, 15148 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15149 // The package status is changed only if the code path 15150 // matches between settings and the container id. 15151 if (ps.codePathString != null 15152 && ps.codePathString.startsWith(args.getCodePath())) { 15153 if (DEBUG_SD_INSTALL) { 15154 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15155 + " at code path: " + ps.codePathString); 15156 } 15157 15158 // We do have a valid package installed on sdcard 15159 processCids.put(args, ps.codePathString); 15160 final int uid = ps.appId; 15161 if (uid != -1) { 15162 uidArr = ArrayUtils.appendInt(uidArr, uid); 15163 } 15164 } else { 15165 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15166 + ps.codePathString); 15167 } 15168 } 15169 } 15170 15171 Arrays.sort(uidArr); 15172 } 15173 15174 // Process packages with valid entries. 15175 if (isMounted) { 15176 if (DEBUG_SD_INSTALL) 15177 Log.i(TAG, "Loading packages"); 15178 loadMediaPackages(processCids, uidArr); 15179 startCleaningPackages(); 15180 mInstallerService.onSecureContainersAvailable(); 15181 } else { 15182 if (DEBUG_SD_INSTALL) 15183 Log.i(TAG, "Unloading packages"); 15184 unloadMediaPackages(processCids, uidArr, reportStatus); 15185 } 15186 } 15187 15188 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15189 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15190 final int size = infos.size(); 15191 final String[] packageNames = new String[size]; 15192 final int[] packageUids = new int[size]; 15193 for (int i = 0; i < size; i++) { 15194 final ApplicationInfo info = infos.get(i); 15195 packageNames[i] = info.packageName; 15196 packageUids[i] = info.uid; 15197 } 15198 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15199 finishedReceiver); 15200 } 15201 15202 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15203 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15204 sendResourcesChangedBroadcast(mediaStatus, replacing, 15205 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15206 } 15207 15208 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15209 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15210 int size = pkgList.length; 15211 if (size > 0) { 15212 // Send broadcasts here 15213 Bundle extras = new Bundle(); 15214 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15215 if (uidArr != null) { 15216 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15217 } 15218 if (replacing) { 15219 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15220 } 15221 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15222 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15223 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15224 } 15225 } 15226 15227 /* 15228 * Look at potentially valid container ids from processCids If package 15229 * information doesn't match the one on record or package scanning fails, 15230 * the cid is added to list of removeCids. We currently don't delete stale 15231 * containers. 15232 */ 15233 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15234 ArrayList<String> pkgList = new ArrayList<String>(); 15235 Set<AsecInstallArgs> keys = processCids.keySet(); 15236 15237 for (AsecInstallArgs args : keys) { 15238 String codePath = processCids.get(args); 15239 if (DEBUG_SD_INSTALL) 15240 Log.i(TAG, "Loading container : " + args.cid); 15241 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15242 try { 15243 // Make sure there are no container errors first. 15244 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15245 Slog.e(TAG, "Failed to mount cid : " + args.cid 15246 + " when installing from sdcard"); 15247 continue; 15248 } 15249 // Check code path here. 15250 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15251 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15252 + " does not match one in settings " + codePath); 15253 continue; 15254 } 15255 // Parse package 15256 int parseFlags = mDefParseFlags; 15257 if (args.isExternalAsec()) { 15258 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15259 } 15260 if (args.isFwdLocked()) { 15261 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15262 } 15263 15264 synchronized (mInstallLock) { 15265 PackageParser.Package pkg = null; 15266 try { 15267 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15268 } catch (PackageManagerException e) { 15269 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15270 } 15271 // Scan the package 15272 if (pkg != null) { 15273 /* 15274 * TODO why is the lock being held? doPostInstall is 15275 * called in other places without the lock. This needs 15276 * to be straightened out. 15277 */ 15278 // writer 15279 synchronized (mPackages) { 15280 retCode = PackageManager.INSTALL_SUCCEEDED; 15281 pkgList.add(pkg.packageName); 15282 // Post process args 15283 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15284 pkg.applicationInfo.uid); 15285 } 15286 } else { 15287 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15288 } 15289 } 15290 15291 } finally { 15292 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15293 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15294 } 15295 } 15296 } 15297 // writer 15298 synchronized (mPackages) { 15299 // If the platform SDK has changed since the last time we booted, 15300 // we need to re-grant app permission to catch any new ones that 15301 // appear. This is really a hack, and means that apps can in some 15302 // cases get permissions that the user didn't initially explicitly 15303 // allow... it would be nice to have some better way to handle 15304 // this situation. 15305 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15306 if (regrantPermissions) 15307 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15308 + mSdkVersion + "; regranting permissions for external storage"); 15309 mSettings.mExternalSdkPlatform = mSdkVersion; 15310 15311 // Make sure group IDs have been assigned, and any permission 15312 // changes in other apps are accounted for 15313 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15314 | (regrantPermissions 15315 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15316 : 0)); 15317 15318 mSettings.updateExternalDatabaseVersion(); 15319 15320 // can downgrade to reader 15321 // Persist settings 15322 mSettings.writeLPr(); 15323 } 15324 // Send a broadcast to let everyone know we are done processing 15325 if (pkgList.size() > 0) { 15326 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15327 } 15328 } 15329 15330 /* 15331 * Utility method to unload a list of specified containers 15332 */ 15333 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15334 // Just unmount all valid containers. 15335 for (AsecInstallArgs arg : cidArgs) { 15336 synchronized (mInstallLock) { 15337 arg.doPostDeleteLI(false); 15338 } 15339 } 15340 } 15341 15342 /* 15343 * Unload packages mounted on external media. This involves deleting package 15344 * data from internal structures, sending broadcasts about diabled packages, 15345 * gc'ing to free up references, unmounting all secure containers 15346 * corresponding to packages on external media, and posting a 15347 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15348 * that we always have to post this message if status has been requested no 15349 * matter what. 15350 */ 15351 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15352 final boolean reportStatus) { 15353 if (DEBUG_SD_INSTALL) 15354 Log.i(TAG, "unloading media packages"); 15355 ArrayList<String> pkgList = new ArrayList<String>(); 15356 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15357 final Set<AsecInstallArgs> keys = processCids.keySet(); 15358 for (AsecInstallArgs args : keys) { 15359 String pkgName = args.getPackageName(); 15360 if (DEBUG_SD_INSTALL) 15361 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15362 // Delete package internally 15363 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15364 synchronized (mInstallLock) { 15365 boolean res = deletePackageLI(pkgName, null, false, null, null, 15366 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15367 if (res) { 15368 pkgList.add(pkgName); 15369 } else { 15370 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15371 failedList.add(args); 15372 } 15373 } 15374 } 15375 15376 // reader 15377 synchronized (mPackages) { 15378 // We didn't update the settings after removing each package; 15379 // write them now for all packages. 15380 mSettings.writeLPr(); 15381 } 15382 15383 // We have to absolutely send UPDATED_MEDIA_STATUS only 15384 // after confirming that all the receivers processed the ordered 15385 // broadcast when packages get disabled, force a gc to clean things up. 15386 // and unload all the containers. 15387 if (pkgList.size() > 0) { 15388 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15389 new IIntentReceiver.Stub() { 15390 public void performReceive(Intent intent, int resultCode, String data, 15391 Bundle extras, boolean ordered, boolean sticky, 15392 int sendingUser) throws RemoteException { 15393 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15394 reportStatus ? 1 : 0, 1, keys); 15395 mHandler.sendMessage(msg); 15396 } 15397 }); 15398 } else { 15399 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15400 keys); 15401 mHandler.sendMessage(msg); 15402 } 15403 } 15404 15405 private void loadPrivatePackages(VolumeInfo vol) { 15406 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15407 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15408 synchronized (mInstallLock) { 15409 synchronized (mPackages) { 15410 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15411 for (PackageSetting ps : packages) { 15412 final PackageParser.Package pkg; 15413 try { 15414 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15415 loaded.add(pkg.applicationInfo); 15416 } catch (PackageManagerException e) { 15417 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15418 } 15419 } 15420 15421 // TODO: regrant any permissions that changed based since original install 15422 15423 mSettings.writeLPr(); 15424 } 15425 } 15426 15427 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15428 sendResourcesChangedBroadcast(true, false, loaded, null); 15429 } 15430 15431 private void unloadPrivatePackages(VolumeInfo vol) { 15432 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15433 synchronized (mInstallLock) { 15434 synchronized (mPackages) { 15435 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15436 for (PackageSetting ps : packages) { 15437 if (ps.pkg == null) continue; 15438 15439 final ApplicationInfo info = ps.pkg.applicationInfo; 15440 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15441 if (deletePackageLI(ps.name, null, false, null, null, 15442 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15443 unloaded.add(info); 15444 } else { 15445 Slog.w(TAG, "Failed to unload " + ps.codePath); 15446 } 15447 } 15448 15449 mSettings.writeLPr(); 15450 } 15451 } 15452 15453 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15454 sendResourcesChangedBroadcast(false, false, unloaded, null); 15455 } 15456 15457 /** 15458 * Examine all users present on given mounted volume, and destroy data 15459 * belonging to users that are no longer valid, or whose user ID has been 15460 * recycled. 15461 */ 15462 private void reconcileUsers(String volumeUuid) { 15463 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15464 if (ArrayUtils.isEmpty(files)) { 15465 Slog.d(TAG, "No users found on " + volumeUuid); 15466 return; 15467 } 15468 15469 for (File file : files) { 15470 if (!file.isDirectory()) continue; 15471 15472 final int userId; 15473 final UserInfo info; 15474 try { 15475 userId = Integer.parseInt(file.getName()); 15476 info = sUserManager.getUserInfo(userId); 15477 } catch (NumberFormatException e) { 15478 Slog.w(TAG, "Invalid user directory " + file); 15479 continue; 15480 } 15481 15482 boolean destroyUser = false; 15483 if (info == null) { 15484 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15485 + " because no matching user was found"); 15486 destroyUser = true; 15487 } else { 15488 try { 15489 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15490 } catch (IOException e) { 15491 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15492 + " because we failed to enforce serial number: " + e); 15493 destroyUser = true; 15494 } 15495 } 15496 15497 if (destroyUser) { 15498 synchronized (mInstallLock) { 15499 mInstaller.removeUserDataDirs(volumeUuid, userId); 15500 } 15501 } 15502 } 15503 15504 final UserManager um = mContext.getSystemService(UserManager.class); 15505 for (UserInfo user : um.getUsers()) { 15506 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15507 if (userDir.exists()) continue; 15508 15509 try { 15510 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15511 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15512 } catch (IOException e) { 15513 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15514 } 15515 } 15516 } 15517 15518 /** 15519 * Examine all apps present on given mounted volume, and destroy apps that 15520 * aren't expected, either due to uninstallation or reinstallation on 15521 * another volume. 15522 */ 15523 private void reconcileApps(String volumeUuid) { 15524 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15525 if (ArrayUtils.isEmpty(files)) { 15526 Slog.d(TAG, "No apps found on " + volumeUuid); 15527 return; 15528 } 15529 15530 for (File file : files) { 15531 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15532 && !PackageInstallerService.isStageName(file.getName()); 15533 if (!isPackage) { 15534 // Ignore entries which are not packages 15535 continue; 15536 } 15537 15538 boolean destroyApp = false; 15539 String packageName = null; 15540 try { 15541 final PackageLite pkg = PackageParser.parsePackageLite(file, 15542 PackageParser.PARSE_MUST_BE_APK); 15543 packageName = pkg.packageName; 15544 15545 synchronized (mPackages) { 15546 final PackageSetting ps = mSettings.mPackages.get(packageName); 15547 if (ps == null) { 15548 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15549 + volumeUuid + " because we found no install record"); 15550 destroyApp = true; 15551 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15552 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15553 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15554 destroyApp = true; 15555 } 15556 } 15557 15558 } catch (PackageParserException e) { 15559 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15560 destroyApp = true; 15561 } 15562 15563 if (destroyApp) { 15564 synchronized (mInstallLock) { 15565 if (packageName != null) { 15566 removeDataDirsLI(volumeUuid, packageName); 15567 } 15568 if (file.isDirectory()) { 15569 mInstaller.rmPackageDir(file.getAbsolutePath()); 15570 } else { 15571 file.delete(); 15572 } 15573 } 15574 } 15575 } 15576 } 15577 15578 private void unfreezePackage(String packageName) { 15579 synchronized (mPackages) { 15580 final PackageSetting ps = mSettings.mPackages.get(packageName); 15581 if (ps != null) { 15582 ps.frozen = false; 15583 } 15584 } 15585 } 15586 15587 @Override 15588 public int movePackage(final String packageName, final String volumeUuid) { 15589 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15590 15591 final int moveId = mNextMoveId.getAndIncrement(); 15592 try { 15593 movePackageInternal(packageName, volumeUuid, moveId); 15594 } catch (PackageManagerException e) { 15595 Slog.w(TAG, "Failed to move " + packageName, e); 15596 mMoveCallbacks.notifyStatusChanged(moveId, 15597 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15598 } 15599 return moveId; 15600 } 15601 15602 private void movePackageInternal(final String packageName, final String volumeUuid, 15603 final int moveId) throws PackageManagerException { 15604 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15605 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15606 final PackageManager pm = mContext.getPackageManager(); 15607 15608 final boolean currentAsec; 15609 final String currentVolumeUuid; 15610 final File codeFile; 15611 final String installerPackageName; 15612 final String packageAbiOverride; 15613 final int appId; 15614 final String seinfo; 15615 final String label; 15616 15617 // reader 15618 synchronized (mPackages) { 15619 final PackageParser.Package pkg = mPackages.get(packageName); 15620 final PackageSetting ps = mSettings.mPackages.get(packageName); 15621 if (pkg == null || ps == null) { 15622 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15623 } 15624 15625 if (pkg.applicationInfo.isSystemApp()) { 15626 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15627 "Cannot move system application"); 15628 } 15629 15630 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15631 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15632 "Package already moved to " + volumeUuid); 15633 } 15634 15635 final File probe = new File(pkg.codePath); 15636 final File probeOat = new File(probe, "oat"); 15637 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15638 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15639 "Move only supported for modern cluster style installs"); 15640 } 15641 15642 if (ps.frozen) { 15643 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15644 "Failed to move already frozen package"); 15645 } 15646 ps.frozen = true; 15647 15648 currentAsec = pkg.applicationInfo.isForwardLocked() 15649 || pkg.applicationInfo.isExternalAsec(); 15650 currentVolumeUuid = ps.volumeUuid; 15651 codeFile = new File(pkg.codePath); 15652 installerPackageName = ps.installerPackageName; 15653 packageAbiOverride = ps.cpuAbiOverrideString; 15654 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15655 seinfo = pkg.applicationInfo.seinfo; 15656 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15657 } 15658 15659 // Now that we're guarded by frozen state, kill app during move 15660 killApplication(packageName, appId, "move pkg"); 15661 15662 final Bundle extras = new Bundle(); 15663 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15664 extras.putString(Intent.EXTRA_TITLE, label); 15665 mMoveCallbacks.notifyCreated(moveId, extras); 15666 15667 int installFlags; 15668 final boolean moveCompleteApp; 15669 final File measurePath; 15670 15671 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15672 installFlags = INSTALL_INTERNAL; 15673 moveCompleteApp = !currentAsec; 15674 measurePath = Environment.getDataAppDirectory(volumeUuid); 15675 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15676 installFlags = INSTALL_EXTERNAL; 15677 moveCompleteApp = false; 15678 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15679 } else { 15680 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15681 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15682 || !volume.isMountedWritable()) { 15683 unfreezePackage(packageName); 15684 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15685 "Move location not mounted private volume"); 15686 } 15687 15688 Preconditions.checkState(!currentAsec); 15689 15690 installFlags = INSTALL_INTERNAL; 15691 moveCompleteApp = true; 15692 measurePath = Environment.getDataAppDirectory(volumeUuid); 15693 } 15694 15695 final PackageStats stats = new PackageStats(null, -1); 15696 synchronized (mInstaller) { 15697 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15698 unfreezePackage(packageName); 15699 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15700 "Failed to measure package size"); 15701 } 15702 } 15703 15704 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15705 + stats.dataSize); 15706 15707 final long startFreeBytes = measurePath.getFreeSpace(); 15708 final long sizeBytes; 15709 if (moveCompleteApp) { 15710 sizeBytes = stats.codeSize + stats.dataSize; 15711 } else { 15712 sizeBytes = stats.codeSize; 15713 } 15714 15715 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15716 unfreezePackage(packageName); 15717 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15718 "Not enough free space to move"); 15719 } 15720 15721 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15722 15723 final CountDownLatch installedLatch = new CountDownLatch(1); 15724 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15725 @Override 15726 public void onUserActionRequired(Intent intent) throws RemoteException { 15727 throw new IllegalStateException(); 15728 } 15729 15730 @Override 15731 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15732 Bundle extras) throws RemoteException { 15733 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15734 + PackageManager.installStatusToString(returnCode, msg)); 15735 15736 installedLatch.countDown(); 15737 15738 // Regardless of success or failure of the move operation, 15739 // always unfreeze the package 15740 unfreezePackage(packageName); 15741 15742 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15743 switch (status) { 15744 case PackageInstaller.STATUS_SUCCESS: 15745 mMoveCallbacks.notifyStatusChanged(moveId, 15746 PackageManager.MOVE_SUCCEEDED); 15747 break; 15748 case PackageInstaller.STATUS_FAILURE_STORAGE: 15749 mMoveCallbacks.notifyStatusChanged(moveId, 15750 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15751 break; 15752 default: 15753 mMoveCallbacks.notifyStatusChanged(moveId, 15754 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15755 break; 15756 } 15757 } 15758 }; 15759 15760 final MoveInfo move; 15761 if (moveCompleteApp) { 15762 // Kick off a thread to report progress estimates 15763 new Thread() { 15764 @Override 15765 public void run() { 15766 while (true) { 15767 try { 15768 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15769 break; 15770 } 15771 } catch (InterruptedException ignored) { 15772 } 15773 15774 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15775 final int progress = 10 + (int) MathUtils.constrain( 15776 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15777 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15778 } 15779 } 15780 }.start(); 15781 15782 final String dataAppName = codeFile.getName(); 15783 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15784 dataAppName, appId, seinfo); 15785 } else { 15786 move = null; 15787 } 15788 15789 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15790 15791 final Message msg = mHandler.obtainMessage(INIT_COPY); 15792 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15793 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15794 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15795 mHandler.sendMessage(msg); 15796 } 15797 15798 @Override 15799 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15800 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15801 15802 final int realMoveId = mNextMoveId.getAndIncrement(); 15803 final Bundle extras = new Bundle(); 15804 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15805 mMoveCallbacks.notifyCreated(realMoveId, extras); 15806 15807 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15808 @Override 15809 public void onCreated(int moveId, Bundle extras) { 15810 // Ignored 15811 } 15812 15813 @Override 15814 public void onStatusChanged(int moveId, int status, long estMillis) { 15815 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15816 } 15817 }; 15818 15819 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15820 storage.setPrimaryStorageUuid(volumeUuid, callback); 15821 return realMoveId; 15822 } 15823 15824 @Override 15825 public int getMoveStatus(int moveId) { 15826 mContext.enforceCallingOrSelfPermission( 15827 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15828 return mMoveCallbacks.mLastStatus.get(moveId); 15829 } 15830 15831 @Override 15832 public void registerMoveCallback(IPackageMoveObserver callback) { 15833 mContext.enforceCallingOrSelfPermission( 15834 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15835 mMoveCallbacks.register(callback); 15836 } 15837 15838 @Override 15839 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15840 mContext.enforceCallingOrSelfPermission( 15841 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15842 mMoveCallbacks.unregister(callback); 15843 } 15844 15845 @Override 15846 public boolean setInstallLocation(int loc) { 15847 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15848 null); 15849 if (getInstallLocation() == loc) { 15850 return true; 15851 } 15852 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15853 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15854 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15855 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15856 return true; 15857 } 15858 return false; 15859 } 15860 15861 @Override 15862 public int getInstallLocation() { 15863 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15864 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15865 PackageHelper.APP_INSTALL_AUTO); 15866 } 15867 15868 /** Called by UserManagerService */ 15869 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15870 mDirtyUsers.remove(userHandle); 15871 mSettings.removeUserLPw(userHandle); 15872 mPendingBroadcasts.remove(userHandle); 15873 if (mInstaller != null) { 15874 // Technically, we shouldn't be doing this with the package lock 15875 // held. However, this is very rare, and there is already so much 15876 // other disk I/O going on, that we'll let it slide for now. 15877 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15878 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15879 final String volumeUuid = vol.getFsUuid(); 15880 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15881 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15882 } 15883 } 15884 mUserNeedsBadging.delete(userHandle); 15885 removeUnusedPackagesLILPw(userManager, userHandle); 15886 } 15887 15888 /** 15889 * We're removing userHandle and would like to remove any downloaded packages 15890 * that are no longer in use by any other user. 15891 * @param userHandle the user being removed 15892 */ 15893 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15894 final boolean DEBUG_CLEAN_APKS = false; 15895 int [] users = userManager.getUserIdsLPr(); 15896 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15897 while (psit.hasNext()) { 15898 PackageSetting ps = psit.next(); 15899 if (ps.pkg == null) { 15900 continue; 15901 } 15902 final String packageName = ps.pkg.packageName; 15903 // Skip over if system app 15904 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15905 continue; 15906 } 15907 if (DEBUG_CLEAN_APKS) { 15908 Slog.i(TAG, "Checking package " + packageName); 15909 } 15910 boolean keep = false; 15911 for (int i = 0; i < users.length; i++) { 15912 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15913 keep = true; 15914 if (DEBUG_CLEAN_APKS) { 15915 Slog.i(TAG, " Keeping package " + packageName + " for user " 15916 + users[i]); 15917 } 15918 break; 15919 } 15920 } 15921 if (!keep) { 15922 if (DEBUG_CLEAN_APKS) { 15923 Slog.i(TAG, " Removing package " + packageName); 15924 } 15925 mHandler.post(new Runnable() { 15926 public void run() { 15927 deletePackageX(packageName, userHandle, 0); 15928 } //end run 15929 }); 15930 } 15931 } 15932 } 15933 15934 /** Called by UserManagerService */ 15935 void createNewUserLILPw(int userHandle) { 15936 if (mInstaller != null) { 15937 mInstaller.createUserConfig(userHandle); 15938 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15939 applyFactoryDefaultBrowserLPw(userHandle); 15940 primeDomainVerificationsLPw(userHandle); 15941 } 15942 } 15943 15944 void newUserCreatedLILPw(final int userHandle) { 15945 // We cannot grant the default permissions with a lock held as 15946 // we query providers from other components for default handlers 15947 // such as enabled IMEs, etc. 15948 mHandler.post(new Runnable() { 15949 @Override 15950 public void run() { 15951 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15952 } 15953 }); 15954 } 15955 15956 @Override 15957 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15958 mContext.enforceCallingOrSelfPermission( 15959 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15960 "Only package verification agents can read the verifier device identity"); 15961 15962 synchronized (mPackages) { 15963 return mSettings.getVerifierDeviceIdentityLPw(); 15964 } 15965 } 15966 15967 @Override 15968 public void setPermissionEnforced(String permission, boolean enforced) { 15969 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15970 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15971 synchronized (mPackages) { 15972 if (mSettings.mReadExternalStorageEnforced == null 15973 || mSettings.mReadExternalStorageEnforced != enforced) { 15974 mSettings.mReadExternalStorageEnforced = enforced; 15975 mSettings.writeLPr(); 15976 } 15977 } 15978 // kill any non-foreground processes so we restart them and 15979 // grant/revoke the GID. 15980 final IActivityManager am = ActivityManagerNative.getDefault(); 15981 if (am != null) { 15982 final long token = Binder.clearCallingIdentity(); 15983 try { 15984 am.killProcessesBelowForeground("setPermissionEnforcement"); 15985 } catch (RemoteException e) { 15986 } finally { 15987 Binder.restoreCallingIdentity(token); 15988 } 15989 } 15990 } else { 15991 throw new IllegalArgumentException("No selective enforcement for " + permission); 15992 } 15993 } 15994 15995 @Override 15996 @Deprecated 15997 public boolean isPermissionEnforced(String permission) { 15998 return true; 15999 } 16000 16001 @Override 16002 public boolean isStorageLow() { 16003 final long token = Binder.clearCallingIdentity(); 16004 try { 16005 final DeviceStorageMonitorInternal 16006 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16007 if (dsm != null) { 16008 return dsm.isMemoryLow(); 16009 } else { 16010 return false; 16011 } 16012 } finally { 16013 Binder.restoreCallingIdentity(token); 16014 } 16015 } 16016 16017 @Override 16018 public IPackageInstaller getPackageInstaller() { 16019 return mInstallerService; 16020 } 16021 16022 private boolean userNeedsBadging(int userId) { 16023 int index = mUserNeedsBadging.indexOfKey(userId); 16024 if (index < 0) { 16025 final UserInfo userInfo; 16026 final long token = Binder.clearCallingIdentity(); 16027 try { 16028 userInfo = sUserManager.getUserInfo(userId); 16029 } finally { 16030 Binder.restoreCallingIdentity(token); 16031 } 16032 final boolean b; 16033 if (userInfo != null && userInfo.isManagedProfile()) { 16034 b = true; 16035 } else { 16036 b = false; 16037 } 16038 mUserNeedsBadging.put(userId, b); 16039 return b; 16040 } 16041 return mUserNeedsBadging.valueAt(index); 16042 } 16043 16044 @Override 16045 public KeySet getKeySetByAlias(String packageName, String alias) { 16046 if (packageName == null || alias == null) { 16047 return null; 16048 } 16049 synchronized(mPackages) { 16050 final PackageParser.Package pkg = mPackages.get(packageName); 16051 if (pkg == null) { 16052 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16053 throw new IllegalArgumentException("Unknown package: " + packageName); 16054 } 16055 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16056 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16057 } 16058 } 16059 16060 @Override 16061 public KeySet getSigningKeySet(String packageName) { 16062 if (packageName == null) { 16063 return null; 16064 } 16065 synchronized(mPackages) { 16066 final PackageParser.Package pkg = mPackages.get(packageName); 16067 if (pkg == null) { 16068 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16069 throw new IllegalArgumentException("Unknown package: " + packageName); 16070 } 16071 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16072 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16073 throw new SecurityException("May not access signing KeySet of other apps."); 16074 } 16075 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16076 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16077 } 16078 } 16079 16080 @Override 16081 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16082 if (packageName == null || ks == null) { 16083 return false; 16084 } 16085 synchronized(mPackages) { 16086 final PackageParser.Package pkg = mPackages.get(packageName); 16087 if (pkg == null) { 16088 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16089 throw new IllegalArgumentException("Unknown package: " + packageName); 16090 } 16091 IBinder ksh = ks.getToken(); 16092 if (ksh instanceof KeySetHandle) { 16093 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16094 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16095 } 16096 return false; 16097 } 16098 } 16099 16100 @Override 16101 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16102 if (packageName == null || ks == null) { 16103 return false; 16104 } 16105 synchronized(mPackages) { 16106 final PackageParser.Package pkg = mPackages.get(packageName); 16107 if (pkg == null) { 16108 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16109 throw new IllegalArgumentException("Unknown package: " + packageName); 16110 } 16111 IBinder ksh = ks.getToken(); 16112 if (ksh instanceof KeySetHandle) { 16113 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16114 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16115 } 16116 return false; 16117 } 16118 } 16119 16120 public void getUsageStatsIfNoPackageUsageInfo() { 16121 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16122 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16123 if (usm == null) { 16124 throw new IllegalStateException("UsageStatsManager must be initialized"); 16125 } 16126 long now = System.currentTimeMillis(); 16127 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16128 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16129 String packageName = entry.getKey(); 16130 PackageParser.Package pkg = mPackages.get(packageName); 16131 if (pkg == null) { 16132 continue; 16133 } 16134 UsageStats usage = entry.getValue(); 16135 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16136 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16137 } 16138 } 16139 } 16140 16141 /** 16142 * Check and throw if the given before/after packages would be considered a 16143 * downgrade. 16144 */ 16145 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16146 throws PackageManagerException { 16147 if (after.versionCode < before.mVersionCode) { 16148 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16149 "Update version code " + after.versionCode + " is older than current " 16150 + before.mVersionCode); 16151 } else if (after.versionCode == before.mVersionCode) { 16152 if (after.baseRevisionCode < before.baseRevisionCode) { 16153 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16154 "Update base revision code " + after.baseRevisionCode 16155 + " is older than current " + before.baseRevisionCode); 16156 } 16157 16158 if (!ArrayUtils.isEmpty(after.splitNames)) { 16159 for (int i = 0; i < after.splitNames.length; i++) { 16160 final String splitName = after.splitNames[i]; 16161 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16162 if (j != -1) { 16163 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16164 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16165 "Update split " + splitName + " revision code " 16166 + after.splitRevisionCodes[i] + " is older than current " 16167 + before.splitRevisionCodes[j]); 16168 } 16169 } 16170 } 16171 } 16172 } 16173 } 16174 16175 private static class MoveCallbacks extends Handler { 16176 private static final int MSG_CREATED = 1; 16177 private static final int MSG_STATUS_CHANGED = 2; 16178 16179 private final RemoteCallbackList<IPackageMoveObserver> 16180 mCallbacks = new RemoteCallbackList<>(); 16181 16182 private final SparseIntArray mLastStatus = new SparseIntArray(); 16183 16184 public MoveCallbacks(Looper looper) { 16185 super(looper); 16186 } 16187 16188 public void register(IPackageMoveObserver callback) { 16189 mCallbacks.register(callback); 16190 } 16191 16192 public void unregister(IPackageMoveObserver callback) { 16193 mCallbacks.unregister(callback); 16194 } 16195 16196 @Override 16197 public void handleMessage(Message msg) { 16198 final SomeArgs args = (SomeArgs) msg.obj; 16199 final int n = mCallbacks.beginBroadcast(); 16200 for (int i = 0; i < n; i++) { 16201 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16202 try { 16203 invokeCallback(callback, msg.what, args); 16204 } catch (RemoteException ignored) { 16205 } 16206 } 16207 mCallbacks.finishBroadcast(); 16208 args.recycle(); 16209 } 16210 16211 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16212 throws RemoteException { 16213 switch (what) { 16214 case MSG_CREATED: { 16215 callback.onCreated(args.argi1, (Bundle) args.arg2); 16216 break; 16217 } 16218 case MSG_STATUS_CHANGED: { 16219 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16220 break; 16221 } 16222 } 16223 } 16224 16225 private void notifyCreated(int moveId, Bundle extras) { 16226 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16227 16228 final SomeArgs args = SomeArgs.obtain(); 16229 args.argi1 = moveId; 16230 args.arg2 = extras; 16231 obtainMessage(MSG_CREATED, args).sendToTarget(); 16232 } 16233 16234 private void notifyStatusChanged(int moveId, int status) { 16235 notifyStatusChanged(moveId, status, -1); 16236 } 16237 16238 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16239 Slog.v(TAG, "Move " + moveId + " status " + status); 16240 16241 final SomeArgs args = SomeArgs.obtain(); 16242 args.argi1 = moveId; 16243 args.argi2 = status; 16244 args.arg3 = estMillis; 16245 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16246 16247 synchronized (mLastStatus) { 16248 mLastStatus.put(moveId, status); 16249 } 16250 } 16251 } 16252 16253 private final class OnPermissionChangeListeners extends Handler { 16254 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16255 16256 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16257 new RemoteCallbackList<>(); 16258 16259 public OnPermissionChangeListeners(Looper looper) { 16260 super(looper); 16261 } 16262 16263 @Override 16264 public void handleMessage(Message msg) { 16265 switch (msg.what) { 16266 case MSG_ON_PERMISSIONS_CHANGED: { 16267 final int uid = msg.arg1; 16268 handleOnPermissionsChanged(uid); 16269 } break; 16270 } 16271 } 16272 16273 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16274 mPermissionListeners.register(listener); 16275 16276 } 16277 16278 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16279 mPermissionListeners.unregister(listener); 16280 } 16281 16282 public void onPermissionsChanged(int uid) { 16283 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16284 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16285 } 16286 } 16287 16288 private void handleOnPermissionsChanged(int uid) { 16289 final int count = mPermissionListeners.beginBroadcast(); 16290 try { 16291 for (int i = 0; i < count; i++) { 16292 IOnPermissionsChangeListener callback = mPermissionListeners 16293 .getBroadcastItem(i); 16294 try { 16295 callback.onPermissionsChanged(uid); 16296 } catch (RemoteException e) { 16297 Log.e(TAG, "Permission listener is dead", e); 16298 } 16299 } 16300 } finally { 16301 mPermissionListeners.finishBroadcast(); 16302 } 16303 } 16304 } 16305 16306 private class PackageManagerInternalImpl extends PackageManagerInternal { 16307 @Override 16308 public void setLocationPackagesProvider(PackagesProvider provider) { 16309 synchronized (mPackages) { 16310 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16311 } 16312 } 16313 16314 @Override 16315 public void setImePackagesProvider(PackagesProvider provider) { 16316 synchronized (mPackages) { 16317 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16318 } 16319 } 16320 16321 @Override 16322 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16323 synchronized (mPackages) { 16324 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16325 } 16326 } 16327 16328 @Override 16329 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16330 synchronized (mPackages) { 16331 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16332 } 16333 } 16334 16335 @Override 16336 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16337 synchronized (mPackages) { 16338 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16339 } 16340 } 16341 16342 @Override 16343 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16344 synchronized (mPackages) { 16345 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16346 } 16347 } 16348 16349 @Override 16350 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16351 synchronized (mPackages) { 16352 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16353 packageName, userId); 16354 } 16355 } 16356 16357 @Override 16358 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16359 synchronized (mPackages) { 16360 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16361 packageName, userId); 16362 } 16363 } 16364 } 16365 16366 @Override 16367 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16368 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16369 synchronized (mPackages) { 16370 final long identity = Binder.clearCallingIdentity(); 16371 try { 16372 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16373 packageNames, userId); 16374 } finally { 16375 Binder.restoreCallingIdentity(identity); 16376 } 16377 } 16378 } 16379 16380 private static void enforceSystemOrPhoneCaller(String tag) { 16381 int callingUid = Binder.getCallingUid(); 16382 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16383 throw new SecurityException( 16384 "Cannot call " + tag + " from UID " + callingUid); 16385 } 16386 } 16387} 16388