PackageManagerService.java revision 7efb0521ff4af2eeca5c99011ece066848069ffc
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 * 275mmm frameworks/base/tests/AndroidTests 276adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 277adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 278 * 279 * {@hide} 280 */ 281public class PackageManagerService extends IPackageManager.Stub { 282 static final String TAG = "PackageManager"; 283 static final boolean DEBUG_SETTINGS = false; 284 static final boolean DEBUG_PREFERRED = false; 285 static final boolean DEBUG_UPGRADE = false; 286 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 287 private static final boolean DEBUG_BACKUP = true; 288 private static final boolean DEBUG_INSTALL = false; 289 private static final boolean DEBUG_REMOVE = false; 290 private static final boolean DEBUG_BROADCASTS = false; 291 private static final boolean DEBUG_SHOW_INFO = false; 292 private static final boolean DEBUG_PACKAGE_INFO = false; 293 private static final boolean DEBUG_INTENT_MATCHING = false; 294 private static final boolean DEBUG_PACKAGE_SCANNING = false; 295 private static final boolean DEBUG_VERIFY = false; 296 private static final boolean DEBUG_DEXOPT = false; 297 private static final boolean DEBUG_ABI_SELECTION = false; 298 299 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 300 301 private static final int RADIO_UID = Process.PHONE_UID; 302 private static final int LOG_UID = Process.LOG_UID; 303 private static final int NFC_UID = Process.NFC_UID; 304 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 305 private static final int SHELL_UID = Process.SHELL_UID; 306 307 // Cap the size of permission trees that 3rd party apps can define 308 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 309 310 // Suffix used during package installation when copying/moving 311 // package apks to install directory. 312 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 313 314 static final int SCAN_NO_DEX = 1<<1; 315 static final int SCAN_FORCE_DEX = 1<<2; 316 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 317 static final int SCAN_NEW_INSTALL = 1<<4; 318 static final int SCAN_NO_PATHS = 1<<5; 319 static final int SCAN_UPDATE_TIME = 1<<6; 320 static final int SCAN_DEFER_DEX = 1<<7; 321 static final int SCAN_BOOTING = 1<<8; 322 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 323 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 324 static final int SCAN_REQUIRE_KNOWN = 1<<12; 325 static final int SCAN_MOVE = 1<<13; 326 static final int SCAN_INITIAL = 1<<14; 327 328 static final int REMOVE_CHATTY = 1<<16; 329 330 private static final int[] EMPTY_INT_ARRAY = new int[0]; 331 332 /** 333 * Timeout (in milliseconds) after which the watchdog should declare that 334 * our handler thread is wedged. The usual default for such things is one 335 * minute but we sometimes do very lengthy I/O operations on this thread, 336 * such as installing multi-gigabyte applications, so ours needs to be longer. 337 */ 338 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 339 340 /** 341 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 342 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 343 * settings entry if available, otherwise we use the hardcoded default. If it's been 344 * more than this long since the last fstrim, we force one during the boot sequence. 345 * 346 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 347 * one gets run at the next available charging+idle time. This final mandatory 348 * no-fstrim check kicks in only of the other scheduling criteria is never met. 349 */ 350 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 351 352 /** 353 * Whether verification is enabled by default. 354 */ 355 private static final boolean DEFAULT_VERIFY_ENABLE = true; 356 357 /** 358 * The default maximum time to wait for the verification agent to return in 359 * milliseconds. 360 */ 361 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 362 363 /** 364 * The default response for package verification timeout. 365 * 366 * This can be either PackageManager.VERIFICATION_ALLOW or 367 * PackageManager.VERIFICATION_REJECT. 368 */ 369 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 370 371 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 372 373 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 374 DEFAULT_CONTAINER_PACKAGE, 375 "com.android.defcontainer.DefaultContainerService"); 376 377 private static final String KILL_APP_REASON_GIDS_CHANGED = 378 "permission grant or revoke changed gids"; 379 380 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 381 "permissions revoked"; 382 383 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 384 385 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 386 387 /** Permission grant: not grant the permission. */ 388 private static final int GRANT_DENIED = 1; 389 390 /** Permission grant: grant the permission as an install permission. */ 391 private static final int GRANT_INSTALL = 2; 392 393 /** Permission grant: grant the permission as an install permission for a legacy app. */ 394 private static final int GRANT_INSTALL_LEGACY = 3; 395 396 /** Permission grant: grant the permission as a runtime one. */ 397 private static final int GRANT_RUNTIME = 4; 398 399 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 400 private static final int GRANT_UPGRADE = 5; 401 402 /** Canonical intent used to identify what counts as a "web browser" app */ 403 private static final Intent sBrowserIntent; 404 static { 405 sBrowserIntent = new Intent(); 406 sBrowserIntent.setAction(Intent.ACTION_VIEW); 407 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 408 sBrowserIntent.setData(Uri.parse("http:")); 409 } 410 411 final ServiceThread mHandlerThread; 412 413 final PackageHandler mHandler; 414 415 /** 416 * Messages for {@link #mHandler} that need to wait for system ready before 417 * being dispatched. 418 */ 419 private ArrayList<Message> mPostSystemReadyMessages; 420 421 final int mSdkVersion = Build.VERSION.SDK_INT; 422 423 final Context mContext; 424 final boolean mFactoryTest; 425 final boolean mOnlyCore; 426 final boolean mLazyDexOpt; 427 final long mDexOptLRUThresholdInMills; 428 final DisplayMetrics mMetrics; 429 final int mDefParseFlags; 430 final String[] mSeparateProcesses; 431 final boolean mIsUpgrade; 432 433 // This is where all application persistent data goes. 434 final File mAppDataDir; 435 436 // This is where all application persistent data goes for secondary users. 437 final File mUserAppDataDir; 438 439 /** The location for ASEC container files on internal storage. */ 440 final String mAsecInternalPath; 441 442 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 443 // LOCK HELD. Can be called with mInstallLock held. 444 @GuardedBy("mInstallLock") 445 final Installer mInstaller; 446 447 /** Directory where installed third-party apps stored */ 448 final File mAppInstallDir; 449 450 /** 451 * Directory to which applications installed internally have their 452 * 32 bit native libraries copied. 453 */ 454 private File mAppLib32InstallDir; 455 456 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 457 // apps. 458 final File mDrmAppPrivateInstallDir; 459 460 // ---------------------------------------------------------------- 461 462 // Lock for state used when installing and doing other long running 463 // operations. Methods that must be called with this lock held have 464 // the suffix "LI". 465 final Object mInstallLock = new Object(); 466 467 // ---------------------------------------------------------------- 468 469 // Keys are String (package name), values are Package. This also serves 470 // as the lock for the global state. Methods that must be called with 471 // this lock held have the prefix "LP". 472 @GuardedBy("mPackages") 473 final ArrayMap<String, PackageParser.Package> mPackages = 474 new ArrayMap<String, PackageParser.Package>(); 475 476 // Tracks available target package names -> overlay package paths. 477 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 478 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 479 480 /** 481 * Tracks new system packages [receiving in an OTA] that we expect to 482 * find updated user-installed versions. Keys are package name, values 483 * are package location. 484 */ 485 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 486 487 final Settings mSettings; 488 boolean mRestoredSettings; 489 490 // System configuration read by SystemConfig. 491 final int[] mGlobalGids; 492 final SparseArray<ArraySet<String>> mSystemPermissions; 493 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 494 495 // If mac_permissions.xml was found for seinfo labeling. 496 boolean mFoundPolicyFile; 497 498 // If a recursive restorecon of /data/data/<pkg> is needed. 499 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 500 501 public static final class SharedLibraryEntry { 502 public final String path; 503 public final String apk; 504 505 SharedLibraryEntry(String _path, String _apk) { 506 path = _path; 507 apk = _apk; 508 } 509 } 510 511 // Currently known shared libraries. 512 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 513 new ArrayMap<String, SharedLibraryEntry>(); 514 515 // All available activities, for your resolving pleasure. 516 final ActivityIntentResolver mActivities = 517 new ActivityIntentResolver(); 518 519 // All available receivers, for your resolving pleasure. 520 final ActivityIntentResolver mReceivers = 521 new ActivityIntentResolver(); 522 523 // All available services, for your resolving pleasure. 524 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 525 526 // All available providers, for your resolving pleasure. 527 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 528 529 // Mapping from provider base names (first directory in content URI codePath) 530 // to the provider information. 531 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 532 new ArrayMap<String, PackageParser.Provider>(); 533 534 // Mapping from instrumentation class names to info about them. 535 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 536 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 537 538 // Mapping from permission names to info about them. 539 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 540 new ArrayMap<String, PackageParser.PermissionGroup>(); 541 542 // Packages whose data we have transfered into another package, thus 543 // should no longer exist. 544 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 545 546 // Broadcast actions that are only available to the system. 547 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 548 549 /** List of packages waiting for verification. */ 550 final SparseArray<PackageVerificationState> mPendingVerification 551 = new SparseArray<PackageVerificationState>(); 552 553 /** Set of packages associated with each app op permission. */ 554 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 555 556 final PackageInstallerService mInstallerService; 557 558 private final PackageDexOptimizer mPackageDexOptimizer; 559 560 private AtomicInteger mNextMoveId = new AtomicInteger(); 561 private final MoveCallbacks mMoveCallbacks; 562 563 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 564 565 // Cache of users who need badging. 566 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 567 568 /** Token for keys in mPendingVerification. */ 569 private int mPendingVerificationToken = 0; 570 571 volatile boolean mSystemReady; 572 volatile boolean mSafeMode; 573 volatile boolean mHasSystemUidErrors; 574 575 ApplicationInfo mAndroidApplication; 576 final ActivityInfo mResolveActivity = new ActivityInfo(); 577 final ResolveInfo mResolveInfo = new ResolveInfo(); 578 ComponentName mResolveComponentName; 579 PackageParser.Package mPlatformPackage; 580 ComponentName mCustomResolverComponentName; 581 582 boolean mResolverReplaced = false; 583 584 private final ComponentName mIntentFilterVerifierComponent; 585 private int mIntentFilterVerificationToken = 0; 586 587 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 588 = new SparseArray<IntentFilterVerificationState>(); 589 590 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 591 new DefaultPermissionGrantPolicy(this); 592 593 private static class IFVerificationParams { 594 PackageParser.Package pkg; 595 boolean replacing; 596 int userId; 597 int verifierUid; 598 599 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 600 int _userId, int _verifierUid) { 601 pkg = _pkg; 602 replacing = _replacing; 603 userId = _userId; 604 replacing = _replacing; 605 verifierUid = _verifierUid; 606 } 607 } 608 609 private interface IntentFilterVerifier<T extends IntentFilter> { 610 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 611 T filter, String packageName); 612 void startVerifications(int userId); 613 void receiveVerificationResponse(int verificationId); 614 } 615 616 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 617 private Context mContext; 618 private ComponentName mIntentFilterVerifierComponent; 619 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 620 621 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 622 mContext = context; 623 mIntentFilterVerifierComponent = verifierComponent; 624 } 625 626 private String getDefaultScheme() { 627 return IntentFilter.SCHEME_HTTPS; 628 } 629 630 @Override 631 public void startVerifications(int userId) { 632 // Launch verifications requests 633 int count = mCurrentIntentFilterVerifications.size(); 634 for (int n=0; n<count; n++) { 635 int verificationId = mCurrentIntentFilterVerifications.get(n); 636 final IntentFilterVerificationState ivs = 637 mIntentFilterVerificationStates.get(verificationId); 638 639 String packageName = ivs.getPackageName(); 640 641 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 642 final int filterCount = filters.size(); 643 ArraySet<String> domainsSet = new ArraySet<>(); 644 for (int m=0; m<filterCount; m++) { 645 PackageParser.ActivityIntentInfo filter = filters.get(m); 646 domainsSet.addAll(filter.getHostsList()); 647 } 648 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 649 synchronized (mPackages) { 650 if (mSettings.createIntentFilterVerificationIfNeededLPw( 651 packageName, domainsList) != null) { 652 scheduleWriteSettingsLocked(); 653 } 654 } 655 sendVerificationRequest(userId, verificationId, ivs); 656 } 657 mCurrentIntentFilterVerifications.clear(); 658 } 659 660 private void sendVerificationRequest(int userId, int verificationId, 661 IntentFilterVerificationState ivs) { 662 663 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 664 verificationIntent.putExtra( 665 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 666 verificationId); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 669 getDefaultScheme()); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 672 ivs.getHostsString()); 673 verificationIntent.putExtra( 674 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 675 ivs.getPackageName()); 676 verificationIntent.setComponent(mIntentFilterVerifierComponent); 677 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 678 679 UserHandle user = new UserHandle(userId); 680 mContext.sendBroadcastAsUser(verificationIntent, user); 681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 682 "Sending IntentFilter verification broadcast"); 683 } 684 685 public void receiveVerificationResponse(int verificationId) { 686 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 687 688 final boolean verified = ivs.isVerified(); 689 690 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 691 final int count = filters.size(); 692 if (DEBUG_DOMAIN_VERIFICATION) { 693 Slog.i(TAG, "Received verification response " + verificationId 694 + " for " + count + " filters, verified=" + verified); 695 } 696 for (int n=0; n<count; n++) { 697 PackageParser.ActivityIntentInfo filter = filters.get(n); 698 filter.setVerified(verified); 699 700 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 701 + " verified with result:" + verified + " and hosts:" 702 + ivs.getHostsString()); 703 } 704 705 mIntentFilterVerificationStates.remove(verificationId); 706 707 final String packageName = ivs.getPackageName(); 708 IntentFilterVerificationInfo ivi = null; 709 710 synchronized (mPackages) { 711 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 712 } 713 if (ivi == null) { 714 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 715 + verificationId + " packageName:" + packageName); 716 return; 717 } 718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 719 "Updating IntentFilterVerificationInfo for package " + packageName 720 +" verificationId:" + verificationId); 721 722 synchronized (mPackages) { 723 if (verified) { 724 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 725 } else { 726 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 727 } 728 scheduleWriteSettingsLocked(); 729 730 final int userId = ivs.getUserId(); 731 if (userId != UserHandle.USER_ALL) { 732 final int userStatus = 733 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 734 735 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 736 boolean needUpdate = false; 737 738 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 739 // already been set by the User thru the Disambiguation dialog 740 switch (userStatus) { 741 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 742 if (verified) { 743 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 744 } else { 745 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 746 } 747 needUpdate = true; 748 break; 749 750 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 751 if (verified) { 752 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 753 needUpdate = true; 754 } 755 break; 756 757 default: 758 // Nothing to do 759 } 760 761 if (needUpdate) { 762 mSettings.updateIntentFilterVerificationStatusLPw( 763 packageName, updatedStatus, userId); 764 scheduleWritePackageRestrictionsLocked(userId); 765 } 766 } 767 } 768 } 769 770 @Override 771 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 772 ActivityIntentInfo filter, String packageName) { 773 if (!hasValidDomains(filter)) { 774 return false; 775 } 776 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 777 if (ivs == null) { 778 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 779 packageName); 780 } 781 if (DEBUG_DOMAIN_VERIFICATION) { 782 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 783 } 784 ivs.addFilter(filter); 785 return true; 786 } 787 788 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 789 int userId, int verificationId, String packageName) { 790 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 791 verifierUid, userId, packageName); 792 ivs.setPendingState(); 793 synchronized (mPackages) { 794 mIntentFilterVerificationStates.append(verificationId, ivs); 795 mCurrentIntentFilterVerifications.add(verificationId); 796 } 797 return ivs; 798 } 799 } 800 801 private static boolean hasValidDomains(ActivityIntentInfo filter) { 802 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 803 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 804 if (!hasHTTPorHTTPS) { 805 return false; 806 } 807 return true; 808 } 809 810 private IntentFilterVerifier mIntentFilterVerifier; 811 812 // Set of pending broadcasts for aggregating enable/disable of components. 813 static class PendingPackageBroadcasts { 814 // for each user id, a map of <package name -> components within that package> 815 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 816 817 public PendingPackageBroadcasts() { 818 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 819 } 820 821 public ArrayList<String> get(int userId, String packageName) { 822 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 823 return packages.get(packageName); 824 } 825 826 public void put(int userId, String packageName, ArrayList<String> components) { 827 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 828 packages.put(packageName, components); 829 } 830 831 public void remove(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 833 if (packages != null) { 834 packages.remove(packageName); 835 } 836 } 837 838 public void remove(int userId) { 839 mUidMap.remove(userId); 840 } 841 842 public int userIdCount() { 843 return mUidMap.size(); 844 } 845 846 public int userIdAt(int n) { 847 return mUidMap.keyAt(n); 848 } 849 850 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 851 return mUidMap.get(userId); 852 } 853 854 public int size() { 855 // total number of pending broadcast entries across all userIds 856 int num = 0; 857 for (int i = 0; i< mUidMap.size(); i++) { 858 num += mUidMap.valueAt(i).size(); 859 } 860 return num; 861 } 862 863 public void clear() { 864 mUidMap.clear(); 865 } 866 867 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 868 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 869 if (map == null) { 870 map = new ArrayMap<String, ArrayList<String>>(); 871 mUidMap.put(userId, map); 872 } 873 return map; 874 } 875 } 876 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 877 878 // Service Connection to remote media container service to copy 879 // package uri's from external media onto secure containers 880 // or internal storage. 881 private IMediaContainerService mContainerService = null; 882 883 static final int SEND_PENDING_BROADCAST = 1; 884 static final int MCS_BOUND = 3; 885 static final int END_COPY = 4; 886 static final int INIT_COPY = 5; 887 static final int MCS_UNBIND = 6; 888 static final int START_CLEANING_PACKAGE = 7; 889 static final int FIND_INSTALL_LOC = 8; 890 static final int POST_INSTALL = 9; 891 static final int MCS_RECONNECT = 10; 892 static final int MCS_GIVE_UP = 11; 893 static final int UPDATED_MEDIA_STATUS = 12; 894 static final int WRITE_SETTINGS = 13; 895 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 896 static final int PACKAGE_VERIFIED = 15; 897 static final int CHECK_PENDING_VERIFICATION = 16; 898 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 899 static final int INTENT_FILTER_VERIFIED = 18; 900 901 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 902 903 // Delay time in millisecs 904 static final int BROADCAST_DELAY = 10 * 1000; 905 906 static UserManagerService sUserManager; 907 908 // Stores a list of users whose package restrictions file needs to be updated 909 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 910 911 final private DefaultContainerConnection mDefContainerConn = 912 new DefaultContainerConnection(); 913 class DefaultContainerConnection implements ServiceConnection { 914 public void onServiceConnected(ComponentName name, IBinder service) { 915 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 916 IMediaContainerService imcs = 917 IMediaContainerService.Stub.asInterface(service); 918 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 919 } 920 921 public void onServiceDisconnected(ComponentName name) { 922 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 923 } 924 } 925 926 // Recordkeeping of restore-after-install operations that are currently in flight 927 // between the Package Manager and the Backup Manager 928 class PostInstallData { 929 public InstallArgs args; 930 public PackageInstalledInfo res; 931 932 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 933 args = _a; 934 res = _r; 935 } 936 } 937 938 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 939 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 940 941 // XML tags for backup/restore of various bits of state 942 private static final String TAG_PREFERRED_BACKUP = "pa"; 943 private static final String TAG_DEFAULT_APPS = "da"; 944 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 945 946 final String mRequiredVerifierPackage; 947 final String mRequiredInstallerPackage; 948 949 private final PackageUsage mPackageUsage = new PackageUsage(); 950 951 private class PackageUsage { 952 private static final int WRITE_INTERVAL 953 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 954 955 private final Object mFileLock = new Object(); 956 private final AtomicLong mLastWritten = new AtomicLong(0); 957 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 958 959 private boolean mIsHistoricalPackageUsageAvailable = true; 960 961 boolean isHistoricalPackageUsageAvailable() { 962 return mIsHistoricalPackageUsageAvailable; 963 } 964 965 void write(boolean force) { 966 if (force) { 967 writeInternal(); 968 return; 969 } 970 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 971 && !DEBUG_DEXOPT) { 972 return; 973 } 974 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 975 new Thread("PackageUsage_DiskWriter") { 976 @Override 977 public void run() { 978 try { 979 writeInternal(); 980 } finally { 981 mBackgroundWriteRunning.set(false); 982 } 983 } 984 }.start(); 985 } 986 } 987 988 private void writeInternal() { 989 synchronized (mPackages) { 990 synchronized (mFileLock) { 991 AtomicFile file = getFile(); 992 FileOutputStream f = null; 993 try { 994 f = file.startWrite(); 995 BufferedOutputStream out = new BufferedOutputStream(f); 996 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 997 StringBuilder sb = new StringBuilder(); 998 for (PackageParser.Package pkg : mPackages.values()) { 999 if (pkg.mLastPackageUsageTimeInMills == 0) { 1000 continue; 1001 } 1002 sb.setLength(0); 1003 sb.append(pkg.packageName); 1004 sb.append(' '); 1005 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1006 sb.append('\n'); 1007 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1008 } 1009 out.flush(); 1010 file.finishWrite(f); 1011 } catch (IOException e) { 1012 if (f != null) { 1013 file.failWrite(f); 1014 } 1015 Log.e(TAG, "Failed to write package usage times", e); 1016 } 1017 } 1018 } 1019 mLastWritten.set(SystemClock.elapsedRealtime()); 1020 } 1021 1022 void readLP() { 1023 synchronized (mFileLock) { 1024 AtomicFile file = getFile(); 1025 BufferedInputStream in = null; 1026 try { 1027 in = new BufferedInputStream(file.openRead()); 1028 StringBuffer sb = new StringBuffer(); 1029 while (true) { 1030 String packageName = readToken(in, sb, ' '); 1031 if (packageName == null) { 1032 break; 1033 } 1034 String timeInMillisString = readToken(in, sb, '\n'); 1035 if (timeInMillisString == null) { 1036 throw new IOException("Failed to find last usage time for package " 1037 + packageName); 1038 } 1039 PackageParser.Package pkg = mPackages.get(packageName); 1040 if (pkg == null) { 1041 continue; 1042 } 1043 long timeInMillis; 1044 try { 1045 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1046 } catch (NumberFormatException e) { 1047 throw new IOException("Failed to parse " + timeInMillisString 1048 + " as a long.", e); 1049 } 1050 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1051 } 1052 } catch (FileNotFoundException expected) { 1053 mIsHistoricalPackageUsageAvailable = false; 1054 } catch (IOException e) { 1055 Log.w(TAG, "Failed to read package usage times", e); 1056 } finally { 1057 IoUtils.closeQuietly(in); 1058 } 1059 } 1060 mLastWritten.set(SystemClock.elapsedRealtime()); 1061 } 1062 1063 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1064 throws IOException { 1065 sb.setLength(0); 1066 while (true) { 1067 int ch = in.read(); 1068 if (ch == -1) { 1069 if (sb.length() == 0) { 1070 return null; 1071 } 1072 throw new IOException("Unexpected EOF"); 1073 } 1074 if (ch == endOfToken) { 1075 return sb.toString(); 1076 } 1077 sb.append((char)ch); 1078 } 1079 } 1080 1081 private AtomicFile getFile() { 1082 File dataDir = Environment.getDataDirectory(); 1083 File systemDir = new File(dataDir, "system"); 1084 File fname = new File(systemDir, "package-usage.list"); 1085 return new AtomicFile(fname); 1086 } 1087 } 1088 1089 class PackageHandler extends Handler { 1090 private boolean mBound = false; 1091 final ArrayList<HandlerParams> mPendingInstalls = 1092 new ArrayList<HandlerParams>(); 1093 1094 private boolean connectToService() { 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1096 " DefaultContainerService"); 1097 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1099 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1100 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1102 mBound = true; 1103 return true; 1104 } 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 return false; 1107 } 1108 1109 private void disconnectService() { 1110 mContainerService = null; 1111 mBound = false; 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 mContext.unbindService(mDefContainerConn); 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 } 1116 1117 PackageHandler(Looper looper) { 1118 super(looper); 1119 } 1120 1121 public void handleMessage(Message msg) { 1122 try { 1123 doHandleMessage(msg); 1124 } finally { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 } 1128 1129 void doHandleMessage(Message msg) { 1130 switch (msg.what) { 1131 case INIT_COPY: { 1132 HandlerParams params = (HandlerParams) msg.obj; 1133 int idx = mPendingInstalls.size(); 1134 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1135 // If a bind was already initiated we dont really 1136 // need to do anything. The pending install 1137 // will be processed later on. 1138 if (!mBound) { 1139 // If this is the only one pending we might 1140 // have to bind to the service again. 1141 if (!connectToService()) { 1142 Slog.e(TAG, "Failed to bind to media container service"); 1143 params.serviceError(); 1144 return; 1145 } else { 1146 // Once we bind to the service, the first 1147 // pending request will be processed. 1148 mPendingInstalls.add(idx, params); 1149 } 1150 } else { 1151 mPendingInstalls.add(idx, params); 1152 // Already bound to the service. Just make 1153 // sure we trigger off processing the first request. 1154 if (idx == 0) { 1155 mHandler.sendEmptyMessage(MCS_BOUND); 1156 } 1157 } 1158 break; 1159 } 1160 case MCS_BOUND: { 1161 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1162 if (msg.obj != null) { 1163 mContainerService = (IMediaContainerService) msg.obj; 1164 } 1165 if (mContainerService == null) { 1166 if (!mBound) { 1167 // Something seriously wrong since we are not bound and we are not 1168 // waiting for connection. Bail out. 1169 Slog.e(TAG, "Cannot bind to media container service"); 1170 for (HandlerParams params : mPendingInstalls) { 1171 // Indicate service bind error 1172 params.serviceError(); 1173 } 1174 mPendingInstalls.clear(); 1175 } else { 1176 Slog.w(TAG, "Waiting to connect to media container service"); 1177 } 1178 } else if (mPendingInstalls.size() > 0) { 1179 HandlerParams params = mPendingInstalls.get(0); 1180 if (params != null) { 1181 if (params.startCopy()) { 1182 // We are done... look for more work or to 1183 // go idle. 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, 1185 "Checking for more work or unbind..."); 1186 // Delete pending install 1187 if (mPendingInstalls.size() > 0) { 1188 mPendingInstalls.remove(0); 1189 } 1190 if (mPendingInstalls.size() == 0) { 1191 if (mBound) { 1192 if (DEBUG_SD_INSTALL) Log.i(TAG, 1193 "Posting delayed MCS_UNBIND"); 1194 removeMessages(MCS_UNBIND); 1195 Message ubmsg = obtainMessage(MCS_UNBIND); 1196 // Unbind after a little delay, to avoid 1197 // continual thrashing. 1198 sendMessageDelayed(ubmsg, 10000); 1199 } 1200 } else { 1201 // There are more pending requests in queue. 1202 // Just post MCS_BOUND message to trigger processing 1203 // of next pending install. 1204 if (DEBUG_SD_INSTALL) Log.i(TAG, 1205 "Posting MCS_BOUND for next work"); 1206 mHandler.sendEmptyMessage(MCS_BOUND); 1207 } 1208 } 1209 } 1210 } else { 1211 // Should never happen ideally. 1212 Slog.w(TAG, "Empty queue"); 1213 } 1214 break; 1215 } 1216 case MCS_RECONNECT: { 1217 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1218 if (mPendingInstalls.size() > 0) { 1219 if (mBound) { 1220 disconnectService(); 1221 } 1222 if (!connectToService()) { 1223 Slog.e(TAG, "Failed to bind to media container service"); 1224 for (HandlerParams params : mPendingInstalls) { 1225 // Indicate service bind error 1226 params.serviceError(); 1227 } 1228 mPendingInstalls.clear(); 1229 } 1230 } 1231 break; 1232 } 1233 case MCS_UNBIND: { 1234 // If there is no actual work left, then time to unbind. 1235 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1236 1237 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1238 if (mBound) { 1239 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1240 1241 disconnectService(); 1242 } 1243 } else if (mPendingInstalls.size() > 0) { 1244 // There are more pending requests in queue. 1245 // Just post MCS_BOUND message to trigger processing 1246 // of next pending install. 1247 mHandler.sendEmptyMessage(MCS_BOUND); 1248 } 1249 1250 break; 1251 } 1252 case MCS_GIVE_UP: { 1253 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1254 mPendingInstalls.remove(0); 1255 break; 1256 } 1257 case SEND_PENDING_BROADCAST: { 1258 String packages[]; 1259 ArrayList<String> components[]; 1260 int size = 0; 1261 int uids[]; 1262 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1263 synchronized (mPackages) { 1264 if (mPendingBroadcasts == null) { 1265 return; 1266 } 1267 size = mPendingBroadcasts.size(); 1268 if (size <= 0) { 1269 // Nothing to be done. Just return 1270 return; 1271 } 1272 packages = new String[size]; 1273 components = new ArrayList[size]; 1274 uids = new int[size]; 1275 int i = 0; // filling out the above arrays 1276 1277 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1278 int packageUserId = mPendingBroadcasts.userIdAt(n); 1279 Iterator<Map.Entry<String, ArrayList<String>>> it 1280 = mPendingBroadcasts.packagesForUserId(packageUserId) 1281 .entrySet().iterator(); 1282 while (it.hasNext() && i < size) { 1283 Map.Entry<String, ArrayList<String>> ent = it.next(); 1284 packages[i] = ent.getKey(); 1285 components[i] = ent.getValue(); 1286 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1287 uids[i] = (ps != null) 1288 ? UserHandle.getUid(packageUserId, ps.appId) 1289 : -1; 1290 i++; 1291 } 1292 } 1293 size = i; 1294 mPendingBroadcasts.clear(); 1295 } 1296 // Send broadcasts 1297 for (int i = 0; i < size; i++) { 1298 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1299 } 1300 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1301 break; 1302 } 1303 case START_CLEANING_PACKAGE: { 1304 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1305 final String packageName = (String)msg.obj; 1306 final int userId = msg.arg1; 1307 final boolean andCode = msg.arg2 != 0; 1308 synchronized (mPackages) { 1309 if (userId == UserHandle.USER_ALL) { 1310 int[] users = sUserManager.getUserIds(); 1311 for (int user : users) { 1312 mSettings.addPackageToCleanLPw( 1313 new PackageCleanItem(user, packageName, andCode)); 1314 } 1315 } else { 1316 mSettings.addPackageToCleanLPw( 1317 new PackageCleanItem(userId, packageName, andCode)); 1318 } 1319 } 1320 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1321 startCleaningPackages(); 1322 } break; 1323 case POST_INSTALL: { 1324 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1325 PostInstallData data = mRunningInstalls.get(msg.arg1); 1326 mRunningInstalls.delete(msg.arg1); 1327 boolean deleteOld = false; 1328 1329 if (data != null) { 1330 InstallArgs args = data.args; 1331 PackageInstalledInfo res = data.res; 1332 1333 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1334 final String packageName = res.pkg.applicationInfo.packageName; 1335 res.removedInfo.sendBroadcast(false, true, false); 1336 Bundle extras = new Bundle(1); 1337 extras.putInt(Intent.EXTRA_UID, res.uid); 1338 1339 // Now that we successfully installed the package, grant runtime 1340 // permissions if requested before broadcasting the install. 1341 if ((args.installFlags 1342 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1343 grantRequestedRuntimePermissions(res.pkg, 1344 args.user.getIdentifier()); 1345 } 1346 1347 // Determine the set of users who are adding this 1348 // package for the first time vs. those who are seeing 1349 // an update. 1350 int[] firstUsers; 1351 int[] updateUsers = new int[0]; 1352 if (res.origUsers == null || res.origUsers.length == 0) { 1353 firstUsers = res.newUsers; 1354 } else { 1355 firstUsers = new int[0]; 1356 for (int i=0; i<res.newUsers.length; i++) { 1357 int user = res.newUsers[i]; 1358 boolean isNew = true; 1359 for (int j=0; j<res.origUsers.length; j++) { 1360 if (res.origUsers[j] == user) { 1361 isNew = false; 1362 break; 1363 } 1364 } 1365 if (isNew) { 1366 int[] newFirst = new int[firstUsers.length+1]; 1367 System.arraycopy(firstUsers, 0, newFirst, 0, 1368 firstUsers.length); 1369 newFirst[firstUsers.length] = user; 1370 firstUsers = newFirst; 1371 } else { 1372 int[] newUpdate = new int[updateUsers.length+1]; 1373 System.arraycopy(updateUsers, 0, newUpdate, 0, 1374 updateUsers.length); 1375 newUpdate[updateUsers.length] = user; 1376 updateUsers = newUpdate; 1377 } 1378 } 1379 } 1380 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1381 packageName, extras, null, null, firstUsers); 1382 final boolean update = res.removedInfo.removedPackage != null; 1383 if (update) { 1384 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1385 } 1386 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1387 packageName, extras, null, null, updateUsers); 1388 if (update) { 1389 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1390 packageName, extras, null, null, updateUsers); 1391 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1392 null, null, packageName, null, updateUsers); 1393 1394 // treat asec-hosted packages like removable media on upgrade 1395 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1396 if (DEBUG_INSTALL) { 1397 Slog.i(TAG, "upgrading pkg " + res.pkg 1398 + " is ASEC-hosted -> AVAILABLE"); 1399 } 1400 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1401 ArrayList<String> pkgList = new ArrayList<String>(1); 1402 pkgList.add(packageName); 1403 sendResourcesChangedBroadcast(true, true, 1404 pkgList,uidArray, null); 1405 } 1406 } 1407 if (res.removedInfo.args != null) { 1408 // Remove the replaced package's older resources safely now 1409 deleteOld = true; 1410 } 1411 1412 // If this app is a browser and it's newly-installed for some 1413 // users, clear any default-browser state in those users 1414 if (firstUsers.length > 0) { 1415 // the app's nature doesn't depend on the user, so we can just 1416 // check its browser nature in any user and generalize. 1417 if (packageIsBrowser(packageName, firstUsers[0])) { 1418 synchronized (mPackages) { 1419 for (int userId : firstUsers) { 1420 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1421 } 1422 } 1423 } 1424 } 1425 // Log current value of "unknown sources" setting 1426 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1427 getUnknownSourcesSettings()); 1428 } 1429 // Force a gc to clear up things 1430 Runtime.getRuntime().gc(); 1431 // We delete after a gc for applications on sdcard. 1432 if (deleteOld) { 1433 synchronized (mInstallLock) { 1434 res.removedInfo.args.doPostDeleteLI(true); 1435 } 1436 } 1437 if (args.observer != null) { 1438 try { 1439 Bundle extras = extrasForInstallResult(res); 1440 args.observer.onPackageInstalled(res.name, res.returnCode, 1441 res.returnMsg, extras); 1442 } catch (RemoteException e) { 1443 Slog.i(TAG, "Observer no longer exists."); 1444 } 1445 } 1446 } else { 1447 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1448 } 1449 } break; 1450 case UPDATED_MEDIA_STATUS: { 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1452 boolean reportStatus = msg.arg1 == 1; 1453 boolean doGc = msg.arg2 == 1; 1454 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1455 if (doGc) { 1456 // Force a gc to clear up stale containers. 1457 Runtime.getRuntime().gc(); 1458 } 1459 if (msg.obj != null) { 1460 @SuppressWarnings("unchecked") 1461 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1463 // Unload containers 1464 unloadAllContainers(args); 1465 } 1466 if (reportStatus) { 1467 try { 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1469 PackageHelper.getMountService().finishMediaUpdate(); 1470 } catch (RemoteException e) { 1471 Log.e(TAG, "MountService not running?"); 1472 } 1473 } 1474 } break; 1475 case WRITE_SETTINGS: { 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1477 synchronized (mPackages) { 1478 removeMessages(WRITE_SETTINGS); 1479 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1480 mSettings.writeLPr(); 1481 mDirtyUsers.clear(); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 } break; 1485 case WRITE_PACKAGE_RESTRICTIONS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1489 for (int userId : mDirtyUsers) { 1490 mSettings.writePackageRestrictionsLPr(userId); 1491 } 1492 mDirtyUsers.clear(); 1493 } 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1495 } break; 1496 case CHECK_PENDING_VERIFICATION: { 1497 final int verificationId = msg.arg1; 1498 final PackageVerificationState state = mPendingVerification.get(verificationId); 1499 1500 if ((state != null) && !state.timeoutExtended()) { 1501 final InstallArgs args = state.getInstallArgs(); 1502 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1503 1504 Slog.i(TAG, "Verification timed out for " + originUri); 1505 mPendingVerification.remove(verificationId); 1506 1507 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1508 1509 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1510 Slog.i(TAG, "Continuing with installation of " + originUri); 1511 state.setVerifierResponse(Binder.getCallingUid(), 1512 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1513 broadcastPackageVerified(verificationId, originUri, 1514 PackageManager.VERIFICATION_ALLOW, 1515 state.getInstallArgs().getUser()); 1516 try { 1517 ret = args.copyApk(mContainerService, true); 1518 } catch (RemoteException e) { 1519 Slog.e(TAG, "Could not contact the ContainerService"); 1520 } 1521 } else { 1522 broadcastPackageVerified(verificationId, originUri, 1523 PackageManager.VERIFICATION_REJECT, 1524 state.getInstallArgs().getUser()); 1525 } 1526 1527 processPendingInstall(args, ret); 1528 mHandler.sendEmptyMessage(MCS_UNBIND); 1529 } 1530 break; 1531 } 1532 case PACKAGE_VERIFIED: { 1533 final int verificationId = msg.arg1; 1534 1535 final PackageVerificationState state = mPendingVerification.get(verificationId); 1536 if (state == null) { 1537 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1538 break; 1539 } 1540 1541 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1542 1543 state.setVerifierResponse(response.callerUid, response.code); 1544 1545 if (state.isVerificationComplete()) { 1546 mPendingVerification.remove(verificationId); 1547 1548 final InstallArgs args = state.getInstallArgs(); 1549 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1550 1551 int ret; 1552 if (state.isInstallAllowed()) { 1553 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1554 broadcastPackageVerified(verificationId, originUri, 1555 response.code, state.getInstallArgs().getUser()); 1556 try { 1557 ret = args.copyApk(mContainerService, true); 1558 } catch (RemoteException e) { 1559 Slog.e(TAG, "Could not contact the ContainerService"); 1560 } 1561 } else { 1562 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1563 } 1564 1565 processPendingInstall(args, ret); 1566 1567 mHandler.sendEmptyMessage(MCS_UNBIND); 1568 } 1569 1570 break; 1571 } 1572 case START_INTENT_FILTER_VERIFICATIONS: { 1573 IFVerificationParams params = (IFVerificationParams) msg.obj; 1574 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1575 params.replacing, params.pkg); 1576 break; 1577 } 1578 case INTENT_FILTER_VERIFIED: { 1579 final int verificationId = msg.arg1; 1580 1581 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1582 verificationId); 1583 if (state == null) { 1584 Slog.w(TAG, "Invalid IntentFilter verification token " 1585 + verificationId + " received"); 1586 break; 1587 } 1588 1589 final int userId = state.getUserId(); 1590 1591 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1592 "Processing IntentFilter verification with token:" 1593 + verificationId + " and userId:" + userId); 1594 1595 final IntentFilterVerificationResponse response = 1596 (IntentFilterVerificationResponse) msg.obj; 1597 1598 state.setVerifierResponse(response.callerUid, response.code); 1599 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1601 "IntentFilter verification with token:" + verificationId 1602 + " and userId:" + userId 1603 + " is settings verifier response with response code:" 1604 + response.code); 1605 1606 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1607 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1608 + response.getFailedDomainsString()); 1609 } 1610 1611 if (state.isVerificationComplete()) { 1612 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1613 } else { 1614 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1615 "IntentFilter verification with token:" + verificationId 1616 + " was not said to be complete"); 1617 } 1618 1619 break; 1620 } 1621 } 1622 } 1623 } 1624 1625 private StorageEventListener mStorageListener = new StorageEventListener() { 1626 @Override 1627 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1628 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1629 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1630 final String volumeUuid = vol.getFsUuid(); 1631 1632 // Clean up any users or apps that were removed or recreated 1633 // while this volume was missing 1634 reconcileUsers(volumeUuid); 1635 reconcileApps(volumeUuid); 1636 1637 // Clean up any install sessions that expired or were 1638 // cancelled while this volume was missing 1639 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1640 1641 loadPrivatePackages(vol); 1642 1643 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1644 unloadPrivatePackages(vol); 1645 } 1646 } 1647 1648 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1649 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1650 updateExternalMediaStatus(true, false); 1651 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1652 updateExternalMediaStatus(false, false); 1653 } 1654 } 1655 } 1656 1657 @Override 1658 public void onVolumeForgotten(String fsUuid) { 1659 // Remove any apps installed on the forgotten volume 1660 synchronized (mPackages) { 1661 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1662 for (PackageSetting ps : packages) { 1663 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1664 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1665 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1666 } 1667 1668 mSettings.writeLPr(); 1669 } 1670 } 1671 }; 1672 1673 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1674 if (userId >= UserHandle.USER_OWNER) { 1675 grantRequestedRuntimePermissionsForUser(pkg, userId); 1676 } else if (userId == UserHandle.USER_ALL) { 1677 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1678 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1679 } 1680 } 1681 1682 // We could have touched GID membership, so flush out packages.list 1683 synchronized (mPackages) { 1684 mSettings.writePackageListLPr(); 1685 } 1686 } 1687 1688 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1689 SettingBase sb = (SettingBase) pkg.mExtras; 1690 if (sb == null) { 1691 return; 1692 } 1693 1694 PermissionsState permissionsState = sb.getPermissionsState(); 1695 1696 for (String permission : pkg.requestedPermissions) { 1697 BasePermission bp = mSettings.mPermissions.get(permission); 1698 if (bp != null && bp.isRuntime()) { 1699 permissionsState.grantRuntimePermission(bp, userId); 1700 } 1701 } 1702 } 1703 1704 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1705 Bundle extras = null; 1706 switch (res.returnCode) { 1707 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1708 extras = new Bundle(); 1709 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1710 res.origPermission); 1711 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1712 res.origPackage); 1713 break; 1714 } 1715 case PackageManager.INSTALL_SUCCEEDED: { 1716 extras = new Bundle(); 1717 extras.putBoolean(Intent.EXTRA_REPLACING, 1718 res.removedInfo != null && res.removedInfo.removedPackage != null); 1719 break; 1720 } 1721 } 1722 return extras; 1723 } 1724 1725 void scheduleWriteSettingsLocked() { 1726 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1727 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1728 } 1729 } 1730 1731 void scheduleWritePackageRestrictionsLocked(int userId) { 1732 if (!sUserManager.exists(userId)) return; 1733 mDirtyUsers.add(userId); 1734 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1735 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1736 } 1737 } 1738 1739 public static PackageManagerService main(Context context, Installer installer, 1740 boolean factoryTest, boolean onlyCore) { 1741 PackageManagerService m = new PackageManagerService(context, installer, 1742 factoryTest, onlyCore); 1743 ServiceManager.addService("package", m); 1744 return m; 1745 } 1746 1747 static String[] splitString(String str, char sep) { 1748 int count = 1; 1749 int i = 0; 1750 while ((i=str.indexOf(sep, i)) >= 0) { 1751 count++; 1752 i++; 1753 } 1754 1755 String[] res = new String[count]; 1756 i=0; 1757 count = 0; 1758 int lastI=0; 1759 while ((i=str.indexOf(sep, i)) >= 0) { 1760 res[count] = str.substring(lastI, i); 1761 count++; 1762 i++; 1763 lastI = i; 1764 } 1765 res[count] = str.substring(lastI, str.length()); 1766 return res; 1767 } 1768 1769 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1770 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1771 Context.DISPLAY_SERVICE); 1772 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1773 } 1774 1775 public PackageManagerService(Context context, Installer installer, 1776 boolean factoryTest, boolean onlyCore) { 1777 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1778 SystemClock.uptimeMillis()); 1779 1780 if (mSdkVersion <= 0) { 1781 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1782 } 1783 1784 mContext = context; 1785 mFactoryTest = factoryTest; 1786 mOnlyCore = onlyCore; 1787 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1788 mMetrics = new DisplayMetrics(); 1789 mSettings = new Settings(mPackages); 1790 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1791 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1792 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1793 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1794 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1795 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1796 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1797 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1798 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1799 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1800 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1801 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1802 1803 // TODO: add a property to control this? 1804 long dexOptLRUThresholdInMinutes; 1805 if (mLazyDexOpt) { 1806 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1807 } else { 1808 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1809 } 1810 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1811 1812 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1813 if (separateProcesses != null && separateProcesses.length() > 0) { 1814 if ("*".equals(separateProcesses)) { 1815 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1816 mSeparateProcesses = null; 1817 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1818 } else { 1819 mDefParseFlags = 0; 1820 mSeparateProcesses = separateProcesses.split(","); 1821 Slog.w(TAG, "Running with debug.separate_processes: " 1822 + separateProcesses); 1823 } 1824 } else { 1825 mDefParseFlags = 0; 1826 mSeparateProcesses = null; 1827 } 1828 1829 mInstaller = installer; 1830 mPackageDexOptimizer = new PackageDexOptimizer(this); 1831 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1832 1833 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1834 FgThread.get().getLooper()); 1835 1836 getDefaultDisplayMetrics(context, mMetrics); 1837 1838 SystemConfig systemConfig = SystemConfig.getInstance(); 1839 mGlobalGids = systemConfig.getGlobalGids(); 1840 mSystemPermissions = systemConfig.getSystemPermissions(); 1841 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1842 1843 synchronized (mInstallLock) { 1844 // writer 1845 synchronized (mPackages) { 1846 mHandlerThread = new ServiceThread(TAG, 1847 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1848 mHandlerThread.start(); 1849 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1850 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1851 1852 File dataDir = Environment.getDataDirectory(); 1853 mAppDataDir = new File(dataDir, "data"); 1854 mAppInstallDir = new File(dataDir, "app"); 1855 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1856 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1857 mUserAppDataDir = new File(dataDir, "user"); 1858 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1859 1860 sUserManager = new UserManagerService(context, this, 1861 mInstallLock, mPackages); 1862 1863 // Propagate permission configuration in to package manager. 1864 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1865 = systemConfig.getPermissions(); 1866 for (int i=0; i<permConfig.size(); i++) { 1867 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1868 BasePermission bp = mSettings.mPermissions.get(perm.name); 1869 if (bp == null) { 1870 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1871 mSettings.mPermissions.put(perm.name, bp); 1872 } 1873 if (perm.gids != null) { 1874 bp.setGids(perm.gids, perm.perUser); 1875 } 1876 } 1877 1878 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1879 for (int i=0; i<libConfig.size(); i++) { 1880 mSharedLibraries.put(libConfig.keyAt(i), 1881 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1882 } 1883 1884 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1885 1886 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1887 mSdkVersion, mOnlyCore); 1888 1889 String customResolverActivity = Resources.getSystem().getString( 1890 R.string.config_customResolverActivity); 1891 if (TextUtils.isEmpty(customResolverActivity)) { 1892 customResolverActivity = null; 1893 } else { 1894 mCustomResolverComponentName = ComponentName.unflattenFromString( 1895 customResolverActivity); 1896 } 1897 1898 long startTime = SystemClock.uptimeMillis(); 1899 1900 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1901 startTime); 1902 1903 // Set flag to monitor and not change apk file paths when 1904 // scanning install directories. 1905 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1906 1907 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1908 1909 /** 1910 * Add everything in the in the boot class path to the 1911 * list of process files because dexopt will have been run 1912 * if necessary during zygote startup. 1913 */ 1914 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1915 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1916 1917 if (bootClassPath != null) { 1918 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1919 for (String element : bootClassPathElements) { 1920 alreadyDexOpted.add(element); 1921 } 1922 } else { 1923 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1924 } 1925 1926 if (systemServerClassPath != null) { 1927 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1928 for (String element : systemServerClassPathElements) { 1929 alreadyDexOpted.add(element); 1930 } 1931 } else { 1932 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1933 } 1934 1935 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1936 final String[] dexCodeInstructionSets = 1937 getDexCodeInstructionSets( 1938 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1939 1940 /** 1941 * Ensure all external libraries have had dexopt run on them. 1942 */ 1943 if (mSharedLibraries.size() > 0) { 1944 // NOTE: For now, we're compiling these system "shared libraries" 1945 // (and framework jars) into all available architectures. It's possible 1946 // to compile them only when we come across an app that uses them (there's 1947 // already logic for that in scanPackageLI) but that adds some complexity. 1948 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1949 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1950 final String lib = libEntry.path; 1951 if (lib == null) { 1952 continue; 1953 } 1954 1955 try { 1956 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1957 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1958 alreadyDexOpted.add(lib); 1959 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1960 } 1961 } catch (FileNotFoundException e) { 1962 Slog.w(TAG, "Library not found: " + lib); 1963 } catch (IOException e) { 1964 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1965 + e.getMessage()); 1966 } 1967 } 1968 } 1969 } 1970 1971 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1972 1973 // Gross hack for now: we know this file doesn't contain any 1974 // code, so don't dexopt it to avoid the resulting log spew. 1975 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1976 1977 // Gross hack for now: we know this file is only part of 1978 // the boot class path for art, so don't dexopt it to 1979 // avoid the resulting log spew. 1980 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1981 1982 /** 1983 * There are a number of commands implemented in Java, which 1984 * we currently need to do the dexopt on so that they can be 1985 * run from a non-root shell. 1986 */ 1987 String[] frameworkFiles = frameworkDir.list(); 1988 if (frameworkFiles != null) { 1989 // TODO: We could compile these only for the most preferred ABI. We should 1990 // first double check that the dex files for these commands are not referenced 1991 // by other system apps. 1992 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1993 for (int i=0; i<frameworkFiles.length; i++) { 1994 File libPath = new File(frameworkDir, frameworkFiles[i]); 1995 String path = libPath.getPath(); 1996 // Skip the file if we already did it. 1997 if (alreadyDexOpted.contains(path)) { 1998 continue; 1999 } 2000 // Skip the file if it is not a type we want to dexopt. 2001 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2002 continue; 2003 } 2004 try { 2005 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2006 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2007 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2008 } 2009 } catch (FileNotFoundException e) { 2010 Slog.w(TAG, "Jar not found: " + path); 2011 } catch (IOException e) { 2012 Slog.w(TAG, "Exception reading jar: " + path, e); 2013 } 2014 } 2015 } 2016 } 2017 2018 // Collect vendor overlay packages. 2019 // (Do this before scanning any apps.) 2020 // For security and version matching reason, only consider 2021 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2022 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2023 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2024 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2025 2026 // Find base frameworks (resource packages without code). 2027 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2028 | PackageParser.PARSE_IS_SYSTEM_DIR 2029 | PackageParser.PARSE_IS_PRIVILEGED, 2030 scanFlags | SCAN_NO_DEX, 0); 2031 2032 // Collected privileged system packages. 2033 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2034 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2035 | PackageParser.PARSE_IS_SYSTEM_DIR 2036 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2037 2038 // Collect ordinary system packages. 2039 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2040 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2041 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2042 2043 // Collect all vendor packages. 2044 File vendorAppDir = new File("/vendor/app"); 2045 try { 2046 vendorAppDir = vendorAppDir.getCanonicalFile(); 2047 } catch (IOException e) { 2048 // failed to look up canonical path, continue with original one 2049 } 2050 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2051 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2052 2053 // Collect all OEM packages. 2054 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2055 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2056 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2057 2058 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2059 mInstaller.moveFiles(); 2060 2061 // Prune any system packages that no longer exist. 2062 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2063 if (!mOnlyCore) { 2064 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2065 while (psit.hasNext()) { 2066 PackageSetting ps = psit.next(); 2067 2068 /* 2069 * If this is not a system app, it can't be a 2070 * disable system app. 2071 */ 2072 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2073 continue; 2074 } 2075 2076 /* 2077 * If the package is scanned, it's not erased. 2078 */ 2079 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2080 if (scannedPkg != null) { 2081 /* 2082 * If the system app is both scanned and in the 2083 * disabled packages list, then it must have been 2084 * added via OTA. Remove it from the currently 2085 * scanned package so the previously user-installed 2086 * application can be scanned. 2087 */ 2088 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2089 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2090 + ps.name + "; removing system app. Last known codePath=" 2091 + ps.codePathString + ", installStatus=" + ps.installStatus 2092 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2093 + scannedPkg.mVersionCode); 2094 removePackageLI(ps, true); 2095 mExpectingBetter.put(ps.name, ps.codePath); 2096 } 2097 2098 continue; 2099 } 2100 2101 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2102 psit.remove(); 2103 logCriticalInfo(Log.WARN, "System package " + ps.name 2104 + " no longer exists; wiping its data"); 2105 removeDataDirsLI(null, ps.name); 2106 } else { 2107 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2108 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2109 possiblyDeletedUpdatedSystemApps.add(ps.name); 2110 } 2111 } 2112 } 2113 } 2114 2115 //look for any incomplete package installations 2116 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2117 //clean up list 2118 for(int i = 0; i < deletePkgsList.size(); i++) { 2119 //clean up here 2120 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2121 } 2122 //delete tmp files 2123 deleteTempPackageFiles(); 2124 2125 // Remove any shared userIDs that have no associated packages 2126 mSettings.pruneSharedUsersLPw(); 2127 2128 if (!mOnlyCore) { 2129 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2130 SystemClock.uptimeMillis()); 2131 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2132 2133 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2134 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2135 2136 /** 2137 * Remove disable package settings for any updated system 2138 * apps that were removed via an OTA. If they're not a 2139 * previously-updated app, remove them completely. 2140 * Otherwise, just revoke their system-level permissions. 2141 */ 2142 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2143 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2144 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2145 2146 String msg; 2147 if (deletedPkg == null) { 2148 msg = "Updated system package " + deletedAppName 2149 + " no longer exists; wiping its data"; 2150 removeDataDirsLI(null, deletedAppName); 2151 } else { 2152 msg = "Updated system app + " + deletedAppName 2153 + " no longer present; removing system privileges for " 2154 + deletedAppName; 2155 2156 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2157 2158 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2159 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2160 } 2161 logCriticalInfo(Log.WARN, msg); 2162 } 2163 2164 /** 2165 * Make sure all system apps that we expected to appear on 2166 * the userdata partition actually showed up. If they never 2167 * appeared, crawl back and revive the system version. 2168 */ 2169 for (int i = 0; i < mExpectingBetter.size(); i++) { 2170 final String packageName = mExpectingBetter.keyAt(i); 2171 if (!mPackages.containsKey(packageName)) { 2172 final File scanFile = mExpectingBetter.valueAt(i); 2173 2174 logCriticalInfo(Log.WARN, "Expected better " + packageName 2175 + " but never showed up; reverting to system"); 2176 2177 final int reparseFlags; 2178 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2179 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2180 | PackageParser.PARSE_IS_SYSTEM_DIR 2181 | PackageParser.PARSE_IS_PRIVILEGED; 2182 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2183 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2184 | PackageParser.PARSE_IS_SYSTEM_DIR; 2185 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2186 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2187 | PackageParser.PARSE_IS_SYSTEM_DIR; 2188 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2189 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2190 | PackageParser.PARSE_IS_SYSTEM_DIR; 2191 } else { 2192 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2193 continue; 2194 } 2195 2196 mSettings.enableSystemPackageLPw(packageName); 2197 2198 try { 2199 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2200 } catch (PackageManagerException e) { 2201 Slog.e(TAG, "Failed to parse original system package: " 2202 + e.getMessage()); 2203 } 2204 } 2205 } 2206 } 2207 mExpectingBetter.clear(); 2208 2209 // Now that we know all of the shared libraries, update all clients to have 2210 // the correct library paths. 2211 updateAllSharedLibrariesLPw(); 2212 2213 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2214 // NOTE: We ignore potential failures here during a system scan (like 2215 // the rest of the commands above) because there's precious little we 2216 // can do about it. A settings error is reported, though. 2217 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2218 false /* force dexopt */, false /* defer dexopt */); 2219 } 2220 2221 // Now that we know all the packages we are keeping, 2222 // read and update their last usage times. 2223 mPackageUsage.readLP(); 2224 2225 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2226 SystemClock.uptimeMillis()); 2227 Slog.i(TAG, "Time to scan packages: " 2228 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2229 + " seconds"); 2230 2231 // If the platform SDK has changed since the last time we booted, 2232 // we need to re-grant app permission to catch any new ones that 2233 // appear. This is really a hack, and means that apps can in some 2234 // cases get permissions that the user didn't initially explicitly 2235 // allow... it would be nice to have some better way to handle 2236 // this situation. 2237 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2238 != mSdkVersion; 2239 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2240 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2241 + "; regranting permissions for internal storage"); 2242 mSettings.mInternalSdkPlatform = mSdkVersion; 2243 2244 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2245 | (regrantPermissions 2246 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2247 : 0)); 2248 2249 // If this is the first boot, and it is a normal boot, then 2250 // we need to initialize the default preferred apps. 2251 if (!mRestoredSettings && !onlyCore) { 2252 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2253 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2254 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2255 } 2256 2257 // If this is first boot after an OTA, and a normal boot, then 2258 // we need to clear code cache directories. 2259 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2260 if (mIsUpgrade && !onlyCore) { 2261 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2262 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2263 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2264 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2265 } 2266 mSettings.mFingerprint = Build.FINGERPRINT; 2267 } 2268 2269 checkDefaultBrowser(); 2270 2271 // All the changes are done during package scanning. 2272 mSettings.updateInternalDatabaseVersion(); 2273 2274 // can downgrade to reader 2275 mSettings.writeLPr(); 2276 2277 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2278 SystemClock.uptimeMillis()); 2279 2280 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2281 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2282 2283 mInstallerService = new PackageInstallerService(context, this); 2284 2285 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2286 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2287 mIntentFilterVerifierComponent); 2288 2289 } // synchronized (mPackages) 2290 } // synchronized (mInstallLock) 2291 2292 // Now after opening every single application zip, make sure they 2293 // are all flushed. Not really needed, but keeps things nice and 2294 // tidy. 2295 Runtime.getRuntime().gc(); 2296 2297 // Expose private service for system components to use. 2298 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2299 } 2300 2301 @Override 2302 public boolean isFirstBoot() { 2303 return !mRestoredSettings; 2304 } 2305 2306 @Override 2307 public boolean isOnlyCoreApps() { 2308 return mOnlyCore; 2309 } 2310 2311 @Override 2312 public boolean isUpgrade() { 2313 return mIsUpgrade; 2314 } 2315 2316 private String getRequiredVerifierLPr() { 2317 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2318 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2319 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2320 2321 String requiredVerifier = null; 2322 2323 final int N = receivers.size(); 2324 for (int i = 0; i < N; i++) { 2325 final ResolveInfo info = receivers.get(i); 2326 2327 if (info.activityInfo == null) { 2328 continue; 2329 } 2330 2331 final String packageName = info.activityInfo.packageName; 2332 2333 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2334 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2335 continue; 2336 } 2337 2338 if (requiredVerifier != null) { 2339 throw new RuntimeException("There can be only one required verifier"); 2340 } 2341 2342 requiredVerifier = packageName; 2343 } 2344 2345 return requiredVerifier; 2346 } 2347 2348 private String getRequiredInstallerLPr() { 2349 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2350 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2351 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2352 2353 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2354 PACKAGE_MIME_TYPE, 0, 0); 2355 2356 String requiredInstaller = null; 2357 2358 final int N = installers.size(); 2359 for (int i = 0; i < N; i++) { 2360 final ResolveInfo info = installers.get(i); 2361 final String packageName = info.activityInfo.packageName; 2362 2363 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2364 continue; 2365 } 2366 2367 if (requiredInstaller != null) { 2368 throw new RuntimeException("There must be one required installer"); 2369 } 2370 2371 requiredInstaller = packageName; 2372 } 2373 2374 if (requiredInstaller == null) { 2375 throw new RuntimeException("There must be one required installer"); 2376 } 2377 2378 return requiredInstaller; 2379 } 2380 2381 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2382 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2383 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2384 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2385 2386 ComponentName verifierComponentName = null; 2387 2388 int priority = -1000; 2389 final int N = receivers.size(); 2390 for (int i = 0; i < N; i++) { 2391 final ResolveInfo info = receivers.get(i); 2392 2393 if (info.activityInfo == null) { 2394 continue; 2395 } 2396 2397 final String packageName = info.activityInfo.packageName; 2398 2399 final PackageSetting ps = mSettings.mPackages.get(packageName); 2400 if (ps == null) { 2401 continue; 2402 } 2403 2404 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2405 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2406 continue; 2407 } 2408 2409 // Select the IntentFilterVerifier with the highest priority 2410 if (priority < info.priority) { 2411 priority = info.priority; 2412 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2413 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2414 + verifierComponentName + " with priority: " + info.priority); 2415 } 2416 } 2417 2418 return verifierComponentName; 2419 } 2420 2421 private void primeDomainVerificationsLPw(int userId) { 2422 if (DEBUG_DOMAIN_VERIFICATION) { 2423 Slog.d(TAG, "Priming domain verifications in user " + userId); 2424 } 2425 2426 SystemConfig systemConfig = SystemConfig.getInstance(); 2427 ArraySet<String> packages = systemConfig.getLinkedApps(); 2428 ArraySet<String> domains = new ArraySet<String>(); 2429 2430 for (String packageName : packages) { 2431 PackageParser.Package pkg = mPackages.get(packageName); 2432 if (pkg != null) { 2433 if (!pkg.isSystemApp()) { 2434 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2435 continue; 2436 } 2437 2438 domains.clear(); 2439 for (PackageParser.Activity a : pkg.activities) { 2440 for (ActivityIntentInfo filter : a.intents) { 2441 if (hasValidDomains(filter)) { 2442 domains.addAll(filter.getHostsList()); 2443 } 2444 } 2445 } 2446 2447 if (domains.size() > 0) { 2448 if (DEBUG_DOMAIN_VERIFICATION) { 2449 Slog.v(TAG, " + " + packageName); 2450 } 2451 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2452 // state w.r.t. the formal app-linkage "no verification attempted" state; 2453 // and then 'always' in the per-user state actually used for intent resolution. 2454 final IntentFilterVerificationInfo ivi; 2455 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2456 new ArrayList<String>(domains)); 2457 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2458 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2459 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2460 } else { 2461 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2462 + "' does not handle web links"); 2463 } 2464 } else { 2465 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2466 } 2467 } 2468 2469 scheduleWritePackageRestrictionsLocked(userId); 2470 scheduleWriteSettingsLocked(); 2471 } 2472 2473 private void applyFactoryDefaultBrowserLPw(int userId) { 2474 // The default browser app's package name is stored in a string resource, 2475 // with a product-specific overlay used for vendor customization. 2476 String browserPkg = mContext.getResources().getString( 2477 com.android.internal.R.string.default_browser); 2478 if (!TextUtils.isEmpty(browserPkg)) { 2479 // non-empty string => required to be a known package 2480 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2481 if (ps == null) { 2482 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2483 browserPkg = null; 2484 } else { 2485 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2486 } 2487 } 2488 2489 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2490 // default. If there's more than one, just leave everything alone. 2491 if (browserPkg == null) { 2492 calculateDefaultBrowserLPw(userId); 2493 } 2494 } 2495 2496 private void calculateDefaultBrowserLPw(int userId) { 2497 List<String> allBrowsers = resolveAllBrowserApps(userId); 2498 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2499 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2500 } 2501 2502 private List<String> resolveAllBrowserApps(int userId) { 2503 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2504 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2505 PackageManager.MATCH_ALL, userId); 2506 2507 final int count = list.size(); 2508 List<String> result = new ArrayList<String>(count); 2509 for (int i=0; i<count; i++) { 2510 ResolveInfo info = list.get(i); 2511 if (info.activityInfo == null 2512 || !info.handleAllWebDataURI 2513 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2514 || result.contains(info.activityInfo.packageName)) { 2515 continue; 2516 } 2517 result.add(info.activityInfo.packageName); 2518 } 2519 2520 return result; 2521 } 2522 2523 private boolean packageIsBrowser(String packageName, int userId) { 2524 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2525 PackageManager.MATCH_ALL, userId); 2526 final int N = list.size(); 2527 for (int i = 0; i < N; i++) { 2528 ResolveInfo info = list.get(i); 2529 if (packageName.equals(info.activityInfo.packageName)) { 2530 return true; 2531 } 2532 } 2533 return false; 2534 } 2535 2536 private void checkDefaultBrowser() { 2537 final int myUserId = UserHandle.myUserId(); 2538 final String packageName = getDefaultBrowserPackageName(myUserId); 2539 if (packageName != null) { 2540 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2541 if (info == null) { 2542 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2543 synchronized (mPackages) { 2544 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2545 } 2546 } 2547 } 2548 } 2549 2550 @Override 2551 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2552 throws RemoteException { 2553 try { 2554 return super.onTransact(code, data, reply, flags); 2555 } catch (RuntimeException e) { 2556 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2557 Slog.wtf(TAG, "Package Manager Crash", e); 2558 } 2559 throw e; 2560 } 2561 } 2562 2563 void cleanupInstallFailedPackage(PackageSetting ps) { 2564 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2565 2566 removeDataDirsLI(ps.volumeUuid, ps.name); 2567 if (ps.codePath != null) { 2568 if (ps.codePath.isDirectory()) { 2569 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2570 } else { 2571 ps.codePath.delete(); 2572 } 2573 } 2574 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2575 if (ps.resourcePath.isDirectory()) { 2576 FileUtils.deleteContents(ps.resourcePath); 2577 } 2578 ps.resourcePath.delete(); 2579 } 2580 mSettings.removePackageLPw(ps.name); 2581 } 2582 2583 static int[] appendInts(int[] cur, int[] add) { 2584 if (add == null) return cur; 2585 if (cur == null) return add; 2586 final int N = add.length; 2587 for (int i=0; i<N; i++) { 2588 cur = appendInt(cur, add[i]); 2589 } 2590 return cur; 2591 } 2592 2593 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2594 if (!sUserManager.exists(userId)) return null; 2595 final PackageSetting ps = (PackageSetting) p.mExtras; 2596 if (ps == null) { 2597 return null; 2598 } 2599 2600 final PermissionsState permissionsState = ps.getPermissionsState(); 2601 2602 final int[] gids = permissionsState.computeGids(userId); 2603 final Set<String> permissions = permissionsState.getPermissions(userId); 2604 final PackageUserState state = ps.readUserState(userId); 2605 2606 return PackageParser.generatePackageInfo(p, gids, flags, 2607 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2608 } 2609 2610 @Override 2611 public boolean isPackageFrozen(String packageName) { 2612 synchronized (mPackages) { 2613 final PackageSetting ps = mSettings.mPackages.get(packageName); 2614 if (ps != null) { 2615 return ps.frozen; 2616 } 2617 } 2618 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2619 return true; 2620 } 2621 2622 @Override 2623 public boolean isPackageAvailable(String packageName, int userId) { 2624 if (!sUserManager.exists(userId)) return false; 2625 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2626 synchronized (mPackages) { 2627 PackageParser.Package p = mPackages.get(packageName); 2628 if (p != null) { 2629 final PackageSetting ps = (PackageSetting) p.mExtras; 2630 if (ps != null) { 2631 final PackageUserState state = ps.readUserState(userId); 2632 if (state != null) { 2633 return PackageParser.isAvailable(state); 2634 } 2635 } 2636 } 2637 } 2638 return false; 2639 } 2640 2641 @Override 2642 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2643 if (!sUserManager.exists(userId)) return null; 2644 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2645 // reader 2646 synchronized (mPackages) { 2647 PackageParser.Package p = mPackages.get(packageName); 2648 if (DEBUG_PACKAGE_INFO) 2649 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2650 if (p != null) { 2651 return generatePackageInfo(p, flags, userId); 2652 } 2653 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2654 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2655 } 2656 } 2657 return null; 2658 } 2659 2660 @Override 2661 public String[] currentToCanonicalPackageNames(String[] names) { 2662 String[] out = new String[names.length]; 2663 // reader 2664 synchronized (mPackages) { 2665 for (int i=names.length-1; i>=0; i--) { 2666 PackageSetting ps = mSettings.mPackages.get(names[i]); 2667 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2668 } 2669 } 2670 return out; 2671 } 2672 2673 @Override 2674 public String[] canonicalToCurrentPackageNames(String[] names) { 2675 String[] out = new String[names.length]; 2676 // reader 2677 synchronized (mPackages) { 2678 for (int i=names.length-1; i>=0; i--) { 2679 String cur = mSettings.mRenamedPackages.get(names[i]); 2680 out[i] = cur != null ? cur : names[i]; 2681 } 2682 } 2683 return out; 2684 } 2685 2686 @Override 2687 public int getPackageUid(String packageName, int userId) { 2688 if (!sUserManager.exists(userId)) return -1; 2689 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2690 2691 // reader 2692 synchronized (mPackages) { 2693 PackageParser.Package p = mPackages.get(packageName); 2694 if(p != null) { 2695 return UserHandle.getUid(userId, p.applicationInfo.uid); 2696 } 2697 PackageSetting ps = mSettings.mPackages.get(packageName); 2698 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2699 return -1; 2700 } 2701 p = ps.pkg; 2702 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2703 } 2704 } 2705 2706 @Override 2707 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2708 if (!sUserManager.exists(userId)) { 2709 return null; 2710 } 2711 2712 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2713 "getPackageGids"); 2714 2715 // reader 2716 synchronized (mPackages) { 2717 PackageParser.Package p = mPackages.get(packageName); 2718 if (DEBUG_PACKAGE_INFO) { 2719 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2720 } 2721 if (p != null) { 2722 PackageSetting ps = (PackageSetting) p.mExtras; 2723 return ps.getPermissionsState().computeGids(userId); 2724 } 2725 } 2726 2727 return null; 2728 } 2729 2730 @Override 2731 public int getMountExternalMode(int uid) { 2732 if (Process.isIsolated(uid)) { 2733 return Zygote.MOUNT_EXTERNAL_NONE; 2734 } else { 2735 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 2736 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2737 } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2738 return Zygote.MOUNT_EXTERNAL_WRITE; 2739 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2740 return Zygote.MOUNT_EXTERNAL_READ; 2741 } else { 2742 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2743 } 2744 } 2745 } 2746 2747 static PermissionInfo generatePermissionInfo( 2748 BasePermission bp, int flags) { 2749 if (bp.perm != null) { 2750 return PackageParser.generatePermissionInfo(bp.perm, flags); 2751 } 2752 PermissionInfo pi = new PermissionInfo(); 2753 pi.name = bp.name; 2754 pi.packageName = bp.sourcePackage; 2755 pi.nonLocalizedLabel = bp.name; 2756 pi.protectionLevel = bp.protectionLevel; 2757 return pi; 2758 } 2759 2760 @Override 2761 public PermissionInfo getPermissionInfo(String name, int flags) { 2762 // reader 2763 synchronized (mPackages) { 2764 final BasePermission p = mSettings.mPermissions.get(name); 2765 if (p != null) { 2766 return generatePermissionInfo(p, flags); 2767 } 2768 return null; 2769 } 2770 } 2771 2772 @Override 2773 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2774 // reader 2775 synchronized (mPackages) { 2776 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2777 for (BasePermission p : mSettings.mPermissions.values()) { 2778 if (group == null) { 2779 if (p.perm == null || p.perm.info.group == null) { 2780 out.add(generatePermissionInfo(p, flags)); 2781 } 2782 } else { 2783 if (p.perm != null && group.equals(p.perm.info.group)) { 2784 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2785 } 2786 } 2787 } 2788 2789 if (out.size() > 0) { 2790 return out; 2791 } 2792 return mPermissionGroups.containsKey(group) ? out : null; 2793 } 2794 } 2795 2796 @Override 2797 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2798 // reader 2799 synchronized (mPackages) { 2800 return PackageParser.generatePermissionGroupInfo( 2801 mPermissionGroups.get(name), flags); 2802 } 2803 } 2804 2805 @Override 2806 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2807 // reader 2808 synchronized (mPackages) { 2809 final int N = mPermissionGroups.size(); 2810 ArrayList<PermissionGroupInfo> out 2811 = new ArrayList<PermissionGroupInfo>(N); 2812 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2813 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2814 } 2815 return out; 2816 } 2817 } 2818 2819 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2820 int userId) { 2821 if (!sUserManager.exists(userId)) return null; 2822 PackageSetting ps = mSettings.mPackages.get(packageName); 2823 if (ps != null) { 2824 if (ps.pkg == null) { 2825 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2826 flags, userId); 2827 if (pInfo != null) { 2828 return pInfo.applicationInfo; 2829 } 2830 return null; 2831 } 2832 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2833 ps.readUserState(userId), userId); 2834 } 2835 return null; 2836 } 2837 2838 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2839 int userId) { 2840 if (!sUserManager.exists(userId)) return null; 2841 PackageSetting ps = mSettings.mPackages.get(packageName); 2842 if (ps != null) { 2843 PackageParser.Package pkg = ps.pkg; 2844 if (pkg == null) { 2845 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2846 return null; 2847 } 2848 // Only data remains, so we aren't worried about code paths 2849 pkg = new PackageParser.Package(packageName); 2850 pkg.applicationInfo.packageName = packageName; 2851 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2852 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2853 pkg.applicationInfo.dataDir = Environment 2854 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2855 .getAbsolutePath(); 2856 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2857 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2858 } 2859 return generatePackageInfo(pkg, flags, userId); 2860 } 2861 return null; 2862 } 2863 2864 @Override 2865 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2866 if (!sUserManager.exists(userId)) return null; 2867 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2868 // writer 2869 synchronized (mPackages) { 2870 PackageParser.Package p = mPackages.get(packageName); 2871 if (DEBUG_PACKAGE_INFO) Log.v( 2872 TAG, "getApplicationInfo " + packageName 2873 + ": " + p); 2874 if (p != null) { 2875 PackageSetting ps = mSettings.mPackages.get(packageName); 2876 if (ps == null) return null; 2877 // Note: isEnabledLP() does not apply here - always return info 2878 return PackageParser.generateApplicationInfo( 2879 p, flags, ps.readUserState(userId), userId); 2880 } 2881 if ("android".equals(packageName)||"system".equals(packageName)) { 2882 return mAndroidApplication; 2883 } 2884 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2885 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2886 } 2887 } 2888 return null; 2889 } 2890 2891 @Override 2892 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2893 final IPackageDataObserver observer) { 2894 mContext.enforceCallingOrSelfPermission( 2895 android.Manifest.permission.CLEAR_APP_CACHE, null); 2896 // Queue up an async operation since clearing cache may take a little while. 2897 mHandler.post(new Runnable() { 2898 public void run() { 2899 mHandler.removeCallbacks(this); 2900 int retCode = -1; 2901 synchronized (mInstallLock) { 2902 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2903 if (retCode < 0) { 2904 Slog.w(TAG, "Couldn't clear application caches"); 2905 } 2906 } 2907 if (observer != null) { 2908 try { 2909 observer.onRemoveCompleted(null, (retCode >= 0)); 2910 } catch (RemoteException e) { 2911 Slog.w(TAG, "RemoveException when invoking call back"); 2912 } 2913 } 2914 } 2915 }); 2916 } 2917 2918 @Override 2919 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2920 final IntentSender pi) { 2921 mContext.enforceCallingOrSelfPermission( 2922 android.Manifest.permission.CLEAR_APP_CACHE, null); 2923 // Queue up an async operation since clearing cache may take a little while. 2924 mHandler.post(new Runnable() { 2925 public void run() { 2926 mHandler.removeCallbacks(this); 2927 int retCode = -1; 2928 synchronized (mInstallLock) { 2929 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2930 if (retCode < 0) { 2931 Slog.w(TAG, "Couldn't clear application caches"); 2932 } 2933 } 2934 if(pi != null) { 2935 try { 2936 // Callback via pending intent 2937 int code = (retCode >= 0) ? 1 : 0; 2938 pi.sendIntent(null, code, null, 2939 null, null); 2940 } catch (SendIntentException e1) { 2941 Slog.i(TAG, "Failed to send pending intent"); 2942 } 2943 } 2944 } 2945 }); 2946 } 2947 2948 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2949 synchronized (mInstallLock) { 2950 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2951 throw new IOException("Failed to free enough space"); 2952 } 2953 } 2954 } 2955 2956 @Override 2957 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2958 if (!sUserManager.exists(userId)) return null; 2959 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2960 synchronized (mPackages) { 2961 PackageParser.Activity a = mActivities.mActivities.get(component); 2962 2963 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2964 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2965 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2966 if (ps == null) return null; 2967 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2968 userId); 2969 } 2970 if (mResolveComponentName.equals(component)) { 2971 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2972 new PackageUserState(), userId); 2973 } 2974 } 2975 return null; 2976 } 2977 2978 @Override 2979 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2980 String resolvedType) { 2981 synchronized (mPackages) { 2982 PackageParser.Activity a = mActivities.mActivities.get(component); 2983 if (a == null) { 2984 return false; 2985 } 2986 for (int i=0; i<a.intents.size(); i++) { 2987 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2988 intent.getData(), intent.getCategories(), TAG) >= 0) { 2989 return true; 2990 } 2991 } 2992 return false; 2993 } 2994 } 2995 2996 @Override 2997 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2998 if (!sUserManager.exists(userId)) return null; 2999 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3000 synchronized (mPackages) { 3001 PackageParser.Activity a = mReceivers.mActivities.get(component); 3002 if (DEBUG_PACKAGE_INFO) Log.v( 3003 TAG, "getReceiverInfo " + component + ": " + a); 3004 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3005 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3006 if (ps == null) return null; 3007 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3008 userId); 3009 } 3010 } 3011 return null; 3012 } 3013 3014 @Override 3015 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3016 if (!sUserManager.exists(userId)) return null; 3017 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3018 synchronized (mPackages) { 3019 PackageParser.Service s = mServices.mServices.get(component); 3020 if (DEBUG_PACKAGE_INFO) Log.v( 3021 TAG, "getServiceInfo " + component + ": " + s); 3022 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3023 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3024 if (ps == null) return null; 3025 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3026 userId); 3027 } 3028 } 3029 return null; 3030 } 3031 3032 @Override 3033 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3034 if (!sUserManager.exists(userId)) return null; 3035 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3036 synchronized (mPackages) { 3037 PackageParser.Provider p = mProviders.mProviders.get(component); 3038 if (DEBUG_PACKAGE_INFO) Log.v( 3039 TAG, "getProviderInfo " + component + ": " + p); 3040 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3041 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3042 if (ps == null) return null; 3043 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3044 userId); 3045 } 3046 } 3047 return null; 3048 } 3049 3050 @Override 3051 public String[] getSystemSharedLibraryNames() { 3052 Set<String> libSet; 3053 synchronized (mPackages) { 3054 libSet = mSharedLibraries.keySet(); 3055 int size = libSet.size(); 3056 if (size > 0) { 3057 String[] libs = new String[size]; 3058 libSet.toArray(libs); 3059 return libs; 3060 } 3061 } 3062 return null; 3063 } 3064 3065 /** 3066 * @hide 3067 */ 3068 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3069 synchronized (mPackages) { 3070 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3071 if (lib != null && lib.apk != null) { 3072 return mPackages.get(lib.apk); 3073 } 3074 } 3075 return null; 3076 } 3077 3078 @Override 3079 public FeatureInfo[] getSystemAvailableFeatures() { 3080 Collection<FeatureInfo> featSet; 3081 synchronized (mPackages) { 3082 featSet = mAvailableFeatures.values(); 3083 int size = featSet.size(); 3084 if (size > 0) { 3085 FeatureInfo[] features = new FeatureInfo[size+1]; 3086 featSet.toArray(features); 3087 FeatureInfo fi = new FeatureInfo(); 3088 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3089 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3090 features[size] = fi; 3091 return features; 3092 } 3093 } 3094 return null; 3095 } 3096 3097 @Override 3098 public boolean hasSystemFeature(String name) { 3099 synchronized (mPackages) { 3100 return mAvailableFeatures.containsKey(name); 3101 } 3102 } 3103 3104 private void checkValidCaller(int uid, int userId) { 3105 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3106 return; 3107 3108 throw new SecurityException("Caller uid=" + uid 3109 + " is not privileged to communicate with user=" + userId); 3110 } 3111 3112 @Override 3113 public int checkPermission(String permName, String pkgName, int userId) { 3114 if (!sUserManager.exists(userId)) { 3115 return PackageManager.PERMISSION_DENIED; 3116 } 3117 3118 synchronized (mPackages) { 3119 final PackageParser.Package p = mPackages.get(pkgName); 3120 if (p != null && p.mExtras != null) { 3121 final PackageSetting ps = (PackageSetting) p.mExtras; 3122 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3123 return PackageManager.PERMISSION_GRANTED; 3124 } 3125 } 3126 } 3127 3128 return PackageManager.PERMISSION_DENIED; 3129 } 3130 3131 @Override 3132 public int checkUidPermission(String permName, int uid) { 3133 final int userId = UserHandle.getUserId(uid); 3134 3135 if (!sUserManager.exists(userId)) { 3136 return PackageManager.PERMISSION_DENIED; 3137 } 3138 3139 synchronized (mPackages) { 3140 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3141 if (obj != null) { 3142 final SettingBase ps = (SettingBase) obj; 3143 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3144 return PackageManager.PERMISSION_GRANTED; 3145 } 3146 } else { 3147 ArraySet<String> perms = mSystemPermissions.get(uid); 3148 if (perms != null && perms.contains(permName)) { 3149 return PackageManager.PERMISSION_GRANTED; 3150 } 3151 } 3152 } 3153 3154 return PackageManager.PERMISSION_DENIED; 3155 } 3156 3157 @Override 3158 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3159 if (UserHandle.getCallingUserId() != userId) { 3160 mContext.enforceCallingPermission( 3161 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3162 "isPermissionRevokedByPolicy for user " + userId); 3163 } 3164 3165 if (checkPermission(permission, packageName, userId) 3166 == PackageManager.PERMISSION_GRANTED) { 3167 return false; 3168 } 3169 3170 final long identity = Binder.clearCallingIdentity(); 3171 try { 3172 final int flags = getPermissionFlags(permission, packageName, userId); 3173 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3174 } finally { 3175 Binder.restoreCallingIdentity(identity); 3176 } 3177 } 3178 3179 /** 3180 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3181 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3182 * @param checkShell TODO(yamasani): 3183 * @param message the message to log on security exception 3184 */ 3185 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3186 boolean checkShell, String message) { 3187 if (userId < 0) { 3188 throw new IllegalArgumentException("Invalid userId " + userId); 3189 } 3190 if (checkShell) { 3191 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3192 } 3193 if (userId == UserHandle.getUserId(callingUid)) return; 3194 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3195 if (requireFullPermission) { 3196 mContext.enforceCallingOrSelfPermission( 3197 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3198 } else { 3199 try { 3200 mContext.enforceCallingOrSelfPermission( 3201 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3202 } catch (SecurityException se) { 3203 mContext.enforceCallingOrSelfPermission( 3204 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3205 } 3206 } 3207 } 3208 } 3209 3210 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3211 if (callingUid == Process.SHELL_UID) { 3212 if (userHandle >= 0 3213 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3214 throw new SecurityException("Shell does not have permission to access user " 3215 + userHandle); 3216 } else if (userHandle < 0) { 3217 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3218 + Debug.getCallers(3)); 3219 } 3220 } 3221 } 3222 3223 private BasePermission findPermissionTreeLP(String permName) { 3224 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3225 if (permName.startsWith(bp.name) && 3226 permName.length() > bp.name.length() && 3227 permName.charAt(bp.name.length()) == '.') { 3228 return bp; 3229 } 3230 } 3231 return null; 3232 } 3233 3234 private BasePermission checkPermissionTreeLP(String permName) { 3235 if (permName != null) { 3236 BasePermission bp = findPermissionTreeLP(permName); 3237 if (bp != null) { 3238 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3239 return bp; 3240 } 3241 throw new SecurityException("Calling uid " 3242 + Binder.getCallingUid() 3243 + " is not allowed to add to permission tree " 3244 + bp.name + " owned by uid " + bp.uid); 3245 } 3246 } 3247 throw new SecurityException("No permission tree found for " + permName); 3248 } 3249 3250 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3251 if (s1 == null) { 3252 return s2 == null; 3253 } 3254 if (s2 == null) { 3255 return false; 3256 } 3257 if (s1.getClass() != s2.getClass()) { 3258 return false; 3259 } 3260 return s1.equals(s2); 3261 } 3262 3263 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3264 if (pi1.icon != pi2.icon) return false; 3265 if (pi1.logo != pi2.logo) return false; 3266 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3267 if (!compareStrings(pi1.name, pi2.name)) return false; 3268 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3269 // We'll take care of setting this one. 3270 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3271 // These are not currently stored in settings. 3272 //if (!compareStrings(pi1.group, pi2.group)) return false; 3273 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3274 //if (pi1.labelRes != pi2.labelRes) return false; 3275 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3276 return true; 3277 } 3278 3279 int permissionInfoFootprint(PermissionInfo info) { 3280 int size = info.name.length(); 3281 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3282 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3283 return size; 3284 } 3285 3286 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3287 int size = 0; 3288 for (BasePermission perm : mSettings.mPermissions.values()) { 3289 if (perm.uid == tree.uid) { 3290 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3291 } 3292 } 3293 return size; 3294 } 3295 3296 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3297 // We calculate the max size of permissions defined by this uid and throw 3298 // if that plus the size of 'info' would exceed our stated maximum. 3299 if (tree.uid != Process.SYSTEM_UID) { 3300 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3301 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3302 throw new SecurityException("Permission tree size cap exceeded"); 3303 } 3304 } 3305 } 3306 3307 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3308 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3309 throw new SecurityException("Label must be specified in permission"); 3310 } 3311 BasePermission tree = checkPermissionTreeLP(info.name); 3312 BasePermission bp = mSettings.mPermissions.get(info.name); 3313 boolean added = bp == null; 3314 boolean changed = true; 3315 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3316 if (added) { 3317 enforcePermissionCapLocked(info, tree); 3318 bp = new BasePermission(info.name, tree.sourcePackage, 3319 BasePermission.TYPE_DYNAMIC); 3320 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3321 throw new SecurityException( 3322 "Not allowed to modify non-dynamic permission " 3323 + info.name); 3324 } else { 3325 if (bp.protectionLevel == fixedLevel 3326 && bp.perm.owner.equals(tree.perm.owner) 3327 && bp.uid == tree.uid 3328 && comparePermissionInfos(bp.perm.info, info)) { 3329 changed = false; 3330 } 3331 } 3332 bp.protectionLevel = fixedLevel; 3333 info = new PermissionInfo(info); 3334 info.protectionLevel = fixedLevel; 3335 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3336 bp.perm.info.packageName = tree.perm.info.packageName; 3337 bp.uid = tree.uid; 3338 if (added) { 3339 mSettings.mPermissions.put(info.name, bp); 3340 } 3341 if (changed) { 3342 if (!async) { 3343 mSettings.writeLPr(); 3344 } else { 3345 scheduleWriteSettingsLocked(); 3346 } 3347 } 3348 return added; 3349 } 3350 3351 @Override 3352 public boolean addPermission(PermissionInfo info) { 3353 synchronized (mPackages) { 3354 return addPermissionLocked(info, false); 3355 } 3356 } 3357 3358 @Override 3359 public boolean addPermissionAsync(PermissionInfo info) { 3360 synchronized (mPackages) { 3361 return addPermissionLocked(info, true); 3362 } 3363 } 3364 3365 @Override 3366 public void removePermission(String name) { 3367 synchronized (mPackages) { 3368 checkPermissionTreeLP(name); 3369 BasePermission bp = mSettings.mPermissions.get(name); 3370 if (bp != null) { 3371 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3372 throw new SecurityException( 3373 "Not allowed to modify non-dynamic permission " 3374 + name); 3375 } 3376 mSettings.mPermissions.remove(name); 3377 mSettings.writeLPr(); 3378 } 3379 } 3380 } 3381 3382 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3383 BasePermission bp) { 3384 int index = pkg.requestedPermissions.indexOf(bp.name); 3385 if (index == -1) { 3386 throw new SecurityException("Package " + pkg.packageName 3387 + " has not requested permission " + bp.name); 3388 } 3389 if (!bp.isRuntime()) { 3390 throw new SecurityException("Permission " + bp.name 3391 + " is not a changeable permission type"); 3392 } 3393 } 3394 3395 @Override 3396 public void grantRuntimePermission(String packageName, String name, final int userId) { 3397 if (!sUserManager.exists(userId)) { 3398 Log.e(TAG, "No such user:" + userId); 3399 return; 3400 } 3401 3402 mContext.enforceCallingOrSelfPermission( 3403 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3404 "grantRuntimePermission"); 3405 3406 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3407 "grantRuntimePermission"); 3408 3409 final int uid; 3410 final SettingBase sb; 3411 3412 synchronized (mPackages) { 3413 final PackageParser.Package pkg = mPackages.get(packageName); 3414 if (pkg == null) { 3415 throw new IllegalArgumentException("Unknown package: " + packageName); 3416 } 3417 3418 final BasePermission bp = mSettings.mPermissions.get(name); 3419 if (bp == null) { 3420 throw new IllegalArgumentException("Unknown permission: " + name); 3421 } 3422 3423 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3424 3425 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3426 sb = (SettingBase) pkg.mExtras; 3427 if (sb == null) { 3428 throw new IllegalArgumentException("Unknown package: " + packageName); 3429 } 3430 3431 final PermissionsState permissionsState = sb.getPermissionsState(); 3432 3433 final int flags = permissionsState.getPermissionFlags(name, userId); 3434 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3435 throw new SecurityException("Cannot grant system fixed permission: " 3436 + name + " for package: " + packageName); 3437 } 3438 3439 final int result = permissionsState.grantRuntimePermission(bp, userId); 3440 switch (result) { 3441 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3442 return; 3443 } 3444 3445 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3446 mHandler.post(new Runnable() { 3447 @Override 3448 public void run() { 3449 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3450 } 3451 }); 3452 } break; 3453 } 3454 3455 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3456 3457 // Not critical if that is lost - app has to request again. 3458 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3459 } 3460 3461 // Only need to do this if user is initialized. Otherwise it's a new user 3462 // and there are no processes running as the user yet and there's no need 3463 // to make an expensive call to remount processes for the changed permissions. 3464 if (READ_EXTERNAL_STORAGE.equals(name) 3465 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3466 final long token = Binder.clearCallingIdentity(); 3467 try { 3468 if (sUserManager.isInitialized(userId)) { 3469 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3470 storage.remountUid(uid); 3471 } 3472 } finally { 3473 Binder.restoreCallingIdentity(token); 3474 } 3475 } 3476 } 3477 3478 @Override 3479 public void revokeRuntimePermission(String packageName, String name, int userId) { 3480 if (!sUserManager.exists(userId)) { 3481 Log.e(TAG, "No such user:" + userId); 3482 return; 3483 } 3484 3485 mContext.enforceCallingOrSelfPermission( 3486 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3487 "revokeRuntimePermission"); 3488 3489 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3490 "revokeRuntimePermission"); 3491 3492 final SettingBase sb; 3493 3494 synchronized (mPackages) { 3495 final PackageParser.Package pkg = mPackages.get(packageName); 3496 if (pkg == null) { 3497 throw new IllegalArgumentException("Unknown package: " + packageName); 3498 } 3499 3500 final BasePermission bp = mSettings.mPermissions.get(name); 3501 if (bp == null) { 3502 throw new IllegalArgumentException("Unknown permission: " + name); 3503 } 3504 3505 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3506 3507 sb = (SettingBase) pkg.mExtras; 3508 if (sb == null) { 3509 throw new IllegalArgumentException("Unknown package: " + packageName); 3510 } 3511 3512 final PermissionsState permissionsState = sb.getPermissionsState(); 3513 3514 final int flags = permissionsState.getPermissionFlags(name, userId); 3515 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3516 throw new SecurityException("Cannot revoke system fixed permission: " 3517 + name + " for package: " + packageName); 3518 } 3519 3520 if (permissionsState.revokeRuntimePermission(bp, userId) == 3521 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3522 return; 3523 } 3524 3525 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3526 3527 // Critical, after this call app should never have the permission. 3528 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3529 } 3530 3531 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3532 } 3533 3534 @Override 3535 public void resetRuntimePermissions() { 3536 mContext.enforceCallingOrSelfPermission( 3537 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3538 "revokeRuntimePermission"); 3539 3540 int callingUid = Binder.getCallingUid(); 3541 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3542 mContext.enforceCallingOrSelfPermission( 3543 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3544 "resetRuntimePermissions"); 3545 } 3546 3547 final int[] userIds; 3548 3549 synchronized (mPackages) { 3550 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3551 final int userCount = UserManagerService.getInstance().getUserIds().length; 3552 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3553 } 3554 3555 for (int userId : userIds) { 3556 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3557 } 3558 } 3559 3560 @Override 3561 public int getPermissionFlags(String name, String packageName, int userId) { 3562 if (!sUserManager.exists(userId)) { 3563 return 0; 3564 } 3565 3566 mContext.enforceCallingOrSelfPermission( 3567 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3568 "getPermissionFlags"); 3569 3570 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3571 "getPermissionFlags"); 3572 3573 synchronized (mPackages) { 3574 final PackageParser.Package pkg = mPackages.get(packageName); 3575 if (pkg == null) { 3576 throw new IllegalArgumentException("Unknown package: " + packageName); 3577 } 3578 3579 final BasePermission bp = mSettings.mPermissions.get(name); 3580 if (bp == null) { 3581 throw new IllegalArgumentException("Unknown permission: " + name); 3582 } 3583 3584 SettingBase sb = (SettingBase) pkg.mExtras; 3585 if (sb == null) { 3586 throw new IllegalArgumentException("Unknown package: " + packageName); 3587 } 3588 3589 PermissionsState permissionsState = sb.getPermissionsState(); 3590 return permissionsState.getPermissionFlags(name, userId); 3591 } 3592 } 3593 3594 @Override 3595 public void updatePermissionFlags(String name, String packageName, int flagMask, 3596 int flagValues, int userId) { 3597 if (!sUserManager.exists(userId)) { 3598 return; 3599 } 3600 3601 mContext.enforceCallingOrSelfPermission( 3602 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3603 "updatePermissionFlags"); 3604 3605 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3606 "updatePermissionFlags"); 3607 3608 // Only the system can change system fixed flags. 3609 if (getCallingUid() != Process.SYSTEM_UID) { 3610 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3611 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3612 } 3613 3614 synchronized (mPackages) { 3615 final PackageParser.Package pkg = mPackages.get(packageName); 3616 if (pkg == null) { 3617 throw new IllegalArgumentException("Unknown package: " + packageName); 3618 } 3619 3620 final BasePermission bp = mSettings.mPermissions.get(name); 3621 if (bp == null) { 3622 throw new IllegalArgumentException("Unknown permission: " + name); 3623 } 3624 3625 SettingBase sb = (SettingBase) pkg.mExtras; 3626 if (sb == null) { 3627 throw new IllegalArgumentException("Unknown package: " + packageName); 3628 } 3629 3630 PermissionsState permissionsState = sb.getPermissionsState(); 3631 3632 // Only the package manager can change flags for system component permissions. 3633 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3634 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3635 return; 3636 } 3637 3638 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3639 3640 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3641 // Install and runtime permissions are stored in different places, 3642 // so figure out what permission changed and persist the change. 3643 if (permissionsState.getInstallPermissionState(name) != null) { 3644 scheduleWriteSettingsLocked(); 3645 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3646 || hadState) { 3647 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3648 } 3649 } 3650 } 3651 } 3652 3653 /** 3654 * Update the permission flags for all packages and runtime permissions of a user in order 3655 * to allow device or profile owner to remove POLICY_FIXED. 3656 */ 3657 @Override 3658 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3659 if (!sUserManager.exists(userId)) { 3660 return; 3661 } 3662 3663 mContext.enforceCallingOrSelfPermission( 3664 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3665 "updatePermissionFlagsForAllApps"); 3666 3667 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3668 "updatePermissionFlagsForAllApps"); 3669 3670 // Only the system can change system fixed flags. 3671 if (getCallingUid() != Process.SYSTEM_UID) { 3672 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3673 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3674 } 3675 3676 synchronized (mPackages) { 3677 boolean changed = false; 3678 final int packageCount = mPackages.size(); 3679 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3680 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3681 SettingBase sb = (SettingBase) pkg.mExtras; 3682 if (sb == null) { 3683 continue; 3684 } 3685 PermissionsState permissionsState = sb.getPermissionsState(); 3686 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3687 userId, flagMask, flagValues); 3688 } 3689 if (changed) { 3690 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3691 } 3692 } 3693 } 3694 3695 @Override 3696 public boolean shouldShowRequestPermissionRationale(String permissionName, 3697 String packageName, int userId) { 3698 if (UserHandle.getCallingUserId() != userId) { 3699 mContext.enforceCallingPermission( 3700 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3701 "canShowRequestPermissionRationale for user " + userId); 3702 } 3703 3704 final int uid = getPackageUid(packageName, userId); 3705 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3706 return false; 3707 } 3708 3709 if (checkPermission(permissionName, packageName, userId) 3710 == PackageManager.PERMISSION_GRANTED) { 3711 return false; 3712 } 3713 3714 final int flags; 3715 3716 final long identity = Binder.clearCallingIdentity(); 3717 try { 3718 flags = getPermissionFlags(permissionName, 3719 packageName, userId); 3720 } finally { 3721 Binder.restoreCallingIdentity(identity); 3722 } 3723 3724 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3725 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3726 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3727 3728 if ((flags & fixedFlags) != 0) { 3729 return false; 3730 } 3731 3732 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3733 } 3734 3735 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3736 BasePermission bp = mSettings.mPermissions.get(permission); 3737 if (bp == null) { 3738 throw new SecurityException("Missing " + permission + " permission"); 3739 } 3740 3741 SettingBase sb = (SettingBase) pkg.mExtras; 3742 PermissionsState permissionsState = sb.getPermissionsState(); 3743 3744 if (permissionsState.grantInstallPermission(bp) != 3745 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3746 scheduleWriteSettingsLocked(); 3747 } 3748 } 3749 3750 @Override 3751 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3752 mContext.enforceCallingOrSelfPermission( 3753 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3754 "addOnPermissionsChangeListener"); 3755 3756 synchronized (mPackages) { 3757 mOnPermissionChangeListeners.addListenerLocked(listener); 3758 } 3759 } 3760 3761 @Override 3762 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3763 synchronized (mPackages) { 3764 mOnPermissionChangeListeners.removeListenerLocked(listener); 3765 } 3766 } 3767 3768 @Override 3769 public boolean isProtectedBroadcast(String actionName) { 3770 synchronized (mPackages) { 3771 return mProtectedBroadcasts.contains(actionName); 3772 } 3773 } 3774 3775 @Override 3776 public int checkSignatures(String pkg1, String pkg2) { 3777 synchronized (mPackages) { 3778 final PackageParser.Package p1 = mPackages.get(pkg1); 3779 final PackageParser.Package p2 = mPackages.get(pkg2); 3780 if (p1 == null || p1.mExtras == null 3781 || p2 == null || p2.mExtras == null) { 3782 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3783 } 3784 return compareSignatures(p1.mSignatures, p2.mSignatures); 3785 } 3786 } 3787 3788 @Override 3789 public int checkUidSignatures(int uid1, int uid2) { 3790 // Map to base uids. 3791 uid1 = UserHandle.getAppId(uid1); 3792 uid2 = UserHandle.getAppId(uid2); 3793 // reader 3794 synchronized (mPackages) { 3795 Signature[] s1; 3796 Signature[] s2; 3797 Object obj = mSettings.getUserIdLPr(uid1); 3798 if (obj != null) { 3799 if (obj instanceof SharedUserSetting) { 3800 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3801 } else if (obj instanceof PackageSetting) { 3802 s1 = ((PackageSetting)obj).signatures.mSignatures; 3803 } else { 3804 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3805 } 3806 } else { 3807 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3808 } 3809 obj = mSettings.getUserIdLPr(uid2); 3810 if (obj != null) { 3811 if (obj instanceof SharedUserSetting) { 3812 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3813 } else if (obj instanceof PackageSetting) { 3814 s2 = ((PackageSetting)obj).signatures.mSignatures; 3815 } else { 3816 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3817 } 3818 } else { 3819 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3820 } 3821 return compareSignatures(s1, s2); 3822 } 3823 } 3824 3825 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3826 final long identity = Binder.clearCallingIdentity(); 3827 try { 3828 if (sb instanceof SharedUserSetting) { 3829 SharedUserSetting sus = (SharedUserSetting) sb; 3830 final int packageCount = sus.packages.size(); 3831 for (int i = 0; i < packageCount; i++) { 3832 PackageSetting susPs = sus.packages.valueAt(i); 3833 if (userId == UserHandle.USER_ALL) { 3834 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3835 } else { 3836 final int uid = UserHandle.getUid(userId, susPs.appId); 3837 killUid(uid, reason); 3838 } 3839 } 3840 } else if (sb instanceof PackageSetting) { 3841 PackageSetting ps = (PackageSetting) sb; 3842 if (userId == UserHandle.USER_ALL) { 3843 killApplication(ps.pkg.packageName, ps.appId, reason); 3844 } else { 3845 final int uid = UserHandle.getUid(userId, ps.appId); 3846 killUid(uid, reason); 3847 } 3848 } 3849 } finally { 3850 Binder.restoreCallingIdentity(identity); 3851 } 3852 } 3853 3854 private static void killUid(int uid, String reason) { 3855 IActivityManager am = ActivityManagerNative.getDefault(); 3856 if (am != null) { 3857 try { 3858 am.killUid(uid, reason); 3859 } catch (RemoteException e) { 3860 /* ignore - same process */ 3861 } 3862 } 3863 } 3864 3865 /** 3866 * Compares two sets of signatures. Returns: 3867 * <br /> 3868 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3869 * <br /> 3870 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3871 * <br /> 3872 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3873 * <br /> 3874 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3875 * <br /> 3876 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3877 */ 3878 static int compareSignatures(Signature[] s1, Signature[] s2) { 3879 if (s1 == null) { 3880 return s2 == null 3881 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3882 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3883 } 3884 3885 if (s2 == null) { 3886 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3887 } 3888 3889 if (s1.length != s2.length) { 3890 return PackageManager.SIGNATURE_NO_MATCH; 3891 } 3892 3893 // Since both signature sets are of size 1, we can compare without HashSets. 3894 if (s1.length == 1) { 3895 return s1[0].equals(s2[0]) ? 3896 PackageManager.SIGNATURE_MATCH : 3897 PackageManager.SIGNATURE_NO_MATCH; 3898 } 3899 3900 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3901 for (Signature sig : s1) { 3902 set1.add(sig); 3903 } 3904 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3905 for (Signature sig : s2) { 3906 set2.add(sig); 3907 } 3908 // Make sure s2 contains all signatures in s1. 3909 if (set1.equals(set2)) { 3910 return PackageManager.SIGNATURE_MATCH; 3911 } 3912 return PackageManager.SIGNATURE_NO_MATCH; 3913 } 3914 3915 /** 3916 * If the database version for this type of package (internal storage or 3917 * external storage) is less than the version where package signatures 3918 * were updated, return true. 3919 */ 3920 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3921 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3922 DatabaseVersion.SIGNATURE_END_ENTITY)) 3923 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3924 DatabaseVersion.SIGNATURE_END_ENTITY)); 3925 } 3926 3927 /** 3928 * Used for backward compatibility to make sure any packages with 3929 * certificate chains get upgraded to the new style. {@code existingSigs} 3930 * will be in the old format (since they were stored on disk from before the 3931 * system upgrade) and {@code scannedSigs} will be in the newer format. 3932 */ 3933 private int compareSignaturesCompat(PackageSignatures existingSigs, 3934 PackageParser.Package scannedPkg) { 3935 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3936 return PackageManager.SIGNATURE_NO_MATCH; 3937 } 3938 3939 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3940 for (Signature sig : existingSigs.mSignatures) { 3941 existingSet.add(sig); 3942 } 3943 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3944 for (Signature sig : scannedPkg.mSignatures) { 3945 try { 3946 Signature[] chainSignatures = sig.getChainSignatures(); 3947 for (Signature chainSig : chainSignatures) { 3948 scannedCompatSet.add(chainSig); 3949 } 3950 } catch (CertificateEncodingException e) { 3951 scannedCompatSet.add(sig); 3952 } 3953 } 3954 /* 3955 * Make sure the expanded scanned set contains all signatures in the 3956 * existing one. 3957 */ 3958 if (scannedCompatSet.equals(existingSet)) { 3959 // Migrate the old signatures to the new scheme. 3960 existingSigs.assignSignatures(scannedPkg.mSignatures); 3961 // The new KeySets will be re-added later in the scanning process. 3962 synchronized (mPackages) { 3963 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3964 } 3965 return PackageManager.SIGNATURE_MATCH; 3966 } 3967 return PackageManager.SIGNATURE_NO_MATCH; 3968 } 3969 3970 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3971 if (isExternal(scannedPkg)) { 3972 return mSettings.isExternalDatabaseVersionOlderThan( 3973 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3974 } else { 3975 return mSettings.isInternalDatabaseVersionOlderThan( 3976 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3977 } 3978 } 3979 3980 private int compareSignaturesRecover(PackageSignatures existingSigs, 3981 PackageParser.Package scannedPkg) { 3982 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3983 return PackageManager.SIGNATURE_NO_MATCH; 3984 } 3985 3986 String msg = null; 3987 try { 3988 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3989 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3990 + scannedPkg.packageName); 3991 return PackageManager.SIGNATURE_MATCH; 3992 } 3993 } catch (CertificateException e) { 3994 msg = e.getMessage(); 3995 } 3996 3997 logCriticalInfo(Log.INFO, 3998 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3999 return PackageManager.SIGNATURE_NO_MATCH; 4000 } 4001 4002 @Override 4003 public String[] getPackagesForUid(int uid) { 4004 uid = UserHandle.getAppId(uid); 4005 // reader 4006 synchronized (mPackages) { 4007 Object obj = mSettings.getUserIdLPr(uid); 4008 if (obj instanceof SharedUserSetting) { 4009 final SharedUserSetting sus = (SharedUserSetting) obj; 4010 final int N = sus.packages.size(); 4011 final String[] res = new String[N]; 4012 final Iterator<PackageSetting> it = sus.packages.iterator(); 4013 int i = 0; 4014 while (it.hasNext()) { 4015 res[i++] = it.next().name; 4016 } 4017 return res; 4018 } else if (obj instanceof PackageSetting) { 4019 final PackageSetting ps = (PackageSetting) obj; 4020 return new String[] { ps.name }; 4021 } 4022 } 4023 return null; 4024 } 4025 4026 @Override 4027 public String getNameForUid(int uid) { 4028 // reader 4029 synchronized (mPackages) { 4030 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4031 if (obj instanceof SharedUserSetting) { 4032 final SharedUserSetting sus = (SharedUserSetting) obj; 4033 return sus.name + ":" + sus.userId; 4034 } else if (obj instanceof PackageSetting) { 4035 final PackageSetting ps = (PackageSetting) obj; 4036 return ps.name; 4037 } 4038 } 4039 return null; 4040 } 4041 4042 @Override 4043 public int getUidForSharedUser(String sharedUserName) { 4044 if(sharedUserName == null) { 4045 return -1; 4046 } 4047 // reader 4048 synchronized (mPackages) { 4049 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4050 if (suid == null) { 4051 return -1; 4052 } 4053 return suid.userId; 4054 } 4055 } 4056 4057 @Override 4058 public int getFlagsForUid(int uid) { 4059 synchronized (mPackages) { 4060 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4061 if (obj instanceof SharedUserSetting) { 4062 final SharedUserSetting sus = (SharedUserSetting) obj; 4063 return sus.pkgFlags; 4064 } else if (obj instanceof PackageSetting) { 4065 final PackageSetting ps = (PackageSetting) obj; 4066 return ps.pkgFlags; 4067 } 4068 } 4069 return 0; 4070 } 4071 4072 @Override 4073 public int getPrivateFlagsForUid(int uid) { 4074 synchronized (mPackages) { 4075 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4076 if (obj instanceof SharedUserSetting) { 4077 final SharedUserSetting sus = (SharedUserSetting) obj; 4078 return sus.pkgPrivateFlags; 4079 } else if (obj instanceof PackageSetting) { 4080 final PackageSetting ps = (PackageSetting) obj; 4081 return ps.pkgPrivateFlags; 4082 } 4083 } 4084 return 0; 4085 } 4086 4087 @Override 4088 public boolean isUidPrivileged(int uid) { 4089 uid = UserHandle.getAppId(uid); 4090 // reader 4091 synchronized (mPackages) { 4092 Object obj = mSettings.getUserIdLPr(uid); 4093 if (obj instanceof SharedUserSetting) { 4094 final SharedUserSetting sus = (SharedUserSetting) obj; 4095 final Iterator<PackageSetting> it = sus.packages.iterator(); 4096 while (it.hasNext()) { 4097 if (it.next().isPrivileged()) { 4098 return true; 4099 } 4100 } 4101 } else if (obj instanceof PackageSetting) { 4102 final PackageSetting ps = (PackageSetting) obj; 4103 return ps.isPrivileged(); 4104 } 4105 } 4106 return false; 4107 } 4108 4109 @Override 4110 public String[] getAppOpPermissionPackages(String permissionName) { 4111 synchronized (mPackages) { 4112 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4113 if (pkgs == null) { 4114 return null; 4115 } 4116 return pkgs.toArray(new String[pkgs.size()]); 4117 } 4118 } 4119 4120 @Override 4121 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4122 int flags, int userId) { 4123 if (!sUserManager.exists(userId)) return null; 4124 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4125 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4126 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4127 } 4128 4129 @Override 4130 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4131 IntentFilter filter, int match, ComponentName activity) { 4132 final int userId = UserHandle.getCallingUserId(); 4133 if (DEBUG_PREFERRED) { 4134 Log.v(TAG, "setLastChosenActivity intent=" + intent 4135 + " resolvedType=" + resolvedType 4136 + " flags=" + flags 4137 + " filter=" + filter 4138 + " match=" + match 4139 + " activity=" + activity); 4140 filter.dump(new PrintStreamPrinter(System.out), " "); 4141 } 4142 intent.setComponent(null); 4143 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4144 // Find any earlier preferred or last chosen entries and nuke them 4145 findPreferredActivity(intent, resolvedType, 4146 flags, query, 0, false, true, false, userId); 4147 // Add the new activity as the last chosen for this filter 4148 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4149 "Setting last chosen"); 4150 } 4151 4152 @Override 4153 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4154 final int userId = UserHandle.getCallingUserId(); 4155 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4156 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4157 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4158 false, false, false, userId); 4159 } 4160 4161 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4162 int flags, List<ResolveInfo> query, int userId) { 4163 if (query != null) { 4164 final int N = query.size(); 4165 if (N == 1) { 4166 return query.get(0); 4167 } else if (N > 1) { 4168 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4169 // If there is more than one activity with the same priority, 4170 // then let the user decide between them. 4171 ResolveInfo r0 = query.get(0); 4172 ResolveInfo r1 = query.get(1); 4173 if (DEBUG_INTENT_MATCHING || debug) { 4174 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4175 + r1.activityInfo.name + "=" + r1.priority); 4176 } 4177 // If the first activity has a higher priority, or a different 4178 // default, then it is always desireable to pick it. 4179 if (r0.priority != r1.priority 4180 || r0.preferredOrder != r1.preferredOrder 4181 || r0.isDefault != r1.isDefault) { 4182 return query.get(0); 4183 } 4184 // If we have saved a preference for a preferred activity for 4185 // this Intent, use that. 4186 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4187 flags, query, r0.priority, true, false, debug, userId); 4188 if (ri != null) { 4189 return ri; 4190 } 4191 if (userId != 0) { 4192 ri = new ResolveInfo(mResolveInfo); 4193 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4194 ri.activityInfo.applicationInfo = new ApplicationInfo( 4195 ri.activityInfo.applicationInfo); 4196 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4197 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4198 return ri; 4199 } 4200 return mResolveInfo; 4201 } 4202 } 4203 return null; 4204 } 4205 4206 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4207 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4208 final int N = query.size(); 4209 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4210 .get(userId); 4211 // Get the list of persistent preferred activities that handle the intent 4212 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4213 List<PersistentPreferredActivity> pprefs = ppir != null 4214 ? ppir.queryIntent(intent, resolvedType, 4215 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4216 : null; 4217 if (pprefs != null && pprefs.size() > 0) { 4218 final int M = pprefs.size(); 4219 for (int i=0; i<M; i++) { 4220 final PersistentPreferredActivity ppa = pprefs.get(i); 4221 if (DEBUG_PREFERRED || debug) { 4222 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4223 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4224 + "\n component=" + ppa.mComponent); 4225 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4226 } 4227 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4228 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4229 if (DEBUG_PREFERRED || debug) { 4230 Slog.v(TAG, "Found persistent preferred activity:"); 4231 if (ai != null) { 4232 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4233 } else { 4234 Slog.v(TAG, " null"); 4235 } 4236 } 4237 if (ai == null) { 4238 // This previously registered persistent preferred activity 4239 // component is no longer known. Ignore it and do NOT remove it. 4240 continue; 4241 } 4242 for (int j=0; j<N; j++) { 4243 final ResolveInfo ri = query.get(j); 4244 if (!ri.activityInfo.applicationInfo.packageName 4245 .equals(ai.applicationInfo.packageName)) { 4246 continue; 4247 } 4248 if (!ri.activityInfo.name.equals(ai.name)) { 4249 continue; 4250 } 4251 // Found a persistent preference that can handle the intent. 4252 if (DEBUG_PREFERRED || debug) { 4253 Slog.v(TAG, "Returning persistent preferred activity: " + 4254 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4255 } 4256 return ri; 4257 } 4258 } 4259 } 4260 return null; 4261 } 4262 4263 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4264 List<ResolveInfo> query, int priority, boolean always, 4265 boolean removeMatches, boolean debug, int userId) { 4266 if (!sUserManager.exists(userId)) return null; 4267 // writer 4268 synchronized (mPackages) { 4269 if (intent.getSelector() != null) { 4270 intent = intent.getSelector(); 4271 } 4272 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4273 4274 // Try to find a matching persistent preferred activity. 4275 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4276 debug, userId); 4277 4278 // If a persistent preferred activity matched, use it. 4279 if (pri != null) { 4280 return pri; 4281 } 4282 4283 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4284 // Get the list of preferred activities that handle the intent 4285 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4286 List<PreferredActivity> prefs = pir != null 4287 ? pir.queryIntent(intent, resolvedType, 4288 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4289 : null; 4290 if (prefs != null && prefs.size() > 0) { 4291 boolean changed = false; 4292 try { 4293 // First figure out how good the original match set is. 4294 // We will only allow preferred activities that came 4295 // from the same match quality. 4296 int match = 0; 4297 4298 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4299 4300 final int N = query.size(); 4301 for (int j=0; j<N; j++) { 4302 final ResolveInfo ri = query.get(j); 4303 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4304 + ": 0x" + Integer.toHexString(match)); 4305 if (ri.match > match) { 4306 match = ri.match; 4307 } 4308 } 4309 4310 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4311 + Integer.toHexString(match)); 4312 4313 match &= IntentFilter.MATCH_CATEGORY_MASK; 4314 final int M = prefs.size(); 4315 for (int i=0; i<M; i++) { 4316 final PreferredActivity pa = prefs.get(i); 4317 if (DEBUG_PREFERRED || debug) { 4318 Slog.v(TAG, "Checking PreferredActivity ds=" 4319 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4320 + "\n component=" + pa.mPref.mComponent); 4321 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4322 } 4323 if (pa.mPref.mMatch != match) { 4324 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4325 + Integer.toHexString(pa.mPref.mMatch)); 4326 continue; 4327 } 4328 // If it's not an "always" type preferred activity and that's what we're 4329 // looking for, skip it. 4330 if (always && !pa.mPref.mAlways) { 4331 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4332 continue; 4333 } 4334 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4335 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4336 if (DEBUG_PREFERRED || debug) { 4337 Slog.v(TAG, "Found preferred activity:"); 4338 if (ai != null) { 4339 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4340 } else { 4341 Slog.v(TAG, " null"); 4342 } 4343 } 4344 if (ai == null) { 4345 // This previously registered preferred activity 4346 // component is no longer known. Most likely an update 4347 // to the app was installed and in the new version this 4348 // component no longer exists. Clean it up by removing 4349 // it from the preferred activities list, and skip it. 4350 Slog.w(TAG, "Removing dangling preferred activity: " 4351 + pa.mPref.mComponent); 4352 pir.removeFilter(pa); 4353 changed = true; 4354 continue; 4355 } 4356 for (int j=0; j<N; j++) { 4357 final ResolveInfo ri = query.get(j); 4358 if (!ri.activityInfo.applicationInfo.packageName 4359 .equals(ai.applicationInfo.packageName)) { 4360 continue; 4361 } 4362 if (!ri.activityInfo.name.equals(ai.name)) { 4363 continue; 4364 } 4365 4366 if (removeMatches) { 4367 pir.removeFilter(pa); 4368 changed = true; 4369 if (DEBUG_PREFERRED) { 4370 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4371 } 4372 break; 4373 } 4374 4375 // Okay we found a previously set preferred or last chosen app. 4376 // If the result set is different from when this 4377 // was created, we need to clear it and re-ask the 4378 // user their preference, if we're looking for an "always" type entry. 4379 if (always && !pa.mPref.sameSet(query)) { 4380 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4381 + intent + " type " + resolvedType); 4382 if (DEBUG_PREFERRED) { 4383 Slog.v(TAG, "Removing preferred activity since set changed " 4384 + pa.mPref.mComponent); 4385 } 4386 pir.removeFilter(pa); 4387 // Re-add the filter as a "last chosen" entry (!always) 4388 PreferredActivity lastChosen = new PreferredActivity( 4389 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4390 pir.addFilter(lastChosen); 4391 changed = true; 4392 return null; 4393 } 4394 4395 // Yay! Either the set matched or we're looking for the last chosen 4396 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4397 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4398 return ri; 4399 } 4400 } 4401 } finally { 4402 if (changed) { 4403 if (DEBUG_PREFERRED) { 4404 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4405 } 4406 scheduleWritePackageRestrictionsLocked(userId); 4407 } 4408 } 4409 } 4410 } 4411 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4412 return null; 4413 } 4414 4415 /* 4416 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4417 */ 4418 @Override 4419 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4420 int targetUserId) { 4421 mContext.enforceCallingOrSelfPermission( 4422 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4423 List<CrossProfileIntentFilter> matches = 4424 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4425 if (matches != null) { 4426 int size = matches.size(); 4427 for (int i = 0; i < size; i++) { 4428 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4429 } 4430 } 4431 if (hasWebURI(intent)) { 4432 // cross-profile app linking works only towards the parent. 4433 final UserInfo parent = getProfileParent(sourceUserId); 4434 synchronized(mPackages) { 4435 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4436 intent, resolvedType, 0, sourceUserId, parent.id); 4437 return xpDomainInfo != null 4438 && xpDomainInfo.bestDomainVerificationStatus != 4439 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 4440 } 4441 } 4442 return false; 4443 } 4444 4445 private UserInfo getProfileParent(int userId) { 4446 final long identity = Binder.clearCallingIdentity(); 4447 try { 4448 return sUserManager.getProfileParent(userId); 4449 } finally { 4450 Binder.restoreCallingIdentity(identity); 4451 } 4452 } 4453 4454 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4455 String resolvedType, int userId) { 4456 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4457 if (resolver != null) { 4458 return resolver.queryIntent(intent, resolvedType, false, userId); 4459 } 4460 return null; 4461 } 4462 4463 @Override 4464 public List<ResolveInfo> queryIntentActivities(Intent intent, 4465 String resolvedType, int flags, int userId) { 4466 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4467 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4468 ComponentName comp = intent.getComponent(); 4469 if (comp == null) { 4470 if (intent.getSelector() != null) { 4471 intent = intent.getSelector(); 4472 comp = intent.getComponent(); 4473 } 4474 } 4475 4476 if (comp != null) { 4477 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4478 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4479 if (ai != null) { 4480 final ResolveInfo ri = new ResolveInfo(); 4481 ri.activityInfo = ai; 4482 list.add(ri); 4483 } 4484 return list; 4485 } 4486 4487 // reader 4488 synchronized (mPackages) { 4489 final String pkgName = intent.getPackage(); 4490 if (pkgName == null) { 4491 List<CrossProfileIntentFilter> matchingFilters = 4492 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4493 // Check for results that need to skip the current profile. 4494 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4495 resolvedType, flags, userId); 4496 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4497 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4498 result.add(xpResolveInfo); 4499 return filterIfNotPrimaryUser(result, userId); 4500 } 4501 4502 // Check for results in the current profile. 4503 List<ResolveInfo> result = mActivities.queryIntent( 4504 intent, resolvedType, flags, userId); 4505 4506 // Check for cross profile results. 4507 xpResolveInfo = queryCrossProfileIntents( 4508 matchingFilters, intent, resolvedType, flags, userId); 4509 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4510 result.add(xpResolveInfo); 4511 Collections.sort(result, mResolvePrioritySorter); 4512 } 4513 result = filterIfNotPrimaryUser(result, userId); 4514 if (hasWebURI(intent)) { 4515 CrossProfileDomainInfo xpDomainInfo = null; 4516 final UserInfo parent = getProfileParent(userId); 4517 if (parent != null) { 4518 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4519 flags, userId, parent.id); 4520 } 4521 if (xpDomainInfo != null) { 4522 if (xpResolveInfo != null) { 4523 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4524 // in the result. 4525 result.remove(xpResolveInfo); 4526 } 4527 if (result.size() == 0) { 4528 result.add(xpDomainInfo.resolveInfo); 4529 return result; 4530 } 4531 } else if (result.size() <= 1) { 4532 return result; 4533 } 4534 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4535 xpDomainInfo, userId); 4536 Collections.sort(result, mResolvePrioritySorter); 4537 } 4538 return result; 4539 } 4540 final PackageParser.Package pkg = mPackages.get(pkgName); 4541 if (pkg != null) { 4542 return filterIfNotPrimaryUser( 4543 mActivities.queryIntentForPackage( 4544 intent, resolvedType, flags, pkg.activities, userId), 4545 userId); 4546 } 4547 return new ArrayList<ResolveInfo>(); 4548 } 4549 } 4550 4551 private static class CrossProfileDomainInfo { 4552 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4553 ResolveInfo resolveInfo; 4554 /* Best domain verification status of the activities found in the other profile */ 4555 int bestDomainVerificationStatus; 4556 } 4557 4558 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4559 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4560 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4561 sourceUserId)) { 4562 return null; 4563 } 4564 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4565 resolvedType, flags, parentUserId); 4566 4567 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4568 return null; 4569 } 4570 CrossProfileDomainInfo result = null; 4571 int size = resultTargetUser.size(); 4572 for (int i = 0; i < size; i++) { 4573 ResolveInfo riTargetUser = resultTargetUser.get(i); 4574 // Intent filter verification is only for filters that specify a host. So don't return 4575 // those that handle all web uris. 4576 if (riTargetUser.handleAllWebDataURI) { 4577 continue; 4578 } 4579 String packageName = riTargetUser.activityInfo.packageName; 4580 PackageSetting ps = mSettings.mPackages.get(packageName); 4581 if (ps == null) { 4582 continue; 4583 } 4584 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4585 if (result == null) { 4586 result = new CrossProfileDomainInfo(); 4587 result.resolveInfo = 4588 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4589 result.bestDomainVerificationStatus = status; 4590 } else { 4591 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4592 result.bestDomainVerificationStatus); 4593 } 4594 } 4595 return result; 4596 } 4597 4598 /** 4599 * Verification statuses are ordered from the worse to the best, except for 4600 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4601 */ 4602 private int bestDomainVerificationStatus(int status1, int status2) { 4603 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4604 return status2; 4605 } 4606 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4607 return status1; 4608 } 4609 return (int) MathUtils.max(status1, status2); 4610 } 4611 4612 private boolean isUserEnabled(int userId) { 4613 long callingId = Binder.clearCallingIdentity(); 4614 try { 4615 UserInfo userInfo = sUserManager.getUserInfo(userId); 4616 return userInfo != null && userInfo.isEnabled(); 4617 } finally { 4618 Binder.restoreCallingIdentity(callingId); 4619 } 4620 } 4621 4622 /** 4623 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4624 * 4625 * @return filtered list 4626 */ 4627 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4628 if (userId == UserHandle.USER_OWNER) { 4629 return resolveInfos; 4630 } 4631 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4632 ResolveInfo info = resolveInfos.get(i); 4633 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4634 resolveInfos.remove(i); 4635 } 4636 } 4637 return resolveInfos; 4638 } 4639 4640 private static boolean hasWebURI(Intent intent) { 4641 if (intent.getData() == null) { 4642 return false; 4643 } 4644 final String scheme = intent.getScheme(); 4645 if (TextUtils.isEmpty(scheme)) { 4646 return false; 4647 } 4648 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4649 } 4650 4651 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4652 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4653 int userId) { 4654 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4655 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4656 candidates.size()); 4657 } 4658 4659 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4660 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4661 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4662 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4663 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4664 4665 synchronized (mPackages) { 4666 final int count = candidates.size(); 4667 // First, try to use linked apps. Partition the candidates into four lists: 4668 // one for the final results, one for the "do not use ever", one for "undefined status" 4669 // and finally one for "browser app type". 4670 for (int n=0; n<count; n++) { 4671 ResolveInfo info = candidates.get(n); 4672 String packageName = info.activityInfo.packageName; 4673 PackageSetting ps = mSettings.mPackages.get(packageName); 4674 if (ps != null) { 4675 // Add to the special match all list (Browser use case) 4676 if (info.handleAllWebDataURI) { 4677 matchAllList.add(info); 4678 continue; 4679 } 4680 // Try to get the status from User settings first 4681 int status = getDomainVerificationStatusLPr(ps, userId); 4682 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4683 if (DEBUG_DOMAIN_VERIFICATION) { 4684 Slog.i(TAG, " + always: " + info.activityInfo.packageName); 4685 } 4686 alwaysList.add(info); 4687 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4688 if (DEBUG_DOMAIN_VERIFICATION) { 4689 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4690 } 4691 neverList.add(info); 4692 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4693 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4694 if (DEBUG_DOMAIN_VERIFICATION) { 4695 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4696 } 4697 undefinedList.add(info); 4698 } 4699 } 4700 } 4701 // First try to add the "always" resolution for the current user if there is any 4702 if (alwaysList.size() > 0) { 4703 result.addAll(alwaysList); 4704 // if there is an "always" for the parent user, add it. 4705 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4706 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4707 result.add(xpDomainInfo.resolveInfo); 4708 } else { 4709 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4710 result.addAll(undefinedList); 4711 if (xpDomainInfo != null && ( 4712 xpDomainInfo.bestDomainVerificationStatus 4713 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4714 || xpDomainInfo.bestDomainVerificationStatus 4715 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4716 result.add(xpDomainInfo.resolveInfo); 4717 } 4718 // Also add Browsers (all of them or only the default one) 4719 if ((flags & MATCH_ALL) != 0) { 4720 result.addAll(matchAllList); 4721 } else { 4722 // Try to add the Default Browser if we can 4723 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4724 UserHandle.myUserId()); 4725 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4726 boolean defaultBrowserFound = false; 4727 final int browserCount = matchAllList.size(); 4728 for (int n=0; n<browserCount; n++) { 4729 ResolveInfo browser = matchAllList.get(n); 4730 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4731 result.add(browser); 4732 defaultBrowserFound = true; 4733 break; 4734 } 4735 } 4736 if (!defaultBrowserFound) { 4737 result.addAll(matchAllList); 4738 } 4739 } else { 4740 result.addAll(matchAllList); 4741 } 4742 } 4743 4744 // If there is nothing selected, add all candidates and remove the ones that the user 4745 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4746 if (result.size() == 0) { 4747 result.addAll(candidates); 4748 result.removeAll(neverList); 4749 } 4750 } 4751 } 4752 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4753 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4754 result.size()); 4755 for (ResolveInfo info : result) { 4756 Slog.v(TAG, " + " + info.activityInfo); 4757 } 4758 } 4759 return result; 4760 } 4761 4762 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4763 int status = ps.getDomainVerificationStatusForUser(userId); 4764 // if none available, get the master status 4765 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4766 if (ps.getIntentFilterVerificationInfo() != null) { 4767 status = ps.getIntentFilterVerificationInfo().getStatus(); 4768 } 4769 } 4770 return status; 4771 } 4772 4773 private ResolveInfo querySkipCurrentProfileIntents( 4774 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4775 int flags, int sourceUserId) { 4776 if (matchingFilters != null) { 4777 int size = matchingFilters.size(); 4778 for (int i = 0; i < size; i ++) { 4779 CrossProfileIntentFilter filter = matchingFilters.get(i); 4780 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4781 // Checking if there are activities in the target user that can handle the 4782 // intent. 4783 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4784 flags, sourceUserId); 4785 if (resolveInfo != null) { 4786 return resolveInfo; 4787 } 4788 } 4789 } 4790 } 4791 return null; 4792 } 4793 4794 // Return matching ResolveInfo if any for skip current profile intent filters. 4795 private ResolveInfo queryCrossProfileIntents( 4796 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4797 int flags, int sourceUserId) { 4798 if (matchingFilters != null) { 4799 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4800 // match the same intent. For performance reasons, it is better not to 4801 // run queryIntent twice for the same userId 4802 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4803 int size = matchingFilters.size(); 4804 for (int i = 0; i < size; i++) { 4805 CrossProfileIntentFilter filter = matchingFilters.get(i); 4806 int targetUserId = filter.getTargetUserId(); 4807 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4808 && !alreadyTriedUserIds.get(targetUserId)) { 4809 // Checking if there are activities in the target user that can handle the 4810 // intent. 4811 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4812 flags, sourceUserId); 4813 if (resolveInfo != null) return resolveInfo; 4814 alreadyTriedUserIds.put(targetUserId, true); 4815 } 4816 } 4817 } 4818 return null; 4819 } 4820 4821 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4822 String resolvedType, int flags, int sourceUserId) { 4823 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4824 resolvedType, flags, filter.getTargetUserId()); 4825 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4826 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4827 } 4828 return null; 4829 } 4830 4831 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4832 int sourceUserId, int targetUserId) { 4833 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4834 String className; 4835 if (targetUserId == UserHandle.USER_OWNER) { 4836 className = FORWARD_INTENT_TO_USER_OWNER; 4837 } else { 4838 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4839 } 4840 ComponentName forwardingActivityComponentName = new ComponentName( 4841 mAndroidApplication.packageName, className); 4842 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4843 sourceUserId); 4844 if (targetUserId == UserHandle.USER_OWNER) { 4845 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4846 forwardingResolveInfo.noResourceId = true; 4847 } 4848 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4849 forwardingResolveInfo.priority = 0; 4850 forwardingResolveInfo.preferredOrder = 0; 4851 forwardingResolveInfo.match = 0; 4852 forwardingResolveInfo.isDefault = true; 4853 forwardingResolveInfo.filter = filter; 4854 forwardingResolveInfo.targetUserId = targetUserId; 4855 return forwardingResolveInfo; 4856 } 4857 4858 @Override 4859 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4860 Intent[] specifics, String[] specificTypes, Intent intent, 4861 String resolvedType, int flags, int userId) { 4862 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4863 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4864 false, "query intent activity options"); 4865 final String resultsAction = intent.getAction(); 4866 4867 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4868 | PackageManager.GET_RESOLVED_FILTER, userId); 4869 4870 if (DEBUG_INTENT_MATCHING) { 4871 Log.v(TAG, "Query " + intent + ": " + results); 4872 } 4873 4874 int specificsPos = 0; 4875 int N; 4876 4877 // todo: note that the algorithm used here is O(N^2). This 4878 // isn't a problem in our current environment, but if we start running 4879 // into situations where we have more than 5 or 10 matches then this 4880 // should probably be changed to something smarter... 4881 4882 // First we go through and resolve each of the specific items 4883 // that were supplied, taking care of removing any corresponding 4884 // duplicate items in the generic resolve list. 4885 if (specifics != null) { 4886 for (int i=0; i<specifics.length; i++) { 4887 final Intent sintent = specifics[i]; 4888 if (sintent == null) { 4889 continue; 4890 } 4891 4892 if (DEBUG_INTENT_MATCHING) { 4893 Log.v(TAG, "Specific #" + i + ": " + sintent); 4894 } 4895 4896 String action = sintent.getAction(); 4897 if (resultsAction != null && resultsAction.equals(action)) { 4898 // If this action was explicitly requested, then don't 4899 // remove things that have it. 4900 action = null; 4901 } 4902 4903 ResolveInfo ri = null; 4904 ActivityInfo ai = null; 4905 4906 ComponentName comp = sintent.getComponent(); 4907 if (comp == null) { 4908 ri = resolveIntent( 4909 sintent, 4910 specificTypes != null ? specificTypes[i] : null, 4911 flags, userId); 4912 if (ri == null) { 4913 continue; 4914 } 4915 if (ri == mResolveInfo) { 4916 // ACK! Must do something better with this. 4917 } 4918 ai = ri.activityInfo; 4919 comp = new ComponentName(ai.applicationInfo.packageName, 4920 ai.name); 4921 } else { 4922 ai = getActivityInfo(comp, flags, userId); 4923 if (ai == null) { 4924 continue; 4925 } 4926 } 4927 4928 // Look for any generic query activities that are duplicates 4929 // of this specific one, and remove them from the results. 4930 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4931 N = results.size(); 4932 int j; 4933 for (j=specificsPos; j<N; j++) { 4934 ResolveInfo sri = results.get(j); 4935 if ((sri.activityInfo.name.equals(comp.getClassName()) 4936 && sri.activityInfo.applicationInfo.packageName.equals( 4937 comp.getPackageName())) 4938 || (action != null && sri.filter.matchAction(action))) { 4939 results.remove(j); 4940 if (DEBUG_INTENT_MATCHING) Log.v( 4941 TAG, "Removing duplicate item from " + j 4942 + " due to specific " + specificsPos); 4943 if (ri == null) { 4944 ri = sri; 4945 } 4946 j--; 4947 N--; 4948 } 4949 } 4950 4951 // Add this specific item to its proper place. 4952 if (ri == null) { 4953 ri = new ResolveInfo(); 4954 ri.activityInfo = ai; 4955 } 4956 results.add(specificsPos, ri); 4957 ri.specificIndex = i; 4958 specificsPos++; 4959 } 4960 } 4961 4962 // Now we go through the remaining generic results and remove any 4963 // duplicate actions that are found here. 4964 N = results.size(); 4965 for (int i=specificsPos; i<N-1; i++) { 4966 final ResolveInfo rii = results.get(i); 4967 if (rii.filter == null) { 4968 continue; 4969 } 4970 4971 // Iterate over all of the actions of this result's intent 4972 // filter... typically this should be just one. 4973 final Iterator<String> it = rii.filter.actionsIterator(); 4974 if (it == null) { 4975 continue; 4976 } 4977 while (it.hasNext()) { 4978 final String action = it.next(); 4979 if (resultsAction != null && resultsAction.equals(action)) { 4980 // If this action was explicitly requested, then don't 4981 // remove things that have it. 4982 continue; 4983 } 4984 for (int j=i+1; j<N; j++) { 4985 final ResolveInfo rij = results.get(j); 4986 if (rij.filter != null && rij.filter.hasAction(action)) { 4987 results.remove(j); 4988 if (DEBUG_INTENT_MATCHING) Log.v( 4989 TAG, "Removing duplicate item from " + j 4990 + " due to action " + action + " at " + i); 4991 j--; 4992 N--; 4993 } 4994 } 4995 } 4996 4997 // If the caller didn't request filter information, drop it now 4998 // so we don't have to marshall/unmarshall it. 4999 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5000 rii.filter = null; 5001 } 5002 } 5003 5004 // Filter out the caller activity if so requested. 5005 if (caller != null) { 5006 N = results.size(); 5007 for (int i=0; i<N; i++) { 5008 ActivityInfo ainfo = results.get(i).activityInfo; 5009 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5010 && caller.getClassName().equals(ainfo.name)) { 5011 results.remove(i); 5012 break; 5013 } 5014 } 5015 } 5016 5017 // If the caller didn't request filter information, 5018 // drop them now so we don't have to 5019 // marshall/unmarshall it. 5020 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5021 N = results.size(); 5022 for (int i=0; i<N; i++) { 5023 results.get(i).filter = null; 5024 } 5025 } 5026 5027 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5028 return results; 5029 } 5030 5031 @Override 5032 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5033 int userId) { 5034 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5035 ComponentName comp = intent.getComponent(); 5036 if (comp == null) { 5037 if (intent.getSelector() != null) { 5038 intent = intent.getSelector(); 5039 comp = intent.getComponent(); 5040 } 5041 } 5042 if (comp != null) { 5043 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5044 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5045 if (ai != null) { 5046 ResolveInfo ri = new ResolveInfo(); 5047 ri.activityInfo = ai; 5048 list.add(ri); 5049 } 5050 return list; 5051 } 5052 5053 // reader 5054 synchronized (mPackages) { 5055 String pkgName = intent.getPackage(); 5056 if (pkgName == null) { 5057 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5058 } 5059 final PackageParser.Package pkg = mPackages.get(pkgName); 5060 if (pkg != null) { 5061 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5062 userId); 5063 } 5064 return null; 5065 } 5066 } 5067 5068 @Override 5069 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5070 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5071 if (!sUserManager.exists(userId)) return null; 5072 if (query != null) { 5073 if (query.size() >= 1) { 5074 // If there is more than one service with the same priority, 5075 // just arbitrarily pick the first one. 5076 return query.get(0); 5077 } 5078 } 5079 return null; 5080 } 5081 5082 @Override 5083 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5084 int userId) { 5085 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5086 ComponentName comp = intent.getComponent(); 5087 if (comp == null) { 5088 if (intent.getSelector() != null) { 5089 intent = intent.getSelector(); 5090 comp = intent.getComponent(); 5091 } 5092 } 5093 if (comp != null) { 5094 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5095 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5096 if (si != null) { 5097 final ResolveInfo ri = new ResolveInfo(); 5098 ri.serviceInfo = si; 5099 list.add(ri); 5100 } 5101 return list; 5102 } 5103 5104 // reader 5105 synchronized (mPackages) { 5106 String pkgName = intent.getPackage(); 5107 if (pkgName == null) { 5108 return mServices.queryIntent(intent, resolvedType, flags, userId); 5109 } 5110 final PackageParser.Package pkg = mPackages.get(pkgName); 5111 if (pkg != null) { 5112 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5113 userId); 5114 } 5115 return null; 5116 } 5117 } 5118 5119 @Override 5120 public List<ResolveInfo> queryIntentContentProviders( 5121 Intent intent, String resolvedType, int flags, int userId) { 5122 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5123 ComponentName comp = intent.getComponent(); 5124 if (comp == null) { 5125 if (intent.getSelector() != null) { 5126 intent = intent.getSelector(); 5127 comp = intent.getComponent(); 5128 } 5129 } 5130 if (comp != null) { 5131 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5132 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5133 if (pi != null) { 5134 final ResolveInfo ri = new ResolveInfo(); 5135 ri.providerInfo = pi; 5136 list.add(ri); 5137 } 5138 return list; 5139 } 5140 5141 // reader 5142 synchronized (mPackages) { 5143 String pkgName = intent.getPackage(); 5144 if (pkgName == null) { 5145 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5146 } 5147 final PackageParser.Package pkg = mPackages.get(pkgName); 5148 if (pkg != null) { 5149 return mProviders.queryIntentForPackage( 5150 intent, resolvedType, flags, pkg.providers, userId); 5151 } 5152 return null; 5153 } 5154 } 5155 5156 @Override 5157 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5158 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5159 5160 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5161 5162 // writer 5163 synchronized (mPackages) { 5164 ArrayList<PackageInfo> list; 5165 if (listUninstalled) { 5166 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5167 for (PackageSetting ps : mSettings.mPackages.values()) { 5168 PackageInfo pi; 5169 if (ps.pkg != null) { 5170 pi = generatePackageInfo(ps.pkg, flags, userId); 5171 } else { 5172 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5173 } 5174 if (pi != null) { 5175 list.add(pi); 5176 } 5177 } 5178 } else { 5179 list = new ArrayList<PackageInfo>(mPackages.size()); 5180 for (PackageParser.Package p : mPackages.values()) { 5181 PackageInfo pi = generatePackageInfo(p, flags, userId); 5182 if (pi != null) { 5183 list.add(pi); 5184 } 5185 } 5186 } 5187 5188 return new ParceledListSlice<PackageInfo>(list); 5189 } 5190 } 5191 5192 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5193 String[] permissions, boolean[] tmp, int flags, int userId) { 5194 int numMatch = 0; 5195 final PermissionsState permissionsState = ps.getPermissionsState(); 5196 for (int i=0; i<permissions.length; i++) { 5197 final String permission = permissions[i]; 5198 if (permissionsState.hasPermission(permission, userId)) { 5199 tmp[i] = true; 5200 numMatch++; 5201 } else { 5202 tmp[i] = false; 5203 } 5204 } 5205 if (numMatch == 0) { 5206 return; 5207 } 5208 PackageInfo pi; 5209 if (ps.pkg != null) { 5210 pi = generatePackageInfo(ps.pkg, flags, userId); 5211 } else { 5212 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5213 } 5214 // The above might return null in cases of uninstalled apps or install-state 5215 // skew across users/profiles. 5216 if (pi != null) { 5217 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5218 if (numMatch == permissions.length) { 5219 pi.requestedPermissions = permissions; 5220 } else { 5221 pi.requestedPermissions = new String[numMatch]; 5222 numMatch = 0; 5223 for (int i=0; i<permissions.length; i++) { 5224 if (tmp[i]) { 5225 pi.requestedPermissions[numMatch] = permissions[i]; 5226 numMatch++; 5227 } 5228 } 5229 } 5230 } 5231 list.add(pi); 5232 } 5233 } 5234 5235 @Override 5236 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5237 String[] permissions, int flags, int userId) { 5238 if (!sUserManager.exists(userId)) return null; 5239 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5240 5241 // writer 5242 synchronized (mPackages) { 5243 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5244 boolean[] tmpBools = new boolean[permissions.length]; 5245 if (listUninstalled) { 5246 for (PackageSetting ps : mSettings.mPackages.values()) { 5247 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5248 } 5249 } else { 5250 for (PackageParser.Package pkg : mPackages.values()) { 5251 PackageSetting ps = (PackageSetting)pkg.mExtras; 5252 if (ps != null) { 5253 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5254 userId); 5255 } 5256 } 5257 } 5258 5259 return new ParceledListSlice<PackageInfo>(list); 5260 } 5261 } 5262 5263 @Override 5264 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5265 if (!sUserManager.exists(userId)) return null; 5266 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5267 5268 // writer 5269 synchronized (mPackages) { 5270 ArrayList<ApplicationInfo> list; 5271 if (listUninstalled) { 5272 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5273 for (PackageSetting ps : mSettings.mPackages.values()) { 5274 ApplicationInfo ai; 5275 if (ps.pkg != null) { 5276 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5277 ps.readUserState(userId), userId); 5278 } else { 5279 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5280 } 5281 if (ai != null) { 5282 list.add(ai); 5283 } 5284 } 5285 } else { 5286 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5287 for (PackageParser.Package p : mPackages.values()) { 5288 if (p.mExtras != null) { 5289 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5290 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5291 if (ai != null) { 5292 list.add(ai); 5293 } 5294 } 5295 } 5296 } 5297 5298 return new ParceledListSlice<ApplicationInfo>(list); 5299 } 5300 } 5301 5302 public List<ApplicationInfo> getPersistentApplications(int flags) { 5303 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5304 5305 // reader 5306 synchronized (mPackages) { 5307 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5308 final int userId = UserHandle.getCallingUserId(); 5309 while (i.hasNext()) { 5310 final PackageParser.Package p = i.next(); 5311 if (p.applicationInfo != null 5312 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5313 && (!mSafeMode || isSystemApp(p))) { 5314 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5315 if (ps != null) { 5316 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5317 ps.readUserState(userId), userId); 5318 if (ai != null) { 5319 finalList.add(ai); 5320 } 5321 } 5322 } 5323 } 5324 } 5325 5326 return finalList; 5327 } 5328 5329 @Override 5330 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5331 if (!sUserManager.exists(userId)) return null; 5332 // reader 5333 synchronized (mPackages) { 5334 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5335 PackageSetting ps = provider != null 5336 ? mSettings.mPackages.get(provider.owner.packageName) 5337 : null; 5338 return ps != null 5339 && mSettings.isEnabledLPr(provider.info, flags, userId) 5340 && (!mSafeMode || (provider.info.applicationInfo.flags 5341 &ApplicationInfo.FLAG_SYSTEM) != 0) 5342 ? PackageParser.generateProviderInfo(provider, flags, 5343 ps.readUserState(userId), userId) 5344 : null; 5345 } 5346 } 5347 5348 /** 5349 * @deprecated 5350 */ 5351 @Deprecated 5352 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5353 // reader 5354 synchronized (mPackages) { 5355 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5356 .entrySet().iterator(); 5357 final int userId = UserHandle.getCallingUserId(); 5358 while (i.hasNext()) { 5359 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5360 PackageParser.Provider p = entry.getValue(); 5361 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5362 5363 if (ps != null && p.syncable 5364 && (!mSafeMode || (p.info.applicationInfo.flags 5365 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5366 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5367 ps.readUserState(userId), userId); 5368 if (info != null) { 5369 outNames.add(entry.getKey()); 5370 outInfo.add(info); 5371 } 5372 } 5373 } 5374 } 5375 } 5376 5377 @Override 5378 public List<ProviderInfo> queryContentProviders(String processName, 5379 int uid, int flags) { 5380 ArrayList<ProviderInfo> finalList = null; 5381 // reader 5382 synchronized (mPackages) { 5383 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5384 final int userId = processName != null ? 5385 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5386 while (i.hasNext()) { 5387 final PackageParser.Provider p = i.next(); 5388 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5389 if (ps != null && p.info.authority != null 5390 && (processName == null 5391 || (p.info.processName.equals(processName) 5392 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5393 && mSettings.isEnabledLPr(p.info, flags, userId) 5394 && (!mSafeMode 5395 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5396 if (finalList == null) { 5397 finalList = new ArrayList<ProviderInfo>(3); 5398 } 5399 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5400 ps.readUserState(userId), userId); 5401 if (info != null) { 5402 finalList.add(info); 5403 } 5404 } 5405 } 5406 } 5407 5408 if (finalList != null) { 5409 Collections.sort(finalList, mProviderInitOrderSorter); 5410 } 5411 5412 return finalList; 5413 } 5414 5415 @Override 5416 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5417 int flags) { 5418 // reader 5419 synchronized (mPackages) { 5420 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5421 return PackageParser.generateInstrumentationInfo(i, flags); 5422 } 5423 } 5424 5425 @Override 5426 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5427 int flags) { 5428 ArrayList<InstrumentationInfo> finalList = 5429 new ArrayList<InstrumentationInfo>(); 5430 5431 // reader 5432 synchronized (mPackages) { 5433 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5434 while (i.hasNext()) { 5435 final PackageParser.Instrumentation p = i.next(); 5436 if (targetPackage == null 5437 || targetPackage.equals(p.info.targetPackage)) { 5438 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5439 flags); 5440 if (ii != null) { 5441 finalList.add(ii); 5442 } 5443 } 5444 } 5445 } 5446 5447 return finalList; 5448 } 5449 5450 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5451 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5452 if (overlays == null) { 5453 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5454 return; 5455 } 5456 for (PackageParser.Package opkg : overlays.values()) { 5457 // Not much to do if idmap fails: we already logged the error 5458 // and we certainly don't want to abort installation of pkg simply 5459 // because an overlay didn't fit properly. For these reasons, 5460 // ignore the return value of createIdmapForPackagePairLI. 5461 createIdmapForPackagePairLI(pkg, opkg); 5462 } 5463 } 5464 5465 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5466 PackageParser.Package opkg) { 5467 if (!opkg.mTrustedOverlay) { 5468 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5469 opkg.baseCodePath + ": overlay not trusted"); 5470 return false; 5471 } 5472 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5473 if (overlaySet == null) { 5474 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5475 opkg.baseCodePath + " but target package has no known overlays"); 5476 return false; 5477 } 5478 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5479 // TODO: generate idmap for split APKs 5480 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5481 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5482 + opkg.baseCodePath); 5483 return false; 5484 } 5485 PackageParser.Package[] overlayArray = 5486 overlaySet.values().toArray(new PackageParser.Package[0]); 5487 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5488 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5489 return p1.mOverlayPriority - p2.mOverlayPriority; 5490 } 5491 }; 5492 Arrays.sort(overlayArray, cmp); 5493 5494 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5495 int i = 0; 5496 for (PackageParser.Package p : overlayArray) { 5497 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5498 } 5499 return true; 5500 } 5501 5502 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5503 final File[] files = dir.listFiles(); 5504 if (ArrayUtils.isEmpty(files)) { 5505 Log.d(TAG, "No files in app dir " + dir); 5506 return; 5507 } 5508 5509 if (DEBUG_PACKAGE_SCANNING) { 5510 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5511 + " flags=0x" + Integer.toHexString(parseFlags)); 5512 } 5513 5514 for (File file : files) { 5515 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5516 && !PackageInstallerService.isStageName(file.getName()); 5517 if (!isPackage) { 5518 // Ignore entries which are not packages 5519 continue; 5520 } 5521 try { 5522 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5523 scanFlags, currentTime, null); 5524 } catch (PackageManagerException e) { 5525 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5526 5527 // Delete invalid userdata apps 5528 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5529 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5530 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5531 if (file.isDirectory()) { 5532 mInstaller.rmPackageDir(file.getAbsolutePath()); 5533 } else { 5534 file.delete(); 5535 } 5536 } 5537 } 5538 } 5539 } 5540 5541 private static File getSettingsProblemFile() { 5542 File dataDir = Environment.getDataDirectory(); 5543 File systemDir = new File(dataDir, "system"); 5544 File fname = new File(systemDir, "uiderrors.txt"); 5545 return fname; 5546 } 5547 5548 static void reportSettingsProblem(int priority, String msg) { 5549 logCriticalInfo(priority, msg); 5550 } 5551 5552 static void logCriticalInfo(int priority, String msg) { 5553 Slog.println(priority, TAG, msg); 5554 EventLogTags.writePmCriticalInfo(msg); 5555 try { 5556 File fname = getSettingsProblemFile(); 5557 FileOutputStream out = new FileOutputStream(fname, true); 5558 PrintWriter pw = new FastPrintWriter(out); 5559 SimpleDateFormat formatter = new SimpleDateFormat(); 5560 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5561 pw.println(dateString + ": " + msg); 5562 pw.close(); 5563 FileUtils.setPermissions( 5564 fname.toString(), 5565 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5566 -1, -1); 5567 } catch (java.io.IOException e) { 5568 } 5569 } 5570 5571 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5572 PackageParser.Package pkg, File srcFile, int parseFlags) 5573 throws PackageManagerException { 5574 if (ps != null 5575 && ps.codePath.equals(srcFile) 5576 && ps.timeStamp == srcFile.lastModified() 5577 && !isCompatSignatureUpdateNeeded(pkg) 5578 && !isRecoverSignatureUpdateNeeded(pkg)) { 5579 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5580 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5581 ArraySet<PublicKey> signingKs; 5582 synchronized (mPackages) { 5583 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5584 } 5585 if (ps.signatures.mSignatures != null 5586 && ps.signatures.mSignatures.length != 0 5587 && signingKs != null) { 5588 // Optimization: reuse the existing cached certificates 5589 // if the package appears to be unchanged. 5590 pkg.mSignatures = ps.signatures.mSignatures; 5591 pkg.mSigningKeys = signingKs; 5592 return; 5593 } 5594 5595 Slog.w(TAG, "PackageSetting for " + ps.name 5596 + " is missing signatures. Collecting certs again to recover them."); 5597 } else { 5598 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5599 } 5600 5601 try { 5602 pp.collectCertificates(pkg, parseFlags); 5603 pp.collectManifestDigest(pkg); 5604 } catch (PackageParserException e) { 5605 throw PackageManagerException.from(e); 5606 } 5607 } 5608 5609 /* 5610 * Scan a package and return the newly parsed package. 5611 * Returns null in case of errors and the error code is stored in mLastScanError 5612 */ 5613 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5614 long currentTime, UserHandle user) throws PackageManagerException { 5615 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5616 parseFlags |= mDefParseFlags; 5617 PackageParser pp = new PackageParser(); 5618 pp.setSeparateProcesses(mSeparateProcesses); 5619 pp.setOnlyCoreApps(mOnlyCore); 5620 pp.setDisplayMetrics(mMetrics); 5621 5622 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5623 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5624 } 5625 5626 final PackageParser.Package pkg; 5627 try { 5628 pkg = pp.parsePackage(scanFile, parseFlags); 5629 } catch (PackageParserException e) { 5630 throw PackageManagerException.from(e); 5631 } 5632 5633 PackageSetting ps = null; 5634 PackageSetting updatedPkg; 5635 // reader 5636 synchronized (mPackages) { 5637 // Look to see if we already know about this package. 5638 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5639 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5640 // This package has been renamed to its original name. Let's 5641 // use that. 5642 ps = mSettings.peekPackageLPr(oldName); 5643 } 5644 // If there was no original package, see one for the real package name. 5645 if (ps == null) { 5646 ps = mSettings.peekPackageLPr(pkg.packageName); 5647 } 5648 // Check to see if this package could be hiding/updating a system 5649 // package. Must look for it either under the original or real 5650 // package name depending on our state. 5651 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5652 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5653 } 5654 boolean updatedPkgBetter = false; 5655 // First check if this is a system package that may involve an update 5656 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5657 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5658 // it needs to drop FLAG_PRIVILEGED. 5659 if (locationIsPrivileged(scanFile)) { 5660 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5661 } else { 5662 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5663 } 5664 5665 if (ps != null && !ps.codePath.equals(scanFile)) { 5666 // The path has changed from what was last scanned... check the 5667 // version of the new path against what we have stored to determine 5668 // what to do. 5669 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5670 if (pkg.mVersionCode <= ps.versionCode) { 5671 // The system package has been updated and the code path does not match 5672 // Ignore entry. Skip it. 5673 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5674 + " ignored: updated version " + ps.versionCode 5675 + " better than this " + pkg.mVersionCode); 5676 if (!updatedPkg.codePath.equals(scanFile)) { 5677 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5678 + ps.name + " changing from " + updatedPkg.codePathString 5679 + " to " + scanFile); 5680 updatedPkg.codePath = scanFile; 5681 updatedPkg.codePathString = scanFile.toString(); 5682 updatedPkg.resourcePath = scanFile; 5683 updatedPkg.resourcePathString = scanFile.toString(); 5684 } 5685 updatedPkg.pkg = pkg; 5686 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5687 "Package " + ps.name + " at " + scanFile 5688 + " ignored: updated version " + ps.versionCode 5689 + " better than this " + pkg.mVersionCode); 5690 } else { 5691 // The current app on the system partition is better than 5692 // what we have updated to on the data partition; switch 5693 // back to the system partition version. 5694 // At this point, its safely assumed that package installation for 5695 // apps in system partition will go through. If not there won't be a working 5696 // version of the app 5697 // writer 5698 synchronized (mPackages) { 5699 // Just remove the loaded entries from package lists. 5700 mPackages.remove(ps.name); 5701 } 5702 5703 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5704 + " reverting from " + ps.codePathString 5705 + ": new version " + pkg.mVersionCode 5706 + " better than installed " + ps.versionCode); 5707 5708 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5709 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5710 synchronized (mInstallLock) { 5711 args.cleanUpResourcesLI(); 5712 } 5713 synchronized (mPackages) { 5714 mSettings.enableSystemPackageLPw(ps.name); 5715 } 5716 updatedPkgBetter = true; 5717 } 5718 } 5719 } 5720 5721 if (updatedPkg != null) { 5722 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5723 // initially 5724 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5725 5726 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5727 // flag set initially 5728 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5729 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5730 } 5731 } 5732 5733 // Verify certificates against what was last scanned 5734 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5735 5736 /* 5737 * A new system app appeared, but we already had a non-system one of the 5738 * same name installed earlier. 5739 */ 5740 boolean shouldHideSystemApp = false; 5741 if (updatedPkg == null && ps != null 5742 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5743 /* 5744 * Check to make sure the signatures match first. If they don't, 5745 * wipe the installed application and its data. 5746 */ 5747 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5748 != PackageManager.SIGNATURE_MATCH) { 5749 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5750 + " signatures don't match existing userdata copy; removing"); 5751 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5752 ps = null; 5753 } else { 5754 /* 5755 * If the newly-added system app is an older version than the 5756 * already installed version, hide it. It will be scanned later 5757 * and re-added like an update. 5758 */ 5759 if (pkg.mVersionCode <= ps.versionCode) { 5760 shouldHideSystemApp = true; 5761 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5762 + " but new version " + pkg.mVersionCode + " better than installed " 5763 + ps.versionCode + "; hiding system"); 5764 } else { 5765 /* 5766 * The newly found system app is a newer version that the 5767 * one previously installed. Simply remove the 5768 * already-installed application and replace it with our own 5769 * while keeping the application data. 5770 */ 5771 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5772 + " reverting from " + ps.codePathString + ": new version " 5773 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5774 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5775 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5776 synchronized (mInstallLock) { 5777 args.cleanUpResourcesLI(); 5778 } 5779 } 5780 } 5781 } 5782 5783 // The apk is forward locked (not public) if its code and resources 5784 // are kept in different files. (except for app in either system or 5785 // vendor path). 5786 // TODO grab this value from PackageSettings 5787 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5788 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5789 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5790 } 5791 } 5792 5793 // TODO: extend to support forward-locked splits 5794 String resourcePath = null; 5795 String baseResourcePath = null; 5796 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5797 if (ps != null && ps.resourcePathString != null) { 5798 resourcePath = ps.resourcePathString; 5799 baseResourcePath = ps.resourcePathString; 5800 } else { 5801 // Should not happen at all. Just log an error. 5802 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5803 } 5804 } else { 5805 resourcePath = pkg.codePath; 5806 baseResourcePath = pkg.baseCodePath; 5807 } 5808 5809 // Set application objects path explicitly. 5810 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5811 pkg.applicationInfo.setCodePath(pkg.codePath); 5812 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5813 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5814 pkg.applicationInfo.setResourcePath(resourcePath); 5815 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5816 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5817 5818 // Note that we invoke the following method only if we are about to unpack an application 5819 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5820 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5821 5822 /* 5823 * If the system app should be overridden by a previously installed 5824 * data, hide the system app now and let the /data/app scan pick it up 5825 * again. 5826 */ 5827 if (shouldHideSystemApp) { 5828 synchronized (mPackages) { 5829 /* 5830 * We have to grant systems permissions before we hide, because 5831 * grantPermissions will assume the package update is trying to 5832 * expand its permissions. 5833 */ 5834 grantPermissionsLPw(pkg, true, pkg.packageName); 5835 mSettings.disableSystemPackageLPw(pkg.packageName); 5836 } 5837 } 5838 5839 return scannedPkg; 5840 } 5841 5842 private static String fixProcessName(String defProcessName, 5843 String processName, int uid) { 5844 if (processName == null) { 5845 return defProcessName; 5846 } 5847 return processName; 5848 } 5849 5850 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5851 throws PackageManagerException { 5852 if (pkgSetting.signatures.mSignatures != null) { 5853 // Already existing package. Make sure signatures match 5854 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5855 == PackageManager.SIGNATURE_MATCH; 5856 if (!match) { 5857 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5858 == PackageManager.SIGNATURE_MATCH; 5859 } 5860 if (!match) { 5861 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5862 == PackageManager.SIGNATURE_MATCH; 5863 } 5864 if (!match) { 5865 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5866 + pkg.packageName + " signatures do not match the " 5867 + "previously installed version; ignoring!"); 5868 } 5869 } 5870 5871 // Check for shared user signatures 5872 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5873 // Already existing package. Make sure signatures match 5874 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5875 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5876 if (!match) { 5877 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5878 == PackageManager.SIGNATURE_MATCH; 5879 } 5880 if (!match) { 5881 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5882 == PackageManager.SIGNATURE_MATCH; 5883 } 5884 if (!match) { 5885 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5886 "Package " + pkg.packageName 5887 + " has no signatures that match those in shared user " 5888 + pkgSetting.sharedUser.name + "; ignoring!"); 5889 } 5890 } 5891 } 5892 5893 /** 5894 * Enforces that only the system UID or root's UID can call a method exposed 5895 * via Binder. 5896 * 5897 * @param message used as message if SecurityException is thrown 5898 * @throws SecurityException if the caller is not system or root 5899 */ 5900 private static final void enforceSystemOrRoot(String message) { 5901 final int uid = Binder.getCallingUid(); 5902 if (uid != Process.SYSTEM_UID && uid != 0) { 5903 throw new SecurityException(message); 5904 } 5905 } 5906 5907 @Override 5908 public void performBootDexOpt() { 5909 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5910 5911 // Before everything else, see whether we need to fstrim. 5912 try { 5913 IMountService ms = PackageHelper.getMountService(); 5914 if (ms != null) { 5915 final boolean isUpgrade = isUpgrade(); 5916 boolean doTrim = isUpgrade; 5917 if (doTrim) { 5918 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5919 } else { 5920 final long interval = android.provider.Settings.Global.getLong( 5921 mContext.getContentResolver(), 5922 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5923 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5924 if (interval > 0) { 5925 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5926 if (timeSinceLast > interval) { 5927 doTrim = true; 5928 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5929 + "; running immediately"); 5930 } 5931 } 5932 } 5933 if (doTrim) { 5934 if (!isFirstBoot()) { 5935 try { 5936 ActivityManagerNative.getDefault().showBootMessage( 5937 mContext.getResources().getString( 5938 R.string.android_upgrading_fstrim), true); 5939 } catch (RemoteException e) { 5940 } 5941 } 5942 ms.runMaintenance(); 5943 } 5944 } else { 5945 Slog.e(TAG, "Mount service unavailable!"); 5946 } 5947 } catch (RemoteException e) { 5948 // Can't happen; MountService is local 5949 } 5950 5951 final ArraySet<PackageParser.Package> pkgs; 5952 synchronized (mPackages) { 5953 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5954 } 5955 5956 if (pkgs != null) { 5957 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5958 // in case the device runs out of space. 5959 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5960 // Give priority to core apps. 5961 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5962 PackageParser.Package pkg = it.next(); 5963 if (pkg.coreApp) { 5964 if (DEBUG_DEXOPT) { 5965 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5966 } 5967 sortedPkgs.add(pkg); 5968 it.remove(); 5969 } 5970 } 5971 // Give priority to system apps that listen for pre boot complete. 5972 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5973 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5974 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5975 PackageParser.Package pkg = it.next(); 5976 if (pkgNames.contains(pkg.packageName)) { 5977 if (DEBUG_DEXOPT) { 5978 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5979 } 5980 sortedPkgs.add(pkg); 5981 it.remove(); 5982 } 5983 } 5984 // Give priority to system apps. 5985 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5986 PackageParser.Package pkg = it.next(); 5987 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5988 if (DEBUG_DEXOPT) { 5989 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5990 } 5991 sortedPkgs.add(pkg); 5992 it.remove(); 5993 } 5994 } 5995 // Give priority to updated system apps. 5996 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5997 PackageParser.Package pkg = it.next(); 5998 if (pkg.isUpdatedSystemApp()) { 5999 if (DEBUG_DEXOPT) { 6000 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6001 } 6002 sortedPkgs.add(pkg); 6003 it.remove(); 6004 } 6005 } 6006 // Give priority to apps that listen for boot complete. 6007 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6008 pkgNames = getPackageNamesForIntent(intent); 6009 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6010 PackageParser.Package pkg = it.next(); 6011 if (pkgNames.contains(pkg.packageName)) { 6012 if (DEBUG_DEXOPT) { 6013 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6014 } 6015 sortedPkgs.add(pkg); 6016 it.remove(); 6017 } 6018 } 6019 // Filter out packages that aren't recently used. 6020 filterRecentlyUsedApps(pkgs); 6021 // Add all remaining apps. 6022 for (PackageParser.Package pkg : pkgs) { 6023 if (DEBUG_DEXOPT) { 6024 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6025 } 6026 sortedPkgs.add(pkg); 6027 } 6028 6029 // If we want to be lazy, filter everything that wasn't recently used. 6030 if (mLazyDexOpt) { 6031 filterRecentlyUsedApps(sortedPkgs); 6032 } 6033 6034 int i = 0; 6035 int total = sortedPkgs.size(); 6036 File dataDir = Environment.getDataDirectory(); 6037 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6038 if (lowThreshold == 0) { 6039 throw new IllegalStateException("Invalid low memory threshold"); 6040 } 6041 for (PackageParser.Package pkg : sortedPkgs) { 6042 long usableSpace = dataDir.getUsableSpace(); 6043 if (usableSpace < lowThreshold) { 6044 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6045 break; 6046 } 6047 performBootDexOpt(pkg, ++i, total); 6048 } 6049 } 6050 } 6051 6052 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6053 // Filter out packages that aren't recently used. 6054 // 6055 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6056 // should do a full dexopt. 6057 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6058 int total = pkgs.size(); 6059 int skipped = 0; 6060 long now = System.currentTimeMillis(); 6061 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6062 PackageParser.Package pkg = i.next(); 6063 long then = pkg.mLastPackageUsageTimeInMills; 6064 if (then + mDexOptLRUThresholdInMills < now) { 6065 if (DEBUG_DEXOPT) { 6066 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6067 ((then == 0) ? "never" : new Date(then))); 6068 } 6069 i.remove(); 6070 skipped++; 6071 } 6072 } 6073 if (DEBUG_DEXOPT) { 6074 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6075 } 6076 } 6077 } 6078 6079 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6080 List<ResolveInfo> ris = null; 6081 try { 6082 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6083 intent, null, 0, UserHandle.USER_OWNER); 6084 } catch (RemoteException e) { 6085 } 6086 ArraySet<String> pkgNames = new ArraySet<String>(); 6087 if (ris != null) { 6088 for (ResolveInfo ri : ris) { 6089 pkgNames.add(ri.activityInfo.packageName); 6090 } 6091 } 6092 return pkgNames; 6093 } 6094 6095 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6096 if (DEBUG_DEXOPT) { 6097 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6098 } 6099 if (!isFirstBoot()) { 6100 try { 6101 ActivityManagerNative.getDefault().showBootMessage( 6102 mContext.getResources().getString(R.string.android_upgrading_apk, 6103 curr, total), true); 6104 } catch (RemoteException e) { 6105 } 6106 } 6107 PackageParser.Package p = pkg; 6108 synchronized (mInstallLock) { 6109 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6110 false /* force dex */, false /* defer */, true /* include dependencies */); 6111 } 6112 } 6113 6114 @Override 6115 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6116 return performDexOpt(packageName, instructionSet, false); 6117 } 6118 6119 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6120 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6121 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6122 if (!dexopt && !updateUsage) { 6123 // We aren't going to dexopt or update usage, so bail early. 6124 return false; 6125 } 6126 PackageParser.Package p; 6127 final String targetInstructionSet; 6128 synchronized (mPackages) { 6129 p = mPackages.get(packageName); 6130 if (p == null) { 6131 return false; 6132 } 6133 if (updateUsage) { 6134 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6135 } 6136 mPackageUsage.write(false); 6137 if (!dexopt) { 6138 // We aren't going to dexopt, so bail early. 6139 return false; 6140 } 6141 6142 targetInstructionSet = instructionSet != null ? instructionSet : 6143 getPrimaryInstructionSet(p.applicationInfo); 6144 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6145 return false; 6146 } 6147 } 6148 6149 synchronized (mInstallLock) { 6150 final String[] instructionSets = new String[] { targetInstructionSet }; 6151 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6152 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6153 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6154 } 6155 } 6156 6157 public ArraySet<String> getPackagesThatNeedDexOpt() { 6158 ArraySet<String> pkgs = null; 6159 synchronized (mPackages) { 6160 for (PackageParser.Package p : mPackages.values()) { 6161 if (DEBUG_DEXOPT) { 6162 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6163 } 6164 if (!p.mDexOptPerformed.isEmpty()) { 6165 continue; 6166 } 6167 if (pkgs == null) { 6168 pkgs = new ArraySet<String>(); 6169 } 6170 pkgs.add(p.packageName); 6171 } 6172 } 6173 return pkgs; 6174 } 6175 6176 public void shutdown() { 6177 mPackageUsage.write(true); 6178 } 6179 6180 @Override 6181 public void forceDexOpt(String packageName) { 6182 enforceSystemOrRoot("forceDexOpt"); 6183 6184 PackageParser.Package pkg; 6185 synchronized (mPackages) { 6186 pkg = mPackages.get(packageName); 6187 if (pkg == null) { 6188 throw new IllegalArgumentException("Missing package: " + packageName); 6189 } 6190 } 6191 6192 synchronized (mInstallLock) { 6193 final String[] instructionSets = new String[] { 6194 getPrimaryInstructionSet(pkg.applicationInfo) }; 6195 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6196 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6197 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6198 throw new IllegalStateException("Failed to dexopt: " + res); 6199 } 6200 } 6201 } 6202 6203 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6204 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6205 Slog.w(TAG, "Unable to update from " + oldPkg.name 6206 + " to " + newPkg.packageName 6207 + ": old package not in system partition"); 6208 return false; 6209 } else if (mPackages.get(oldPkg.name) != null) { 6210 Slog.w(TAG, "Unable to update from " + oldPkg.name 6211 + " to " + newPkg.packageName 6212 + ": old package still exists"); 6213 return false; 6214 } 6215 return true; 6216 } 6217 6218 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6219 int[] users = sUserManager.getUserIds(); 6220 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6221 if (res < 0) { 6222 return res; 6223 } 6224 for (int user : users) { 6225 if (user != 0) { 6226 res = mInstaller.createUserData(volumeUuid, packageName, 6227 UserHandle.getUid(user, uid), user, seinfo); 6228 if (res < 0) { 6229 return res; 6230 } 6231 } 6232 } 6233 return res; 6234 } 6235 6236 private int removeDataDirsLI(String volumeUuid, String packageName) { 6237 int[] users = sUserManager.getUserIds(); 6238 int res = 0; 6239 for (int user : users) { 6240 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6241 if (resInner < 0) { 6242 res = resInner; 6243 } 6244 } 6245 6246 return res; 6247 } 6248 6249 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6250 int[] users = sUserManager.getUserIds(); 6251 int res = 0; 6252 for (int user : users) { 6253 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6254 if (resInner < 0) { 6255 res = resInner; 6256 } 6257 } 6258 return res; 6259 } 6260 6261 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6262 PackageParser.Package changingLib) { 6263 if (file.path != null) { 6264 usesLibraryFiles.add(file.path); 6265 return; 6266 } 6267 PackageParser.Package p = mPackages.get(file.apk); 6268 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6269 // If we are doing this while in the middle of updating a library apk, 6270 // then we need to make sure to use that new apk for determining the 6271 // dependencies here. (We haven't yet finished committing the new apk 6272 // to the package manager state.) 6273 if (p == null || p.packageName.equals(changingLib.packageName)) { 6274 p = changingLib; 6275 } 6276 } 6277 if (p != null) { 6278 usesLibraryFiles.addAll(p.getAllCodePaths()); 6279 } 6280 } 6281 6282 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6283 PackageParser.Package changingLib) throws PackageManagerException { 6284 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6285 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6286 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6287 for (int i=0; i<N; i++) { 6288 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6289 if (file == null) { 6290 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6291 "Package " + pkg.packageName + " requires unavailable shared library " 6292 + pkg.usesLibraries.get(i) + "; failing!"); 6293 } 6294 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6295 } 6296 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6297 for (int i=0; i<N; i++) { 6298 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6299 if (file == null) { 6300 Slog.w(TAG, "Package " + pkg.packageName 6301 + " desires unavailable shared library " 6302 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6303 } else { 6304 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6305 } 6306 } 6307 N = usesLibraryFiles.size(); 6308 if (N > 0) { 6309 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6310 } else { 6311 pkg.usesLibraryFiles = null; 6312 } 6313 } 6314 } 6315 6316 private static boolean hasString(List<String> list, List<String> which) { 6317 if (list == null) { 6318 return false; 6319 } 6320 for (int i=list.size()-1; i>=0; i--) { 6321 for (int j=which.size()-1; j>=0; j--) { 6322 if (which.get(j).equals(list.get(i))) { 6323 return true; 6324 } 6325 } 6326 } 6327 return false; 6328 } 6329 6330 private void updateAllSharedLibrariesLPw() { 6331 for (PackageParser.Package pkg : mPackages.values()) { 6332 try { 6333 updateSharedLibrariesLPw(pkg, null); 6334 } catch (PackageManagerException e) { 6335 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6336 } 6337 } 6338 } 6339 6340 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6341 PackageParser.Package changingPkg) { 6342 ArrayList<PackageParser.Package> res = null; 6343 for (PackageParser.Package pkg : mPackages.values()) { 6344 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6345 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6346 if (res == null) { 6347 res = new ArrayList<PackageParser.Package>(); 6348 } 6349 res.add(pkg); 6350 try { 6351 updateSharedLibrariesLPw(pkg, changingPkg); 6352 } catch (PackageManagerException e) { 6353 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6354 } 6355 } 6356 } 6357 return res; 6358 } 6359 6360 /** 6361 * Derive the value of the {@code cpuAbiOverride} based on the provided 6362 * value and an optional stored value from the package settings. 6363 */ 6364 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6365 String cpuAbiOverride = null; 6366 6367 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6368 cpuAbiOverride = null; 6369 } else if (abiOverride != null) { 6370 cpuAbiOverride = abiOverride; 6371 } else if (settings != null) { 6372 cpuAbiOverride = settings.cpuAbiOverrideString; 6373 } 6374 6375 return cpuAbiOverride; 6376 } 6377 6378 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6379 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6380 boolean success = false; 6381 try { 6382 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6383 currentTime, user); 6384 success = true; 6385 return res; 6386 } finally { 6387 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6388 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6389 } 6390 } 6391 } 6392 6393 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6394 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6395 final File scanFile = new File(pkg.codePath); 6396 if (pkg.applicationInfo.getCodePath() == null || 6397 pkg.applicationInfo.getResourcePath() == null) { 6398 // Bail out. The resource and code paths haven't been set. 6399 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6400 "Code and resource paths haven't been set correctly"); 6401 } 6402 6403 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6404 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6405 } else { 6406 // Only allow system apps to be flagged as core apps. 6407 pkg.coreApp = false; 6408 } 6409 6410 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6411 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6412 } 6413 6414 if (mCustomResolverComponentName != null && 6415 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6416 setUpCustomResolverActivity(pkg); 6417 } 6418 6419 if (pkg.packageName.equals("android")) { 6420 synchronized (mPackages) { 6421 if (mAndroidApplication != null) { 6422 Slog.w(TAG, "*************************************************"); 6423 Slog.w(TAG, "Core android package being redefined. Skipping."); 6424 Slog.w(TAG, " file=" + scanFile); 6425 Slog.w(TAG, "*************************************************"); 6426 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6427 "Core android package being redefined. Skipping."); 6428 } 6429 6430 // Set up information for our fall-back user intent resolution activity. 6431 mPlatformPackage = pkg; 6432 pkg.mVersionCode = mSdkVersion; 6433 mAndroidApplication = pkg.applicationInfo; 6434 6435 if (!mResolverReplaced) { 6436 mResolveActivity.applicationInfo = mAndroidApplication; 6437 mResolveActivity.name = ResolverActivity.class.getName(); 6438 mResolveActivity.packageName = mAndroidApplication.packageName; 6439 mResolveActivity.processName = "system:ui"; 6440 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6441 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6442 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6443 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6444 mResolveActivity.exported = true; 6445 mResolveActivity.enabled = true; 6446 mResolveInfo.activityInfo = mResolveActivity; 6447 mResolveInfo.priority = 0; 6448 mResolveInfo.preferredOrder = 0; 6449 mResolveInfo.match = 0; 6450 mResolveComponentName = new ComponentName( 6451 mAndroidApplication.packageName, mResolveActivity.name); 6452 } 6453 } 6454 } 6455 6456 if (DEBUG_PACKAGE_SCANNING) { 6457 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6458 Log.d(TAG, "Scanning package " + pkg.packageName); 6459 } 6460 6461 if (mPackages.containsKey(pkg.packageName) 6462 || mSharedLibraries.containsKey(pkg.packageName)) { 6463 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6464 "Application package " + pkg.packageName 6465 + " already installed. Skipping duplicate."); 6466 } 6467 6468 // If we're only installing presumed-existing packages, require that the 6469 // scanned APK is both already known and at the path previously established 6470 // for it. Previously unknown packages we pick up normally, but if we have an 6471 // a priori expectation about this package's install presence, enforce it. 6472 // With a singular exception for new system packages. When an OTA contains 6473 // a new system package, we allow the codepath to change from a system location 6474 // to the user-installed location. If we don't allow this change, any newer, 6475 // user-installed version of the application will be ignored. 6476 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6477 if (mExpectingBetter.containsKey(pkg.packageName)) { 6478 logCriticalInfo(Log.WARN, 6479 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6480 } else { 6481 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6482 if (known != null) { 6483 if (DEBUG_PACKAGE_SCANNING) { 6484 Log.d(TAG, "Examining " + pkg.codePath 6485 + " and requiring known paths " + known.codePathString 6486 + " & " + known.resourcePathString); 6487 } 6488 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6489 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6490 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6491 "Application package " + pkg.packageName 6492 + " found at " + pkg.applicationInfo.getCodePath() 6493 + " but expected at " + known.codePathString + "; ignoring."); 6494 } 6495 } 6496 } 6497 } 6498 6499 // Initialize package source and resource directories 6500 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6501 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6502 6503 SharedUserSetting suid = null; 6504 PackageSetting pkgSetting = null; 6505 6506 if (!isSystemApp(pkg)) { 6507 // Only system apps can use these features. 6508 pkg.mOriginalPackages = null; 6509 pkg.mRealPackage = null; 6510 pkg.mAdoptPermissions = null; 6511 } 6512 6513 // writer 6514 synchronized (mPackages) { 6515 if (pkg.mSharedUserId != null) { 6516 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6517 if (suid == null) { 6518 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6519 "Creating application package " + pkg.packageName 6520 + " for shared user failed"); 6521 } 6522 if (DEBUG_PACKAGE_SCANNING) { 6523 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6524 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6525 + "): packages=" + suid.packages); 6526 } 6527 } 6528 6529 // Check if we are renaming from an original package name. 6530 PackageSetting origPackage = null; 6531 String realName = null; 6532 if (pkg.mOriginalPackages != null) { 6533 // This package may need to be renamed to a previously 6534 // installed name. Let's check on that... 6535 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6536 if (pkg.mOriginalPackages.contains(renamed)) { 6537 // This package had originally been installed as the 6538 // original name, and we have already taken care of 6539 // transitioning to the new one. Just update the new 6540 // one to continue using the old name. 6541 realName = pkg.mRealPackage; 6542 if (!pkg.packageName.equals(renamed)) { 6543 // Callers into this function may have already taken 6544 // care of renaming the package; only do it here if 6545 // it is not already done. 6546 pkg.setPackageName(renamed); 6547 } 6548 6549 } else { 6550 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6551 if ((origPackage = mSettings.peekPackageLPr( 6552 pkg.mOriginalPackages.get(i))) != null) { 6553 // We do have the package already installed under its 6554 // original name... should we use it? 6555 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6556 // New package is not compatible with original. 6557 origPackage = null; 6558 continue; 6559 } else if (origPackage.sharedUser != null) { 6560 // Make sure uid is compatible between packages. 6561 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6562 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6563 + " to " + pkg.packageName + ": old uid " 6564 + origPackage.sharedUser.name 6565 + " differs from " + pkg.mSharedUserId); 6566 origPackage = null; 6567 continue; 6568 } 6569 } else { 6570 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6571 + pkg.packageName + " to old name " + origPackage.name); 6572 } 6573 break; 6574 } 6575 } 6576 } 6577 } 6578 6579 if (mTransferedPackages.contains(pkg.packageName)) { 6580 Slog.w(TAG, "Package " + pkg.packageName 6581 + " was transferred to another, but its .apk remains"); 6582 } 6583 6584 // Just create the setting, don't add it yet. For already existing packages 6585 // the PkgSetting exists already and doesn't have to be created. 6586 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6587 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6588 pkg.applicationInfo.primaryCpuAbi, 6589 pkg.applicationInfo.secondaryCpuAbi, 6590 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6591 user, false); 6592 if (pkgSetting == null) { 6593 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6594 "Creating application package " + pkg.packageName + " failed"); 6595 } 6596 6597 if (pkgSetting.origPackage != null) { 6598 // If we are first transitioning from an original package, 6599 // fix up the new package's name now. We need to do this after 6600 // looking up the package under its new name, so getPackageLP 6601 // can take care of fiddling things correctly. 6602 pkg.setPackageName(origPackage.name); 6603 6604 // File a report about this. 6605 String msg = "New package " + pkgSetting.realName 6606 + " renamed to replace old package " + pkgSetting.name; 6607 reportSettingsProblem(Log.WARN, msg); 6608 6609 // Make a note of it. 6610 mTransferedPackages.add(origPackage.name); 6611 6612 // No longer need to retain this. 6613 pkgSetting.origPackage = null; 6614 } 6615 6616 if (realName != null) { 6617 // Make a note of it. 6618 mTransferedPackages.add(pkg.packageName); 6619 } 6620 6621 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6622 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6623 } 6624 6625 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6626 // Check all shared libraries and map to their actual file path. 6627 // We only do this here for apps not on a system dir, because those 6628 // are the only ones that can fail an install due to this. We 6629 // will take care of the system apps by updating all of their 6630 // library paths after the scan is done. 6631 updateSharedLibrariesLPw(pkg, null); 6632 } 6633 6634 if (mFoundPolicyFile) { 6635 SELinuxMMAC.assignSeinfoValue(pkg); 6636 } 6637 6638 pkg.applicationInfo.uid = pkgSetting.appId; 6639 pkg.mExtras = pkgSetting; 6640 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6641 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6642 // We just determined the app is signed correctly, so bring 6643 // over the latest parsed certs. 6644 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6645 } else { 6646 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6647 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6648 "Package " + pkg.packageName + " upgrade keys do not match the " 6649 + "previously installed version"); 6650 } else { 6651 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6652 String msg = "System package " + pkg.packageName 6653 + " signature changed; retaining data."; 6654 reportSettingsProblem(Log.WARN, msg); 6655 } 6656 } 6657 } else { 6658 try { 6659 verifySignaturesLP(pkgSetting, pkg); 6660 // We just determined the app is signed correctly, so bring 6661 // over the latest parsed certs. 6662 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6663 } catch (PackageManagerException e) { 6664 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6665 throw e; 6666 } 6667 // The signature has changed, but this package is in the system 6668 // image... let's recover! 6669 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6670 // However... if this package is part of a shared user, but it 6671 // doesn't match the signature of the shared user, let's fail. 6672 // What this means is that you can't change the signatures 6673 // associated with an overall shared user, which doesn't seem all 6674 // that unreasonable. 6675 if (pkgSetting.sharedUser != null) { 6676 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6677 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6678 throw new PackageManagerException( 6679 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6680 "Signature mismatch for shared user : " 6681 + pkgSetting.sharedUser); 6682 } 6683 } 6684 // File a report about this. 6685 String msg = "System package " + pkg.packageName 6686 + " signature changed; retaining data."; 6687 reportSettingsProblem(Log.WARN, msg); 6688 } 6689 } 6690 // Verify that this new package doesn't have any content providers 6691 // that conflict with existing packages. Only do this if the 6692 // package isn't already installed, since we don't want to break 6693 // things that are installed. 6694 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6695 final int N = pkg.providers.size(); 6696 int i; 6697 for (i=0; i<N; i++) { 6698 PackageParser.Provider p = pkg.providers.get(i); 6699 if (p.info.authority != null) { 6700 String names[] = p.info.authority.split(";"); 6701 for (int j = 0; j < names.length; j++) { 6702 if (mProvidersByAuthority.containsKey(names[j])) { 6703 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6704 final String otherPackageName = 6705 ((other != null && other.getComponentName() != null) ? 6706 other.getComponentName().getPackageName() : "?"); 6707 throw new PackageManagerException( 6708 INSTALL_FAILED_CONFLICTING_PROVIDER, 6709 "Can't install because provider name " + names[j] 6710 + " (in package " + pkg.applicationInfo.packageName 6711 + ") is already used by " + otherPackageName); 6712 } 6713 } 6714 } 6715 } 6716 } 6717 6718 if (pkg.mAdoptPermissions != null) { 6719 // This package wants to adopt ownership of permissions from 6720 // another package. 6721 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6722 final String origName = pkg.mAdoptPermissions.get(i); 6723 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6724 if (orig != null) { 6725 if (verifyPackageUpdateLPr(orig, pkg)) { 6726 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6727 + pkg.packageName); 6728 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6729 } 6730 } 6731 } 6732 } 6733 } 6734 6735 final String pkgName = pkg.packageName; 6736 6737 final long scanFileTime = scanFile.lastModified(); 6738 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6739 pkg.applicationInfo.processName = fixProcessName( 6740 pkg.applicationInfo.packageName, 6741 pkg.applicationInfo.processName, 6742 pkg.applicationInfo.uid); 6743 6744 File dataPath; 6745 if (mPlatformPackage == pkg) { 6746 // The system package is special. 6747 dataPath = new File(Environment.getDataDirectory(), "system"); 6748 6749 pkg.applicationInfo.dataDir = dataPath.getPath(); 6750 6751 } else { 6752 // This is a normal package, need to make its data directory. 6753 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6754 UserHandle.USER_OWNER, pkg.packageName); 6755 6756 boolean uidError = false; 6757 if (dataPath.exists()) { 6758 int currentUid = 0; 6759 try { 6760 StructStat stat = Os.stat(dataPath.getPath()); 6761 currentUid = stat.st_uid; 6762 } catch (ErrnoException e) { 6763 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6764 } 6765 6766 // If we have mismatched owners for the data path, we have a problem. 6767 if (currentUid != pkg.applicationInfo.uid) { 6768 boolean recovered = false; 6769 if (currentUid == 0) { 6770 // The directory somehow became owned by root. Wow. 6771 // This is probably because the system was stopped while 6772 // installd was in the middle of messing with its libs 6773 // directory. Ask installd to fix that. 6774 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6775 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6776 if (ret >= 0) { 6777 recovered = true; 6778 String msg = "Package " + pkg.packageName 6779 + " unexpectedly changed to uid 0; recovered to " + 6780 + pkg.applicationInfo.uid; 6781 reportSettingsProblem(Log.WARN, msg); 6782 } 6783 } 6784 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6785 || (scanFlags&SCAN_BOOTING) != 0)) { 6786 // If this is a system app, we can at least delete its 6787 // current data so the application will still work. 6788 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6789 if (ret >= 0) { 6790 // TODO: Kill the processes first 6791 // Old data gone! 6792 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6793 ? "System package " : "Third party package "; 6794 String msg = prefix + pkg.packageName 6795 + " has changed from uid: " 6796 + currentUid + " to " 6797 + pkg.applicationInfo.uid + "; old data erased"; 6798 reportSettingsProblem(Log.WARN, msg); 6799 recovered = true; 6800 6801 // And now re-install the app. 6802 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6803 pkg.applicationInfo.seinfo); 6804 if (ret == -1) { 6805 // Ack should not happen! 6806 msg = prefix + pkg.packageName 6807 + " could not have data directory re-created after delete."; 6808 reportSettingsProblem(Log.WARN, msg); 6809 throw new PackageManagerException( 6810 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6811 } 6812 } 6813 if (!recovered) { 6814 mHasSystemUidErrors = true; 6815 } 6816 } else if (!recovered) { 6817 // If we allow this install to proceed, we will be broken. 6818 // Abort, abort! 6819 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6820 "scanPackageLI"); 6821 } 6822 if (!recovered) { 6823 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6824 + pkg.applicationInfo.uid + "/fs_" 6825 + currentUid; 6826 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6827 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6828 String msg = "Package " + pkg.packageName 6829 + " has mismatched uid: " 6830 + currentUid + " on disk, " 6831 + pkg.applicationInfo.uid + " in settings"; 6832 // writer 6833 synchronized (mPackages) { 6834 mSettings.mReadMessages.append(msg); 6835 mSettings.mReadMessages.append('\n'); 6836 uidError = true; 6837 if (!pkgSetting.uidError) { 6838 reportSettingsProblem(Log.ERROR, msg); 6839 } 6840 } 6841 } 6842 } 6843 pkg.applicationInfo.dataDir = dataPath.getPath(); 6844 if (mShouldRestoreconData) { 6845 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6846 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6847 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6848 } 6849 } else { 6850 if (DEBUG_PACKAGE_SCANNING) { 6851 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6852 Log.v(TAG, "Want this data dir: " + dataPath); 6853 } 6854 //invoke installer to do the actual installation 6855 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6856 pkg.applicationInfo.seinfo); 6857 if (ret < 0) { 6858 // Error from installer 6859 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6860 "Unable to create data dirs [errorCode=" + ret + "]"); 6861 } 6862 6863 if (dataPath.exists()) { 6864 pkg.applicationInfo.dataDir = dataPath.getPath(); 6865 } else { 6866 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6867 pkg.applicationInfo.dataDir = null; 6868 } 6869 } 6870 6871 pkgSetting.uidError = uidError; 6872 } 6873 6874 final String path = scanFile.getPath(); 6875 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6876 6877 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6878 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6879 6880 // Some system apps still use directory structure for native libraries 6881 // in which case we might end up not detecting abi solely based on apk 6882 // structure. Try to detect abi based on directory structure. 6883 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6884 pkg.applicationInfo.primaryCpuAbi == null) { 6885 setBundledAppAbisAndRoots(pkg, pkgSetting); 6886 setNativeLibraryPaths(pkg); 6887 } 6888 6889 } else { 6890 if ((scanFlags & SCAN_MOVE) != 0) { 6891 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6892 // but we already have this packages package info in the PackageSetting. We just 6893 // use that and derive the native library path based on the new codepath. 6894 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6895 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6896 } 6897 6898 // Set native library paths again. For moves, the path will be updated based on the 6899 // ABIs we've determined above. For non-moves, the path will be updated based on the 6900 // ABIs we determined during compilation, but the path will depend on the final 6901 // package path (after the rename away from the stage path). 6902 setNativeLibraryPaths(pkg); 6903 } 6904 6905 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6906 final int[] userIds = sUserManager.getUserIds(); 6907 synchronized (mInstallLock) { 6908 // Make sure all user data directories are ready to roll; we're okay 6909 // if they already exist 6910 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6911 for (int userId : userIds) { 6912 if (userId != 0) { 6913 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6914 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6915 pkg.applicationInfo.seinfo); 6916 } 6917 } 6918 } 6919 6920 // Create a native library symlink only if we have native libraries 6921 // and if the native libraries are 32 bit libraries. We do not provide 6922 // this symlink for 64 bit libraries. 6923 if (pkg.applicationInfo.primaryCpuAbi != null && 6924 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6925 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6926 for (int userId : userIds) { 6927 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6928 nativeLibPath, userId) < 0) { 6929 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6930 "Failed linking native library dir (user=" + userId + ")"); 6931 } 6932 } 6933 } 6934 } 6935 6936 // This is a special case for the "system" package, where the ABI is 6937 // dictated by the zygote configuration (and init.rc). We should keep track 6938 // of this ABI so that we can deal with "normal" applications that run under 6939 // the same UID correctly. 6940 if (mPlatformPackage == pkg) { 6941 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6942 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6943 } 6944 6945 // If there's a mismatch between the abi-override in the package setting 6946 // and the abiOverride specified for the install. Warn about this because we 6947 // would've already compiled the app without taking the package setting into 6948 // account. 6949 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6950 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6951 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6952 " for package: " + pkg.packageName); 6953 } 6954 } 6955 6956 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6957 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6958 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6959 6960 // Copy the derived override back to the parsed package, so that we can 6961 // update the package settings accordingly. 6962 pkg.cpuAbiOverride = cpuAbiOverride; 6963 6964 if (DEBUG_ABI_SELECTION) { 6965 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6966 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6967 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6968 } 6969 6970 // Push the derived path down into PackageSettings so we know what to 6971 // clean up at uninstall time. 6972 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6973 6974 if (DEBUG_ABI_SELECTION) { 6975 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6976 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6977 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6978 } 6979 6980 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6981 // We don't do this here during boot because we can do it all 6982 // at once after scanning all existing packages. 6983 // 6984 // We also do this *before* we perform dexopt on this package, so that 6985 // we can avoid redundant dexopts, and also to make sure we've got the 6986 // code and package path correct. 6987 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6988 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6989 } 6990 6991 if ((scanFlags & SCAN_NO_DEX) == 0) { 6992 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6993 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6994 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6995 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6996 } 6997 } 6998 if (mFactoryTest && pkg.requestedPermissions.contains( 6999 android.Manifest.permission.FACTORY_TEST)) { 7000 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7001 } 7002 7003 ArrayList<PackageParser.Package> clientLibPkgs = null; 7004 7005 // writer 7006 synchronized (mPackages) { 7007 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7008 // Only system apps can add new shared libraries. 7009 if (pkg.libraryNames != null) { 7010 for (int i=0; i<pkg.libraryNames.size(); i++) { 7011 String name = pkg.libraryNames.get(i); 7012 boolean allowed = false; 7013 if (pkg.isUpdatedSystemApp()) { 7014 // New library entries can only be added through the 7015 // system image. This is important to get rid of a lot 7016 // of nasty edge cases: for example if we allowed a non- 7017 // system update of the app to add a library, then uninstalling 7018 // the update would make the library go away, and assumptions 7019 // we made such as through app install filtering would now 7020 // have allowed apps on the device which aren't compatible 7021 // with it. Better to just have the restriction here, be 7022 // conservative, and create many fewer cases that can negatively 7023 // impact the user experience. 7024 final PackageSetting sysPs = mSettings 7025 .getDisabledSystemPkgLPr(pkg.packageName); 7026 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7027 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7028 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7029 allowed = true; 7030 allowed = true; 7031 break; 7032 } 7033 } 7034 } 7035 } else { 7036 allowed = true; 7037 } 7038 if (allowed) { 7039 if (!mSharedLibraries.containsKey(name)) { 7040 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7041 } else if (!name.equals(pkg.packageName)) { 7042 Slog.w(TAG, "Package " + pkg.packageName + " library " 7043 + name + " already exists; skipping"); 7044 } 7045 } else { 7046 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7047 + name + " that is not declared on system image; skipping"); 7048 } 7049 } 7050 if ((scanFlags&SCAN_BOOTING) == 0) { 7051 // If we are not booting, we need to update any applications 7052 // that are clients of our shared library. If we are booting, 7053 // this will all be done once the scan is complete. 7054 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7055 } 7056 } 7057 } 7058 } 7059 7060 // We also need to dexopt any apps that are dependent on this library. Note that 7061 // if these fail, we should abort the install since installing the library will 7062 // result in some apps being broken. 7063 if (clientLibPkgs != null) { 7064 if ((scanFlags & SCAN_NO_DEX) == 0) { 7065 for (int i = 0; i < clientLibPkgs.size(); i++) { 7066 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7067 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7068 null /* instruction sets */, forceDex, 7069 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7070 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7071 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7072 "scanPackageLI failed to dexopt clientLibPkgs"); 7073 } 7074 } 7075 } 7076 } 7077 7078 // Also need to kill any apps that are dependent on the library. 7079 if (clientLibPkgs != null) { 7080 for (int i=0; i<clientLibPkgs.size(); i++) { 7081 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7082 killApplication(clientPkg.applicationInfo.packageName, 7083 clientPkg.applicationInfo.uid, "update lib"); 7084 } 7085 } 7086 7087 // Make sure we're not adding any bogus keyset info 7088 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7089 ksms.assertScannedPackageValid(pkg); 7090 7091 // writer 7092 synchronized (mPackages) { 7093 // We don't expect installation to fail beyond this point 7094 7095 // Add the new setting to mSettings 7096 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7097 // Add the new setting to mPackages 7098 mPackages.put(pkg.applicationInfo.packageName, pkg); 7099 // Make sure we don't accidentally delete its data. 7100 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7101 while (iter.hasNext()) { 7102 PackageCleanItem item = iter.next(); 7103 if (pkgName.equals(item.packageName)) { 7104 iter.remove(); 7105 } 7106 } 7107 7108 // Take care of first install / last update times. 7109 if (currentTime != 0) { 7110 if (pkgSetting.firstInstallTime == 0) { 7111 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7112 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7113 pkgSetting.lastUpdateTime = currentTime; 7114 } 7115 } else if (pkgSetting.firstInstallTime == 0) { 7116 // We need *something*. Take time time stamp of the file. 7117 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7118 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7119 if (scanFileTime != pkgSetting.timeStamp) { 7120 // A package on the system image has changed; consider this 7121 // to be an update. 7122 pkgSetting.lastUpdateTime = scanFileTime; 7123 } 7124 } 7125 7126 // Add the package's KeySets to the global KeySetManagerService 7127 ksms.addScannedPackageLPw(pkg); 7128 7129 int N = pkg.providers.size(); 7130 StringBuilder r = null; 7131 int i; 7132 for (i=0; i<N; i++) { 7133 PackageParser.Provider p = pkg.providers.get(i); 7134 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7135 p.info.processName, pkg.applicationInfo.uid); 7136 mProviders.addProvider(p); 7137 p.syncable = p.info.isSyncable; 7138 if (p.info.authority != null) { 7139 String names[] = p.info.authority.split(";"); 7140 p.info.authority = null; 7141 for (int j = 0; j < names.length; j++) { 7142 if (j == 1 && p.syncable) { 7143 // We only want the first authority for a provider to possibly be 7144 // syncable, so if we already added this provider using a different 7145 // authority clear the syncable flag. We copy the provider before 7146 // changing it because the mProviders object contains a reference 7147 // to a provider that we don't want to change. 7148 // Only do this for the second authority since the resulting provider 7149 // object can be the same for all future authorities for this provider. 7150 p = new PackageParser.Provider(p); 7151 p.syncable = false; 7152 } 7153 if (!mProvidersByAuthority.containsKey(names[j])) { 7154 mProvidersByAuthority.put(names[j], p); 7155 if (p.info.authority == null) { 7156 p.info.authority = names[j]; 7157 } else { 7158 p.info.authority = p.info.authority + ";" + names[j]; 7159 } 7160 if (DEBUG_PACKAGE_SCANNING) { 7161 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7162 Log.d(TAG, "Registered content provider: " + names[j] 7163 + ", className = " + p.info.name + ", isSyncable = " 7164 + p.info.isSyncable); 7165 } 7166 } else { 7167 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7168 Slog.w(TAG, "Skipping provider name " + names[j] + 7169 " (in package " + pkg.applicationInfo.packageName + 7170 "): name already used by " 7171 + ((other != null && other.getComponentName() != null) 7172 ? other.getComponentName().getPackageName() : "?")); 7173 } 7174 } 7175 } 7176 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7177 if (r == null) { 7178 r = new StringBuilder(256); 7179 } else { 7180 r.append(' '); 7181 } 7182 r.append(p.info.name); 7183 } 7184 } 7185 if (r != null) { 7186 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7187 } 7188 7189 N = pkg.services.size(); 7190 r = null; 7191 for (i=0; i<N; i++) { 7192 PackageParser.Service s = pkg.services.get(i); 7193 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7194 s.info.processName, pkg.applicationInfo.uid); 7195 mServices.addService(s); 7196 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7197 if (r == null) { 7198 r = new StringBuilder(256); 7199 } else { 7200 r.append(' '); 7201 } 7202 r.append(s.info.name); 7203 } 7204 } 7205 if (r != null) { 7206 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7207 } 7208 7209 N = pkg.receivers.size(); 7210 r = null; 7211 for (i=0; i<N; i++) { 7212 PackageParser.Activity a = pkg.receivers.get(i); 7213 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7214 a.info.processName, pkg.applicationInfo.uid); 7215 mReceivers.addActivity(a, "receiver"); 7216 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7217 if (r == null) { 7218 r = new StringBuilder(256); 7219 } else { 7220 r.append(' '); 7221 } 7222 r.append(a.info.name); 7223 } 7224 } 7225 if (r != null) { 7226 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7227 } 7228 7229 N = pkg.activities.size(); 7230 r = null; 7231 for (i=0; i<N; i++) { 7232 PackageParser.Activity a = pkg.activities.get(i); 7233 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7234 a.info.processName, pkg.applicationInfo.uid); 7235 mActivities.addActivity(a, "activity"); 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(a.info.name); 7243 } 7244 } 7245 if (r != null) { 7246 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7247 } 7248 7249 N = pkg.permissionGroups.size(); 7250 r = null; 7251 for (i=0; i<N; i++) { 7252 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7253 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7254 if (cur == null) { 7255 mPermissionGroups.put(pg.info.name, pg); 7256 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7257 if (r == null) { 7258 r = new StringBuilder(256); 7259 } else { 7260 r.append(' '); 7261 } 7262 r.append(pg.info.name); 7263 } 7264 } else { 7265 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7266 + pg.info.packageName + " ignored: original from " 7267 + cur.info.packageName); 7268 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7269 if (r == null) { 7270 r = new StringBuilder(256); 7271 } else { 7272 r.append(' '); 7273 } 7274 r.append("DUP:"); 7275 r.append(pg.info.name); 7276 } 7277 } 7278 } 7279 if (r != null) { 7280 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7281 } 7282 7283 N = pkg.permissions.size(); 7284 r = null; 7285 for (i=0; i<N; i++) { 7286 PackageParser.Permission p = pkg.permissions.get(i); 7287 7288 // Now that permission groups have a special meaning, we ignore permission 7289 // groups for legacy apps to prevent unexpected behavior. In particular, 7290 // permissions for one app being granted to someone just becuase they happen 7291 // to be in a group defined by another app (before this had no implications). 7292 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7293 p.group = mPermissionGroups.get(p.info.group); 7294 // Warn for a permission in an unknown group. 7295 if (p.info.group != null && p.group == null) { 7296 Slog.w(TAG, "Permission " + p.info.name + " from package " 7297 + p.info.packageName + " in an unknown group " + p.info.group); 7298 } 7299 } 7300 7301 ArrayMap<String, BasePermission> permissionMap = 7302 p.tree ? mSettings.mPermissionTrees 7303 : mSettings.mPermissions; 7304 BasePermission bp = permissionMap.get(p.info.name); 7305 7306 // Allow system apps to redefine non-system permissions 7307 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7308 final boolean currentOwnerIsSystem = (bp.perm != null 7309 && isSystemApp(bp.perm.owner)); 7310 if (isSystemApp(p.owner)) { 7311 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7312 // It's a built-in permission and no owner, take ownership now 7313 bp.packageSetting = pkgSetting; 7314 bp.perm = p; 7315 bp.uid = pkg.applicationInfo.uid; 7316 bp.sourcePackage = p.info.packageName; 7317 } else if (!currentOwnerIsSystem) { 7318 String msg = "New decl " + p.owner + " of permission " 7319 + p.info.name + " is system; overriding " + bp.sourcePackage; 7320 reportSettingsProblem(Log.WARN, msg); 7321 bp = null; 7322 } 7323 } 7324 } 7325 7326 if (bp == null) { 7327 bp = new BasePermission(p.info.name, p.info.packageName, 7328 BasePermission.TYPE_NORMAL); 7329 permissionMap.put(p.info.name, bp); 7330 } 7331 7332 if (bp.perm == null) { 7333 if (bp.sourcePackage == null 7334 || bp.sourcePackage.equals(p.info.packageName)) { 7335 BasePermission tree = findPermissionTreeLP(p.info.name); 7336 if (tree == null 7337 || tree.sourcePackage.equals(p.info.packageName)) { 7338 bp.packageSetting = pkgSetting; 7339 bp.perm = p; 7340 bp.uid = pkg.applicationInfo.uid; 7341 bp.sourcePackage = p.info.packageName; 7342 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7343 if (r == null) { 7344 r = new StringBuilder(256); 7345 } else { 7346 r.append(' '); 7347 } 7348 r.append(p.info.name); 7349 } 7350 } else { 7351 Slog.w(TAG, "Permission " + p.info.name + " from package " 7352 + p.info.packageName + " ignored: base tree " 7353 + tree.name + " is from package " 7354 + tree.sourcePackage); 7355 } 7356 } else { 7357 Slog.w(TAG, "Permission " + p.info.name + " from package " 7358 + p.info.packageName + " ignored: original from " 7359 + bp.sourcePackage); 7360 } 7361 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7362 if (r == null) { 7363 r = new StringBuilder(256); 7364 } else { 7365 r.append(' '); 7366 } 7367 r.append("DUP:"); 7368 r.append(p.info.name); 7369 } 7370 if (bp.perm == p) { 7371 bp.protectionLevel = p.info.protectionLevel; 7372 } 7373 } 7374 7375 if (r != null) { 7376 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7377 } 7378 7379 N = pkg.instrumentation.size(); 7380 r = null; 7381 for (i=0; i<N; i++) { 7382 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7383 a.info.packageName = pkg.applicationInfo.packageName; 7384 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7385 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7386 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7387 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7388 a.info.dataDir = pkg.applicationInfo.dataDir; 7389 7390 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7391 // need other information about the application, like the ABI and what not ? 7392 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7393 mInstrumentation.put(a.getComponentName(), a); 7394 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7395 if (r == null) { 7396 r = new StringBuilder(256); 7397 } else { 7398 r.append(' '); 7399 } 7400 r.append(a.info.name); 7401 } 7402 } 7403 if (r != null) { 7404 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7405 } 7406 7407 if (pkg.protectedBroadcasts != null) { 7408 N = pkg.protectedBroadcasts.size(); 7409 for (i=0; i<N; i++) { 7410 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7411 } 7412 } 7413 7414 pkgSetting.setTimeStamp(scanFileTime); 7415 7416 // Create idmap files for pairs of (packages, overlay packages). 7417 // Note: "android", ie framework-res.apk, is handled by native layers. 7418 if (pkg.mOverlayTarget != null) { 7419 // This is an overlay package. 7420 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7421 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7422 mOverlays.put(pkg.mOverlayTarget, 7423 new ArrayMap<String, PackageParser.Package>()); 7424 } 7425 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7426 map.put(pkg.packageName, pkg); 7427 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7428 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7429 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7430 "scanPackageLI failed to createIdmap"); 7431 } 7432 } 7433 } else if (mOverlays.containsKey(pkg.packageName) && 7434 !pkg.packageName.equals("android")) { 7435 // This is a regular package, with one or more known overlay packages. 7436 createIdmapsForPackageLI(pkg); 7437 } 7438 } 7439 7440 return pkg; 7441 } 7442 7443 /** 7444 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7445 * is derived purely on the basis of the contents of {@code scanFile} and 7446 * {@code cpuAbiOverride}. 7447 * 7448 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7449 */ 7450 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7451 String cpuAbiOverride, boolean extractLibs) 7452 throws PackageManagerException { 7453 // TODO: We can probably be smarter about this stuff. For installed apps, 7454 // we can calculate this information at install time once and for all. For 7455 // system apps, we can probably assume that this information doesn't change 7456 // after the first boot scan. As things stand, we do lots of unnecessary work. 7457 7458 // Give ourselves some initial paths; we'll come back for another 7459 // pass once we've determined ABI below. 7460 setNativeLibraryPaths(pkg); 7461 7462 // We would never need to extract libs for forward-locked and external packages, 7463 // since the container service will do it for us. We shouldn't attempt to 7464 // extract libs from system app when it was not updated. 7465 if (pkg.isForwardLocked() || isExternal(pkg) || 7466 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7467 extractLibs = false; 7468 } 7469 7470 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7471 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7472 7473 NativeLibraryHelper.Handle handle = null; 7474 try { 7475 handle = NativeLibraryHelper.Handle.create(scanFile); 7476 // TODO(multiArch): This can be null for apps that didn't go through the 7477 // usual installation process. We can calculate it again, like we 7478 // do during install time. 7479 // 7480 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7481 // unnecessary. 7482 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7483 7484 // Null out the abis so that they can be recalculated. 7485 pkg.applicationInfo.primaryCpuAbi = null; 7486 pkg.applicationInfo.secondaryCpuAbi = null; 7487 if (isMultiArch(pkg.applicationInfo)) { 7488 // Warn if we've set an abiOverride for multi-lib packages.. 7489 // By definition, we need to copy both 32 and 64 bit libraries for 7490 // such packages. 7491 if (pkg.cpuAbiOverride != null 7492 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7493 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7494 } 7495 7496 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7497 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7498 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7499 if (extractLibs) { 7500 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7501 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7502 useIsaSpecificSubdirs); 7503 } else { 7504 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7505 } 7506 } 7507 7508 maybeThrowExceptionForMultiArchCopy( 7509 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7510 7511 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7512 if (extractLibs) { 7513 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7514 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7515 useIsaSpecificSubdirs); 7516 } else { 7517 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7518 } 7519 } 7520 7521 maybeThrowExceptionForMultiArchCopy( 7522 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7523 7524 if (abi64 >= 0) { 7525 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7526 } 7527 7528 if (abi32 >= 0) { 7529 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7530 if (abi64 >= 0) { 7531 pkg.applicationInfo.secondaryCpuAbi = abi; 7532 } else { 7533 pkg.applicationInfo.primaryCpuAbi = abi; 7534 } 7535 } 7536 } else { 7537 String[] abiList = (cpuAbiOverride != null) ? 7538 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7539 7540 // Enable gross and lame hacks for apps that are built with old 7541 // SDK tools. We must scan their APKs for renderscript bitcode and 7542 // not launch them if it's present. Don't bother checking on devices 7543 // that don't have 64 bit support. 7544 boolean needsRenderScriptOverride = false; 7545 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7546 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7547 abiList = Build.SUPPORTED_32_BIT_ABIS; 7548 needsRenderScriptOverride = true; 7549 } 7550 7551 final int copyRet; 7552 if (extractLibs) { 7553 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7554 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7555 } else { 7556 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7557 } 7558 7559 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7560 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7561 "Error unpackaging native libs for app, errorCode=" + copyRet); 7562 } 7563 7564 if (copyRet >= 0) { 7565 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7566 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7567 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7568 } else if (needsRenderScriptOverride) { 7569 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7570 } 7571 } 7572 } catch (IOException ioe) { 7573 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7574 } finally { 7575 IoUtils.closeQuietly(handle); 7576 } 7577 7578 // Now that we've calculated the ABIs and determined if it's an internal app, 7579 // we will go ahead and populate the nativeLibraryPath. 7580 setNativeLibraryPaths(pkg); 7581 } 7582 7583 /** 7584 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7585 * i.e, so that all packages can be run inside a single process if required. 7586 * 7587 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7588 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7589 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7590 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7591 * updating a package that belongs to a shared user. 7592 * 7593 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7594 * adds unnecessary complexity. 7595 */ 7596 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7597 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7598 String requiredInstructionSet = null; 7599 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7600 requiredInstructionSet = VMRuntime.getInstructionSet( 7601 scannedPackage.applicationInfo.primaryCpuAbi); 7602 } 7603 7604 PackageSetting requirer = null; 7605 for (PackageSetting ps : packagesForUser) { 7606 // If packagesForUser contains scannedPackage, we skip it. This will happen 7607 // when scannedPackage is an update of an existing package. Without this check, 7608 // we will never be able to change the ABI of any package belonging to a shared 7609 // user, even if it's compatible with other packages. 7610 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7611 if (ps.primaryCpuAbiString == null) { 7612 continue; 7613 } 7614 7615 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7616 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7617 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7618 // this but there's not much we can do. 7619 String errorMessage = "Instruction set mismatch, " 7620 + ((requirer == null) ? "[caller]" : requirer) 7621 + " requires " + requiredInstructionSet + " whereas " + ps 7622 + " requires " + instructionSet; 7623 Slog.w(TAG, errorMessage); 7624 } 7625 7626 if (requiredInstructionSet == null) { 7627 requiredInstructionSet = instructionSet; 7628 requirer = ps; 7629 } 7630 } 7631 } 7632 7633 if (requiredInstructionSet != null) { 7634 String adjustedAbi; 7635 if (requirer != null) { 7636 // requirer != null implies that either scannedPackage was null or that scannedPackage 7637 // did not require an ABI, in which case we have to adjust scannedPackage to match 7638 // the ABI of the set (which is the same as requirer's ABI) 7639 adjustedAbi = requirer.primaryCpuAbiString; 7640 if (scannedPackage != null) { 7641 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7642 } 7643 } else { 7644 // requirer == null implies that we're updating all ABIs in the set to 7645 // match scannedPackage. 7646 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7647 } 7648 7649 for (PackageSetting ps : packagesForUser) { 7650 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7651 if (ps.primaryCpuAbiString != null) { 7652 continue; 7653 } 7654 7655 ps.primaryCpuAbiString = adjustedAbi; 7656 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7657 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7658 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7659 7660 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7661 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7662 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7663 ps.primaryCpuAbiString = null; 7664 ps.pkg.applicationInfo.primaryCpuAbi = null; 7665 return; 7666 } else { 7667 mInstaller.rmdex(ps.codePathString, 7668 getDexCodeInstructionSet(getPreferredInstructionSet())); 7669 } 7670 } 7671 } 7672 } 7673 } 7674 } 7675 7676 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7677 synchronized (mPackages) { 7678 mResolverReplaced = true; 7679 // Set up information for custom user intent resolution activity. 7680 mResolveActivity.applicationInfo = pkg.applicationInfo; 7681 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7682 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7683 mResolveActivity.processName = pkg.applicationInfo.packageName; 7684 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7685 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7686 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7687 mResolveActivity.theme = 0; 7688 mResolveActivity.exported = true; 7689 mResolveActivity.enabled = true; 7690 mResolveInfo.activityInfo = mResolveActivity; 7691 mResolveInfo.priority = 0; 7692 mResolveInfo.preferredOrder = 0; 7693 mResolveInfo.match = 0; 7694 mResolveComponentName = mCustomResolverComponentName; 7695 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7696 mResolveComponentName); 7697 } 7698 } 7699 7700 private static String calculateBundledApkRoot(final String codePathString) { 7701 final File codePath = new File(codePathString); 7702 final File codeRoot; 7703 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7704 codeRoot = Environment.getRootDirectory(); 7705 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7706 codeRoot = Environment.getOemDirectory(); 7707 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7708 codeRoot = Environment.getVendorDirectory(); 7709 } else { 7710 // Unrecognized code path; take its top real segment as the apk root: 7711 // e.g. /something/app/blah.apk => /something 7712 try { 7713 File f = codePath.getCanonicalFile(); 7714 File parent = f.getParentFile(); // non-null because codePath is a file 7715 File tmp; 7716 while ((tmp = parent.getParentFile()) != null) { 7717 f = parent; 7718 parent = tmp; 7719 } 7720 codeRoot = f; 7721 Slog.w(TAG, "Unrecognized code path " 7722 + codePath + " - using " + codeRoot); 7723 } catch (IOException e) { 7724 // Can't canonicalize the code path -- shenanigans? 7725 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7726 return Environment.getRootDirectory().getPath(); 7727 } 7728 } 7729 return codeRoot.getPath(); 7730 } 7731 7732 /** 7733 * Derive and set the location of native libraries for the given package, 7734 * which varies depending on where and how the package was installed. 7735 */ 7736 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7737 final ApplicationInfo info = pkg.applicationInfo; 7738 final String codePath = pkg.codePath; 7739 final File codeFile = new File(codePath); 7740 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7741 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7742 7743 info.nativeLibraryRootDir = null; 7744 info.nativeLibraryRootRequiresIsa = false; 7745 info.nativeLibraryDir = null; 7746 info.secondaryNativeLibraryDir = null; 7747 7748 if (isApkFile(codeFile)) { 7749 // Monolithic install 7750 if (bundledApp) { 7751 // If "/system/lib64/apkname" exists, assume that is the per-package 7752 // native library directory to use; otherwise use "/system/lib/apkname". 7753 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7754 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7755 getPrimaryInstructionSet(info)); 7756 7757 // This is a bundled system app so choose the path based on the ABI. 7758 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7759 // is just the default path. 7760 final String apkName = deriveCodePathName(codePath); 7761 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7762 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7763 apkName).getAbsolutePath(); 7764 7765 if (info.secondaryCpuAbi != null) { 7766 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7767 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7768 secondaryLibDir, apkName).getAbsolutePath(); 7769 } 7770 } else if (asecApp) { 7771 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7772 .getAbsolutePath(); 7773 } else { 7774 final String apkName = deriveCodePathName(codePath); 7775 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7776 .getAbsolutePath(); 7777 } 7778 7779 info.nativeLibraryRootRequiresIsa = false; 7780 info.nativeLibraryDir = info.nativeLibraryRootDir; 7781 } else { 7782 // Cluster install 7783 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7784 info.nativeLibraryRootRequiresIsa = true; 7785 7786 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7787 getPrimaryInstructionSet(info)).getAbsolutePath(); 7788 7789 if (info.secondaryCpuAbi != null) { 7790 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7791 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7792 } 7793 } 7794 } 7795 7796 /** 7797 * Calculate the abis and roots for a bundled app. These can uniquely 7798 * be determined from the contents of the system partition, i.e whether 7799 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7800 * of this information, and instead assume that the system was built 7801 * sensibly. 7802 */ 7803 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7804 PackageSetting pkgSetting) { 7805 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7806 7807 // If "/system/lib64/apkname" exists, assume that is the per-package 7808 // native library directory to use; otherwise use "/system/lib/apkname". 7809 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7810 setBundledAppAbi(pkg, apkRoot, apkName); 7811 // pkgSetting might be null during rescan following uninstall of updates 7812 // to a bundled app, so accommodate that possibility. The settings in 7813 // that case will be established later from the parsed package. 7814 // 7815 // If the settings aren't null, sync them up with what we've just derived. 7816 // note that apkRoot isn't stored in the package settings. 7817 if (pkgSetting != null) { 7818 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7819 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7820 } 7821 } 7822 7823 /** 7824 * Deduces the ABI of a bundled app and sets the relevant fields on the 7825 * parsed pkg object. 7826 * 7827 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7828 * under which system libraries are installed. 7829 * @param apkName the name of the installed package. 7830 */ 7831 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7832 final File codeFile = new File(pkg.codePath); 7833 7834 final boolean has64BitLibs; 7835 final boolean has32BitLibs; 7836 if (isApkFile(codeFile)) { 7837 // Monolithic install 7838 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7839 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7840 } else { 7841 // Cluster install 7842 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7843 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7844 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7845 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7846 has64BitLibs = (new File(rootDir, isa)).exists(); 7847 } else { 7848 has64BitLibs = false; 7849 } 7850 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7851 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7852 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7853 has32BitLibs = (new File(rootDir, isa)).exists(); 7854 } else { 7855 has32BitLibs = false; 7856 } 7857 } 7858 7859 if (has64BitLibs && !has32BitLibs) { 7860 // The package has 64 bit libs, but not 32 bit libs. Its primary 7861 // ABI should be 64 bit. We can safely assume here that the bundled 7862 // native libraries correspond to the most preferred ABI in the list. 7863 7864 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7865 pkg.applicationInfo.secondaryCpuAbi = null; 7866 } else if (has32BitLibs && !has64BitLibs) { 7867 // The package has 32 bit libs but not 64 bit libs. Its primary 7868 // ABI should be 32 bit. 7869 7870 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7871 pkg.applicationInfo.secondaryCpuAbi = null; 7872 } else if (has32BitLibs && has64BitLibs) { 7873 // The application has both 64 and 32 bit bundled libraries. We check 7874 // here that the app declares multiArch support, and warn if it doesn't. 7875 // 7876 // We will be lenient here and record both ABIs. The primary will be the 7877 // ABI that's higher on the list, i.e, a device that's configured to prefer 7878 // 64 bit apps will see a 64 bit primary ABI, 7879 7880 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7881 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7882 } 7883 7884 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7885 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7886 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7887 } else { 7888 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7889 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7890 } 7891 } else { 7892 pkg.applicationInfo.primaryCpuAbi = null; 7893 pkg.applicationInfo.secondaryCpuAbi = null; 7894 } 7895 } 7896 7897 private void killApplication(String pkgName, int appId, String reason) { 7898 // Request the ActivityManager to kill the process(only for existing packages) 7899 // so that we do not end up in a confused state while the user is still using the older 7900 // version of the application while the new one gets installed. 7901 IActivityManager am = ActivityManagerNative.getDefault(); 7902 if (am != null) { 7903 try { 7904 am.killApplicationWithAppId(pkgName, appId, reason); 7905 } catch (RemoteException e) { 7906 } 7907 } 7908 } 7909 7910 void removePackageLI(PackageSetting ps, boolean chatty) { 7911 if (DEBUG_INSTALL) { 7912 if (chatty) 7913 Log.d(TAG, "Removing package " + ps.name); 7914 } 7915 7916 // writer 7917 synchronized (mPackages) { 7918 mPackages.remove(ps.name); 7919 final PackageParser.Package pkg = ps.pkg; 7920 if (pkg != null) { 7921 cleanPackageDataStructuresLILPw(pkg, chatty); 7922 } 7923 } 7924 } 7925 7926 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7927 if (DEBUG_INSTALL) { 7928 if (chatty) 7929 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7930 } 7931 7932 // writer 7933 synchronized (mPackages) { 7934 mPackages.remove(pkg.applicationInfo.packageName); 7935 cleanPackageDataStructuresLILPw(pkg, chatty); 7936 } 7937 } 7938 7939 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7940 int N = pkg.providers.size(); 7941 StringBuilder r = null; 7942 int i; 7943 for (i=0; i<N; i++) { 7944 PackageParser.Provider p = pkg.providers.get(i); 7945 mProviders.removeProvider(p); 7946 if (p.info.authority == null) { 7947 7948 /* There was another ContentProvider with this authority when 7949 * this app was installed so this authority is null, 7950 * Ignore it as we don't have to unregister the provider. 7951 */ 7952 continue; 7953 } 7954 String names[] = p.info.authority.split(";"); 7955 for (int j = 0; j < names.length; j++) { 7956 if (mProvidersByAuthority.get(names[j]) == p) { 7957 mProvidersByAuthority.remove(names[j]); 7958 if (DEBUG_REMOVE) { 7959 if (chatty) 7960 Log.d(TAG, "Unregistered content provider: " + names[j] 7961 + ", className = " + p.info.name + ", isSyncable = " 7962 + p.info.isSyncable); 7963 } 7964 } 7965 } 7966 if (DEBUG_REMOVE && chatty) { 7967 if (r == null) { 7968 r = new StringBuilder(256); 7969 } else { 7970 r.append(' '); 7971 } 7972 r.append(p.info.name); 7973 } 7974 } 7975 if (r != null) { 7976 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7977 } 7978 7979 N = pkg.services.size(); 7980 r = null; 7981 for (i=0; i<N; i++) { 7982 PackageParser.Service s = pkg.services.get(i); 7983 mServices.removeService(s); 7984 if (chatty) { 7985 if (r == null) { 7986 r = new StringBuilder(256); 7987 } else { 7988 r.append(' '); 7989 } 7990 r.append(s.info.name); 7991 } 7992 } 7993 if (r != null) { 7994 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7995 } 7996 7997 N = pkg.receivers.size(); 7998 r = null; 7999 for (i=0; i<N; i++) { 8000 PackageParser.Activity a = pkg.receivers.get(i); 8001 mReceivers.removeActivity(a, "receiver"); 8002 if (DEBUG_REMOVE && chatty) { 8003 if (r == null) { 8004 r = new StringBuilder(256); 8005 } else { 8006 r.append(' '); 8007 } 8008 r.append(a.info.name); 8009 } 8010 } 8011 if (r != null) { 8012 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8013 } 8014 8015 N = pkg.activities.size(); 8016 r = null; 8017 for (i=0; i<N; i++) { 8018 PackageParser.Activity a = pkg.activities.get(i); 8019 mActivities.removeActivity(a, "activity"); 8020 if (DEBUG_REMOVE && chatty) { 8021 if (r == null) { 8022 r = new StringBuilder(256); 8023 } else { 8024 r.append(' '); 8025 } 8026 r.append(a.info.name); 8027 } 8028 } 8029 if (r != null) { 8030 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8031 } 8032 8033 N = pkg.permissions.size(); 8034 r = null; 8035 for (i=0; i<N; i++) { 8036 PackageParser.Permission p = pkg.permissions.get(i); 8037 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8038 if (bp == null) { 8039 bp = mSettings.mPermissionTrees.get(p.info.name); 8040 } 8041 if (bp != null && bp.perm == p) { 8042 bp.perm = null; 8043 if (DEBUG_REMOVE && chatty) { 8044 if (r == null) { 8045 r = new StringBuilder(256); 8046 } else { 8047 r.append(' '); 8048 } 8049 r.append(p.info.name); 8050 } 8051 } 8052 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8053 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8054 if (appOpPerms != null) { 8055 appOpPerms.remove(pkg.packageName); 8056 } 8057 } 8058 } 8059 if (r != null) { 8060 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8061 } 8062 8063 N = pkg.requestedPermissions.size(); 8064 r = null; 8065 for (i=0; i<N; i++) { 8066 String perm = pkg.requestedPermissions.get(i); 8067 BasePermission bp = mSettings.mPermissions.get(perm); 8068 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8069 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8070 if (appOpPerms != null) { 8071 appOpPerms.remove(pkg.packageName); 8072 if (appOpPerms.isEmpty()) { 8073 mAppOpPermissionPackages.remove(perm); 8074 } 8075 } 8076 } 8077 } 8078 if (r != null) { 8079 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8080 } 8081 8082 N = pkg.instrumentation.size(); 8083 r = null; 8084 for (i=0; i<N; i++) { 8085 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8086 mInstrumentation.remove(a.getComponentName()); 8087 if (DEBUG_REMOVE && chatty) { 8088 if (r == null) { 8089 r = new StringBuilder(256); 8090 } else { 8091 r.append(' '); 8092 } 8093 r.append(a.info.name); 8094 } 8095 } 8096 if (r != null) { 8097 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8098 } 8099 8100 r = null; 8101 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8102 // Only system apps can hold shared libraries. 8103 if (pkg.libraryNames != null) { 8104 for (i=0; i<pkg.libraryNames.size(); i++) { 8105 String name = pkg.libraryNames.get(i); 8106 SharedLibraryEntry cur = mSharedLibraries.get(name); 8107 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8108 mSharedLibraries.remove(name); 8109 if (DEBUG_REMOVE && chatty) { 8110 if (r == null) { 8111 r = new StringBuilder(256); 8112 } else { 8113 r.append(' '); 8114 } 8115 r.append(name); 8116 } 8117 } 8118 } 8119 } 8120 } 8121 if (r != null) { 8122 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8123 } 8124 } 8125 8126 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8127 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8128 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8129 return true; 8130 } 8131 } 8132 return false; 8133 } 8134 8135 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8136 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8137 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8138 8139 private void updatePermissionsLPw(String changingPkg, 8140 PackageParser.Package pkgInfo, int flags) { 8141 // Make sure there are no dangling permission trees. 8142 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8143 while (it.hasNext()) { 8144 final BasePermission bp = it.next(); 8145 if (bp.packageSetting == null) { 8146 // We may not yet have parsed the package, so just see if 8147 // we still know about its settings. 8148 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8149 } 8150 if (bp.packageSetting == null) { 8151 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8152 + " from package " + bp.sourcePackage); 8153 it.remove(); 8154 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8155 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8156 Slog.i(TAG, "Removing old permission tree: " + bp.name 8157 + " from package " + bp.sourcePackage); 8158 flags |= UPDATE_PERMISSIONS_ALL; 8159 it.remove(); 8160 } 8161 } 8162 } 8163 8164 // Make sure all dynamic permissions have been assigned to a package, 8165 // and make sure there are no dangling permissions. 8166 it = mSettings.mPermissions.values().iterator(); 8167 while (it.hasNext()) { 8168 final BasePermission bp = it.next(); 8169 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8170 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8171 + bp.name + " pkg=" + bp.sourcePackage 8172 + " info=" + bp.pendingInfo); 8173 if (bp.packageSetting == null && bp.pendingInfo != null) { 8174 final BasePermission tree = findPermissionTreeLP(bp.name); 8175 if (tree != null && tree.perm != null) { 8176 bp.packageSetting = tree.packageSetting; 8177 bp.perm = new PackageParser.Permission(tree.perm.owner, 8178 new PermissionInfo(bp.pendingInfo)); 8179 bp.perm.info.packageName = tree.perm.info.packageName; 8180 bp.perm.info.name = bp.name; 8181 bp.uid = tree.uid; 8182 } 8183 } 8184 } 8185 if (bp.packageSetting == null) { 8186 // We may not yet have parsed the package, so just see if 8187 // we still know about its settings. 8188 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8189 } 8190 if (bp.packageSetting == null) { 8191 Slog.w(TAG, "Removing dangling permission: " + bp.name 8192 + " from package " + bp.sourcePackage); 8193 it.remove(); 8194 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8195 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8196 Slog.i(TAG, "Removing old permission: " + bp.name 8197 + " from package " + bp.sourcePackage); 8198 flags |= UPDATE_PERMISSIONS_ALL; 8199 it.remove(); 8200 } 8201 } 8202 } 8203 8204 // Now update the permissions for all packages, in particular 8205 // replace the granted permissions of the system packages. 8206 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8207 for (PackageParser.Package pkg : mPackages.values()) { 8208 if (pkg != pkgInfo) { 8209 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8210 changingPkg); 8211 } 8212 } 8213 } 8214 8215 if (pkgInfo != null) { 8216 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8217 } 8218 } 8219 8220 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8221 String packageOfInterest) { 8222 // IMPORTANT: There are two types of permissions: install and runtime. 8223 // Install time permissions are granted when the app is installed to 8224 // all device users and users added in the future. Runtime permissions 8225 // are granted at runtime explicitly to specific users. Normal and signature 8226 // protected permissions are install time permissions. Dangerous permissions 8227 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8228 // otherwise they are runtime permissions. This function does not manage 8229 // runtime permissions except for the case an app targeting Lollipop MR1 8230 // being upgraded to target a newer SDK, in which case dangerous permissions 8231 // are transformed from install time to runtime ones. 8232 8233 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8234 if (ps == null) { 8235 return; 8236 } 8237 8238 PermissionsState permissionsState = ps.getPermissionsState(); 8239 PermissionsState origPermissions = permissionsState; 8240 8241 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8242 8243 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8244 8245 boolean changedInstallPermission = false; 8246 8247 if (replace) { 8248 ps.installPermissionsFixed = false; 8249 if (!ps.isSharedUser()) { 8250 origPermissions = new PermissionsState(permissionsState); 8251 permissionsState.reset(); 8252 } 8253 } 8254 8255 permissionsState.setGlobalGids(mGlobalGids); 8256 8257 final int N = pkg.requestedPermissions.size(); 8258 for (int i=0; i<N; i++) { 8259 final String name = pkg.requestedPermissions.get(i); 8260 final BasePermission bp = mSettings.mPermissions.get(name); 8261 8262 if (DEBUG_INSTALL) { 8263 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8264 } 8265 8266 if (bp == null || bp.packageSetting == null) { 8267 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8268 Slog.w(TAG, "Unknown permission " + name 8269 + " in package " + pkg.packageName); 8270 } 8271 continue; 8272 } 8273 8274 final String perm = bp.name; 8275 boolean allowedSig = false; 8276 int grant = GRANT_DENIED; 8277 8278 // Keep track of app op permissions. 8279 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8280 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8281 if (pkgs == null) { 8282 pkgs = new ArraySet<>(); 8283 mAppOpPermissionPackages.put(bp.name, pkgs); 8284 } 8285 pkgs.add(pkg.packageName); 8286 } 8287 8288 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8289 switch (level) { 8290 case PermissionInfo.PROTECTION_NORMAL: { 8291 // For all apps normal permissions are install time ones. 8292 grant = GRANT_INSTALL; 8293 } break; 8294 8295 case PermissionInfo.PROTECTION_DANGEROUS: { 8296 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8297 // For legacy apps dangerous permissions are install time ones. 8298 grant = GRANT_INSTALL_LEGACY; 8299 } else if (origPermissions.hasInstallPermission(bp.name)) { 8300 // For legacy apps that became modern, install becomes runtime. 8301 grant = GRANT_UPGRADE; 8302 } else { 8303 // For modern apps keep runtime permissions unchanged. 8304 grant = GRANT_RUNTIME; 8305 } 8306 } break; 8307 8308 case PermissionInfo.PROTECTION_SIGNATURE: { 8309 // For all apps signature permissions are install time ones. 8310 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8311 if (allowedSig) { 8312 grant = GRANT_INSTALL; 8313 } 8314 } break; 8315 } 8316 8317 if (DEBUG_INSTALL) { 8318 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8319 } 8320 8321 if (grant != GRANT_DENIED) { 8322 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8323 // If this is an existing, non-system package, then 8324 // we can't add any new permissions to it. 8325 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8326 // Except... if this is a permission that was added 8327 // to the platform (note: need to only do this when 8328 // updating the platform). 8329 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8330 grant = GRANT_DENIED; 8331 } 8332 } 8333 } 8334 8335 switch (grant) { 8336 case GRANT_INSTALL: { 8337 // Revoke this as runtime permission to handle the case of 8338 // a runtime permission being downgraded to an install one. 8339 for (int userId : UserManagerService.getInstance().getUserIds()) { 8340 if (origPermissions.getRuntimePermissionState( 8341 bp.name, userId) != null) { 8342 // Revoke the runtime permission and clear the flags. 8343 origPermissions.revokeRuntimePermission(bp, userId); 8344 origPermissions.updatePermissionFlags(bp, userId, 8345 PackageManager.MASK_PERMISSION_FLAGS, 0); 8346 // If we revoked a permission permission, we have to write. 8347 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8348 changedRuntimePermissionUserIds, userId); 8349 } 8350 } 8351 // Grant an install permission. 8352 if (permissionsState.grantInstallPermission(bp) != 8353 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8354 changedInstallPermission = true; 8355 } 8356 } break; 8357 8358 case GRANT_INSTALL_LEGACY: { 8359 // Grant an install permission. 8360 if (permissionsState.grantInstallPermission(bp) != 8361 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8362 changedInstallPermission = true; 8363 } 8364 } break; 8365 8366 case GRANT_RUNTIME: { 8367 // Grant previously granted runtime permissions. 8368 for (int userId : UserManagerService.getInstance().getUserIds()) { 8369 PermissionState permissionState = origPermissions 8370 .getRuntimePermissionState(bp.name, userId); 8371 final int flags = permissionState != null 8372 ? permissionState.getFlags() : 0; 8373 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8374 if (permissionsState.grantRuntimePermission(bp, userId) == 8375 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8376 // If we cannot put the permission as it was, we have to write. 8377 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8378 changedRuntimePermissionUserIds, userId); 8379 } 8380 } 8381 // Propagate the permission flags. 8382 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8383 } 8384 } break; 8385 8386 case GRANT_UPGRADE: { 8387 // Grant runtime permissions for a previously held install permission. 8388 PermissionState permissionState = origPermissions 8389 .getInstallPermissionState(bp.name); 8390 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8391 8392 if (origPermissions.revokeInstallPermission(bp) 8393 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8394 // We will be transferring the permission flags, so clear them. 8395 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8396 PackageManager.MASK_PERMISSION_FLAGS, 0); 8397 changedInstallPermission = true; 8398 } 8399 8400 // If the permission is not to be promoted to runtime we ignore it and 8401 // also its other flags as they are not applicable to install permissions. 8402 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8403 for (int userId : currentUserIds) { 8404 if (permissionsState.grantRuntimePermission(bp, userId) != 8405 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8406 // Transfer the permission flags. 8407 permissionsState.updatePermissionFlags(bp, userId, 8408 flags, flags); 8409 // If we granted the permission, we have to write. 8410 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8411 changedRuntimePermissionUserIds, userId); 8412 } 8413 } 8414 } 8415 } break; 8416 8417 default: { 8418 if (packageOfInterest == null 8419 || packageOfInterest.equals(pkg.packageName)) { 8420 Slog.w(TAG, "Not granting permission " + perm 8421 + " to package " + pkg.packageName 8422 + " because it was previously installed without"); 8423 } 8424 } break; 8425 } 8426 } else { 8427 if (permissionsState.revokeInstallPermission(bp) != 8428 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8429 // Also drop the permission flags. 8430 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8431 PackageManager.MASK_PERMISSION_FLAGS, 0); 8432 changedInstallPermission = true; 8433 Slog.i(TAG, "Un-granting permission " + perm 8434 + " from package " + pkg.packageName 8435 + " (protectionLevel=" + bp.protectionLevel 8436 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8437 + ")"); 8438 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8439 // Don't print warning for app op permissions, since it is fine for them 8440 // not to be granted, there is a UI for the user to decide. 8441 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8442 Slog.w(TAG, "Not granting permission " + perm 8443 + " to package " + pkg.packageName 8444 + " (protectionLevel=" + bp.protectionLevel 8445 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8446 + ")"); 8447 } 8448 } 8449 } 8450 } 8451 8452 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8453 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8454 // This is the first that we have heard about this package, so the 8455 // permissions we have now selected are fixed until explicitly 8456 // changed. 8457 ps.installPermissionsFixed = true; 8458 } 8459 8460 // Persist the runtime permissions state for users with changes. 8461 for (int userId : changedRuntimePermissionUserIds) { 8462 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8463 } 8464 } 8465 8466 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8467 boolean allowed = false; 8468 final int NP = PackageParser.NEW_PERMISSIONS.length; 8469 for (int ip=0; ip<NP; ip++) { 8470 final PackageParser.NewPermissionInfo npi 8471 = PackageParser.NEW_PERMISSIONS[ip]; 8472 if (npi.name.equals(perm) 8473 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8474 allowed = true; 8475 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8476 + pkg.packageName); 8477 break; 8478 } 8479 } 8480 return allowed; 8481 } 8482 8483 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8484 BasePermission bp, PermissionsState origPermissions) { 8485 boolean allowed; 8486 allowed = (compareSignatures( 8487 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8488 == PackageManager.SIGNATURE_MATCH) 8489 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8490 == PackageManager.SIGNATURE_MATCH); 8491 if (!allowed && (bp.protectionLevel 8492 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8493 if (isSystemApp(pkg)) { 8494 // For updated system applications, a system permission 8495 // is granted only if it had been defined by the original application. 8496 if (pkg.isUpdatedSystemApp()) { 8497 final PackageSetting sysPs = mSettings 8498 .getDisabledSystemPkgLPr(pkg.packageName); 8499 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8500 // If the original was granted this permission, we take 8501 // that grant decision as read and propagate it to the 8502 // update. 8503 if (sysPs.isPrivileged()) { 8504 allowed = true; 8505 } 8506 } else { 8507 // The system apk may have been updated with an older 8508 // version of the one on the data partition, but which 8509 // granted a new system permission that it didn't have 8510 // before. In this case we do want to allow the app to 8511 // now get the new permission if the ancestral apk is 8512 // privileged to get it. 8513 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8514 for (int j=0; 8515 j<sysPs.pkg.requestedPermissions.size(); j++) { 8516 if (perm.equals( 8517 sysPs.pkg.requestedPermissions.get(j))) { 8518 allowed = true; 8519 break; 8520 } 8521 } 8522 } 8523 } 8524 } else { 8525 allowed = isPrivilegedApp(pkg); 8526 } 8527 } 8528 } 8529 if (!allowed) { 8530 if (!allowed && (bp.protectionLevel 8531 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8532 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8533 // If this was a previously normal/dangerous permission that got moved 8534 // to a system permission as part of the runtime permission redesign, then 8535 // we still want to blindly grant it to old apps. 8536 allowed = true; 8537 } 8538 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8539 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8540 // If this permission is to be granted to the system installer and 8541 // this app is an installer, then it gets the permission. 8542 allowed = true; 8543 } 8544 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8545 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8546 // If this permission is to be granted to the system verifier and 8547 // this app is a verifier, then it gets the permission. 8548 allowed = true; 8549 } 8550 if (!allowed && (bp.protectionLevel 8551 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8552 && isSystemApp(pkg)) { 8553 // Any pre-installed system app is allowed to get this permission. 8554 allowed = true; 8555 } 8556 if (!allowed && (bp.protectionLevel 8557 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8558 // For development permissions, a development permission 8559 // is granted only if it was already granted. 8560 allowed = origPermissions.hasInstallPermission(perm); 8561 } 8562 } 8563 return allowed; 8564 } 8565 8566 final class ActivityIntentResolver 8567 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8568 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8569 boolean defaultOnly, int userId) { 8570 if (!sUserManager.exists(userId)) return null; 8571 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8572 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8573 } 8574 8575 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8576 int userId) { 8577 if (!sUserManager.exists(userId)) return null; 8578 mFlags = flags; 8579 return super.queryIntent(intent, resolvedType, 8580 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8581 } 8582 8583 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8584 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8585 if (!sUserManager.exists(userId)) return null; 8586 if (packageActivities == null) { 8587 return null; 8588 } 8589 mFlags = flags; 8590 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8591 final int N = packageActivities.size(); 8592 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8593 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8594 8595 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8596 for (int i = 0; i < N; ++i) { 8597 intentFilters = packageActivities.get(i).intents; 8598 if (intentFilters != null && intentFilters.size() > 0) { 8599 PackageParser.ActivityIntentInfo[] array = 8600 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8601 intentFilters.toArray(array); 8602 listCut.add(array); 8603 } 8604 } 8605 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8606 } 8607 8608 public final void addActivity(PackageParser.Activity a, String type) { 8609 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8610 mActivities.put(a.getComponentName(), a); 8611 if (DEBUG_SHOW_INFO) 8612 Log.v( 8613 TAG, " " + type + " " + 8614 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8615 if (DEBUG_SHOW_INFO) 8616 Log.v(TAG, " Class=" + a.info.name); 8617 final int NI = a.intents.size(); 8618 for (int j=0; j<NI; j++) { 8619 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8620 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8621 intent.setPriority(0); 8622 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8623 + a.className + " with priority > 0, forcing to 0"); 8624 } 8625 if (DEBUG_SHOW_INFO) { 8626 Log.v(TAG, " IntentFilter:"); 8627 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8628 } 8629 if (!intent.debugCheck()) { 8630 Log.w(TAG, "==> For Activity " + a.info.name); 8631 } 8632 addFilter(intent); 8633 } 8634 } 8635 8636 public final void removeActivity(PackageParser.Activity a, String type) { 8637 mActivities.remove(a.getComponentName()); 8638 if (DEBUG_SHOW_INFO) { 8639 Log.v(TAG, " " + type + " " 8640 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8641 : a.info.name) + ":"); 8642 Log.v(TAG, " Class=" + a.info.name); 8643 } 8644 final int NI = a.intents.size(); 8645 for (int j=0; j<NI; j++) { 8646 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8647 if (DEBUG_SHOW_INFO) { 8648 Log.v(TAG, " IntentFilter:"); 8649 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8650 } 8651 removeFilter(intent); 8652 } 8653 } 8654 8655 @Override 8656 protected boolean allowFilterResult( 8657 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8658 ActivityInfo filterAi = filter.activity.info; 8659 for (int i=dest.size()-1; i>=0; i--) { 8660 ActivityInfo destAi = dest.get(i).activityInfo; 8661 if (destAi.name == filterAi.name 8662 && destAi.packageName == filterAi.packageName) { 8663 return false; 8664 } 8665 } 8666 return true; 8667 } 8668 8669 @Override 8670 protected ActivityIntentInfo[] newArray(int size) { 8671 return new ActivityIntentInfo[size]; 8672 } 8673 8674 @Override 8675 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8676 if (!sUserManager.exists(userId)) return true; 8677 PackageParser.Package p = filter.activity.owner; 8678 if (p != null) { 8679 PackageSetting ps = (PackageSetting)p.mExtras; 8680 if (ps != null) { 8681 // System apps are never considered stopped for purposes of 8682 // filtering, because there may be no way for the user to 8683 // actually re-launch them. 8684 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8685 && ps.getStopped(userId); 8686 } 8687 } 8688 return false; 8689 } 8690 8691 @Override 8692 protected boolean isPackageForFilter(String packageName, 8693 PackageParser.ActivityIntentInfo info) { 8694 return packageName.equals(info.activity.owner.packageName); 8695 } 8696 8697 @Override 8698 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8699 int match, int userId) { 8700 if (!sUserManager.exists(userId)) return null; 8701 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8702 return null; 8703 } 8704 final PackageParser.Activity activity = info.activity; 8705 if (mSafeMode && (activity.info.applicationInfo.flags 8706 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8707 return null; 8708 } 8709 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8710 if (ps == null) { 8711 return null; 8712 } 8713 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8714 ps.readUserState(userId), userId); 8715 if (ai == null) { 8716 return null; 8717 } 8718 final ResolveInfo res = new ResolveInfo(); 8719 res.activityInfo = ai; 8720 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8721 res.filter = info; 8722 } 8723 if (info != null) { 8724 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8725 } 8726 res.priority = info.getPriority(); 8727 res.preferredOrder = activity.owner.mPreferredOrder; 8728 //System.out.println("Result: " + res.activityInfo.className + 8729 // " = " + res.priority); 8730 res.match = match; 8731 res.isDefault = info.hasDefault; 8732 res.labelRes = info.labelRes; 8733 res.nonLocalizedLabel = info.nonLocalizedLabel; 8734 if (userNeedsBadging(userId)) { 8735 res.noResourceId = true; 8736 } else { 8737 res.icon = info.icon; 8738 } 8739 res.iconResourceId = info.icon; 8740 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8741 return res; 8742 } 8743 8744 @Override 8745 protected void sortResults(List<ResolveInfo> results) { 8746 Collections.sort(results, mResolvePrioritySorter); 8747 } 8748 8749 @Override 8750 protected void dumpFilter(PrintWriter out, String prefix, 8751 PackageParser.ActivityIntentInfo filter) { 8752 out.print(prefix); out.print( 8753 Integer.toHexString(System.identityHashCode(filter.activity))); 8754 out.print(' '); 8755 filter.activity.printComponentShortName(out); 8756 out.print(" filter "); 8757 out.println(Integer.toHexString(System.identityHashCode(filter))); 8758 } 8759 8760 @Override 8761 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8762 return filter.activity; 8763 } 8764 8765 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8766 PackageParser.Activity activity = (PackageParser.Activity)label; 8767 out.print(prefix); out.print( 8768 Integer.toHexString(System.identityHashCode(activity))); 8769 out.print(' '); 8770 activity.printComponentShortName(out); 8771 if (count > 1) { 8772 out.print(" ("); out.print(count); out.print(" filters)"); 8773 } 8774 out.println(); 8775 } 8776 8777// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8778// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8779// final List<ResolveInfo> retList = Lists.newArrayList(); 8780// while (i.hasNext()) { 8781// final ResolveInfo resolveInfo = i.next(); 8782// if (isEnabledLP(resolveInfo.activityInfo)) { 8783// retList.add(resolveInfo); 8784// } 8785// } 8786// return retList; 8787// } 8788 8789 // Keys are String (activity class name), values are Activity. 8790 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8791 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8792 private int mFlags; 8793 } 8794 8795 private final class ServiceIntentResolver 8796 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8797 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8798 boolean defaultOnly, int userId) { 8799 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8800 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8801 } 8802 8803 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8804 int userId) { 8805 if (!sUserManager.exists(userId)) return null; 8806 mFlags = flags; 8807 return super.queryIntent(intent, resolvedType, 8808 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8809 } 8810 8811 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8812 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8813 if (!sUserManager.exists(userId)) return null; 8814 if (packageServices == null) { 8815 return null; 8816 } 8817 mFlags = flags; 8818 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8819 final int N = packageServices.size(); 8820 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8821 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8822 8823 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8824 for (int i = 0; i < N; ++i) { 8825 intentFilters = packageServices.get(i).intents; 8826 if (intentFilters != null && intentFilters.size() > 0) { 8827 PackageParser.ServiceIntentInfo[] array = 8828 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8829 intentFilters.toArray(array); 8830 listCut.add(array); 8831 } 8832 } 8833 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8834 } 8835 8836 public final void addService(PackageParser.Service s) { 8837 mServices.put(s.getComponentName(), s); 8838 if (DEBUG_SHOW_INFO) { 8839 Log.v(TAG, " " 8840 + (s.info.nonLocalizedLabel != null 8841 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8842 Log.v(TAG, " Class=" + s.info.name); 8843 } 8844 final int NI = s.intents.size(); 8845 int j; 8846 for (j=0; j<NI; j++) { 8847 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8848 if (DEBUG_SHOW_INFO) { 8849 Log.v(TAG, " IntentFilter:"); 8850 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8851 } 8852 if (!intent.debugCheck()) { 8853 Log.w(TAG, "==> For Service " + s.info.name); 8854 } 8855 addFilter(intent); 8856 } 8857 } 8858 8859 public final void removeService(PackageParser.Service s) { 8860 mServices.remove(s.getComponentName()); 8861 if (DEBUG_SHOW_INFO) { 8862 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8863 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8864 Log.v(TAG, " Class=" + s.info.name); 8865 } 8866 final int NI = s.intents.size(); 8867 int j; 8868 for (j=0; j<NI; j++) { 8869 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8870 if (DEBUG_SHOW_INFO) { 8871 Log.v(TAG, " IntentFilter:"); 8872 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8873 } 8874 removeFilter(intent); 8875 } 8876 } 8877 8878 @Override 8879 protected boolean allowFilterResult( 8880 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8881 ServiceInfo filterSi = filter.service.info; 8882 for (int i=dest.size()-1; i>=0; i--) { 8883 ServiceInfo destAi = dest.get(i).serviceInfo; 8884 if (destAi.name == filterSi.name 8885 && destAi.packageName == filterSi.packageName) { 8886 return false; 8887 } 8888 } 8889 return true; 8890 } 8891 8892 @Override 8893 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8894 return new PackageParser.ServiceIntentInfo[size]; 8895 } 8896 8897 @Override 8898 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8899 if (!sUserManager.exists(userId)) return true; 8900 PackageParser.Package p = filter.service.owner; 8901 if (p != null) { 8902 PackageSetting ps = (PackageSetting)p.mExtras; 8903 if (ps != null) { 8904 // System apps are never considered stopped for purposes of 8905 // filtering, because there may be no way for the user to 8906 // actually re-launch them. 8907 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8908 && ps.getStopped(userId); 8909 } 8910 } 8911 return false; 8912 } 8913 8914 @Override 8915 protected boolean isPackageForFilter(String packageName, 8916 PackageParser.ServiceIntentInfo info) { 8917 return packageName.equals(info.service.owner.packageName); 8918 } 8919 8920 @Override 8921 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8922 int match, int userId) { 8923 if (!sUserManager.exists(userId)) return null; 8924 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8925 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8926 return null; 8927 } 8928 final PackageParser.Service service = info.service; 8929 if (mSafeMode && (service.info.applicationInfo.flags 8930 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8931 return null; 8932 } 8933 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8934 if (ps == null) { 8935 return null; 8936 } 8937 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8938 ps.readUserState(userId), userId); 8939 if (si == null) { 8940 return null; 8941 } 8942 final ResolveInfo res = new ResolveInfo(); 8943 res.serviceInfo = si; 8944 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8945 res.filter = filter; 8946 } 8947 res.priority = info.getPriority(); 8948 res.preferredOrder = service.owner.mPreferredOrder; 8949 res.match = match; 8950 res.isDefault = info.hasDefault; 8951 res.labelRes = info.labelRes; 8952 res.nonLocalizedLabel = info.nonLocalizedLabel; 8953 res.icon = info.icon; 8954 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8955 return res; 8956 } 8957 8958 @Override 8959 protected void sortResults(List<ResolveInfo> results) { 8960 Collections.sort(results, mResolvePrioritySorter); 8961 } 8962 8963 @Override 8964 protected void dumpFilter(PrintWriter out, String prefix, 8965 PackageParser.ServiceIntentInfo filter) { 8966 out.print(prefix); out.print( 8967 Integer.toHexString(System.identityHashCode(filter.service))); 8968 out.print(' '); 8969 filter.service.printComponentShortName(out); 8970 out.print(" filter "); 8971 out.println(Integer.toHexString(System.identityHashCode(filter))); 8972 } 8973 8974 @Override 8975 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8976 return filter.service; 8977 } 8978 8979 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8980 PackageParser.Service service = (PackageParser.Service)label; 8981 out.print(prefix); out.print( 8982 Integer.toHexString(System.identityHashCode(service))); 8983 out.print(' '); 8984 service.printComponentShortName(out); 8985 if (count > 1) { 8986 out.print(" ("); out.print(count); out.print(" filters)"); 8987 } 8988 out.println(); 8989 } 8990 8991// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8992// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8993// final List<ResolveInfo> retList = Lists.newArrayList(); 8994// while (i.hasNext()) { 8995// final ResolveInfo resolveInfo = (ResolveInfo) i; 8996// if (isEnabledLP(resolveInfo.serviceInfo)) { 8997// retList.add(resolveInfo); 8998// } 8999// } 9000// return retList; 9001// } 9002 9003 // Keys are String (activity class name), values are Activity. 9004 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9005 = new ArrayMap<ComponentName, PackageParser.Service>(); 9006 private int mFlags; 9007 }; 9008 9009 private final class ProviderIntentResolver 9010 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9011 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9012 boolean defaultOnly, int userId) { 9013 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9014 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9015 } 9016 9017 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9018 int userId) { 9019 if (!sUserManager.exists(userId)) 9020 return null; 9021 mFlags = flags; 9022 return super.queryIntent(intent, resolvedType, 9023 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9024 } 9025 9026 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9027 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9028 if (!sUserManager.exists(userId)) 9029 return null; 9030 if (packageProviders == null) { 9031 return null; 9032 } 9033 mFlags = flags; 9034 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9035 final int N = packageProviders.size(); 9036 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9037 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9038 9039 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9040 for (int i = 0; i < N; ++i) { 9041 intentFilters = packageProviders.get(i).intents; 9042 if (intentFilters != null && intentFilters.size() > 0) { 9043 PackageParser.ProviderIntentInfo[] array = 9044 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9045 intentFilters.toArray(array); 9046 listCut.add(array); 9047 } 9048 } 9049 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9050 } 9051 9052 public final void addProvider(PackageParser.Provider p) { 9053 if (mProviders.containsKey(p.getComponentName())) { 9054 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9055 return; 9056 } 9057 9058 mProviders.put(p.getComponentName(), p); 9059 if (DEBUG_SHOW_INFO) { 9060 Log.v(TAG, " " 9061 + (p.info.nonLocalizedLabel != null 9062 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9063 Log.v(TAG, " Class=" + p.info.name); 9064 } 9065 final int NI = p.intents.size(); 9066 int j; 9067 for (j = 0; j < NI; j++) { 9068 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9069 if (DEBUG_SHOW_INFO) { 9070 Log.v(TAG, " IntentFilter:"); 9071 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9072 } 9073 if (!intent.debugCheck()) { 9074 Log.w(TAG, "==> For Provider " + p.info.name); 9075 } 9076 addFilter(intent); 9077 } 9078 } 9079 9080 public final void removeProvider(PackageParser.Provider p) { 9081 mProviders.remove(p.getComponentName()); 9082 if (DEBUG_SHOW_INFO) { 9083 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9084 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9085 Log.v(TAG, " Class=" + p.info.name); 9086 } 9087 final int NI = p.intents.size(); 9088 int j; 9089 for (j = 0; j < NI; j++) { 9090 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9091 if (DEBUG_SHOW_INFO) { 9092 Log.v(TAG, " IntentFilter:"); 9093 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9094 } 9095 removeFilter(intent); 9096 } 9097 } 9098 9099 @Override 9100 protected boolean allowFilterResult( 9101 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9102 ProviderInfo filterPi = filter.provider.info; 9103 for (int i = dest.size() - 1; i >= 0; i--) { 9104 ProviderInfo destPi = dest.get(i).providerInfo; 9105 if (destPi.name == filterPi.name 9106 && destPi.packageName == filterPi.packageName) { 9107 return false; 9108 } 9109 } 9110 return true; 9111 } 9112 9113 @Override 9114 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9115 return new PackageParser.ProviderIntentInfo[size]; 9116 } 9117 9118 @Override 9119 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9120 if (!sUserManager.exists(userId)) 9121 return true; 9122 PackageParser.Package p = filter.provider.owner; 9123 if (p != null) { 9124 PackageSetting ps = (PackageSetting) p.mExtras; 9125 if (ps != null) { 9126 // System apps are never considered stopped for purposes of 9127 // filtering, because there may be no way for the user to 9128 // actually re-launch them. 9129 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9130 && ps.getStopped(userId); 9131 } 9132 } 9133 return false; 9134 } 9135 9136 @Override 9137 protected boolean isPackageForFilter(String packageName, 9138 PackageParser.ProviderIntentInfo info) { 9139 return packageName.equals(info.provider.owner.packageName); 9140 } 9141 9142 @Override 9143 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9144 int match, int userId) { 9145 if (!sUserManager.exists(userId)) 9146 return null; 9147 final PackageParser.ProviderIntentInfo info = filter; 9148 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9149 return null; 9150 } 9151 final PackageParser.Provider provider = info.provider; 9152 if (mSafeMode && (provider.info.applicationInfo.flags 9153 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9154 return null; 9155 } 9156 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9157 if (ps == null) { 9158 return null; 9159 } 9160 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9161 ps.readUserState(userId), userId); 9162 if (pi == null) { 9163 return null; 9164 } 9165 final ResolveInfo res = new ResolveInfo(); 9166 res.providerInfo = pi; 9167 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9168 res.filter = filter; 9169 } 9170 res.priority = info.getPriority(); 9171 res.preferredOrder = provider.owner.mPreferredOrder; 9172 res.match = match; 9173 res.isDefault = info.hasDefault; 9174 res.labelRes = info.labelRes; 9175 res.nonLocalizedLabel = info.nonLocalizedLabel; 9176 res.icon = info.icon; 9177 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9178 return res; 9179 } 9180 9181 @Override 9182 protected void sortResults(List<ResolveInfo> results) { 9183 Collections.sort(results, mResolvePrioritySorter); 9184 } 9185 9186 @Override 9187 protected void dumpFilter(PrintWriter out, String prefix, 9188 PackageParser.ProviderIntentInfo filter) { 9189 out.print(prefix); 9190 out.print( 9191 Integer.toHexString(System.identityHashCode(filter.provider))); 9192 out.print(' '); 9193 filter.provider.printComponentShortName(out); 9194 out.print(" filter "); 9195 out.println(Integer.toHexString(System.identityHashCode(filter))); 9196 } 9197 9198 @Override 9199 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9200 return filter.provider; 9201 } 9202 9203 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9204 PackageParser.Provider provider = (PackageParser.Provider)label; 9205 out.print(prefix); out.print( 9206 Integer.toHexString(System.identityHashCode(provider))); 9207 out.print(' '); 9208 provider.printComponentShortName(out); 9209 if (count > 1) { 9210 out.print(" ("); out.print(count); out.print(" filters)"); 9211 } 9212 out.println(); 9213 } 9214 9215 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9216 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9217 private int mFlags; 9218 }; 9219 9220 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9221 new Comparator<ResolveInfo>() { 9222 public int compare(ResolveInfo r1, ResolveInfo r2) { 9223 int v1 = r1.priority; 9224 int v2 = r2.priority; 9225 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9226 if (v1 != v2) { 9227 return (v1 > v2) ? -1 : 1; 9228 } 9229 v1 = r1.preferredOrder; 9230 v2 = r2.preferredOrder; 9231 if (v1 != v2) { 9232 return (v1 > v2) ? -1 : 1; 9233 } 9234 if (r1.isDefault != r2.isDefault) { 9235 return r1.isDefault ? -1 : 1; 9236 } 9237 v1 = r1.match; 9238 v2 = r2.match; 9239 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9240 if (v1 != v2) { 9241 return (v1 > v2) ? -1 : 1; 9242 } 9243 if (r1.system != r2.system) { 9244 return r1.system ? -1 : 1; 9245 } 9246 return 0; 9247 } 9248 }; 9249 9250 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9251 new Comparator<ProviderInfo>() { 9252 public int compare(ProviderInfo p1, ProviderInfo p2) { 9253 final int v1 = p1.initOrder; 9254 final int v2 = p2.initOrder; 9255 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9256 } 9257 }; 9258 9259 final void sendPackageBroadcast(final String action, final String pkg, 9260 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9261 final int[] userIds) { 9262 mHandler.post(new Runnable() { 9263 @Override 9264 public void run() { 9265 try { 9266 final IActivityManager am = ActivityManagerNative.getDefault(); 9267 if (am == null) return; 9268 final int[] resolvedUserIds; 9269 if (userIds == null) { 9270 resolvedUserIds = am.getRunningUserIds(); 9271 } else { 9272 resolvedUserIds = userIds; 9273 } 9274 for (int id : resolvedUserIds) { 9275 final Intent intent = new Intent(action, 9276 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9277 if (extras != null) { 9278 intent.putExtras(extras); 9279 } 9280 if (targetPkg != null) { 9281 intent.setPackage(targetPkg); 9282 } 9283 // Modify the UID when posting to other users 9284 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9285 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9286 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9287 intent.putExtra(Intent.EXTRA_UID, uid); 9288 } 9289 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9290 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9291 if (DEBUG_BROADCASTS) { 9292 RuntimeException here = new RuntimeException("here"); 9293 here.fillInStackTrace(); 9294 Slog.d(TAG, "Sending to user " + id + ": " 9295 + intent.toShortString(false, true, false, false) 9296 + " " + intent.getExtras(), here); 9297 } 9298 am.broadcastIntent(null, intent, null, finishedReceiver, 9299 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9300 null, finishedReceiver != null, false, id); 9301 } 9302 } catch (RemoteException ex) { 9303 } 9304 } 9305 }); 9306 } 9307 9308 /** 9309 * Check if the external storage media is available. This is true if there 9310 * is a mounted external storage medium or if the external storage is 9311 * emulated. 9312 */ 9313 private boolean isExternalMediaAvailable() { 9314 return mMediaMounted || Environment.isExternalStorageEmulated(); 9315 } 9316 9317 @Override 9318 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9319 // writer 9320 synchronized (mPackages) { 9321 if (!isExternalMediaAvailable()) { 9322 // If the external storage is no longer mounted at this point, 9323 // the caller may not have been able to delete all of this 9324 // packages files and can not delete any more. Bail. 9325 return null; 9326 } 9327 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9328 if (lastPackage != null) { 9329 pkgs.remove(lastPackage); 9330 } 9331 if (pkgs.size() > 0) { 9332 return pkgs.get(0); 9333 } 9334 } 9335 return null; 9336 } 9337 9338 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9339 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9340 userId, andCode ? 1 : 0, packageName); 9341 if (mSystemReady) { 9342 msg.sendToTarget(); 9343 } else { 9344 if (mPostSystemReadyMessages == null) { 9345 mPostSystemReadyMessages = new ArrayList<>(); 9346 } 9347 mPostSystemReadyMessages.add(msg); 9348 } 9349 } 9350 9351 void startCleaningPackages() { 9352 // reader 9353 synchronized (mPackages) { 9354 if (!isExternalMediaAvailable()) { 9355 return; 9356 } 9357 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9358 return; 9359 } 9360 } 9361 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9362 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9363 IActivityManager am = ActivityManagerNative.getDefault(); 9364 if (am != null) { 9365 try { 9366 am.startService(null, intent, null, mContext.getOpPackageName(), 9367 UserHandle.USER_OWNER); 9368 } catch (RemoteException e) { 9369 } 9370 } 9371 } 9372 9373 @Override 9374 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9375 int installFlags, String installerPackageName, VerificationParams verificationParams, 9376 String packageAbiOverride) { 9377 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9378 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9379 } 9380 9381 @Override 9382 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9383 int installFlags, String installerPackageName, VerificationParams verificationParams, 9384 String packageAbiOverride, int userId) { 9385 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9386 9387 final int callingUid = Binder.getCallingUid(); 9388 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9389 9390 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9391 try { 9392 if (observer != null) { 9393 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9394 } 9395 } catch (RemoteException re) { 9396 } 9397 return; 9398 } 9399 9400 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9401 installFlags |= PackageManager.INSTALL_FROM_ADB; 9402 9403 } else { 9404 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9405 // about installerPackageName. 9406 9407 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9408 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9409 } 9410 9411 UserHandle user; 9412 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9413 user = UserHandle.ALL; 9414 } else { 9415 user = new UserHandle(userId); 9416 } 9417 9418 // Only system components can circumvent runtime permissions when installing. 9419 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9420 && mContext.checkCallingOrSelfPermission(Manifest.permission 9421 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9422 throw new SecurityException("You need the " 9423 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9424 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9425 } 9426 9427 verificationParams.setInstallerUid(callingUid); 9428 9429 final File originFile = new File(originPath); 9430 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9431 9432 final Message msg = mHandler.obtainMessage(INIT_COPY); 9433 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9434 null, verificationParams, user, packageAbiOverride); 9435 mHandler.sendMessage(msg); 9436 } 9437 9438 void installStage(String packageName, File stagedDir, String stagedCid, 9439 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9440 String installerPackageName, int installerUid, UserHandle user) { 9441 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9442 params.referrerUri, installerUid, null); 9443 verifParams.setInstallerUid(installerUid); 9444 9445 final OriginInfo origin; 9446 if (stagedDir != null) { 9447 origin = OriginInfo.fromStagedFile(stagedDir); 9448 } else { 9449 origin = OriginInfo.fromStagedContainer(stagedCid); 9450 } 9451 9452 final Message msg = mHandler.obtainMessage(INIT_COPY); 9453 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9454 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9455 mHandler.sendMessage(msg); 9456 } 9457 9458 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9459 Bundle extras = new Bundle(1); 9460 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9461 9462 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9463 packageName, extras, null, null, new int[] {userId}); 9464 try { 9465 IActivityManager am = ActivityManagerNative.getDefault(); 9466 final boolean isSystem = 9467 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9468 if (isSystem && am.isUserRunning(userId, false)) { 9469 // The just-installed/enabled app is bundled on the system, so presumed 9470 // to be able to run automatically without needing an explicit launch. 9471 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9472 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9473 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9474 .setPackage(packageName); 9475 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9476 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9477 } 9478 } catch (RemoteException e) { 9479 // shouldn't happen 9480 Slog.w(TAG, "Unable to bootstrap installed package", e); 9481 } 9482 } 9483 9484 @Override 9485 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9486 int userId) { 9487 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9488 PackageSetting pkgSetting; 9489 final int uid = Binder.getCallingUid(); 9490 enforceCrossUserPermission(uid, userId, true, true, 9491 "setApplicationHiddenSetting for user " + userId); 9492 9493 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9494 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9495 return false; 9496 } 9497 9498 long callingId = Binder.clearCallingIdentity(); 9499 try { 9500 boolean sendAdded = false; 9501 boolean sendRemoved = false; 9502 // writer 9503 synchronized (mPackages) { 9504 pkgSetting = mSettings.mPackages.get(packageName); 9505 if (pkgSetting == null) { 9506 return false; 9507 } 9508 if (pkgSetting.getHidden(userId) != hidden) { 9509 pkgSetting.setHidden(hidden, userId); 9510 mSettings.writePackageRestrictionsLPr(userId); 9511 if (hidden) { 9512 sendRemoved = true; 9513 } else { 9514 sendAdded = true; 9515 } 9516 } 9517 } 9518 if (sendAdded) { 9519 sendPackageAddedForUser(packageName, pkgSetting, userId); 9520 return true; 9521 } 9522 if (sendRemoved) { 9523 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9524 "hiding pkg"); 9525 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9526 } 9527 } finally { 9528 Binder.restoreCallingIdentity(callingId); 9529 } 9530 return false; 9531 } 9532 9533 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9534 int userId) { 9535 final PackageRemovedInfo info = new PackageRemovedInfo(); 9536 info.removedPackage = packageName; 9537 info.removedUsers = new int[] {userId}; 9538 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9539 info.sendBroadcast(false, false, false); 9540 } 9541 9542 /** 9543 * Returns true if application is not found or there was an error. Otherwise it returns 9544 * the hidden state of the package for the given user. 9545 */ 9546 @Override 9547 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9548 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9549 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9550 false, "getApplicationHidden for user " + userId); 9551 PackageSetting pkgSetting; 9552 long callingId = Binder.clearCallingIdentity(); 9553 try { 9554 // writer 9555 synchronized (mPackages) { 9556 pkgSetting = mSettings.mPackages.get(packageName); 9557 if (pkgSetting == null) { 9558 return true; 9559 } 9560 return pkgSetting.getHidden(userId); 9561 } 9562 } finally { 9563 Binder.restoreCallingIdentity(callingId); 9564 } 9565 } 9566 9567 /** 9568 * @hide 9569 */ 9570 @Override 9571 public int installExistingPackageAsUser(String packageName, int userId) { 9572 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9573 null); 9574 PackageSetting pkgSetting; 9575 final int uid = Binder.getCallingUid(); 9576 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9577 + userId); 9578 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9579 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9580 } 9581 9582 long callingId = Binder.clearCallingIdentity(); 9583 try { 9584 boolean sendAdded = false; 9585 9586 // writer 9587 synchronized (mPackages) { 9588 pkgSetting = mSettings.mPackages.get(packageName); 9589 if (pkgSetting == null) { 9590 return PackageManager.INSTALL_FAILED_INVALID_URI; 9591 } 9592 if (!pkgSetting.getInstalled(userId)) { 9593 pkgSetting.setInstalled(true, userId); 9594 pkgSetting.setHidden(false, userId); 9595 mSettings.writePackageRestrictionsLPr(userId); 9596 sendAdded = true; 9597 } 9598 } 9599 9600 if (sendAdded) { 9601 sendPackageAddedForUser(packageName, pkgSetting, userId); 9602 } 9603 } finally { 9604 Binder.restoreCallingIdentity(callingId); 9605 } 9606 9607 return PackageManager.INSTALL_SUCCEEDED; 9608 } 9609 9610 boolean isUserRestricted(int userId, String restrictionKey) { 9611 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9612 if (restrictions.getBoolean(restrictionKey, false)) { 9613 Log.w(TAG, "User is restricted: " + restrictionKey); 9614 return true; 9615 } 9616 return false; 9617 } 9618 9619 @Override 9620 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9621 mContext.enforceCallingOrSelfPermission( 9622 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9623 "Only package verification agents can verify applications"); 9624 9625 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9626 final PackageVerificationResponse response = new PackageVerificationResponse( 9627 verificationCode, Binder.getCallingUid()); 9628 msg.arg1 = id; 9629 msg.obj = response; 9630 mHandler.sendMessage(msg); 9631 } 9632 9633 @Override 9634 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9635 long millisecondsToDelay) { 9636 mContext.enforceCallingOrSelfPermission( 9637 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9638 "Only package verification agents can extend verification timeouts"); 9639 9640 final PackageVerificationState state = mPendingVerification.get(id); 9641 final PackageVerificationResponse response = new PackageVerificationResponse( 9642 verificationCodeAtTimeout, Binder.getCallingUid()); 9643 9644 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9645 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9646 } 9647 if (millisecondsToDelay < 0) { 9648 millisecondsToDelay = 0; 9649 } 9650 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9651 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9652 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9653 } 9654 9655 if ((state != null) && !state.timeoutExtended()) { 9656 state.extendTimeout(); 9657 9658 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9659 msg.arg1 = id; 9660 msg.obj = response; 9661 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9662 } 9663 } 9664 9665 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9666 int verificationCode, UserHandle user) { 9667 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9668 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9669 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9670 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9671 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9672 9673 mContext.sendBroadcastAsUser(intent, user, 9674 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9675 } 9676 9677 private ComponentName matchComponentForVerifier(String packageName, 9678 List<ResolveInfo> receivers) { 9679 ActivityInfo targetReceiver = null; 9680 9681 final int NR = receivers.size(); 9682 for (int i = 0; i < NR; i++) { 9683 final ResolveInfo info = receivers.get(i); 9684 if (info.activityInfo == null) { 9685 continue; 9686 } 9687 9688 if (packageName.equals(info.activityInfo.packageName)) { 9689 targetReceiver = info.activityInfo; 9690 break; 9691 } 9692 } 9693 9694 if (targetReceiver == null) { 9695 return null; 9696 } 9697 9698 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9699 } 9700 9701 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9702 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9703 if (pkgInfo.verifiers.length == 0) { 9704 return null; 9705 } 9706 9707 final int N = pkgInfo.verifiers.length; 9708 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9709 for (int i = 0; i < N; i++) { 9710 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9711 9712 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9713 receivers); 9714 if (comp == null) { 9715 continue; 9716 } 9717 9718 final int verifierUid = getUidForVerifier(verifierInfo); 9719 if (verifierUid == -1) { 9720 continue; 9721 } 9722 9723 if (DEBUG_VERIFY) { 9724 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9725 + " with the correct signature"); 9726 } 9727 sufficientVerifiers.add(comp); 9728 verificationState.addSufficientVerifier(verifierUid); 9729 } 9730 9731 return sufficientVerifiers; 9732 } 9733 9734 private int getUidForVerifier(VerifierInfo verifierInfo) { 9735 synchronized (mPackages) { 9736 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9737 if (pkg == null) { 9738 return -1; 9739 } else if (pkg.mSignatures.length != 1) { 9740 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9741 + " has more than one signature; ignoring"); 9742 return -1; 9743 } 9744 9745 /* 9746 * If the public key of the package's signature does not match 9747 * our expected public key, then this is a different package and 9748 * we should skip. 9749 */ 9750 9751 final byte[] expectedPublicKey; 9752 try { 9753 final Signature verifierSig = pkg.mSignatures[0]; 9754 final PublicKey publicKey = verifierSig.getPublicKey(); 9755 expectedPublicKey = publicKey.getEncoded(); 9756 } catch (CertificateException e) { 9757 return -1; 9758 } 9759 9760 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9761 9762 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9763 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9764 + " does not have the expected public key; ignoring"); 9765 return -1; 9766 } 9767 9768 return pkg.applicationInfo.uid; 9769 } 9770 } 9771 9772 @Override 9773 public void finishPackageInstall(int token) { 9774 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9775 9776 if (DEBUG_INSTALL) { 9777 Slog.v(TAG, "BM finishing package install for " + token); 9778 } 9779 9780 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9781 mHandler.sendMessage(msg); 9782 } 9783 9784 /** 9785 * Get the verification agent timeout. 9786 * 9787 * @return verification timeout in milliseconds 9788 */ 9789 private long getVerificationTimeout() { 9790 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9791 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9792 DEFAULT_VERIFICATION_TIMEOUT); 9793 } 9794 9795 /** 9796 * Get the default verification agent response code. 9797 * 9798 * @return default verification response code 9799 */ 9800 private int getDefaultVerificationResponse() { 9801 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9802 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9803 DEFAULT_VERIFICATION_RESPONSE); 9804 } 9805 9806 /** 9807 * Check whether or not package verification has been enabled. 9808 * 9809 * @return true if verification should be performed 9810 */ 9811 private boolean isVerificationEnabled(int userId, int installFlags) { 9812 if (!DEFAULT_VERIFY_ENABLE) { 9813 return false; 9814 } 9815 9816 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9817 9818 // Check if installing from ADB 9819 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9820 // Do not run verification in a test harness environment 9821 if (ActivityManager.isRunningInTestHarness()) { 9822 return false; 9823 } 9824 if (ensureVerifyAppsEnabled) { 9825 return true; 9826 } 9827 // Check if the developer does not want package verification for ADB installs 9828 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9829 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9830 return false; 9831 } 9832 } 9833 9834 if (ensureVerifyAppsEnabled) { 9835 return true; 9836 } 9837 9838 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9839 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9840 } 9841 9842 @Override 9843 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9844 throws RemoteException { 9845 mContext.enforceCallingOrSelfPermission( 9846 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9847 "Only intentfilter verification agents can verify applications"); 9848 9849 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9850 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9851 Binder.getCallingUid(), verificationCode, failedDomains); 9852 msg.arg1 = id; 9853 msg.obj = response; 9854 mHandler.sendMessage(msg); 9855 } 9856 9857 @Override 9858 public int getIntentVerificationStatus(String packageName, int userId) { 9859 synchronized (mPackages) { 9860 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9861 } 9862 } 9863 9864 @Override 9865 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9866 mContext.enforceCallingOrSelfPermission( 9867 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9868 9869 boolean result = false; 9870 synchronized (mPackages) { 9871 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9872 } 9873 if (result) { 9874 scheduleWritePackageRestrictionsLocked(userId); 9875 } 9876 return result; 9877 } 9878 9879 @Override 9880 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9881 synchronized (mPackages) { 9882 return mSettings.getIntentFilterVerificationsLPr(packageName); 9883 } 9884 } 9885 9886 @Override 9887 public List<IntentFilter> getAllIntentFilters(String packageName) { 9888 if (TextUtils.isEmpty(packageName)) { 9889 return Collections.<IntentFilter>emptyList(); 9890 } 9891 synchronized (mPackages) { 9892 PackageParser.Package pkg = mPackages.get(packageName); 9893 if (pkg == null || pkg.activities == null) { 9894 return Collections.<IntentFilter>emptyList(); 9895 } 9896 final int count = pkg.activities.size(); 9897 ArrayList<IntentFilter> result = new ArrayList<>(); 9898 for (int n=0; n<count; n++) { 9899 PackageParser.Activity activity = pkg.activities.get(n); 9900 if (activity.intents != null || activity.intents.size() > 0) { 9901 result.addAll(activity.intents); 9902 } 9903 } 9904 return result; 9905 } 9906 } 9907 9908 @Override 9909 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9910 mContext.enforceCallingOrSelfPermission( 9911 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9912 9913 synchronized (mPackages) { 9914 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9915 if (packageName != null) { 9916 result |= updateIntentVerificationStatus(packageName, 9917 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9918 UserHandle.myUserId()); 9919 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9920 packageName, userId); 9921 } 9922 return result; 9923 } 9924 } 9925 9926 @Override 9927 public String getDefaultBrowserPackageName(int userId) { 9928 synchronized (mPackages) { 9929 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9930 } 9931 } 9932 9933 /** 9934 * Get the "allow unknown sources" setting. 9935 * 9936 * @return the current "allow unknown sources" setting 9937 */ 9938 private int getUnknownSourcesSettings() { 9939 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9940 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9941 -1); 9942 } 9943 9944 @Override 9945 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9946 final int uid = Binder.getCallingUid(); 9947 // writer 9948 synchronized (mPackages) { 9949 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9950 if (targetPackageSetting == null) { 9951 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9952 } 9953 9954 PackageSetting installerPackageSetting; 9955 if (installerPackageName != null) { 9956 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9957 if (installerPackageSetting == null) { 9958 throw new IllegalArgumentException("Unknown installer package: " 9959 + installerPackageName); 9960 } 9961 } else { 9962 installerPackageSetting = null; 9963 } 9964 9965 Signature[] callerSignature; 9966 Object obj = mSettings.getUserIdLPr(uid); 9967 if (obj != null) { 9968 if (obj instanceof SharedUserSetting) { 9969 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9970 } else if (obj instanceof PackageSetting) { 9971 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9972 } else { 9973 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9974 } 9975 } else { 9976 throw new SecurityException("Unknown calling uid " + uid); 9977 } 9978 9979 // Verify: can't set installerPackageName to a package that is 9980 // not signed with the same cert as the caller. 9981 if (installerPackageSetting != null) { 9982 if (compareSignatures(callerSignature, 9983 installerPackageSetting.signatures.mSignatures) 9984 != PackageManager.SIGNATURE_MATCH) { 9985 throw new SecurityException( 9986 "Caller does not have same cert as new installer package " 9987 + installerPackageName); 9988 } 9989 } 9990 9991 // Verify: if target already has an installer package, it must 9992 // be signed with the same cert as the caller. 9993 if (targetPackageSetting.installerPackageName != null) { 9994 PackageSetting setting = mSettings.mPackages.get( 9995 targetPackageSetting.installerPackageName); 9996 // If the currently set package isn't valid, then it's always 9997 // okay to change it. 9998 if (setting != null) { 9999 if (compareSignatures(callerSignature, 10000 setting.signatures.mSignatures) 10001 != PackageManager.SIGNATURE_MATCH) { 10002 throw new SecurityException( 10003 "Caller does not have same cert as old installer package " 10004 + targetPackageSetting.installerPackageName); 10005 } 10006 } 10007 } 10008 10009 // Okay! 10010 targetPackageSetting.installerPackageName = installerPackageName; 10011 scheduleWriteSettingsLocked(); 10012 } 10013 } 10014 10015 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10016 // Queue up an async operation since the package installation may take a little while. 10017 mHandler.post(new Runnable() { 10018 public void run() { 10019 mHandler.removeCallbacks(this); 10020 // Result object to be returned 10021 PackageInstalledInfo res = new PackageInstalledInfo(); 10022 res.returnCode = currentStatus; 10023 res.uid = -1; 10024 res.pkg = null; 10025 res.removedInfo = new PackageRemovedInfo(); 10026 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10027 args.doPreInstall(res.returnCode); 10028 synchronized (mInstallLock) { 10029 installPackageLI(args, res); 10030 } 10031 args.doPostInstall(res.returnCode, res.uid); 10032 } 10033 10034 // A restore should be performed at this point if (a) the install 10035 // succeeded, (b) the operation is not an update, and (c) the new 10036 // package has not opted out of backup participation. 10037 final boolean update = res.removedInfo.removedPackage != null; 10038 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10039 boolean doRestore = !update 10040 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10041 10042 // Set up the post-install work request bookkeeping. This will be used 10043 // and cleaned up by the post-install event handling regardless of whether 10044 // there's a restore pass performed. Token values are >= 1. 10045 int token; 10046 if (mNextInstallToken < 0) mNextInstallToken = 1; 10047 token = mNextInstallToken++; 10048 10049 PostInstallData data = new PostInstallData(args, res); 10050 mRunningInstalls.put(token, data); 10051 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10052 10053 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10054 // Pass responsibility to the Backup Manager. It will perform a 10055 // restore if appropriate, then pass responsibility back to the 10056 // Package Manager to run the post-install observer callbacks 10057 // and broadcasts. 10058 IBackupManager bm = IBackupManager.Stub.asInterface( 10059 ServiceManager.getService(Context.BACKUP_SERVICE)); 10060 if (bm != null) { 10061 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10062 + " to BM for possible restore"); 10063 try { 10064 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10065 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10066 } else { 10067 doRestore = false; 10068 } 10069 } catch (RemoteException e) { 10070 // can't happen; the backup manager is local 10071 } catch (Exception e) { 10072 Slog.e(TAG, "Exception trying to enqueue restore", e); 10073 doRestore = false; 10074 } 10075 } else { 10076 Slog.e(TAG, "Backup Manager not found!"); 10077 doRestore = false; 10078 } 10079 } 10080 10081 if (!doRestore) { 10082 // No restore possible, or the Backup Manager was mysteriously not 10083 // available -- just fire the post-install work request directly. 10084 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10085 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10086 mHandler.sendMessage(msg); 10087 } 10088 } 10089 }); 10090 } 10091 10092 private abstract class HandlerParams { 10093 private static final int MAX_RETRIES = 4; 10094 10095 /** 10096 * Number of times startCopy() has been attempted and had a non-fatal 10097 * error. 10098 */ 10099 private int mRetries = 0; 10100 10101 /** User handle for the user requesting the information or installation. */ 10102 private final UserHandle mUser; 10103 10104 HandlerParams(UserHandle user) { 10105 mUser = user; 10106 } 10107 10108 UserHandle getUser() { 10109 return mUser; 10110 } 10111 10112 final boolean startCopy() { 10113 boolean res; 10114 try { 10115 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10116 10117 if (++mRetries > MAX_RETRIES) { 10118 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10119 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10120 handleServiceError(); 10121 return false; 10122 } else { 10123 handleStartCopy(); 10124 res = true; 10125 } 10126 } catch (RemoteException e) { 10127 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10128 mHandler.sendEmptyMessage(MCS_RECONNECT); 10129 res = false; 10130 } 10131 handleReturnCode(); 10132 return res; 10133 } 10134 10135 final void serviceError() { 10136 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10137 handleServiceError(); 10138 handleReturnCode(); 10139 } 10140 10141 abstract void handleStartCopy() throws RemoteException; 10142 abstract void handleServiceError(); 10143 abstract void handleReturnCode(); 10144 } 10145 10146 class MeasureParams extends HandlerParams { 10147 private final PackageStats mStats; 10148 private boolean mSuccess; 10149 10150 private final IPackageStatsObserver mObserver; 10151 10152 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10153 super(new UserHandle(stats.userHandle)); 10154 mObserver = observer; 10155 mStats = stats; 10156 } 10157 10158 @Override 10159 public String toString() { 10160 return "MeasureParams{" 10161 + Integer.toHexString(System.identityHashCode(this)) 10162 + " " + mStats.packageName + "}"; 10163 } 10164 10165 @Override 10166 void handleStartCopy() throws RemoteException { 10167 synchronized (mInstallLock) { 10168 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10169 } 10170 10171 if (mSuccess) { 10172 final boolean mounted; 10173 if (Environment.isExternalStorageEmulated()) { 10174 mounted = true; 10175 } else { 10176 final String status = Environment.getExternalStorageState(); 10177 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10178 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10179 } 10180 10181 if (mounted) { 10182 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10183 10184 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10185 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10186 10187 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10188 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10189 10190 // Always subtract cache size, since it's a subdirectory 10191 mStats.externalDataSize -= mStats.externalCacheSize; 10192 10193 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10194 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10195 10196 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10197 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10198 } 10199 } 10200 } 10201 10202 @Override 10203 void handleReturnCode() { 10204 if (mObserver != null) { 10205 try { 10206 mObserver.onGetStatsCompleted(mStats, mSuccess); 10207 } catch (RemoteException e) { 10208 Slog.i(TAG, "Observer no longer exists."); 10209 } 10210 } 10211 } 10212 10213 @Override 10214 void handleServiceError() { 10215 Slog.e(TAG, "Could not measure application " + mStats.packageName 10216 + " external storage"); 10217 } 10218 } 10219 10220 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10221 throws RemoteException { 10222 long result = 0; 10223 for (File path : paths) { 10224 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10225 } 10226 return result; 10227 } 10228 10229 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10230 for (File path : paths) { 10231 try { 10232 mcs.clearDirectory(path.getAbsolutePath()); 10233 } catch (RemoteException e) { 10234 } 10235 } 10236 } 10237 10238 static class OriginInfo { 10239 /** 10240 * Location where install is coming from, before it has been 10241 * copied/renamed into place. This could be a single monolithic APK 10242 * file, or a cluster directory. This location may be untrusted. 10243 */ 10244 final File file; 10245 final String cid; 10246 10247 /** 10248 * Flag indicating that {@link #file} or {@link #cid} has already been 10249 * staged, meaning downstream users don't need to defensively copy the 10250 * contents. 10251 */ 10252 final boolean staged; 10253 10254 /** 10255 * Flag indicating that {@link #file} or {@link #cid} is an already 10256 * installed app that is being moved. 10257 */ 10258 final boolean existing; 10259 10260 final String resolvedPath; 10261 final File resolvedFile; 10262 10263 static OriginInfo fromNothing() { 10264 return new OriginInfo(null, null, false, false); 10265 } 10266 10267 static OriginInfo fromUntrustedFile(File file) { 10268 return new OriginInfo(file, null, false, false); 10269 } 10270 10271 static OriginInfo fromExistingFile(File file) { 10272 return new OriginInfo(file, null, false, true); 10273 } 10274 10275 static OriginInfo fromStagedFile(File file) { 10276 return new OriginInfo(file, null, true, false); 10277 } 10278 10279 static OriginInfo fromStagedContainer(String cid) { 10280 return new OriginInfo(null, cid, true, false); 10281 } 10282 10283 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10284 this.file = file; 10285 this.cid = cid; 10286 this.staged = staged; 10287 this.existing = existing; 10288 10289 if (cid != null) { 10290 resolvedPath = PackageHelper.getSdDir(cid); 10291 resolvedFile = new File(resolvedPath); 10292 } else if (file != null) { 10293 resolvedPath = file.getAbsolutePath(); 10294 resolvedFile = file; 10295 } else { 10296 resolvedPath = null; 10297 resolvedFile = null; 10298 } 10299 } 10300 } 10301 10302 class MoveInfo { 10303 final int moveId; 10304 final String fromUuid; 10305 final String toUuid; 10306 final String packageName; 10307 final String dataAppName; 10308 final int appId; 10309 final String seinfo; 10310 10311 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10312 String dataAppName, int appId, String seinfo) { 10313 this.moveId = moveId; 10314 this.fromUuid = fromUuid; 10315 this.toUuid = toUuid; 10316 this.packageName = packageName; 10317 this.dataAppName = dataAppName; 10318 this.appId = appId; 10319 this.seinfo = seinfo; 10320 } 10321 } 10322 10323 class InstallParams extends HandlerParams { 10324 final OriginInfo origin; 10325 final MoveInfo move; 10326 final IPackageInstallObserver2 observer; 10327 int installFlags; 10328 final String installerPackageName; 10329 final String volumeUuid; 10330 final VerificationParams verificationParams; 10331 private InstallArgs mArgs; 10332 private int mRet; 10333 final String packageAbiOverride; 10334 10335 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10336 int installFlags, String installerPackageName, String volumeUuid, 10337 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10338 super(user); 10339 this.origin = origin; 10340 this.move = move; 10341 this.observer = observer; 10342 this.installFlags = installFlags; 10343 this.installerPackageName = installerPackageName; 10344 this.volumeUuid = volumeUuid; 10345 this.verificationParams = verificationParams; 10346 this.packageAbiOverride = packageAbiOverride; 10347 } 10348 10349 @Override 10350 public String toString() { 10351 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10352 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10353 } 10354 10355 public ManifestDigest getManifestDigest() { 10356 if (verificationParams == null) { 10357 return null; 10358 } 10359 return verificationParams.getManifestDigest(); 10360 } 10361 10362 private int installLocationPolicy(PackageInfoLite pkgLite) { 10363 String packageName = pkgLite.packageName; 10364 int installLocation = pkgLite.installLocation; 10365 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10366 // reader 10367 synchronized (mPackages) { 10368 PackageParser.Package pkg = mPackages.get(packageName); 10369 if (pkg != null) { 10370 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10371 // Check for downgrading. 10372 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10373 try { 10374 checkDowngrade(pkg, pkgLite); 10375 } catch (PackageManagerException e) { 10376 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10377 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10378 } 10379 } 10380 // Check for updated system application. 10381 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10382 if (onSd) { 10383 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10384 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10385 } 10386 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10387 } else { 10388 if (onSd) { 10389 // Install flag overrides everything. 10390 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10391 } 10392 // If current upgrade specifies particular preference 10393 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10394 // Application explicitly specified internal. 10395 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10396 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10397 // App explictly prefers external. Let policy decide 10398 } else { 10399 // Prefer previous location 10400 if (isExternal(pkg)) { 10401 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10402 } 10403 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10404 } 10405 } 10406 } else { 10407 // Invalid install. Return error code 10408 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10409 } 10410 } 10411 } 10412 // All the special cases have been taken care of. 10413 // Return result based on recommended install location. 10414 if (onSd) { 10415 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10416 } 10417 return pkgLite.recommendedInstallLocation; 10418 } 10419 10420 /* 10421 * Invoke remote method to get package information and install 10422 * location values. Override install location based on default 10423 * policy if needed and then create install arguments based 10424 * on the install location. 10425 */ 10426 public void handleStartCopy() throws RemoteException { 10427 int ret = PackageManager.INSTALL_SUCCEEDED; 10428 10429 // If we're already staged, we've firmly committed to an install location 10430 if (origin.staged) { 10431 if (origin.file != null) { 10432 installFlags |= PackageManager.INSTALL_INTERNAL; 10433 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10434 } else if (origin.cid != null) { 10435 installFlags |= PackageManager.INSTALL_EXTERNAL; 10436 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10437 } else { 10438 throw new IllegalStateException("Invalid stage location"); 10439 } 10440 } 10441 10442 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10443 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10444 10445 PackageInfoLite pkgLite = null; 10446 10447 if (onInt && onSd) { 10448 // Check if both bits are set. 10449 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10450 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10451 } else { 10452 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10453 packageAbiOverride); 10454 10455 /* 10456 * If we have too little free space, try to free cache 10457 * before giving up. 10458 */ 10459 if (!origin.staged && pkgLite.recommendedInstallLocation 10460 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10461 // TODO: focus freeing disk space on the target device 10462 final StorageManager storage = StorageManager.from(mContext); 10463 final long lowThreshold = storage.getStorageLowBytes( 10464 Environment.getDataDirectory()); 10465 10466 final long sizeBytes = mContainerService.calculateInstalledSize( 10467 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10468 10469 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10470 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10471 installFlags, packageAbiOverride); 10472 } 10473 10474 /* 10475 * The cache free must have deleted the file we 10476 * downloaded to install. 10477 * 10478 * TODO: fix the "freeCache" call to not delete 10479 * the file we care about. 10480 */ 10481 if (pkgLite.recommendedInstallLocation 10482 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10483 pkgLite.recommendedInstallLocation 10484 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10485 } 10486 } 10487 } 10488 10489 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10490 int loc = pkgLite.recommendedInstallLocation; 10491 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10492 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10493 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10494 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10495 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10496 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10497 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10498 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10499 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10500 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10501 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10502 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10503 } else { 10504 // Override with defaults if needed. 10505 loc = installLocationPolicy(pkgLite); 10506 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10507 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10508 } else if (!onSd && !onInt) { 10509 // Override install location with flags 10510 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10511 // Set the flag to install on external media. 10512 installFlags |= PackageManager.INSTALL_EXTERNAL; 10513 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10514 } else { 10515 // Make sure the flag for installing on external 10516 // media is unset 10517 installFlags |= PackageManager.INSTALL_INTERNAL; 10518 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10519 } 10520 } 10521 } 10522 } 10523 10524 final InstallArgs args = createInstallArgs(this); 10525 mArgs = args; 10526 10527 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10528 /* 10529 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10530 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10531 */ 10532 int userIdentifier = getUser().getIdentifier(); 10533 if (userIdentifier == UserHandle.USER_ALL 10534 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10535 userIdentifier = UserHandle.USER_OWNER; 10536 } 10537 10538 /* 10539 * Determine if we have any installed package verifiers. If we 10540 * do, then we'll defer to them to verify the packages. 10541 */ 10542 final int requiredUid = mRequiredVerifierPackage == null ? -1 10543 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10544 if (!origin.existing && requiredUid != -1 10545 && isVerificationEnabled(userIdentifier, installFlags)) { 10546 final Intent verification = new Intent( 10547 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10548 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10549 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10550 PACKAGE_MIME_TYPE); 10551 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10552 10553 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10554 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10555 0 /* TODO: Which userId? */); 10556 10557 if (DEBUG_VERIFY) { 10558 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10559 + verification.toString() + " with " + pkgLite.verifiers.length 10560 + " optional verifiers"); 10561 } 10562 10563 final int verificationId = mPendingVerificationToken++; 10564 10565 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10566 10567 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10568 installerPackageName); 10569 10570 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10571 installFlags); 10572 10573 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10574 pkgLite.packageName); 10575 10576 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10577 pkgLite.versionCode); 10578 10579 if (verificationParams != null) { 10580 if (verificationParams.getVerificationURI() != null) { 10581 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10582 verificationParams.getVerificationURI()); 10583 } 10584 if (verificationParams.getOriginatingURI() != null) { 10585 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10586 verificationParams.getOriginatingURI()); 10587 } 10588 if (verificationParams.getReferrer() != null) { 10589 verification.putExtra(Intent.EXTRA_REFERRER, 10590 verificationParams.getReferrer()); 10591 } 10592 if (verificationParams.getOriginatingUid() >= 0) { 10593 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10594 verificationParams.getOriginatingUid()); 10595 } 10596 if (verificationParams.getInstallerUid() >= 0) { 10597 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10598 verificationParams.getInstallerUid()); 10599 } 10600 } 10601 10602 final PackageVerificationState verificationState = new PackageVerificationState( 10603 requiredUid, args); 10604 10605 mPendingVerification.append(verificationId, verificationState); 10606 10607 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10608 receivers, verificationState); 10609 10610 /* 10611 * If any sufficient verifiers were listed in the package 10612 * manifest, attempt to ask them. 10613 */ 10614 if (sufficientVerifiers != null) { 10615 final int N = sufficientVerifiers.size(); 10616 if (N == 0) { 10617 Slog.i(TAG, "Additional verifiers required, but none installed."); 10618 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10619 } else { 10620 for (int i = 0; i < N; i++) { 10621 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10622 10623 final Intent sufficientIntent = new Intent(verification); 10624 sufficientIntent.setComponent(verifierComponent); 10625 10626 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10627 } 10628 } 10629 } 10630 10631 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10632 mRequiredVerifierPackage, receivers); 10633 if (ret == PackageManager.INSTALL_SUCCEEDED 10634 && mRequiredVerifierPackage != null) { 10635 /* 10636 * Send the intent to the required verification agent, 10637 * but only start the verification timeout after the 10638 * target BroadcastReceivers have run. 10639 */ 10640 verification.setComponent(requiredVerifierComponent); 10641 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10642 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10643 new BroadcastReceiver() { 10644 @Override 10645 public void onReceive(Context context, Intent intent) { 10646 final Message msg = mHandler 10647 .obtainMessage(CHECK_PENDING_VERIFICATION); 10648 msg.arg1 = verificationId; 10649 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10650 } 10651 }, null, 0, null, null); 10652 10653 /* 10654 * We don't want the copy to proceed until verification 10655 * succeeds, so null out this field. 10656 */ 10657 mArgs = null; 10658 } 10659 } else { 10660 /* 10661 * No package verification is enabled, so immediately start 10662 * the remote call to initiate copy using temporary file. 10663 */ 10664 ret = args.copyApk(mContainerService, true); 10665 } 10666 } 10667 10668 mRet = ret; 10669 } 10670 10671 @Override 10672 void handleReturnCode() { 10673 // If mArgs is null, then MCS couldn't be reached. When it 10674 // reconnects, it will try again to install. At that point, this 10675 // will succeed. 10676 if (mArgs != null) { 10677 processPendingInstall(mArgs, mRet); 10678 } 10679 } 10680 10681 @Override 10682 void handleServiceError() { 10683 mArgs = createInstallArgs(this); 10684 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10685 } 10686 10687 public boolean isForwardLocked() { 10688 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10689 } 10690 } 10691 10692 /** 10693 * Used during creation of InstallArgs 10694 * 10695 * @param installFlags package installation flags 10696 * @return true if should be installed on external storage 10697 */ 10698 private static boolean installOnExternalAsec(int installFlags) { 10699 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10700 return false; 10701 } 10702 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10703 return true; 10704 } 10705 return false; 10706 } 10707 10708 /** 10709 * Used during creation of InstallArgs 10710 * 10711 * @param installFlags package installation flags 10712 * @return true if should be installed as forward locked 10713 */ 10714 private static boolean installForwardLocked(int installFlags) { 10715 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10716 } 10717 10718 private InstallArgs createInstallArgs(InstallParams params) { 10719 if (params.move != null) { 10720 return new MoveInstallArgs(params); 10721 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10722 return new AsecInstallArgs(params); 10723 } else { 10724 return new FileInstallArgs(params); 10725 } 10726 } 10727 10728 /** 10729 * Create args that describe an existing installed package. Typically used 10730 * when cleaning up old installs, or used as a move source. 10731 */ 10732 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10733 String resourcePath, String[] instructionSets) { 10734 final boolean isInAsec; 10735 if (installOnExternalAsec(installFlags)) { 10736 /* Apps on SD card are always in ASEC containers. */ 10737 isInAsec = true; 10738 } else if (installForwardLocked(installFlags) 10739 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10740 /* 10741 * Forward-locked apps are only in ASEC containers if they're the 10742 * new style 10743 */ 10744 isInAsec = true; 10745 } else { 10746 isInAsec = false; 10747 } 10748 10749 if (isInAsec) { 10750 return new AsecInstallArgs(codePath, instructionSets, 10751 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10752 } else { 10753 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10754 } 10755 } 10756 10757 static abstract class InstallArgs { 10758 /** @see InstallParams#origin */ 10759 final OriginInfo origin; 10760 /** @see InstallParams#move */ 10761 final MoveInfo move; 10762 10763 final IPackageInstallObserver2 observer; 10764 // Always refers to PackageManager flags only 10765 final int installFlags; 10766 final String installerPackageName; 10767 final String volumeUuid; 10768 final ManifestDigest manifestDigest; 10769 final UserHandle user; 10770 final String abiOverride; 10771 10772 // The list of instruction sets supported by this app. This is currently 10773 // only used during the rmdex() phase to clean up resources. We can get rid of this 10774 // if we move dex files under the common app path. 10775 /* nullable */ String[] instructionSets; 10776 10777 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10778 int installFlags, String installerPackageName, String volumeUuid, 10779 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10780 String abiOverride) { 10781 this.origin = origin; 10782 this.move = move; 10783 this.installFlags = installFlags; 10784 this.observer = observer; 10785 this.installerPackageName = installerPackageName; 10786 this.volumeUuid = volumeUuid; 10787 this.manifestDigest = manifestDigest; 10788 this.user = user; 10789 this.instructionSets = instructionSets; 10790 this.abiOverride = abiOverride; 10791 } 10792 10793 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10794 abstract int doPreInstall(int status); 10795 10796 /** 10797 * Rename package into final resting place. All paths on the given 10798 * scanned package should be updated to reflect the rename. 10799 */ 10800 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10801 abstract int doPostInstall(int status, int uid); 10802 10803 /** @see PackageSettingBase#codePathString */ 10804 abstract String getCodePath(); 10805 /** @see PackageSettingBase#resourcePathString */ 10806 abstract String getResourcePath(); 10807 10808 // Need installer lock especially for dex file removal. 10809 abstract void cleanUpResourcesLI(); 10810 abstract boolean doPostDeleteLI(boolean delete); 10811 10812 /** 10813 * Called before the source arguments are copied. This is used mostly 10814 * for MoveParams when it needs to read the source file to put it in the 10815 * destination. 10816 */ 10817 int doPreCopy() { 10818 return PackageManager.INSTALL_SUCCEEDED; 10819 } 10820 10821 /** 10822 * Called after the source arguments are copied. This is used mostly for 10823 * MoveParams when it needs to read the source file to put it in the 10824 * destination. 10825 * 10826 * @return 10827 */ 10828 int doPostCopy(int uid) { 10829 return PackageManager.INSTALL_SUCCEEDED; 10830 } 10831 10832 protected boolean isFwdLocked() { 10833 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10834 } 10835 10836 protected boolean isExternalAsec() { 10837 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10838 } 10839 10840 UserHandle getUser() { 10841 return user; 10842 } 10843 } 10844 10845 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10846 if (!allCodePaths.isEmpty()) { 10847 if (instructionSets == null) { 10848 throw new IllegalStateException("instructionSet == null"); 10849 } 10850 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10851 for (String codePath : allCodePaths) { 10852 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10853 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10854 if (retCode < 0) { 10855 Slog.w(TAG, "Couldn't remove dex file for package: " 10856 + " at location " + codePath + ", retcode=" + retCode); 10857 // we don't consider this to be a failure of the core package deletion 10858 } 10859 } 10860 } 10861 } 10862 } 10863 10864 /** 10865 * Logic to handle installation of non-ASEC applications, including copying 10866 * and renaming logic. 10867 */ 10868 class FileInstallArgs extends InstallArgs { 10869 private File codeFile; 10870 private File resourceFile; 10871 10872 // Example topology: 10873 // /data/app/com.example/base.apk 10874 // /data/app/com.example/split_foo.apk 10875 // /data/app/com.example/lib/arm/libfoo.so 10876 // /data/app/com.example/lib/arm64/libfoo.so 10877 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10878 10879 /** New install */ 10880 FileInstallArgs(InstallParams params) { 10881 super(params.origin, params.move, params.observer, params.installFlags, 10882 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10883 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10884 if (isFwdLocked()) { 10885 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10886 } 10887 } 10888 10889 /** Existing install */ 10890 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10891 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10892 null); 10893 this.codeFile = (codePath != null) ? new File(codePath) : null; 10894 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10895 } 10896 10897 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10898 if (origin.staged) { 10899 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10900 codeFile = origin.file; 10901 resourceFile = origin.file; 10902 return PackageManager.INSTALL_SUCCEEDED; 10903 } 10904 10905 try { 10906 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10907 codeFile = tempDir; 10908 resourceFile = tempDir; 10909 } catch (IOException e) { 10910 Slog.w(TAG, "Failed to create copy file: " + e); 10911 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10912 } 10913 10914 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10915 @Override 10916 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10917 if (!FileUtils.isValidExtFilename(name)) { 10918 throw new IllegalArgumentException("Invalid filename: " + name); 10919 } 10920 try { 10921 final File file = new File(codeFile, name); 10922 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10923 O_RDWR | O_CREAT, 0644); 10924 Os.chmod(file.getAbsolutePath(), 0644); 10925 return new ParcelFileDescriptor(fd); 10926 } catch (ErrnoException e) { 10927 throw new RemoteException("Failed to open: " + e.getMessage()); 10928 } 10929 } 10930 }; 10931 10932 int ret = PackageManager.INSTALL_SUCCEEDED; 10933 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10934 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10935 Slog.e(TAG, "Failed to copy package"); 10936 return ret; 10937 } 10938 10939 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10940 NativeLibraryHelper.Handle handle = null; 10941 try { 10942 handle = NativeLibraryHelper.Handle.create(codeFile); 10943 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10944 abiOverride); 10945 } catch (IOException e) { 10946 Slog.e(TAG, "Copying native libraries failed", e); 10947 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10948 } finally { 10949 IoUtils.closeQuietly(handle); 10950 } 10951 10952 return ret; 10953 } 10954 10955 int doPreInstall(int status) { 10956 if (status != PackageManager.INSTALL_SUCCEEDED) { 10957 cleanUp(); 10958 } 10959 return status; 10960 } 10961 10962 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10963 if (status != PackageManager.INSTALL_SUCCEEDED) { 10964 cleanUp(); 10965 return false; 10966 } 10967 10968 final File targetDir = codeFile.getParentFile(); 10969 final File beforeCodeFile = codeFile; 10970 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10971 10972 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10973 try { 10974 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10975 } catch (ErrnoException e) { 10976 Slog.w(TAG, "Failed to rename", e); 10977 return false; 10978 } 10979 10980 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10981 Slog.w(TAG, "Failed to restorecon"); 10982 return false; 10983 } 10984 10985 // Reflect the rename internally 10986 codeFile = afterCodeFile; 10987 resourceFile = afterCodeFile; 10988 10989 // Reflect the rename in scanned details 10990 pkg.codePath = afterCodeFile.getAbsolutePath(); 10991 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10992 pkg.baseCodePath); 10993 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10994 pkg.splitCodePaths); 10995 10996 // Reflect the rename in app info 10997 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10998 pkg.applicationInfo.setCodePath(pkg.codePath); 10999 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11000 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11001 pkg.applicationInfo.setResourcePath(pkg.codePath); 11002 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11003 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11004 11005 return true; 11006 } 11007 11008 int doPostInstall(int status, int uid) { 11009 if (status != PackageManager.INSTALL_SUCCEEDED) { 11010 cleanUp(); 11011 } 11012 return status; 11013 } 11014 11015 @Override 11016 String getCodePath() { 11017 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11018 } 11019 11020 @Override 11021 String getResourcePath() { 11022 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11023 } 11024 11025 private boolean cleanUp() { 11026 if (codeFile == null || !codeFile.exists()) { 11027 return false; 11028 } 11029 11030 if (codeFile.isDirectory()) { 11031 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11032 } else { 11033 codeFile.delete(); 11034 } 11035 11036 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11037 resourceFile.delete(); 11038 } 11039 11040 return true; 11041 } 11042 11043 void cleanUpResourcesLI() { 11044 // Try enumerating all code paths before deleting 11045 List<String> allCodePaths = Collections.EMPTY_LIST; 11046 if (codeFile != null && codeFile.exists()) { 11047 try { 11048 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11049 allCodePaths = pkg.getAllCodePaths(); 11050 } catch (PackageParserException e) { 11051 // Ignored; we tried our best 11052 } 11053 } 11054 11055 cleanUp(); 11056 removeDexFiles(allCodePaths, instructionSets); 11057 } 11058 11059 boolean doPostDeleteLI(boolean delete) { 11060 // XXX err, shouldn't we respect the delete flag? 11061 cleanUpResourcesLI(); 11062 return true; 11063 } 11064 } 11065 11066 private boolean isAsecExternal(String cid) { 11067 final String asecPath = PackageHelper.getSdFilesystem(cid); 11068 return !asecPath.startsWith(mAsecInternalPath); 11069 } 11070 11071 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11072 PackageManagerException { 11073 if (copyRet < 0) { 11074 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11075 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11076 throw new PackageManagerException(copyRet, message); 11077 } 11078 } 11079 } 11080 11081 /** 11082 * Extract the MountService "container ID" from the full code path of an 11083 * .apk. 11084 */ 11085 static String cidFromCodePath(String fullCodePath) { 11086 int eidx = fullCodePath.lastIndexOf("/"); 11087 String subStr1 = fullCodePath.substring(0, eidx); 11088 int sidx = subStr1.lastIndexOf("/"); 11089 return subStr1.substring(sidx+1, eidx); 11090 } 11091 11092 /** 11093 * Logic to handle installation of ASEC applications, including copying and 11094 * renaming logic. 11095 */ 11096 class AsecInstallArgs extends InstallArgs { 11097 static final String RES_FILE_NAME = "pkg.apk"; 11098 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11099 11100 String cid; 11101 String packagePath; 11102 String resourcePath; 11103 11104 /** New install */ 11105 AsecInstallArgs(InstallParams params) { 11106 super(params.origin, params.move, params.observer, params.installFlags, 11107 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11108 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11109 } 11110 11111 /** Existing install */ 11112 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11113 boolean isExternal, boolean isForwardLocked) { 11114 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11115 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11116 instructionSets, null); 11117 // Hackily pretend we're still looking at a full code path 11118 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11119 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11120 } 11121 11122 // Extract cid from fullCodePath 11123 int eidx = fullCodePath.lastIndexOf("/"); 11124 String subStr1 = fullCodePath.substring(0, eidx); 11125 int sidx = subStr1.lastIndexOf("/"); 11126 cid = subStr1.substring(sidx+1, eidx); 11127 setMountPath(subStr1); 11128 } 11129 11130 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11131 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11132 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11133 instructionSets, null); 11134 this.cid = cid; 11135 setMountPath(PackageHelper.getSdDir(cid)); 11136 } 11137 11138 void createCopyFile() { 11139 cid = mInstallerService.allocateExternalStageCidLegacy(); 11140 } 11141 11142 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11143 if (origin.staged) { 11144 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11145 cid = origin.cid; 11146 setMountPath(PackageHelper.getSdDir(cid)); 11147 return PackageManager.INSTALL_SUCCEEDED; 11148 } 11149 11150 if (temp) { 11151 createCopyFile(); 11152 } else { 11153 /* 11154 * Pre-emptively destroy the container since it's destroyed if 11155 * copying fails due to it existing anyway. 11156 */ 11157 PackageHelper.destroySdDir(cid); 11158 } 11159 11160 final String newMountPath = imcs.copyPackageToContainer( 11161 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11162 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11163 11164 if (newMountPath != null) { 11165 setMountPath(newMountPath); 11166 return PackageManager.INSTALL_SUCCEEDED; 11167 } else { 11168 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11169 } 11170 } 11171 11172 @Override 11173 String getCodePath() { 11174 return packagePath; 11175 } 11176 11177 @Override 11178 String getResourcePath() { 11179 return resourcePath; 11180 } 11181 11182 int doPreInstall(int status) { 11183 if (status != PackageManager.INSTALL_SUCCEEDED) { 11184 // Destroy container 11185 PackageHelper.destroySdDir(cid); 11186 } else { 11187 boolean mounted = PackageHelper.isContainerMounted(cid); 11188 if (!mounted) { 11189 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11190 Process.SYSTEM_UID); 11191 if (newMountPath != null) { 11192 setMountPath(newMountPath); 11193 } else { 11194 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11195 } 11196 } 11197 } 11198 return status; 11199 } 11200 11201 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11202 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11203 String newMountPath = null; 11204 if (PackageHelper.isContainerMounted(cid)) { 11205 // Unmount the container 11206 if (!PackageHelper.unMountSdDir(cid)) { 11207 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11208 return false; 11209 } 11210 } 11211 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11212 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11213 " which might be stale. Will try to clean up."); 11214 // Clean up the stale container and proceed to recreate. 11215 if (!PackageHelper.destroySdDir(newCacheId)) { 11216 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11217 return false; 11218 } 11219 // Successfully cleaned up stale container. Try to rename again. 11220 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11221 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11222 + " inspite of cleaning it up."); 11223 return false; 11224 } 11225 } 11226 if (!PackageHelper.isContainerMounted(newCacheId)) { 11227 Slog.w(TAG, "Mounting container " + newCacheId); 11228 newMountPath = PackageHelper.mountSdDir(newCacheId, 11229 getEncryptKey(), Process.SYSTEM_UID); 11230 } else { 11231 newMountPath = PackageHelper.getSdDir(newCacheId); 11232 } 11233 if (newMountPath == null) { 11234 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11235 return false; 11236 } 11237 Log.i(TAG, "Succesfully renamed " + cid + 11238 " to " + newCacheId + 11239 " at new path: " + newMountPath); 11240 cid = newCacheId; 11241 11242 final File beforeCodeFile = new File(packagePath); 11243 setMountPath(newMountPath); 11244 final File afterCodeFile = new File(packagePath); 11245 11246 // Reflect the rename in scanned details 11247 pkg.codePath = afterCodeFile.getAbsolutePath(); 11248 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11249 pkg.baseCodePath); 11250 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11251 pkg.splitCodePaths); 11252 11253 // Reflect the rename in app info 11254 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11255 pkg.applicationInfo.setCodePath(pkg.codePath); 11256 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11257 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11258 pkg.applicationInfo.setResourcePath(pkg.codePath); 11259 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11260 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11261 11262 return true; 11263 } 11264 11265 private void setMountPath(String mountPath) { 11266 final File mountFile = new File(mountPath); 11267 11268 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11269 if (monolithicFile.exists()) { 11270 packagePath = monolithicFile.getAbsolutePath(); 11271 if (isFwdLocked()) { 11272 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11273 } else { 11274 resourcePath = packagePath; 11275 } 11276 } else { 11277 packagePath = mountFile.getAbsolutePath(); 11278 resourcePath = packagePath; 11279 } 11280 } 11281 11282 int doPostInstall(int status, int uid) { 11283 if (status != PackageManager.INSTALL_SUCCEEDED) { 11284 cleanUp(); 11285 } else { 11286 final int groupOwner; 11287 final String protectedFile; 11288 if (isFwdLocked()) { 11289 groupOwner = UserHandle.getSharedAppGid(uid); 11290 protectedFile = RES_FILE_NAME; 11291 } else { 11292 groupOwner = -1; 11293 protectedFile = null; 11294 } 11295 11296 if (uid < Process.FIRST_APPLICATION_UID 11297 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11298 Slog.e(TAG, "Failed to finalize " + cid); 11299 PackageHelper.destroySdDir(cid); 11300 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11301 } 11302 11303 boolean mounted = PackageHelper.isContainerMounted(cid); 11304 if (!mounted) { 11305 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11306 } 11307 } 11308 return status; 11309 } 11310 11311 private void cleanUp() { 11312 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11313 11314 // Destroy secure container 11315 PackageHelper.destroySdDir(cid); 11316 } 11317 11318 private List<String> getAllCodePaths() { 11319 final File codeFile = new File(getCodePath()); 11320 if (codeFile != null && codeFile.exists()) { 11321 try { 11322 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11323 return pkg.getAllCodePaths(); 11324 } catch (PackageParserException e) { 11325 // Ignored; we tried our best 11326 } 11327 } 11328 return Collections.EMPTY_LIST; 11329 } 11330 11331 void cleanUpResourcesLI() { 11332 // Enumerate all code paths before deleting 11333 cleanUpResourcesLI(getAllCodePaths()); 11334 } 11335 11336 private void cleanUpResourcesLI(List<String> allCodePaths) { 11337 cleanUp(); 11338 removeDexFiles(allCodePaths, instructionSets); 11339 } 11340 11341 String getPackageName() { 11342 return getAsecPackageName(cid); 11343 } 11344 11345 boolean doPostDeleteLI(boolean delete) { 11346 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11347 final List<String> allCodePaths = getAllCodePaths(); 11348 boolean mounted = PackageHelper.isContainerMounted(cid); 11349 if (mounted) { 11350 // Unmount first 11351 if (PackageHelper.unMountSdDir(cid)) { 11352 mounted = false; 11353 } 11354 } 11355 if (!mounted && delete) { 11356 cleanUpResourcesLI(allCodePaths); 11357 } 11358 return !mounted; 11359 } 11360 11361 @Override 11362 int doPreCopy() { 11363 if (isFwdLocked()) { 11364 if (!PackageHelper.fixSdPermissions(cid, 11365 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11366 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11367 } 11368 } 11369 11370 return PackageManager.INSTALL_SUCCEEDED; 11371 } 11372 11373 @Override 11374 int doPostCopy(int uid) { 11375 if (isFwdLocked()) { 11376 if (uid < Process.FIRST_APPLICATION_UID 11377 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11378 RES_FILE_NAME)) { 11379 Slog.e(TAG, "Failed to finalize " + cid); 11380 PackageHelper.destroySdDir(cid); 11381 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11382 } 11383 } 11384 11385 return PackageManager.INSTALL_SUCCEEDED; 11386 } 11387 } 11388 11389 /** 11390 * Logic to handle movement of existing installed applications. 11391 */ 11392 class MoveInstallArgs extends InstallArgs { 11393 private File codeFile; 11394 private File resourceFile; 11395 11396 /** New install */ 11397 MoveInstallArgs(InstallParams params) { 11398 super(params.origin, params.move, params.observer, params.installFlags, 11399 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11400 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11401 } 11402 11403 int copyApk(IMediaContainerService imcs, boolean temp) { 11404 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11405 + move.fromUuid + " to " + move.toUuid); 11406 synchronized (mInstaller) { 11407 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11408 move.dataAppName, move.appId, move.seinfo) != 0) { 11409 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11410 } 11411 } 11412 11413 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11414 resourceFile = codeFile; 11415 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11416 11417 return PackageManager.INSTALL_SUCCEEDED; 11418 } 11419 11420 int doPreInstall(int status) { 11421 if (status != PackageManager.INSTALL_SUCCEEDED) { 11422 cleanUp(move.toUuid); 11423 } 11424 return status; 11425 } 11426 11427 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11428 if (status != PackageManager.INSTALL_SUCCEEDED) { 11429 cleanUp(move.toUuid); 11430 return false; 11431 } 11432 11433 // Reflect the move in app info 11434 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11435 pkg.applicationInfo.setCodePath(pkg.codePath); 11436 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11437 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11438 pkg.applicationInfo.setResourcePath(pkg.codePath); 11439 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11440 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11441 11442 return true; 11443 } 11444 11445 int doPostInstall(int status, int uid) { 11446 if (status == PackageManager.INSTALL_SUCCEEDED) { 11447 cleanUp(move.fromUuid); 11448 } else { 11449 cleanUp(move.toUuid); 11450 } 11451 return status; 11452 } 11453 11454 @Override 11455 String getCodePath() { 11456 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11457 } 11458 11459 @Override 11460 String getResourcePath() { 11461 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11462 } 11463 11464 private boolean cleanUp(String volumeUuid) { 11465 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11466 move.dataAppName); 11467 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11468 synchronized (mInstallLock) { 11469 // Clean up both app data and code 11470 removeDataDirsLI(volumeUuid, move.packageName); 11471 if (codeFile.isDirectory()) { 11472 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11473 } else { 11474 codeFile.delete(); 11475 } 11476 } 11477 return true; 11478 } 11479 11480 void cleanUpResourcesLI() { 11481 throw new UnsupportedOperationException(); 11482 } 11483 11484 boolean doPostDeleteLI(boolean delete) { 11485 throw new UnsupportedOperationException(); 11486 } 11487 } 11488 11489 static String getAsecPackageName(String packageCid) { 11490 int idx = packageCid.lastIndexOf("-"); 11491 if (idx == -1) { 11492 return packageCid; 11493 } 11494 return packageCid.substring(0, idx); 11495 } 11496 11497 // Utility method used to create code paths based on package name and available index. 11498 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11499 String idxStr = ""; 11500 int idx = 1; 11501 // Fall back to default value of idx=1 if prefix is not 11502 // part of oldCodePath 11503 if (oldCodePath != null) { 11504 String subStr = oldCodePath; 11505 // Drop the suffix right away 11506 if (suffix != null && subStr.endsWith(suffix)) { 11507 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11508 } 11509 // If oldCodePath already contains prefix find out the 11510 // ending index to either increment or decrement. 11511 int sidx = subStr.lastIndexOf(prefix); 11512 if (sidx != -1) { 11513 subStr = subStr.substring(sidx + prefix.length()); 11514 if (subStr != null) { 11515 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11516 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11517 } 11518 try { 11519 idx = Integer.parseInt(subStr); 11520 if (idx <= 1) { 11521 idx++; 11522 } else { 11523 idx--; 11524 } 11525 } catch(NumberFormatException e) { 11526 } 11527 } 11528 } 11529 } 11530 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11531 return prefix + idxStr; 11532 } 11533 11534 private File getNextCodePath(File targetDir, String packageName) { 11535 int suffix = 1; 11536 File result; 11537 do { 11538 result = new File(targetDir, packageName + "-" + suffix); 11539 suffix++; 11540 } while (result.exists()); 11541 return result; 11542 } 11543 11544 // Utility method that returns the relative package path with respect 11545 // to the installation directory. Like say for /data/data/com.test-1.apk 11546 // string com.test-1 is returned. 11547 static String deriveCodePathName(String codePath) { 11548 if (codePath == null) { 11549 return null; 11550 } 11551 final File codeFile = new File(codePath); 11552 final String name = codeFile.getName(); 11553 if (codeFile.isDirectory()) { 11554 return name; 11555 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11556 final int lastDot = name.lastIndexOf('.'); 11557 return name.substring(0, lastDot); 11558 } else { 11559 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11560 return null; 11561 } 11562 } 11563 11564 class PackageInstalledInfo { 11565 String name; 11566 int uid; 11567 // The set of users that originally had this package installed. 11568 int[] origUsers; 11569 // The set of users that now have this package installed. 11570 int[] newUsers; 11571 PackageParser.Package pkg; 11572 int returnCode; 11573 String returnMsg; 11574 PackageRemovedInfo removedInfo; 11575 11576 public void setError(int code, String msg) { 11577 returnCode = code; 11578 returnMsg = msg; 11579 Slog.w(TAG, msg); 11580 } 11581 11582 public void setError(String msg, PackageParserException e) { 11583 returnCode = e.error; 11584 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11585 Slog.w(TAG, msg, e); 11586 } 11587 11588 public void setError(String msg, PackageManagerException e) { 11589 returnCode = e.error; 11590 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11591 Slog.w(TAG, msg, e); 11592 } 11593 11594 // In some error cases we want to convey more info back to the observer 11595 String origPackage; 11596 String origPermission; 11597 } 11598 11599 /* 11600 * Install a non-existing package. 11601 */ 11602 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11603 UserHandle user, String installerPackageName, String volumeUuid, 11604 PackageInstalledInfo res) { 11605 // Remember this for later, in case we need to rollback this install 11606 String pkgName = pkg.packageName; 11607 11608 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11609 final boolean dataDirExists = Environment 11610 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11611 synchronized(mPackages) { 11612 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11613 // A package with the same name is already installed, though 11614 // it has been renamed to an older name. The package we 11615 // are trying to install should be installed as an update to 11616 // the existing one, but that has not been requested, so bail. 11617 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11618 + " without first uninstalling package running as " 11619 + mSettings.mRenamedPackages.get(pkgName)); 11620 return; 11621 } 11622 if (mPackages.containsKey(pkgName)) { 11623 // Don't allow installation over an existing package with the same name. 11624 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11625 + " without first uninstalling."); 11626 return; 11627 } 11628 } 11629 11630 try { 11631 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11632 System.currentTimeMillis(), user); 11633 11634 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11635 // delete the partially installed application. the data directory will have to be 11636 // restored if it was already existing 11637 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11638 // remove package from internal structures. Note that we want deletePackageX to 11639 // delete the package data and cache directories that it created in 11640 // scanPackageLocked, unless those directories existed before we even tried to 11641 // install. 11642 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11643 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11644 res.removedInfo, true); 11645 } 11646 11647 } catch (PackageManagerException e) { 11648 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11649 } 11650 } 11651 11652 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11653 // Can't rotate keys during boot or if sharedUser. 11654 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11655 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11656 return false; 11657 } 11658 // app is using upgradeKeySets; make sure all are valid 11659 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11660 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11661 for (int i = 0; i < upgradeKeySets.length; i++) { 11662 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11663 Slog.wtf(TAG, "Package " 11664 + (oldPs.name != null ? oldPs.name : "<null>") 11665 + " contains upgrade-key-set reference to unknown key-set: " 11666 + upgradeKeySets[i] 11667 + " reverting to signatures check."); 11668 return false; 11669 } 11670 } 11671 return true; 11672 } 11673 11674 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11675 // Upgrade keysets are being used. Determine if new package has a superset of the 11676 // required keys. 11677 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11678 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11679 for (int i = 0; i < upgradeKeySets.length; i++) { 11680 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11681 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11682 return true; 11683 } 11684 } 11685 return false; 11686 } 11687 11688 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11689 UserHandle user, String installerPackageName, String volumeUuid, 11690 PackageInstalledInfo res) { 11691 final PackageParser.Package oldPackage; 11692 final String pkgName = pkg.packageName; 11693 final int[] allUsers; 11694 final boolean[] perUserInstalled; 11695 final boolean weFroze; 11696 11697 // First find the old package info and check signatures 11698 synchronized(mPackages) { 11699 oldPackage = mPackages.get(pkgName); 11700 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11701 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11702 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11703 if(!checkUpgradeKeySetLP(ps, pkg)) { 11704 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11705 "New package not signed by keys specified by upgrade-keysets: " 11706 + pkgName); 11707 return; 11708 } 11709 } else { 11710 // default to original signature matching 11711 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11712 != PackageManager.SIGNATURE_MATCH) { 11713 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11714 "New package has a different signature: " + pkgName); 11715 return; 11716 } 11717 } 11718 11719 // In case of rollback, remember per-user/profile install state 11720 allUsers = sUserManager.getUserIds(); 11721 perUserInstalled = new boolean[allUsers.length]; 11722 for (int i = 0; i < allUsers.length; i++) { 11723 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11724 } 11725 11726 // Mark the app as frozen to prevent launching during the upgrade 11727 // process, and then kill all running instances 11728 if (!ps.frozen) { 11729 ps.frozen = true; 11730 weFroze = true; 11731 } else { 11732 weFroze = false; 11733 } 11734 } 11735 11736 // Now that we're guarded by frozen state, kill app during upgrade 11737 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11738 11739 try { 11740 boolean sysPkg = (isSystemApp(oldPackage)); 11741 if (sysPkg) { 11742 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11743 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11744 } else { 11745 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11746 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11747 } 11748 } finally { 11749 // Regardless of success or failure of upgrade steps above, always 11750 // unfreeze the package if we froze it 11751 if (weFroze) { 11752 unfreezePackage(pkgName); 11753 } 11754 } 11755 } 11756 11757 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11758 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11759 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11760 String volumeUuid, PackageInstalledInfo res) { 11761 String pkgName = deletedPackage.packageName; 11762 boolean deletedPkg = true; 11763 boolean updatedSettings = false; 11764 11765 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11766 + deletedPackage); 11767 long origUpdateTime; 11768 if (pkg.mExtras != null) { 11769 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11770 } else { 11771 origUpdateTime = 0; 11772 } 11773 11774 // First delete the existing package while retaining the data directory 11775 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11776 res.removedInfo, true)) { 11777 // If the existing package wasn't successfully deleted 11778 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11779 deletedPkg = false; 11780 } else { 11781 // Successfully deleted the old package; proceed with replace. 11782 11783 // If deleted package lived in a container, give users a chance to 11784 // relinquish resources before killing. 11785 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11786 if (DEBUG_INSTALL) { 11787 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11788 } 11789 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11790 final ArrayList<String> pkgList = new ArrayList<String>(1); 11791 pkgList.add(deletedPackage.applicationInfo.packageName); 11792 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11793 } 11794 11795 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11796 try { 11797 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11798 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11799 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11800 perUserInstalled, res, user); 11801 updatedSettings = true; 11802 } catch (PackageManagerException e) { 11803 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11804 } 11805 } 11806 11807 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11808 // remove package from internal structures. Note that we want deletePackageX to 11809 // delete the package data and cache directories that it created in 11810 // scanPackageLocked, unless those directories existed before we even tried to 11811 // install. 11812 if(updatedSettings) { 11813 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11814 deletePackageLI( 11815 pkgName, null, true, allUsers, perUserInstalled, 11816 PackageManager.DELETE_KEEP_DATA, 11817 res.removedInfo, true); 11818 } 11819 // Since we failed to install the new package we need to restore the old 11820 // package that we deleted. 11821 if (deletedPkg) { 11822 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11823 File restoreFile = new File(deletedPackage.codePath); 11824 // Parse old package 11825 boolean oldExternal = isExternal(deletedPackage); 11826 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11827 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11828 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11829 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11830 try { 11831 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11832 } catch (PackageManagerException e) { 11833 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11834 + e.getMessage()); 11835 return; 11836 } 11837 // Restore of old package succeeded. Update permissions. 11838 // writer 11839 synchronized (mPackages) { 11840 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11841 UPDATE_PERMISSIONS_ALL); 11842 // can downgrade to reader 11843 mSettings.writeLPr(); 11844 } 11845 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11846 } 11847 } 11848 } 11849 11850 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11851 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11852 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11853 String volumeUuid, PackageInstalledInfo res) { 11854 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11855 + ", old=" + deletedPackage); 11856 boolean disabledSystem = false; 11857 boolean updatedSettings = false; 11858 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11859 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11860 != 0) { 11861 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11862 } 11863 String packageName = deletedPackage.packageName; 11864 if (packageName == null) { 11865 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11866 "Attempt to delete null packageName."); 11867 return; 11868 } 11869 PackageParser.Package oldPkg; 11870 PackageSetting oldPkgSetting; 11871 // reader 11872 synchronized (mPackages) { 11873 oldPkg = mPackages.get(packageName); 11874 oldPkgSetting = mSettings.mPackages.get(packageName); 11875 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11876 (oldPkgSetting == null)) { 11877 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11878 "Couldn't find package:" + packageName + " information"); 11879 return; 11880 } 11881 } 11882 11883 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11884 res.removedInfo.removedPackage = packageName; 11885 // Remove existing system package 11886 removePackageLI(oldPkgSetting, true); 11887 // writer 11888 synchronized (mPackages) { 11889 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11890 if (!disabledSystem && deletedPackage != null) { 11891 // We didn't need to disable the .apk as a current system package, 11892 // which means we are replacing another update that is already 11893 // installed. We need to make sure to delete the older one's .apk. 11894 res.removedInfo.args = createInstallArgsForExisting(0, 11895 deletedPackage.applicationInfo.getCodePath(), 11896 deletedPackage.applicationInfo.getResourcePath(), 11897 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11898 } else { 11899 res.removedInfo.args = null; 11900 } 11901 } 11902 11903 // Successfully disabled the old package. Now proceed with re-installation 11904 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11905 11906 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11907 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11908 11909 PackageParser.Package newPackage = null; 11910 try { 11911 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11912 if (newPackage.mExtras != null) { 11913 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11914 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11915 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11916 11917 // is the update attempting to change shared user? that isn't going to work... 11918 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11919 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11920 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11921 + " to " + newPkgSetting.sharedUser); 11922 updatedSettings = true; 11923 } 11924 } 11925 11926 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11927 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11928 perUserInstalled, res, user); 11929 updatedSettings = true; 11930 } 11931 11932 } catch (PackageManagerException e) { 11933 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11934 } 11935 11936 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11937 // Re installation failed. Restore old information 11938 // Remove new pkg information 11939 if (newPackage != null) { 11940 removeInstalledPackageLI(newPackage, true); 11941 } 11942 // Add back the old system package 11943 try { 11944 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11945 } catch (PackageManagerException e) { 11946 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11947 } 11948 // Restore the old system information in Settings 11949 synchronized (mPackages) { 11950 if (disabledSystem) { 11951 mSettings.enableSystemPackageLPw(packageName); 11952 } 11953 if (updatedSettings) { 11954 mSettings.setInstallerPackageName(packageName, 11955 oldPkgSetting.installerPackageName); 11956 } 11957 mSettings.writeLPr(); 11958 } 11959 } 11960 } 11961 11962 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11963 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11964 UserHandle user) { 11965 String pkgName = newPackage.packageName; 11966 synchronized (mPackages) { 11967 //write settings. the installStatus will be incomplete at this stage. 11968 //note that the new package setting would have already been 11969 //added to mPackages. It hasn't been persisted yet. 11970 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11971 mSettings.writeLPr(); 11972 } 11973 11974 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11975 11976 synchronized (mPackages) { 11977 updatePermissionsLPw(newPackage.packageName, newPackage, 11978 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11979 ? UPDATE_PERMISSIONS_ALL : 0)); 11980 // For system-bundled packages, we assume that installing an upgraded version 11981 // of the package implies that the user actually wants to run that new code, 11982 // so we enable the package. 11983 PackageSetting ps = mSettings.mPackages.get(pkgName); 11984 if (ps != null) { 11985 if (isSystemApp(newPackage)) { 11986 // NB: implicit assumption that system package upgrades apply to all users 11987 if (DEBUG_INSTALL) { 11988 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11989 } 11990 if (res.origUsers != null) { 11991 for (int userHandle : res.origUsers) { 11992 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11993 userHandle, installerPackageName); 11994 } 11995 } 11996 // Also convey the prior install/uninstall state 11997 if (allUsers != null && perUserInstalled != null) { 11998 for (int i = 0; i < allUsers.length; i++) { 11999 if (DEBUG_INSTALL) { 12000 Slog.d(TAG, " user " + allUsers[i] 12001 + " => " + perUserInstalled[i]); 12002 } 12003 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12004 } 12005 // these install state changes will be persisted in the 12006 // upcoming call to mSettings.writeLPr(). 12007 } 12008 } 12009 // It's implied that when a user requests installation, they want the app to be 12010 // installed and enabled. 12011 int userId = user.getIdentifier(); 12012 if (userId != UserHandle.USER_ALL) { 12013 ps.setInstalled(true, userId); 12014 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12015 } 12016 } 12017 res.name = pkgName; 12018 res.uid = newPackage.applicationInfo.uid; 12019 res.pkg = newPackage; 12020 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12021 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12022 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12023 //to update install status 12024 mSettings.writeLPr(); 12025 } 12026 } 12027 12028 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12029 final int installFlags = args.installFlags; 12030 final String installerPackageName = args.installerPackageName; 12031 final String volumeUuid = args.volumeUuid; 12032 final File tmpPackageFile = new File(args.getCodePath()); 12033 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12034 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12035 || (args.volumeUuid != null)); 12036 boolean replace = false; 12037 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12038 if (args.move != null) { 12039 // moving a complete application; perfom an initial scan on the new install location 12040 scanFlags |= SCAN_INITIAL; 12041 } 12042 // Result object to be returned 12043 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12044 12045 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12046 // Retrieve PackageSettings and parse package 12047 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12048 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12049 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12050 PackageParser pp = new PackageParser(); 12051 pp.setSeparateProcesses(mSeparateProcesses); 12052 pp.setDisplayMetrics(mMetrics); 12053 12054 final PackageParser.Package pkg; 12055 try { 12056 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12057 } catch (PackageParserException e) { 12058 res.setError("Failed parse during installPackageLI", e); 12059 return; 12060 } 12061 12062 // Mark that we have an install time CPU ABI override. 12063 pkg.cpuAbiOverride = args.abiOverride; 12064 12065 String pkgName = res.name = pkg.packageName; 12066 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12067 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12068 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12069 return; 12070 } 12071 } 12072 12073 try { 12074 pp.collectCertificates(pkg, parseFlags); 12075 pp.collectManifestDigest(pkg); 12076 } catch (PackageParserException e) { 12077 res.setError("Failed collect during installPackageLI", e); 12078 return; 12079 } 12080 12081 /* If the installer passed in a manifest digest, compare it now. */ 12082 if (args.manifestDigest != null) { 12083 if (DEBUG_INSTALL) { 12084 final String parsedManifest = pkg.manifestDigest == null ? "null" 12085 : pkg.manifestDigest.toString(); 12086 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12087 + parsedManifest); 12088 } 12089 12090 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12091 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12092 return; 12093 } 12094 } else if (DEBUG_INSTALL) { 12095 final String parsedManifest = pkg.manifestDigest == null 12096 ? "null" : pkg.manifestDigest.toString(); 12097 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12098 } 12099 12100 // Get rid of all references to package scan path via parser. 12101 pp = null; 12102 String oldCodePath = null; 12103 boolean systemApp = false; 12104 synchronized (mPackages) { 12105 // Check if installing already existing package 12106 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12107 String oldName = mSettings.mRenamedPackages.get(pkgName); 12108 if (pkg.mOriginalPackages != null 12109 && pkg.mOriginalPackages.contains(oldName) 12110 && mPackages.containsKey(oldName)) { 12111 // This package is derived from an original package, 12112 // and this device has been updating from that original 12113 // name. We must continue using the original name, so 12114 // rename the new package here. 12115 pkg.setPackageName(oldName); 12116 pkgName = pkg.packageName; 12117 replace = true; 12118 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12119 + oldName + " pkgName=" + pkgName); 12120 } else if (mPackages.containsKey(pkgName)) { 12121 // This package, under its official name, already exists 12122 // on the device; we should replace it. 12123 replace = true; 12124 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12125 } 12126 12127 // Prevent apps opting out from runtime permissions 12128 if (replace) { 12129 PackageParser.Package oldPackage = mPackages.get(pkgName); 12130 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12131 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12132 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12133 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12134 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12135 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12136 + " doesn't support runtime permissions but the old" 12137 + " target SDK " + oldTargetSdk + " does."); 12138 return; 12139 } 12140 } 12141 } 12142 12143 PackageSetting ps = mSettings.mPackages.get(pkgName); 12144 if (ps != null) { 12145 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12146 12147 // Quick sanity check that we're signed correctly if updating; 12148 // we'll check this again later when scanning, but we want to 12149 // bail early here before tripping over redefined permissions. 12150 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12151 if (!checkUpgradeKeySetLP(ps, pkg)) { 12152 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12153 + pkg.packageName + " upgrade keys do not match the " 12154 + "previously installed version"); 12155 return; 12156 } 12157 } else { 12158 try { 12159 verifySignaturesLP(ps, pkg); 12160 } catch (PackageManagerException e) { 12161 res.setError(e.error, e.getMessage()); 12162 return; 12163 } 12164 } 12165 12166 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12167 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12168 systemApp = (ps.pkg.applicationInfo.flags & 12169 ApplicationInfo.FLAG_SYSTEM) != 0; 12170 } 12171 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12172 } 12173 12174 // Check whether the newly-scanned package wants to define an already-defined perm 12175 int N = pkg.permissions.size(); 12176 for (int i = N-1; i >= 0; i--) { 12177 PackageParser.Permission perm = pkg.permissions.get(i); 12178 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12179 if (bp != null) { 12180 // If the defining package is signed with our cert, it's okay. This 12181 // also includes the "updating the same package" case, of course. 12182 // "updating same package" could also involve key-rotation. 12183 final boolean sigsOk; 12184 if (bp.sourcePackage.equals(pkg.packageName) 12185 && (bp.packageSetting instanceof PackageSetting) 12186 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12187 scanFlags))) { 12188 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12189 } else { 12190 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12191 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12192 } 12193 if (!sigsOk) { 12194 // If the owning package is the system itself, we log but allow 12195 // install to proceed; we fail the install on all other permission 12196 // redefinitions. 12197 if (!bp.sourcePackage.equals("android")) { 12198 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12199 + pkg.packageName + " attempting to redeclare permission " 12200 + perm.info.name + " already owned by " + bp.sourcePackage); 12201 res.origPermission = perm.info.name; 12202 res.origPackage = bp.sourcePackage; 12203 return; 12204 } else { 12205 Slog.w(TAG, "Package " + pkg.packageName 12206 + " attempting to redeclare system permission " 12207 + perm.info.name + "; ignoring new declaration"); 12208 pkg.permissions.remove(i); 12209 } 12210 } 12211 } 12212 } 12213 12214 } 12215 12216 if (systemApp && onExternal) { 12217 // Disable updates to system apps on sdcard 12218 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12219 "Cannot install updates to system apps on sdcard"); 12220 return; 12221 } 12222 12223 if (args.move != null) { 12224 // We did an in-place move, so dex is ready to roll 12225 scanFlags |= SCAN_NO_DEX; 12226 scanFlags |= SCAN_MOVE; 12227 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12228 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12229 scanFlags |= SCAN_NO_DEX; 12230 12231 try { 12232 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12233 true /* extract libs */); 12234 } catch (PackageManagerException pme) { 12235 Slog.e(TAG, "Error deriving application ABI", pme); 12236 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12237 return; 12238 } 12239 12240 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12241 int result = mPackageDexOptimizer 12242 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12243 false /* defer */, false /* inclDependencies */); 12244 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12245 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12246 return; 12247 } 12248 } 12249 12250 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12251 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12252 return; 12253 } 12254 12255 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12256 12257 if (replace) { 12258 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12259 installerPackageName, volumeUuid, res); 12260 } else { 12261 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12262 args.user, installerPackageName, volumeUuid, res); 12263 } 12264 synchronized (mPackages) { 12265 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12266 if (ps != null) { 12267 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12268 } 12269 } 12270 } 12271 12272 private void startIntentFilterVerifications(int userId, boolean replacing, 12273 PackageParser.Package pkg) { 12274 if (mIntentFilterVerifierComponent == null) { 12275 Slog.w(TAG, "No IntentFilter verification will not be done as " 12276 + "there is no IntentFilterVerifier available!"); 12277 return; 12278 } 12279 12280 final int verifierUid = getPackageUid( 12281 mIntentFilterVerifierComponent.getPackageName(), 12282 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12283 12284 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12285 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12286 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12287 mHandler.sendMessage(msg); 12288 } 12289 12290 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12291 PackageParser.Package pkg) { 12292 int size = pkg.activities.size(); 12293 if (size == 0) { 12294 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12295 "No activity, so no need to verify any IntentFilter!"); 12296 return; 12297 } 12298 12299 final boolean hasDomainURLs = hasDomainURLs(pkg); 12300 if (!hasDomainURLs) { 12301 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12302 "No domain URLs, so no need to verify any IntentFilter!"); 12303 return; 12304 } 12305 12306 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12307 + " if any IntentFilter from the " + size 12308 + " Activities needs verification ..."); 12309 12310 int count = 0; 12311 final String packageName = pkg.packageName; 12312 12313 synchronized (mPackages) { 12314 // If this is a new install and we see that we've already run verification for this 12315 // package, we have nothing to do: it means the state was restored from backup. 12316 if (!replacing) { 12317 IntentFilterVerificationInfo ivi = 12318 mSettings.getIntentFilterVerificationLPr(packageName); 12319 if (ivi != null) { 12320 if (DEBUG_DOMAIN_VERIFICATION) { 12321 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12322 + ivi.getStatusString()); 12323 } 12324 return; 12325 } 12326 } 12327 12328 // If any filters need to be verified, then all need to be. 12329 boolean needToVerify = false; 12330 for (PackageParser.Activity a : pkg.activities) { 12331 for (ActivityIntentInfo filter : a.intents) { 12332 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12333 if (DEBUG_DOMAIN_VERIFICATION) { 12334 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12335 } 12336 needToVerify = true; 12337 break; 12338 } 12339 } 12340 } 12341 12342 if (needToVerify) { 12343 final int verificationId = mIntentFilterVerificationToken++; 12344 for (PackageParser.Activity a : pkg.activities) { 12345 for (ActivityIntentInfo filter : a.intents) { 12346 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12347 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12348 "Verification needed for IntentFilter:" + filter.toString()); 12349 mIntentFilterVerifier.addOneIntentFilterVerification( 12350 verifierUid, userId, verificationId, filter, packageName); 12351 count++; 12352 } 12353 } 12354 } 12355 } 12356 } 12357 12358 if (count > 0) { 12359 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12360 + " IntentFilter verification" + (count > 1 ? "s" : "") 12361 + " for userId:" + userId); 12362 mIntentFilterVerifier.startVerifications(userId); 12363 } else { 12364 if (DEBUG_DOMAIN_VERIFICATION) { 12365 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12366 } 12367 } 12368 } 12369 12370 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12371 final ComponentName cn = filter.activity.getComponentName(); 12372 final String packageName = cn.getPackageName(); 12373 12374 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12375 packageName); 12376 if (ivi == null) { 12377 return true; 12378 } 12379 int status = ivi.getStatus(); 12380 switch (status) { 12381 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12382 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12383 return true; 12384 12385 default: 12386 // Nothing to do 12387 return false; 12388 } 12389 } 12390 12391 private static boolean isMultiArch(PackageSetting ps) { 12392 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12393 } 12394 12395 private static boolean isMultiArch(ApplicationInfo info) { 12396 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12397 } 12398 12399 private static boolean isExternal(PackageParser.Package pkg) { 12400 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12401 } 12402 12403 private static boolean isExternal(PackageSetting ps) { 12404 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12405 } 12406 12407 private static boolean isExternal(ApplicationInfo info) { 12408 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12409 } 12410 12411 private static boolean isSystemApp(PackageParser.Package pkg) { 12412 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12413 } 12414 12415 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12416 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12417 } 12418 12419 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12420 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12421 } 12422 12423 private static boolean isSystemApp(PackageSetting ps) { 12424 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12425 } 12426 12427 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12428 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12429 } 12430 12431 private int packageFlagsToInstallFlags(PackageSetting ps) { 12432 int installFlags = 0; 12433 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12434 // This existing package was an external ASEC install when we have 12435 // the external flag without a UUID 12436 installFlags |= PackageManager.INSTALL_EXTERNAL; 12437 } 12438 if (ps.isForwardLocked()) { 12439 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12440 } 12441 return installFlags; 12442 } 12443 12444 private void deleteTempPackageFiles() { 12445 final FilenameFilter filter = new FilenameFilter() { 12446 public boolean accept(File dir, String name) { 12447 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12448 } 12449 }; 12450 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12451 file.delete(); 12452 } 12453 } 12454 12455 @Override 12456 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12457 int flags) { 12458 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12459 flags); 12460 } 12461 12462 @Override 12463 public void deletePackage(final String packageName, 12464 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12465 mContext.enforceCallingOrSelfPermission( 12466 android.Manifest.permission.DELETE_PACKAGES, null); 12467 Preconditions.checkNotNull(packageName); 12468 Preconditions.checkNotNull(observer); 12469 final int uid = Binder.getCallingUid(); 12470 if (UserHandle.getUserId(uid) != userId) { 12471 mContext.enforceCallingPermission( 12472 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12473 "deletePackage for user " + userId); 12474 } 12475 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12476 try { 12477 observer.onPackageDeleted(packageName, 12478 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12479 } catch (RemoteException re) { 12480 } 12481 return; 12482 } 12483 12484 boolean uninstallBlocked = false; 12485 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12486 int[] users = sUserManager.getUserIds(); 12487 for (int i = 0; i < users.length; ++i) { 12488 if (getBlockUninstallForUser(packageName, users[i])) { 12489 uninstallBlocked = true; 12490 break; 12491 } 12492 } 12493 } else { 12494 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12495 } 12496 if (uninstallBlocked) { 12497 try { 12498 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12499 null); 12500 } catch (RemoteException re) { 12501 } 12502 return; 12503 } 12504 12505 if (DEBUG_REMOVE) { 12506 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12507 } 12508 // Queue up an async operation since the package deletion may take a little while. 12509 mHandler.post(new Runnable() { 12510 public void run() { 12511 mHandler.removeCallbacks(this); 12512 final int returnCode = deletePackageX(packageName, userId, flags); 12513 if (observer != null) { 12514 try { 12515 observer.onPackageDeleted(packageName, returnCode, null); 12516 } catch (RemoteException e) { 12517 Log.i(TAG, "Observer no longer exists."); 12518 } //end catch 12519 } //end if 12520 } //end run 12521 }); 12522 } 12523 12524 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12525 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12526 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12527 try { 12528 if (dpm != null) { 12529 if (dpm.isDeviceOwner(packageName)) { 12530 return true; 12531 } 12532 int[] users; 12533 if (userId == UserHandle.USER_ALL) { 12534 users = sUserManager.getUserIds(); 12535 } else { 12536 users = new int[]{userId}; 12537 } 12538 for (int i = 0; i < users.length; ++i) { 12539 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12540 return true; 12541 } 12542 } 12543 } 12544 } catch (RemoteException e) { 12545 } 12546 return false; 12547 } 12548 12549 /** 12550 * This method is an internal method that could be get invoked either 12551 * to delete an installed package or to clean up a failed installation. 12552 * After deleting an installed package, a broadcast is sent to notify any 12553 * listeners that the package has been installed. For cleaning up a failed 12554 * installation, the broadcast is not necessary since the package's 12555 * installation wouldn't have sent the initial broadcast either 12556 * The key steps in deleting a package are 12557 * deleting the package information in internal structures like mPackages, 12558 * deleting the packages base directories through installd 12559 * updating mSettings to reflect current status 12560 * persisting settings for later use 12561 * sending a broadcast if necessary 12562 */ 12563 private int deletePackageX(String packageName, int userId, int flags) { 12564 final PackageRemovedInfo info = new PackageRemovedInfo(); 12565 final boolean res; 12566 12567 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12568 ? UserHandle.ALL : new UserHandle(userId); 12569 12570 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12571 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12572 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12573 } 12574 12575 boolean removedForAllUsers = false; 12576 boolean systemUpdate = false; 12577 12578 // for the uninstall-updates case and restricted profiles, remember the per- 12579 // userhandle installed state 12580 int[] allUsers; 12581 boolean[] perUserInstalled; 12582 synchronized (mPackages) { 12583 PackageSetting ps = mSettings.mPackages.get(packageName); 12584 allUsers = sUserManager.getUserIds(); 12585 perUserInstalled = new boolean[allUsers.length]; 12586 for (int i = 0; i < allUsers.length; i++) { 12587 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12588 } 12589 } 12590 12591 synchronized (mInstallLock) { 12592 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12593 res = deletePackageLI(packageName, removeForUser, 12594 true, allUsers, perUserInstalled, 12595 flags | REMOVE_CHATTY, info, true); 12596 systemUpdate = info.isRemovedPackageSystemUpdate; 12597 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12598 removedForAllUsers = true; 12599 } 12600 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12601 + " removedForAllUsers=" + removedForAllUsers); 12602 } 12603 12604 if (res) { 12605 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12606 12607 // If the removed package was a system update, the old system package 12608 // was re-enabled; we need to broadcast this information 12609 if (systemUpdate) { 12610 Bundle extras = new Bundle(1); 12611 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12612 ? info.removedAppId : info.uid); 12613 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12614 12615 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12616 extras, null, null, null); 12617 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12618 extras, null, null, null); 12619 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12620 null, packageName, null, null); 12621 } 12622 } 12623 // Force a gc here. 12624 Runtime.getRuntime().gc(); 12625 // Delete the resources here after sending the broadcast to let 12626 // other processes clean up before deleting resources. 12627 if (info.args != null) { 12628 synchronized (mInstallLock) { 12629 info.args.doPostDeleteLI(true); 12630 } 12631 } 12632 12633 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12634 } 12635 12636 class PackageRemovedInfo { 12637 String removedPackage; 12638 int uid = -1; 12639 int removedAppId = -1; 12640 int[] removedUsers = null; 12641 boolean isRemovedPackageSystemUpdate = false; 12642 // Clean up resources deleted packages. 12643 InstallArgs args = null; 12644 12645 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12646 Bundle extras = new Bundle(1); 12647 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12648 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12649 if (replacing) { 12650 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12651 } 12652 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12653 if (removedPackage != null) { 12654 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12655 extras, null, null, removedUsers); 12656 if (fullRemove && !replacing) { 12657 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12658 extras, null, null, removedUsers); 12659 } 12660 } 12661 if (removedAppId >= 0) { 12662 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12663 removedUsers); 12664 } 12665 } 12666 } 12667 12668 /* 12669 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12670 * flag is not set, the data directory is removed as well. 12671 * make sure this flag is set for partially installed apps. If not its meaningless to 12672 * delete a partially installed application. 12673 */ 12674 private void removePackageDataLI(PackageSetting ps, 12675 int[] allUserHandles, boolean[] perUserInstalled, 12676 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12677 String packageName = ps.name; 12678 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12679 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12680 // Retrieve object to delete permissions for shared user later on 12681 final PackageSetting deletedPs; 12682 // reader 12683 synchronized (mPackages) { 12684 deletedPs = mSettings.mPackages.get(packageName); 12685 if (outInfo != null) { 12686 outInfo.removedPackage = packageName; 12687 outInfo.removedUsers = deletedPs != null 12688 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12689 : null; 12690 } 12691 } 12692 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12693 removeDataDirsLI(ps.volumeUuid, packageName); 12694 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12695 } 12696 // writer 12697 synchronized (mPackages) { 12698 if (deletedPs != null) { 12699 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12700 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12701 clearDefaultBrowserIfNeeded(packageName); 12702 if (outInfo != null) { 12703 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12704 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12705 } 12706 updatePermissionsLPw(deletedPs.name, null, 0); 12707 if (deletedPs.sharedUser != null) { 12708 // Remove permissions associated with package. Since runtime 12709 // permissions are per user we have to kill the removed package 12710 // or packages running under the shared user of the removed 12711 // package if revoking the permissions requested only by the removed 12712 // package is successful and this causes a change in gids. 12713 for (int userId : UserManagerService.getInstance().getUserIds()) { 12714 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12715 userId); 12716 if (userIdToKill == UserHandle.USER_ALL 12717 || userIdToKill >= UserHandle.USER_OWNER) { 12718 // If gids changed for this user, kill all affected packages. 12719 mHandler.post(new Runnable() { 12720 @Override 12721 public void run() { 12722 // This has to happen with no lock held. 12723 killSettingPackagesForUser(deletedPs, userIdToKill, 12724 KILL_APP_REASON_GIDS_CHANGED); 12725 } 12726 }); 12727 break; 12728 } 12729 } 12730 } 12731 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12732 } 12733 // make sure to preserve per-user disabled state if this removal was just 12734 // a downgrade of a system app to the factory package 12735 if (allUserHandles != null && perUserInstalled != null) { 12736 if (DEBUG_REMOVE) { 12737 Slog.d(TAG, "Propagating install state across downgrade"); 12738 } 12739 for (int i = 0; i < allUserHandles.length; i++) { 12740 if (DEBUG_REMOVE) { 12741 Slog.d(TAG, " user " + allUserHandles[i] 12742 + " => " + perUserInstalled[i]); 12743 } 12744 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12745 } 12746 } 12747 } 12748 // can downgrade to reader 12749 if (writeSettings) { 12750 // Save settings now 12751 mSettings.writeLPr(); 12752 } 12753 } 12754 if (outInfo != null) { 12755 // A user ID was deleted here. Go through all users and remove it 12756 // from KeyStore. 12757 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12758 } 12759 } 12760 12761 static boolean locationIsPrivileged(File path) { 12762 try { 12763 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12764 .getCanonicalPath(); 12765 return path.getCanonicalPath().startsWith(privilegedAppDir); 12766 } catch (IOException e) { 12767 Slog.e(TAG, "Unable to access code path " + path); 12768 } 12769 return false; 12770 } 12771 12772 /* 12773 * Tries to delete system package. 12774 */ 12775 private boolean deleteSystemPackageLI(PackageSetting newPs, 12776 int[] allUserHandles, boolean[] perUserInstalled, 12777 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12778 final boolean applyUserRestrictions 12779 = (allUserHandles != null) && (perUserInstalled != null); 12780 PackageSetting disabledPs = null; 12781 // Confirm if the system package has been updated 12782 // An updated system app can be deleted. This will also have to restore 12783 // the system pkg from system partition 12784 // reader 12785 synchronized (mPackages) { 12786 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12787 } 12788 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12789 + " disabledPs=" + disabledPs); 12790 if (disabledPs == null) { 12791 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12792 return false; 12793 } else if (DEBUG_REMOVE) { 12794 Slog.d(TAG, "Deleting system pkg from data partition"); 12795 } 12796 if (DEBUG_REMOVE) { 12797 if (applyUserRestrictions) { 12798 Slog.d(TAG, "Remembering install states:"); 12799 for (int i = 0; i < allUserHandles.length; i++) { 12800 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12801 } 12802 } 12803 } 12804 // Delete the updated package 12805 outInfo.isRemovedPackageSystemUpdate = true; 12806 if (disabledPs.versionCode < newPs.versionCode) { 12807 // Delete data for downgrades 12808 flags &= ~PackageManager.DELETE_KEEP_DATA; 12809 } else { 12810 // Preserve data by setting flag 12811 flags |= PackageManager.DELETE_KEEP_DATA; 12812 } 12813 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12814 allUserHandles, perUserInstalled, outInfo, writeSettings); 12815 if (!ret) { 12816 return false; 12817 } 12818 // writer 12819 synchronized (mPackages) { 12820 // Reinstate the old system package 12821 mSettings.enableSystemPackageLPw(newPs.name); 12822 // Remove any native libraries from the upgraded package. 12823 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12824 } 12825 // Install the system package 12826 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12827 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12828 if (locationIsPrivileged(disabledPs.codePath)) { 12829 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12830 } 12831 12832 final PackageParser.Package newPkg; 12833 try { 12834 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12835 } catch (PackageManagerException e) { 12836 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12837 return false; 12838 } 12839 12840 // writer 12841 synchronized (mPackages) { 12842 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12843 12844 // Propagate the permissions state as we do want to drop on the floor 12845 // runtime permissions. The update permissions method below will take 12846 // care of removing obsolete permissions and grant install permissions. 12847 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12848 updatePermissionsLPw(newPkg.packageName, newPkg, 12849 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12850 12851 if (applyUserRestrictions) { 12852 if (DEBUG_REMOVE) { 12853 Slog.d(TAG, "Propagating install state across reinstall"); 12854 } 12855 for (int i = 0; i < allUserHandles.length; i++) { 12856 if (DEBUG_REMOVE) { 12857 Slog.d(TAG, " user " + allUserHandles[i] 12858 + " => " + perUserInstalled[i]); 12859 } 12860 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12861 } 12862 // Regardless of writeSettings we need to ensure that this restriction 12863 // state propagation is persisted 12864 mSettings.writeAllUsersPackageRestrictionsLPr(); 12865 } 12866 // can downgrade to reader here 12867 if (writeSettings) { 12868 mSettings.writeLPr(); 12869 } 12870 } 12871 return true; 12872 } 12873 12874 private boolean deleteInstalledPackageLI(PackageSetting ps, 12875 boolean deleteCodeAndResources, int flags, 12876 int[] allUserHandles, boolean[] perUserInstalled, 12877 PackageRemovedInfo outInfo, boolean writeSettings) { 12878 if (outInfo != null) { 12879 outInfo.uid = ps.appId; 12880 } 12881 12882 // Delete package data from internal structures and also remove data if flag is set 12883 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12884 12885 // Delete application code and resources 12886 if (deleteCodeAndResources && (outInfo != null)) { 12887 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12888 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12889 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12890 } 12891 return true; 12892 } 12893 12894 @Override 12895 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12896 int userId) { 12897 mContext.enforceCallingOrSelfPermission( 12898 android.Manifest.permission.DELETE_PACKAGES, null); 12899 synchronized (mPackages) { 12900 PackageSetting ps = mSettings.mPackages.get(packageName); 12901 if (ps == null) { 12902 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12903 return false; 12904 } 12905 if (!ps.getInstalled(userId)) { 12906 // Can't block uninstall for an app that is not installed or enabled. 12907 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12908 return false; 12909 } 12910 ps.setBlockUninstall(blockUninstall, userId); 12911 mSettings.writePackageRestrictionsLPr(userId); 12912 } 12913 return true; 12914 } 12915 12916 @Override 12917 public boolean getBlockUninstallForUser(String packageName, int userId) { 12918 synchronized (mPackages) { 12919 PackageSetting ps = mSettings.mPackages.get(packageName); 12920 if (ps == null) { 12921 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12922 return false; 12923 } 12924 return ps.getBlockUninstall(userId); 12925 } 12926 } 12927 12928 /* 12929 * This method handles package deletion in general 12930 */ 12931 private boolean deletePackageLI(String packageName, UserHandle user, 12932 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12933 int flags, PackageRemovedInfo outInfo, 12934 boolean writeSettings) { 12935 if (packageName == null) { 12936 Slog.w(TAG, "Attempt to delete null packageName."); 12937 return false; 12938 } 12939 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12940 PackageSetting ps; 12941 boolean dataOnly = false; 12942 int removeUser = -1; 12943 int appId = -1; 12944 synchronized (mPackages) { 12945 ps = mSettings.mPackages.get(packageName); 12946 if (ps == null) { 12947 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12948 return false; 12949 } 12950 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12951 && user.getIdentifier() != UserHandle.USER_ALL) { 12952 // The caller is asking that the package only be deleted for a single 12953 // user. To do this, we just mark its uninstalled state and delete 12954 // its data. If this is a system app, we only allow this to happen if 12955 // they have set the special DELETE_SYSTEM_APP which requests different 12956 // semantics than normal for uninstalling system apps. 12957 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12958 ps.setUserState(user.getIdentifier(), 12959 COMPONENT_ENABLED_STATE_DEFAULT, 12960 false, //installed 12961 true, //stopped 12962 true, //notLaunched 12963 false, //hidden 12964 null, null, null, 12965 false, // blockUninstall 12966 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12967 if (!isSystemApp(ps)) { 12968 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12969 // Other user still have this package installed, so all 12970 // we need to do is clear this user's data and save that 12971 // it is uninstalled. 12972 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12973 removeUser = user.getIdentifier(); 12974 appId = ps.appId; 12975 scheduleWritePackageRestrictionsLocked(removeUser); 12976 } else { 12977 // We need to set it back to 'installed' so the uninstall 12978 // broadcasts will be sent correctly. 12979 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12980 ps.setInstalled(true, user.getIdentifier()); 12981 } 12982 } else { 12983 // This is a system app, so we assume that the 12984 // other users still have this package installed, so all 12985 // we need to do is clear this user's data and save that 12986 // it is uninstalled. 12987 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12988 removeUser = user.getIdentifier(); 12989 appId = ps.appId; 12990 scheduleWritePackageRestrictionsLocked(removeUser); 12991 } 12992 } 12993 } 12994 12995 if (removeUser >= 0) { 12996 // From above, we determined that we are deleting this only 12997 // for a single user. Continue the work here. 12998 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12999 if (outInfo != null) { 13000 outInfo.removedPackage = packageName; 13001 outInfo.removedAppId = appId; 13002 outInfo.removedUsers = new int[] {removeUser}; 13003 } 13004 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13005 removeKeystoreDataIfNeeded(removeUser, appId); 13006 schedulePackageCleaning(packageName, removeUser, false); 13007 synchronized (mPackages) { 13008 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13009 scheduleWritePackageRestrictionsLocked(removeUser); 13010 } 13011 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13012 } 13013 return true; 13014 } 13015 13016 if (dataOnly) { 13017 // Delete application data first 13018 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13019 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13020 return true; 13021 } 13022 13023 boolean ret = false; 13024 if (isSystemApp(ps)) { 13025 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13026 // When an updated system application is deleted we delete the existing resources as well and 13027 // fall back to existing code in system partition 13028 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13029 flags, outInfo, writeSettings); 13030 } else { 13031 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13032 // Kill application pre-emptively especially for apps on sd. 13033 killApplication(packageName, ps.appId, "uninstall pkg"); 13034 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13035 allUserHandles, perUserInstalled, 13036 outInfo, writeSettings); 13037 } 13038 13039 return ret; 13040 } 13041 13042 private final class ClearStorageConnection implements ServiceConnection { 13043 IMediaContainerService mContainerService; 13044 13045 @Override 13046 public void onServiceConnected(ComponentName name, IBinder service) { 13047 synchronized (this) { 13048 mContainerService = IMediaContainerService.Stub.asInterface(service); 13049 notifyAll(); 13050 } 13051 } 13052 13053 @Override 13054 public void onServiceDisconnected(ComponentName name) { 13055 } 13056 } 13057 13058 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13059 final boolean mounted; 13060 if (Environment.isExternalStorageEmulated()) { 13061 mounted = true; 13062 } else { 13063 final String status = Environment.getExternalStorageState(); 13064 13065 mounted = status.equals(Environment.MEDIA_MOUNTED) 13066 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13067 } 13068 13069 if (!mounted) { 13070 return; 13071 } 13072 13073 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13074 int[] users; 13075 if (userId == UserHandle.USER_ALL) { 13076 users = sUserManager.getUserIds(); 13077 } else { 13078 users = new int[] { userId }; 13079 } 13080 final ClearStorageConnection conn = new ClearStorageConnection(); 13081 if (mContext.bindServiceAsUser( 13082 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13083 try { 13084 for (int curUser : users) { 13085 long timeout = SystemClock.uptimeMillis() + 5000; 13086 synchronized (conn) { 13087 long now = SystemClock.uptimeMillis(); 13088 while (conn.mContainerService == null && now < timeout) { 13089 try { 13090 conn.wait(timeout - now); 13091 } catch (InterruptedException e) { 13092 } 13093 } 13094 } 13095 if (conn.mContainerService == null) { 13096 return; 13097 } 13098 13099 final UserEnvironment userEnv = new UserEnvironment(curUser); 13100 clearDirectory(conn.mContainerService, 13101 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13102 if (allData) { 13103 clearDirectory(conn.mContainerService, 13104 userEnv.buildExternalStorageAppDataDirs(packageName)); 13105 clearDirectory(conn.mContainerService, 13106 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13107 } 13108 } 13109 } finally { 13110 mContext.unbindService(conn); 13111 } 13112 } 13113 } 13114 13115 @Override 13116 public void clearApplicationUserData(final String packageName, 13117 final IPackageDataObserver observer, final int userId) { 13118 mContext.enforceCallingOrSelfPermission( 13119 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13120 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13121 // Queue up an async operation since the package deletion may take a little while. 13122 mHandler.post(new Runnable() { 13123 public void run() { 13124 mHandler.removeCallbacks(this); 13125 final boolean succeeded; 13126 synchronized (mInstallLock) { 13127 succeeded = clearApplicationUserDataLI(packageName, userId); 13128 } 13129 clearExternalStorageDataSync(packageName, userId, true); 13130 if (succeeded) { 13131 // invoke DeviceStorageMonitor's update method to clear any notifications 13132 DeviceStorageMonitorInternal 13133 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13134 if (dsm != null) { 13135 dsm.checkMemory(); 13136 } 13137 } 13138 if(observer != null) { 13139 try { 13140 observer.onRemoveCompleted(packageName, succeeded); 13141 } catch (RemoteException e) { 13142 Log.i(TAG, "Observer no longer exists."); 13143 } 13144 } //end if observer 13145 } //end run 13146 }); 13147 } 13148 13149 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13150 if (packageName == null) { 13151 Slog.w(TAG, "Attempt to delete null packageName."); 13152 return false; 13153 } 13154 13155 // Try finding details about the requested package 13156 PackageParser.Package pkg; 13157 synchronized (mPackages) { 13158 pkg = mPackages.get(packageName); 13159 if (pkg == null) { 13160 final PackageSetting ps = mSettings.mPackages.get(packageName); 13161 if (ps != null) { 13162 pkg = ps.pkg; 13163 } 13164 } 13165 13166 if (pkg == null) { 13167 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13168 return false; 13169 } 13170 13171 PackageSetting ps = (PackageSetting) pkg.mExtras; 13172 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13173 } 13174 13175 // Always delete data directories for package, even if we found no other 13176 // record of app. This helps users recover from UID mismatches without 13177 // resorting to a full data wipe. 13178 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13179 if (retCode < 0) { 13180 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13181 return false; 13182 } 13183 13184 final int appId = pkg.applicationInfo.uid; 13185 removeKeystoreDataIfNeeded(userId, appId); 13186 13187 // Create a native library symlink only if we have native libraries 13188 // and if the native libraries are 32 bit libraries. We do not provide 13189 // this symlink for 64 bit libraries. 13190 if (pkg.applicationInfo.primaryCpuAbi != null && 13191 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13192 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13193 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13194 nativeLibPath, userId) < 0) { 13195 Slog.w(TAG, "Failed linking native library dir"); 13196 return false; 13197 } 13198 } 13199 13200 return true; 13201 } 13202 13203 /** 13204 * Reverts user permission state changes (permissions and flags). 13205 * 13206 * @param ps The package for which to reset. 13207 * @param userId The device user for which to do a reset. 13208 */ 13209 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13210 final PackageSetting ps, final int userId) { 13211 if (ps.pkg == null) { 13212 return; 13213 } 13214 13215 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13216 | FLAG_PERMISSION_USER_FIXED 13217 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13218 13219 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13220 | FLAG_PERMISSION_POLICY_FIXED; 13221 13222 boolean writeInstallPermissions = false; 13223 boolean writeRuntimePermissions = false; 13224 13225 final int permissionCount = ps.pkg.requestedPermissions.size(); 13226 for (int i = 0; i < permissionCount; i++) { 13227 String permission = ps.pkg.requestedPermissions.get(i); 13228 13229 BasePermission bp = mSettings.mPermissions.get(permission); 13230 if (bp == null) { 13231 continue; 13232 } 13233 13234 // If shared user we just reset the state to which only this app contributed. 13235 if (ps.sharedUser != null) { 13236 boolean used = false; 13237 final int packageCount = ps.sharedUser.packages.size(); 13238 for (int j = 0; j < packageCount; j++) { 13239 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13240 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13241 && pkg.pkg.requestedPermissions.contains(permission)) { 13242 used = true; 13243 break; 13244 } 13245 } 13246 if (used) { 13247 continue; 13248 } 13249 } 13250 13251 PermissionsState permissionsState = ps.getPermissionsState(); 13252 13253 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13254 13255 // Always clear the user settable flags. 13256 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13257 bp.name) != null; 13258 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13259 if (hasInstallState) { 13260 writeInstallPermissions = true; 13261 } else { 13262 writeRuntimePermissions = true; 13263 } 13264 } 13265 13266 // Below is only runtime permission handling. 13267 if (!bp.isRuntime()) { 13268 continue; 13269 } 13270 13271 // Never clobber system or policy. 13272 if ((oldFlags & policyOrSystemFlags) != 0) { 13273 continue; 13274 } 13275 13276 // If this permission was granted by default, make sure it is. 13277 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13278 if (permissionsState.grantRuntimePermission(bp, userId) 13279 != PERMISSION_OPERATION_FAILURE) { 13280 writeRuntimePermissions = true; 13281 } 13282 } else { 13283 // Otherwise, reset the permission. 13284 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13285 switch (revokeResult) { 13286 case PERMISSION_OPERATION_SUCCESS: { 13287 writeRuntimePermissions = true; 13288 } break; 13289 13290 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13291 writeRuntimePermissions = true; 13292 // If gids changed for this user, kill all affected packages. 13293 mHandler.post(new Runnable() { 13294 @Override 13295 public void run() { 13296 // This has to happen with no lock held. 13297 killSettingPackagesForUser(ps, userId, 13298 KILL_APP_REASON_GIDS_CHANGED); 13299 } 13300 }); 13301 } break; 13302 } 13303 } 13304 } 13305 13306 // Synchronously write as we are taking permissions away. 13307 if (writeRuntimePermissions) { 13308 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13309 } 13310 13311 // Synchronously write as we are taking permissions away. 13312 if (writeInstallPermissions) { 13313 mSettings.writeLPr(); 13314 } 13315 } 13316 13317 /** 13318 * Remove entries from the keystore daemon. Will only remove it if the 13319 * {@code appId} is valid. 13320 */ 13321 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13322 if (appId < 0) { 13323 return; 13324 } 13325 13326 final KeyStore keyStore = KeyStore.getInstance(); 13327 if (keyStore != null) { 13328 if (userId == UserHandle.USER_ALL) { 13329 for (final int individual : sUserManager.getUserIds()) { 13330 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13331 } 13332 } else { 13333 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13334 } 13335 } else { 13336 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13337 } 13338 } 13339 13340 @Override 13341 public void deleteApplicationCacheFiles(final String packageName, 13342 final IPackageDataObserver observer) { 13343 mContext.enforceCallingOrSelfPermission( 13344 android.Manifest.permission.DELETE_CACHE_FILES, null); 13345 // Queue up an async operation since the package deletion may take a little while. 13346 final int userId = UserHandle.getCallingUserId(); 13347 mHandler.post(new Runnable() { 13348 public void run() { 13349 mHandler.removeCallbacks(this); 13350 final boolean succeded; 13351 synchronized (mInstallLock) { 13352 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13353 } 13354 clearExternalStorageDataSync(packageName, userId, false); 13355 if (observer != null) { 13356 try { 13357 observer.onRemoveCompleted(packageName, succeded); 13358 } catch (RemoteException e) { 13359 Log.i(TAG, "Observer no longer exists."); 13360 } 13361 } //end if observer 13362 } //end run 13363 }); 13364 } 13365 13366 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13367 if (packageName == null) { 13368 Slog.w(TAG, "Attempt to delete null packageName."); 13369 return false; 13370 } 13371 PackageParser.Package p; 13372 synchronized (mPackages) { 13373 p = mPackages.get(packageName); 13374 } 13375 if (p == null) { 13376 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13377 return false; 13378 } 13379 final ApplicationInfo applicationInfo = p.applicationInfo; 13380 if (applicationInfo == null) { 13381 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13382 return false; 13383 } 13384 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13385 if (retCode < 0) { 13386 Slog.w(TAG, "Couldn't remove cache files for package: " 13387 + packageName + " u" + userId); 13388 return false; 13389 } 13390 return true; 13391 } 13392 13393 @Override 13394 public void getPackageSizeInfo(final String packageName, int userHandle, 13395 final IPackageStatsObserver observer) { 13396 mContext.enforceCallingOrSelfPermission( 13397 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13398 if (packageName == null) { 13399 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13400 } 13401 13402 PackageStats stats = new PackageStats(packageName, userHandle); 13403 13404 /* 13405 * Queue up an async operation since the package measurement may take a 13406 * little while. 13407 */ 13408 Message msg = mHandler.obtainMessage(INIT_COPY); 13409 msg.obj = new MeasureParams(stats, observer); 13410 mHandler.sendMessage(msg); 13411 } 13412 13413 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13414 PackageStats pStats) { 13415 if (packageName == null) { 13416 Slog.w(TAG, "Attempt to get size of null packageName."); 13417 return false; 13418 } 13419 PackageParser.Package p; 13420 boolean dataOnly = false; 13421 String libDirRoot = null; 13422 String asecPath = null; 13423 PackageSetting ps = null; 13424 synchronized (mPackages) { 13425 p = mPackages.get(packageName); 13426 ps = mSettings.mPackages.get(packageName); 13427 if(p == null) { 13428 dataOnly = true; 13429 if((ps == null) || (ps.pkg == null)) { 13430 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13431 return false; 13432 } 13433 p = ps.pkg; 13434 } 13435 if (ps != null) { 13436 libDirRoot = ps.legacyNativeLibraryPathString; 13437 } 13438 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13439 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13440 if (secureContainerId != null) { 13441 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13442 } 13443 } 13444 } 13445 String publicSrcDir = null; 13446 if(!dataOnly) { 13447 final ApplicationInfo applicationInfo = p.applicationInfo; 13448 if (applicationInfo == null) { 13449 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13450 return false; 13451 } 13452 if (p.isForwardLocked()) { 13453 publicSrcDir = applicationInfo.getBaseResourcePath(); 13454 } 13455 } 13456 // TODO: extend to measure size of split APKs 13457 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13458 // not just the first level. 13459 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13460 // just the primary. 13461 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13462 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13463 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13464 if (res < 0) { 13465 return false; 13466 } 13467 13468 // Fix-up for forward-locked applications in ASEC containers. 13469 if (!isExternal(p)) { 13470 pStats.codeSize += pStats.externalCodeSize; 13471 pStats.externalCodeSize = 0L; 13472 } 13473 13474 return true; 13475 } 13476 13477 13478 @Override 13479 public void addPackageToPreferred(String packageName) { 13480 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13481 } 13482 13483 @Override 13484 public void removePackageFromPreferred(String packageName) { 13485 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13486 } 13487 13488 @Override 13489 public List<PackageInfo> getPreferredPackages(int flags) { 13490 return new ArrayList<PackageInfo>(); 13491 } 13492 13493 private int getUidTargetSdkVersionLockedLPr(int uid) { 13494 Object obj = mSettings.getUserIdLPr(uid); 13495 if (obj instanceof SharedUserSetting) { 13496 final SharedUserSetting sus = (SharedUserSetting) obj; 13497 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13498 final Iterator<PackageSetting> it = sus.packages.iterator(); 13499 while (it.hasNext()) { 13500 final PackageSetting ps = it.next(); 13501 if (ps.pkg != null) { 13502 int v = ps.pkg.applicationInfo.targetSdkVersion; 13503 if (v < vers) vers = v; 13504 } 13505 } 13506 return vers; 13507 } else if (obj instanceof PackageSetting) { 13508 final PackageSetting ps = (PackageSetting) obj; 13509 if (ps.pkg != null) { 13510 return ps.pkg.applicationInfo.targetSdkVersion; 13511 } 13512 } 13513 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13514 } 13515 13516 @Override 13517 public void addPreferredActivity(IntentFilter filter, int match, 13518 ComponentName[] set, ComponentName activity, int userId) { 13519 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13520 "Adding preferred"); 13521 } 13522 13523 private void addPreferredActivityInternal(IntentFilter filter, int match, 13524 ComponentName[] set, ComponentName activity, boolean always, int userId, 13525 String opname) { 13526 // writer 13527 int callingUid = Binder.getCallingUid(); 13528 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13529 if (filter.countActions() == 0) { 13530 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13531 return; 13532 } 13533 synchronized (mPackages) { 13534 if (mContext.checkCallingOrSelfPermission( 13535 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13536 != PackageManager.PERMISSION_GRANTED) { 13537 if (getUidTargetSdkVersionLockedLPr(callingUid) 13538 < Build.VERSION_CODES.FROYO) { 13539 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13540 + callingUid); 13541 return; 13542 } 13543 mContext.enforceCallingOrSelfPermission( 13544 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13545 } 13546 13547 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13548 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13549 + userId + ":"); 13550 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13551 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13552 scheduleWritePackageRestrictionsLocked(userId); 13553 } 13554 } 13555 13556 @Override 13557 public void replacePreferredActivity(IntentFilter filter, int match, 13558 ComponentName[] set, ComponentName activity, int userId) { 13559 if (filter.countActions() != 1) { 13560 throw new IllegalArgumentException( 13561 "replacePreferredActivity expects filter to have only 1 action."); 13562 } 13563 if (filter.countDataAuthorities() != 0 13564 || filter.countDataPaths() != 0 13565 || filter.countDataSchemes() > 1 13566 || filter.countDataTypes() != 0) { 13567 throw new IllegalArgumentException( 13568 "replacePreferredActivity expects filter to have no data authorities, " + 13569 "paths, or types; and at most one scheme."); 13570 } 13571 13572 final int callingUid = Binder.getCallingUid(); 13573 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13574 synchronized (mPackages) { 13575 if (mContext.checkCallingOrSelfPermission( 13576 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13577 != PackageManager.PERMISSION_GRANTED) { 13578 if (getUidTargetSdkVersionLockedLPr(callingUid) 13579 < Build.VERSION_CODES.FROYO) { 13580 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13581 + Binder.getCallingUid()); 13582 return; 13583 } 13584 mContext.enforceCallingOrSelfPermission( 13585 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13586 } 13587 13588 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13589 if (pir != null) { 13590 // Get all of the existing entries that exactly match this filter. 13591 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13592 if (existing != null && existing.size() == 1) { 13593 PreferredActivity cur = existing.get(0); 13594 if (DEBUG_PREFERRED) { 13595 Slog.i(TAG, "Checking replace of preferred:"); 13596 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13597 if (!cur.mPref.mAlways) { 13598 Slog.i(TAG, " -- CUR; not mAlways!"); 13599 } else { 13600 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13601 Slog.i(TAG, " -- CUR: mSet=" 13602 + Arrays.toString(cur.mPref.mSetComponents)); 13603 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13604 Slog.i(TAG, " -- NEW: mMatch=" 13605 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13606 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13607 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13608 } 13609 } 13610 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13611 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13612 && cur.mPref.sameSet(set)) { 13613 // Setting the preferred activity to what it happens to be already 13614 if (DEBUG_PREFERRED) { 13615 Slog.i(TAG, "Replacing with same preferred activity " 13616 + cur.mPref.mShortComponent + " for user " 13617 + userId + ":"); 13618 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13619 } 13620 return; 13621 } 13622 } 13623 13624 if (existing != null) { 13625 if (DEBUG_PREFERRED) { 13626 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13627 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13628 } 13629 for (int i = 0; i < existing.size(); i++) { 13630 PreferredActivity pa = existing.get(i); 13631 if (DEBUG_PREFERRED) { 13632 Slog.i(TAG, "Removing existing preferred activity " 13633 + pa.mPref.mComponent + ":"); 13634 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13635 } 13636 pir.removeFilter(pa); 13637 } 13638 } 13639 } 13640 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13641 "Replacing preferred"); 13642 } 13643 } 13644 13645 @Override 13646 public void clearPackagePreferredActivities(String packageName) { 13647 final int uid = Binder.getCallingUid(); 13648 // writer 13649 synchronized (mPackages) { 13650 PackageParser.Package pkg = mPackages.get(packageName); 13651 if (pkg == null || pkg.applicationInfo.uid != uid) { 13652 if (mContext.checkCallingOrSelfPermission( 13653 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13654 != PackageManager.PERMISSION_GRANTED) { 13655 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13656 < Build.VERSION_CODES.FROYO) { 13657 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13658 + Binder.getCallingUid()); 13659 return; 13660 } 13661 mContext.enforceCallingOrSelfPermission( 13662 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13663 } 13664 } 13665 13666 int user = UserHandle.getCallingUserId(); 13667 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13668 scheduleWritePackageRestrictionsLocked(user); 13669 } 13670 } 13671 } 13672 13673 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13674 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13675 ArrayList<PreferredActivity> removed = null; 13676 boolean changed = false; 13677 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13678 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13679 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13680 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13681 continue; 13682 } 13683 Iterator<PreferredActivity> it = pir.filterIterator(); 13684 while (it.hasNext()) { 13685 PreferredActivity pa = it.next(); 13686 // Mark entry for removal only if it matches the package name 13687 // and the entry is of type "always". 13688 if (packageName == null || 13689 (pa.mPref.mComponent.getPackageName().equals(packageName) 13690 && pa.mPref.mAlways)) { 13691 if (removed == null) { 13692 removed = new ArrayList<PreferredActivity>(); 13693 } 13694 removed.add(pa); 13695 } 13696 } 13697 if (removed != null) { 13698 for (int j=0; j<removed.size(); j++) { 13699 PreferredActivity pa = removed.get(j); 13700 pir.removeFilter(pa); 13701 } 13702 changed = true; 13703 } 13704 } 13705 return changed; 13706 } 13707 13708 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13709 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13710 if (userId == UserHandle.USER_ALL) { 13711 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13712 sUserManager.getUserIds())) { 13713 for (int oneUserId : sUserManager.getUserIds()) { 13714 scheduleWritePackageRestrictionsLocked(oneUserId); 13715 } 13716 } 13717 } else { 13718 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13719 scheduleWritePackageRestrictionsLocked(userId); 13720 } 13721 } 13722 } 13723 13724 13725 void clearDefaultBrowserIfNeeded(String packageName) { 13726 for (int oneUserId : sUserManager.getUserIds()) { 13727 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13728 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13729 if (packageName.equals(defaultBrowserPackageName)) { 13730 setDefaultBrowserPackageName(null, oneUserId); 13731 } 13732 } 13733 } 13734 13735 @Override 13736 public void resetPreferredActivities(int userId) { 13737 mContext.enforceCallingOrSelfPermission( 13738 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13739 // writer 13740 synchronized (mPackages) { 13741 clearPackagePreferredActivitiesLPw(null, userId); 13742 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13743 applyFactoryDefaultBrowserLPw(userId); 13744 primeDomainVerificationsLPw(userId); 13745 13746 scheduleWritePackageRestrictionsLocked(userId); 13747 } 13748 } 13749 13750 @Override 13751 public int getPreferredActivities(List<IntentFilter> outFilters, 13752 List<ComponentName> outActivities, String packageName) { 13753 13754 int num = 0; 13755 final int userId = UserHandle.getCallingUserId(); 13756 // reader 13757 synchronized (mPackages) { 13758 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13759 if (pir != null) { 13760 final Iterator<PreferredActivity> it = pir.filterIterator(); 13761 while (it.hasNext()) { 13762 final PreferredActivity pa = it.next(); 13763 if (packageName == null 13764 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13765 && pa.mPref.mAlways)) { 13766 if (outFilters != null) { 13767 outFilters.add(new IntentFilter(pa)); 13768 } 13769 if (outActivities != null) { 13770 outActivities.add(pa.mPref.mComponent); 13771 } 13772 } 13773 } 13774 } 13775 } 13776 13777 return num; 13778 } 13779 13780 @Override 13781 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13782 int userId) { 13783 int callingUid = Binder.getCallingUid(); 13784 if (callingUid != Process.SYSTEM_UID) { 13785 throw new SecurityException( 13786 "addPersistentPreferredActivity can only be run by the system"); 13787 } 13788 if (filter.countActions() == 0) { 13789 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13790 return; 13791 } 13792 synchronized (mPackages) { 13793 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13794 " :"); 13795 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13796 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13797 new PersistentPreferredActivity(filter, activity)); 13798 scheduleWritePackageRestrictionsLocked(userId); 13799 } 13800 } 13801 13802 @Override 13803 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13804 int callingUid = Binder.getCallingUid(); 13805 if (callingUid != Process.SYSTEM_UID) { 13806 throw new SecurityException( 13807 "clearPackagePersistentPreferredActivities can only be run by the system"); 13808 } 13809 ArrayList<PersistentPreferredActivity> removed = null; 13810 boolean changed = false; 13811 synchronized (mPackages) { 13812 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13813 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13814 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13815 .valueAt(i); 13816 if (userId != thisUserId) { 13817 continue; 13818 } 13819 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13820 while (it.hasNext()) { 13821 PersistentPreferredActivity ppa = it.next(); 13822 // Mark entry for removal only if it matches the package name. 13823 if (ppa.mComponent.getPackageName().equals(packageName)) { 13824 if (removed == null) { 13825 removed = new ArrayList<PersistentPreferredActivity>(); 13826 } 13827 removed.add(ppa); 13828 } 13829 } 13830 if (removed != null) { 13831 for (int j=0; j<removed.size(); j++) { 13832 PersistentPreferredActivity ppa = removed.get(j); 13833 ppir.removeFilter(ppa); 13834 } 13835 changed = true; 13836 } 13837 } 13838 13839 if (changed) { 13840 scheduleWritePackageRestrictionsLocked(userId); 13841 } 13842 } 13843 } 13844 13845 /** 13846 * Common machinery for picking apart a restored XML blob and passing 13847 * it to a caller-supplied functor to be applied to the running system. 13848 */ 13849 private void restoreFromXml(XmlPullParser parser, int userId, 13850 String expectedStartTag, BlobXmlRestorer functor) 13851 throws IOException, XmlPullParserException { 13852 int type; 13853 while ((type = parser.next()) != XmlPullParser.START_TAG 13854 && type != XmlPullParser.END_DOCUMENT) { 13855 } 13856 if (type != XmlPullParser.START_TAG) { 13857 // oops didn't find a start tag?! 13858 if (DEBUG_BACKUP) { 13859 Slog.e(TAG, "Didn't find start tag during restore"); 13860 } 13861 return; 13862 } 13863 13864 // this is supposed to be TAG_PREFERRED_BACKUP 13865 if (!expectedStartTag.equals(parser.getName())) { 13866 if (DEBUG_BACKUP) { 13867 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13868 } 13869 return; 13870 } 13871 13872 // skip interfering stuff, then we're aligned with the backing implementation 13873 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13874 functor.apply(parser, userId); 13875 } 13876 13877 private interface BlobXmlRestorer { 13878 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13879 } 13880 13881 /** 13882 * Non-Binder method, support for the backup/restore mechanism: write the 13883 * full set of preferred activities in its canonical XML format. Returns the 13884 * XML output as a byte array, or null if there is none. 13885 */ 13886 @Override 13887 public byte[] getPreferredActivityBackup(int userId) { 13888 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13889 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13890 } 13891 13892 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13893 try { 13894 final XmlSerializer serializer = new FastXmlSerializer(); 13895 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13896 serializer.startDocument(null, true); 13897 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13898 13899 synchronized (mPackages) { 13900 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13901 } 13902 13903 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13904 serializer.endDocument(); 13905 serializer.flush(); 13906 } catch (Exception e) { 13907 if (DEBUG_BACKUP) { 13908 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13909 } 13910 return null; 13911 } 13912 13913 return dataStream.toByteArray(); 13914 } 13915 13916 @Override 13917 public void restorePreferredActivities(byte[] backup, int userId) { 13918 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13919 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13920 } 13921 13922 try { 13923 final XmlPullParser parser = Xml.newPullParser(); 13924 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13925 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13926 new BlobXmlRestorer() { 13927 @Override 13928 public void apply(XmlPullParser parser, int userId) 13929 throws XmlPullParserException, IOException { 13930 synchronized (mPackages) { 13931 mSettings.readPreferredActivitiesLPw(parser, userId); 13932 } 13933 } 13934 } ); 13935 } catch (Exception e) { 13936 if (DEBUG_BACKUP) { 13937 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13938 } 13939 } 13940 } 13941 13942 /** 13943 * Non-Binder method, support for the backup/restore mechanism: write the 13944 * default browser (etc) settings in its canonical XML format. Returns the default 13945 * browser XML representation as a byte array, or null if there is none. 13946 */ 13947 @Override 13948 public byte[] getDefaultAppsBackup(int userId) { 13949 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13950 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13951 } 13952 13953 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13954 try { 13955 final XmlSerializer serializer = new FastXmlSerializer(); 13956 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13957 serializer.startDocument(null, true); 13958 serializer.startTag(null, TAG_DEFAULT_APPS); 13959 13960 synchronized (mPackages) { 13961 mSettings.writeDefaultAppsLPr(serializer, userId); 13962 } 13963 13964 serializer.endTag(null, TAG_DEFAULT_APPS); 13965 serializer.endDocument(); 13966 serializer.flush(); 13967 } catch (Exception e) { 13968 if (DEBUG_BACKUP) { 13969 Slog.e(TAG, "Unable to write default apps for backup", e); 13970 } 13971 return null; 13972 } 13973 13974 return dataStream.toByteArray(); 13975 } 13976 13977 @Override 13978 public void restoreDefaultApps(byte[] backup, int userId) { 13979 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13980 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13981 } 13982 13983 try { 13984 final XmlPullParser parser = Xml.newPullParser(); 13985 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13986 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13987 new BlobXmlRestorer() { 13988 @Override 13989 public void apply(XmlPullParser parser, int userId) 13990 throws XmlPullParserException, IOException { 13991 synchronized (mPackages) { 13992 mSettings.readDefaultAppsLPw(parser, userId); 13993 } 13994 } 13995 } ); 13996 } catch (Exception e) { 13997 if (DEBUG_BACKUP) { 13998 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13999 } 14000 } 14001 } 14002 14003 @Override 14004 public byte[] getIntentFilterVerificationBackup(int userId) { 14005 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14006 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14007 } 14008 14009 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14010 try { 14011 final XmlSerializer serializer = new FastXmlSerializer(); 14012 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14013 serializer.startDocument(null, true); 14014 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14015 14016 synchronized (mPackages) { 14017 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14018 } 14019 14020 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14021 serializer.endDocument(); 14022 serializer.flush(); 14023 } catch (Exception e) { 14024 if (DEBUG_BACKUP) { 14025 Slog.e(TAG, "Unable to write default apps for backup", e); 14026 } 14027 return null; 14028 } 14029 14030 return dataStream.toByteArray(); 14031 } 14032 14033 @Override 14034 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14035 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14036 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14037 } 14038 14039 try { 14040 final XmlPullParser parser = Xml.newPullParser(); 14041 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14042 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14043 new BlobXmlRestorer() { 14044 @Override 14045 public void apply(XmlPullParser parser, int userId) 14046 throws XmlPullParserException, IOException { 14047 synchronized (mPackages) { 14048 mSettings.readAllDomainVerificationsLPr(parser, userId); 14049 mSettings.writeLPr(); 14050 } 14051 } 14052 } ); 14053 } catch (Exception e) { 14054 if (DEBUG_BACKUP) { 14055 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14056 } 14057 } 14058 } 14059 14060 @Override 14061 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14062 int sourceUserId, int targetUserId, int flags) { 14063 mContext.enforceCallingOrSelfPermission( 14064 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14065 int callingUid = Binder.getCallingUid(); 14066 enforceOwnerRights(ownerPackage, callingUid); 14067 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14068 if (intentFilter.countActions() == 0) { 14069 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14070 return; 14071 } 14072 synchronized (mPackages) { 14073 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14074 ownerPackage, targetUserId, flags); 14075 CrossProfileIntentResolver resolver = 14076 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14077 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14078 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14079 if (existing != null) { 14080 int size = existing.size(); 14081 for (int i = 0; i < size; i++) { 14082 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14083 return; 14084 } 14085 } 14086 } 14087 resolver.addFilter(newFilter); 14088 scheduleWritePackageRestrictionsLocked(sourceUserId); 14089 } 14090 } 14091 14092 @Override 14093 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14094 mContext.enforceCallingOrSelfPermission( 14095 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14096 int callingUid = Binder.getCallingUid(); 14097 enforceOwnerRights(ownerPackage, callingUid); 14098 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14099 synchronized (mPackages) { 14100 CrossProfileIntentResolver resolver = 14101 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14102 ArraySet<CrossProfileIntentFilter> set = 14103 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14104 for (CrossProfileIntentFilter filter : set) { 14105 if (filter.getOwnerPackage().equals(ownerPackage)) { 14106 resolver.removeFilter(filter); 14107 } 14108 } 14109 scheduleWritePackageRestrictionsLocked(sourceUserId); 14110 } 14111 } 14112 14113 // Enforcing that callingUid is owning pkg on userId 14114 private void enforceOwnerRights(String pkg, int callingUid) { 14115 // The system owns everything. 14116 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14117 return; 14118 } 14119 int callingUserId = UserHandle.getUserId(callingUid); 14120 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14121 if (pi == null) { 14122 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14123 + callingUserId); 14124 } 14125 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14126 throw new SecurityException("Calling uid " + callingUid 14127 + " does not own package " + pkg); 14128 } 14129 } 14130 14131 @Override 14132 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14133 Intent intent = new Intent(Intent.ACTION_MAIN); 14134 intent.addCategory(Intent.CATEGORY_HOME); 14135 14136 final int callingUserId = UserHandle.getCallingUserId(); 14137 List<ResolveInfo> list = queryIntentActivities(intent, null, 14138 PackageManager.GET_META_DATA, callingUserId); 14139 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14140 true, false, false, callingUserId); 14141 14142 allHomeCandidates.clear(); 14143 if (list != null) { 14144 for (ResolveInfo ri : list) { 14145 allHomeCandidates.add(ri); 14146 } 14147 } 14148 return (preferred == null || preferred.activityInfo == null) 14149 ? null 14150 : new ComponentName(preferred.activityInfo.packageName, 14151 preferred.activityInfo.name); 14152 } 14153 14154 @Override 14155 public void setApplicationEnabledSetting(String appPackageName, 14156 int newState, int flags, int userId, String callingPackage) { 14157 if (!sUserManager.exists(userId)) return; 14158 if (callingPackage == null) { 14159 callingPackage = Integer.toString(Binder.getCallingUid()); 14160 } 14161 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14162 } 14163 14164 @Override 14165 public void setComponentEnabledSetting(ComponentName componentName, 14166 int newState, int flags, int userId) { 14167 if (!sUserManager.exists(userId)) return; 14168 setEnabledSetting(componentName.getPackageName(), 14169 componentName.getClassName(), newState, flags, userId, null); 14170 } 14171 14172 private void setEnabledSetting(final String packageName, String className, int newState, 14173 final int flags, int userId, String callingPackage) { 14174 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14175 || newState == COMPONENT_ENABLED_STATE_ENABLED 14176 || newState == COMPONENT_ENABLED_STATE_DISABLED 14177 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14178 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14179 throw new IllegalArgumentException("Invalid new component state: " 14180 + newState); 14181 } 14182 PackageSetting pkgSetting; 14183 final int uid = Binder.getCallingUid(); 14184 final int permission = mContext.checkCallingOrSelfPermission( 14185 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14186 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14187 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14188 boolean sendNow = false; 14189 boolean isApp = (className == null); 14190 String componentName = isApp ? packageName : className; 14191 int packageUid = -1; 14192 ArrayList<String> components; 14193 14194 // writer 14195 synchronized (mPackages) { 14196 pkgSetting = mSettings.mPackages.get(packageName); 14197 if (pkgSetting == null) { 14198 if (className == null) { 14199 throw new IllegalArgumentException( 14200 "Unknown package: " + packageName); 14201 } 14202 throw new IllegalArgumentException( 14203 "Unknown component: " + packageName 14204 + "/" + className); 14205 } 14206 // Allow root and verify that userId is not being specified by a different user 14207 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14208 throw new SecurityException( 14209 "Permission Denial: attempt to change component state from pid=" 14210 + Binder.getCallingPid() 14211 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14212 } 14213 if (className == null) { 14214 // We're dealing with an application/package level state change 14215 if (pkgSetting.getEnabled(userId) == newState) { 14216 // Nothing to do 14217 return; 14218 } 14219 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14220 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14221 // Don't care about who enables an app. 14222 callingPackage = null; 14223 } 14224 pkgSetting.setEnabled(newState, userId, callingPackage); 14225 // pkgSetting.pkg.mSetEnabled = newState; 14226 } else { 14227 // We're dealing with a component level state change 14228 // First, verify that this is a valid class name. 14229 PackageParser.Package pkg = pkgSetting.pkg; 14230 if (pkg == null || !pkg.hasComponentClassName(className)) { 14231 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14232 throw new IllegalArgumentException("Component class " + className 14233 + " does not exist in " + packageName); 14234 } else { 14235 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14236 + className + " does not exist in " + packageName); 14237 } 14238 } 14239 switch (newState) { 14240 case COMPONENT_ENABLED_STATE_ENABLED: 14241 if (!pkgSetting.enableComponentLPw(className, userId)) { 14242 return; 14243 } 14244 break; 14245 case COMPONENT_ENABLED_STATE_DISABLED: 14246 if (!pkgSetting.disableComponentLPw(className, userId)) { 14247 return; 14248 } 14249 break; 14250 case COMPONENT_ENABLED_STATE_DEFAULT: 14251 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14252 return; 14253 } 14254 break; 14255 default: 14256 Slog.e(TAG, "Invalid new component state: " + newState); 14257 return; 14258 } 14259 } 14260 scheduleWritePackageRestrictionsLocked(userId); 14261 components = mPendingBroadcasts.get(userId, packageName); 14262 final boolean newPackage = components == null; 14263 if (newPackage) { 14264 components = new ArrayList<String>(); 14265 } 14266 if (!components.contains(componentName)) { 14267 components.add(componentName); 14268 } 14269 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14270 sendNow = true; 14271 // Purge entry from pending broadcast list if another one exists already 14272 // since we are sending one right away. 14273 mPendingBroadcasts.remove(userId, packageName); 14274 } else { 14275 if (newPackage) { 14276 mPendingBroadcasts.put(userId, packageName, components); 14277 } 14278 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14279 // Schedule a message 14280 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14281 } 14282 } 14283 } 14284 14285 long callingId = Binder.clearCallingIdentity(); 14286 try { 14287 if (sendNow) { 14288 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14289 sendPackageChangedBroadcast(packageName, 14290 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14291 } 14292 } finally { 14293 Binder.restoreCallingIdentity(callingId); 14294 } 14295 } 14296 14297 private void sendPackageChangedBroadcast(String packageName, 14298 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14299 if (DEBUG_INSTALL) 14300 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14301 + componentNames); 14302 Bundle extras = new Bundle(4); 14303 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14304 String nameList[] = new String[componentNames.size()]; 14305 componentNames.toArray(nameList); 14306 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14307 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14308 extras.putInt(Intent.EXTRA_UID, packageUid); 14309 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14310 new int[] {UserHandle.getUserId(packageUid)}); 14311 } 14312 14313 @Override 14314 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14315 if (!sUserManager.exists(userId)) return; 14316 final int uid = Binder.getCallingUid(); 14317 final int permission = mContext.checkCallingOrSelfPermission( 14318 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14319 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14320 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14321 // writer 14322 synchronized (mPackages) { 14323 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14324 allowedByPermission, uid, userId)) { 14325 scheduleWritePackageRestrictionsLocked(userId); 14326 } 14327 } 14328 } 14329 14330 @Override 14331 public String getInstallerPackageName(String packageName) { 14332 // reader 14333 synchronized (mPackages) { 14334 return mSettings.getInstallerPackageNameLPr(packageName); 14335 } 14336 } 14337 14338 @Override 14339 public int getApplicationEnabledSetting(String packageName, int userId) { 14340 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14341 int uid = Binder.getCallingUid(); 14342 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14343 // reader 14344 synchronized (mPackages) { 14345 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14346 } 14347 } 14348 14349 @Override 14350 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14351 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14352 int uid = Binder.getCallingUid(); 14353 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14354 // reader 14355 synchronized (mPackages) { 14356 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14357 } 14358 } 14359 14360 @Override 14361 public void enterSafeMode() { 14362 enforceSystemOrRoot("Only the system can request entering safe mode"); 14363 14364 if (!mSystemReady) { 14365 mSafeMode = true; 14366 } 14367 } 14368 14369 @Override 14370 public void systemReady() { 14371 mSystemReady = true; 14372 14373 // Read the compatibilty setting when the system is ready. 14374 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14375 mContext.getContentResolver(), 14376 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14377 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14378 if (DEBUG_SETTINGS) { 14379 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14380 } 14381 14382 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14383 14384 synchronized (mPackages) { 14385 // Verify that all of the preferred activity components actually 14386 // exist. It is possible for applications to be updated and at 14387 // that point remove a previously declared activity component that 14388 // had been set as a preferred activity. We try to clean this up 14389 // the next time we encounter that preferred activity, but it is 14390 // possible for the user flow to never be able to return to that 14391 // situation so here we do a sanity check to make sure we haven't 14392 // left any junk around. 14393 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14394 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14395 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14396 removed.clear(); 14397 for (PreferredActivity pa : pir.filterSet()) { 14398 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14399 removed.add(pa); 14400 } 14401 } 14402 if (removed.size() > 0) { 14403 for (int r=0; r<removed.size(); r++) { 14404 PreferredActivity pa = removed.get(r); 14405 Slog.w(TAG, "Removing dangling preferred activity: " 14406 + pa.mPref.mComponent); 14407 pir.removeFilter(pa); 14408 } 14409 mSettings.writePackageRestrictionsLPr( 14410 mSettings.mPreferredActivities.keyAt(i)); 14411 } 14412 } 14413 14414 for (int userId : UserManagerService.getInstance().getUserIds()) { 14415 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14416 grantPermissionsUserIds = ArrayUtils.appendInt( 14417 grantPermissionsUserIds, userId); 14418 } 14419 } 14420 } 14421 sUserManager.systemReady(); 14422 14423 // If we upgraded grant all default permissions before kicking off. 14424 for (int userId : grantPermissionsUserIds) { 14425 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14426 } 14427 14428 // Kick off any messages waiting for system ready 14429 if (mPostSystemReadyMessages != null) { 14430 for (Message msg : mPostSystemReadyMessages) { 14431 msg.sendToTarget(); 14432 } 14433 mPostSystemReadyMessages = null; 14434 } 14435 14436 // Watch for external volumes that come and go over time 14437 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14438 storage.registerListener(mStorageListener); 14439 14440 mInstallerService.systemReady(); 14441 mPackageDexOptimizer.systemReady(); 14442 } 14443 14444 @Override 14445 public boolean isSafeMode() { 14446 return mSafeMode; 14447 } 14448 14449 @Override 14450 public boolean hasSystemUidErrors() { 14451 return mHasSystemUidErrors; 14452 } 14453 14454 static String arrayToString(int[] array) { 14455 StringBuffer buf = new StringBuffer(128); 14456 buf.append('['); 14457 if (array != null) { 14458 for (int i=0; i<array.length; i++) { 14459 if (i > 0) buf.append(", "); 14460 buf.append(array[i]); 14461 } 14462 } 14463 buf.append(']'); 14464 return buf.toString(); 14465 } 14466 14467 static class DumpState { 14468 public static final int DUMP_LIBS = 1 << 0; 14469 public static final int DUMP_FEATURES = 1 << 1; 14470 public static final int DUMP_RESOLVERS = 1 << 2; 14471 public static final int DUMP_PERMISSIONS = 1 << 3; 14472 public static final int DUMP_PACKAGES = 1 << 4; 14473 public static final int DUMP_SHARED_USERS = 1 << 5; 14474 public static final int DUMP_MESSAGES = 1 << 6; 14475 public static final int DUMP_PROVIDERS = 1 << 7; 14476 public static final int DUMP_VERIFIERS = 1 << 8; 14477 public static final int DUMP_PREFERRED = 1 << 9; 14478 public static final int DUMP_PREFERRED_XML = 1 << 10; 14479 public static final int DUMP_KEYSETS = 1 << 11; 14480 public static final int DUMP_VERSION = 1 << 12; 14481 public static final int DUMP_INSTALLS = 1 << 13; 14482 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14483 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14484 14485 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14486 14487 private int mTypes; 14488 14489 private int mOptions; 14490 14491 private boolean mTitlePrinted; 14492 14493 private SharedUserSetting mSharedUser; 14494 14495 public boolean isDumping(int type) { 14496 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14497 return true; 14498 } 14499 14500 return (mTypes & type) != 0; 14501 } 14502 14503 public void setDump(int type) { 14504 mTypes |= type; 14505 } 14506 14507 public boolean isOptionEnabled(int option) { 14508 return (mOptions & option) != 0; 14509 } 14510 14511 public void setOptionEnabled(int option) { 14512 mOptions |= option; 14513 } 14514 14515 public boolean onTitlePrinted() { 14516 final boolean printed = mTitlePrinted; 14517 mTitlePrinted = true; 14518 return printed; 14519 } 14520 14521 public boolean getTitlePrinted() { 14522 return mTitlePrinted; 14523 } 14524 14525 public void setTitlePrinted(boolean enabled) { 14526 mTitlePrinted = enabled; 14527 } 14528 14529 public SharedUserSetting getSharedUser() { 14530 return mSharedUser; 14531 } 14532 14533 public void setSharedUser(SharedUserSetting user) { 14534 mSharedUser = user; 14535 } 14536 } 14537 14538 @Override 14539 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14540 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14541 != PackageManager.PERMISSION_GRANTED) { 14542 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14543 + Binder.getCallingPid() 14544 + ", uid=" + Binder.getCallingUid() 14545 + " without permission " 14546 + android.Manifest.permission.DUMP); 14547 return; 14548 } 14549 14550 DumpState dumpState = new DumpState(); 14551 boolean fullPreferred = false; 14552 boolean checkin = false; 14553 14554 String packageName = null; 14555 ArraySet<String> permissionNames = null; 14556 14557 int opti = 0; 14558 while (opti < args.length) { 14559 String opt = args[opti]; 14560 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14561 break; 14562 } 14563 opti++; 14564 14565 if ("-a".equals(opt)) { 14566 // Right now we only know how to print all. 14567 } else if ("-h".equals(opt)) { 14568 pw.println("Package manager dump options:"); 14569 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14570 pw.println(" --checkin: dump for a checkin"); 14571 pw.println(" -f: print details of intent filters"); 14572 pw.println(" -h: print this help"); 14573 pw.println(" cmd may be one of:"); 14574 pw.println(" l[ibraries]: list known shared libraries"); 14575 pw.println(" f[ibraries]: list device features"); 14576 pw.println(" k[eysets]: print known keysets"); 14577 pw.println(" r[esolvers]: dump intent resolvers"); 14578 pw.println(" perm[issions]: dump permissions"); 14579 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14580 pw.println(" pref[erred]: print preferred package settings"); 14581 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14582 pw.println(" prov[iders]: dump content providers"); 14583 pw.println(" p[ackages]: dump installed packages"); 14584 pw.println(" s[hared-users]: dump shared user IDs"); 14585 pw.println(" m[essages]: print collected runtime messages"); 14586 pw.println(" v[erifiers]: print package verifier info"); 14587 pw.println(" version: print database version info"); 14588 pw.println(" write: write current settings now"); 14589 pw.println(" <package.name>: info about given package"); 14590 pw.println(" installs: details about install sessions"); 14591 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14592 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14593 return; 14594 } else if ("--checkin".equals(opt)) { 14595 checkin = true; 14596 } else if ("-f".equals(opt)) { 14597 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14598 } else { 14599 pw.println("Unknown argument: " + opt + "; use -h for help"); 14600 } 14601 } 14602 14603 // Is the caller requesting to dump a particular piece of data? 14604 if (opti < args.length) { 14605 String cmd = args[opti]; 14606 opti++; 14607 // Is this a package name? 14608 if ("android".equals(cmd) || cmd.contains(".")) { 14609 packageName = cmd; 14610 // When dumping a single package, we always dump all of its 14611 // filter information since the amount of data will be reasonable. 14612 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14613 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14614 dumpState.setDump(DumpState.DUMP_LIBS); 14615 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14616 dumpState.setDump(DumpState.DUMP_FEATURES); 14617 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14618 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14619 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14620 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14621 } else if ("permission".equals(cmd)) { 14622 if (opti >= args.length) { 14623 pw.println("Error: permission requires permission name"); 14624 return; 14625 } 14626 permissionNames = new ArraySet<>(); 14627 while (opti < args.length) { 14628 permissionNames.add(args[opti]); 14629 opti++; 14630 } 14631 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14632 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14633 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14634 dumpState.setDump(DumpState.DUMP_PREFERRED); 14635 } else if ("preferred-xml".equals(cmd)) { 14636 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14637 if (opti < args.length && "--full".equals(args[opti])) { 14638 fullPreferred = true; 14639 opti++; 14640 } 14641 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14642 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14643 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14644 dumpState.setDump(DumpState.DUMP_PACKAGES); 14645 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14646 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14647 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14648 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14649 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14650 dumpState.setDump(DumpState.DUMP_MESSAGES); 14651 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14652 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14653 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14654 || "intent-filter-verifiers".equals(cmd)) { 14655 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14656 } else if ("version".equals(cmd)) { 14657 dumpState.setDump(DumpState.DUMP_VERSION); 14658 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14659 dumpState.setDump(DumpState.DUMP_KEYSETS); 14660 } else if ("installs".equals(cmd)) { 14661 dumpState.setDump(DumpState.DUMP_INSTALLS); 14662 } else if ("write".equals(cmd)) { 14663 synchronized (mPackages) { 14664 mSettings.writeLPr(); 14665 pw.println("Settings written."); 14666 return; 14667 } 14668 } 14669 } 14670 14671 if (checkin) { 14672 pw.println("vers,1"); 14673 } 14674 14675 // reader 14676 synchronized (mPackages) { 14677 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14678 if (!checkin) { 14679 if (dumpState.onTitlePrinted()) 14680 pw.println(); 14681 pw.println("Database versions:"); 14682 pw.print(" SDK Version:"); 14683 pw.print(" internal="); 14684 pw.print(mSettings.mInternalSdkPlatform); 14685 pw.print(" external="); 14686 pw.println(mSettings.mExternalSdkPlatform); 14687 pw.print(" DB Version:"); 14688 pw.print(" internal="); 14689 pw.print(mSettings.mInternalDatabaseVersion); 14690 pw.print(" external="); 14691 pw.println(mSettings.mExternalDatabaseVersion); 14692 } 14693 } 14694 14695 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14696 if (!checkin) { 14697 if (dumpState.onTitlePrinted()) 14698 pw.println(); 14699 pw.println("Verifiers:"); 14700 pw.print(" Required: "); 14701 pw.print(mRequiredVerifierPackage); 14702 pw.print(" (uid="); 14703 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14704 pw.println(")"); 14705 } else if (mRequiredVerifierPackage != null) { 14706 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14707 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14708 } 14709 } 14710 14711 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14712 packageName == null) { 14713 if (mIntentFilterVerifierComponent != null) { 14714 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14715 if (!checkin) { 14716 if (dumpState.onTitlePrinted()) 14717 pw.println(); 14718 pw.println("Intent Filter Verifier:"); 14719 pw.print(" Using: "); 14720 pw.print(verifierPackageName); 14721 pw.print(" (uid="); 14722 pw.print(getPackageUid(verifierPackageName, 0)); 14723 pw.println(")"); 14724 } else if (verifierPackageName != null) { 14725 pw.print("ifv,"); pw.print(verifierPackageName); 14726 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14727 } 14728 } else { 14729 pw.println(); 14730 pw.println("No Intent Filter Verifier available!"); 14731 } 14732 } 14733 14734 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14735 boolean printedHeader = false; 14736 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14737 while (it.hasNext()) { 14738 String name = it.next(); 14739 SharedLibraryEntry ent = mSharedLibraries.get(name); 14740 if (!checkin) { 14741 if (!printedHeader) { 14742 if (dumpState.onTitlePrinted()) 14743 pw.println(); 14744 pw.println("Libraries:"); 14745 printedHeader = true; 14746 } 14747 pw.print(" "); 14748 } else { 14749 pw.print("lib,"); 14750 } 14751 pw.print(name); 14752 if (!checkin) { 14753 pw.print(" -> "); 14754 } 14755 if (ent.path != null) { 14756 if (!checkin) { 14757 pw.print("(jar) "); 14758 pw.print(ent.path); 14759 } else { 14760 pw.print(",jar,"); 14761 pw.print(ent.path); 14762 } 14763 } else { 14764 if (!checkin) { 14765 pw.print("(apk) "); 14766 pw.print(ent.apk); 14767 } else { 14768 pw.print(",apk,"); 14769 pw.print(ent.apk); 14770 } 14771 } 14772 pw.println(); 14773 } 14774 } 14775 14776 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14777 if (dumpState.onTitlePrinted()) 14778 pw.println(); 14779 if (!checkin) { 14780 pw.println("Features:"); 14781 } 14782 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14783 while (it.hasNext()) { 14784 String name = it.next(); 14785 if (!checkin) { 14786 pw.print(" "); 14787 } else { 14788 pw.print("feat,"); 14789 } 14790 pw.println(name); 14791 } 14792 } 14793 14794 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14795 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14796 : "Activity Resolver Table:", " ", packageName, 14797 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14798 dumpState.setTitlePrinted(true); 14799 } 14800 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14801 : "Receiver Resolver Table:", " ", packageName, 14802 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14803 dumpState.setTitlePrinted(true); 14804 } 14805 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14806 : "Service Resolver Table:", " ", packageName, 14807 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14808 dumpState.setTitlePrinted(true); 14809 } 14810 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14811 : "Provider Resolver Table:", " ", packageName, 14812 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14813 dumpState.setTitlePrinted(true); 14814 } 14815 } 14816 14817 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14818 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14819 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14820 int user = mSettings.mPreferredActivities.keyAt(i); 14821 if (pir.dump(pw, 14822 dumpState.getTitlePrinted() 14823 ? "\nPreferred Activities User " + user + ":" 14824 : "Preferred Activities User " + user + ":", " ", 14825 packageName, true, false)) { 14826 dumpState.setTitlePrinted(true); 14827 } 14828 } 14829 } 14830 14831 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14832 pw.flush(); 14833 FileOutputStream fout = new FileOutputStream(fd); 14834 BufferedOutputStream str = new BufferedOutputStream(fout); 14835 XmlSerializer serializer = new FastXmlSerializer(); 14836 try { 14837 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14838 serializer.startDocument(null, true); 14839 serializer.setFeature( 14840 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14841 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14842 serializer.endDocument(); 14843 serializer.flush(); 14844 } catch (IllegalArgumentException e) { 14845 pw.println("Failed writing: " + e); 14846 } catch (IllegalStateException e) { 14847 pw.println("Failed writing: " + e); 14848 } catch (IOException e) { 14849 pw.println("Failed writing: " + e); 14850 } 14851 } 14852 14853 if (!checkin 14854 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14855 && packageName == null) { 14856 pw.println(); 14857 int count = mSettings.mPackages.size(); 14858 if (count == 0) { 14859 pw.println("No applications!"); 14860 pw.println(); 14861 } else { 14862 final String prefix = " "; 14863 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14864 if (allPackageSettings.size() == 0) { 14865 pw.println("No domain preferred apps!"); 14866 pw.println(); 14867 } else { 14868 pw.println("App verification status:"); 14869 pw.println(); 14870 count = 0; 14871 for (PackageSetting ps : allPackageSettings) { 14872 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14873 if (ivi == null || ivi.getPackageName() == null) continue; 14874 pw.println(prefix + "Package: " + ivi.getPackageName()); 14875 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14876 pw.println(prefix + "Status: " + ivi.getStatusString()); 14877 pw.println(); 14878 count++; 14879 } 14880 if (count == 0) { 14881 pw.println(prefix + "No app verification established."); 14882 pw.println(); 14883 } 14884 for (int userId : sUserManager.getUserIds()) { 14885 pw.println("App linkages for user " + userId + ":"); 14886 pw.println(); 14887 count = 0; 14888 for (PackageSetting ps : allPackageSettings) { 14889 final int status = ps.getDomainVerificationStatusForUser(userId); 14890 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14891 continue; 14892 } 14893 pw.println(prefix + "Package: " + ps.name); 14894 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14895 String statusStr = IntentFilterVerificationInfo. 14896 getStatusStringFromValue(status); 14897 pw.println(prefix + "Status: " + statusStr); 14898 pw.println(); 14899 count++; 14900 } 14901 if (count == 0) { 14902 pw.println(prefix + "No configured app linkages."); 14903 pw.println(); 14904 } 14905 } 14906 } 14907 } 14908 } 14909 14910 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14911 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14912 if (packageName == null && permissionNames == null) { 14913 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14914 if (iperm == 0) { 14915 if (dumpState.onTitlePrinted()) 14916 pw.println(); 14917 pw.println("AppOp Permissions:"); 14918 } 14919 pw.print(" AppOp Permission "); 14920 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14921 pw.println(":"); 14922 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14923 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14924 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14925 } 14926 } 14927 } 14928 } 14929 14930 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14931 boolean printedSomething = false; 14932 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14933 if (packageName != null && !packageName.equals(p.info.packageName)) { 14934 continue; 14935 } 14936 if (!printedSomething) { 14937 if (dumpState.onTitlePrinted()) 14938 pw.println(); 14939 pw.println("Registered ContentProviders:"); 14940 printedSomething = true; 14941 } 14942 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14943 pw.print(" "); pw.println(p.toString()); 14944 } 14945 printedSomething = false; 14946 for (Map.Entry<String, PackageParser.Provider> entry : 14947 mProvidersByAuthority.entrySet()) { 14948 PackageParser.Provider p = entry.getValue(); 14949 if (packageName != null && !packageName.equals(p.info.packageName)) { 14950 continue; 14951 } 14952 if (!printedSomething) { 14953 if (dumpState.onTitlePrinted()) 14954 pw.println(); 14955 pw.println("ContentProvider Authorities:"); 14956 printedSomething = true; 14957 } 14958 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14959 pw.print(" "); pw.println(p.toString()); 14960 if (p.info != null && p.info.applicationInfo != null) { 14961 final String appInfo = p.info.applicationInfo.toString(); 14962 pw.print(" applicationInfo="); pw.println(appInfo); 14963 } 14964 } 14965 } 14966 14967 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14968 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14969 } 14970 14971 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14972 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14973 } 14974 14975 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14976 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14977 } 14978 14979 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14980 // XXX should handle packageName != null by dumping only install data that 14981 // the given package is involved with. 14982 if (dumpState.onTitlePrinted()) pw.println(); 14983 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14984 } 14985 14986 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14987 if (dumpState.onTitlePrinted()) pw.println(); 14988 mSettings.dumpReadMessagesLPr(pw, dumpState); 14989 14990 pw.println(); 14991 pw.println("Package warning messages:"); 14992 BufferedReader in = null; 14993 String line = null; 14994 try { 14995 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14996 while ((line = in.readLine()) != null) { 14997 if (line.contains("ignored: updated version")) continue; 14998 pw.println(line); 14999 } 15000 } catch (IOException ignored) { 15001 } finally { 15002 IoUtils.closeQuietly(in); 15003 } 15004 } 15005 15006 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15007 BufferedReader in = null; 15008 String line = null; 15009 try { 15010 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15011 while ((line = in.readLine()) != null) { 15012 if (line.contains("ignored: updated version")) continue; 15013 pw.print("msg,"); 15014 pw.println(line); 15015 } 15016 } catch (IOException ignored) { 15017 } finally { 15018 IoUtils.closeQuietly(in); 15019 } 15020 } 15021 } 15022 } 15023 15024 private String dumpDomainString(String packageName) { 15025 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15026 List<IntentFilter> filters = getAllIntentFilters(packageName); 15027 15028 ArraySet<String> result = new ArraySet<>(); 15029 if (iviList.size() > 0) { 15030 for (IntentFilterVerificationInfo ivi : iviList) { 15031 for (String host : ivi.getDomains()) { 15032 result.add(host); 15033 } 15034 } 15035 } 15036 if (filters != null && filters.size() > 0) { 15037 for (IntentFilter filter : filters) { 15038 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15039 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) { 15040 result.addAll(filter.getHostsList()); 15041 } 15042 } 15043 } 15044 15045 StringBuilder sb = new StringBuilder(result.size() * 16); 15046 for (String domain : result) { 15047 if (sb.length() > 0) sb.append(" "); 15048 sb.append(domain); 15049 } 15050 return sb.toString(); 15051 } 15052 15053 // ------- apps on sdcard specific code ------- 15054 static final boolean DEBUG_SD_INSTALL = false; 15055 15056 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15057 15058 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15059 15060 private boolean mMediaMounted = false; 15061 15062 static String getEncryptKey() { 15063 try { 15064 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15065 SD_ENCRYPTION_KEYSTORE_NAME); 15066 if (sdEncKey == null) { 15067 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15068 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15069 if (sdEncKey == null) { 15070 Slog.e(TAG, "Failed to create encryption keys"); 15071 return null; 15072 } 15073 } 15074 return sdEncKey; 15075 } catch (NoSuchAlgorithmException nsae) { 15076 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15077 return null; 15078 } catch (IOException ioe) { 15079 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15080 return null; 15081 } 15082 } 15083 15084 /* 15085 * Update media status on PackageManager. 15086 */ 15087 @Override 15088 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15089 int callingUid = Binder.getCallingUid(); 15090 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15091 throw new SecurityException("Media status can only be updated by the system"); 15092 } 15093 // reader; this apparently protects mMediaMounted, but should probably 15094 // be a different lock in that case. 15095 synchronized (mPackages) { 15096 Log.i(TAG, "Updating external media status from " 15097 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15098 + (mediaStatus ? "mounted" : "unmounted")); 15099 if (DEBUG_SD_INSTALL) 15100 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15101 + ", mMediaMounted=" + mMediaMounted); 15102 if (mediaStatus == mMediaMounted) { 15103 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15104 : 0, -1); 15105 mHandler.sendMessage(msg); 15106 return; 15107 } 15108 mMediaMounted = mediaStatus; 15109 } 15110 // Queue up an async operation since the package installation may take a 15111 // little while. 15112 mHandler.post(new Runnable() { 15113 public void run() { 15114 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15115 } 15116 }); 15117 } 15118 15119 /** 15120 * Called by MountService when the initial ASECs to scan are available. 15121 * Should block until all the ASEC containers are finished being scanned. 15122 */ 15123 public void scanAvailableAsecs() { 15124 updateExternalMediaStatusInner(true, false, false); 15125 if (mShouldRestoreconData) { 15126 SELinuxMMAC.setRestoreconDone(); 15127 mShouldRestoreconData = false; 15128 } 15129 } 15130 15131 /* 15132 * Collect information of applications on external media, map them against 15133 * existing containers and update information based on current mount status. 15134 * Please note that we always have to report status if reportStatus has been 15135 * set to true especially when unloading packages. 15136 */ 15137 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15138 boolean externalStorage) { 15139 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15140 int[] uidArr = EmptyArray.INT; 15141 15142 final String[] list = PackageHelper.getSecureContainerList(); 15143 if (ArrayUtils.isEmpty(list)) { 15144 Log.i(TAG, "No secure containers found"); 15145 } else { 15146 // Process list of secure containers and categorize them 15147 // as active or stale based on their package internal state. 15148 15149 // reader 15150 synchronized (mPackages) { 15151 for (String cid : list) { 15152 // Leave stages untouched for now; installer service owns them 15153 if (PackageInstallerService.isStageName(cid)) continue; 15154 15155 if (DEBUG_SD_INSTALL) 15156 Log.i(TAG, "Processing container " + cid); 15157 String pkgName = getAsecPackageName(cid); 15158 if (pkgName == null) { 15159 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15160 continue; 15161 } 15162 if (DEBUG_SD_INSTALL) 15163 Log.i(TAG, "Looking for pkg : " + pkgName); 15164 15165 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15166 if (ps == null) { 15167 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15168 continue; 15169 } 15170 15171 /* 15172 * Skip packages that are not external if we're unmounting 15173 * external storage. 15174 */ 15175 if (externalStorage && !isMounted && !isExternal(ps)) { 15176 continue; 15177 } 15178 15179 final AsecInstallArgs args = new AsecInstallArgs(cid, 15180 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15181 // The package status is changed only if the code path 15182 // matches between settings and the container id. 15183 if (ps.codePathString != null 15184 && ps.codePathString.startsWith(args.getCodePath())) { 15185 if (DEBUG_SD_INSTALL) { 15186 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15187 + " at code path: " + ps.codePathString); 15188 } 15189 15190 // We do have a valid package installed on sdcard 15191 processCids.put(args, ps.codePathString); 15192 final int uid = ps.appId; 15193 if (uid != -1) { 15194 uidArr = ArrayUtils.appendInt(uidArr, uid); 15195 } 15196 } else { 15197 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15198 + ps.codePathString); 15199 } 15200 } 15201 } 15202 15203 Arrays.sort(uidArr); 15204 } 15205 15206 // Process packages with valid entries. 15207 if (isMounted) { 15208 if (DEBUG_SD_INSTALL) 15209 Log.i(TAG, "Loading packages"); 15210 loadMediaPackages(processCids, uidArr); 15211 startCleaningPackages(); 15212 mInstallerService.onSecureContainersAvailable(); 15213 } else { 15214 if (DEBUG_SD_INSTALL) 15215 Log.i(TAG, "Unloading packages"); 15216 unloadMediaPackages(processCids, uidArr, reportStatus); 15217 } 15218 } 15219 15220 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15221 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15222 final int size = infos.size(); 15223 final String[] packageNames = new String[size]; 15224 final int[] packageUids = new int[size]; 15225 for (int i = 0; i < size; i++) { 15226 final ApplicationInfo info = infos.get(i); 15227 packageNames[i] = info.packageName; 15228 packageUids[i] = info.uid; 15229 } 15230 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15231 finishedReceiver); 15232 } 15233 15234 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15235 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15236 sendResourcesChangedBroadcast(mediaStatus, replacing, 15237 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15238 } 15239 15240 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15241 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15242 int size = pkgList.length; 15243 if (size > 0) { 15244 // Send broadcasts here 15245 Bundle extras = new Bundle(); 15246 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15247 if (uidArr != null) { 15248 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15249 } 15250 if (replacing) { 15251 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15252 } 15253 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15254 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15255 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15256 } 15257 } 15258 15259 /* 15260 * Look at potentially valid container ids from processCids If package 15261 * information doesn't match the one on record or package scanning fails, 15262 * the cid is added to list of removeCids. We currently don't delete stale 15263 * containers. 15264 */ 15265 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15266 ArrayList<String> pkgList = new ArrayList<String>(); 15267 Set<AsecInstallArgs> keys = processCids.keySet(); 15268 15269 for (AsecInstallArgs args : keys) { 15270 String codePath = processCids.get(args); 15271 if (DEBUG_SD_INSTALL) 15272 Log.i(TAG, "Loading container : " + args.cid); 15273 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15274 try { 15275 // Make sure there are no container errors first. 15276 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15277 Slog.e(TAG, "Failed to mount cid : " + args.cid 15278 + " when installing from sdcard"); 15279 continue; 15280 } 15281 // Check code path here. 15282 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15283 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15284 + " does not match one in settings " + codePath); 15285 continue; 15286 } 15287 // Parse package 15288 int parseFlags = mDefParseFlags; 15289 if (args.isExternalAsec()) { 15290 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15291 } 15292 if (args.isFwdLocked()) { 15293 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15294 } 15295 15296 synchronized (mInstallLock) { 15297 PackageParser.Package pkg = null; 15298 try { 15299 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15300 } catch (PackageManagerException e) { 15301 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15302 } 15303 // Scan the package 15304 if (pkg != null) { 15305 /* 15306 * TODO why is the lock being held? doPostInstall is 15307 * called in other places without the lock. This needs 15308 * to be straightened out. 15309 */ 15310 // writer 15311 synchronized (mPackages) { 15312 retCode = PackageManager.INSTALL_SUCCEEDED; 15313 pkgList.add(pkg.packageName); 15314 // Post process args 15315 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15316 pkg.applicationInfo.uid); 15317 } 15318 } else { 15319 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15320 } 15321 } 15322 15323 } finally { 15324 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15325 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15326 } 15327 } 15328 } 15329 // writer 15330 synchronized (mPackages) { 15331 // If the platform SDK has changed since the last time we booted, 15332 // we need to re-grant app permission to catch any new ones that 15333 // appear. This is really a hack, and means that apps can in some 15334 // cases get permissions that the user didn't initially explicitly 15335 // allow... it would be nice to have some better way to handle 15336 // this situation. 15337 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15338 if (regrantPermissions) 15339 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15340 + mSdkVersion + "; regranting permissions for external storage"); 15341 mSettings.mExternalSdkPlatform = mSdkVersion; 15342 15343 // Make sure group IDs have been assigned, and any permission 15344 // changes in other apps are accounted for 15345 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15346 | (regrantPermissions 15347 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15348 : 0)); 15349 15350 mSettings.updateExternalDatabaseVersion(); 15351 15352 // can downgrade to reader 15353 // Persist settings 15354 mSettings.writeLPr(); 15355 } 15356 // Send a broadcast to let everyone know we are done processing 15357 if (pkgList.size() > 0) { 15358 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15359 } 15360 } 15361 15362 /* 15363 * Utility method to unload a list of specified containers 15364 */ 15365 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15366 // Just unmount all valid containers. 15367 for (AsecInstallArgs arg : cidArgs) { 15368 synchronized (mInstallLock) { 15369 arg.doPostDeleteLI(false); 15370 } 15371 } 15372 } 15373 15374 /* 15375 * Unload packages mounted on external media. This involves deleting package 15376 * data from internal structures, sending broadcasts about diabled packages, 15377 * gc'ing to free up references, unmounting all secure containers 15378 * corresponding to packages on external media, and posting a 15379 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15380 * that we always have to post this message if status has been requested no 15381 * matter what. 15382 */ 15383 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15384 final boolean reportStatus) { 15385 if (DEBUG_SD_INSTALL) 15386 Log.i(TAG, "unloading media packages"); 15387 ArrayList<String> pkgList = new ArrayList<String>(); 15388 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15389 final Set<AsecInstallArgs> keys = processCids.keySet(); 15390 for (AsecInstallArgs args : keys) { 15391 String pkgName = args.getPackageName(); 15392 if (DEBUG_SD_INSTALL) 15393 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15394 // Delete package internally 15395 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15396 synchronized (mInstallLock) { 15397 boolean res = deletePackageLI(pkgName, null, false, null, null, 15398 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15399 if (res) { 15400 pkgList.add(pkgName); 15401 } else { 15402 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15403 failedList.add(args); 15404 } 15405 } 15406 } 15407 15408 // reader 15409 synchronized (mPackages) { 15410 // We didn't update the settings after removing each package; 15411 // write them now for all packages. 15412 mSettings.writeLPr(); 15413 } 15414 15415 // We have to absolutely send UPDATED_MEDIA_STATUS only 15416 // after confirming that all the receivers processed the ordered 15417 // broadcast when packages get disabled, force a gc to clean things up. 15418 // and unload all the containers. 15419 if (pkgList.size() > 0) { 15420 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15421 new IIntentReceiver.Stub() { 15422 public void performReceive(Intent intent, int resultCode, String data, 15423 Bundle extras, boolean ordered, boolean sticky, 15424 int sendingUser) throws RemoteException { 15425 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15426 reportStatus ? 1 : 0, 1, keys); 15427 mHandler.sendMessage(msg); 15428 } 15429 }); 15430 } else { 15431 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15432 keys); 15433 mHandler.sendMessage(msg); 15434 } 15435 } 15436 15437 private void loadPrivatePackages(VolumeInfo vol) { 15438 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15439 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15440 synchronized (mInstallLock) { 15441 synchronized (mPackages) { 15442 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15443 for (PackageSetting ps : packages) { 15444 final PackageParser.Package pkg; 15445 try { 15446 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15447 loaded.add(pkg.applicationInfo); 15448 } catch (PackageManagerException e) { 15449 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15450 } 15451 } 15452 15453 // TODO: regrant any permissions that changed based since original install 15454 15455 mSettings.writeLPr(); 15456 } 15457 } 15458 15459 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15460 sendResourcesChangedBroadcast(true, false, loaded, null); 15461 } 15462 15463 private void unloadPrivatePackages(VolumeInfo vol) { 15464 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15465 synchronized (mInstallLock) { 15466 synchronized (mPackages) { 15467 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15468 for (PackageSetting ps : packages) { 15469 if (ps.pkg == null) continue; 15470 15471 final ApplicationInfo info = ps.pkg.applicationInfo; 15472 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15473 if (deletePackageLI(ps.name, null, false, null, null, 15474 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15475 unloaded.add(info); 15476 } else { 15477 Slog.w(TAG, "Failed to unload " + ps.codePath); 15478 } 15479 } 15480 15481 mSettings.writeLPr(); 15482 } 15483 } 15484 15485 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15486 sendResourcesChangedBroadcast(false, false, unloaded, null); 15487 } 15488 15489 /** 15490 * Examine all users present on given mounted volume, and destroy data 15491 * belonging to users that are no longer valid, or whose user ID has been 15492 * recycled. 15493 */ 15494 private void reconcileUsers(String volumeUuid) { 15495 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15496 if (ArrayUtils.isEmpty(files)) { 15497 Slog.d(TAG, "No users found on " + volumeUuid); 15498 return; 15499 } 15500 15501 for (File file : files) { 15502 if (!file.isDirectory()) continue; 15503 15504 final int userId; 15505 final UserInfo info; 15506 try { 15507 userId = Integer.parseInt(file.getName()); 15508 info = sUserManager.getUserInfo(userId); 15509 } catch (NumberFormatException e) { 15510 Slog.w(TAG, "Invalid user directory " + file); 15511 continue; 15512 } 15513 15514 boolean destroyUser = false; 15515 if (info == null) { 15516 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15517 + " because no matching user was found"); 15518 destroyUser = true; 15519 } else { 15520 try { 15521 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15522 } catch (IOException e) { 15523 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15524 + " because we failed to enforce serial number: " + e); 15525 destroyUser = true; 15526 } 15527 } 15528 15529 if (destroyUser) { 15530 synchronized (mInstallLock) { 15531 mInstaller.removeUserDataDirs(volumeUuid, userId); 15532 } 15533 } 15534 } 15535 15536 final UserManager um = mContext.getSystemService(UserManager.class); 15537 for (UserInfo user : um.getUsers()) { 15538 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15539 if (userDir.exists()) continue; 15540 15541 try { 15542 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15543 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15544 } catch (IOException e) { 15545 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15546 } 15547 } 15548 } 15549 15550 /** 15551 * Examine all apps present on given mounted volume, and destroy apps that 15552 * aren't expected, either due to uninstallation or reinstallation on 15553 * another volume. 15554 */ 15555 private void reconcileApps(String volumeUuid) { 15556 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15557 if (ArrayUtils.isEmpty(files)) { 15558 Slog.d(TAG, "No apps found on " + volumeUuid); 15559 return; 15560 } 15561 15562 for (File file : files) { 15563 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15564 && !PackageInstallerService.isStageName(file.getName()); 15565 if (!isPackage) { 15566 // Ignore entries which are not packages 15567 continue; 15568 } 15569 15570 boolean destroyApp = false; 15571 String packageName = null; 15572 try { 15573 final PackageLite pkg = PackageParser.parsePackageLite(file, 15574 PackageParser.PARSE_MUST_BE_APK); 15575 packageName = pkg.packageName; 15576 15577 synchronized (mPackages) { 15578 final PackageSetting ps = mSettings.mPackages.get(packageName); 15579 if (ps == null) { 15580 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15581 + volumeUuid + " because we found no install record"); 15582 destroyApp = true; 15583 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15584 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15585 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15586 destroyApp = true; 15587 } 15588 } 15589 15590 } catch (PackageParserException e) { 15591 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15592 destroyApp = true; 15593 } 15594 15595 if (destroyApp) { 15596 synchronized (mInstallLock) { 15597 if (packageName != null) { 15598 removeDataDirsLI(volumeUuid, packageName); 15599 } 15600 if (file.isDirectory()) { 15601 mInstaller.rmPackageDir(file.getAbsolutePath()); 15602 } else { 15603 file.delete(); 15604 } 15605 } 15606 } 15607 } 15608 } 15609 15610 private void unfreezePackage(String packageName) { 15611 synchronized (mPackages) { 15612 final PackageSetting ps = mSettings.mPackages.get(packageName); 15613 if (ps != null) { 15614 ps.frozen = false; 15615 } 15616 } 15617 } 15618 15619 @Override 15620 public int movePackage(final String packageName, final String volumeUuid) { 15621 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15622 15623 final int moveId = mNextMoveId.getAndIncrement(); 15624 try { 15625 movePackageInternal(packageName, volumeUuid, moveId); 15626 } catch (PackageManagerException e) { 15627 Slog.w(TAG, "Failed to move " + packageName, e); 15628 mMoveCallbacks.notifyStatusChanged(moveId, 15629 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15630 } 15631 return moveId; 15632 } 15633 15634 private void movePackageInternal(final String packageName, final String volumeUuid, 15635 final int moveId) throws PackageManagerException { 15636 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15637 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15638 final PackageManager pm = mContext.getPackageManager(); 15639 15640 final boolean currentAsec; 15641 final String currentVolumeUuid; 15642 final File codeFile; 15643 final String installerPackageName; 15644 final String packageAbiOverride; 15645 final int appId; 15646 final String seinfo; 15647 final String label; 15648 15649 // reader 15650 synchronized (mPackages) { 15651 final PackageParser.Package pkg = mPackages.get(packageName); 15652 final PackageSetting ps = mSettings.mPackages.get(packageName); 15653 if (pkg == null || ps == null) { 15654 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15655 } 15656 15657 if (pkg.applicationInfo.isSystemApp()) { 15658 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15659 "Cannot move system application"); 15660 } 15661 15662 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15663 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15664 "Package already moved to " + volumeUuid); 15665 } 15666 15667 final File probe = new File(pkg.codePath); 15668 final File probeOat = new File(probe, "oat"); 15669 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15670 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15671 "Move only supported for modern cluster style installs"); 15672 } 15673 15674 if (ps.frozen) { 15675 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15676 "Failed to move already frozen package"); 15677 } 15678 ps.frozen = true; 15679 15680 currentAsec = pkg.applicationInfo.isForwardLocked() 15681 || pkg.applicationInfo.isExternalAsec(); 15682 currentVolumeUuid = ps.volumeUuid; 15683 codeFile = new File(pkg.codePath); 15684 installerPackageName = ps.installerPackageName; 15685 packageAbiOverride = ps.cpuAbiOverrideString; 15686 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15687 seinfo = pkg.applicationInfo.seinfo; 15688 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15689 } 15690 15691 // Now that we're guarded by frozen state, kill app during move 15692 killApplication(packageName, appId, "move pkg"); 15693 15694 final Bundle extras = new Bundle(); 15695 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15696 extras.putString(Intent.EXTRA_TITLE, label); 15697 mMoveCallbacks.notifyCreated(moveId, extras); 15698 15699 int installFlags; 15700 final boolean moveCompleteApp; 15701 final File measurePath; 15702 15703 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15704 installFlags = INSTALL_INTERNAL; 15705 moveCompleteApp = !currentAsec; 15706 measurePath = Environment.getDataAppDirectory(volumeUuid); 15707 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15708 installFlags = INSTALL_EXTERNAL; 15709 moveCompleteApp = false; 15710 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15711 } else { 15712 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15713 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15714 || !volume.isMountedWritable()) { 15715 unfreezePackage(packageName); 15716 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15717 "Move location not mounted private volume"); 15718 } 15719 15720 Preconditions.checkState(!currentAsec); 15721 15722 installFlags = INSTALL_INTERNAL; 15723 moveCompleteApp = true; 15724 measurePath = Environment.getDataAppDirectory(volumeUuid); 15725 } 15726 15727 final PackageStats stats = new PackageStats(null, -1); 15728 synchronized (mInstaller) { 15729 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15730 unfreezePackage(packageName); 15731 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15732 "Failed to measure package size"); 15733 } 15734 } 15735 15736 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15737 + stats.dataSize); 15738 15739 final long startFreeBytes = measurePath.getFreeSpace(); 15740 final long sizeBytes; 15741 if (moveCompleteApp) { 15742 sizeBytes = stats.codeSize + stats.dataSize; 15743 } else { 15744 sizeBytes = stats.codeSize; 15745 } 15746 15747 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15748 unfreezePackage(packageName); 15749 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15750 "Not enough free space to move"); 15751 } 15752 15753 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15754 15755 final CountDownLatch installedLatch = new CountDownLatch(1); 15756 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15757 @Override 15758 public void onUserActionRequired(Intent intent) throws RemoteException { 15759 throw new IllegalStateException(); 15760 } 15761 15762 @Override 15763 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15764 Bundle extras) throws RemoteException { 15765 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15766 + PackageManager.installStatusToString(returnCode, msg)); 15767 15768 installedLatch.countDown(); 15769 15770 // Regardless of success or failure of the move operation, 15771 // always unfreeze the package 15772 unfreezePackage(packageName); 15773 15774 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15775 switch (status) { 15776 case PackageInstaller.STATUS_SUCCESS: 15777 mMoveCallbacks.notifyStatusChanged(moveId, 15778 PackageManager.MOVE_SUCCEEDED); 15779 break; 15780 case PackageInstaller.STATUS_FAILURE_STORAGE: 15781 mMoveCallbacks.notifyStatusChanged(moveId, 15782 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15783 break; 15784 default: 15785 mMoveCallbacks.notifyStatusChanged(moveId, 15786 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15787 break; 15788 } 15789 } 15790 }; 15791 15792 final MoveInfo move; 15793 if (moveCompleteApp) { 15794 // Kick off a thread to report progress estimates 15795 new Thread() { 15796 @Override 15797 public void run() { 15798 while (true) { 15799 try { 15800 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15801 break; 15802 } 15803 } catch (InterruptedException ignored) { 15804 } 15805 15806 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15807 final int progress = 10 + (int) MathUtils.constrain( 15808 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15809 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15810 } 15811 } 15812 }.start(); 15813 15814 final String dataAppName = codeFile.getName(); 15815 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15816 dataAppName, appId, seinfo); 15817 } else { 15818 move = null; 15819 } 15820 15821 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15822 15823 final Message msg = mHandler.obtainMessage(INIT_COPY); 15824 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15825 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15826 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15827 mHandler.sendMessage(msg); 15828 } 15829 15830 @Override 15831 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15832 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15833 15834 final int realMoveId = mNextMoveId.getAndIncrement(); 15835 final Bundle extras = new Bundle(); 15836 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15837 mMoveCallbacks.notifyCreated(realMoveId, extras); 15838 15839 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15840 @Override 15841 public void onCreated(int moveId, Bundle extras) { 15842 // Ignored 15843 } 15844 15845 @Override 15846 public void onStatusChanged(int moveId, int status, long estMillis) { 15847 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15848 } 15849 }; 15850 15851 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15852 storage.setPrimaryStorageUuid(volumeUuid, callback); 15853 return realMoveId; 15854 } 15855 15856 @Override 15857 public int getMoveStatus(int moveId) { 15858 mContext.enforceCallingOrSelfPermission( 15859 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15860 return mMoveCallbacks.mLastStatus.get(moveId); 15861 } 15862 15863 @Override 15864 public void registerMoveCallback(IPackageMoveObserver callback) { 15865 mContext.enforceCallingOrSelfPermission( 15866 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15867 mMoveCallbacks.register(callback); 15868 } 15869 15870 @Override 15871 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15872 mContext.enforceCallingOrSelfPermission( 15873 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15874 mMoveCallbacks.unregister(callback); 15875 } 15876 15877 @Override 15878 public boolean setInstallLocation(int loc) { 15879 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15880 null); 15881 if (getInstallLocation() == loc) { 15882 return true; 15883 } 15884 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15885 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15886 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15887 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15888 return true; 15889 } 15890 return false; 15891 } 15892 15893 @Override 15894 public int getInstallLocation() { 15895 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15896 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15897 PackageHelper.APP_INSTALL_AUTO); 15898 } 15899 15900 /** Called by UserManagerService */ 15901 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15902 mDirtyUsers.remove(userHandle); 15903 mSettings.removeUserLPw(userHandle); 15904 mPendingBroadcasts.remove(userHandle); 15905 if (mInstaller != null) { 15906 // Technically, we shouldn't be doing this with the package lock 15907 // held. However, this is very rare, and there is already so much 15908 // other disk I/O going on, that we'll let it slide for now. 15909 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15910 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15911 final String volumeUuid = vol.getFsUuid(); 15912 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15913 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15914 } 15915 } 15916 mUserNeedsBadging.delete(userHandle); 15917 removeUnusedPackagesLILPw(userManager, userHandle); 15918 } 15919 15920 /** 15921 * We're removing userHandle and would like to remove any downloaded packages 15922 * that are no longer in use by any other user. 15923 * @param userHandle the user being removed 15924 */ 15925 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15926 final boolean DEBUG_CLEAN_APKS = false; 15927 int [] users = userManager.getUserIdsLPr(); 15928 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15929 while (psit.hasNext()) { 15930 PackageSetting ps = psit.next(); 15931 if (ps.pkg == null) { 15932 continue; 15933 } 15934 final String packageName = ps.pkg.packageName; 15935 // Skip over if system app 15936 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15937 continue; 15938 } 15939 if (DEBUG_CLEAN_APKS) { 15940 Slog.i(TAG, "Checking package " + packageName); 15941 } 15942 boolean keep = false; 15943 for (int i = 0; i < users.length; i++) { 15944 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15945 keep = true; 15946 if (DEBUG_CLEAN_APKS) { 15947 Slog.i(TAG, " Keeping package " + packageName + " for user " 15948 + users[i]); 15949 } 15950 break; 15951 } 15952 } 15953 if (!keep) { 15954 if (DEBUG_CLEAN_APKS) { 15955 Slog.i(TAG, " Removing package " + packageName); 15956 } 15957 mHandler.post(new Runnable() { 15958 public void run() { 15959 deletePackageX(packageName, userHandle, 0); 15960 } //end run 15961 }); 15962 } 15963 } 15964 } 15965 15966 /** Called by UserManagerService */ 15967 void createNewUserLILPw(int userHandle) { 15968 if (mInstaller != null) { 15969 mInstaller.createUserConfig(userHandle); 15970 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15971 applyFactoryDefaultBrowserLPw(userHandle); 15972 primeDomainVerificationsLPw(userHandle); 15973 } 15974 } 15975 15976 void newUserCreated(final int userHandle) { 15977 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15978 } 15979 15980 @Override 15981 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15982 mContext.enforceCallingOrSelfPermission( 15983 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15984 "Only package verification agents can read the verifier device identity"); 15985 15986 synchronized (mPackages) { 15987 return mSettings.getVerifierDeviceIdentityLPw(); 15988 } 15989 } 15990 15991 @Override 15992 public void setPermissionEnforced(String permission, boolean enforced) { 15993 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15994 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15995 synchronized (mPackages) { 15996 if (mSettings.mReadExternalStorageEnforced == null 15997 || mSettings.mReadExternalStorageEnforced != enforced) { 15998 mSettings.mReadExternalStorageEnforced = enforced; 15999 mSettings.writeLPr(); 16000 } 16001 } 16002 // kill any non-foreground processes so we restart them and 16003 // grant/revoke the GID. 16004 final IActivityManager am = ActivityManagerNative.getDefault(); 16005 if (am != null) { 16006 final long token = Binder.clearCallingIdentity(); 16007 try { 16008 am.killProcessesBelowForeground("setPermissionEnforcement"); 16009 } catch (RemoteException e) { 16010 } finally { 16011 Binder.restoreCallingIdentity(token); 16012 } 16013 } 16014 } else { 16015 throw new IllegalArgumentException("No selective enforcement for " + permission); 16016 } 16017 } 16018 16019 @Override 16020 @Deprecated 16021 public boolean isPermissionEnforced(String permission) { 16022 return true; 16023 } 16024 16025 @Override 16026 public boolean isStorageLow() { 16027 final long token = Binder.clearCallingIdentity(); 16028 try { 16029 final DeviceStorageMonitorInternal 16030 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16031 if (dsm != null) { 16032 return dsm.isMemoryLow(); 16033 } else { 16034 return false; 16035 } 16036 } finally { 16037 Binder.restoreCallingIdentity(token); 16038 } 16039 } 16040 16041 @Override 16042 public IPackageInstaller getPackageInstaller() { 16043 return mInstallerService; 16044 } 16045 16046 private boolean userNeedsBadging(int userId) { 16047 int index = mUserNeedsBadging.indexOfKey(userId); 16048 if (index < 0) { 16049 final UserInfo userInfo; 16050 final long token = Binder.clearCallingIdentity(); 16051 try { 16052 userInfo = sUserManager.getUserInfo(userId); 16053 } finally { 16054 Binder.restoreCallingIdentity(token); 16055 } 16056 final boolean b; 16057 if (userInfo != null && userInfo.isManagedProfile()) { 16058 b = true; 16059 } else { 16060 b = false; 16061 } 16062 mUserNeedsBadging.put(userId, b); 16063 return b; 16064 } 16065 return mUserNeedsBadging.valueAt(index); 16066 } 16067 16068 @Override 16069 public KeySet getKeySetByAlias(String packageName, String alias) { 16070 if (packageName == null || alias == null) { 16071 return null; 16072 } 16073 synchronized(mPackages) { 16074 final PackageParser.Package pkg = mPackages.get(packageName); 16075 if (pkg == null) { 16076 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16077 throw new IllegalArgumentException("Unknown package: " + packageName); 16078 } 16079 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16080 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16081 } 16082 } 16083 16084 @Override 16085 public KeySet getSigningKeySet(String packageName) { 16086 if (packageName == null) { 16087 return null; 16088 } 16089 synchronized(mPackages) { 16090 final PackageParser.Package pkg = mPackages.get(packageName); 16091 if (pkg == null) { 16092 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16093 throw new IllegalArgumentException("Unknown package: " + packageName); 16094 } 16095 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16096 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16097 throw new SecurityException("May not access signing KeySet of other apps."); 16098 } 16099 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16100 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16101 } 16102 } 16103 16104 @Override 16105 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16106 if (packageName == null || ks == null) { 16107 return false; 16108 } 16109 synchronized(mPackages) { 16110 final PackageParser.Package pkg = mPackages.get(packageName); 16111 if (pkg == null) { 16112 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16113 throw new IllegalArgumentException("Unknown package: " + packageName); 16114 } 16115 IBinder ksh = ks.getToken(); 16116 if (ksh instanceof KeySetHandle) { 16117 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16118 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16119 } 16120 return false; 16121 } 16122 } 16123 16124 @Override 16125 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16126 if (packageName == null || ks == null) { 16127 return false; 16128 } 16129 synchronized(mPackages) { 16130 final PackageParser.Package pkg = mPackages.get(packageName); 16131 if (pkg == null) { 16132 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16133 throw new IllegalArgumentException("Unknown package: " + packageName); 16134 } 16135 IBinder ksh = ks.getToken(); 16136 if (ksh instanceof KeySetHandle) { 16137 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16138 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16139 } 16140 return false; 16141 } 16142 } 16143 16144 public void getUsageStatsIfNoPackageUsageInfo() { 16145 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16146 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16147 if (usm == null) { 16148 throw new IllegalStateException("UsageStatsManager must be initialized"); 16149 } 16150 long now = System.currentTimeMillis(); 16151 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16152 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16153 String packageName = entry.getKey(); 16154 PackageParser.Package pkg = mPackages.get(packageName); 16155 if (pkg == null) { 16156 continue; 16157 } 16158 UsageStats usage = entry.getValue(); 16159 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16160 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16161 } 16162 } 16163 } 16164 16165 /** 16166 * Check and throw if the given before/after packages would be considered a 16167 * downgrade. 16168 */ 16169 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16170 throws PackageManagerException { 16171 if (after.versionCode < before.mVersionCode) { 16172 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16173 "Update version code " + after.versionCode + " is older than current " 16174 + before.mVersionCode); 16175 } else if (after.versionCode == before.mVersionCode) { 16176 if (after.baseRevisionCode < before.baseRevisionCode) { 16177 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16178 "Update base revision code " + after.baseRevisionCode 16179 + " is older than current " + before.baseRevisionCode); 16180 } 16181 16182 if (!ArrayUtils.isEmpty(after.splitNames)) { 16183 for (int i = 0; i < after.splitNames.length; i++) { 16184 final String splitName = after.splitNames[i]; 16185 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16186 if (j != -1) { 16187 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16188 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16189 "Update split " + splitName + " revision code " 16190 + after.splitRevisionCodes[i] + " is older than current " 16191 + before.splitRevisionCodes[j]); 16192 } 16193 } 16194 } 16195 } 16196 } 16197 } 16198 16199 private static class MoveCallbacks extends Handler { 16200 private static final int MSG_CREATED = 1; 16201 private static final int MSG_STATUS_CHANGED = 2; 16202 16203 private final RemoteCallbackList<IPackageMoveObserver> 16204 mCallbacks = new RemoteCallbackList<>(); 16205 16206 private final SparseIntArray mLastStatus = new SparseIntArray(); 16207 16208 public MoveCallbacks(Looper looper) { 16209 super(looper); 16210 } 16211 16212 public void register(IPackageMoveObserver callback) { 16213 mCallbacks.register(callback); 16214 } 16215 16216 public void unregister(IPackageMoveObserver callback) { 16217 mCallbacks.unregister(callback); 16218 } 16219 16220 @Override 16221 public void handleMessage(Message msg) { 16222 final SomeArgs args = (SomeArgs) msg.obj; 16223 final int n = mCallbacks.beginBroadcast(); 16224 for (int i = 0; i < n; i++) { 16225 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16226 try { 16227 invokeCallback(callback, msg.what, args); 16228 } catch (RemoteException ignored) { 16229 } 16230 } 16231 mCallbacks.finishBroadcast(); 16232 args.recycle(); 16233 } 16234 16235 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16236 throws RemoteException { 16237 switch (what) { 16238 case MSG_CREATED: { 16239 callback.onCreated(args.argi1, (Bundle) args.arg2); 16240 break; 16241 } 16242 case MSG_STATUS_CHANGED: { 16243 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16244 break; 16245 } 16246 } 16247 } 16248 16249 private void notifyCreated(int moveId, Bundle extras) { 16250 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16251 16252 final SomeArgs args = SomeArgs.obtain(); 16253 args.argi1 = moveId; 16254 args.arg2 = extras; 16255 obtainMessage(MSG_CREATED, args).sendToTarget(); 16256 } 16257 16258 private void notifyStatusChanged(int moveId, int status) { 16259 notifyStatusChanged(moveId, status, -1); 16260 } 16261 16262 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16263 Slog.v(TAG, "Move " + moveId + " status " + status); 16264 16265 final SomeArgs args = SomeArgs.obtain(); 16266 args.argi1 = moveId; 16267 args.argi2 = status; 16268 args.arg3 = estMillis; 16269 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16270 16271 synchronized (mLastStatus) { 16272 mLastStatus.put(moveId, status); 16273 } 16274 } 16275 } 16276 16277 private final class OnPermissionChangeListeners extends Handler { 16278 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16279 16280 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16281 new RemoteCallbackList<>(); 16282 16283 public OnPermissionChangeListeners(Looper looper) { 16284 super(looper); 16285 } 16286 16287 @Override 16288 public void handleMessage(Message msg) { 16289 switch (msg.what) { 16290 case MSG_ON_PERMISSIONS_CHANGED: { 16291 final int uid = msg.arg1; 16292 handleOnPermissionsChanged(uid); 16293 } break; 16294 } 16295 } 16296 16297 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16298 mPermissionListeners.register(listener); 16299 16300 } 16301 16302 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16303 mPermissionListeners.unregister(listener); 16304 } 16305 16306 public void onPermissionsChanged(int uid) { 16307 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16308 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16309 } 16310 } 16311 16312 private void handleOnPermissionsChanged(int uid) { 16313 final int count = mPermissionListeners.beginBroadcast(); 16314 try { 16315 for (int i = 0; i < count; i++) { 16316 IOnPermissionsChangeListener callback = mPermissionListeners 16317 .getBroadcastItem(i); 16318 try { 16319 callback.onPermissionsChanged(uid); 16320 } catch (RemoteException e) { 16321 Log.e(TAG, "Permission listener is dead", e); 16322 } 16323 } 16324 } finally { 16325 mPermissionListeners.finishBroadcast(); 16326 } 16327 } 16328 } 16329 16330 private class PackageManagerInternalImpl extends PackageManagerInternal { 16331 @Override 16332 public void setLocationPackagesProvider(PackagesProvider provider) { 16333 synchronized (mPackages) { 16334 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16335 } 16336 } 16337 16338 @Override 16339 public void setImePackagesProvider(PackagesProvider provider) { 16340 synchronized (mPackages) { 16341 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16342 } 16343 } 16344 16345 @Override 16346 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16347 synchronized (mPackages) { 16348 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16349 } 16350 } 16351 16352 @Override 16353 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16354 synchronized (mPackages) { 16355 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16356 } 16357 } 16358 16359 @Override 16360 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16361 synchronized (mPackages) { 16362 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16363 } 16364 } 16365 16366 @Override 16367 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16368 synchronized (mPackages) { 16369 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16370 } 16371 } 16372 16373 @Override 16374 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16375 synchronized (mPackages) { 16376 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16377 packageName, userId); 16378 } 16379 } 16380 16381 @Override 16382 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16383 synchronized (mPackages) { 16384 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16385 packageName, userId); 16386 } 16387 } 16388 } 16389 16390 @Override 16391 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16392 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16393 synchronized (mPackages) { 16394 final long identity = Binder.clearCallingIdentity(); 16395 try { 16396 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16397 packageNames, userId); 16398 } finally { 16399 Binder.restoreCallingIdentity(identity); 16400 } 16401 } 16402 } 16403 16404 private static void enforceSystemOrPhoneCaller(String tag) { 16405 int callingUid = Binder.getCallingUid(); 16406 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16407 throw new SecurityException( 16408 "Cannot call " + tag + " from UID " + callingUid); 16409 } 16410 } 16411} 16412