PackageManagerService.java revision 16b43e43f973896baa14961c4805979eeb310654
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 71import static android.system.OsConstants.O_CREAT; 72import static android.system.OsConstants.O_RDWR; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 77import static com.android.internal.util.ArrayUtils.appendInt; 78import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 81import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 82import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 86 87import android.Manifest; 88import android.app.ActivityManager; 89import android.app.ActivityManagerNative; 90import android.app.AppGlobals; 91import android.app.IActivityManager; 92import android.app.admin.IDevicePolicyManager; 93import android.app.backup.IBackupManager; 94import android.app.usage.UsageStats; 95import android.app.usage.UsageStatsManager; 96import android.content.BroadcastReceiver; 97import android.content.ComponentName; 98import android.content.Context; 99import android.content.IIntentReceiver; 100import android.content.Intent; 101import android.content.IntentFilter; 102import android.content.IntentSender; 103import android.content.IntentSender.SendIntentException; 104import android.content.ServiceConnection; 105import android.content.pm.ActivityInfo; 106import android.content.pm.ApplicationInfo; 107import android.content.pm.FeatureInfo; 108import android.content.pm.IOnPermissionsChangeListener; 109import android.content.pm.IPackageDataObserver; 110import android.content.pm.IPackageDeleteObserver; 111import android.content.pm.IPackageDeleteObserver2; 112import android.content.pm.IPackageInstallObserver2; 113import android.content.pm.IPackageInstaller; 114import android.content.pm.IPackageManager; 115import android.content.pm.IPackageMoveObserver; 116import android.content.pm.IPackageStatsObserver; 117import android.content.pm.InstrumentationInfo; 118import android.content.pm.IntentFilterVerificationInfo; 119import android.content.pm.KeySet; 120import android.content.pm.ManifestDigest; 121import android.content.pm.PackageCleanItem; 122import android.content.pm.PackageInfo; 123import android.content.pm.PackageInfoLite; 124import android.content.pm.PackageInstaller; 125import android.content.pm.PackageManager; 126import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 127import android.content.pm.PackageManagerInternal; 128import android.content.pm.PackageParser; 129import android.content.pm.PackageParser.ActivityIntentInfo; 130import android.content.pm.PackageParser.PackageLite; 131import android.content.pm.PackageParser.PackageParserException; 132import android.content.pm.PackageStats; 133import android.content.pm.PackageUserState; 134import android.content.pm.ParceledListSlice; 135import android.content.pm.PermissionGroupInfo; 136import android.content.pm.PermissionInfo; 137import android.content.pm.ProviderInfo; 138import android.content.pm.ResolveInfo; 139import android.content.pm.ServiceInfo; 140import android.content.pm.Signature; 141import android.content.pm.UserInfo; 142import android.content.pm.VerificationParams; 143import android.content.pm.VerifierDeviceIdentity; 144import android.content.pm.VerifierInfo; 145import android.content.res.Resources; 146import android.hardware.display.DisplayManager; 147import android.net.Uri; 148import android.os.Debug; 149import android.os.Binder; 150import android.os.Build; 151import android.os.Bundle; 152import android.os.Environment; 153import android.os.Environment.UserEnvironment; 154import android.os.FileUtils; 155import android.os.Handler; 156import android.os.IBinder; 157import android.os.Looper; 158import android.os.Message; 159import android.os.Parcel; 160import android.os.ParcelFileDescriptor; 161import android.os.Process; 162import android.os.RemoteCallbackList; 163import android.os.RemoteException; 164import android.os.SELinux; 165import android.os.ServiceManager; 166import android.os.SystemClock; 167import android.os.SystemProperties; 168import android.os.Trace; 169import android.os.UserHandle; 170import android.os.UserManager; 171import android.os.storage.IMountService; 172import android.os.storage.MountServiceInternal; 173import android.os.storage.StorageEventListener; 174import android.os.storage.StorageManager; 175import android.os.storage.VolumeInfo; 176import android.os.storage.VolumeRecord; 177import android.security.KeyStore; 178import android.security.SystemKeyStore; 179import android.system.ErrnoException; 180import android.system.Os; 181import android.system.StructStat; 182import android.text.TextUtils; 183import android.text.format.DateUtils; 184import android.util.ArrayMap; 185import android.util.ArraySet; 186import android.util.AtomicFile; 187import android.util.DisplayMetrics; 188import android.util.EventLog; 189import android.util.ExceptionUtils; 190import android.util.Log; 191import android.util.LogPrinter; 192import android.util.MathUtils; 193import android.util.PrintStreamPrinter; 194import android.util.Slog; 195import android.util.SparseArray; 196import android.util.SparseBooleanArray; 197import android.util.SparseIntArray; 198import android.util.Xml; 199import android.view.Display; 200 201import dalvik.system.DexFile; 202import dalvik.system.VMRuntime; 203 204import libcore.io.IoUtils; 205import libcore.util.EmptyArray; 206 207import com.android.internal.R; 208import com.android.internal.annotations.GuardedBy; 209import com.android.internal.app.IMediaContainerService; 210import com.android.internal.app.ResolverActivity; 211import com.android.internal.content.NativeLibraryHelper; 212import com.android.internal.content.PackageHelper; 213import com.android.internal.os.IParcelFileDescriptorFactory; 214import com.android.internal.os.SomeArgs; 215import com.android.internal.os.Zygote; 216import com.android.internal.util.ArrayUtils; 217import com.android.internal.util.FastPrintWriter; 218import com.android.internal.util.FastXmlSerializer; 219import com.android.internal.util.IndentingPrintWriter; 220import com.android.internal.util.Preconditions; 221import com.android.server.EventLogTags; 222import com.android.server.FgThread; 223import com.android.server.IntentResolver; 224import com.android.server.LocalServices; 225import com.android.server.ServiceThread; 226import com.android.server.SystemConfig; 227import com.android.server.Watchdog; 228import com.android.server.pm.PermissionsState.PermissionState; 229import com.android.server.pm.Settings.DatabaseVersion; 230import com.android.server.pm.Settings.VersionInfo; 231import com.android.server.storage.DeviceStorageMonitorInternal; 232 233import org.xmlpull.v1.XmlPullParser; 234import org.xmlpull.v1.XmlPullParserException; 235import org.xmlpull.v1.XmlSerializer; 236 237import java.io.BufferedInputStream; 238import java.io.BufferedOutputStream; 239import java.io.BufferedReader; 240import java.io.ByteArrayInputStream; 241import java.io.ByteArrayOutputStream; 242import java.io.File; 243import java.io.FileDescriptor; 244import java.io.FileNotFoundException; 245import java.io.FileOutputStream; 246import java.io.FileReader; 247import java.io.FilenameFilter; 248import java.io.IOException; 249import java.io.InputStream; 250import java.io.PrintWriter; 251import java.nio.charset.StandardCharsets; 252import java.security.NoSuchAlgorithmException; 253import java.security.PublicKey; 254import java.security.cert.CertificateEncodingException; 255import java.security.cert.CertificateException; 256import java.text.SimpleDateFormat; 257import java.util.ArrayList; 258import java.util.Arrays; 259import java.util.Collection; 260import java.util.Collections; 261import java.util.Comparator; 262import java.util.Date; 263import java.util.Iterator; 264import java.util.List; 265import java.util.Map; 266import java.util.Objects; 267import java.util.Set; 268import java.util.concurrent.CountDownLatch; 269import java.util.concurrent.TimeUnit; 270import java.util.concurrent.atomic.AtomicBoolean; 271import java.util.concurrent.atomic.AtomicInteger; 272import java.util.concurrent.atomic.AtomicLong; 273 274/** 275 * Keep track of all those .apks everywhere. 276 * 277 * This is very central to the platform's security; please run the unit 278 * tests whenever making modifications here: 279 * 280runtest -c android.content.pm.PackageManagerTests frameworks-core 281 * 282 * {@hide} 283 */ 284public class PackageManagerService extends IPackageManager.Stub { 285 static final String TAG = "PackageManager"; 286 static final boolean DEBUG_SETTINGS = false; 287 static final boolean DEBUG_PREFERRED = false; 288 static final boolean DEBUG_UPGRADE = false; 289 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 290 private static final boolean DEBUG_BACKUP = false; 291 private static final boolean DEBUG_INSTALL = false; 292 private static final boolean DEBUG_REMOVE = false; 293 private static final boolean DEBUG_BROADCASTS = false; 294 private static final boolean DEBUG_SHOW_INFO = false; 295 private static final boolean DEBUG_PACKAGE_INFO = false; 296 private static final boolean DEBUG_INTENT_MATCHING = false; 297 private static final boolean DEBUG_PACKAGE_SCANNING = false; 298 private static final boolean DEBUG_VERIFY = false; 299 private static final boolean DEBUG_DEXOPT = false; 300 private static final boolean DEBUG_ABI_SELECTION = false; 301 302 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 303 304 private static final int RADIO_UID = Process.PHONE_UID; 305 private static final int LOG_UID = Process.LOG_UID; 306 private static final int NFC_UID = Process.NFC_UID; 307 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 308 private static final int SHELL_UID = Process.SHELL_UID; 309 310 // Cap the size of permission trees that 3rd party apps can define 311 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 312 313 // Suffix used during package installation when copying/moving 314 // package apks to install directory. 315 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 316 317 static final int SCAN_NO_DEX = 1<<1; 318 static final int SCAN_FORCE_DEX = 1<<2; 319 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 320 static final int SCAN_NEW_INSTALL = 1<<4; 321 static final int SCAN_NO_PATHS = 1<<5; 322 static final int SCAN_UPDATE_TIME = 1<<6; 323 static final int SCAN_DEFER_DEX = 1<<7; 324 static final int SCAN_BOOTING = 1<<8; 325 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 326 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 327 static final int SCAN_REPLACING = 1<<11; 328 static final int SCAN_REQUIRE_KNOWN = 1<<12; 329 static final int SCAN_MOVE = 1<<13; 330 static final int SCAN_INITIAL = 1<<14; 331 332 static final int REMOVE_CHATTY = 1<<16; 333 334 private static final int[] EMPTY_INT_ARRAY = new int[0]; 335 336 /** 337 * Timeout (in milliseconds) after which the watchdog should declare that 338 * our handler thread is wedged. The usual default for such things is one 339 * minute but we sometimes do very lengthy I/O operations on this thread, 340 * such as installing multi-gigabyte applications, so ours needs to be longer. 341 */ 342 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 343 344 /** 345 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 346 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 347 * settings entry if available, otherwise we use the hardcoded default. If it's been 348 * more than this long since the last fstrim, we force one during the boot sequence. 349 * 350 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 351 * one gets run at the next available charging+idle time. This final mandatory 352 * no-fstrim check kicks in only of the other scheduling criteria is never met. 353 */ 354 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 355 356 /** 357 * Whether verification is enabled by default. 358 */ 359 private static final boolean DEFAULT_VERIFY_ENABLE = true; 360 361 /** 362 * The default maximum time to wait for the verification agent to return in 363 * milliseconds. 364 */ 365 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 366 367 /** 368 * The default response for package verification timeout. 369 * 370 * This can be either PackageManager.VERIFICATION_ALLOW or 371 * PackageManager.VERIFICATION_REJECT. 372 */ 373 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 374 375 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 376 377 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 378 DEFAULT_CONTAINER_PACKAGE, 379 "com.android.defcontainer.DefaultContainerService"); 380 381 private static final String KILL_APP_REASON_GIDS_CHANGED = 382 "permission grant or revoke changed gids"; 383 384 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 385 "permissions revoked"; 386 387 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 388 389 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 390 391 /** Permission grant: not grant the permission. */ 392 private static final int GRANT_DENIED = 1; 393 394 /** Permission grant: grant the permission as an install permission. */ 395 private static final int GRANT_INSTALL = 2; 396 397 /** Permission grant: grant the permission as an install permission for a legacy app. */ 398 private static final int GRANT_INSTALL_LEGACY = 3; 399 400 /** Permission grant: grant the permission as a runtime one. */ 401 private static final int GRANT_RUNTIME = 4; 402 403 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 404 private static final int GRANT_UPGRADE = 5; 405 406 /** Canonical intent used to identify what counts as a "web browser" app */ 407 private static final Intent sBrowserIntent; 408 static { 409 sBrowserIntent = new Intent(); 410 sBrowserIntent.setAction(Intent.ACTION_VIEW); 411 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 412 sBrowserIntent.setData(Uri.parse("http:")); 413 } 414 415 final ServiceThread mHandlerThread; 416 417 final PackageHandler mHandler; 418 419 /** 420 * Messages for {@link #mHandler} that need to wait for system ready before 421 * being dispatched. 422 */ 423 private ArrayList<Message> mPostSystemReadyMessages; 424 425 final int mSdkVersion = Build.VERSION.SDK_INT; 426 427 final Context mContext; 428 final boolean mFactoryTest; 429 final boolean mOnlyCore; 430 final boolean mLazyDexOpt; 431 final long mDexOptLRUThresholdInMills; 432 final DisplayMetrics mMetrics; 433 final int mDefParseFlags; 434 final String[] mSeparateProcesses; 435 final boolean mIsUpgrade; 436 437 // This is where all application persistent data goes. 438 final File mAppDataDir; 439 440 // This is where all application persistent data goes for secondary users. 441 final File mUserAppDataDir; 442 443 /** The location for ASEC container files on internal storage. */ 444 final String mAsecInternalPath; 445 446 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 447 // LOCK HELD. Can be called with mInstallLock held. 448 @GuardedBy("mInstallLock") 449 final Installer mInstaller; 450 451 /** Directory where installed third-party apps stored */ 452 final File mAppInstallDir; 453 454 /** 455 * Directory to which applications installed internally have their 456 * 32 bit native libraries copied. 457 */ 458 private File mAppLib32InstallDir; 459 460 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 461 // apps. 462 final File mDrmAppPrivateInstallDir; 463 464 // ---------------------------------------------------------------- 465 466 // Lock for state used when installing and doing other long running 467 // operations. Methods that must be called with this lock held have 468 // the suffix "LI". 469 final Object mInstallLock = new Object(); 470 471 // ---------------------------------------------------------------- 472 473 // Keys are String (package name), values are Package. This also serves 474 // as the lock for the global state. Methods that must be called with 475 // this lock held have the prefix "LP". 476 @GuardedBy("mPackages") 477 final ArrayMap<String, PackageParser.Package> mPackages = 478 new ArrayMap<String, PackageParser.Package>(); 479 480 // Tracks available target package names -> overlay package paths. 481 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 482 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 483 484 /** 485 * Tracks new system packages [received in an OTA] that we expect to 486 * find updated user-installed versions. Keys are package name, values 487 * are package location. 488 */ 489 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 490 491 /** 492 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 493 */ 494 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 495 /** 496 * Whether or not system app permissions should be promoted from install to runtime. 497 */ 498 boolean mPromoteSystemApps; 499 500 final Settings mSettings; 501 boolean mRestoredSettings; 502 503 // System configuration read by SystemConfig. 504 final int[] mGlobalGids; 505 final SparseArray<ArraySet<String>> mSystemPermissions; 506 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 507 508 // If mac_permissions.xml was found for seinfo labeling. 509 boolean mFoundPolicyFile; 510 511 // If a recursive restorecon of /data/data/<pkg> is needed. 512 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 513 514 public static final class SharedLibraryEntry { 515 public final String path; 516 public final String apk; 517 518 SharedLibraryEntry(String _path, String _apk) { 519 path = _path; 520 apk = _apk; 521 } 522 } 523 524 // Currently known shared libraries. 525 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 526 new ArrayMap<String, SharedLibraryEntry>(); 527 528 // All available activities, for your resolving pleasure. 529 final ActivityIntentResolver mActivities = 530 new ActivityIntentResolver(); 531 532 // All available receivers, for your resolving pleasure. 533 final ActivityIntentResolver mReceivers = 534 new ActivityIntentResolver(); 535 536 // All available services, for your resolving pleasure. 537 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 538 539 // All available providers, for your resolving pleasure. 540 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 541 542 // Mapping from provider base names (first directory in content URI codePath) 543 // to the provider information. 544 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 545 new ArrayMap<String, PackageParser.Provider>(); 546 547 // Mapping from instrumentation class names to info about them. 548 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 549 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 550 551 // Mapping from permission names to info about them. 552 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 553 new ArrayMap<String, PackageParser.PermissionGroup>(); 554 555 // Packages whose data we have transfered into another package, thus 556 // should no longer exist. 557 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 558 559 // Broadcast actions that are only available to the system. 560 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 561 562 /** List of packages waiting for verification. */ 563 final SparseArray<PackageVerificationState> mPendingVerification 564 = new SparseArray<PackageVerificationState>(); 565 566 /** Set of packages associated with each app op permission. */ 567 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 568 569 final PackageInstallerService mInstallerService; 570 571 private final PackageDexOptimizer mPackageDexOptimizer; 572 573 private AtomicInteger mNextMoveId = new AtomicInteger(); 574 private final MoveCallbacks mMoveCallbacks; 575 576 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 577 578 // Cache of users who need badging. 579 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 580 581 /** Token for keys in mPendingVerification. */ 582 private int mPendingVerificationToken = 0; 583 584 volatile boolean mSystemReady; 585 volatile boolean mSafeMode; 586 volatile boolean mHasSystemUidErrors; 587 588 ApplicationInfo mAndroidApplication; 589 final ActivityInfo mResolveActivity = new ActivityInfo(); 590 final ResolveInfo mResolveInfo = new ResolveInfo(); 591 ComponentName mResolveComponentName; 592 PackageParser.Package mPlatformPackage; 593 ComponentName mCustomResolverComponentName; 594 595 boolean mResolverReplaced = false; 596 597 private final ComponentName mIntentFilterVerifierComponent; 598 private int mIntentFilterVerificationToken = 0; 599 600 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 601 = new SparseArray<IntentFilterVerificationState>(); 602 603 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 604 new DefaultPermissionGrantPolicy(this); 605 606 private static class IFVerificationParams { 607 PackageParser.Package pkg; 608 boolean replacing; 609 int userId; 610 int verifierUid; 611 612 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 613 int _userId, int _verifierUid) { 614 pkg = _pkg; 615 replacing = _replacing; 616 userId = _userId; 617 replacing = _replacing; 618 verifierUid = _verifierUid; 619 } 620 } 621 622 private interface IntentFilterVerifier<T extends IntentFilter> { 623 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 624 T filter, String packageName); 625 void startVerifications(int userId); 626 void receiveVerificationResponse(int verificationId); 627 } 628 629 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 630 private Context mContext; 631 private ComponentName mIntentFilterVerifierComponent; 632 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 633 634 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 635 mContext = context; 636 mIntentFilterVerifierComponent = verifierComponent; 637 } 638 639 private String getDefaultScheme() { 640 return IntentFilter.SCHEME_HTTPS; 641 } 642 643 @Override 644 public void startVerifications(int userId) { 645 // Launch verifications requests 646 int count = mCurrentIntentFilterVerifications.size(); 647 for (int n=0; n<count; n++) { 648 int verificationId = mCurrentIntentFilterVerifications.get(n); 649 final IntentFilterVerificationState ivs = 650 mIntentFilterVerificationStates.get(verificationId); 651 652 String packageName = ivs.getPackageName(); 653 654 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 655 final int filterCount = filters.size(); 656 ArraySet<String> domainsSet = new ArraySet<>(); 657 for (int m=0; m<filterCount; m++) { 658 PackageParser.ActivityIntentInfo filter = filters.get(m); 659 domainsSet.addAll(filter.getHostsList()); 660 } 661 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 662 synchronized (mPackages) { 663 if (mSettings.createIntentFilterVerificationIfNeededLPw( 664 packageName, domainsList) != null) { 665 scheduleWriteSettingsLocked(); 666 } 667 } 668 sendVerificationRequest(userId, verificationId, ivs); 669 } 670 mCurrentIntentFilterVerifications.clear(); 671 } 672 673 private void sendVerificationRequest(int userId, int verificationId, 674 IntentFilterVerificationState ivs) { 675 676 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 677 verificationIntent.putExtra( 678 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 679 verificationId); 680 verificationIntent.putExtra( 681 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 682 getDefaultScheme()); 683 verificationIntent.putExtra( 684 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 685 ivs.getHostsString()); 686 verificationIntent.putExtra( 687 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 688 ivs.getPackageName()); 689 verificationIntent.setComponent(mIntentFilterVerifierComponent); 690 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 691 692 UserHandle user = new UserHandle(userId); 693 mContext.sendBroadcastAsUser(verificationIntent, user); 694 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 695 "Sending IntentFilter verification broadcast"); 696 } 697 698 public void receiveVerificationResponse(int verificationId) { 699 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 700 701 final boolean verified = ivs.isVerified(); 702 703 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 704 final int count = filters.size(); 705 if (DEBUG_DOMAIN_VERIFICATION) { 706 Slog.i(TAG, "Received verification response " + verificationId 707 + " for " + count + " filters, verified=" + verified); 708 } 709 for (int n=0; n<count; n++) { 710 PackageParser.ActivityIntentInfo filter = filters.get(n); 711 filter.setVerified(verified); 712 713 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 714 + " verified with result:" + verified + " and hosts:" 715 + ivs.getHostsString()); 716 } 717 718 mIntentFilterVerificationStates.remove(verificationId); 719 720 final String packageName = ivs.getPackageName(); 721 IntentFilterVerificationInfo ivi = null; 722 723 synchronized (mPackages) { 724 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 725 } 726 if (ivi == null) { 727 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 728 + verificationId + " packageName:" + packageName); 729 return; 730 } 731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 732 "Updating IntentFilterVerificationInfo for package " + packageName 733 +" verificationId:" + verificationId); 734 735 synchronized (mPackages) { 736 if (verified) { 737 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 738 } else { 739 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 740 } 741 scheduleWriteSettingsLocked(); 742 743 final int userId = ivs.getUserId(); 744 if (userId != UserHandle.USER_ALL) { 745 final int userStatus = 746 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 747 748 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 749 boolean needUpdate = false; 750 751 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 752 // already been set by the User thru the Disambiguation dialog 753 switch (userStatus) { 754 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 755 if (verified) { 756 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 757 } else { 758 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 759 } 760 needUpdate = true; 761 break; 762 763 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 764 if (verified) { 765 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 766 needUpdate = true; 767 } 768 break; 769 770 default: 771 // Nothing to do 772 } 773 774 if (needUpdate) { 775 mSettings.updateIntentFilterVerificationStatusLPw( 776 packageName, updatedStatus, userId); 777 scheduleWritePackageRestrictionsLocked(userId); 778 } 779 } 780 } 781 } 782 783 @Override 784 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 785 ActivityIntentInfo filter, String packageName) { 786 if (!hasValidDomains(filter)) { 787 return false; 788 } 789 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 790 if (ivs == null) { 791 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 792 packageName); 793 } 794 if (DEBUG_DOMAIN_VERIFICATION) { 795 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 796 } 797 ivs.addFilter(filter); 798 return true; 799 } 800 801 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 802 int userId, int verificationId, String packageName) { 803 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 804 verifierUid, userId, packageName); 805 ivs.setPendingState(); 806 synchronized (mPackages) { 807 mIntentFilterVerificationStates.append(verificationId, ivs); 808 mCurrentIntentFilterVerifications.add(verificationId); 809 } 810 return ivs; 811 } 812 } 813 814 private static boolean hasValidDomains(ActivityIntentInfo filter) { 815 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 816 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 817 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 818 } 819 820 private IntentFilterVerifier mIntentFilterVerifier; 821 822 // Set of pending broadcasts for aggregating enable/disable of components. 823 static class PendingPackageBroadcasts { 824 // for each user id, a map of <package name -> components within that package> 825 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 826 827 public PendingPackageBroadcasts() { 828 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 829 } 830 831 public ArrayList<String> get(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 833 return packages.get(packageName); 834 } 835 836 public void put(int userId, String packageName, ArrayList<String> components) { 837 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 838 packages.put(packageName, components); 839 } 840 841 public void remove(int userId, String packageName) { 842 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 843 if (packages != null) { 844 packages.remove(packageName); 845 } 846 } 847 848 public void remove(int userId) { 849 mUidMap.remove(userId); 850 } 851 852 public int userIdCount() { 853 return mUidMap.size(); 854 } 855 856 public int userIdAt(int n) { 857 return mUidMap.keyAt(n); 858 } 859 860 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 861 return mUidMap.get(userId); 862 } 863 864 public int size() { 865 // total number of pending broadcast entries across all userIds 866 int num = 0; 867 for (int i = 0; i< mUidMap.size(); i++) { 868 num += mUidMap.valueAt(i).size(); 869 } 870 return num; 871 } 872 873 public void clear() { 874 mUidMap.clear(); 875 } 876 877 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 878 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 879 if (map == null) { 880 map = new ArrayMap<String, ArrayList<String>>(); 881 mUidMap.put(userId, map); 882 } 883 return map; 884 } 885 } 886 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 887 888 // Service Connection to remote media container service to copy 889 // package uri's from external media onto secure containers 890 // or internal storage. 891 private IMediaContainerService mContainerService = null; 892 893 static final int SEND_PENDING_BROADCAST = 1; 894 static final int MCS_BOUND = 3; 895 static final int END_COPY = 4; 896 static final int INIT_COPY = 5; 897 static final int MCS_UNBIND = 6; 898 static final int START_CLEANING_PACKAGE = 7; 899 static final int FIND_INSTALL_LOC = 8; 900 static final int POST_INSTALL = 9; 901 static final int MCS_RECONNECT = 10; 902 static final int MCS_GIVE_UP = 11; 903 static final int UPDATED_MEDIA_STATUS = 12; 904 static final int WRITE_SETTINGS = 13; 905 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 906 static final int PACKAGE_VERIFIED = 15; 907 static final int CHECK_PENDING_VERIFICATION = 16; 908 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 909 static final int INTENT_FILTER_VERIFIED = 18; 910 911 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 912 913 // Delay time in millisecs 914 static final int BROADCAST_DELAY = 10 * 1000; 915 916 static UserManagerService sUserManager; 917 918 // Stores a list of users whose package restrictions file needs to be updated 919 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 920 921 final private DefaultContainerConnection mDefContainerConn = 922 new DefaultContainerConnection(); 923 class DefaultContainerConnection implements ServiceConnection { 924 public void onServiceConnected(ComponentName name, IBinder service) { 925 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 926 IMediaContainerService imcs = 927 IMediaContainerService.Stub.asInterface(service); 928 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 929 } 930 931 public void onServiceDisconnected(ComponentName name) { 932 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 933 } 934 } 935 936 // Recordkeeping of restore-after-install operations that are currently in flight 937 // between the Package Manager and the Backup Manager 938 class PostInstallData { 939 public InstallArgs args; 940 public PackageInstalledInfo res; 941 942 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 943 args = _a; 944 res = _r; 945 } 946 } 947 948 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 949 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 950 951 // XML tags for backup/restore of various bits of state 952 private static final String TAG_PREFERRED_BACKUP = "pa"; 953 private static final String TAG_DEFAULT_APPS = "da"; 954 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 955 956 final String mRequiredVerifierPackage; 957 final String mRequiredInstallerPackage; 958 959 private final PackageUsage mPackageUsage = new PackageUsage(); 960 961 private class PackageUsage { 962 private static final int WRITE_INTERVAL 963 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 964 965 private final Object mFileLock = new Object(); 966 private final AtomicLong mLastWritten = new AtomicLong(0); 967 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 968 969 private boolean mIsHistoricalPackageUsageAvailable = true; 970 971 boolean isHistoricalPackageUsageAvailable() { 972 return mIsHistoricalPackageUsageAvailable; 973 } 974 975 void write(boolean force) { 976 if (force) { 977 writeInternal(); 978 return; 979 } 980 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 981 && !DEBUG_DEXOPT) { 982 return; 983 } 984 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 985 new Thread("PackageUsage_DiskWriter") { 986 @Override 987 public void run() { 988 try { 989 writeInternal(); 990 } finally { 991 mBackgroundWriteRunning.set(false); 992 } 993 } 994 }.start(); 995 } 996 } 997 998 private void writeInternal() { 999 synchronized (mPackages) { 1000 synchronized (mFileLock) { 1001 AtomicFile file = getFile(); 1002 FileOutputStream f = null; 1003 try { 1004 f = file.startWrite(); 1005 BufferedOutputStream out = new BufferedOutputStream(f); 1006 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1007 StringBuilder sb = new StringBuilder(); 1008 for (PackageParser.Package pkg : mPackages.values()) { 1009 if (pkg.mLastPackageUsageTimeInMills == 0) { 1010 continue; 1011 } 1012 sb.setLength(0); 1013 sb.append(pkg.packageName); 1014 sb.append(' '); 1015 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1016 sb.append('\n'); 1017 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1018 } 1019 out.flush(); 1020 file.finishWrite(f); 1021 } catch (IOException e) { 1022 if (f != null) { 1023 file.failWrite(f); 1024 } 1025 Log.e(TAG, "Failed to write package usage times", e); 1026 } 1027 } 1028 } 1029 mLastWritten.set(SystemClock.elapsedRealtime()); 1030 } 1031 1032 void readLP() { 1033 synchronized (mFileLock) { 1034 AtomicFile file = getFile(); 1035 BufferedInputStream in = null; 1036 try { 1037 in = new BufferedInputStream(file.openRead()); 1038 StringBuffer sb = new StringBuffer(); 1039 while (true) { 1040 String packageName = readToken(in, sb, ' '); 1041 if (packageName == null) { 1042 break; 1043 } 1044 String timeInMillisString = readToken(in, sb, '\n'); 1045 if (timeInMillisString == null) { 1046 throw new IOException("Failed to find last usage time for package " 1047 + packageName); 1048 } 1049 PackageParser.Package pkg = mPackages.get(packageName); 1050 if (pkg == null) { 1051 continue; 1052 } 1053 long timeInMillis; 1054 try { 1055 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1056 } catch (NumberFormatException e) { 1057 throw new IOException("Failed to parse " + timeInMillisString 1058 + " as a long.", e); 1059 } 1060 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1061 } 1062 } catch (FileNotFoundException expected) { 1063 mIsHistoricalPackageUsageAvailable = false; 1064 } catch (IOException e) { 1065 Log.w(TAG, "Failed to read package usage times", e); 1066 } finally { 1067 IoUtils.closeQuietly(in); 1068 } 1069 } 1070 mLastWritten.set(SystemClock.elapsedRealtime()); 1071 } 1072 1073 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1074 throws IOException { 1075 sb.setLength(0); 1076 while (true) { 1077 int ch = in.read(); 1078 if (ch == -1) { 1079 if (sb.length() == 0) { 1080 return null; 1081 } 1082 throw new IOException("Unexpected EOF"); 1083 } 1084 if (ch == endOfToken) { 1085 return sb.toString(); 1086 } 1087 sb.append((char)ch); 1088 } 1089 } 1090 1091 private AtomicFile getFile() { 1092 File dataDir = Environment.getDataDirectory(); 1093 File systemDir = new File(dataDir, "system"); 1094 File fname = new File(systemDir, "package-usage.list"); 1095 return new AtomicFile(fname); 1096 } 1097 } 1098 1099 class PackageHandler extends Handler { 1100 private boolean mBound = false; 1101 final ArrayList<HandlerParams> mPendingInstalls = 1102 new ArrayList<HandlerParams>(); 1103 1104 private boolean connectToService() { 1105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1106 " DefaultContainerService"); 1107 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1109 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1110 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 mBound = true; 1113 return true; 1114 } 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1116 return false; 1117 } 1118 1119 private void disconnectService() { 1120 mContainerService = null; 1121 mBound = false; 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1123 mContext.unbindService(mDefContainerConn); 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } 1126 1127 PackageHandler(Looper looper) { 1128 super(looper); 1129 } 1130 1131 public void handleMessage(Message msg) { 1132 try { 1133 doHandleMessage(msg); 1134 } finally { 1135 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1136 } 1137 } 1138 1139 void doHandleMessage(Message msg) { 1140 switch (msg.what) { 1141 case INIT_COPY: { 1142 HandlerParams params = (HandlerParams) msg.obj; 1143 int idx = mPendingInstalls.size(); 1144 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1145 // If a bind was already initiated we dont really 1146 // need to do anything. The pending install 1147 // will be processed later on. 1148 if (!mBound) { 1149 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1150 System.identityHashCode(mHandler)); 1151 // If this is the only one pending we might 1152 // have to bind to the service again. 1153 if (!connectToService()) { 1154 Slog.e(TAG, "Failed to bind to media container service"); 1155 params.serviceError(); 1156 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1157 System.identityHashCode(mHandler)); 1158 if (params.traceMethod != null) { 1159 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1160 params.traceCookie); 1161 } 1162 return; 1163 } else { 1164 // Once we bind to the service, the first 1165 // pending request will be processed. 1166 mPendingInstalls.add(idx, params); 1167 } 1168 } else { 1169 mPendingInstalls.add(idx, params); 1170 // Already bound to the service. Just make 1171 // sure we trigger off processing the first request. 1172 if (idx == 0) { 1173 mHandler.sendEmptyMessage(MCS_BOUND); 1174 } 1175 } 1176 break; 1177 } 1178 case MCS_BOUND: { 1179 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1180 if (msg.obj != null) { 1181 mContainerService = (IMediaContainerService) msg.obj; 1182 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1183 System.identityHashCode(mHandler)); 1184 } 1185 if (mContainerService == null) { 1186 if (!mBound) { 1187 // Something seriously wrong since we are not bound and we are not 1188 // waiting for connection. Bail out. 1189 Slog.e(TAG, "Cannot bind to media container service"); 1190 for (HandlerParams params : mPendingInstalls) { 1191 // Indicate service bind error 1192 params.serviceError(); 1193 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1194 System.identityHashCode(params)); 1195 if (params.traceMethod != null) { 1196 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1197 params.traceMethod, params.traceCookie); 1198 } 1199 return; 1200 } 1201 mPendingInstalls.clear(); 1202 } else { 1203 Slog.w(TAG, "Waiting to connect to media container service"); 1204 } 1205 } else if (mPendingInstalls.size() > 0) { 1206 HandlerParams params = mPendingInstalls.get(0); 1207 if (params != null) { 1208 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1209 System.identityHashCode(params)); 1210 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1211 if (params.startCopy()) { 1212 // We are done... look for more work or to 1213 // go idle. 1214 if (DEBUG_SD_INSTALL) Log.i(TAG, 1215 "Checking for more work or unbind..."); 1216 // Delete pending install 1217 if (mPendingInstalls.size() > 0) { 1218 mPendingInstalls.remove(0); 1219 } 1220 if (mPendingInstalls.size() == 0) { 1221 if (mBound) { 1222 if (DEBUG_SD_INSTALL) Log.i(TAG, 1223 "Posting delayed MCS_UNBIND"); 1224 removeMessages(MCS_UNBIND); 1225 Message ubmsg = obtainMessage(MCS_UNBIND); 1226 // Unbind after a little delay, to avoid 1227 // continual thrashing. 1228 sendMessageDelayed(ubmsg, 10000); 1229 } 1230 } else { 1231 // There are more pending requests in queue. 1232 // Just post MCS_BOUND message to trigger processing 1233 // of next pending install. 1234 if (DEBUG_SD_INSTALL) Log.i(TAG, 1235 "Posting MCS_BOUND for next work"); 1236 mHandler.sendEmptyMessage(MCS_BOUND); 1237 } 1238 } 1239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1240 } 1241 } else { 1242 // Should never happen ideally. 1243 Slog.w(TAG, "Empty queue"); 1244 } 1245 break; 1246 } 1247 case MCS_RECONNECT: { 1248 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1249 if (mPendingInstalls.size() > 0) { 1250 if (mBound) { 1251 disconnectService(); 1252 } 1253 if (!connectToService()) { 1254 Slog.e(TAG, "Failed to bind to media container service"); 1255 for (HandlerParams params : mPendingInstalls) { 1256 // Indicate service bind error 1257 params.serviceError(); 1258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1259 System.identityHashCode(params)); 1260 } 1261 mPendingInstalls.clear(); 1262 } 1263 } 1264 break; 1265 } 1266 case MCS_UNBIND: { 1267 // If there is no actual work left, then time to unbind. 1268 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1269 1270 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1271 if (mBound) { 1272 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1273 1274 disconnectService(); 1275 } 1276 } else if (mPendingInstalls.size() > 0) { 1277 // There are more pending requests in queue. 1278 // Just post MCS_BOUND message to trigger processing 1279 // of next pending install. 1280 mHandler.sendEmptyMessage(MCS_BOUND); 1281 } 1282 1283 break; 1284 } 1285 case MCS_GIVE_UP: { 1286 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1287 HandlerParams params = mPendingInstalls.remove(0); 1288 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1289 System.identityHashCode(params)); 1290 break; 1291 } 1292 case SEND_PENDING_BROADCAST: { 1293 String packages[]; 1294 ArrayList<String> components[]; 1295 int size = 0; 1296 int uids[]; 1297 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1298 synchronized (mPackages) { 1299 if (mPendingBroadcasts == null) { 1300 return; 1301 } 1302 size = mPendingBroadcasts.size(); 1303 if (size <= 0) { 1304 // Nothing to be done. Just return 1305 return; 1306 } 1307 packages = new String[size]; 1308 components = new ArrayList[size]; 1309 uids = new int[size]; 1310 int i = 0; // filling out the above arrays 1311 1312 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1313 int packageUserId = mPendingBroadcasts.userIdAt(n); 1314 Iterator<Map.Entry<String, ArrayList<String>>> it 1315 = mPendingBroadcasts.packagesForUserId(packageUserId) 1316 .entrySet().iterator(); 1317 while (it.hasNext() && i < size) { 1318 Map.Entry<String, ArrayList<String>> ent = it.next(); 1319 packages[i] = ent.getKey(); 1320 components[i] = ent.getValue(); 1321 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1322 uids[i] = (ps != null) 1323 ? UserHandle.getUid(packageUserId, ps.appId) 1324 : -1; 1325 i++; 1326 } 1327 } 1328 size = i; 1329 mPendingBroadcasts.clear(); 1330 } 1331 // Send broadcasts 1332 for (int i = 0; i < size; i++) { 1333 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1334 } 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1336 break; 1337 } 1338 case START_CLEANING_PACKAGE: { 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1340 final String packageName = (String)msg.obj; 1341 final int userId = msg.arg1; 1342 final boolean andCode = msg.arg2 != 0; 1343 synchronized (mPackages) { 1344 if (userId == UserHandle.USER_ALL) { 1345 int[] users = sUserManager.getUserIds(); 1346 for (int user : users) { 1347 mSettings.addPackageToCleanLPw( 1348 new PackageCleanItem(user, packageName, andCode)); 1349 } 1350 } else { 1351 mSettings.addPackageToCleanLPw( 1352 new PackageCleanItem(userId, packageName, andCode)); 1353 } 1354 } 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1356 startCleaningPackages(); 1357 } break; 1358 case POST_INSTALL: { 1359 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1360 PostInstallData data = mRunningInstalls.get(msg.arg1); 1361 mRunningInstalls.delete(msg.arg1); 1362 boolean deleteOld = false; 1363 1364 if (data != null) { 1365 InstallArgs args = data.args; 1366 PackageInstalledInfo res = data.res; 1367 1368 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1369 final String packageName = res.pkg.applicationInfo.packageName; 1370 res.removedInfo.sendBroadcast(false, true, false); 1371 Bundle extras = new Bundle(1); 1372 extras.putInt(Intent.EXTRA_UID, res.uid); 1373 1374 // Now that we successfully installed the package, grant runtime 1375 // permissions if requested before broadcasting the install. 1376 if ((args.installFlags 1377 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1378 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1379 args.installGrantPermissions); 1380 } 1381 1382 // Determine the set of users who are adding this 1383 // package for the first time vs. those who are seeing 1384 // an update. 1385 int[] firstUsers; 1386 int[] updateUsers = new int[0]; 1387 if (res.origUsers == null || res.origUsers.length == 0) { 1388 firstUsers = res.newUsers; 1389 } else { 1390 firstUsers = new int[0]; 1391 for (int i=0; i<res.newUsers.length; i++) { 1392 int user = res.newUsers[i]; 1393 boolean isNew = true; 1394 for (int j=0; j<res.origUsers.length; j++) { 1395 if (res.origUsers[j] == user) { 1396 isNew = false; 1397 break; 1398 } 1399 } 1400 if (isNew) { 1401 int[] newFirst = new int[firstUsers.length+1]; 1402 System.arraycopy(firstUsers, 0, newFirst, 0, 1403 firstUsers.length); 1404 newFirst[firstUsers.length] = user; 1405 firstUsers = newFirst; 1406 } else { 1407 int[] newUpdate = new int[updateUsers.length+1]; 1408 System.arraycopy(updateUsers, 0, newUpdate, 0, 1409 updateUsers.length); 1410 newUpdate[updateUsers.length] = user; 1411 updateUsers = newUpdate; 1412 } 1413 } 1414 } 1415 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1416 packageName, extras, null, null, firstUsers); 1417 final boolean update = res.removedInfo.removedPackage != null; 1418 if (update) { 1419 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1420 } 1421 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1422 packageName, extras, null, null, updateUsers); 1423 if (update) { 1424 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1425 packageName, extras, null, null, updateUsers); 1426 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1427 null, null, packageName, null, updateUsers); 1428 1429 // treat asec-hosted packages like removable media on upgrade 1430 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1431 if (DEBUG_INSTALL) { 1432 Slog.i(TAG, "upgrading pkg " + res.pkg 1433 + " is ASEC-hosted -> AVAILABLE"); 1434 } 1435 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1436 ArrayList<String> pkgList = new ArrayList<String>(1); 1437 pkgList.add(packageName); 1438 sendResourcesChangedBroadcast(true, true, 1439 pkgList,uidArray, null); 1440 } 1441 } 1442 if (res.removedInfo.args != null) { 1443 // Remove the replaced package's older resources safely now 1444 deleteOld = true; 1445 } 1446 1447 // If this app is a browser and it's newly-installed for some 1448 // users, clear any default-browser state in those users 1449 if (firstUsers.length > 0) { 1450 // the app's nature doesn't depend on the user, so we can just 1451 // check its browser nature in any user and generalize. 1452 if (packageIsBrowser(packageName, firstUsers[0])) { 1453 synchronized (mPackages) { 1454 for (int userId : firstUsers) { 1455 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1456 } 1457 } 1458 } 1459 } 1460 // Log current value of "unknown sources" setting 1461 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1462 getUnknownSourcesSettings()); 1463 } 1464 // Force a gc to clear up things 1465 Runtime.getRuntime().gc(); 1466 // We delete after a gc for applications on sdcard. 1467 if (deleteOld) { 1468 synchronized (mInstallLock) { 1469 res.removedInfo.args.doPostDeleteLI(true); 1470 } 1471 } 1472 if (args.observer != null) { 1473 try { 1474 Bundle extras = extrasForInstallResult(res); 1475 args.observer.onPackageInstalled(res.name, res.returnCode, 1476 res.returnMsg, extras); 1477 } catch (RemoteException e) { 1478 Slog.i(TAG, "Observer no longer exists."); 1479 } 1480 } 1481 if (args.traceMethod != null) { 1482 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1483 args.traceCookie); 1484 } 1485 return; 1486 } else { 1487 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1488 } 1489 1490 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1491 } break; 1492 case UPDATED_MEDIA_STATUS: { 1493 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1494 boolean reportStatus = msg.arg1 == 1; 1495 boolean doGc = msg.arg2 == 1; 1496 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1497 if (doGc) { 1498 // Force a gc to clear up stale containers. 1499 Runtime.getRuntime().gc(); 1500 } 1501 if (msg.obj != null) { 1502 @SuppressWarnings("unchecked") 1503 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1504 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1505 // Unload containers 1506 unloadAllContainers(args); 1507 } 1508 if (reportStatus) { 1509 try { 1510 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1511 PackageHelper.getMountService().finishMediaUpdate(); 1512 } catch (RemoteException e) { 1513 Log.e(TAG, "MountService not running?"); 1514 } 1515 } 1516 } break; 1517 case WRITE_SETTINGS: { 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 removeMessages(WRITE_SETTINGS); 1521 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1522 mSettings.writeLPr(); 1523 mDirtyUsers.clear(); 1524 } 1525 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1526 } break; 1527 case WRITE_PACKAGE_RESTRICTIONS: { 1528 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1529 synchronized (mPackages) { 1530 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1531 for (int userId : mDirtyUsers) { 1532 mSettings.writePackageRestrictionsLPr(userId); 1533 } 1534 mDirtyUsers.clear(); 1535 } 1536 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1537 } break; 1538 case CHECK_PENDING_VERIFICATION: { 1539 final int verificationId = msg.arg1; 1540 final PackageVerificationState state = mPendingVerification.get(verificationId); 1541 1542 if ((state != null) && !state.timeoutExtended()) { 1543 final InstallArgs args = state.getInstallArgs(); 1544 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1545 1546 Slog.i(TAG, "Verification timed out for " + originUri); 1547 mPendingVerification.remove(verificationId); 1548 1549 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1550 1551 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1552 Slog.i(TAG, "Continuing with installation of " + originUri); 1553 state.setVerifierResponse(Binder.getCallingUid(), 1554 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1555 broadcastPackageVerified(verificationId, originUri, 1556 PackageManager.VERIFICATION_ALLOW, 1557 state.getInstallArgs().getUser()); 1558 try { 1559 ret = args.copyApk(mContainerService, true); 1560 } catch (RemoteException e) { 1561 Slog.e(TAG, "Could not contact the ContainerService"); 1562 } 1563 } else { 1564 broadcastPackageVerified(verificationId, originUri, 1565 PackageManager.VERIFICATION_REJECT, 1566 state.getInstallArgs().getUser()); 1567 } 1568 1569 Trace.asyncTraceEnd( 1570 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1571 1572 processPendingInstall(args, ret); 1573 mHandler.sendEmptyMessage(MCS_UNBIND); 1574 } 1575 break; 1576 } 1577 case PACKAGE_VERIFIED: { 1578 final int verificationId = msg.arg1; 1579 1580 final PackageVerificationState state = mPendingVerification.get(verificationId); 1581 if (state == null) { 1582 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1583 break; 1584 } 1585 1586 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1587 1588 state.setVerifierResponse(response.callerUid, response.code); 1589 1590 if (state.isVerificationComplete()) { 1591 mPendingVerification.remove(verificationId); 1592 1593 final InstallArgs args = state.getInstallArgs(); 1594 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1595 1596 int ret; 1597 if (state.isInstallAllowed()) { 1598 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1599 broadcastPackageVerified(verificationId, originUri, 1600 response.code, state.getInstallArgs().getUser()); 1601 try { 1602 ret = args.copyApk(mContainerService, true); 1603 } catch (RemoteException e) { 1604 Slog.e(TAG, "Could not contact the ContainerService"); 1605 } 1606 } else { 1607 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1608 } 1609 1610 Trace.asyncTraceEnd( 1611 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1612 1613 processPendingInstall(args, ret); 1614 mHandler.sendEmptyMessage(MCS_UNBIND); 1615 } 1616 1617 break; 1618 } 1619 case START_INTENT_FILTER_VERIFICATIONS: { 1620 IFVerificationParams params = (IFVerificationParams) msg.obj; 1621 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1622 params.replacing, params.pkg); 1623 break; 1624 } 1625 case INTENT_FILTER_VERIFIED: { 1626 final int verificationId = msg.arg1; 1627 1628 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1629 verificationId); 1630 if (state == null) { 1631 Slog.w(TAG, "Invalid IntentFilter verification token " 1632 + verificationId + " received"); 1633 break; 1634 } 1635 1636 final int userId = state.getUserId(); 1637 1638 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1639 "Processing IntentFilter verification with token:" 1640 + verificationId + " and userId:" + userId); 1641 1642 final IntentFilterVerificationResponse response = 1643 (IntentFilterVerificationResponse) msg.obj; 1644 1645 state.setVerifierResponse(response.callerUid, response.code); 1646 1647 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1648 "IntentFilter verification with token:" + verificationId 1649 + " and userId:" + userId 1650 + " is settings verifier response with response code:" 1651 + response.code); 1652 1653 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1654 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1655 + response.getFailedDomainsString()); 1656 } 1657 1658 if (state.isVerificationComplete()) { 1659 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1660 } else { 1661 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1662 "IntentFilter verification with token:" + verificationId 1663 + " was not said to be complete"); 1664 } 1665 1666 break; 1667 } 1668 } 1669 } 1670 } 1671 1672 private StorageEventListener mStorageListener = new StorageEventListener() { 1673 @Override 1674 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1675 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1676 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1677 final String volumeUuid = vol.getFsUuid(); 1678 1679 // Clean up any users or apps that were removed or recreated 1680 // while this volume was missing 1681 reconcileUsers(volumeUuid); 1682 reconcileApps(volumeUuid); 1683 1684 // Clean up any install sessions that expired or were 1685 // cancelled while this volume was missing 1686 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1687 1688 loadPrivatePackages(vol); 1689 1690 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1691 unloadPrivatePackages(vol); 1692 } 1693 } 1694 1695 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1696 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1697 updateExternalMediaStatus(true, false); 1698 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1699 updateExternalMediaStatus(false, false); 1700 } 1701 } 1702 } 1703 1704 @Override 1705 public void onVolumeForgotten(String fsUuid) { 1706 if (TextUtils.isEmpty(fsUuid)) { 1707 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1708 return; 1709 } 1710 1711 // Remove any apps installed on the forgotten volume 1712 synchronized (mPackages) { 1713 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1714 for (PackageSetting ps : packages) { 1715 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1716 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1717 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1718 } 1719 1720 mSettings.onVolumeForgotten(fsUuid); 1721 mSettings.writeLPr(); 1722 } 1723 } 1724 }; 1725 1726 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1727 String[] grantedPermissions) { 1728 if (userId >= UserHandle.USER_OWNER) { 1729 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1730 } else if (userId == UserHandle.USER_ALL) { 1731 final int[] userIds; 1732 synchronized (mPackages) { 1733 userIds = UserManagerService.getInstance().getUserIds(); 1734 } 1735 for (int someUserId : userIds) { 1736 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1737 } 1738 } 1739 1740 // We could have touched GID membership, so flush out packages.list 1741 synchronized (mPackages) { 1742 mSettings.writePackageListLPr(); 1743 } 1744 } 1745 1746 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1747 String[] grantedPermissions) { 1748 SettingBase sb = (SettingBase) pkg.mExtras; 1749 if (sb == null) { 1750 return; 1751 } 1752 1753 PermissionsState permissionsState = sb.getPermissionsState(); 1754 1755 for (String permission : pkg.requestedPermissions) { 1756 BasePermission bp = mSettings.mPermissions.get(permission); 1757 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1758 || ArrayUtils.contains(grantedPermissions, permission))) { 1759 permissionsState.grantRuntimePermission(bp, userId); 1760 } 1761 } 1762 } 1763 1764 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1765 Bundle extras = null; 1766 switch (res.returnCode) { 1767 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1768 extras = new Bundle(); 1769 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1770 res.origPermission); 1771 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1772 res.origPackage); 1773 break; 1774 } 1775 case PackageManager.INSTALL_SUCCEEDED: { 1776 extras = new Bundle(); 1777 extras.putBoolean(Intent.EXTRA_REPLACING, 1778 res.removedInfo != null && res.removedInfo.removedPackage != null); 1779 break; 1780 } 1781 } 1782 return extras; 1783 } 1784 1785 void scheduleWriteSettingsLocked() { 1786 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1787 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1788 } 1789 } 1790 1791 void scheduleWritePackageRestrictionsLocked(int userId) { 1792 if (!sUserManager.exists(userId)) return; 1793 mDirtyUsers.add(userId); 1794 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1795 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1796 } 1797 } 1798 1799 public static PackageManagerService main(Context context, Installer installer, 1800 boolean factoryTest, boolean onlyCore) { 1801 PackageManagerService m = new PackageManagerService(context, installer, 1802 factoryTest, onlyCore); 1803 ServiceManager.addService("package", m); 1804 return m; 1805 } 1806 1807 static String[] splitString(String str, char sep) { 1808 int count = 1; 1809 int i = 0; 1810 while ((i=str.indexOf(sep, i)) >= 0) { 1811 count++; 1812 i++; 1813 } 1814 1815 String[] res = new String[count]; 1816 i=0; 1817 count = 0; 1818 int lastI=0; 1819 while ((i=str.indexOf(sep, i)) >= 0) { 1820 res[count] = str.substring(lastI, i); 1821 count++; 1822 i++; 1823 lastI = i; 1824 } 1825 res[count] = str.substring(lastI, str.length()); 1826 return res; 1827 } 1828 1829 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1830 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1831 Context.DISPLAY_SERVICE); 1832 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1833 } 1834 1835 public PackageManagerService(Context context, Installer installer, 1836 boolean factoryTest, boolean onlyCore) { 1837 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1838 SystemClock.uptimeMillis()); 1839 1840 if (mSdkVersion <= 0) { 1841 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1842 } 1843 1844 mContext = context; 1845 mFactoryTest = factoryTest; 1846 mOnlyCore = onlyCore; 1847 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1848 mMetrics = new DisplayMetrics(); 1849 mSettings = new Settings(mPackages); 1850 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1851 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1852 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1853 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1854 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1855 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1856 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1857 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1858 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1859 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1860 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1861 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1862 1863 // TODO: add a property to control this? 1864 long dexOptLRUThresholdInMinutes; 1865 if (mLazyDexOpt) { 1866 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1867 } else { 1868 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1869 } 1870 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1871 1872 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1873 if (separateProcesses != null && separateProcesses.length() > 0) { 1874 if ("*".equals(separateProcesses)) { 1875 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1876 mSeparateProcesses = null; 1877 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1878 } else { 1879 mDefParseFlags = 0; 1880 mSeparateProcesses = separateProcesses.split(","); 1881 Slog.w(TAG, "Running with debug.separate_processes: " 1882 + separateProcesses); 1883 } 1884 } else { 1885 mDefParseFlags = 0; 1886 mSeparateProcesses = null; 1887 } 1888 1889 mInstaller = installer; 1890 mPackageDexOptimizer = new PackageDexOptimizer(this); 1891 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1892 1893 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1894 FgThread.get().getLooper()); 1895 1896 getDefaultDisplayMetrics(context, mMetrics); 1897 1898 SystemConfig systemConfig = SystemConfig.getInstance(); 1899 mGlobalGids = systemConfig.getGlobalGids(); 1900 mSystemPermissions = systemConfig.getSystemPermissions(); 1901 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1902 1903 synchronized (mInstallLock) { 1904 // writer 1905 synchronized (mPackages) { 1906 mHandlerThread = new ServiceThread(TAG, 1907 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1908 mHandlerThread.start(); 1909 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1910 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1911 1912 File dataDir = Environment.getDataDirectory(); 1913 mAppDataDir = new File(dataDir, "data"); 1914 mAppInstallDir = new File(dataDir, "app"); 1915 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1916 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1917 mUserAppDataDir = new File(dataDir, "user"); 1918 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1919 1920 sUserManager = new UserManagerService(context, this, 1921 mInstallLock, mPackages); 1922 1923 // Propagate permission configuration in to package manager. 1924 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1925 = systemConfig.getPermissions(); 1926 for (int i=0; i<permConfig.size(); i++) { 1927 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1928 BasePermission bp = mSettings.mPermissions.get(perm.name); 1929 if (bp == null) { 1930 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1931 mSettings.mPermissions.put(perm.name, bp); 1932 } 1933 if (perm.gids != null) { 1934 bp.setGids(perm.gids, perm.perUser); 1935 } 1936 } 1937 1938 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1939 for (int i=0; i<libConfig.size(); i++) { 1940 mSharedLibraries.put(libConfig.keyAt(i), 1941 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1942 } 1943 1944 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1945 1946 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1947 1948 String customResolverActivity = Resources.getSystem().getString( 1949 R.string.config_customResolverActivity); 1950 if (TextUtils.isEmpty(customResolverActivity)) { 1951 customResolverActivity = null; 1952 } else { 1953 mCustomResolverComponentName = ComponentName.unflattenFromString( 1954 customResolverActivity); 1955 } 1956 1957 long startTime = SystemClock.uptimeMillis(); 1958 1959 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1960 startTime); 1961 1962 // Set flag to monitor and not change apk file paths when 1963 // scanning install directories. 1964 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1965 1966 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1967 1968 /** 1969 * Add everything in the in the boot class path to the 1970 * list of process files because dexopt will have been run 1971 * if necessary during zygote startup. 1972 */ 1973 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1974 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1975 1976 if (bootClassPath != null) { 1977 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1978 for (String element : bootClassPathElements) { 1979 alreadyDexOpted.add(element); 1980 } 1981 } else { 1982 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1983 } 1984 1985 if (systemServerClassPath != null) { 1986 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1987 for (String element : systemServerClassPathElements) { 1988 alreadyDexOpted.add(element); 1989 } 1990 } else { 1991 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1992 } 1993 1994 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1995 final String[] dexCodeInstructionSets = 1996 getDexCodeInstructionSets( 1997 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1998 1999 /** 2000 * Ensure all external libraries have had dexopt run on them. 2001 */ 2002 if (mSharedLibraries.size() > 0) { 2003 // NOTE: For now, we're compiling these system "shared libraries" 2004 // (and framework jars) into all available architectures. It's possible 2005 // to compile them only when we come across an app that uses them (there's 2006 // already logic for that in scanPackageLI) but that adds some complexity. 2007 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2008 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2009 final String lib = libEntry.path; 2010 if (lib == null) { 2011 continue; 2012 } 2013 2014 try { 2015 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2016 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2017 alreadyDexOpted.add(lib); 2018 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2019 } 2020 } catch (FileNotFoundException e) { 2021 Slog.w(TAG, "Library not found: " + lib); 2022 } catch (IOException e) { 2023 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2024 + e.getMessage()); 2025 } 2026 } 2027 } 2028 } 2029 2030 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2031 2032 // Gross hack for now: we know this file doesn't contain any 2033 // code, so don't dexopt it to avoid the resulting log spew. 2034 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2035 2036 // Gross hack for now: we know this file is only part of 2037 // the boot class path for art, so don't dexopt it to 2038 // avoid the resulting log spew. 2039 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2040 2041 /** 2042 * There are a number of commands implemented in Java, which 2043 * we currently need to do the dexopt on so that they can be 2044 * run from a non-root shell. 2045 */ 2046 String[] frameworkFiles = frameworkDir.list(); 2047 if (frameworkFiles != null) { 2048 // TODO: We could compile these only for the most preferred ABI. We should 2049 // first double check that the dex files for these commands are not referenced 2050 // by other system apps. 2051 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2052 for (int i=0; i<frameworkFiles.length; i++) { 2053 File libPath = new File(frameworkDir, frameworkFiles[i]); 2054 String path = libPath.getPath(); 2055 // Skip the file if we already did it. 2056 if (alreadyDexOpted.contains(path)) { 2057 continue; 2058 } 2059 // Skip the file if it is not a type we want to dexopt. 2060 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2061 continue; 2062 } 2063 try { 2064 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2065 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2066 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2067 } 2068 } catch (FileNotFoundException e) { 2069 Slog.w(TAG, "Jar not found: " + path); 2070 } catch (IOException e) { 2071 Slog.w(TAG, "Exception reading jar: " + path, e); 2072 } 2073 } 2074 } 2075 } 2076 2077 final VersionInfo ver = mSettings.getInternalVersion(); 2078 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2079 // when upgrading from pre-M, promote system app permissions from install to runtime 2080 mPromoteSystemApps = 2081 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2082 2083 // save off the names of pre-existing system packages prior to scanning; we don't 2084 // want to automatically grant runtime permissions for new system apps 2085 if (mPromoteSystemApps) { 2086 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2087 while (pkgSettingIter.hasNext()) { 2088 PackageSetting ps = pkgSettingIter.next(); 2089 if (isSystemApp(ps)) { 2090 mExistingSystemPackages.add(ps.name); 2091 } 2092 } 2093 } 2094 2095 // Collect vendor overlay packages. 2096 // (Do this before scanning any apps.) 2097 // For security and version matching reason, only consider 2098 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2099 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2100 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2101 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2102 2103 // Find base frameworks (resource packages without code). 2104 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2105 | PackageParser.PARSE_IS_SYSTEM_DIR 2106 | PackageParser.PARSE_IS_PRIVILEGED, 2107 scanFlags | SCAN_NO_DEX, 0); 2108 2109 // Collected privileged system packages. 2110 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2111 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2112 | PackageParser.PARSE_IS_SYSTEM_DIR 2113 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2114 2115 // Collect ordinary system packages. 2116 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2117 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2118 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2119 2120 // Collect all vendor packages. 2121 File vendorAppDir = new File("/vendor/app"); 2122 try { 2123 vendorAppDir = vendorAppDir.getCanonicalFile(); 2124 } catch (IOException e) { 2125 // failed to look up canonical path, continue with original one 2126 } 2127 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2128 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2129 2130 // Collect all OEM packages. 2131 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2132 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2133 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2134 2135 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2136 mInstaller.moveFiles(); 2137 2138 // Prune any system packages that no longer exist. 2139 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2140 if (!mOnlyCore) { 2141 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2142 while (psit.hasNext()) { 2143 PackageSetting ps = psit.next(); 2144 2145 /* 2146 * If this is not a system app, it can't be a 2147 * disable system app. 2148 */ 2149 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2150 continue; 2151 } 2152 2153 /* 2154 * If the package is scanned, it's not erased. 2155 */ 2156 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2157 if (scannedPkg != null) { 2158 /* 2159 * If the system app is both scanned and in the 2160 * disabled packages list, then it must have been 2161 * added via OTA. Remove it from the currently 2162 * scanned package so the previously user-installed 2163 * application can be scanned. 2164 */ 2165 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2166 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2167 + ps.name + "; removing system app. Last known codePath=" 2168 + ps.codePathString + ", installStatus=" + ps.installStatus 2169 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2170 + scannedPkg.mVersionCode); 2171 removePackageLI(ps, true); 2172 mExpectingBetter.put(ps.name, ps.codePath); 2173 } 2174 2175 continue; 2176 } 2177 2178 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2179 psit.remove(); 2180 logCriticalInfo(Log.WARN, "System package " + ps.name 2181 + " no longer exists; wiping its data"); 2182 removeDataDirsLI(null, ps.name); 2183 } else { 2184 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2185 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2186 possiblyDeletedUpdatedSystemApps.add(ps.name); 2187 } 2188 } 2189 } 2190 } 2191 2192 //look for any incomplete package installations 2193 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2194 //clean up list 2195 for(int i = 0; i < deletePkgsList.size(); i++) { 2196 //clean up here 2197 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2198 } 2199 //delete tmp files 2200 deleteTempPackageFiles(); 2201 2202 // Remove any shared userIDs that have no associated packages 2203 mSettings.pruneSharedUsersLPw(); 2204 2205 if (!mOnlyCore) { 2206 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2207 SystemClock.uptimeMillis()); 2208 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2209 2210 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2211 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2212 2213 /** 2214 * Remove disable package settings for any updated system 2215 * apps that were removed via an OTA. If they're not a 2216 * previously-updated app, remove them completely. 2217 * Otherwise, just revoke their system-level permissions. 2218 */ 2219 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2220 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2221 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2222 2223 String msg; 2224 if (deletedPkg == null) { 2225 msg = "Updated system package " + deletedAppName 2226 + " no longer exists; wiping its data"; 2227 removeDataDirsLI(null, deletedAppName); 2228 } else { 2229 msg = "Updated system app + " + deletedAppName 2230 + " no longer present; removing system privileges for " 2231 + deletedAppName; 2232 2233 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2234 2235 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2236 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2237 } 2238 logCriticalInfo(Log.WARN, msg); 2239 } 2240 2241 /** 2242 * Make sure all system apps that we expected to appear on 2243 * the userdata partition actually showed up. If they never 2244 * appeared, crawl back and revive the system version. 2245 */ 2246 for (int i = 0; i < mExpectingBetter.size(); i++) { 2247 final String packageName = mExpectingBetter.keyAt(i); 2248 if (!mPackages.containsKey(packageName)) { 2249 final File scanFile = mExpectingBetter.valueAt(i); 2250 2251 logCriticalInfo(Log.WARN, "Expected better " + packageName 2252 + " but never showed up; reverting to system"); 2253 2254 final int reparseFlags; 2255 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2256 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2257 | PackageParser.PARSE_IS_SYSTEM_DIR 2258 | PackageParser.PARSE_IS_PRIVILEGED; 2259 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2260 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2261 | PackageParser.PARSE_IS_SYSTEM_DIR; 2262 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2263 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2264 | PackageParser.PARSE_IS_SYSTEM_DIR; 2265 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2266 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2267 | PackageParser.PARSE_IS_SYSTEM_DIR; 2268 } else { 2269 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2270 continue; 2271 } 2272 2273 mSettings.enableSystemPackageLPw(packageName); 2274 2275 try { 2276 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2277 } catch (PackageManagerException e) { 2278 Slog.e(TAG, "Failed to parse original system package: " 2279 + e.getMessage()); 2280 } 2281 } 2282 } 2283 } 2284 mExpectingBetter.clear(); 2285 2286 // Now that we know all of the shared libraries, update all clients to have 2287 // the correct library paths. 2288 updateAllSharedLibrariesLPw(); 2289 2290 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2291 // NOTE: We ignore potential failures here during a system scan (like 2292 // the rest of the commands above) because there's precious little we 2293 // can do about it. A settings error is reported, though. 2294 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2295 false /* force dexopt */, false /* defer dexopt */); 2296 } 2297 2298 // Now that we know all the packages we are keeping, 2299 // read and update their last usage times. 2300 mPackageUsage.readLP(); 2301 2302 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2303 SystemClock.uptimeMillis()); 2304 Slog.i(TAG, "Time to scan packages: " 2305 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2306 + " seconds"); 2307 2308 // If the platform SDK has changed since the last time we booted, 2309 // we need to re-grant app permission to catch any new ones that 2310 // appear. This is really a hack, and means that apps can in some 2311 // cases get permissions that the user didn't initially explicitly 2312 // allow... it would be nice to have some better way to handle 2313 // this situation. 2314 int updateFlags = UPDATE_PERMISSIONS_ALL; 2315 if (ver.sdkVersion != mSdkVersion) { 2316 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2317 + mSdkVersion + "; regranting permissions for internal storage"); 2318 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2319 } 2320 updatePermissionsLPw(null, null, updateFlags); 2321 ver.sdkVersion = mSdkVersion; 2322 2323 // If this is the first boot or an update from pre-M, and it is a normal 2324 // boot, then we need to initialize the default preferred apps across 2325 // all defined users. 2326 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2327 for (UserInfo user : sUserManager.getUsers(true)) { 2328 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2329 applyFactoryDefaultBrowserLPw(user.id); 2330 primeDomainVerificationsLPw(user.id); 2331 } 2332 } 2333 2334 // If this is first boot after an OTA, and a normal boot, then 2335 // we need to clear code cache directories. 2336 if (mIsUpgrade && !onlyCore) { 2337 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2338 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2339 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2340 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2341 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2342 } 2343 } 2344 ver.fingerprint = Build.FINGERPRINT; 2345 } 2346 2347 checkDefaultBrowser(); 2348 2349 // clear only after permissions and other defaults have been updated 2350 mExistingSystemPackages.clear(); 2351 mPromoteSystemApps = false; 2352 2353 // All the changes are done during package scanning. 2354 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2355 2356 // can downgrade to reader 2357 mSettings.writeLPr(); 2358 2359 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2360 SystemClock.uptimeMillis()); 2361 2362 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2363 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2364 2365 mInstallerService = new PackageInstallerService(context, this); 2366 2367 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2368 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2369 mIntentFilterVerifierComponent); 2370 2371 } // synchronized (mPackages) 2372 } // synchronized (mInstallLock) 2373 2374 // Now after opening every single application zip, make sure they 2375 // are all flushed. Not really needed, but keeps things nice and 2376 // tidy. 2377 Runtime.getRuntime().gc(); 2378 2379 // Expose private service for system components to use. 2380 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2381 } 2382 2383 @Override 2384 public boolean isFirstBoot() { 2385 return !mRestoredSettings; 2386 } 2387 2388 @Override 2389 public boolean isOnlyCoreApps() { 2390 return mOnlyCore; 2391 } 2392 2393 @Override 2394 public boolean isUpgrade() { 2395 return mIsUpgrade; 2396 } 2397 2398 private String getRequiredVerifierLPr() { 2399 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2400 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2401 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2402 2403 String requiredVerifier = null; 2404 2405 final int N = receivers.size(); 2406 for (int i = 0; i < N; i++) { 2407 final ResolveInfo info = receivers.get(i); 2408 2409 if (info.activityInfo == null) { 2410 continue; 2411 } 2412 2413 final String packageName = info.activityInfo.packageName; 2414 2415 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2416 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2417 continue; 2418 } 2419 2420 if (requiredVerifier != null) { 2421 throw new RuntimeException("There can be only one required verifier"); 2422 } 2423 2424 requiredVerifier = packageName; 2425 } 2426 2427 return requiredVerifier; 2428 } 2429 2430 private String getRequiredInstallerLPr() { 2431 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2432 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2433 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2434 2435 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2436 PACKAGE_MIME_TYPE, 0, 0); 2437 2438 String requiredInstaller = null; 2439 2440 final int N = installers.size(); 2441 for (int i = 0; i < N; i++) { 2442 final ResolveInfo info = installers.get(i); 2443 final String packageName = info.activityInfo.packageName; 2444 2445 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2446 continue; 2447 } 2448 2449 if (requiredInstaller != null) { 2450 throw new RuntimeException("There must be one required installer"); 2451 } 2452 2453 requiredInstaller = packageName; 2454 } 2455 2456 if (requiredInstaller == null) { 2457 throw new RuntimeException("There must be one required installer"); 2458 } 2459 2460 return requiredInstaller; 2461 } 2462 2463 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2464 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2465 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2466 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2467 2468 ComponentName verifierComponentName = null; 2469 2470 int priority = -1000; 2471 final int N = receivers.size(); 2472 for (int i = 0; i < N; i++) { 2473 final ResolveInfo info = receivers.get(i); 2474 2475 if (info.activityInfo == null) { 2476 continue; 2477 } 2478 2479 final String packageName = info.activityInfo.packageName; 2480 2481 final PackageSetting ps = mSettings.mPackages.get(packageName); 2482 if (ps == null) { 2483 continue; 2484 } 2485 2486 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2487 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2488 continue; 2489 } 2490 2491 // Select the IntentFilterVerifier with the highest priority 2492 if (priority < info.priority) { 2493 priority = info.priority; 2494 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2495 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2496 + verifierComponentName + " with priority: " + info.priority); 2497 } 2498 } 2499 2500 return verifierComponentName; 2501 } 2502 2503 private void primeDomainVerificationsLPw(int userId) { 2504 if (DEBUG_DOMAIN_VERIFICATION) { 2505 Slog.d(TAG, "Priming domain verifications in user " + userId); 2506 } 2507 2508 SystemConfig systemConfig = SystemConfig.getInstance(); 2509 ArraySet<String> packages = systemConfig.getLinkedApps(); 2510 ArraySet<String> domains = new ArraySet<String>(); 2511 2512 for (String packageName : packages) { 2513 PackageParser.Package pkg = mPackages.get(packageName); 2514 if (pkg != null) { 2515 if (!pkg.isSystemApp()) { 2516 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2517 continue; 2518 } 2519 2520 domains.clear(); 2521 for (PackageParser.Activity a : pkg.activities) { 2522 for (ActivityIntentInfo filter : a.intents) { 2523 if (hasValidDomains(filter)) { 2524 domains.addAll(filter.getHostsList()); 2525 } 2526 } 2527 } 2528 2529 if (domains.size() > 0) { 2530 if (DEBUG_DOMAIN_VERIFICATION) { 2531 Slog.v(TAG, " + " + packageName); 2532 } 2533 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2534 // state w.r.t. the formal app-linkage "no verification attempted" state; 2535 // and then 'always' in the per-user state actually used for intent resolution. 2536 final IntentFilterVerificationInfo ivi; 2537 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2538 new ArrayList<String>(domains)); 2539 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2540 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2541 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2542 } else { 2543 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2544 + "' does not handle web links"); 2545 } 2546 } else { 2547 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2548 } 2549 } 2550 2551 scheduleWritePackageRestrictionsLocked(userId); 2552 scheduleWriteSettingsLocked(); 2553 } 2554 2555 private void applyFactoryDefaultBrowserLPw(int userId) { 2556 // The default browser app's package name is stored in a string resource, 2557 // with a product-specific overlay used for vendor customization. 2558 String browserPkg = mContext.getResources().getString( 2559 com.android.internal.R.string.default_browser); 2560 if (!TextUtils.isEmpty(browserPkg)) { 2561 // non-empty string => required to be a known package 2562 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2563 if (ps == null) { 2564 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2565 browserPkg = null; 2566 } else { 2567 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2568 } 2569 } 2570 2571 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2572 // default. If there's more than one, just leave everything alone. 2573 if (browserPkg == null) { 2574 calculateDefaultBrowserLPw(userId); 2575 } 2576 } 2577 2578 private void calculateDefaultBrowserLPw(int userId) { 2579 List<String> allBrowsers = resolveAllBrowserApps(userId); 2580 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2581 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2582 } 2583 2584 private List<String> resolveAllBrowserApps(int userId) { 2585 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2586 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2587 PackageManager.MATCH_ALL, userId); 2588 2589 final int count = list.size(); 2590 List<String> result = new ArrayList<String>(count); 2591 for (int i=0; i<count; i++) { 2592 ResolveInfo info = list.get(i); 2593 if (info.activityInfo == null 2594 || !info.handleAllWebDataURI 2595 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2596 || result.contains(info.activityInfo.packageName)) { 2597 continue; 2598 } 2599 result.add(info.activityInfo.packageName); 2600 } 2601 2602 return result; 2603 } 2604 2605 private boolean packageIsBrowser(String packageName, int userId) { 2606 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2607 PackageManager.MATCH_ALL, userId); 2608 final int N = list.size(); 2609 for (int i = 0; i < N; i++) { 2610 ResolveInfo info = list.get(i); 2611 if (packageName.equals(info.activityInfo.packageName)) { 2612 return true; 2613 } 2614 } 2615 return false; 2616 } 2617 2618 private void checkDefaultBrowser() { 2619 final int myUserId = UserHandle.myUserId(); 2620 final String packageName = getDefaultBrowserPackageName(myUserId); 2621 if (packageName != null) { 2622 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2623 if (info == null) { 2624 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2625 synchronized (mPackages) { 2626 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2627 } 2628 } 2629 } 2630 } 2631 2632 @Override 2633 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2634 throws RemoteException { 2635 try { 2636 return super.onTransact(code, data, reply, flags); 2637 } catch (RuntimeException e) { 2638 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2639 Slog.wtf(TAG, "Package Manager Crash", e); 2640 } 2641 throw e; 2642 } 2643 } 2644 2645 void cleanupInstallFailedPackage(PackageSetting ps) { 2646 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2647 2648 removeDataDirsLI(ps.volumeUuid, ps.name); 2649 if (ps.codePath != null) { 2650 if (ps.codePath.isDirectory()) { 2651 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2652 } else { 2653 ps.codePath.delete(); 2654 } 2655 } 2656 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2657 if (ps.resourcePath.isDirectory()) { 2658 FileUtils.deleteContents(ps.resourcePath); 2659 } 2660 ps.resourcePath.delete(); 2661 } 2662 mSettings.removePackageLPw(ps.name); 2663 } 2664 2665 static int[] appendInts(int[] cur, int[] add) { 2666 if (add == null) return cur; 2667 if (cur == null) return add; 2668 final int N = add.length; 2669 for (int i=0; i<N; i++) { 2670 cur = appendInt(cur, add[i]); 2671 } 2672 return cur; 2673 } 2674 2675 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2676 if (!sUserManager.exists(userId)) return null; 2677 final PackageSetting ps = (PackageSetting) p.mExtras; 2678 if (ps == null) { 2679 return null; 2680 } 2681 2682 final PermissionsState permissionsState = ps.getPermissionsState(); 2683 2684 final int[] gids = permissionsState.computeGids(userId); 2685 final Set<String> permissions = permissionsState.getPermissions(userId); 2686 final PackageUserState state = ps.readUserState(userId); 2687 2688 return PackageParser.generatePackageInfo(p, gids, flags, 2689 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2690 } 2691 2692 @Override 2693 public boolean isPackageFrozen(String packageName) { 2694 synchronized (mPackages) { 2695 final PackageSetting ps = mSettings.mPackages.get(packageName); 2696 if (ps != null) { 2697 return ps.frozen; 2698 } 2699 } 2700 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2701 return true; 2702 } 2703 2704 @Override 2705 public boolean isPackageAvailable(String packageName, int userId) { 2706 if (!sUserManager.exists(userId)) return false; 2707 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2708 synchronized (mPackages) { 2709 PackageParser.Package p = mPackages.get(packageName); 2710 if (p != null) { 2711 final PackageSetting ps = (PackageSetting) p.mExtras; 2712 if (ps != null) { 2713 final PackageUserState state = ps.readUserState(userId); 2714 if (state != null) { 2715 return PackageParser.isAvailable(state); 2716 } 2717 } 2718 } 2719 } 2720 return false; 2721 } 2722 2723 @Override 2724 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2725 if (!sUserManager.exists(userId)) return null; 2726 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2727 // reader 2728 synchronized (mPackages) { 2729 PackageParser.Package p = mPackages.get(packageName); 2730 if (DEBUG_PACKAGE_INFO) 2731 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2732 if (p != null) { 2733 return generatePackageInfo(p, flags, userId); 2734 } 2735 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2736 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2737 } 2738 } 2739 return null; 2740 } 2741 2742 @Override 2743 public String[] currentToCanonicalPackageNames(String[] names) { 2744 String[] out = new String[names.length]; 2745 // reader 2746 synchronized (mPackages) { 2747 for (int i=names.length-1; i>=0; i--) { 2748 PackageSetting ps = mSettings.mPackages.get(names[i]); 2749 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2750 } 2751 } 2752 return out; 2753 } 2754 2755 @Override 2756 public String[] canonicalToCurrentPackageNames(String[] names) { 2757 String[] out = new String[names.length]; 2758 // reader 2759 synchronized (mPackages) { 2760 for (int i=names.length-1; i>=0; i--) { 2761 String cur = mSettings.mRenamedPackages.get(names[i]); 2762 out[i] = cur != null ? cur : names[i]; 2763 } 2764 } 2765 return out; 2766 } 2767 2768 @Override 2769 public int getPackageUid(String packageName, int userId) { 2770 if (!sUserManager.exists(userId)) return -1; 2771 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2772 2773 // reader 2774 synchronized (mPackages) { 2775 PackageParser.Package p = mPackages.get(packageName); 2776 if(p != null) { 2777 return UserHandle.getUid(userId, p.applicationInfo.uid); 2778 } 2779 PackageSetting ps = mSettings.mPackages.get(packageName); 2780 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2781 return -1; 2782 } 2783 p = ps.pkg; 2784 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2785 } 2786 } 2787 2788 @Override 2789 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2790 if (!sUserManager.exists(userId)) { 2791 return null; 2792 } 2793 2794 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2795 "getPackageGids"); 2796 2797 // reader 2798 synchronized (mPackages) { 2799 PackageParser.Package p = mPackages.get(packageName); 2800 if (DEBUG_PACKAGE_INFO) { 2801 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2802 } 2803 if (p != null) { 2804 PackageSetting ps = (PackageSetting) p.mExtras; 2805 return ps.getPermissionsState().computeGids(userId); 2806 } 2807 } 2808 2809 return null; 2810 } 2811 2812 static PermissionInfo generatePermissionInfo( 2813 BasePermission bp, int flags) { 2814 if (bp.perm != null) { 2815 return PackageParser.generatePermissionInfo(bp.perm, flags); 2816 } 2817 PermissionInfo pi = new PermissionInfo(); 2818 pi.name = bp.name; 2819 pi.packageName = bp.sourcePackage; 2820 pi.nonLocalizedLabel = bp.name; 2821 pi.protectionLevel = bp.protectionLevel; 2822 return pi; 2823 } 2824 2825 @Override 2826 public PermissionInfo getPermissionInfo(String name, int flags) { 2827 // reader 2828 synchronized (mPackages) { 2829 final BasePermission p = mSettings.mPermissions.get(name); 2830 if (p != null) { 2831 return generatePermissionInfo(p, flags); 2832 } 2833 return null; 2834 } 2835 } 2836 2837 @Override 2838 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2839 // reader 2840 synchronized (mPackages) { 2841 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2842 for (BasePermission p : mSettings.mPermissions.values()) { 2843 if (group == null) { 2844 if (p.perm == null || p.perm.info.group == null) { 2845 out.add(generatePermissionInfo(p, flags)); 2846 } 2847 } else { 2848 if (p.perm != null && group.equals(p.perm.info.group)) { 2849 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2850 } 2851 } 2852 } 2853 2854 if (out.size() > 0) { 2855 return out; 2856 } 2857 return mPermissionGroups.containsKey(group) ? out : null; 2858 } 2859 } 2860 2861 @Override 2862 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2863 // reader 2864 synchronized (mPackages) { 2865 return PackageParser.generatePermissionGroupInfo( 2866 mPermissionGroups.get(name), flags); 2867 } 2868 } 2869 2870 @Override 2871 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2872 // reader 2873 synchronized (mPackages) { 2874 final int N = mPermissionGroups.size(); 2875 ArrayList<PermissionGroupInfo> out 2876 = new ArrayList<PermissionGroupInfo>(N); 2877 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2878 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2879 } 2880 return out; 2881 } 2882 } 2883 2884 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2885 int userId) { 2886 if (!sUserManager.exists(userId)) return null; 2887 PackageSetting ps = mSettings.mPackages.get(packageName); 2888 if (ps != null) { 2889 if (ps.pkg == null) { 2890 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2891 flags, userId); 2892 if (pInfo != null) { 2893 return pInfo.applicationInfo; 2894 } 2895 return null; 2896 } 2897 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2898 ps.readUserState(userId), userId); 2899 } 2900 return null; 2901 } 2902 2903 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2904 int userId) { 2905 if (!sUserManager.exists(userId)) return null; 2906 PackageSetting ps = mSettings.mPackages.get(packageName); 2907 if (ps != null) { 2908 PackageParser.Package pkg = ps.pkg; 2909 if (pkg == null) { 2910 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2911 return null; 2912 } 2913 // Only data remains, so we aren't worried about code paths 2914 pkg = new PackageParser.Package(packageName); 2915 pkg.applicationInfo.packageName = packageName; 2916 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2917 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2918 pkg.applicationInfo.dataDir = Environment 2919 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2920 .getAbsolutePath(); 2921 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2922 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2923 } 2924 return generatePackageInfo(pkg, flags, userId); 2925 } 2926 return null; 2927 } 2928 2929 @Override 2930 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2931 if (!sUserManager.exists(userId)) return null; 2932 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2933 // writer 2934 synchronized (mPackages) { 2935 PackageParser.Package p = mPackages.get(packageName); 2936 if (DEBUG_PACKAGE_INFO) Log.v( 2937 TAG, "getApplicationInfo " + packageName 2938 + ": " + p); 2939 if (p != null) { 2940 PackageSetting ps = mSettings.mPackages.get(packageName); 2941 if (ps == null) return null; 2942 // Note: isEnabledLP() does not apply here - always return info 2943 return PackageParser.generateApplicationInfo( 2944 p, flags, ps.readUserState(userId), userId); 2945 } 2946 if ("android".equals(packageName)||"system".equals(packageName)) { 2947 return mAndroidApplication; 2948 } 2949 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2950 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2951 } 2952 } 2953 return null; 2954 } 2955 2956 @Override 2957 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2958 final IPackageDataObserver observer) { 2959 mContext.enforceCallingOrSelfPermission( 2960 android.Manifest.permission.CLEAR_APP_CACHE, null); 2961 // Queue up an async operation since clearing cache may take a little while. 2962 mHandler.post(new Runnable() { 2963 public void run() { 2964 mHandler.removeCallbacks(this); 2965 int retCode = -1; 2966 synchronized (mInstallLock) { 2967 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2968 if (retCode < 0) { 2969 Slog.w(TAG, "Couldn't clear application caches"); 2970 } 2971 } 2972 if (observer != null) { 2973 try { 2974 observer.onRemoveCompleted(null, (retCode >= 0)); 2975 } catch (RemoteException e) { 2976 Slog.w(TAG, "RemoveException when invoking call back"); 2977 } 2978 } 2979 } 2980 }); 2981 } 2982 2983 @Override 2984 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2985 final IntentSender pi) { 2986 mContext.enforceCallingOrSelfPermission( 2987 android.Manifest.permission.CLEAR_APP_CACHE, null); 2988 // Queue up an async operation since clearing cache may take a little while. 2989 mHandler.post(new Runnable() { 2990 public void run() { 2991 mHandler.removeCallbacks(this); 2992 int retCode = -1; 2993 synchronized (mInstallLock) { 2994 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2995 if (retCode < 0) { 2996 Slog.w(TAG, "Couldn't clear application caches"); 2997 } 2998 } 2999 if(pi != null) { 3000 try { 3001 // Callback via pending intent 3002 int code = (retCode >= 0) ? 1 : 0; 3003 pi.sendIntent(null, code, null, 3004 null, null); 3005 } catch (SendIntentException e1) { 3006 Slog.i(TAG, "Failed to send pending intent"); 3007 } 3008 } 3009 } 3010 }); 3011 } 3012 3013 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3014 synchronized (mInstallLock) { 3015 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3016 throw new IOException("Failed to free enough space"); 3017 } 3018 } 3019 } 3020 3021 @Override 3022 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3023 if (!sUserManager.exists(userId)) return null; 3024 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3025 synchronized (mPackages) { 3026 PackageParser.Activity a = mActivities.mActivities.get(component); 3027 3028 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3029 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3030 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3031 if (ps == null) return null; 3032 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3033 userId); 3034 } 3035 if (mResolveComponentName.equals(component)) { 3036 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3037 new PackageUserState(), userId); 3038 } 3039 } 3040 return null; 3041 } 3042 3043 @Override 3044 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3045 String resolvedType) { 3046 synchronized (mPackages) { 3047 if (component.equals(mResolveComponentName)) { 3048 // The resolver supports EVERYTHING! 3049 return true; 3050 } 3051 PackageParser.Activity a = mActivities.mActivities.get(component); 3052 if (a == null) { 3053 return false; 3054 } 3055 for (int i=0; i<a.intents.size(); i++) { 3056 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3057 intent.getData(), intent.getCategories(), TAG) >= 0) { 3058 return true; 3059 } 3060 } 3061 return false; 3062 } 3063 } 3064 3065 @Override 3066 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3067 if (!sUserManager.exists(userId)) return null; 3068 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3069 synchronized (mPackages) { 3070 PackageParser.Activity a = mReceivers.mActivities.get(component); 3071 if (DEBUG_PACKAGE_INFO) Log.v( 3072 TAG, "getReceiverInfo " + component + ": " + a); 3073 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3074 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3075 if (ps == null) return null; 3076 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3077 userId); 3078 } 3079 } 3080 return null; 3081 } 3082 3083 @Override 3084 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3085 if (!sUserManager.exists(userId)) return null; 3086 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3087 synchronized (mPackages) { 3088 PackageParser.Service s = mServices.mServices.get(component); 3089 if (DEBUG_PACKAGE_INFO) Log.v( 3090 TAG, "getServiceInfo " + component + ": " + s); 3091 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3092 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3093 if (ps == null) return null; 3094 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3095 userId); 3096 } 3097 } 3098 return null; 3099 } 3100 3101 @Override 3102 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3103 if (!sUserManager.exists(userId)) return null; 3104 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3105 synchronized (mPackages) { 3106 PackageParser.Provider p = mProviders.mProviders.get(component); 3107 if (DEBUG_PACKAGE_INFO) Log.v( 3108 TAG, "getProviderInfo " + component + ": " + p); 3109 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3110 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3111 if (ps == null) return null; 3112 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3113 userId); 3114 } 3115 } 3116 return null; 3117 } 3118 3119 @Override 3120 public String[] getSystemSharedLibraryNames() { 3121 Set<String> libSet; 3122 synchronized (mPackages) { 3123 libSet = mSharedLibraries.keySet(); 3124 int size = libSet.size(); 3125 if (size > 0) { 3126 String[] libs = new String[size]; 3127 libSet.toArray(libs); 3128 return libs; 3129 } 3130 } 3131 return null; 3132 } 3133 3134 /** 3135 * @hide 3136 */ 3137 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3138 synchronized (mPackages) { 3139 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3140 if (lib != null && lib.apk != null) { 3141 return mPackages.get(lib.apk); 3142 } 3143 } 3144 return null; 3145 } 3146 3147 @Override 3148 public FeatureInfo[] getSystemAvailableFeatures() { 3149 Collection<FeatureInfo> featSet; 3150 synchronized (mPackages) { 3151 featSet = mAvailableFeatures.values(); 3152 int size = featSet.size(); 3153 if (size > 0) { 3154 FeatureInfo[] features = new FeatureInfo[size+1]; 3155 featSet.toArray(features); 3156 FeatureInfo fi = new FeatureInfo(); 3157 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3158 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3159 features[size] = fi; 3160 return features; 3161 } 3162 } 3163 return null; 3164 } 3165 3166 @Override 3167 public boolean hasSystemFeature(String name) { 3168 synchronized (mPackages) { 3169 return mAvailableFeatures.containsKey(name); 3170 } 3171 } 3172 3173 private void checkValidCaller(int uid, int userId) { 3174 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3175 return; 3176 3177 throw new SecurityException("Caller uid=" + uid 3178 + " is not privileged to communicate with user=" + userId); 3179 } 3180 3181 @Override 3182 public int checkPermission(String permName, String pkgName, int userId) { 3183 if (!sUserManager.exists(userId)) { 3184 return PackageManager.PERMISSION_DENIED; 3185 } 3186 3187 synchronized (mPackages) { 3188 final PackageParser.Package p = mPackages.get(pkgName); 3189 if (p != null && p.mExtras != null) { 3190 final PackageSetting ps = (PackageSetting) p.mExtras; 3191 final PermissionsState permissionsState = ps.getPermissionsState(); 3192 if (permissionsState.hasPermission(permName, userId)) { 3193 return PackageManager.PERMISSION_GRANTED; 3194 } 3195 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3196 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3197 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3198 return PackageManager.PERMISSION_GRANTED; 3199 } 3200 } 3201 } 3202 3203 return PackageManager.PERMISSION_DENIED; 3204 } 3205 3206 @Override 3207 public int checkUidPermission(String permName, int uid) { 3208 final int userId = UserHandle.getUserId(uid); 3209 3210 if (!sUserManager.exists(userId)) { 3211 return PackageManager.PERMISSION_DENIED; 3212 } 3213 3214 synchronized (mPackages) { 3215 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3216 if (obj != null) { 3217 final SettingBase ps = (SettingBase) obj; 3218 final PermissionsState permissionsState = ps.getPermissionsState(); 3219 if (permissionsState.hasPermission(permName, userId)) { 3220 return PackageManager.PERMISSION_GRANTED; 3221 } 3222 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3223 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3224 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3225 return PackageManager.PERMISSION_GRANTED; 3226 } 3227 } else { 3228 ArraySet<String> perms = mSystemPermissions.get(uid); 3229 if (perms != null) { 3230 if (perms.contains(permName)) { 3231 return PackageManager.PERMISSION_GRANTED; 3232 } 3233 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3234 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3235 return PackageManager.PERMISSION_GRANTED; 3236 } 3237 } 3238 } 3239 } 3240 3241 return PackageManager.PERMISSION_DENIED; 3242 } 3243 3244 @Override 3245 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3246 if (UserHandle.getCallingUserId() != userId) { 3247 mContext.enforceCallingPermission( 3248 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3249 "isPermissionRevokedByPolicy for user " + userId); 3250 } 3251 3252 if (checkPermission(permission, packageName, userId) 3253 == PackageManager.PERMISSION_GRANTED) { 3254 return false; 3255 } 3256 3257 final long identity = Binder.clearCallingIdentity(); 3258 try { 3259 final int flags = getPermissionFlags(permission, packageName, userId); 3260 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3261 } finally { 3262 Binder.restoreCallingIdentity(identity); 3263 } 3264 } 3265 3266 @Override 3267 public String getPermissionControllerPackageName() { 3268 synchronized (mPackages) { 3269 return mRequiredInstallerPackage; 3270 } 3271 } 3272 3273 /** 3274 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3275 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3276 * @param checkShell TODO(yamasani): 3277 * @param message the message to log on security exception 3278 */ 3279 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3280 boolean checkShell, String message) { 3281 if (userId < 0) { 3282 throw new IllegalArgumentException("Invalid userId " + userId); 3283 } 3284 if (checkShell) { 3285 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3286 } 3287 if (userId == UserHandle.getUserId(callingUid)) return; 3288 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3289 if (requireFullPermission) { 3290 mContext.enforceCallingOrSelfPermission( 3291 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3292 } else { 3293 try { 3294 mContext.enforceCallingOrSelfPermission( 3295 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3296 } catch (SecurityException se) { 3297 mContext.enforceCallingOrSelfPermission( 3298 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3299 } 3300 } 3301 } 3302 } 3303 3304 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3305 if (callingUid == Process.SHELL_UID) { 3306 if (userHandle >= 0 3307 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3308 throw new SecurityException("Shell does not have permission to access user " 3309 + userHandle); 3310 } else if (userHandle < 0) { 3311 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3312 + Debug.getCallers(3)); 3313 } 3314 } 3315 } 3316 3317 private BasePermission findPermissionTreeLP(String permName) { 3318 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3319 if (permName.startsWith(bp.name) && 3320 permName.length() > bp.name.length() && 3321 permName.charAt(bp.name.length()) == '.') { 3322 return bp; 3323 } 3324 } 3325 return null; 3326 } 3327 3328 private BasePermission checkPermissionTreeLP(String permName) { 3329 if (permName != null) { 3330 BasePermission bp = findPermissionTreeLP(permName); 3331 if (bp != null) { 3332 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3333 return bp; 3334 } 3335 throw new SecurityException("Calling uid " 3336 + Binder.getCallingUid() 3337 + " is not allowed to add to permission tree " 3338 + bp.name + " owned by uid " + bp.uid); 3339 } 3340 } 3341 throw new SecurityException("No permission tree found for " + permName); 3342 } 3343 3344 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3345 if (s1 == null) { 3346 return s2 == null; 3347 } 3348 if (s2 == null) { 3349 return false; 3350 } 3351 if (s1.getClass() != s2.getClass()) { 3352 return false; 3353 } 3354 return s1.equals(s2); 3355 } 3356 3357 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3358 if (pi1.icon != pi2.icon) return false; 3359 if (pi1.logo != pi2.logo) return false; 3360 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3361 if (!compareStrings(pi1.name, pi2.name)) return false; 3362 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3363 // We'll take care of setting this one. 3364 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3365 // These are not currently stored in settings. 3366 //if (!compareStrings(pi1.group, pi2.group)) return false; 3367 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3368 //if (pi1.labelRes != pi2.labelRes) return false; 3369 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3370 return true; 3371 } 3372 3373 int permissionInfoFootprint(PermissionInfo info) { 3374 int size = info.name.length(); 3375 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3376 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3377 return size; 3378 } 3379 3380 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3381 int size = 0; 3382 for (BasePermission perm : mSettings.mPermissions.values()) { 3383 if (perm.uid == tree.uid) { 3384 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3385 } 3386 } 3387 return size; 3388 } 3389 3390 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3391 // We calculate the max size of permissions defined by this uid and throw 3392 // if that plus the size of 'info' would exceed our stated maximum. 3393 if (tree.uid != Process.SYSTEM_UID) { 3394 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3395 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3396 throw new SecurityException("Permission tree size cap exceeded"); 3397 } 3398 } 3399 } 3400 3401 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3402 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3403 throw new SecurityException("Label must be specified in permission"); 3404 } 3405 BasePermission tree = checkPermissionTreeLP(info.name); 3406 BasePermission bp = mSettings.mPermissions.get(info.name); 3407 boolean added = bp == null; 3408 boolean changed = true; 3409 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3410 if (added) { 3411 enforcePermissionCapLocked(info, tree); 3412 bp = new BasePermission(info.name, tree.sourcePackage, 3413 BasePermission.TYPE_DYNAMIC); 3414 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3415 throw new SecurityException( 3416 "Not allowed to modify non-dynamic permission " 3417 + info.name); 3418 } else { 3419 if (bp.protectionLevel == fixedLevel 3420 && bp.perm.owner.equals(tree.perm.owner) 3421 && bp.uid == tree.uid 3422 && comparePermissionInfos(bp.perm.info, info)) { 3423 changed = false; 3424 } 3425 } 3426 bp.protectionLevel = fixedLevel; 3427 info = new PermissionInfo(info); 3428 info.protectionLevel = fixedLevel; 3429 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3430 bp.perm.info.packageName = tree.perm.info.packageName; 3431 bp.uid = tree.uid; 3432 if (added) { 3433 mSettings.mPermissions.put(info.name, bp); 3434 } 3435 if (changed) { 3436 if (!async) { 3437 mSettings.writeLPr(); 3438 } else { 3439 scheduleWriteSettingsLocked(); 3440 } 3441 } 3442 return added; 3443 } 3444 3445 @Override 3446 public boolean addPermission(PermissionInfo info) { 3447 synchronized (mPackages) { 3448 return addPermissionLocked(info, false); 3449 } 3450 } 3451 3452 @Override 3453 public boolean addPermissionAsync(PermissionInfo info) { 3454 synchronized (mPackages) { 3455 return addPermissionLocked(info, true); 3456 } 3457 } 3458 3459 @Override 3460 public void removePermission(String name) { 3461 synchronized (mPackages) { 3462 checkPermissionTreeLP(name); 3463 BasePermission bp = mSettings.mPermissions.get(name); 3464 if (bp != null) { 3465 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3466 throw new SecurityException( 3467 "Not allowed to modify non-dynamic permission " 3468 + name); 3469 } 3470 mSettings.mPermissions.remove(name); 3471 mSettings.writeLPr(); 3472 } 3473 } 3474 } 3475 3476 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3477 BasePermission bp) { 3478 int index = pkg.requestedPermissions.indexOf(bp.name); 3479 if (index == -1) { 3480 throw new SecurityException("Package " + pkg.packageName 3481 + " has not requested permission " + bp.name); 3482 } 3483 if (!bp.isRuntime() && !bp.isDevelopment()) { 3484 throw new SecurityException("Permission " + bp.name 3485 + " is not a changeable permission type"); 3486 } 3487 } 3488 3489 @Override 3490 public void grantRuntimePermission(String packageName, String name, final int userId) { 3491 if (!sUserManager.exists(userId)) { 3492 Log.e(TAG, "No such user:" + userId); 3493 return; 3494 } 3495 3496 mContext.enforceCallingOrSelfPermission( 3497 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3498 "grantRuntimePermission"); 3499 3500 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3501 "grantRuntimePermission"); 3502 3503 final int uid; 3504 final SettingBase sb; 3505 3506 synchronized (mPackages) { 3507 final PackageParser.Package pkg = mPackages.get(packageName); 3508 if (pkg == null) { 3509 throw new IllegalArgumentException("Unknown package: " + packageName); 3510 } 3511 3512 final BasePermission bp = mSettings.mPermissions.get(name); 3513 if (bp == null) { 3514 throw new IllegalArgumentException("Unknown permission: " + name); 3515 } 3516 3517 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3518 3519 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3520 sb = (SettingBase) pkg.mExtras; 3521 if (sb == null) { 3522 throw new IllegalArgumentException("Unknown package: " + packageName); 3523 } 3524 3525 final PermissionsState permissionsState = sb.getPermissionsState(); 3526 3527 final int flags = permissionsState.getPermissionFlags(name, userId); 3528 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3529 throw new SecurityException("Cannot grant system fixed permission: " 3530 + name + " for package: " + packageName); 3531 } 3532 3533 if (bp.isDevelopment()) { 3534 // Development permissions must be handled specially, since they are not 3535 // normal runtime permissions. For now they apply to all users. 3536 if (permissionsState.grantInstallPermission(bp) != 3537 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3538 scheduleWriteSettingsLocked(); 3539 } 3540 return; 3541 } 3542 3543 final int result = permissionsState.grantRuntimePermission(bp, userId); 3544 switch (result) { 3545 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3546 return; 3547 } 3548 3549 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3550 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3551 mHandler.post(new Runnable() { 3552 @Override 3553 public void run() { 3554 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3555 } 3556 }); 3557 } break; 3558 } 3559 3560 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3561 3562 // Not critical if that is lost - app has to request again. 3563 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3564 } 3565 3566 // Only need to do this if user is initialized. Otherwise it's a new user 3567 // and there are no processes running as the user yet and there's no need 3568 // to make an expensive call to remount processes for the changed permissions. 3569 if (READ_EXTERNAL_STORAGE.equals(name) 3570 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3571 final long token = Binder.clearCallingIdentity(); 3572 try { 3573 if (sUserManager.isInitialized(userId)) { 3574 MountServiceInternal mountServiceInternal = LocalServices.getService( 3575 MountServiceInternal.class); 3576 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3577 } 3578 } finally { 3579 Binder.restoreCallingIdentity(token); 3580 } 3581 } 3582 } 3583 3584 @Override 3585 public void revokeRuntimePermission(String packageName, String name, int userId) { 3586 if (!sUserManager.exists(userId)) { 3587 Log.e(TAG, "No such user:" + userId); 3588 return; 3589 } 3590 3591 mContext.enforceCallingOrSelfPermission( 3592 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3593 "revokeRuntimePermission"); 3594 3595 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3596 "revokeRuntimePermission"); 3597 3598 final int appId; 3599 3600 synchronized (mPackages) { 3601 final PackageParser.Package pkg = mPackages.get(packageName); 3602 if (pkg == null) { 3603 throw new IllegalArgumentException("Unknown package: " + packageName); 3604 } 3605 3606 final BasePermission bp = mSettings.mPermissions.get(name); 3607 if (bp == null) { 3608 throw new IllegalArgumentException("Unknown permission: " + name); 3609 } 3610 3611 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3612 3613 SettingBase sb = (SettingBase) pkg.mExtras; 3614 if (sb == null) { 3615 throw new IllegalArgumentException("Unknown package: " + packageName); 3616 } 3617 3618 final PermissionsState permissionsState = sb.getPermissionsState(); 3619 3620 final int flags = permissionsState.getPermissionFlags(name, userId); 3621 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3622 throw new SecurityException("Cannot revoke system fixed permission: " 3623 + name + " for package: " + packageName); 3624 } 3625 3626 if (bp.isDevelopment()) { 3627 // Development permissions must be handled specially, since they are not 3628 // normal runtime permissions. For now they apply to all users. 3629 if (permissionsState.revokeInstallPermission(bp) != 3630 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3631 scheduleWriteSettingsLocked(); 3632 } 3633 return; 3634 } 3635 3636 if (permissionsState.revokeRuntimePermission(bp, userId) == 3637 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3638 return; 3639 } 3640 3641 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3642 3643 // Critical, after this call app should never have the permission. 3644 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3645 3646 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3647 } 3648 3649 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3650 } 3651 3652 @Override 3653 public void resetRuntimePermissions() { 3654 mContext.enforceCallingOrSelfPermission( 3655 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3656 "revokeRuntimePermission"); 3657 3658 int callingUid = Binder.getCallingUid(); 3659 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3660 mContext.enforceCallingOrSelfPermission( 3661 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3662 "resetRuntimePermissions"); 3663 } 3664 3665 synchronized (mPackages) { 3666 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3667 for (int userId : UserManagerService.getInstance().getUserIds()) { 3668 final int packageCount = mPackages.size(); 3669 for (int i = 0; i < packageCount; i++) { 3670 PackageParser.Package pkg = mPackages.valueAt(i); 3671 if (!(pkg.mExtras instanceof PackageSetting)) { 3672 continue; 3673 } 3674 PackageSetting ps = (PackageSetting) pkg.mExtras; 3675 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3676 } 3677 } 3678 } 3679 } 3680 3681 @Override 3682 public int getPermissionFlags(String name, String packageName, int userId) { 3683 if (!sUserManager.exists(userId)) { 3684 return 0; 3685 } 3686 3687 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3688 3689 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3690 "getPermissionFlags"); 3691 3692 synchronized (mPackages) { 3693 final PackageParser.Package pkg = mPackages.get(packageName); 3694 if (pkg == null) { 3695 throw new IllegalArgumentException("Unknown package: " + packageName); 3696 } 3697 3698 final BasePermission bp = mSettings.mPermissions.get(name); 3699 if (bp == null) { 3700 throw new IllegalArgumentException("Unknown permission: " + name); 3701 } 3702 3703 SettingBase sb = (SettingBase) pkg.mExtras; 3704 if (sb == null) { 3705 throw new IllegalArgumentException("Unknown package: " + packageName); 3706 } 3707 3708 PermissionsState permissionsState = sb.getPermissionsState(); 3709 return permissionsState.getPermissionFlags(name, userId); 3710 } 3711 } 3712 3713 @Override 3714 public void updatePermissionFlags(String name, String packageName, int flagMask, 3715 int flagValues, int userId) { 3716 if (!sUserManager.exists(userId)) { 3717 return; 3718 } 3719 3720 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3721 3722 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3723 "updatePermissionFlags"); 3724 3725 // Only the system can change these flags and nothing else. 3726 if (getCallingUid() != Process.SYSTEM_UID) { 3727 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3728 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3729 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3730 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3731 } 3732 3733 synchronized (mPackages) { 3734 final PackageParser.Package pkg = mPackages.get(packageName); 3735 if (pkg == null) { 3736 throw new IllegalArgumentException("Unknown package: " + packageName); 3737 } 3738 3739 final BasePermission bp = mSettings.mPermissions.get(name); 3740 if (bp == null) { 3741 throw new IllegalArgumentException("Unknown permission: " + name); 3742 } 3743 3744 SettingBase sb = (SettingBase) pkg.mExtras; 3745 if (sb == null) { 3746 throw new IllegalArgumentException("Unknown package: " + packageName); 3747 } 3748 3749 PermissionsState permissionsState = sb.getPermissionsState(); 3750 3751 // Only the package manager can change flags for system component permissions. 3752 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3753 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3754 return; 3755 } 3756 3757 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3758 3759 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3760 // Install and runtime permissions are stored in different places, 3761 // so figure out what permission changed and persist the change. 3762 if (permissionsState.getInstallPermissionState(name) != null) { 3763 scheduleWriteSettingsLocked(); 3764 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3765 || hadState) { 3766 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3767 } 3768 } 3769 } 3770 } 3771 3772 /** 3773 * Update the permission flags for all packages and runtime permissions of a user in order 3774 * to allow device or profile owner to remove POLICY_FIXED. 3775 */ 3776 @Override 3777 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3778 if (!sUserManager.exists(userId)) { 3779 return; 3780 } 3781 3782 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3783 3784 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3785 "updatePermissionFlagsForAllApps"); 3786 3787 // Only the system can change system fixed flags. 3788 if (getCallingUid() != Process.SYSTEM_UID) { 3789 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3790 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3791 } 3792 3793 synchronized (mPackages) { 3794 boolean changed = false; 3795 final int packageCount = mPackages.size(); 3796 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3797 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3798 SettingBase sb = (SettingBase) pkg.mExtras; 3799 if (sb == null) { 3800 continue; 3801 } 3802 PermissionsState permissionsState = sb.getPermissionsState(); 3803 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3804 userId, flagMask, flagValues); 3805 } 3806 if (changed) { 3807 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3808 } 3809 } 3810 } 3811 3812 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3813 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3814 != PackageManager.PERMISSION_GRANTED 3815 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3816 != PackageManager.PERMISSION_GRANTED) { 3817 throw new SecurityException(message + " requires " 3818 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3819 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3820 } 3821 } 3822 3823 @Override 3824 public boolean shouldShowRequestPermissionRationale(String permissionName, 3825 String packageName, int userId) { 3826 if (UserHandle.getCallingUserId() != userId) { 3827 mContext.enforceCallingPermission( 3828 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3829 "canShowRequestPermissionRationale for user " + userId); 3830 } 3831 3832 final int uid = getPackageUid(packageName, userId); 3833 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3834 return false; 3835 } 3836 3837 if (checkPermission(permissionName, packageName, userId) 3838 == PackageManager.PERMISSION_GRANTED) { 3839 return false; 3840 } 3841 3842 final int flags; 3843 3844 final long identity = Binder.clearCallingIdentity(); 3845 try { 3846 flags = getPermissionFlags(permissionName, 3847 packageName, userId); 3848 } finally { 3849 Binder.restoreCallingIdentity(identity); 3850 } 3851 3852 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3853 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3854 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3855 3856 if ((flags & fixedFlags) != 0) { 3857 return false; 3858 } 3859 3860 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3861 } 3862 3863 @Override 3864 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3865 mContext.enforceCallingOrSelfPermission( 3866 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3867 "addOnPermissionsChangeListener"); 3868 3869 synchronized (mPackages) { 3870 mOnPermissionChangeListeners.addListenerLocked(listener); 3871 } 3872 } 3873 3874 @Override 3875 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3876 synchronized (mPackages) { 3877 mOnPermissionChangeListeners.removeListenerLocked(listener); 3878 } 3879 } 3880 3881 @Override 3882 public boolean isProtectedBroadcast(String actionName) { 3883 synchronized (mPackages) { 3884 return mProtectedBroadcasts.contains(actionName); 3885 } 3886 } 3887 3888 @Override 3889 public int checkSignatures(String pkg1, String pkg2) { 3890 synchronized (mPackages) { 3891 final PackageParser.Package p1 = mPackages.get(pkg1); 3892 final PackageParser.Package p2 = mPackages.get(pkg2); 3893 if (p1 == null || p1.mExtras == null 3894 || p2 == null || p2.mExtras == null) { 3895 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3896 } 3897 return compareSignatures(p1.mSignatures, p2.mSignatures); 3898 } 3899 } 3900 3901 @Override 3902 public int checkUidSignatures(int uid1, int uid2) { 3903 // Map to base uids. 3904 uid1 = UserHandle.getAppId(uid1); 3905 uid2 = UserHandle.getAppId(uid2); 3906 // reader 3907 synchronized (mPackages) { 3908 Signature[] s1; 3909 Signature[] s2; 3910 Object obj = mSettings.getUserIdLPr(uid1); 3911 if (obj != null) { 3912 if (obj instanceof SharedUserSetting) { 3913 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3914 } else if (obj instanceof PackageSetting) { 3915 s1 = ((PackageSetting)obj).signatures.mSignatures; 3916 } else { 3917 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3918 } 3919 } else { 3920 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3921 } 3922 obj = mSettings.getUserIdLPr(uid2); 3923 if (obj != null) { 3924 if (obj instanceof SharedUserSetting) { 3925 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3926 } else if (obj instanceof PackageSetting) { 3927 s2 = ((PackageSetting)obj).signatures.mSignatures; 3928 } else { 3929 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3930 } 3931 } else { 3932 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3933 } 3934 return compareSignatures(s1, s2); 3935 } 3936 } 3937 3938 private void killUid(int appId, int userId, String reason) { 3939 final long identity = Binder.clearCallingIdentity(); 3940 try { 3941 IActivityManager am = ActivityManagerNative.getDefault(); 3942 if (am != null) { 3943 try { 3944 am.killUid(appId, userId, reason); 3945 } catch (RemoteException e) { 3946 /* ignore - same process */ 3947 } 3948 } 3949 } finally { 3950 Binder.restoreCallingIdentity(identity); 3951 } 3952 } 3953 3954 /** 3955 * Compares two sets of signatures. Returns: 3956 * <br /> 3957 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3958 * <br /> 3959 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3960 * <br /> 3961 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3962 * <br /> 3963 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3964 * <br /> 3965 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3966 */ 3967 static int compareSignatures(Signature[] s1, Signature[] s2) { 3968 if (s1 == null) { 3969 return s2 == null 3970 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3971 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3972 } 3973 3974 if (s2 == null) { 3975 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3976 } 3977 3978 if (s1.length != s2.length) { 3979 return PackageManager.SIGNATURE_NO_MATCH; 3980 } 3981 3982 // Since both signature sets are of size 1, we can compare without HashSets. 3983 if (s1.length == 1) { 3984 return s1[0].equals(s2[0]) ? 3985 PackageManager.SIGNATURE_MATCH : 3986 PackageManager.SIGNATURE_NO_MATCH; 3987 } 3988 3989 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3990 for (Signature sig : s1) { 3991 set1.add(sig); 3992 } 3993 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3994 for (Signature sig : s2) { 3995 set2.add(sig); 3996 } 3997 // Make sure s2 contains all signatures in s1. 3998 if (set1.equals(set2)) { 3999 return PackageManager.SIGNATURE_MATCH; 4000 } 4001 return PackageManager.SIGNATURE_NO_MATCH; 4002 } 4003 4004 /** 4005 * If the database version for this type of package (internal storage or 4006 * external storage) is less than the version where package signatures 4007 * were updated, return true. 4008 */ 4009 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4010 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4011 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4012 } 4013 4014 /** 4015 * Used for backward compatibility to make sure any packages with 4016 * certificate chains get upgraded to the new style. {@code existingSigs} 4017 * will be in the old format (since they were stored on disk from before the 4018 * system upgrade) and {@code scannedSigs} will be in the newer format. 4019 */ 4020 private int compareSignaturesCompat(PackageSignatures existingSigs, 4021 PackageParser.Package scannedPkg) { 4022 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4023 return PackageManager.SIGNATURE_NO_MATCH; 4024 } 4025 4026 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4027 for (Signature sig : existingSigs.mSignatures) { 4028 existingSet.add(sig); 4029 } 4030 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4031 for (Signature sig : scannedPkg.mSignatures) { 4032 try { 4033 Signature[] chainSignatures = sig.getChainSignatures(); 4034 for (Signature chainSig : chainSignatures) { 4035 scannedCompatSet.add(chainSig); 4036 } 4037 } catch (CertificateEncodingException e) { 4038 scannedCompatSet.add(sig); 4039 } 4040 } 4041 /* 4042 * Make sure the expanded scanned set contains all signatures in the 4043 * existing one. 4044 */ 4045 if (scannedCompatSet.equals(existingSet)) { 4046 // Migrate the old signatures to the new scheme. 4047 existingSigs.assignSignatures(scannedPkg.mSignatures); 4048 // The new KeySets will be re-added later in the scanning process. 4049 synchronized (mPackages) { 4050 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4051 } 4052 return PackageManager.SIGNATURE_MATCH; 4053 } 4054 return PackageManager.SIGNATURE_NO_MATCH; 4055 } 4056 4057 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4058 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4059 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4060 } 4061 4062 private int compareSignaturesRecover(PackageSignatures existingSigs, 4063 PackageParser.Package scannedPkg) { 4064 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4065 return PackageManager.SIGNATURE_NO_MATCH; 4066 } 4067 4068 String msg = null; 4069 try { 4070 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4071 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4072 + scannedPkg.packageName); 4073 return PackageManager.SIGNATURE_MATCH; 4074 } 4075 } catch (CertificateException e) { 4076 msg = e.getMessage(); 4077 } 4078 4079 logCriticalInfo(Log.INFO, 4080 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4081 return PackageManager.SIGNATURE_NO_MATCH; 4082 } 4083 4084 @Override 4085 public String[] getPackagesForUid(int uid) { 4086 uid = UserHandle.getAppId(uid); 4087 // reader 4088 synchronized (mPackages) { 4089 Object obj = mSettings.getUserIdLPr(uid); 4090 if (obj instanceof SharedUserSetting) { 4091 final SharedUserSetting sus = (SharedUserSetting) obj; 4092 final int N = sus.packages.size(); 4093 final String[] res = new String[N]; 4094 final Iterator<PackageSetting> it = sus.packages.iterator(); 4095 int i = 0; 4096 while (it.hasNext()) { 4097 res[i++] = it.next().name; 4098 } 4099 return res; 4100 } else if (obj instanceof PackageSetting) { 4101 final PackageSetting ps = (PackageSetting) obj; 4102 return new String[] { ps.name }; 4103 } 4104 } 4105 return null; 4106 } 4107 4108 @Override 4109 public String getNameForUid(int uid) { 4110 // reader 4111 synchronized (mPackages) { 4112 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4113 if (obj instanceof SharedUserSetting) { 4114 final SharedUserSetting sus = (SharedUserSetting) obj; 4115 return sus.name + ":" + sus.userId; 4116 } else if (obj instanceof PackageSetting) { 4117 final PackageSetting ps = (PackageSetting) obj; 4118 return ps.name; 4119 } 4120 } 4121 return null; 4122 } 4123 4124 @Override 4125 public int getUidForSharedUser(String sharedUserName) { 4126 if(sharedUserName == null) { 4127 return -1; 4128 } 4129 // reader 4130 synchronized (mPackages) { 4131 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4132 if (suid == null) { 4133 return -1; 4134 } 4135 return suid.userId; 4136 } 4137 } 4138 4139 @Override 4140 public int getFlagsForUid(int uid) { 4141 synchronized (mPackages) { 4142 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4143 if (obj instanceof SharedUserSetting) { 4144 final SharedUserSetting sus = (SharedUserSetting) obj; 4145 return sus.pkgFlags; 4146 } else if (obj instanceof PackageSetting) { 4147 final PackageSetting ps = (PackageSetting) obj; 4148 return ps.pkgFlags; 4149 } 4150 } 4151 return 0; 4152 } 4153 4154 @Override 4155 public int getPrivateFlagsForUid(int uid) { 4156 synchronized (mPackages) { 4157 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4158 if (obj instanceof SharedUserSetting) { 4159 final SharedUserSetting sus = (SharedUserSetting) obj; 4160 return sus.pkgPrivateFlags; 4161 } else if (obj instanceof PackageSetting) { 4162 final PackageSetting ps = (PackageSetting) obj; 4163 return ps.pkgPrivateFlags; 4164 } 4165 } 4166 return 0; 4167 } 4168 4169 @Override 4170 public boolean isUidPrivileged(int uid) { 4171 uid = UserHandle.getAppId(uid); 4172 // reader 4173 synchronized (mPackages) { 4174 Object obj = mSettings.getUserIdLPr(uid); 4175 if (obj instanceof SharedUserSetting) { 4176 final SharedUserSetting sus = (SharedUserSetting) obj; 4177 final Iterator<PackageSetting> it = sus.packages.iterator(); 4178 while (it.hasNext()) { 4179 if (it.next().isPrivileged()) { 4180 return true; 4181 } 4182 } 4183 } else if (obj instanceof PackageSetting) { 4184 final PackageSetting ps = (PackageSetting) obj; 4185 return ps.isPrivileged(); 4186 } 4187 } 4188 return false; 4189 } 4190 4191 @Override 4192 public String[] getAppOpPermissionPackages(String permissionName) { 4193 synchronized (mPackages) { 4194 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4195 if (pkgs == null) { 4196 return null; 4197 } 4198 return pkgs.toArray(new String[pkgs.size()]); 4199 } 4200 } 4201 4202 @Override 4203 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4204 int flags, int userId) { 4205 if (!sUserManager.exists(userId)) return null; 4206 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4207 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4208 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4209 } 4210 4211 @Override 4212 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4213 IntentFilter filter, int match, ComponentName activity) { 4214 final int userId = UserHandle.getCallingUserId(); 4215 if (DEBUG_PREFERRED) { 4216 Log.v(TAG, "setLastChosenActivity intent=" + intent 4217 + " resolvedType=" + resolvedType 4218 + " flags=" + flags 4219 + " filter=" + filter 4220 + " match=" + match 4221 + " activity=" + activity); 4222 filter.dump(new PrintStreamPrinter(System.out), " "); 4223 } 4224 intent.setComponent(null); 4225 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4226 // Find any earlier preferred or last chosen entries and nuke them 4227 findPreferredActivity(intent, resolvedType, 4228 flags, query, 0, false, true, false, userId); 4229 // Add the new activity as the last chosen for this filter 4230 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4231 "Setting last chosen"); 4232 } 4233 4234 @Override 4235 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4236 final int userId = UserHandle.getCallingUserId(); 4237 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4238 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4239 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4240 false, false, false, userId); 4241 } 4242 4243 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4244 int flags, List<ResolveInfo> query, int userId) { 4245 if (query != null) { 4246 final int N = query.size(); 4247 if (N == 1) { 4248 return query.get(0); 4249 } else if (N > 1) { 4250 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4251 // If there is more than one activity with the same priority, 4252 // then let the user decide between them. 4253 ResolveInfo r0 = query.get(0); 4254 ResolveInfo r1 = query.get(1); 4255 if (DEBUG_INTENT_MATCHING || debug) { 4256 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4257 + r1.activityInfo.name + "=" + r1.priority); 4258 } 4259 // If the first activity has a higher priority, or a different 4260 // default, then it is always desireable to pick it. 4261 if (r0.priority != r1.priority 4262 || r0.preferredOrder != r1.preferredOrder 4263 || r0.isDefault != r1.isDefault) { 4264 return query.get(0); 4265 } 4266 // If we have saved a preference for a preferred activity for 4267 // this Intent, use that. 4268 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4269 flags, query, r0.priority, true, false, debug, userId); 4270 if (ri != null) { 4271 return ri; 4272 } 4273 ri = new ResolveInfo(mResolveInfo); 4274 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4275 ri.activityInfo.applicationInfo = new ApplicationInfo( 4276 ri.activityInfo.applicationInfo); 4277 if (userId != 0) { 4278 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4279 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4280 } 4281 // Make sure that the resolver is displayable in car mode 4282 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4283 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4284 return ri; 4285 } 4286 } 4287 return null; 4288 } 4289 4290 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4291 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4292 final int N = query.size(); 4293 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4294 .get(userId); 4295 // Get the list of persistent preferred activities that handle the intent 4296 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4297 List<PersistentPreferredActivity> pprefs = ppir != null 4298 ? ppir.queryIntent(intent, resolvedType, 4299 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4300 : null; 4301 if (pprefs != null && pprefs.size() > 0) { 4302 final int M = pprefs.size(); 4303 for (int i=0; i<M; i++) { 4304 final PersistentPreferredActivity ppa = pprefs.get(i); 4305 if (DEBUG_PREFERRED || debug) { 4306 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4307 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4308 + "\n component=" + ppa.mComponent); 4309 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4310 } 4311 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4312 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4313 if (DEBUG_PREFERRED || debug) { 4314 Slog.v(TAG, "Found persistent preferred activity:"); 4315 if (ai != null) { 4316 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4317 } else { 4318 Slog.v(TAG, " null"); 4319 } 4320 } 4321 if (ai == null) { 4322 // This previously registered persistent preferred activity 4323 // component is no longer known. Ignore it and do NOT remove it. 4324 continue; 4325 } 4326 for (int j=0; j<N; j++) { 4327 final ResolveInfo ri = query.get(j); 4328 if (!ri.activityInfo.applicationInfo.packageName 4329 .equals(ai.applicationInfo.packageName)) { 4330 continue; 4331 } 4332 if (!ri.activityInfo.name.equals(ai.name)) { 4333 continue; 4334 } 4335 // Found a persistent preference that can handle the intent. 4336 if (DEBUG_PREFERRED || debug) { 4337 Slog.v(TAG, "Returning persistent preferred activity: " + 4338 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4339 } 4340 return ri; 4341 } 4342 } 4343 } 4344 return null; 4345 } 4346 4347 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4348 List<ResolveInfo> query, int priority, boolean always, 4349 boolean removeMatches, boolean debug, int userId) { 4350 if (!sUserManager.exists(userId)) return null; 4351 // writer 4352 synchronized (mPackages) { 4353 if (intent.getSelector() != null) { 4354 intent = intent.getSelector(); 4355 } 4356 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4357 4358 // Try to find a matching persistent preferred activity. 4359 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4360 debug, userId); 4361 4362 // If a persistent preferred activity matched, use it. 4363 if (pri != null) { 4364 return pri; 4365 } 4366 4367 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4368 // Get the list of preferred activities that handle the intent 4369 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4370 List<PreferredActivity> prefs = pir != null 4371 ? pir.queryIntent(intent, resolvedType, 4372 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4373 : null; 4374 if (prefs != null && prefs.size() > 0) { 4375 boolean changed = false; 4376 try { 4377 // First figure out how good the original match set is. 4378 // We will only allow preferred activities that came 4379 // from the same match quality. 4380 int match = 0; 4381 4382 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4383 4384 final int N = query.size(); 4385 for (int j=0; j<N; j++) { 4386 final ResolveInfo ri = query.get(j); 4387 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4388 + ": 0x" + Integer.toHexString(match)); 4389 if (ri.match > match) { 4390 match = ri.match; 4391 } 4392 } 4393 4394 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4395 + Integer.toHexString(match)); 4396 4397 match &= IntentFilter.MATCH_CATEGORY_MASK; 4398 final int M = prefs.size(); 4399 for (int i=0; i<M; i++) { 4400 final PreferredActivity pa = prefs.get(i); 4401 if (DEBUG_PREFERRED || debug) { 4402 Slog.v(TAG, "Checking PreferredActivity ds=" 4403 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4404 + "\n component=" + pa.mPref.mComponent); 4405 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4406 } 4407 if (pa.mPref.mMatch != match) { 4408 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4409 + Integer.toHexString(pa.mPref.mMatch)); 4410 continue; 4411 } 4412 // If it's not an "always" type preferred activity and that's what we're 4413 // looking for, skip it. 4414 if (always && !pa.mPref.mAlways) { 4415 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4416 continue; 4417 } 4418 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4419 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4420 if (DEBUG_PREFERRED || debug) { 4421 Slog.v(TAG, "Found preferred activity:"); 4422 if (ai != null) { 4423 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4424 } else { 4425 Slog.v(TAG, " null"); 4426 } 4427 } 4428 if (ai == null) { 4429 // This previously registered preferred activity 4430 // component is no longer known. Most likely an update 4431 // to the app was installed and in the new version this 4432 // component no longer exists. Clean it up by removing 4433 // it from the preferred activities list, and skip it. 4434 Slog.w(TAG, "Removing dangling preferred activity: " 4435 + pa.mPref.mComponent); 4436 pir.removeFilter(pa); 4437 changed = true; 4438 continue; 4439 } 4440 for (int j=0; j<N; j++) { 4441 final ResolveInfo ri = query.get(j); 4442 if (!ri.activityInfo.applicationInfo.packageName 4443 .equals(ai.applicationInfo.packageName)) { 4444 continue; 4445 } 4446 if (!ri.activityInfo.name.equals(ai.name)) { 4447 continue; 4448 } 4449 4450 if (removeMatches) { 4451 pir.removeFilter(pa); 4452 changed = true; 4453 if (DEBUG_PREFERRED) { 4454 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4455 } 4456 break; 4457 } 4458 4459 // Okay we found a previously set preferred or last chosen app. 4460 // If the result set is different from when this 4461 // was created, we need to clear it and re-ask the 4462 // user their preference, if we're looking for an "always" type entry. 4463 if (always && !pa.mPref.sameSet(query)) { 4464 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4465 + intent + " type " + resolvedType); 4466 if (DEBUG_PREFERRED) { 4467 Slog.v(TAG, "Removing preferred activity since set changed " 4468 + pa.mPref.mComponent); 4469 } 4470 pir.removeFilter(pa); 4471 // Re-add the filter as a "last chosen" entry (!always) 4472 PreferredActivity lastChosen = new PreferredActivity( 4473 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4474 pir.addFilter(lastChosen); 4475 changed = true; 4476 return null; 4477 } 4478 4479 // Yay! Either the set matched or we're looking for the last chosen 4480 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4481 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4482 return ri; 4483 } 4484 } 4485 } finally { 4486 if (changed) { 4487 if (DEBUG_PREFERRED) { 4488 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4489 } 4490 scheduleWritePackageRestrictionsLocked(userId); 4491 } 4492 } 4493 } 4494 } 4495 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4496 return null; 4497 } 4498 4499 /* 4500 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4501 */ 4502 @Override 4503 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4504 int targetUserId) { 4505 mContext.enforceCallingOrSelfPermission( 4506 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4507 List<CrossProfileIntentFilter> matches = 4508 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4509 if (matches != null) { 4510 int size = matches.size(); 4511 for (int i = 0; i < size; i++) { 4512 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4513 } 4514 } 4515 if (hasWebURI(intent)) { 4516 // cross-profile app linking works only towards the parent. 4517 final UserInfo parent = getProfileParent(sourceUserId); 4518 synchronized(mPackages) { 4519 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4520 intent, resolvedType, 0, sourceUserId, parent.id); 4521 return xpDomainInfo != null; 4522 } 4523 } 4524 return false; 4525 } 4526 4527 private UserInfo getProfileParent(int userId) { 4528 final long identity = Binder.clearCallingIdentity(); 4529 try { 4530 return sUserManager.getProfileParent(userId); 4531 } finally { 4532 Binder.restoreCallingIdentity(identity); 4533 } 4534 } 4535 4536 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4537 String resolvedType, int userId) { 4538 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4539 if (resolver != null) { 4540 return resolver.queryIntent(intent, resolvedType, false, userId); 4541 } 4542 return null; 4543 } 4544 4545 @Override 4546 public List<ResolveInfo> queryIntentActivities(Intent intent, 4547 String resolvedType, int flags, int userId) { 4548 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4549 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4550 ComponentName comp = intent.getComponent(); 4551 if (comp == null) { 4552 if (intent.getSelector() != null) { 4553 intent = intent.getSelector(); 4554 comp = intent.getComponent(); 4555 } 4556 } 4557 4558 if (comp != null) { 4559 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4560 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4561 if (ai != null) { 4562 final ResolveInfo ri = new ResolveInfo(); 4563 ri.activityInfo = ai; 4564 list.add(ri); 4565 } 4566 return list; 4567 } 4568 4569 // reader 4570 synchronized (mPackages) { 4571 final String pkgName = intent.getPackage(); 4572 if (pkgName == null) { 4573 List<CrossProfileIntentFilter> matchingFilters = 4574 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4575 // Check for results that need to skip the current profile. 4576 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4577 resolvedType, flags, userId); 4578 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4579 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4580 result.add(xpResolveInfo); 4581 return filterIfNotSystemUser(result, userId); 4582 } 4583 4584 // Check for results in the current profile. 4585 List<ResolveInfo> result = mActivities.queryIntent( 4586 intent, resolvedType, flags, userId); 4587 4588 // Check for cross profile results. 4589 xpResolveInfo = queryCrossProfileIntents( 4590 matchingFilters, intent, resolvedType, flags, userId); 4591 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4592 result.add(xpResolveInfo); 4593 Collections.sort(result, mResolvePrioritySorter); 4594 } 4595 result = filterIfNotSystemUser(result, userId); 4596 if (hasWebURI(intent)) { 4597 CrossProfileDomainInfo xpDomainInfo = null; 4598 final UserInfo parent = getProfileParent(userId); 4599 if (parent != null) { 4600 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4601 flags, userId, parent.id); 4602 } 4603 if (xpDomainInfo != null) { 4604 if (xpResolveInfo != null) { 4605 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4606 // in the result. 4607 result.remove(xpResolveInfo); 4608 } 4609 if (result.size() == 0) { 4610 result.add(xpDomainInfo.resolveInfo); 4611 return result; 4612 } 4613 } else if (result.size() <= 1) { 4614 return result; 4615 } 4616 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4617 xpDomainInfo, userId); 4618 Collections.sort(result, mResolvePrioritySorter); 4619 } 4620 return result; 4621 } 4622 final PackageParser.Package pkg = mPackages.get(pkgName); 4623 if (pkg != null) { 4624 return filterIfNotSystemUser( 4625 mActivities.queryIntentForPackage( 4626 intent, resolvedType, flags, pkg.activities, userId), 4627 userId); 4628 } 4629 return new ArrayList<ResolveInfo>(); 4630 } 4631 } 4632 4633 private static class CrossProfileDomainInfo { 4634 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4635 ResolveInfo resolveInfo; 4636 /* Best domain verification status of the activities found in the other profile */ 4637 int bestDomainVerificationStatus; 4638 } 4639 4640 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4641 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4642 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4643 sourceUserId)) { 4644 return null; 4645 } 4646 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4647 resolvedType, flags, parentUserId); 4648 4649 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4650 return null; 4651 } 4652 CrossProfileDomainInfo result = null; 4653 int size = resultTargetUser.size(); 4654 for (int i = 0; i < size; i++) { 4655 ResolveInfo riTargetUser = resultTargetUser.get(i); 4656 // Intent filter verification is only for filters that specify a host. So don't return 4657 // those that handle all web uris. 4658 if (riTargetUser.handleAllWebDataURI) { 4659 continue; 4660 } 4661 String packageName = riTargetUser.activityInfo.packageName; 4662 PackageSetting ps = mSettings.mPackages.get(packageName); 4663 if (ps == null) { 4664 continue; 4665 } 4666 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4667 int status = (int)(verificationState >> 32); 4668 if (result == null) { 4669 result = new CrossProfileDomainInfo(); 4670 result.resolveInfo = 4671 createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId); 4672 result.bestDomainVerificationStatus = status; 4673 } else { 4674 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4675 result.bestDomainVerificationStatus); 4676 } 4677 } 4678 // Don't consider matches with status NEVER across profiles. 4679 if (result != null && result.bestDomainVerificationStatus 4680 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4681 return null; 4682 } 4683 return result; 4684 } 4685 4686 /** 4687 * Verification statuses are ordered from the worse to the best, except for 4688 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4689 */ 4690 private int bestDomainVerificationStatus(int status1, int status2) { 4691 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4692 return status2; 4693 } 4694 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4695 return status1; 4696 } 4697 return (int) MathUtils.max(status1, status2); 4698 } 4699 4700 private boolean isUserEnabled(int userId) { 4701 long callingId = Binder.clearCallingIdentity(); 4702 try { 4703 UserInfo userInfo = sUserManager.getUserInfo(userId); 4704 return userInfo != null && userInfo.isEnabled(); 4705 } finally { 4706 Binder.restoreCallingIdentity(callingId); 4707 } 4708 } 4709 4710 /** 4711 * Filter out activities with systemUserOnly flag set, when current user is not System. 4712 * 4713 * @return filtered list 4714 */ 4715 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4716 if (userId == UserHandle.USER_SYSTEM) { 4717 return resolveInfos; 4718 } 4719 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4720 ResolveInfo info = resolveInfos.get(i); 4721 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4722 resolveInfos.remove(i); 4723 } 4724 } 4725 return resolveInfos; 4726 } 4727 4728 private static boolean hasWebURI(Intent intent) { 4729 if (intent.getData() == null) { 4730 return false; 4731 } 4732 final String scheme = intent.getScheme(); 4733 if (TextUtils.isEmpty(scheme)) { 4734 return false; 4735 } 4736 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4737 } 4738 4739 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4740 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4741 int userId) { 4742 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4743 4744 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4745 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4746 candidates.size()); 4747 } 4748 4749 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4750 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4751 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4752 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4753 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4754 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4755 4756 synchronized (mPackages) { 4757 final int count = candidates.size(); 4758 // First, try to use linked apps. Partition the candidates into four lists: 4759 // one for the final results, one for the "do not use ever", one for "undefined status" 4760 // and finally one for "browser app type". 4761 for (int n=0; n<count; n++) { 4762 ResolveInfo info = candidates.get(n); 4763 String packageName = info.activityInfo.packageName; 4764 PackageSetting ps = mSettings.mPackages.get(packageName); 4765 if (ps != null) { 4766 // Add to the special match all list (Browser use case) 4767 if (info.handleAllWebDataURI) { 4768 matchAllList.add(info); 4769 continue; 4770 } 4771 // Try to get the status from User settings first 4772 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4773 int status = (int)(packedStatus >> 32); 4774 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4775 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4776 if (DEBUG_DOMAIN_VERIFICATION) { 4777 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4778 + " : linkgen=" + linkGeneration); 4779 } 4780 // Use link-enabled generation as preferredOrder, i.e. 4781 // prefer newly-enabled over earlier-enabled. 4782 info.preferredOrder = linkGeneration; 4783 alwaysList.add(info); 4784 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4785 if (DEBUG_DOMAIN_VERIFICATION) { 4786 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4787 } 4788 neverList.add(info); 4789 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4790 if (DEBUG_DOMAIN_VERIFICATION) { 4791 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4792 } 4793 alwaysAskList.add(info); 4794 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4795 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4796 if (DEBUG_DOMAIN_VERIFICATION) { 4797 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4798 } 4799 undefinedList.add(info); 4800 } 4801 } 4802 } 4803 4804 // We'll want to include browser possibilities in a few cases 4805 boolean includeBrowser = false; 4806 4807 // First try to add the "always" resolution(s) for the current user, if any 4808 if (alwaysList.size() > 0) { 4809 result.addAll(alwaysList); 4810 // if there is an "always" for the parent user, add it. 4811 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4812 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4813 result.add(xpDomainInfo.resolveInfo); 4814 } else { 4815 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4816 result.addAll(undefinedList); 4817 if (xpDomainInfo != null && ( 4818 xpDomainInfo.bestDomainVerificationStatus 4819 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4820 || xpDomainInfo.bestDomainVerificationStatus 4821 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4822 result.add(xpDomainInfo.resolveInfo); 4823 } 4824 includeBrowser = true; 4825 } 4826 4827 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4828 // If there were 'always' entries their preferred order has been set, so we also 4829 // back that off to make the alternatives equivalent 4830 if (alwaysAskList.size() > 0) { 4831 for (ResolveInfo i : result) { 4832 i.preferredOrder = 0; 4833 } 4834 result.addAll(alwaysAskList); 4835 includeBrowser = true; 4836 } 4837 4838 if (includeBrowser) { 4839 // Also add browsers (all of them or only the default one) 4840 if (DEBUG_DOMAIN_VERIFICATION) { 4841 Slog.v(TAG, " ...including browsers in candidate set"); 4842 } 4843 if ((matchFlags & MATCH_ALL) != 0) { 4844 result.addAll(matchAllList); 4845 } else { 4846 // Browser/generic handling case. If there's a default browser, go straight 4847 // to that (but only if there is no other higher-priority match). 4848 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4849 int maxMatchPrio = 0; 4850 ResolveInfo defaultBrowserMatch = null; 4851 final int numCandidates = matchAllList.size(); 4852 for (int n = 0; n < numCandidates; n++) { 4853 ResolveInfo info = matchAllList.get(n); 4854 // track the highest overall match priority... 4855 if (info.priority > maxMatchPrio) { 4856 maxMatchPrio = info.priority; 4857 } 4858 // ...and the highest-priority default browser match 4859 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4860 if (defaultBrowserMatch == null 4861 || (defaultBrowserMatch.priority < info.priority)) { 4862 if (debug) { 4863 Slog.v(TAG, "Considering default browser match " + info); 4864 } 4865 defaultBrowserMatch = info; 4866 } 4867 } 4868 } 4869 if (defaultBrowserMatch != null 4870 && defaultBrowserMatch.priority >= maxMatchPrio 4871 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4872 { 4873 if (debug) { 4874 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4875 } 4876 result.add(defaultBrowserMatch); 4877 } else { 4878 result.addAll(matchAllList); 4879 } 4880 } 4881 4882 // If there is nothing selected, add all candidates and remove the ones that the user 4883 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4884 if (result.size() == 0) { 4885 result.addAll(candidates); 4886 result.removeAll(neverList); 4887 } 4888 } 4889 } 4890 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4891 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4892 result.size()); 4893 for (ResolveInfo info : result) { 4894 Slog.v(TAG, " + " + info.activityInfo); 4895 } 4896 } 4897 return result; 4898 } 4899 4900 // Returns a packed value as a long: 4901 // 4902 // high 'int'-sized word: link status: undefined/ask/never/always. 4903 // low 'int'-sized word: relative priority among 'always' results. 4904 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4905 long result = ps.getDomainVerificationStatusForUser(userId); 4906 // if none available, get the master status 4907 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4908 if (ps.getIntentFilterVerificationInfo() != null) { 4909 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4910 } 4911 } 4912 return result; 4913 } 4914 4915 private ResolveInfo querySkipCurrentProfileIntents( 4916 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4917 int flags, int sourceUserId) { 4918 if (matchingFilters != null) { 4919 int size = matchingFilters.size(); 4920 for (int i = 0; i < size; i ++) { 4921 CrossProfileIntentFilter filter = matchingFilters.get(i); 4922 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4923 // Checking if there are activities in the target user that can handle the 4924 // intent. 4925 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4926 flags, sourceUserId); 4927 if (resolveInfo != null) { 4928 return resolveInfo; 4929 } 4930 } 4931 } 4932 } 4933 return null; 4934 } 4935 4936 // Return matching ResolveInfo if any for skip current profile intent filters. 4937 private ResolveInfo queryCrossProfileIntents( 4938 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4939 int flags, int sourceUserId) { 4940 if (matchingFilters != null) { 4941 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4942 // match the same intent. For performance reasons, it is better not to 4943 // run queryIntent twice for the same userId 4944 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4945 int size = matchingFilters.size(); 4946 for (int i = 0; i < size; i++) { 4947 CrossProfileIntentFilter filter = matchingFilters.get(i); 4948 int targetUserId = filter.getTargetUserId(); 4949 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4950 && !alreadyTriedUserIds.get(targetUserId)) { 4951 // Checking if there are activities in the target user that can handle the 4952 // intent. 4953 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4954 flags, sourceUserId); 4955 if (resolveInfo != null) return resolveInfo; 4956 alreadyTriedUserIds.put(targetUserId, true); 4957 } 4958 } 4959 } 4960 return null; 4961 } 4962 4963 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4964 String resolvedType, int flags, int sourceUserId) { 4965 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4966 resolvedType, flags, filter.getTargetUserId()); 4967 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4968 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4969 } 4970 return null; 4971 } 4972 4973 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4974 int sourceUserId, int targetUserId) { 4975 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4976 long ident = Binder.clearCallingIdentity(); 4977 boolean targetIsProfile; 4978 try { 4979 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4980 } finally { 4981 Binder.restoreCallingIdentity(ident); 4982 } 4983 String className; 4984 if (targetIsProfile) { 4985 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4986 } else { 4987 className = FORWARD_INTENT_TO_PARENT; 4988 } 4989 ComponentName forwardingActivityComponentName = new ComponentName( 4990 mAndroidApplication.packageName, className); 4991 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4992 sourceUserId); 4993 if (!targetIsProfile) { 4994 forwardingActivityInfo.showUserIcon = targetUserId; 4995 forwardingResolveInfo.noResourceId = true; 4996 } 4997 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4998 forwardingResolveInfo.priority = 0; 4999 forwardingResolveInfo.preferredOrder = 0; 5000 forwardingResolveInfo.match = 0; 5001 forwardingResolveInfo.isDefault = true; 5002 forwardingResolveInfo.filter = filter; 5003 forwardingResolveInfo.targetUserId = targetUserId; 5004 return forwardingResolveInfo; 5005 } 5006 5007 @Override 5008 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5009 Intent[] specifics, String[] specificTypes, Intent intent, 5010 String resolvedType, int flags, int userId) { 5011 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5012 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5013 false, "query intent activity options"); 5014 final String resultsAction = intent.getAction(); 5015 5016 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5017 | PackageManager.GET_RESOLVED_FILTER, userId); 5018 5019 if (DEBUG_INTENT_MATCHING) { 5020 Log.v(TAG, "Query " + intent + ": " + results); 5021 } 5022 5023 int specificsPos = 0; 5024 int N; 5025 5026 // todo: note that the algorithm used here is O(N^2). This 5027 // isn't a problem in our current environment, but if we start running 5028 // into situations where we have more than 5 or 10 matches then this 5029 // should probably be changed to something smarter... 5030 5031 // First we go through and resolve each of the specific items 5032 // that were supplied, taking care of removing any corresponding 5033 // duplicate items in the generic resolve list. 5034 if (specifics != null) { 5035 for (int i=0; i<specifics.length; i++) { 5036 final Intent sintent = specifics[i]; 5037 if (sintent == null) { 5038 continue; 5039 } 5040 5041 if (DEBUG_INTENT_MATCHING) { 5042 Log.v(TAG, "Specific #" + i + ": " + sintent); 5043 } 5044 5045 String action = sintent.getAction(); 5046 if (resultsAction != null && resultsAction.equals(action)) { 5047 // If this action was explicitly requested, then don't 5048 // remove things that have it. 5049 action = null; 5050 } 5051 5052 ResolveInfo ri = null; 5053 ActivityInfo ai = null; 5054 5055 ComponentName comp = sintent.getComponent(); 5056 if (comp == null) { 5057 ri = resolveIntent( 5058 sintent, 5059 specificTypes != null ? specificTypes[i] : null, 5060 flags, userId); 5061 if (ri == null) { 5062 continue; 5063 } 5064 if (ri == mResolveInfo) { 5065 // ACK! Must do something better with this. 5066 } 5067 ai = ri.activityInfo; 5068 comp = new ComponentName(ai.applicationInfo.packageName, 5069 ai.name); 5070 } else { 5071 ai = getActivityInfo(comp, flags, userId); 5072 if (ai == null) { 5073 continue; 5074 } 5075 } 5076 5077 // Look for any generic query activities that are duplicates 5078 // of this specific one, and remove them from the results. 5079 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5080 N = results.size(); 5081 int j; 5082 for (j=specificsPos; j<N; j++) { 5083 ResolveInfo sri = results.get(j); 5084 if ((sri.activityInfo.name.equals(comp.getClassName()) 5085 && sri.activityInfo.applicationInfo.packageName.equals( 5086 comp.getPackageName())) 5087 || (action != null && sri.filter.matchAction(action))) { 5088 results.remove(j); 5089 if (DEBUG_INTENT_MATCHING) Log.v( 5090 TAG, "Removing duplicate item from " + j 5091 + " due to specific " + specificsPos); 5092 if (ri == null) { 5093 ri = sri; 5094 } 5095 j--; 5096 N--; 5097 } 5098 } 5099 5100 // Add this specific item to its proper place. 5101 if (ri == null) { 5102 ri = new ResolveInfo(); 5103 ri.activityInfo = ai; 5104 } 5105 results.add(specificsPos, ri); 5106 ri.specificIndex = i; 5107 specificsPos++; 5108 } 5109 } 5110 5111 // Now we go through the remaining generic results and remove any 5112 // duplicate actions that are found here. 5113 N = results.size(); 5114 for (int i=specificsPos; i<N-1; i++) { 5115 final ResolveInfo rii = results.get(i); 5116 if (rii.filter == null) { 5117 continue; 5118 } 5119 5120 // Iterate over all of the actions of this result's intent 5121 // filter... typically this should be just one. 5122 final Iterator<String> it = rii.filter.actionsIterator(); 5123 if (it == null) { 5124 continue; 5125 } 5126 while (it.hasNext()) { 5127 final String action = it.next(); 5128 if (resultsAction != null && resultsAction.equals(action)) { 5129 // If this action was explicitly requested, then don't 5130 // remove things that have it. 5131 continue; 5132 } 5133 for (int j=i+1; j<N; j++) { 5134 final ResolveInfo rij = results.get(j); 5135 if (rij.filter != null && rij.filter.hasAction(action)) { 5136 results.remove(j); 5137 if (DEBUG_INTENT_MATCHING) Log.v( 5138 TAG, "Removing duplicate item from " + j 5139 + " due to action " + action + " at " + i); 5140 j--; 5141 N--; 5142 } 5143 } 5144 } 5145 5146 // If the caller didn't request filter information, drop it now 5147 // so we don't have to marshall/unmarshall it. 5148 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5149 rii.filter = null; 5150 } 5151 } 5152 5153 // Filter out the caller activity if so requested. 5154 if (caller != null) { 5155 N = results.size(); 5156 for (int i=0; i<N; i++) { 5157 ActivityInfo ainfo = results.get(i).activityInfo; 5158 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5159 && caller.getClassName().equals(ainfo.name)) { 5160 results.remove(i); 5161 break; 5162 } 5163 } 5164 } 5165 5166 // If the caller didn't request filter information, 5167 // drop them now so we don't have to 5168 // marshall/unmarshall it. 5169 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5170 N = results.size(); 5171 for (int i=0; i<N; i++) { 5172 results.get(i).filter = null; 5173 } 5174 } 5175 5176 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5177 return results; 5178 } 5179 5180 @Override 5181 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5182 int userId) { 5183 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5184 ComponentName comp = intent.getComponent(); 5185 if (comp == null) { 5186 if (intent.getSelector() != null) { 5187 intent = intent.getSelector(); 5188 comp = intent.getComponent(); 5189 } 5190 } 5191 if (comp != null) { 5192 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5193 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5194 if (ai != null) { 5195 ResolveInfo ri = new ResolveInfo(); 5196 ri.activityInfo = ai; 5197 list.add(ri); 5198 } 5199 return list; 5200 } 5201 5202 // reader 5203 synchronized (mPackages) { 5204 String pkgName = intent.getPackage(); 5205 if (pkgName == null) { 5206 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5207 } 5208 final PackageParser.Package pkg = mPackages.get(pkgName); 5209 if (pkg != null) { 5210 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5211 userId); 5212 } 5213 return null; 5214 } 5215 } 5216 5217 @Override 5218 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5219 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5220 if (!sUserManager.exists(userId)) return null; 5221 if (query != null) { 5222 if (query.size() >= 1) { 5223 // If there is more than one service with the same priority, 5224 // just arbitrarily pick the first one. 5225 return query.get(0); 5226 } 5227 } 5228 return null; 5229 } 5230 5231 @Override 5232 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5233 int userId) { 5234 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5235 ComponentName comp = intent.getComponent(); 5236 if (comp == null) { 5237 if (intent.getSelector() != null) { 5238 intent = intent.getSelector(); 5239 comp = intent.getComponent(); 5240 } 5241 } 5242 if (comp != null) { 5243 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5244 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5245 if (si != null) { 5246 final ResolveInfo ri = new ResolveInfo(); 5247 ri.serviceInfo = si; 5248 list.add(ri); 5249 } 5250 return list; 5251 } 5252 5253 // reader 5254 synchronized (mPackages) { 5255 String pkgName = intent.getPackage(); 5256 if (pkgName == null) { 5257 return mServices.queryIntent(intent, resolvedType, flags, userId); 5258 } 5259 final PackageParser.Package pkg = mPackages.get(pkgName); 5260 if (pkg != null) { 5261 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5262 userId); 5263 } 5264 return null; 5265 } 5266 } 5267 5268 @Override 5269 public List<ResolveInfo> queryIntentContentProviders( 5270 Intent intent, String resolvedType, int flags, int userId) { 5271 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5272 ComponentName comp = intent.getComponent(); 5273 if (comp == null) { 5274 if (intent.getSelector() != null) { 5275 intent = intent.getSelector(); 5276 comp = intent.getComponent(); 5277 } 5278 } 5279 if (comp != null) { 5280 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5281 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5282 if (pi != null) { 5283 final ResolveInfo ri = new ResolveInfo(); 5284 ri.providerInfo = pi; 5285 list.add(ri); 5286 } 5287 return list; 5288 } 5289 5290 // reader 5291 synchronized (mPackages) { 5292 String pkgName = intent.getPackage(); 5293 if (pkgName == null) { 5294 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5295 } 5296 final PackageParser.Package pkg = mPackages.get(pkgName); 5297 if (pkg != null) { 5298 return mProviders.queryIntentForPackage( 5299 intent, resolvedType, flags, pkg.providers, userId); 5300 } 5301 return null; 5302 } 5303 } 5304 5305 @Override 5306 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5307 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5308 5309 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5310 5311 // writer 5312 synchronized (mPackages) { 5313 ArrayList<PackageInfo> list; 5314 if (listUninstalled) { 5315 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5316 for (PackageSetting ps : mSettings.mPackages.values()) { 5317 PackageInfo pi; 5318 if (ps.pkg != null) { 5319 pi = generatePackageInfo(ps.pkg, flags, userId); 5320 } else { 5321 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5322 } 5323 if (pi != null) { 5324 list.add(pi); 5325 } 5326 } 5327 } else { 5328 list = new ArrayList<PackageInfo>(mPackages.size()); 5329 for (PackageParser.Package p : mPackages.values()) { 5330 PackageInfo pi = generatePackageInfo(p, flags, userId); 5331 if (pi != null) { 5332 list.add(pi); 5333 } 5334 } 5335 } 5336 5337 return new ParceledListSlice<PackageInfo>(list); 5338 } 5339 } 5340 5341 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5342 String[] permissions, boolean[] tmp, int flags, int userId) { 5343 int numMatch = 0; 5344 final PermissionsState permissionsState = ps.getPermissionsState(); 5345 for (int i=0; i<permissions.length; i++) { 5346 final String permission = permissions[i]; 5347 if (permissionsState.hasPermission(permission, userId)) { 5348 tmp[i] = true; 5349 numMatch++; 5350 } else { 5351 tmp[i] = false; 5352 } 5353 } 5354 if (numMatch == 0) { 5355 return; 5356 } 5357 PackageInfo pi; 5358 if (ps.pkg != null) { 5359 pi = generatePackageInfo(ps.pkg, flags, userId); 5360 } else { 5361 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5362 } 5363 // The above might return null in cases of uninstalled apps or install-state 5364 // skew across users/profiles. 5365 if (pi != null) { 5366 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5367 if (numMatch == permissions.length) { 5368 pi.requestedPermissions = permissions; 5369 } else { 5370 pi.requestedPermissions = new String[numMatch]; 5371 numMatch = 0; 5372 for (int i=0; i<permissions.length; i++) { 5373 if (tmp[i]) { 5374 pi.requestedPermissions[numMatch] = permissions[i]; 5375 numMatch++; 5376 } 5377 } 5378 } 5379 } 5380 list.add(pi); 5381 } 5382 } 5383 5384 @Override 5385 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5386 String[] permissions, int flags, int userId) { 5387 if (!sUserManager.exists(userId)) return null; 5388 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5389 5390 // writer 5391 synchronized (mPackages) { 5392 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5393 boolean[] tmpBools = new boolean[permissions.length]; 5394 if (listUninstalled) { 5395 for (PackageSetting ps : mSettings.mPackages.values()) { 5396 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5397 } 5398 } else { 5399 for (PackageParser.Package pkg : mPackages.values()) { 5400 PackageSetting ps = (PackageSetting)pkg.mExtras; 5401 if (ps != null) { 5402 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5403 userId); 5404 } 5405 } 5406 } 5407 5408 return new ParceledListSlice<PackageInfo>(list); 5409 } 5410 } 5411 5412 @Override 5413 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5414 if (!sUserManager.exists(userId)) return null; 5415 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5416 5417 // writer 5418 synchronized (mPackages) { 5419 ArrayList<ApplicationInfo> list; 5420 if (listUninstalled) { 5421 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5422 for (PackageSetting ps : mSettings.mPackages.values()) { 5423 ApplicationInfo ai; 5424 if (ps.pkg != null) { 5425 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5426 ps.readUserState(userId), userId); 5427 } else { 5428 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5429 } 5430 if (ai != null) { 5431 list.add(ai); 5432 } 5433 } 5434 } else { 5435 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5436 for (PackageParser.Package p : mPackages.values()) { 5437 if (p.mExtras != null) { 5438 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5439 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5440 if (ai != null) { 5441 list.add(ai); 5442 } 5443 } 5444 } 5445 } 5446 5447 return new ParceledListSlice<ApplicationInfo>(list); 5448 } 5449 } 5450 5451 public List<ApplicationInfo> getPersistentApplications(int flags) { 5452 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5453 5454 // reader 5455 synchronized (mPackages) { 5456 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5457 final int userId = UserHandle.getCallingUserId(); 5458 while (i.hasNext()) { 5459 final PackageParser.Package p = i.next(); 5460 if (p.applicationInfo != null 5461 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5462 && (!mSafeMode || isSystemApp(p))) { 5463 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5464 if (ps != null) { 5465 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5466 ps.readUserState(userId), userId); 5467 if (ai != null) { 5468 finalList.add(ai); 5469 } 5470 } 5471 } 5472 } 5473 } 5474 5475 return finalList; 5476 } 5477 5478 @Override 5479 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5480 if (!sUserManager.exists(userId)) return null; 5481 // reader 5482 synchronized (mPackages) { 5483 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5484 PackageSetting ps = provider != null 5485 ? mSettings.mPackages.get(provider.owner.packageName) 5486 : null; 5487 return ps != null 5488 && mSettings.isEnabledLPr(provider.info, flags, userId) 5489 && (!mSafeMode || (provider.info.applicationInfo.flags 5490 &ApplicationInfo.FLAG_SYSTEM) != 0) 5491 ? PackageParser.generateProviderInfo(provider, flags, 5492 ps.readUserState(userId), userId) 5493 : null; 5494 } 5495 } 5496 5497 /** 5498 * @deprecated 5499 */ 5500 @Deprecated 5501 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5502 // reader 5503 synchronized (mPackages) { 5504 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5505 .entrySet().iterator(); 5506 final int userId = UserHandle.getCallingUserId(); 5507 while (i.hasNext()) { 5508 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5509 PackageParser.Provider p = entry.getValue(); 5510 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5511 5512 if (ps != null && p.syncable 5513 && (!mSafeMode || (p.info.applicationInfo.flags 5514 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5515 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5516 ps.readUserState(userId), userId); 5517 if (info != null) { 5518 outNames.add(entry.getKey()); 5519 outInfo.add(info); 5520 } 5521 } 5522 } 5523 } 5524 } 5525 5526 @Override 5527 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5528 int uid, int flags) { 5529 ArrayList<ProviderInfo> finalList = null; 5530 // reader 5531 synchronized (mPackages) { 5532 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5533 final int userId = processName != null ? 5534 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5535 while (i.hasNext()) { 5536 final PackageParser.Provider p = i.next(); 5537 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5538 if (ps != null && p.info.authority != null 5539 && (processName == null 5540 || (p.info.processName.equals(processName) 5541 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5542 && mSettings.isEnabledLPr(p.info, flags, userId) 5543 && (!mSafeMode 5544 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5545 if (finalList == null) { 5546 finalList = new ArrayList<ProviderInfo>(3); 5547 } 5548 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5549 ps.readUserState(userId), userId); 5550 if (info != null) { 5551 finalList.add(info); 5552 } 5553 } 5554 } 5555 } 5556 5557 if (finalList != null) { 5558 Collections.sort(finalList, mProviderInitOrderSorter); 5559 return new ParceledListSlice<ProviderInfo>(finalList); 5560 } 5561 5562 return null; 5563 } 5564 5565 @Override 5566 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5567 int flags) { 5568 // reader 5569 synchronized (mPackages) { 5570 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5571 return PackageParser.generateInstrumentationInfo(i, flags); 5572 } 5573 } 5574 5575 @Override 5576 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5577 int flags) { 5578 ArrayList<InstrumentationInfo> finalList = 5579 new ArrayList<InstrumentationInfo>(); 5580 5581 // reader 5582 synchronized (mPackages) { 5583 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5584 while (i.hasNext()) { 5585 final PackageParser.Instrumentation p = i.next(); 5586 if (targetPackage == null 5587 || targetPackage.equals(p.info.targetPackage)) { 5588 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5589 flags); 5590 if (ii != null) { 5591 finalList.add(ii); 5592 } 5593 } 5594 } 5595 } 5596 5597 return finalList; 5598 } 5599 5600 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5601 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5602 if (overlays == null) { 5603 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5604 return; 5605 } 5606 for (PackageParser.Package opkg : overlays.values()) { 5607 // Not much to do if idmap fails: we already logged the error 5608 // and we certainly don't want to abort installation of pkg simply 5609 // because an overlay didn't fit properly. For these reasons, 5610 // ignore the return value of createIdmapForPackagePairLI. 5611 createIdmapForPackagePairLI(pkg, opkg); 5612 } 5613 } 5614 5615 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5616 PackageParser.Package opkg) { 5617 if (!opkg.mTrustedOverlay) { 5618 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5619 opkg.baseCodePath + ": overlay not trusted"); 5620 return false; 5621 } 5622 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5623 if (overlaySet == null) { 5624 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5625 opkg.baseCodePath + " but target package has no known overlays"); 5626 return false; 5627 } 5628 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5629 // TODO: generate idmap for split APKs 5630 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5631 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5632 + opkg.baseCodePath); 5633 return false; 5634 } 5635 PackageParser.Package[] overlayArray = 5636 overlaySet.values().toArray(new PackageParser.Package[0]); 5637 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5638 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5639 return p1.mOverlayPriority - p2.mOverlayPriority; 5640 } 5641 }; 5642 Arrays.sort(overlayArray, cmp); 5643 5644 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5645 int i = 0; 5646 for (PackageParser.Package p : overlayArray) { 5647 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5648 } 5649 return true; 5650 } 5651 5652 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5653 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5654 try { 5655 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5656 } finally { 5657 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5658 } 5659 } 5660 5661 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5662 final File[] files = dir.listFiles(); 5663 if (ArrayUtils.isEmpty(files)) { 5664 Log.d(TAG, "No files in app dir " + dir); 5665 return; 5666 } 5667 5668 if (DEBUG_PACKAGE_SCANNING) { 5669 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5670 + " flags=0x" + Integer.toHexString(parseFlags)); 5671 } 5672 5673 for (File file : files) { 5674 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5675 && !PackageInstallerService.isStageName(file.getName()); 5676 if (!isPackage) { 5677 // Ignore entries which are not packages 5678 continue; 5679 } 5680 try { 5681 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5682 scanFlags, currentTime, null); 5683 } catch (PackageManagerException e) { 5684 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5685 5686 // Delete invalid userdata apps 5687 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5688 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5689 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5690 if (file.isDirectory()) { 5691 mInstaller.rmPackageDir(file.getAbsolutePath()); 5692 } else { 5693 file.delete(); 5694 } 5695 } 5696 } 5697 } 5698 } 5699 5700 private static File getSettingsProblemFile() { 5701 File dataDir = Environment.getDataDirectory(); 5702 File systemDir = new File(dataDir, "system"); 5703 File fname = new File(systemDir, "uiderrors.txt"); 5704 return fname; 5705 } 5706 5707 static void reportSettingsProblem(int priority, String msg) { 5708 logCriticalInfo(priority, msg); 5709 } 5710 5711 static void logCriticalInfo(int priority, String msg) { 5712 Slog.println(priority, TAG, msg); 5713 EventLogTags.writePmCriticalInfo(msg); 5714 try { 5715 File fname = getSettingsProblemFile(); 5716 FileOutputStream out = new FileOutputStream(fname, true); 5717 PrintWriter pw = new FastPrintWriter(out); 5718 SimpleDateFormat formatter = new SimpleDateFormat(); 5719 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5720 pw.println(dateString + ": " + msg); 5721 pw.close(); 5722 FileUtils.setPermissions( 5723 fname.toString(), 5724 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5725 -1, -1); 5726 } catch (java.io.IOException e) { 5727 } 5728 } 5729 5730 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5731 PackageParser.Package pkg, File srcFile, int parseFlags) 5732 throws PackageManagerException { 5733 if (ps != null 5734 && ps.codePath.equals(srcFile) 5735 && ps.timeStamp == srcFile.lastModified() 5736 && !isCompatSignatureUpdateNeeded(pkg) 5737 && !isRecoverSignatureUpdateNeeded(pkg)) { 5738 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5739 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5740 ArraySet<PublicKey> signingKs; 5741 synchronized (mPackages) { 5742 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5743 } 5744 if (ps.signatures.mSignatures != null 5745 && ps.signatures.mSignatures.length != 0 5746 && signingKs != null) { 5747 // Optimization: reuse the existing cached certificates 5748 // if the package appears to be unchanged. 5749 pkg.mSignatures = ps.signatures.mSignatures; 5750 pkg.mSigningKeys = signingKs; 5751 return; 5752 } 5753 5754 Slog.w(TAG, "PackageSetting for " + ps.name 5755 + " is missing signatures. Collecting certs again to recover them."); 5756 } else { 5757 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5758 } 5759 5760 try { 5761 pp.collectCertificates(pkg, parseFlags); 5762 pp.collectManifestDigest(pkg); 5763 } catch (PackageParserException e) { 5764 throw PackageManagerException.from(e); 5765 } 5766 } 5767 5768 /** 5769 * Traces a package scan. 5770 * @see #scanPackageLI(File, int, int, long, UserHandle) 5771 */ 5772 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5773 long currentTime, UserHandle user) throws PackageManagerException { 5774 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5775 try { 5776 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5777 } finally { 5778 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5779 } 5780 } 5781 5782 /** 5783 * Scans a package and returns the newly parsed package. 5784 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5785 */ 5786 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5787 long currentTime, UserHandle user) throws PackageManagerException { 5788 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5789 parseFlags |= mDefParseFlags; 5790 PackageParser pp = new PackageParser(); 5791 pp.setSeparateProcesses(mSeparateProcesses); 5792 pp.setOnlyCoreApps(mOnlyCore); 5793 pp.setDisplayMetrics(mMetrics); 5794 5795 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5796 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5797 } 5798 5799 final PackageParser.Package pkg; 5800 try { 5801 pkg = pp.parsePackage(scanFile, parseFlags); 5802 } catch (PackageParserException e) { 5803 throw PackageManagerException.from(e); 5804 } 5805 5806 PackageSetting ps = null; 5807 PackageSetting updatedPkg; 5808 // reader 5809 synchronized (mPackages) { 5810 // Look to see if we already know about this package. 5811 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5812 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5813 // This package has been renamed to its original name. Let's 5814 // use that. 5815 ps = mSettings.peekPackageLPr(oldName); 5816 } 5817 // If there was no original package, see one for the real package name. 5818 if (ps == null) { 5819 ps = mSettings.peekPackageLPr(pkg.packageName); 5820 } 5821 // Check to see if this package could be hiding/updating a system 5822 // package. Must look for it either under the original or real 5823 // package name depending on our state. 5824 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5825 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5826 } 5827 boolean updatedPkgBetter = false; 5828 // First check if this is a system package that may involve an update 5829 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5830 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5831 // it needs to drop FLAG_PRIVILEGED. 5832 if (locationIsPrivileged(scanFile)) { 5833 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5834 } else { 5835 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5836 } 5837 5838 if (ps != null && !ps.codePath.equals(scanFile)) { 5839 // The path has changed from what was last scanned... check the 5840 // version of the new path against what we have stored to determine 5841 // what to do. 5842 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5843 if (pkg.mVersionCode <= ps.versionCode) { 5844 // The system package has been updated and the code path does not match 5845 // Ignore entry. Skip it. 5846 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5847 + " ignored: updated version " + ps.versionCode 5848 + " better than this " + pkg.mVersionCode); 5849 if (!updatedPkg.codePath.equals(scanFile)) { 5850 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5851 + ps.name + " changing from " + updatedPkg.codePathString 5852 + " to " + scanFile); 5853 updatedPkg.codePath = scanFile; 5854 updatedPkg.codePathString = scanFile.toString(); 5855 updatedPkg.resourcePath = scanFile; 5856 updatedPkg.resourcePathString = scanFile.toString(); 5857 } 5858 updatedPkg.pkg = pkg; 5859 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5860 "Package " + ps.name + " at " + scanFile 5861 + " ignored: updated version " + ps.versionCode 5862 + " better than this " + pkg.mVersionCode); 5863 } else { 5864 // The current app on the system partition is better than 5865 // what we have updated to on the data partition; switch 5866 // back to the system partition version. 5867 // At this point, its safely assumed that package installation for 5868 // apps in system partition will go through. If not there won't be a working 5869 // version of the app 5870 // writer 5871 synchronized (mPackages) { 5872 // Just remove the loaded entries from package lists. 5873 mPackages.remove(ps.name); 5874 } 5875 5876 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5877 + " reverting from " + ps.codePathString 5878 + ": new version " + pkg.mVersionCode 5879 + " better than installed " + ps.versionCode); 5880 5881 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5882 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5883 synchronized (mInstallLock) { 5884 args.cleanUpResourcesLI(); 5885 } 5886 synchronized (mPackages) { 5887 mSettings.enableSystemPackageLPw(ps.name); 5888 } 5889 updatedPkgBetter = true; 5890 } 5891 } 5892 } 5893 5894 if (updatedPkg != null) { 5895 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5896 // initially 5897 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5898 5899 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5900 // flag set initially 5901 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5902 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5903 } 5904 } 5905 5906 // Verify certificates against what was last scanned 5907 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5908 5909 /* 5910 * A new system app appeared, but we already had a non-system one of the 5911 * same name installed earlier. 5912 */ 5913 boolean shouldHideSystemApp = false; 5914 if (updatedPkg == null && ps != null 5915 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5916 /* 5917 * Check to make sure the signatures match first. If they don't, 5918 * wipe the installed application and its data. 5919 */ 5920 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5921 != PackageManager.SIGNATURE_MATCH) { 5922 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5923 + " signatures don't match existing userdata copy; removing"); 5924 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5925 ps = null; 5926 } else { 5927 /* 5928 * If the newly-added system app is an older version than the 5929 * already installed version, hide it. It will be scanned later 5930 * and re-added like an update. 5931 */ 5932 if (pkg.mVersionCode <= ps.versionCode) { 5933 shouldHideSystemApp = true; 5934 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5935 + " but new version " + pkg.mVersionCode + " better than installed " 5936 + ps.versionCode + "; hiding system"); 5937 } else { 5938 /* 5939 * The newly found system app is a newer version that the 5940 * one previously installed. Simply remove the 5941 * already-installed application and replace it with our own 5942 * while keeping the application data. 5943 */ 5944 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5945 + " reverting from " + ps.codePathString + ": new version " 5946 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5947 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5948 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5949 synchronized (mInstallLock) { 5950 args.cleanUpResourcesLI(); 5951 } 5952 } 5953 } 5954 } 5955 5956 // The apk is forward locked (not public) if its code and resources 5957 // are kept in different files. (except for app in either system or 5958 // vendor path). 5959 // TODO grab this value from PackageSettings 5960 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5961 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5962 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5963 } 5964 } 5965 5966 // TODO: extend to support forward-locked splits 5967 String resourcePath = null; 5968 String baseResourcePath = null; 5969 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5970 if (ps != null && ps.resourcePathString != null) { 5971 resourcePath = ps.resourcePathString; 5972 baseResourcePath = ps.resourcePathString; 5973 } else { 5974 // Should not happen at all. Just log an error. 5975 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5976 } 5977 } else { 5978 resourcePath = pkg.codePath; 5979 baseResourcePath = pkg.baseCodePath; 5980 } 5981 5982 // Set application objects path explicitly. 5983 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5984 pkg.applicationInfo.setCodePath(pkg.codePath); 5985 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5986 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5987 pkg.applicationInfo.setResourcePath(resourcePath); 5988 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5989 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5990 5991 // Note that we invoke the following method only if we are about to unpack an application 5992 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5993 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5994 5995 /* 5996 * If the system app should be overridden by a previously installed 5997 * data, hide the system app now and let the /data/app scan pick it up 5998 * again. 5999 */ 6000 if (shouldHideSystemApp) { 6001 synchronized (mPackages) { 6002 mSettings.disableSystemPackageLPw(pkg.packageName); 6003 } 6004 } 6005 6006 return scannedPkg; 6007 } 6008 6009 private static String fixProcessName(String defProcessName, 6010 String processName, int uid) { 6011 if (processName == null) { 6012 return defProcessName; 6013 } 6014 return processName; 6015 } 6016 6017 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6018 throws PackageManagerException { 6019 if (pkgSetting.signatures.mSignatures != null) { 6020 // Already existing package. Make sure signatures match 6021 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6022 == PackageManager.SIGNATURE_MATCH; 6023 if (!match) { 6024 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6025 == PackageManager.SIGNATURE_MATCH; 6026 } 6027 if (!match) { 6028 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6029 == PackageManager.SIGNATURE_MATCH; 6030 } 6031 if (!match) { 6032 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6033 + pkg.packageName + " signatures do not match the " 6034 + "previously installed version; ignoring!"); 6035 } 6036 } 6037 6038 // Check for shared user signatures 6039 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6040 // Already existing package. Make sure signatures match 6041 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6042 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6043 if (!match) { 6044 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6045 == PackageManager.SIGNATURE_MATCH; 6046 } 6047 if (!match) { 6048 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6049 == PackageManager.SIGNATURE_MATCH; 6050 } 6051 if (!match) { 6052 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6053 "Package " + pkg.packageName 6054 + " has no signatures that match those in shared user " 6055 + pkgSetting.sharedUser.name + "; ignoring!"); 6056 } 6057 } 6058 } 6059 6060 /** 6061 * Enforces that only the system UID or root's UID can call a method exposed 6062 * via Binder. 6063 * 6064 * @param message used as message if SecurityException is thrown 6065 * @throws SecurityException if the caller is not system or root 6066 */ 6067 private static final void enforceSystemOrRoot(String message) { 6068 final int uid = Binder.getCallingUid(); 6069 if (uid != Process.SYSTEM_UID && uid != 0) { 6070 throw new SecurityException(message); 6071 } 6072 } 6073 6074 @Override 6075 public void performBootDexOpt() { 6076 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6077 6078 // Before everything else, see whether we need to fstrim. 6079 try { 6080 IMountService ms = PackageHelper.getMountService(); 6081 if (ms != null) { 6082 final boolean isUpgrade = isUpgrade(); 6083 boolean doTrim = isUpgrade; 6084 if (doTrim) { 6085 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6086 } else { 6087 final long interval = android.provider.Settings.Global.getLong( 6088 mContext.getContentResolver(), 6089 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6090 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6091 if (interval > 0) { 6092 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6093 if (timeSinceLast > interval) { 6094 doTrim = true; 6095 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6096 + "; running immediately"); 6097 } 6098 } 6099 } 6100 if (doTrim) { 6101 if (!isFirstBoot()) { 6102 try { 6103 ActivityManagerNative.getDefault().showBootMessage( 6104 mContext.getResources().getString( 6105 R.string.android_upgrading_fstrim), true); 6106 } catch (RemoteException e) { 6107 } 6108 } 6109 ms.runMaintenance(); 6110 } 6111 } else { 6112 Slog.e(TAG, "Mount service unavailable!"); 6113 } 6114 } catch (RemoteException e) { 6115 // Can't happen; MountService is local 6116 } 6117 6118 final ArraySet<PackageParser.Package> pkgs; 6119 synchronized (mPackages) { 6120 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6121 } 6122 6123 if (pkgs != null) { 6124 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6125 // in case the device runs out of space. 6126 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6127 // Give priority to core apps. 6128 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6129 PackageParser.Package pkg = it.next(); 6130 if (pkg.coreApp) { 6131 if (DEBUG_DEXOPT) { 6132 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6133 } 6134 sortedPkgs.add(pkg); 6135 it.remove(); 6136 } 6137 } 6138 // Give priority to system apps that listen for pre boot complete. 6139 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6140 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6141 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6142 PackageParser.Package pkg = it.next(); 6143 if (pkgNames.contains(pkg.packageName)) { 6144 if (DEBUG_DEXOPT) { 6145 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6146 } 6147 sortedPkgs.add(pkg); 6148 it.remove(); 6149 } 6150 } 6151 // Give priority to system apps. 6152 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6153 PackageParser.Package pkg = it.next(); 6154 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6155 if (DEBUG_DEXOPT) { 6156 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6157 } 6158 sortedPkgs.add(pkg); 6159 it.remove(); 6160 } 6161 } 6162 // Give priority to updated system apps. 6163 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6164 PackageParser.Package pkg = it.next(); 6165 if (pkg.isUpdatedSystemApp()) { 6166 if (DEBUG_DEXOPT) { 6167 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6168 } 6169 sortedPkgs.add(pkg); 6170 it.remove(); 6171 } 6172 } 6173 // Give priority to apps that listen for boot complete. 6174 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6175 pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6176 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6177 PackageParser.Package pkg = it.next(); 6178 if (pkgNames.contains(pkg.packageName)) { 6179 if (DEBUG_DEXOPT) { 6180 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6181 } 6182 sortedPkgs.add(pkg); 6183 it.remove(); 6184 } 6185 } 6186 // Filter out packages that aren't recently used. 6187 filterRecentlyUsedApps(pkgs); 6188 // Add all remaining apps. 6189 for (PackageParser.Package pkg : pkgs) { 6190 if (DEBUG_DEXOPT) { 6191 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6192 } 6193 sortedPkgs.add(pkg); 6194 } 6195 6196 // If we want to be lazy, filter everything that wasn't recently used. 6197 if (mLazyDexOpt) { 6198 filterRecentlyUsedApps(sortedPkgs); 6199 } 6200 6201 int i = 0; 6202 int total = sortedPkgs.size(); 6203 File dataDir = Environment.getDataDirectory(); 6204 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6205 if (lowThreshold == 0) { 6206 throw new IllegalStateException("Invalid low memory threshold"); 6207 } 6208 for (PackageParser.Package pkg : sortedPkgs) { 6209 long usableSpace = dataDir.getUsableSpace(); 6210 if (usableSpace < lowThreshold) { 6211 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6212 break; 6213 } 6214 performBootDexOpt(pkg, ++i, total); 6215 } 6216 } 6217 } 6218 6219 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6220 // Filter out packages that aren't recently used. 6221 // 6222 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6223 // should do a full dexopt. 6224 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6225 int total = pkgs.size(); 6226 int skipped = 0; 6227 long now = System.currentTimeMillis(); 6228 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6229 PackageParser.Package pkg = i.next(); 6230 long then = pkg.mLastPackageUsageTimeInMills; 6231 if (then + mDexOptLRUThresholdInMills < now) { 6232 if (DEBUG_DEXOPT) { 6233 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6234 ((then == 0) ? "never" : new Date(then))); 6235 } 6236 i.remove(); 6237 skipped++; 6238 } 6239 } 6240 if (DEBUG_DEXOPT) { 6241 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6242 } 6243 } 6244 } 6245 6246 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6247 List<ResolveInfo> ris = null; 6248 try { 6249 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6250 intent, null, 0, userId); 6251 } catch (RemoteException e) { 6252 } 6253 ArraySet<String> pkgNames = new ArraySet<String>(); 6254 if (ris != null) { 6255 for (ResolveInfo ri : ris) { 6256 pkgNames.add(ri.activityInfo.packageName); 6257 } 6258 } 6259 return pkgNames; 6260 } 6261 6262 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6263 if (DEBUG_DEXOPT) { 6264 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6265 } 6266 if (!isFirstBoot()) { 6267 try { 6268 ActivityManagerNative.getDefault().showBootMessage( 6269 mContext.getResources().getString(R.string.android_upgrading_apk, 6270 curr, total), true); 6271 } catch (RemoteException e) { 6272 } 6273 } 6274 PackageParser.Package p = pkg; 6275 synchronized (mInstallLock) { 6276 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6277 false /* force dex */, false /* defer */, true /* include dependencies */); 6278 } 6279 } 6280 6281 @Override 6282 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6283 return performDexOptTraced(packageName, instructionSet, false); 6284 } 6285 6286 public boolean performDexOpt( 6287 String packageName, String instructionSet, boolean backgroundDexopt) { 6288 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6289 } 6290 6291 private boolean performDexOptTraced( 6292 String packageName, String instructionSet, boolean backgroundDexopt) { 6293 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6294 try { 6295 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6296 } finally { 6297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6298 } 6299 } 6300 6301 private boolean performDexOptInternal( 6302 String packageName, String instructionSet, boolean backgroundDexopt) { 6303 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6304 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6305 if (!dexopt && !updateUsage) { 6306 // We aren't going to dexopt or update usage, so bail early. 6307 return false; 6308 } 6309 PackageParser.Package p; 6310 final String targetInstructionSet; 6311 synchronized (mPackages) { 6312 p = mPackages.get(packageName); 6313 if (p == null) { 6314 return false; 6315 } 6316 if (updateUsage) { 6317 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6318 } 6319 mPackageUsage.write(false); 6320 if (!dexopt) { 6321 // We aren't going to dexopt, so bail early. 6322 return false; 6323 } 6324 6325 targetInstructionSet = instructionSet != null ? instructionSet : 6326 getPrimaryInstructionSet(p.applicationInfo); 6327 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6328 return false; 6329 } 6330 } 6331 long callingId = Binder.clearCallingIdentity(); 6332 try { 6333 synchronized (mInstallLock) { 6334 final String[] instructionSets = new String[] { targetInstructionSet }; 6335 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6336 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6337 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6338 } 6339 } finally { 6340 Binder.restoreCallingIdentity(callingId); 6341 } 6342 } 6343 6344 public ArraySet<String> getPackagesThatNeedDexOpt() { 6345 ArraySet<String> pkgs = null; 6346 synchronized (mPackages) { 6347 for (PackageParser.Package p : mPackages.values()) { 6348 if (DEBUG_DEXOPT) { 6349 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6350 } 6351 if (!p.mDexOptPerformed.isEmpty()) { 6352 continue; 6353 } 6354 if (pkgs == null) { 6355 pkgs = new ArraySet<String>(); 6356 } 6357 pkgs.add(p.packageName); 6358 } 6359 } 6360 return pkgs; 6361 } 6362 6363 public void shutdown() { 6364 mPackageUsage.write(true); 6365 } 6366 6367 @Override 6368 public void forceDexOpt(String packageName) { 6369 enforceSystemOrRoot("forceDexOpt"); 6370 6371 PackageParser.Package pkg; 6372 synchronized (mPackages) { 6373 pkg = mPackages.get(packageName); 6374 if (pkg == null) { 6375 throw new IllegalArgumentException("Missing package: " + packageName); 6376 } 6377 } 6378 6379 synchronized (mInstallLock) { 6380 final String[] instructionSets = new String[] { 6381 getPrimaryInstructionSet(pkg.applicationInfo) }; 6382 6383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6384 6385 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6386 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6387 6388 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6389 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6390 throw new IllegalStateException("Failed to dexopt: " + res); 6391 } 6392 } 6393 } 6394 6395 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6396 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6397 Slog.w(TAG, "Unable to update from " + oldPkg.name 6398 + " to " + newPkg.packageName 6399 + ": old package not in system partition"); 6400 return false; 6401 } else if (mPackages.get(oldPkg.name) != null) { 6402 Slog.w(TAG, "Unable to update from " + oldPkg.name 6403 + " to " + newPkg.packageName 6404 + ": old package still exists"); 6405 return false; 6406 } 6407 return true; 6408 } 6409 6410 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6411 int[] users = sUserManager.getUserIds(); 6412 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6413 if (res < 0) { 6414 return res; 6415 } 6416 for (int user : users) { 6417 if (user != 0) { 6418 res = mInstaller.createUserData(volumeUuid, packageName, 6419 UserHandle.getUid(user, uid), user, seinfo); 6420 if (res < 0) { 6421 return res; 6422 } 6423 } 6424 } 6425 return res; 6426 } 6427 6428 private int removeDataDirsLI(String volumeUuid, String packageName) { 6429 int[] users = sUserManager.getUserIds(); 6430 int res = 0; 6431 for (int user : users) { 6432 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6433 if (resInner < 0) { 6434 res = resInner; 6435 } 6436 } 6437 6438 return res; 6439 } 6440 6441 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6442 int[] users = sUserManager.getUserIds(); 6443 int res = 0; 6444 for (int user : users) { 6445 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6446 if (resInner < 0) { 6447 res = resInner; 6448 } 6449 } 6450 return res; 6451 } 6452 6453 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6454 PackageParser.Package changingLib) { 6455 if (file.path != null) { 6456 usesLibraryFiles.add(file.path); 6457 return; 6458 } 6459 PackageParser.Package p = mPackages.get(file.apk); 6460 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6461 // If we are doing this while in the middle of updating a library apk, 6462 // then we need to make sure to use that new apk for determining the 6463 // dependencies here. (We haven't yet finished committing the new apk 6464 // to the package manager state.) 6465 if (p == null || p.packageName.equals(changingLib.packageName)) { 6466 p = changingLib; 6467 } 6468 } 6469 if (p != null) { 6470 usesLibraryFiles.addAll(p.getAllCodePaths()); 6471 } 6472 } 6473 6474 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6475 PackageParser.Package changingLib) throws PackageManagerException { 6476 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6477 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6478 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6479 for (int i=0; i<N; i++) { 6480 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6481 if (file == null) { 6482 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6483 "Package " + pkg.packageName + " requires unavailable shared library " 6484 + pkg.usesLibraries.get(i) + "; failing!"); 6485 } 6486 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6487 } 6488 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6489 for (int i=0; i<N; i++) { 6490 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6491 if (file == null) { 6492 Slog.w(TAG, "Package " + pkg.packageName 6493 + " desires unavailable shared library " 6494 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6495 } else { 6496 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6497 } 6498 } 6499 N = usesLibraryFiles.size(); 6500 if (N > 0) { 6501 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6502 } else { 6503 pkg.usesLibraryFiles = null; 6504 } 6505 } 6506 } 6507 6508 private static boolean hasString(List<String> list, List<String> which) { 6509 if (list == null) { 6510 return false; 6511 } 6512 for (int i=list.size()-1; i>=0; i--) { 6513 for (int j=which.size()-1; j>=0; j--) { 6514 if (which.get(j).equals(list.get(i))) { 6515 return true; 6516 } 6517 } 6518 } 6519 return false; 6520 } 6521 6522 private void updateAllSharedLibrariesLPw() { 6523 for (PackageParser.Package pkg : mPackages.values()) { 6524 try { 6525 updateSharedLibrariesLPw(pkg, null); 6526 } catch (PackageManagerException e) { 6527 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6528 } 6529 } 6530 } 6531 6532 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6533 PackageParser.Package changingPkg) { 6534 ArrayList<PackageParser.Package> res = null; 6535 for (PackageParser.Package pkg : mPackages.values()) { 6536 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6537 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6538 if (res == null) { 6539 res = new ArrayList<PackageParser.Package>(); 6540 } 6541 res.add(pkg); 6542 try { 6543 updateSharedLibrariesLPw(pkg, changingPkg); 6544 } catch (PackageManagerException e) { 6545 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6546 } 6547 } 6548 } 6549 return res; 6550 } 6551 6552 /** 6553 * Derive the value of the {@code cpuAbiOverride} based on the provided 6554 * value and an optional stored value from the package settings. 6555 */ 6556 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6557 String cpuAbiOverride = null; 6558 6559 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6560 cpuAbiOverride = null; 6561 } else if (abiOverride != null) { 6562 cpuAbiOverride = abiOverride; 6563 } else if (settings != null) { 6564 cpuAbiOverride = settings.cpuAbiOverrideString; 6565 } 6566 6567 return cpuAbiOverride; 6568 } 6569 6570 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6571 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6572 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6573 try { 6574 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6575 } finally { 6576 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6577 } 6578 } 6579 6580 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6581 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6582 boolean success = false; 6583 try { 6584 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6585 currentTime, user); 6586 success = true; 6587 return res; 6588 } finally { 6589 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6590 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6591 } 6592 } 6593 } 6594 6595 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6596 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6597 final File scanFile = new File(pkg.codePath); 6598 if (pkg.applicationInfo.getCodePath() == null || 6599 pkg.applicationInfo.getResourcePath() == null) { 6600 // Bail out. The resource and code paths haven't been set. 6601 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6602 "Code and resource paths haven't been set correctly"); 6603 } 6604 6605 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6606 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6607 } else { 6608 // Only allow system apps to be flagged as core apps. 6609 pkg.coreApp = false; 6610 } 6611 6612 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6613 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6614 } 6615 6616 if (mCustomResolverComponentName != null && 6617 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6618 setUpCustomResolverActivity(pkg); 6619 } 6620 6621 if (pkg.packageName.equals("android")) { 6622 synchronized (mPackages) { 6623 if (mAndroidApplication != null) { 6624 Slog.w(TAG, "*************************************************"); 6625 Slog.w(TAG, "Core android package being redefined. Skipping."); 6626 Slog.w(TAG, " file=" + scanFile); 6627 Slog.w(TAG, "*************************************************"); 6628 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6629 "Core android package being redefined. Skipping."); 6630 } 6631 6632 // Set up information for our fall-back user intent resolution activity. 6633 mPlatformPackage = pkg; 6634 pkg.mVersionCode = mSdkVersion; 6635 mAndroidApplication = pkg.applicationInfo; 6636 6637 if (!mResolverReplaced) { 6638 mResolveActivity.applicationInfo = mAndroidApplication; 6639 mResolveActivity.name = ResolverActivity.class.getName(); 6640 mResolveActivity.packageName = mAndroidApplication.packageName; 6641 mResolveActivity.processName = "system:ui"; 6642 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6643 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6644 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6645 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6646 mResolveActivity.exported = true; 6647 mResolveActivity.enabled = true; 6648 mResolveInfo.activityInfo = mResolveActivity; 6649 mResolveInfo.priority = 0; 6650 mResolveInfo.preferredOrder = 0; 6651 mResolveInfo.match = 0; 6652 mResolveComponentName = new ComponentName( 6653 mAndroidApplication.packageName, mResolveActivity.name); 6654 } 6655 } 6656 } 6657 6658 if (DEBUG_PACKAGE_SCANNING) { 6659 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6660 Log.d(TAG, "Scanning package " + pkg.packageName); 6661 } 6662 6663 if (mPackages.containsKey(pkg.packageName) 6664 || mSharedLibraries.containsKey(pkg.packageName)) { 6665 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6666 "Application package " + pkg.packageName 6667 + " already installed. Skipping duplicate."); 6668 } 6669 6670 // If we're only installing presumed-existing packages, require that the 6671 // scanned APK is both already known and at the path previously established 6672 // for it. Previously unknown packages we pick up normally, but if we have an 6673 // a priori expectation about this package's install presence, enforce it. 6674 // With a singular exception for new system packages. When an OTA contains 6675 // a new system package, we allow the codepath to change from a system location 6676 // to the user-installed location. If we don't allow this change, any newer, 6677 // user-installed version of the application will be ignored. 6678 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6679 if (mExpectingBetter.containsKey(pkg.packageName)) { 6680 logCriticalInfo(Log.WARN, 6681 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6682 } else { 6683 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6684 if (known != null) { 6685 if (DEBUG_PACKAGE_SCANNING) { 6686 Log.d(TAG, "Examining " + pkg.codePath 6687 + " and requiring known paths " + known.codePathString 6688 + " & " + known.resourcePathString); 6689 } 6690 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6691 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6692 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6693 "Application package " + pkg.packageName 6694 + " found at " + pkg.applicationInfo.getCodePath() 6695 + " but expected at " + known.codePathString + "; ignoring."); 6696 } 6697 } 6698 } 6699 } 6700 6701 // Initialize package source and resource directories 6702 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6703 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6704 6705 SharedUserSetting suid = null; 6706 PackageSetting pkgSetting = null; 6707 6708 if (!isSystemApp(pkg)) { 6709 // Only system apps can use these features. 6710 pkg.mOriginalPackages = null; 6711 pkg.mRealPackage = null; 6712 pkg.mAdoptPermissions = null; 6713 } 6714 6715 // writer 6716 synchronized (mPackages) { 6717 if (pkg.mSharedUserId != null) { 6718 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6719 if (suid == null) { 6720 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6721 "Creating application package " + pkg.packageName 6722 + " for shared user failed"); 6723 } 6724 if (DEBUG_PACKAGE_SCANNING) { 6725 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6726 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6727 + "): packages=" + suid.packages); 6728 } 6729 } 6730 6731 // Check if we are renaming from an original package name. 6732 PackageSetting origPackage = null; 6733 String realName = null; 6734 if (pkg.mOriginalPackages != null) { 6735 // This package may need to be renamed to a previously 6736 // installed name. Let's check on that... 6737 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6738 if (pkg.mOriginalPackages.contains(renamed)) { 6739 // This package had originally been installed as the 6740 // original name, and we have already taken care of 6741 // transitioning to the new one. Just update the new 6742 // one to continue using the old name. 6743 realName = pkg.mRealPackage; 6744 if (!pkg.packageName.equals(renamed)) { 6745 // Callers into this function may have already taken 6746 // care of renaming the package; only do it here if 6747 // it is not already done. 6748 pkg.setPackageName(renamed); 6749 } 6750 6751 } else { 6752 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6753 if ((origPackage = mSettings.peekPackageLPr( 6754 pkg.mOriginalPackages.get(i))) != null) { 6755 // We do have the package already installed under its 6756 // original name... should we use it? 6757 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6758 // New package is not compatible with original. 6759 origPackage = null; 6760 continue; 6761 } else if (origPackage.sharedUser != null) { 6762 // Make sure uid is compatible between packages. 6763 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6764 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6765 + " to " + pkg.packageName + ": old uid " 6766 + origPackage.sharedUser.name 6767 + " differs from " + pkg.mSharedUserId); 6768 origPackage = null; 6769 continue; 6770 } 6771 } else { 6772 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6773 + pkg.packageName + " to old name " + origPackage.name); 6774 } 6775 break; 6776 } 6777 } 6778 } 6779 } 6780 6781 if (mTransferedPackages.contains(pkg.packageName)) { 6782 Slog.w(TAG, "Package " + pkg.packageName 6783 + " was transferred to another, but its .apk remains"); 6784 } 6785 6786 // Just create the setting, don't add it yet. For already existing packages 6787 // the PkgSetting exists already and doesn't have to be created. 6788 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6789 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6790 pkg.applicationInfo.primaryCpuAbi, 6791 pkg.applicationInfo.secondaryCpuAbi, 6792 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6793 user, false); 6794 if (pkgSetting == null) { 6795 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6796 "Creating application package " + pkg.packageName + " failed"); 6797 } 6798 6799 if (pkgSetting.origPackage != null) { 6800 // If we are first transitioning from an original package, 6801 // fix up the new package's name now. We need to do this after 6802 // looking up the package under its new name, so getPackageLP 6803 // can take care of fiddling things correctly. 6804 pkg.setPackageName(origPackage.name); 6805 6806 // File a report about this. 6807 String msg = "New package " + pkgSetting.realName 6808 + " renamed to replace old package " + pkgSetting.name; 6809 reportSettingsProblem(Log.WARN, msg); 6810 6811 // Make a note of it. 6812 mTransferedPackages.add(origPackage.name); 6813 6814 // No longer need to retain this. 6815 pkgSetting.origPackage = null; 6816 } 6817 6818 if (realName != null) { 6819 // Make a note of it. 6820 mTransferedPackages.add(pkg.packageName); 6821 } 6822 6823 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6824 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6825 } 6826 6827 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6828 // Check all shared libraries and map to their actual file path. 6829 // We only do this here for apps not on a system dir, because those 6830 // are the only ones that can fail an install due to this. We 6831 // will take care of the system apps by updating all of their 6832 // library paths after the scan is done. 6833 updateSharedLibrariesLPw(pkg, null); 6834 } 6835 6836 if (mFoundPolicyFile) { 6837 SELinuxMMAC.assignSeinfoValue(pkg); 6838 } 6839 6840 pkg.applicationInfo.uid = pkgSetting.appId; 6841 pkg.mExtras = pkgSetting; 6842 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6843 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6844 // We just determined the app is signed correctly, so bring 6845 // over the latest parsed certs. 6846 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6847 } else { 6848 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6849 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6850 "Package " + pkg.packageName + " upgrade keys do not match the " 6851 + "previously installed version"); 6852 } else { 6853 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6854 String msg = "System package " + pkg.packageName 6855 + " signature changed; retaining data."; 6856 reportSettingsProblem(Log.WARN, msg); 6857 } 6858 } 6859 } else { 6860 try { 6861 verifySignaturesLP(pkgSetting, pkg); 6862 // We just determined the app is signed correctly, so bring 6863 // over the latest parsed certs. 6864 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6865 } catch (PackageManagerException e) { 6866 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6867 throw e; 6868 } 6869 // The signature has changed, but this package is in the system 6870 // image... let's recover! 6871 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6872 // However... if this package is part of a shared user, but it 6873 // doesn't match the signature of the shared user, let's fail. 6874 // What this means is that you can't change the signatures 6875 // associated with an overall shared user, which doesn't seem all 6876 // that unreasonable. 6877 if (pkgSetting.sharedUser != null) { 6878 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6879 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6880 throw new PackageManagerException( 6881 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6882 "Signature mismatch for shared user : " 6883 + pkgSetting.sharedUser); 6884 } 6885 } 6886 // File a report about this. 6887 String msg = "System package " + pkg.packageName 6888 + " signature changed; retaining data."; 6889 reportSettingsProblem(Log.WARN, msg); 6890 } 6891 } 6892 // Verify that this new package doesn't have any content providers 6893 // that conflict with existing packages. Only do this if the 6894 // package isn't already installed, since we don't want to break 6895 // things that are installed. 6896 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6897 final int N = pkg.providers.size(); 6898 int i; 6899 for (i=0; i<N; i++) { 6900 PackageParser.Provider p = pkg.providers.get(i); 6901 if (p.info.authority != null) { 6902 String names[] = p.info.authority.split(";"); 6903 for (int j = 0; j < names.length; j++) { 6904 if (mProvidersByAuthority.containsKey(names[j])) { 6905 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6906 final String otherPackageName = 6907 ((other != null && other.getComponentName() != null) ? 6908 other.getComponentName().getPackageName() : "?"); 6909 throw new PackageManagerException( 6910 INSTALL_FAILED_CONFLICTING_PROVIDER, 6911 "Can't install because provider name " + names[j] 6912 + " (in package " + pkg.applicationInfo.packageName 6913 + ") is already used by " + otherPackageName); 6914 } 6915 } 6916 } 6917 } 6918 } 6919 6920 if (pkg.mAdoptPermissions != null) { 6921 // This package wants to adopt ownership of permissions from 6922 // another package. 6923 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6924 final String origName = pkg.mAdoptPermissions.get(i); 6925 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6926 if (orig != null) { 6927 if (verifyPackageUpdateLPr(orig, pkg)) { 6928 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6929 + pkg.packageName); 6930 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6931 } 6932 } 6933 } 6934 } 6935 } 6936 6937 final String pkgName = pkg.packageName; 6938 6939 final long scanFileTime = scanFile.lastModified(); 6940 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6941 pkg.applicationInfo.processName = fixProcessName( 6942 pkg.applicationInfo.packageName, 6943 pkg.applicationInfo.processName, 6944 pkg.applicationInfo.uid); 6945 6946 File dataPath; 6947 if (mPlatformPackage == pkg) { 6948 // The system package is special. 6949 dataPath = new File(Environment.getDataDirectory(), "system"); 6950 6951 pkg.applicationInfo.dataDir = dataPath.getPath(); 6952 6953 } else { 6954 // This is a normal package, need to make its data directory. 6955 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6956 UserHandle.USER_OWNER, pkg.packageName); 6957 6958 boolean uidError = false; 6959 if (dataPath.exists()) { 6960 int currentUid = 0; 6961 try { 6962 StructStat stat = Os.stat(dataPath.getPath()); 6963 currentUid = stat.st_uid; 6964 } catch (ErrnoException e) { 6965 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6966 } 6967 6968 // If we have mismatched owners for the data path, we have a problem. 6969 if (currentUid != pkg.applicationInfo.uid) { 6970 boolean recovered = false; 6971 if (currentUid == 0) { 6972 // The directory somehow became owned by root. Wow. 6973 // This is probably because the system was stopped while 6974 // installd was in the middle of messing with its libs 6975 // directory. Ask installd to fix that. 6976 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6977 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6978 if (ret >= 0) { 6979 recovered = true; 6980 String msg = "Package " + pkg.packageName 6981 + " unexpectedly changed to uid 0; recovered to " + 6982 + pkg.applicationInfo.uid; 6983 reportSettingsProblem(Log.WARN, msg); 6984 } 6985 } 6986 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6987 || (scanFlags&SCAN_BOOTING) != 0)) { 6988 // If this is a system app, we can at least delete its 6989 // current data so the application will still work. 6990 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6991 if (ret >= 0) { 6992 // TODO: Kill the processes first 6993 // Old data gone! 6994 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6995 ? "System package " : "Third party package "; 6996 String msg = prefix + pkg.packageName 6997 + " has changed from uid: " 6998 + currentUid + " to " 6999 + pkg.applicationInfo.uid + "; old data erased"; 7000 reportSettingsProblem(Log.WARN, msg); 7001 recovered = true; 7002 7003 // And now re-install the app. 7004 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7005 pkg.applicationInfo.seinfo); 7006 if (ret == -1) { 7007 // Ack should not happen! 7008 msg = prefix + pkg.packageName 7009 + " could not have data directory re-created after delete."; 7010 reportSettingsProblem(Log.WARN, msg); 7011 throw new PackageManagerException( 7012 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 7013 } 7014 } 7015 if (!recovered) { 7016 mHasSystemUidErrors = true; 7017 } 7018 } else if (!recovered) { 7019 // If we allow this install to proceed, we will be broken. 7020 // Abort, abort! 7021 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7022 "scanPackageLI"); 7023 } 7024 if (!recovered) { 7025 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7026 + pkg.applicationInfo.uid + "/fs_" 7027 + currentUid; 7028 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7029 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7030 String msg = "Package " + pkg.packageName 7031 + " has mismatched uid: " 7032 + currentUid + " on disk, " 7033 + pkg.applicationInfo.uid + " in settings"; 7034 // writer 7035 synchronized (mPackages) { 7036 mSettings.mReadMessages.append(msg); 7037 mSettings.mReadMessages.append('\n'); 7038 uidError = true; 7039 if (!pkgSetting.uidError) { 7040 reportSettingsProblem(Log.ERROR, msg); 7041 } 7042 } 7043 } 7044 } 7045 pkg.applicationInfo.dataDir = dataPath.getPath(); 7046 if (mShouldRestoreconData) { 7047 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7048 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7049 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7050 } 7051 } else { 7052 if (DEBUG_PACKAGE_SCANNING) { 7053 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7054 Log.v(TAG, "Want this data dir: " + dataPath); 7055 } 7056 //invoke installer to do the actual installation 7057 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7058 pkg.applicationInfo.seinfo); 7059 if (ret < 0) { 7060 // Error from installer 7061 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7062 "Unable to create data dirs [errorCode=" + ret + "]"); 7063 } 7064 7065 if (dataPath.exists()) { 7066 pkg.applicationInfo.dataDir = dataPath.getPath(); 7067 } else { 7068 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7069 pkg.applicationInfo.dataDir = null; 7070 } 7071 } 7072 7073 pkgSetting.uidError = uidError; 7074 } 7075 7076 final String path = scanFile.getPath(); 7077 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7078 7079 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7080 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7081 7082 // Some system apps still use directory structure for native libraries 7083 // in which case we might end up not detecting abi solely based on apk 7084 // structure. Try to detect abi based on directory structure. 7085 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7086 pkg.applicationInfo.primaryCpuAbi == null) { 7087 setBundledAppAbisAndRoots(pkg, pkgSetting); 7088 setNativeLibraryPaths(pkg); 7089 } 7090 7091 } else { 7092 if ((scanFlags & SCAN_MOVE) != 0) { 7093 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7094 // but we already have this packages package info in the PackageSetting. We just 7095 // use that and derive the native library path based on the new codepath. 7096 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7097 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7098 } 7099 7100 // Set native library paths again. For moves, the path will be updated based on the 7101 // ABIs we've determined above. For non-moves, the path will be updated based on the 7102 // ABIs we determined during compilation, but the path will depend on the final 7103 // package path (after the rename away from the stage path). 7104 setNativeLibraryPaths(pkg); 7105 } 7106 7107 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7108 final int[] userIds = sUserManager.getUserIds(); 7109 synchronized (mInstallLock) { 7110 // Make sure all user data directories are ready to roll; we're okay 7111 // if they already exist 7112 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7113 for (int userId : userIds) { 7114 if (userId != 0) { 7115 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7116 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7117 pkg.applicationInfo.seinfo); 7118 } 7119 } 7120 } 7121 7122 // Create a native library symlink only if we have native libraries 7123 // and if the native libraries are 32 bit libraries. We do not provide 7124 // this symlink for 64 bit libraries. 7125 if (pkg.applicationInfo.primaryCpuAbi != null && 7126 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7127 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7128 try { 7129 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7130 for (int userId : userIds) { 7131 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7132 nativeLibPath, userId) < 0) { 7133 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7134 "Failed linking native library dir (user=" + userId + ")"); 7135 } 7136 } 7137 } finally { 7138 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7139 } 7140 } 7141 } 7142 7143 // This is a special case for the "system" package, where the ABI is 7144 // dictated by the zygote configuration (and init.rc). We should keep track 7145 // of this ABI so that we can deal with "normal" applications that run under 7146 // the same UID correctly. 7147 if (mPlatformPackage == pkg) { 7148 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7149 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7150 } 7151 7152 // If there's a mismatch between the abi-override in the package setting 7153 // and the abiOverride specified for the install. Warn about this because we 7154 // would've already compiled the app without taking the package setting into 7155 // account. 7156 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7157 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7158 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7159 " for package: " + pkg.packageName); 7160 } 7161 } 7162 7163 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7164 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7165 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7166 7167 // Copy the derived override back to the parsed package, so that we can 7168 // update the package settings accordingly. 7169 pkg.cpuAbiOverride = cpuAbiOverride; 7170 7171 if (DEBUG_ABI_SELECTION) { 7172 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7173 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7174 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7175 } 7176 7177 // Push the derived path down into PackageSettings so we know what to 7178 // clean up at uninstall time. 7179 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7180 7181 if (DEBUG_ABI_SELECTION) { 7182 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7183 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7184 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7185 } 7186 7187 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7188 // We don't do this here during boot because we can do it all 7189 // at once after scanning all existing packages. 7190 // 7191 // We also do this *before* we perform dexopt on this package, so that 7192 // we can avoid redundant dexopts, and also to make sure we've got the 7193 // code and package path correct. 7194 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7195 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7196 } 7197 7198 if ((scanFlags & SCAN_NO_DEX) == 0) { 7199 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7200 7201 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7202 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7203 7204 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7205 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7206 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7207 } 7208 } 7209 if (mFactoryTest && pkg.requestedPermissions.contains( 7210 android.Manifest.permission.FACTORY_TEST)) { 7211 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7212 } 7213 7214 ArrayList<PackageParser.Package> clientLibPkgs = null; 7215 7216 // writer 7217 synchronized (mPackages) { 7218 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7219 // Only system apps can add new shared libraries. 7220 if (pkg.libraryNames != null) { 7221 for (int i=0; i<pkg.libraryNames.size(); i++) { 7222 String name = pkg.libraryNames.get(i); 7223 boolean allowed = false; 7224 if (pkg.isUpdatedSystemApp()) { 7225 // New library entries can only be added through the 7226 // system image. This is important to get rid of a lot 7227 // of nasty edge cases: for example if we allowed a non- 7228 // system update of the app to add a library, then uninstalling 7229 // the update would make the library go away, and assumptions 7230 // we made such as through app install filtering would now 7231 // have allowed apps on the device which aren't compatible 7232 // with it. Better to just have the restriction here, be 7233 // conservative, and create many fewer cases that can negatively 7234 // impact the user experience. 7235 final PackageSetting sysPs = mSettings 7236 .getDisabledSystemPkgLPr(pkg.packageName); 7237 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7238 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7239 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7240 allowed = true; 7241 allowed = true; 7242 break; 7243 } 7244 } 7245 } 7246 } else { 7247 allowed = true; 7248 } 7249 if (allowed) { 7250 if (!mSharedLibraries.containsKey(name)) { 7251 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7252 } else if (!name.equals(pkg.packageName)) { 7253 Slog.w(TAG, "Package " + pkg.packageName + " library " 7254 + name + " already exists; skipping"); 7255 } 7256 } else { 7257 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7258 + name + " that is not declared on system image; skipping"); 7259 } 7260 } 7261 if ((scanFlags&SCAN_BOOTING) == 0) { 7262 // If we are not booting, we need to update any applications 7263 // that are clients of our shared library. If we are booting, 7264 // this will all be done once the scan is complete. 7265 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7266 } 7267 } 7268 } 7269 } 7270 7271 // We also need to dexopt any apps that are dependent on this library. Note that 7272 // if these fail, we should abort the install since installing the library will 7273 // result in some apps being broken. 7274 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7275 try { 7276 if (clientLibPkgs != null) { 7277 if ((scanFlags & SCAN_NO_DEX) == 0) { 7278 for (int i = 0; i < clientLibPkgs.size(); i++) { 7279 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7280 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7281 null /* instruction sets */, forceDex, 7282 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7283 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7284 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7285 "scanPackageLI failed to dexopt clientLibPkgs"); 7286 } 7287 } 7288 } 7289 } 7290 } finally { 7291 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7292 } 7293 7294 // Request the ActivityManager to kill the process(only for existing packages) 7295 // so that we do not end up in a confused state while the user is still using the older 7296 // version of the application while the new one gets installed. 7297 if ((scanFlags & SCAN_REPLACING) != 0) { 7298 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7299 7300 killApplication(pkg.applicationInfo.packageName, 7301 pkg.applicationInfo.uid, "replace pkg"); 7302 7303 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7304 } 7305 7306 // Also need to kill any apps that are dependent on the library. 7307 if (clientLibPkgs != null) { 7308 for (int i=0; i<clientLibPkgs.size(); i++) { 7309 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7310 killApplication(clientPkg.applicationInfo.packageName, 7311 clientPkg.applicationInfo.uid, "update lib"); 7312 } 7313 } 7314 7315 // Make sure we're not adding any bogus keyset info 7316 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7317 ksms.assertScannedPackageValid(pkg); 7318 7319 // writer 7320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7321 7322 boolean createIdmapFailed = false; 7323 synchronized (mPackages) { 7324 // We don't expect installation to fail beyond this point 7325 7326 // Add the new setting to mSettings 7327 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7328 // Add the new setting to mPackages 7329 mPackages.put(pkg.applicationInfo.packageName, pkg); 7330 // Make sure we don't accidentally delete its data. 7331 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7332 while (iter.hasNext()) { 7333 PackageCleanItem item = iter.next(); 7334 if (pkgName.equals(item.packageName)) { 7335 iter.remove(); 7336 } 7337 } 7338 7339 // Take care of first install / last update times. 7340 if (currentTime != 0) { 7341 if (pkgSetting.firstInstallTime == 0) { 7342 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7343 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7344 pkgSetting.lastUpdateTime = currentTime; 7345 } 7346 } else if (pkgSetting.firstInstallTime == 0) { 7347 // We need *something*. Take time time stamp of the file. 7348 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7349 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7350 if (scanFileTime != pkgSetting.timeStamp) { 7351 // A package on the system image has changed; consider this 7352 // to be an update. 7353 pkgSetting.lastUpdateTime = scanFileTime; 7354 } 7355 } 7356 7357 // Add the package's KeySets to the global KeySetManagerService 7358 ksms.addScannedPackageLPw(pkg); 7359 7360 int N = pkg.providers.size(); 7361 StringBuilder r = null; 7362 int i; 7363 for (i=0; i<N; i++) { 7364 PackageParser.Provider p = pkg.providers.get(i); 7365 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7366 p.info.processName, pkg.applicationInfo.uid); 7367 mProviders.addProvider(p); 7368 p.syncable = p.info.isSyncable; 7369 if (p.info.authority != null) { 7370 String names[] = p.info.authority.split(";"); 7371 p.info.authority = null; 7372 for (int j = 0; j < names.length; j++) { 7373 if (j == 1 && p.syncable) { 7374 // We only want the first authority for a provider to possibly be 7375 // syncable, so if we already added this provider using a different 7376 // authority clear the syncable flag. We copy the provider before 7377 // changing it because the mProviders object contains a reference 7378 // to a provider that we don't want to change. 7379 // Only do this for the second authority since the resulting provider 7380 // object can be the same for all future authorities for this provider. 7381 p = new PackageParser.Provider(p); 7382 p.syncable = false; 7383 } 7384 if (!mProvidersByAuthority.containsKey(names[j])) { 7385 mProvidersByAuthority.put(names[j], p); 7386 if (p.info.authority == null) { 7387 p.info.authority = names[j]; 7388 } else { 7389 p.info.authority = p.info.authority + ";" + names[j]; 7390 } 7391 if (DEBUG_PACKAGE_SCANNING) { 7392 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7393 Log.d(TAG, "Registered content provider: " + names[j] 7394 + ", className = " + p.info.name + ", isSyncable = " 7395 + p.info.isSyncable); 7396 } 7397 } else { 7398 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7399 Slog.w(TAG, "Skipping provider name " + names[j] + 7400 " (in package " + pkg.applicationInfo.packageName + 7401 "): name already used by " 7402 + ((other != null && other.getComponentName() != null) 7403 ? other.getComponentName().getPackageName() : "?")); 7404 } 7405 } 7406 } 7407 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7408 if (r == null) { 7409 r = new StringBuilder(256); 7410 } else { 7411 r.append(' '); 7412 } 7413 r.append(p.info.name); 7414 } 7415 } 7416 if (r != null) { 7417 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7418 } 7419 7420 N = pkg.services.size(); 7421 r = null; 7422 for (i=0; i<N; i++) { 7423 PackageParser.Service s = pkg.services.get(i); 7424 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7425 s.info.processName, pkg.applicationInfo.uid); 7426 mServices.addService(s); 7427 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7428 if (r == null) { 7429 r = new StringBuilder(256); 7430 } else { 7431 r.append(' '); 7432 } 7433 r.append(s.info.name); 7434 } 7435 } 7436 if (r != null) { 7437 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7438 } 7439 7440 N = pkg.receivers.size(); 7441 r = null; 7442 for (i=0; i<N; i++) { 7443 PackageParser.Activity a = pkg.receivers.get(i); 7444 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7445 a.info.processName, pkg.applicationInfo.uid); 7446 mReceivers.addActivity(a, "receiver"); 7447 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7448 if (r == null) { 7449 r = new StringBuilder(256); 7450 } else { 7451 r.append(' '); 7452 } 7453 r.append(a.info.name); 7454 } 7455 } 7456 if (r != null) { 7457 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7458 } 7459 7460 N = pkg.activities.size(); 7461 r = null; 7462 for (i=0; i<N; i++) { 7463 PackageParser.Activity a = pkg.activities.get(i); 7464 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7465 a.info.processName, pkg.applicationInfo.uid); 7466 mActivities.addActivity(a, "activity"); 7467 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7468 if (r == null) { 7469 r = new StringBuilder(256); 7470 } else { 7471 r.append(' '); 7472 } 7473 r.append(a.info.name); 7474 } 7475 } 7476 if (r != null) { 7477 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7478 } 7479 7480 N = pkg.permissionGroups.size(); 7481 r = null; 7482 for (i=0; i<N; i++) { 7483 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7484 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7485 if (cur == null) { 7486 mPermissionGroups.put(pg.info.name, pg); 7487 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7488 if (r == null) { 7489 r = new StringBuilder(256); 7490 } else { 7491 r.append(' '); 7492 } 7493 r.append(pg.info.name); 7494 } 7495 } else { 7496 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7497 + pg.info.packageName + " ignored: original from " 7498 + cur.info.packageName); 7499 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7500 if (r == null) { 7501 r = new StringBuilder(256); 7502 } else { 7503 r.append(' '); 7504 } 7505 r.append("DUP:"); 7506 r.append(pg.info.name); 7507 } 7508 } 7509 } 7510 if (r != null) { 7511 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7512 } 7513 7514 N = pkg.permissions.size(); 7515 r = null; 7516 for (i=0; i<N; i++) { 7517 PackageParser.Permission p = pkg.permissions.get(i); 7518 7519 // Assume by default that we did not install this permission into the system. 7520 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7521 7522 // Now that permission groups have a special meaning, we ignore permission 7523 // groups for legacy apps to prevent unexpected behavior. In particular, 7524 // permissions for one app being granted to someone just becuase they happen 7525 // to be in a group defined by another app (before this had no implications). 7526 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7527 p.group = mPermissionGroups.get(p.info.group); 7528 // Warn for a permission in an unknown group. 7529 if (p.info.group != null && p.group == null) { 7530 Slog.w(TAG, "Permission " + p.info.name + " from package " 7531 + p.info.packageName + " in an unknown group " + p.info.group); 7532 } 7533 } 7534 7535 ArrayMap<String, BasePermission> permissionMap = 7536 p.tree ? mSettings.mPermissionTrees 7537 : mSettings.mPermissions; 7538 BasePermission bp = permissionMap.get(p.info.name); 7539 7540 // Allow system apps to redefine non-system permissions 7541 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7542 final boolean currentOwnerIsSystem = (bp.perm != null 7543 && isSystemApp(bp.perm.owner)); 7544 if (isSystemApp(p.owner)) { 7545 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7546 // It's a built-in permission and no owner, take ownership now 7547 bp.packageSetting = pkgSetting; 7548 bp.perm = p; 7549 bp.uid = pkg.applicationInfo.uid; 7550 bp.sourcePackage = p.info.packageName; 7551 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7552 } else if (!currentOwnerIsSystem) { 7553 String msg = "New decl " + p.owner + " of permission " 7554 + p.info.name + " is system; overriding " + bp.sourcePackage; 7555 reportSettingsProblem(Log.WARN, msg); 7556 bp = null; 7557 } 7558 } 7559 } 7560 7561 if (bp == null) { 7562 bp = new BasePermission(p.info.name, p.info.packageName, 7563 BasePermission.TYPE_NORMAL); 7564 permissionMap.put(p.info.name, bp); 7565 } 7566 7567 if (bp.perm == null) { 7568 if (bp.sourcePackage == null 7569 || bp.sourcePackage.equals(p.info.packageName)) { 7570 BasePermission tree = findPermissionTreeLP(p.info.name); 7571 if (tree == null 7572 || tree.sourcePackage.equals(p.info.packageName)) { 7573 bp.packageSetting = pkgSetting; 7574 bp.perm = p; 7575 bp.uid = pkg.applicationInfo.uid; 7576 bp.sourcePackage = p.info.packageName; 7577 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7578 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7579 if (r == null) { 7580 r = new StringBuilder(256); 7581 } else { 7582 r.append(' '); 7583 } 7584 r.append(p.info.name); 7585 } 7586 } else { 7587 Slog.w(TAG, "Permission " + p.info.name + " from package " 7588 + p.info.packageName + " ignored: base tree " 7589 + tree.name + " is from package " 7590 + tree.sourcePackage); 7591 } 7592 } else { 7593 Slog.w(TAG, "Permission " + p.info.name + " from package " 7594 + p.info.packageName + " ignored: original from " 7595 + bp.sourcePackage); 7596 } 7597 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7598 if (r == null) { 7599 r = new StringBuilder(256); 7600 } else { 7601 r.append(' '); 7602 } 7603 r.append("DUP:"); 7604 r.append(p.info.name); 7605 } 7606 if (bp.perm == p) { 7607 bp.protectionLevel = p.info.protectionLevel; 7608 } 7609 } 7610 7611 if (r != null) { 7612 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7613 } 7614 7615 N = pkg.instrumentation.size(); 7616 r = null; 7617 for (i=0; i<N; i++) { 7618 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7619 a.info.packageName = pkg.applicationInfo.packageName; 7620 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7621 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7622 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7623 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7624 a.info.dataDir = pkg.applicationInfo.dataDir; 7625 7626 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7627 // need other information about the application, like the ABI and what not ? 7628 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7629 mInstrumentation.put(a.getComponentName(), a); 7630 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7631 if (r == null) { 7632 r = new StringBuilder(256); 7633 } else { 7634 r.append(' '); 7635 } 7636 r.append(a.info.name); 7637 } 7638 } 7639 if (r != null) { 7640 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7641 } 7642 7643 if (pkg.protectedBroadcasts != null) { 7644 N = pkg.protectedBroadcasts.size(); 7645 for (i=0; i<N; i++) { 7646 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7647 } 7648 } 7649 7650 pkgSetting.setTimeStamp(scanFileTime); 7651 7652 // Create idmap files for pairs of (packages, overlay packages). 7653 // Note: "android", ie framework-res.apk, is handled by native layers. 7654 if (pkg.mOverlayTarget != null) { 7655 // This is an overlay package. 7656 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7657 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7658 mOverlays.put(pkg.mOverlayTarget, 7659 new ArrayMap<String, PackageParser.Package>()); 7660 } 7661 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7662 map.put(pkg.packageName, pkg); 7663 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7664 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7665 createIdmapFailed = true; 7666 } 7667 } 7668 } else if (mOverlays.containsKey(pkg.packageName) && 7669 !pkg.packageName.equals("android")) { 7670 // This is a regular package, with one or more known overlay packages. 7671 createIdmapsForPackageLI(pkg); 7672 } 7673 } 7674 7675 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7676 7677 if (createIdmapFailed) { 7678 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7679 "scanPackageLI failed to createIdmap"); 7680 } 7681 return pkg; 7682 } 7683 7684 /** 7685 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7686 * is derived purely on the basis of the contents of {@code scanFile} and 7687 * {@code cpuAbiOverride}. 7688 * 7689 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7690 */ 7691 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7692 String cpuAbiOverride, boolean extractLibs) 7693 throws PackageManagerException { 7694 // TODO: We can probably be smarter about this stuff. For installed apps, 7695 // we can calculate this information at install time once and for all. For 7696 // system apps, we can probably assume that this information doesn't change 7697 // after the first boot scan. As things stand, we do lots of unnecessary work. 7698 7699 // Give ourselves some initial paths; we'll come back for another 7700 // pass once we've determined ABI below. 7701 setNativeLibraryPaths(pkg); 7702 7703 // We would never need to extract libs for forward-locked and external packages, 7704 // since the container service will do it for us. We shouldn't attempt to 7705 // extract libs from system app when it was not updated. 7706 if (pkg.isForwardLocked() || isExternal(pkg) || 7707 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7708 extractLibs = false; 7709 } 7710 7711 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7712 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7713 7714 NativeLibraryHelper.Handle handle = null; 7715 try { 7716 handle = NativeLibraryHelper.Handle.create(pkg); 7717 // TODO(multiArch): This can be null for apps that didn't go through the 7718 // usual installation process. We can calculate it again, like we 7719 // do during install time. 7720 // 7721 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7722 // unnecessary. 7723 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7724 7725 // Null out the abis so that they can be recalculated. 7726 pkg.applicationInfo.primaryCpuAbi = null; 7727 pkg.applicationInfo.secondaryCpuAbi = null; 7728 if (isMultiArch(pkg.applicationInfo)) { 7729 // Warn if we've set an abiOverride for multi-lib packages.. 7730 // By definition, we need to copy both 32 and 64 bit libraries for 7731 // such packages. 7732 if (pkg.cpuAbiOverride != null 7733 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7734 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7735 } 7736 7737 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7738 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7739 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7740 if (extractLibs) { 7741 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7742 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7743 useIsaSpecificSubdirs); 7744 } else { 7745 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7746 } 7747 } 7748 7749 maybeThrowExceptionForMultiArchCopy( 7750 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7751 7752 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7753 if (extractLibs) { 7754 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7755 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7756 useIsaSpecificSubdirs); 7757 } else { 7758 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7759 } 7760 } 7761 7762 maybeThrowExceptionForMultiArchCopy( 7763 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7764 7765 if (abi64 >= 0) { 7766 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7767 } 7768 7769 if (abi32 >= 0) { 7770 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7771 if (abi64 >= 0) { 7772 pkg.applicationInfo.secondaryCpuAbi = abi; 7773 } else { 7774 pkg.applicationInfo.primaryCpuAbi = abi; 7775 } 7776 } 7777 } else { 7778 String[] abiList = (cpuAbiOverride != null) ? 7779 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7780 7781 // Enable gross and lame hacks for apps that are built with old 7782 // SDK tools. We must scan their APKs for renderscript bitcode and 7783 // not launch them if it's present. Don't bother checking on devices 7784 // that don't have 64 bit support. 7785 boolean needsRenderScriptOverride = false; 7786 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7787 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7788 abiList = Build.SUPPORTED_32_BIT_ABIS; 7789 needsRenderScriptOverride = true; 7790 } 7791 7792 final int copyRet; 7793 if (extractLibs) { 7794 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7795 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7796 } else { 7797 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7798 } 7799 7800 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7801 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7802 "Error unpackaging native libs for app, errorCode=" + copyRet); 7803 } 7804 7805 if (copyRet >= 0) { 7806 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7807 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7808 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7809 } else if (needsRenderScriptOverride) { 7810 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7811 } 7812 } 7813 } catch (IOException ioe) { 7814 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7815 } finally { 7816 IoUtils.closeQuietly(handle); 7817 } 7818 7819 // Now that we've calculated the ABIs and determined if it's an internal app, 7820 // we will go ahead and populate the nativeLibraryPath. 7821 setNativeLibraryPaths(pkg); 7822 } 7823 7824 /** 7825 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7826 * i.e, so that all packages can be run inside a single process if required. 7827 * 7828 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7829 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7830 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7831 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7832 * updating a package that belongs to a shared user. 7833 * 7834 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7835 * adds unnecessary complexity. 7836 */ 7837 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7838 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7839 String requiredInstructionSet = null; 7840 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7841 requiredInstructionSet = VMRuntime.getInstructionSet( 7842 scannedPackage.applicationInfo.primaryCpuAbi); 7843 } 7844 7845 PackageSetting requirer = null; 7846 for (PackageSetting ps : packagesForUser) { 7847 // If packagesForUser contains scannedPackage, we skip it. This will happen 7848 // when scannedPackage is an update of an existing package. Without this check, 7849 // we will never be able to change the ABI of any package belonging to a shared 7850 // user, even if it's compatible with other packages. 7851 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7852 if (ps.primaryCpuAbiString == null) { 7853 continue; 7854 } 7855 7856 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7857 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7858 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7859 // this but there's not much we can do. 7860 String errorMessage = "Instruction set mismatch, " 7861 + ((requirer == null) ? "[caller]" : requirer) 7862 + " requires " + requiredInstructionSet + " whereas " + ps 7863 + " requires " + instructionSet; 7864 Slog.w(TAG, errorMessage); 7865 } 7866 7867 if (requiredInstructionSet == null) { 7868 requiredInstructionSet = instructionSet; 7869 requirer = ps; 7870 } 7871 } 7872 } 7873 7874 if (requiredInstructionSet != null) { 7875 String adjustedAbi; 7876 if (requirer != null) { 7877 // requirer != null implies that either scannedPackage was null or that scannedPackage 7878 // did not require an ABI, in which case we have to adjust scannedPackage to match 7879 // the ABI of the set (which is the same as requirer's ABI) 7880 adjustedAbi = requirer.primaryCpuAbiString; 7881 if (scannedPackage != null) { 7882 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7883 } 7884 } else { 7885 // requirer == null implies that we're updating all ABIs in the set to 7886 // match scannedPackage. 7887 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7888 } 7889 7890 for (PackageSetting ps : packagesForUser) { 7891 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7892 if (ps.primaryCpuAbiString != null) { 7893 continue; 7894 } 7895 7896 ps.primaryCpuAbiString = adjustedAbi; 7897 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7898 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7899 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7900 7901 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7902 7903 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7904 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7905 7906 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7907 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7908 ps.primaryCpuAbiString = null; 7909 ps.pkg.applicationInfo.primaryCpuAbi = null; 7910 return; 7911 } else { 7912 mInstaller.rmdex(ps.codePathString, 7913 getDexCodeInstructionSet(getPreferredInstructionSet())); 7914 } 7915 } 7916 } 7917 } 7918 } 7919 } 7920 7921 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7922 synchronized (mPackages) { 7923 mResolverReplaced = true; 7924 // Set up information for custom user intent resolution activity. 7925 mResolveActivity.applicationInfo = pkg.applicationInfo; 7926 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7927 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7928 mResolveActivity.processName = pkg.applicationInfo.packageName; 7929 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7930 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7931 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7932 mResolveActivity.theme = 0; 7933 mResolveActivity.exported = true; 7934 mResolveActivity.enabled = true; 7935 mResolveInfo.activityInfo = mResolveActivity; 7936 mResolveInfo.priority = 0; 7937 mResolveInfo.preferredOrder = 0; 7938 mResolveInfo.match = 0; 7939 mResolveComponentName = mCustomResolverComponentName; 7940 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7941 mResolveComponentName); 7942 } 7943 } 7944 7945 private static String calculateBundledApkRoot(final String codePathString) { 7946 final File codePath = new File(codePathString); 7947 final File codeRoot; 7948 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7949 codeRoot = Environment.getRootDirectory(); 7950 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7951 codeRoot = Environment.getOemDirectory(); 7952 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7953 codeRoot = Environment.getVendorDirectory(); 7954 } else { 7955 // Unrecognized code path; take its top real segment as the apk root: 7956 // e.g. /something/app/blah.apk => /something 7957 try { 7958 File f = codePath.getCanonicalFile(); 7959 File parent = f.getParentFile(); // non-null because codePath is a file 7960 File tmp; 7961 while ((tmp = parent.getParentFile()) != null) { 7962 f = parent; 7963 parent = tmp; 7964 } 7965 codeRoot = f; 7966 Slog.w(TAG, "Unrecognized code path " 7967 + codePath + " - using " + codeRoot); 7968 } catch (IOException e) { 7969 // Can't canonicalize the code path -- shenanigans? 7970 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7971 return Environment.getRootDirectory().getPath(); 7972 } 7973 } 7974 return codeRoot.getPath(); 7975 } 7976 7977 /** 7978 * Derive and set the location of native libraries for the given package, 7979 * which varies depending on where and how the package was installed. 7980 */ 7981 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7982 final ApplicationInfo info = pkg.applicationInfo; 7983 final String codePath = pkg.codePath; 7984 final File codeFile = new File(codePath); 7985 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7986 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7987 7988 info.nativeLibraryRootDir = null; 7989 info.nativeLibraryRootRequiresIsa = false; 7990 info.nativeLibraryDir = null; 7991 info.secondaryNativeLibraryDir = null; 7992 7993 if (isApkFile(codeFile)) { 7994 // Monolithic install 7995 if (bundledApp) { 7996 // If "/system/lib64/apkname" exists, assume that is the per-package 7997 // native library directory to use; otherwise use "/system/lib/apkname". 7998 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7999 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8000 getPrimaryInstructionSet(info)); 8001 8002 // This is a bundled system app so choose the path based on the ABI. 8003 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8004 // is just the default path. 8005 final String apkName = deriveCodePathName(codePath); 8006 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8007 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8008 apkName).getAbsolutePath(); 8009 8010 if (info.secondaryCpuAbi != null) { 8011 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8012 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8013 secondaryLibDir, apkName).getAbsolutePath(); 8014 } 8015 } else if (asecApp) { 8016 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8017 .getAbsolutePath(); 8018 } else { 8019 final String apkName = deriveCodePathName(codePath); 8020 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8021 .getAbsolutePath(); 8022 } 8023 8024 info.nativeLibraryRootRequiresIsa = false; 8025 info.nativeLibraryDir = info.nativeLibraryRootDir; 8026 } else { 8027 // Cluster install 8028 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8029 info.nativeLibraryRootRequiresIsa = true; 8030 8031 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8032 getPrimaryInstructionSet(info)).getAbsolutePath(); 8033 8034 if (info.secondaryCpuAbi != null) { 8035 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8036 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8037 } 8038 } 8039 } 8040 8041 /** 8042 * Calculate the abis and roots for a bundled app. These can uniquely 8043 * be determined from the contents of the system partition, i.e whether 8044 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8045 * of this information, and instead assume that the system was built 8046 * sensibly. 8047 */ 8048 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8049 PackageSetting pkgSetting) { 8050 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8051 8052 // If "/system/lib64/apkname" exists, assume that is the per-package 8053 // native library directory to use; otherwise use "/system/lib/apkname". 8054 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8055 setBundledAppAbi(pkg, apkRoot, apkName); 8056 // pkgSetting might be null during rescan following uninstall of updates 8057 // to a bundled app, so accommodate that possibility. The settings in 8058 // that case will be established later from the parsed package. 8059 // 8060 // If the settings aren't null, sync them up with what we've just derived. 8061 // note that apkRoot isn't stored in the package settings. 8062 if (pkgSetting != null) { 8063 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8064 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8065 } 8066 } 8067 8068 /** 8069 * Deduces the ABI of a bundled app and sets the relevant fields on the 8070 * parsed pkg object. 8071 * 8072 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8073 * under which system libraries are installed. 8074 * @param apkName the name of the installed package. 8075 */ 8076 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8077 final File codeFile = new File(pkg.codePath); 8078 8079 final boolean has64BitLibs; 8080 final boolean has32BitLibs; 8081 if (isApkFile(codeFile)) { 8082 // Monolithic install 8083 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8084 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8085 } else { 8086 // Cluster install 8087 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8088 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8089 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8090 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8091 has64BitLibs = (new File(rootDir, isa)).exists(); 8092 } else { 8093 has64BitLibs = false; 8094 } 8095 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8096 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8097 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8098 has32BitLibs = (new File(rootDir, isa)).exists(); 8099 } else { 8100 has32BitLibs = false; 8101 } 8102 } 8103 8104 if (has64BitLibs && !has32BitLibs) { 8105 // The package has 64 bit libs, but not 32 bit libs. Its primary 8106 // ABI should be 64 bit. We can safely assume here that the bundled 8107 // native libraries correspond to the most preferred ABI in the list. 8108 8109 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8110 pkg.applicationInfo.secondaryCpuAbi = null; 8111 } else if (has32BitLibs && !has64BitLibs) { 8112 // The package has 32 bit libs but not 64 bit libs. Its primary 8113 // ABI should be 32 bit. 8114 8115 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8116 pkg.applicationInfo.secondaryCpuAbi = null; 8117 } else if (has32BitLibs && has64BitLibs) { 8118 // The application has both 64 and 32 bit bundled libraries. We check 8119 // here that the app declares multiArch support, and warn if it doesn't. 8120 // 8121 // We will be lenient here and record both ABIs. The primary will be the 8122 // ABI that's higher on the list, i.e, a device that's configured to prefer 8123 // 64 bit apps will see a 64 bit primary ABI, 8124 8125 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8126 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8127 } 8128 8129 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8130 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8131 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8132 } else { 8133 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8134 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8135 } 8136 } else { 8137 pkg.applicationInfo.primaryCpuAbi = null; 8138 pkg.applicationInfo.secondaryCpuAbi = null; 8139 } 8140 } 8141 8142 private void killApplication(String pkgName, int appId, String reason) { 8143 // Request the ActivityManager to kill the process(only for existing packages) 8144 // so that we do not end up in a confused state while the user is still using the older 8145 // version of the application while the new one gets installed. 8146 IActivityManager am = ActivityManagerNative.getDefault(); 8147 if (am != null) { 8148 try { 8149 am.killApplicationWithAppId(pkgName, appId, reason); 8150 } catch (RemoteException e) { 8151 } 8152 } 8153 } 8154 8155 void removePackageLI(PackageSetting ps, boolean chatty) { 8156 if (DEBUG_INSTALL) { 8157 if (chatty) 8158 Log.d(TAG, "Removing package " + ps.name); 8159 } 8160 8161 // writer 8162 synchronized (mPackages) { 8163 mPackages.remove(ps.name); 8164 final PackageParser.Package pkg = ps.pkg; 8165 if (pkg != null) { 8166 cleanPackageDataStructuresLILPw(pkg, chatty); 8167 } 8168 } 8169 } 8170 8171 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8172 if (DEBUG_INSTALL) { 8173 if (chatty) 8174 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8175 } 8176 8177 // writer 8178 synchronized (mPackages) { 8179 mPackages.remove(pkg.applicationInfo.packageName); 8180 cleanPackageDataStructuresLILPw(pkg, chatty); 8181 } 8182 } 8183 8184 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8185 int N = pkg.providers.size(); 8186 StringBuilder r = null; 8187 int i; 8188 for (i=0; i<N; i++) { 8189 PackageParser.Provider p = pkg.providers.get(i); 8190 mProviders.removeProvider(p); 8191 if (p.info.authority == null) { 8192 8193 /* There was another ContentProvider with this authority when 8194 * this app was installed so this authority is null, 8195 * Ignore it as we don't have to unregister the provider. 8196 */ 8197 continue; 8198 } 8199 String names[] = p.info.authority.split(";"); 8200 for (int j = 0; j < names.length; j++) { 8201 if (mProvidersByAuthority.get(names[j]) == p) { 8202 mProvidersByAuthority.remove(names[j]); 8203 if (DEBUG_REMOVE) { 8204 if (chatty) 8205 Log.d(TAG, "Unregistered content provider: " + names[j] 8206 + ", className = " + p.info.name + ", isSyncable = " 8207 + p.info.isSyncable); 8208 } 8209 } 8210 } 8211 if (DEBUG_REMOVE && chatty) { 8212 if (r == null) { 8213 r = new StringBuilder(256); 8214 } else { 8215 r.append(' '); 8216 } 8217 r.append(p.info.name); 8218 } 8219 } 8220 if (r != null) { 8221 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8222 } 8223 8224 N = pkg.services.size(); 8225 r = null; 8226 for (i=0; i<N; i++) { 8227 PackageParser.Service s = pkg.services.get(i); 8228 mServices.removeService(s); 8229 if (chatty) { 8230 if (r == null) { 8231 r = new StringBuilder(256); 8232 } else { 8233 r.append(' '); 8234 } 8235 r.append(s.info.name); 8236 } 8237 } 8238 if (r != null) { 8239 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8240 } 8241 8242 N = pkg.receivers.size(); 8243 r = null; 8244 for (i=0; i<N; i++) { 8245 PackageParser.Activity a = pkg.receivers.get(i); 8246 mReceivers.removeActivity(a, "receiver"); 8247 if (DEBUG_REMOVE && chatty) { 8248 if (r == null) { 8249 r = new StringBuilder(256); 8250 } else { 8251 r.append(' '); 8252 } 8253 r.append(a.info.name); 8254 } 8255 } 8256 if (r != null) { 8257 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8258 } 8259 8260 N = pkg.activities.size(); 8261 r = null; 8262 for (i=0; i<N; i++) { 8263 PackageParser.Activity a = pkg.activities.get(i); 8264 mActivities.removeActivity(a, "activity"); 8265 if (DEBUG_REMOVE && chatty) { 8266 if (r == null) { 8267 r = new StringBuilder(256); 8268 } else { 8269 r.append(' '); 8270 } 8271 r.append(a.info.name); 8272 } 8273 } 8274 if (r != null) { 8275 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8276 } 8277 8278 N = pkg.permissions.size(); 8279 r = null; 8280 for (i=0; i<N; i++) { 8281 PackageParser.Permission p = pkg.permissions.get(i); 8282 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8283 if (bp == null) { 8284 bp = mSettings.mPermissionTrees.get(p.info.name); 8285 } 8286 if (bp != null && bp.perm == p) { 8287 bp.perm = null; 8288 if (DEBUG_REMOVE && chatty) { 8289 if (r == null) { 8290 r = new StringBuilder(256); 8291 } else { 8292 r.append(' '); 8293 } 8294 r.append(p.info.name); 8295 } 8296 } 8297 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8298 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8299 if (appOpPerms != null) { 8300 appOpPerms.remove(pkg.packageName); 8301 } 8302 } 8303 } 8304 if (r != null) { 8305 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8306 } 8307 8308 N = pkg.requestedPermissions.size(); 8309 r = null; 8310 for (i=0; i<N; i++) { 8311 String perm = pkg.requestedPermissions.get(i); 8312 BasePermission bp = mSettings.mPermissions.get(perm); 8313 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8314 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8315 if (appOpPerms != null) { 8316 appOpPerms.remove(pkg.packageName); 8317 if (appOpPerms.isEmpty()) { 8318 mAppOpPermissionPackages.remove(perm); 8319 } 8320 } 8321 } 8322 } 8323 if (r != null) { 8324 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8325 } 8326 8327 N = pkg.instrumentation.size(); 8328 r = null; 8329 for (i=0; i<N; i++) { 8330 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8331 mInstrumentation.remove(a.getComponentName()); 8332 if (DEBUG_REMOVE && chatty) { 8333 if (r == null) { 8334 r = new StringBuilder(256); 8335 } else { 8336 r.append(' '); 8337 } 8338 r.append(a.info.name); 8339 } 8340 } 8341 if (r != null) { 8342 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8343 } 8344 8345 r = null; 8346 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8347 // Only system apps can hold shared libraries. 8348 if (pkg.libraryNames != null) { 8349 for (i=0; i<pkg.libraryNames.size(); i++) { 8350 String name = pkg.libraryNames.get(i); 8351 SharedLibraryEntry cur = mSharedLibraries.get(name); 8352 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8353 mSharedLibraries.remove(name); 8354 if (DEBUG_REMOVE && chatty) { 8355 if (r == null) { 8356 r = new StringBuilder(256); 8357 } else { 8358 r.append(' '); 8359 } 8360 r.append(name); 8361 } 8362 } 8363 } 8364 } 8365 } 8366 if (r != null) { 8367 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8368 } 8369 } 8370 8371 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8372 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8373 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8374 return true; 8375 } 8376 } 8377 return false; 8378 } 8379 8380 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8381 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8382 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8383 8384 private void updatePermissionsLPw(String changingPkg, 8385 PackageParser.Package pkgInfo, int flags) { 8386 // Make sure there are no dangling permission trees. 8387 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8388 while (it.hasNext()) { 8389 final BasePermission bp = it.next(); 8390 if (bp.packageSetting == null) { 8391 // We may not yet have parsed the package, so just see if 8392 // we still know about its settings. 8393 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8394 } 8395 if (bp.packageSetting == null) { 8396 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8397 + " from package " + bp.sourcePackage); 8398 it.remove(); 8399 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8400 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8401 Slog.i(TAG, "Removing old permission tree: " + bp.name 8402 + " from package " + bp.sourcePackage); 8403 flags |= UPDATE_PERMISSIONS_ALL; 8404 it.remove(); 8405 } 8406 } 8407 } 8408 8409 // Make sure all dynamic permissions have been assigned to a package, 8410 // and make sure there are no dangling permissions. 8411 it = mSettings.mPermissions.values().iterator(); 8412 while (it.hasNext()) { 8413 final BasePermission bp = it.next(); 8414 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8415 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8416 + bp.name + " pkg=" + bp.sourcePackage 8417 + " info=" + bp.pendingInfo); 8418 if (bp.packageSetting == null && bp.pendingInfo != null) { 8419 final BasePermission tree = findPermissionTreeLP(bp.name); 8420 if (tree != null && tree.perm != null) { 8421 bp.packageSetting = tree.packageSetting; 8422 bp.perm = new PackageParser.Permission(tree.perm.owner, 8423 new PermissionInfo(bp.pendingInfo)); 8424 bp.perm.info.packageName = tree.perm.info.packageName; 8425 bp.perm.info.name = bp.name; 8426 bp.uid = tree.uid; 8427 } 8428 } 8429 } 8430 if (bp.packageSetting == null) { 8431 // We may not yet have parsed the package, so just see if 8432 // we still know about its settings. 8433 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8434 } 8435 if (bp.packageSetting == null) { 8436 Slog.w(TAG, "Removing dangling permission: " + bp.name 8437 + " from package " + bp.sourcePackage); 8438 it.remove(); 8439 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8440 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8441 Slog.i(TAG, "Removing old permission: " + bp.name 8442 + " from package " + bp.sourcePackage); 8443 flags |= UPDATE_PERMISSIONS_ALL; 8444 it.remove(); 8445 } 8446 } 8447 } 8448 8449 // Now update the permissions for all packages, in particular 8450 // replace the granted permissions of the system packages. 8451 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8452 for (PackageParser.Package pkg : mPackages.values()) { 8453 if (pkg != pkgInfo) { 8454 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8455 changingPkg); 8456 } 8457 } 8458 } 8459 8460 if (pkgInfo != null) { 8461 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8462 } 8463 } 8464 8465 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8466 String packageOfInterest) { 8467 // IMPORTANT: There are two types of permissions: install and runtime. 8468 // Install time permissions are granted when the app is installed to 8469 // all device users and users added in the future. Runtime permissions 8470 // are granted at runtime explicitly to specific users. Normal and signature 8471 // protected permissions are install time permissions. Dangerous permissions 8472 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8473 // otherwise they are runtime permissions. This function does not manage 8474 // runtime permissions except for the case an app targeting Lollipop MR1 8475 // being upgraded to target a newer SDK, in which case dangerous permissions 8476 // are transformed from install time to runtime ones. 8477 8478 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8479 if (ps == null) { 8480 return; 8481 } 8482 8483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8484 8485 PermissionsState permissionsState = ps.getPermissionsState(); 8486 PermissionsState origPermissions = permissionsState; 8487 8488 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8489 8490 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8491 8492 boolean changedInstallPermission = false; 8493 8494 if (replace) { 8495 ps.installPermissionsFixed = false; 8496 if (!ps.isSharedUser()) { 8497 origPermissions = new PermissionsState(permissionsState); 8498 permissionsState.reset(); 8499 } 8500 } 8501 8502 permissionsState.setGlobalGids(mGlobalGids); 8503 8504 final int N = pkg.requestedPermissions.size(); 8505 for (int i=0; i<N; i++) { 8506 final String name = pkg.requestedPermissions.get(i); 8507 final BasePermission bp = mSettings.mPermissions.get(name); 8508 8509 if (DEBUG_INSTALL) { 8510 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8511 } 8512 8513 if (bp == null || bp.packageSetting == null) { 8514 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8515 Slog.w(TAG, "Unknown permission " + name 8516 + " in package " + pkg.packageName); 8517 } 8518 continue; 8519 } 8520 8521 final String perm = bp.name; 8522 boolean allowedSig = false; 8523 int grant = GRANT_DENIED; 8524 8525 // Keep track of app op permissions. 8526 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8527 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8528 if (pkgs == null) { 8529 pkgs = new ArraySet<>(); 8530 mAppOpPermissionPackages.put(bp.name, pkgs); 8531 } 8532 pkgs.add(pkg.packageName); 8533 } 8534 8535 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8536 switch (level) { 8537 case PermissionInfo.PROTECTION_NORMAL: { 8538 // For all apps normal permissions are install time ones. 8539 grant = GRANT_INSTALL; 8540 } break; 8541 8542 case PermissionInfo.PROTECTION_DANGEROUS: { 8543 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8544 // For legacy apps dangerous permissions are install time ones. 8545 grant = GRANT_INSTALL_LEGACY; 8546 } else if (origPermissions.hasInstallPermission(bp.name)) { 8547 // For legacy apps that became modern, install becomes runtime. 8548 grant = GRANT_UPGRADE; 8549 } else if (mPromoteSystemApps 8550 && isSystemApp(ps) 8551 && mExistingSystemPackages.contains(ps.name)) { 8552 // For legacy system apps, install becomes runtime. 8553 // We cannot check hasInstallPermission() for system apps since those 8554 // permissions were granted implicitly and not persisted pre-M. 8555 grant = GRANT_UPGRADE; 8556 } else { 8557 // For modern apps keep runtime permissions unchanged. 8558 grant = GRANT_RUNTIME; 8559 } 8560 } break; 8561 8562 case PermissionInfo.PROTECTION_SIGNATURE: { 8563 // For all apps signature permissions are install time ones. 8564 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8565 if (allowedSig) { 8566 grant = GRANT_INSTALL; 8567 } 8568 } break; 8569 } 8570 8571 if (DEBUG_INSTALL) { 8572 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8573 } 8574 8575 if (grant != GRANT_DENIED) { 8576 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8577 // If this is an existing, non-system package, then 8578 // we can't add any new permissions to it. 8579 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8580 // Except... if this is a permission that was added 8581 // to the platform (note: need to only do this when 8582 // updating the platform). 8583 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8584 grant = GRANT_DENIED; 8585 } 8586 } 8587 } 8588 8589 switch (grant) { 8590 case GRANT_INSTALL: { 8591 // Revoke this as runtime permission to handle the case of 8592 // a runtime permission being downgraded to an install one. 8593 for (int userId : UserManagerService.getInstance().getUserIds()) { 8594 if (origPermissions.getRuntimePermissionState( 8595 bp.name, userId) != null) { 8596 // Revoke the runtime permission and clear the flags. 8597 origPermissions.revokeRuntimePermission(bp, userId); 8598 origPermissions.updatePermissionFlags(bp, userId, 8599 PackageManager.MASK_PERMISSION_FLAGS, 0); 8600 // If we revoked a permission permission, we have to write. 8601 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8602 changedRuntimePermissionUserIds, userId); 8603 } 8604 } 8605 // Grant an install permission. 8606 if (permissionsState.grantInstallPermission(bp) != 8607 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8608 changedInstallPermission = true; 8609 } 8610 } break; 8611 8612 case GRANT_INSTALL_LEGACY: { 8613 // Grant an install permission. 8614 if (permissionsState.grantInstallPermission(bp) != 8615 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8616 changedInstallPermission = true; 8617 } 8618 } break; 8619 8620 case GRANT_RUNTIME: { 8621 // Grant previously granted runtime permissions. 8622 for (int userId : UserManagerService.getInstance().getUserIds()) { 8623 PermissionState permissionState = origPermissions 8624 .getRuntimePermissionState(bp.name, userId); 8625 final int flags = permissionState != null 8626 ? permissionState.getFlags() : 0; 8627 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8628 if (permissionsState.grantRuntimePermission(bp, userId) == 8629 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8630 // If we cannot put the permission as it was, we have to write. 8631 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8632 changedRuntimePermissionUserIds, userId); 8633 } 8634 } 8635 // Propagate the permission flags. 8636 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8637 } 8638 } break; 8639 8640 case GRANT_UPGRADE: { 8641 // Grant runtime permissions for a previously held install permission. 8642 PermissionState permissionState = origPermissions 8643 .getInstallPermissionState(bp.name); 8644 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8645 8646 if (origPermissions.revokeInstallPermission(bp) 8647 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8648 // We will be transferring the permission flags, so clear them. 8649 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8650 PackageManager.MASK_PERMISSION_FLAGS, 0); 8651 changedInstallPermission = true; 8652 } 8653 8654 // If the permission is not to be promoted to runtime we ignore it and 8655 // also its other flags as they are not applicable to install permissions. 8656 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8657 for (int userId : currentUserIds) { 8658 if (permissionsState.grantRuntimePermission(bp, userId) != 8659 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8660 // Transfer the permission flags. 8661 permissionsState.updatePermissionFlags(bp, userId, 8662 flags, flags); 8663 // If we granted the permission, we have to write. 8664 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8665 changedRuntimePermissionUserIds, userId); 8666 } 8667 } 8668 } 8669 } break; 8670 8671 default: { 8672 if (packageOfInterest == null 8673 || packageOfInterest.equals(pkg.packageName)) { 8674 Slog.w(TAG, "Not granting permission " + perm 8675 + " to package " + pkg.packageName 8676 + " because it was previously installed without"); 8677 } 8678 } break; 8679 } 8680 } else { 8681 if (permissionsState.revokeInstallPermission(bp) != 8682 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8683 // Also drop the permission flags. 8684 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8685 PackageManager.MASK_PERMISSION_FLAGS, 0); 8686 changedInstallPermission = true; 8687 Slog.i(TAG, "Un-granting permission " + perm 8688 + " from package " + pkg.packageName 8689 + " (protectionLevel=" + bp.protectionLevel 8690 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8691 + ")"); 8692 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8693 // Don't print warning for app op permissions, since it is fine for them 8694 // not to be granted, there is a UI for the user to decide. 8695 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8696 Slog.w(TAG, "Not granting permission " + perm 8697 + " to package " + pkg.packageName 8698 + " (protectionLevel=" + bp.protectionLevel 8699 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8700 + ")"); 8701 } 8702 } 8703 } 8704 } 8705 8706 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8707 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8708 // This is the first that we have heard about this package, so the 8709 // permissions we have now selected are fixed until explicitly 8710 // changed. 8711 ps.installPermissionsFixed = true; 8712 } 8713 8714 // Persist the runtime permissions state for users with changes. 8715 for (int userId : changedRuntimePermissionUserIds) { 8716 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8717 } 8718 8719 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8720 } 8721 8722 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8723 boolean allowed = false; 8724 final int NP = PackageParser.NEW_PERMISSIONS.length; 8725 for (int ip=0; ip<NP; ip++) { 8726 final PackageParser.NewPermissionInfo npi 8727 = PackageParser.NEW_PERMISSIONS[ip]; 8728 if (npi.name.equals(perm) 8729 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8730 allowed = true; 8731 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8732 + pkg.packageName); 8733 break; 8734 } 8735 } 8736 return allowed; 8737 } 8738 8739 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8740 BasePermission bp, PermissionsState origPermissions) { 8741 boolean allowed; 8742 allowed = (compareSignatures( 8743 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8744 == PackageManager.SIGNATURE_MATCH) 8745 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8746 == PackageManager.SIGNATURE_MATCH); 8747 if (!allowed && (bp.protectionLevel 8748 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8749 if (isSystemApp(pkg)) { 8750 // For updated system applications, a system permission 8751 // is granted only if it had been defined by the original application. 8752 if (pkg.isUpdatedSystemApp()) { 8753 final PackageSetting sysPs = mSettings 8754 .getDisabledSystemPkgLPr(pkg.packageName); 8755 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8756 // If the original was granted this permission, we take 8757 // that grant decision as read and propagate it to the 8758 // update. 8759 if (sysPs.isPrivileged()) { 8760 allowed = true; 8761 } 8762 } else { 8763 // The system apk may have been updated with an older 8764 // version of the one on the data partition, but which 8765 // granted a new system permission that it didn't have 8766 // before. In this case we do want to allow the app to 8767 // now get the new permission if the ancestral apk is 8768 // privileged to get it. 8769 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8770 for (int j=0; 8771 j<sysPs.pkg.requestedPermissions.size(); j++) { 8772 if (perm.equals( 8773 sysPs.pkg.requestedPermissions.get(j))) { 8774 allowed = true; 8775 break; 8776 } 8777 } 8778 } 8779 } 8780 } else { 8781 allowed = isPrivilegedApp(pkg); 8782 } 8783 } 8784 } 8785 if (!allowed) { 8786 if (!allowed && (bp.protectionLevel 8787 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8788 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8789 // If this was a previously normal/dangerous permission that got moved 8790 // to a system permission as part of the runtime permission redesign, then 8791 // we still want to blindly grant it to old apps. 8792 allowed = true; 8793 } 8794 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8795 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8796 // If this permission is to be granted to the system installer and 8797 // this app is an installer, then it gets the permission. 8798 allowed = true; 8799 } 8800 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8801 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8802 // If this permission is to be granted to the system verifier and 8803 // this app is a verifier, then it gets the permission. 8804 allowed = true; 8805 } 8806 if (!allowed && (bp.protectionLevel 8807 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8808 && isSystemApp(pkg)) { 8809 // Any pre-installed system app is allowed to get this permission. 8810 allowed = true; 8811 } 8812 if (!allowed && (bp.protectionLevel 8813 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8814 // For development permissions, a development permission 8815 // is granted only if it was already granted. 8816 allowed = origPermissions.hasInstallPermission(perm); 8817 } 8818 } 8819 return allowed; 8820 } 8821 8822 final class ActivityIntentResolver 8823 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8824 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8825 boolean defaultOnly, int userId) { 8826 if (!sUserManager.exists(userId)) return null; 8827 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8828 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8829 } 8830 8831 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8832 int userId) { 8833 if (!sUserManager.exists(userId)) return null; 8834 mFlags = flags; 8835 return super.queryIntent(intent, resolvedType, 8836 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8837 } 8838 8839 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8840 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8841 if (!sUserManager.exists(userId)) return null; 8842 if (packageActivities == null) { 8843 return null; 8844 } 8845 mFlags = flags; 8846 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8847 final int N = packageActivities.size(); 8848 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8849 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8850 8851 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8852 for (int i = 0; i < N; ++i) { 8853 intentFilters = packageActivities.get(i).intents; 8854 if (intentFilters != null && intentFilters.size() > 0) { 8855 PackageParser.ActivityIntentInfo[] array = 8856 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8857 intentFilters.toArray(array); 8858 listCut.add(array); 8859 } 8860 } 8861 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8862 } 8863 8864 public final void addActivity(PackageParser.Activity a, String type) { 8865 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8866 mActivities.put(a.getComponentName(), a); 8867 if (DEBUG_SHOW_INFO) 8868 Log.v( 8869 TAG, " " + type + " " + 8870 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8871 if (DEBUG_SHOW_INFO) 8872 Log.v(TAG, " Class=" + a.info.name); 8873 final int NI = a.intents.size(); 8874 for (int j=0; j<NI; j++) { 8875 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8876 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8877 intent.setPriority(0); 8878 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8879 + a.className + " with priority > 0, forcing to 0"); 8880 } 8881 if (DEBUG_SHOW_INFO) { 8882 Log.v(TAG, " IntentFilter:"); 8883 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8884 } 8885 if (!intent.debugCheck()) { 8886 Log.w(TAG, "==> For Activity " + a.info.name); 8887 } 8888 addFilter(intent); 8889 } 8890 } 8891 8892 public final void removeActivity(PackageParser.Activity a, String type) { 8893 mActivities.remove(a.getComponentName()); 8894 if (DEBUG_SHOW_INFO) { 8895 Log.v(TAG, " " + type + " " 8896 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8897 : a.info.name) + ":"); 8898 Log.v(TAG, " Class=" + a.info.name); 8899 } 8900 final int NI = a.intents.size(); 8901 for (int j=0; j<NI; j++) { 8902 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8903 if (DEBUG_SHOW_INFO) { 8904 Log.v(TAG, " IntentFilter:"); 8905 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8906 } 8907 removeFilter(intent); 8908 } 8909 } 8910 8911 @Override 8912 protected boolean allowFilterResult( 8913 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8914 ActivityInfo filterAi = filter.activity.info; 8915 for (int i=dest.size()-1; i>=0; i--) { 8916 ActivityInfo destAi = dest.get(i).activityInfo; 8917 if (destAi.name == filterAi.name 8918 && destAi.packageName == filterAi.packageName) { 8919 return false; 8920 } 8921 } 8922 return true; 8923 } 8924 8925 @Override 8926 protected ActivityIntentInfo[] newArray(int size) { 8927 return new ActivityIntentInfo[size]; 8928 } 8929 8930 @Override 8931 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8932 if (!sUserManager.exists(userId)) return true; 8933 PackageParser.Package p = filter.activity.owner; 8934 if (p != null) { 8935 PackageSetting ps = (PackageSetting)p.mExtras; 8936 if (ps != null) { 8937 // System apps are never considered stopped for purposes of 8938 // filtering, because there may be no way for the user to 8939 // actually re-launch them. 8940 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8941 && ps.getStopped(userId); 8942 } 8943 } 8944 return false; 8945 } 8946 8947 @Override 8948 protected boolean isPackageForFilter(String packageName, 8949 PackageParser.ActivityIntentInfo info) { 8950 return packageName.equals(info.activity.owner.packageName); 8951 } 8952 8953 @Override 8954 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8955 int match, int userId) { 8956 if (!sUserManager.exists(userId)) return null; 8957 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8958 return null; 8959 } 8960 final PackageParser.Activity activity = info.activity; 8961 if (mSafeMode && (activity.info.applicationInfo.flags 8962 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8963 return null; 8964 } 8965 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8966 if (ps == null) { 8967 return null; 8968 } 8969 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8970 ps.readUserState(userId), userId); 8971 if (ai == null) { 8972 return null; 8973 } 8974 final ResolveInfo res = new ResolveInfo(); 8975 res.activityInfo = ai; 8976 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8977 res.filter = info; 8978 } 8979 if (info != null) { 8980 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8981 } 8982 res.priority = info.getPriority(); 8983 res.preferredOrder = activity.owner.mPreferredOrder; 8984 //System.out.println("Result: " + res.activityInfo.className + 8985 // " = " + res.priority); 8986 res.match = match; 8987 res.isDefault = info.hasDefault; 8988 res.labelRes = info.labelRes; 8989 res.nonLocalizedLabel = info.nonLocalizedLabel; 8990 if (userNeedsBadging(userId)) { 8991 res.noResourceId = true; 8992 } else { 8993 res.icon = info.icon; 8994 } 8995 res.iconResourceId = info.icon; 8996 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8997 return res; 8998 } 8999 9000 @Override 9001 protected void sortResults(List<ResolveInfo> results) { 9002 Collections.sort(results, mResolvePrioritySorter); 9003 } 9004 9005 @Override 9006 protected void dumpFilter(PrintWriter out, String prefix, 9007 PackageParser.ActivityIntentInfo filter) { 9008 out.print(prefix); out.print( 9009 Integer.toHexString(System.identityHashCode(filter.activity))); 9010 out.print(' '); 9011 filter.activity.printComponentShortName(out); 9012 out.print(" filter "); 9013 out.println(Integer.toHexString(System.identityHashCode(filter))); 9014 } 9015 9016 @Override 9017 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9018 return filter.activity; 9019 } 9020 9021 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9022 PackageParser.Activity activity = (PackageParser.Activity)label; 9023 out.print(prefix); out.print( 9024 Integer.toHexString(System.identityHashCode(activity))); 9025 out.print(' '); 9026 activity.printComponentShortName(out); 9027 if (count > 1) { 9028 out.print(" ("); out.print(count); out.print(" filters)"); 9029 } 9030 out.println(); 9031 } 9032 9033// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9034// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9035// final List<ResolveInfo> retList = Lists.newArrayList(); 9036// while (i.hasNext()) { 9037// final ResolveInfo resolveInfo = i.next(); 9038// if (isEnabledLP(resolveInfo.activityInfo)) { 9039// retList.add(resolveInfo); 9040// } 9041// } 9042// return retList; 9043// } 9044 9045 // Keys are String (activity class name), values are Activity. 9046 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9047 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9048 private int mFlags; 9049 } 9050 9051 private final class ServiceIntentResolver 9052 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9053 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9054 boolean defaultOnly, int userId) { 9055 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9056 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9057 } 9058 9059 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9060 int userId) { 9061 if (!sUserManager.exists(userId)) return null; 9062 mFlags = flags; 9063 return super.queryIntent(intent, resolvedType, 9064 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9065 } 9066 9067 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9068 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9069 if (!sUserManager.exists(userId)) return null; 9070 if (packageServices == null) { 9071 return null; 9072 } 9073 mFlags = flags; 9074 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9075 final int N = packageServices.size(); 9076 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9077 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9078 9079 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9080 for (int i = 0; i < N; ++i) { 9081 intentFilters = packageServices.get(i).intents; 9082 if (intentFilters != null && intentFilters.size() > 0) { 9083 PackageParser.ServiceIntentInfo[] array = 9084 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9085 intentFilters.toArray(array); 9086 listCut.add(array); 9087 } 9088 } 9089 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9090 } 9091 9092 public final void addService(PackageParser.Service s) { 9093 mServices.put(s.getComponentName(), s); 9094 if (DEBUG_SHOW_INFO) { 9095 Log.v(TAG, " " 9096 + (s.info.nonLocalizedLabel != null 9097 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9098 Log.v(TAG, " Class=" + s.info.name); 9099 } 9100 final int NI = s.intents.size(); 9101 int j; 9102 for (j=0; j<NI; j++) { 9103 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9104 if (DEBUG_SHOW_INFO) { 9105 Log.v(TAG, " IntentFilter:"); 9106 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9107 } 9108 if (!intent.debugCheck()) { 9109 Log.w(TAG, "==> For Service " + s.info.name); 9110 } 9111 addFilter(intent); 9112 } 9113 } 9114 9115 public final void removeService(PackageParser.Service s) { 9116 mServices.remove(s.getComponentName()); 9117 if (DEBUG_SHOW_INFO) { 9118 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9119 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9120 Log.v(TAG, " Class=" + s.info.name); 9121 } 9122 final int NI = s.intents.size(); 9123 int j; 9124 for (j=0; j<NI; j++) { 9125 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9126 if (DEBUG_SHOW_INFO) { 9127 Log.v(TAG, " IntentFilter:"); 9128 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9129 } 9130 removeFilter(intent); 9131 } 9132 } 9133 9134 @Override 9135 protected boolean allowFilterResult( 9136 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9137 ServiceInfo filterSi = filter.service.info; 9138 for (int i=dest.size()-1; i>=0; i--) { 9139 ServiceInfo destAi = dest.get(i).serviceInfo; 9140 if (destAi.name == filterSi.name 9141 && destAi.packageName == filterSi.packageName) { 9142 return false; 9143 } 9144 } 9145 return true; 9146 } 9147 9148 @Override 9149 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9150 return new PackageParser.ServiceIntentInfo[size]; 9151 } 9152 9153 @Override 9154 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9155 if (!sUserManager.exists(userId)) return true; 9156 PackageParser.Package p = filter.service.owner; 9157 if (p != null) { 9158 PackageSetting ps = (PackageSetting)p.mExtras; 9159 if (ps != null) { 9160 // System apps are never considered stopped for purposes of 9161 // filtering, because there may be no way for the user to 9162 // actually re-launch them. 9163 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9164 && ps.getStopped(userId); 9165 } 9166 } 9167 return false; 9168 } 9169 9170 @Override 9171 protected boolean isPackageForFilter(String packageName, 9172 PackageParser.ServiceIntentInfo info) { 9173 return packageName.equals(info.service.owner.packageName); 9174 } 9175 9176 @Override 9177 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9178 int match, int userId) { 9179 if (!sUserManager.exists(userId)) return null; 9180 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9181 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9182 return null; 9183 } 9184 final PackageParser.Service service = info.service; 9185 if (mSafeMode && (service.info.applicationInfo.flags 9186 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9187 return null; 9188 } 9189 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9190 if (ps == null) { 9191 return null; 9192 } 9193 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9194 ps.readUserState(userId), userId); 9195 if (si == null) { 9196 return null; 9197 } 9198 final ResolveInfo res = new ResolveInfo(); 9199 res.serviceInfo = si; 9200 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9201 res.filter = filter; 9202 } 9203 res.priority = info.getPriority(); 9204 res.preferredOrder = service.owner.mPreferredOrder; 9205 res.match = match; 9206 res.isDefault = info.hasDefault; 9207 res.labelRes = info.labelRes; 9208 res.nonLocalizedLabel = info.nonLocalizedLabel; 9209 res.icon = info.icon; 9210 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9211 return res; 9212 } 9213 9214 @Override 9215 protected void sortResults(List<ResolveInfo> results) { 9216 Collections.sort(results, mResolvePrioritySorter); 9217 } 9218 9219 @Override 9220 protected void dumpFilter(PrintWriter out, String prefix, 9221 PackageParser.ServiceIntentInfo filter) { 9222 out.print(prefix); out.print( 9223 Integer.toHexString(System.identityHashCode(filter.service))); 9224 out.print(' '); 9225 filter.service.printComponentShortName(out); 9226 out.print(" filter "); 9227 out.println(Integer.toHexString(System.identityHashCode(filter))); 9228 } 9229 9230 @Override 9231 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9232 return filter.service; 9233 } 9234 9235 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9236 PackageParser.Service service = (PackageParser.Service)label; 9237 out.print(prefix); out.print( 9238 Integer.toHexString(System.identityHashCode(service))); 9239 out.print(' '); 9240 service.printComponentShortName(out); 9241 if (count > 1) { 9242 out.print(" ("); out.print(count); out.print(" filters)"); 9243 } 9244 out.println(); 9245 } 9246 9247// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9248// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9249// final List<ResolveInfo> retList = Lists.newArrayList(); 9250// while (i.hasNext()) { 9251// final ResolveInfo resolveInfo = (ResolveInfo) i; 9252// if (isEnabledLP(resolveInfo.serviceInfo)) { 9253// retList.add(resolveInfo); 9254// } 9255// } 9256// return retList; 9257// } 9258 9259 // Keys are String (activity class name), values are Activity. 9260 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9261 = new ArrayMap<ComponentName, PackageParser.Service>(); 9262 private int mFlags; 9263 }; 9264 9265 private final class ProviderIntentResolver 9266 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9267 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9268 boolean defaultOnly, int userId) { 9269 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9270 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9271 } 9272 9273 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9274 int userId) { 9275 if (!sUserManager.exists(userId)) 9276 return null; 9277 mFlags = flags; 9278 return super.queryIntent(intent, resolvedType, 9279 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9280 } 9281 9282 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9283 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9284 if (!sUserManager.exists(userId)) 9285 return null; 9286 if (packageProviders == null) { 9287 return null; 9288 } 9289 mFlags = flags; 9290 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9291 final int N = packageProviders.size(); 9292 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9293 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9294 9295 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9296 for (int i = 0; i < N; ++i) { 9297 intentFilters = packageProviders.get(i).intents; 9298 if (intentFilters != null && intentFilters.size() > 0) { 9299 PackageParser.ProviderIntentInfo[] array = 9300 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9301 intentFilters.toArray(array); 9302 listCut.add(array); 9303 } 9304 } 9305 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9306 } 9307 9308 public final void addProvider(PackageParser.Provider p) { 9309 if (mProviders.containsKey(p.getComponentName())) { 9310 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9311 return; 9312 } 9313 9314 mProviders.put(p.getComponentName(), p); 9315 if (DEBUG_SHOW_INFO) { 9316 Log.v(TAG, " " 9317 + (p.info.nonLocalizedLabel != null 9318 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9319 Log.v(TAG, " Class=" + p.info.name); 9320 } 9321 final int NI = p.intents.size(); 9322 int j; 9323 for (j = 0; j < NI; j++) { 9324 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9325 if (DEBUG_SHOW_INFO) { 9326 Log.v(TAG, " IntentFilter:"); 9327 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9328 } 9329 if (!intent.debugCheck()) { 9330 Log.w(TAG, "==> For Provider " + p.info.name); 9331 } 9332 addFilter(intent); 9333 } 9334 } 9335 9336 public final void removeProvider(PackageParser.Provider p) { 9337 mProviders.remove(p.getComponentName()); 9338 if (DEBUG_SHOW_INFO) { 9339 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9340 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9341 Log.v(TAG, " Class=" + p.info.name); 9342 } 9343 final int NI = p.intents.size(); 9344 int j; 9345 for (j = 0; j < NI; j++) { 9346 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9347 if (DEBUG_SHOW_INFO) { 9348 Log.v(TAG, " IntentFilter:"); 9349 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9350 } 9351 removeFilter(intent); 9352 } 9353 } 9354 9355 @Override 9356 protected boolean allowFilterResult( 9357 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9358 ProviderInfo filterPi = filter.provider.info; 9359 for (int i = dest.size() - 1; i >= 0; i--) { 9360 ProviderInfo destPi = dest.get(i).providerInfo; 9361 if (destPi.name == filterPi.name 9362 && destPi.packageName == filterPi.packageName) { 9363 return false; 9364 } 9365 } 9366 return true; 9367 } 9368 9369 @Override 9370 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9371 return new PackageParser.ProviderIntentInfo[size]; 9372 } 9373 9374 @Override 9375 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9376 if (!sUserManager.exists(userId)) 9377 return true; 9378 PackageParser.Package p = filter.provider.owner; 9379 if (p != null) { 9380 PackageSetting ps = (PackageSetting) p.mExtras; 9381 if (ps != null) { 9382 // System apps are never considered stopped for purposes of 9383 // filtering, because there may be no way for the user to 9384 // actually re-launch them. 9385 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9386 && ps.getStopped(userId); 9387 } 9388 } 9389 return false; 9390 } 9391 9392 @Override 9393 protected boolean isPackageForFilter(String packageName, 9394 PackageParser.ProviderIntentInfo info) { 9395 return packageName.equals(info.provider.owner.packageName); 9396 } 9397 9398 @Override 9399 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9400 int match, int userId) { 9401 if (!sUserManager.exists(userId)) 9402 return null; 9403 final PackageParser.ProviderIntentInfo info = filter; 9404 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9405 return null; 9406 } 9407 final PackageParser.Provider provider = info.provider; 9408 if (mSafeMode && (provider.info.applicationInfo.flags 9409 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9410 return null; 9411 } 9412 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9413 if (ps == null) { 9414 return null; 9415 } 9416 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9417 ps.readUserState(userId), userId); 9418 if (pi == null) { 9419 return null; 9420 } 9421 final ResolveInfo res = new ResolveInfo(); 9422 res.providerInfo = pi; 9423 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9424 res.filter = filter; 9425 } 9426 res.priority = info.getPriority(); 9427 res.preferredOrder = provider.owner.mPreferredOrder; 9428 res.match = match; 9429 res.isDefault = info.hasDefault; 9430 res.labelRes = info.labelRes; 9431 res.nonLocalizedLabel = info.nonLocalizedLabel; 9432 res.icon = info.icon; 9433 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9434 return res; 9435 } 9436 9437 @Override 9438 protected void sortResults(List<ResolveInfo> results) { 9439 Collections.sort(results, mResolvePrioritySorter); 9440 } 9441 9442 @Override 9443 protected void dumpFilter(PrintWriter out, String prefix, 9444 PackageParser.ProviderIntentInfo filter) { 9445 out.print(prefix); 9446 out.print( 9447 Integer.toHexString(System.identityHashCode(filter.provider))); 9448 out.print(' '); 9449 filter.provider.printComponentShortName(out); 9450 out.print(" filter "); 9451 out.println(Integer.toHexString(System.identityHashCode(filter))); 9452 } 9453 9454 @Override 9455 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9456 return filter.provider; 9457 } 9458 9459 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9460 PackageParser.Provider provider = (PackageParser.Provider)label; 9461 out.print(prefix); out.print( 9462 Integer.toHexString(System.identityHashCode(provider))); 9463 out.print(' '); 9464 provider.printComponentShortName(out); 9465 if (count > 1) { 9466 out.print(" ("); out.print(count); out.print(" filters)"); 9467 } 9468 out.println(); 9469 } 9470 9471 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9472 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9473 private int mFlags; 9474 }; 9475 9476 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9477 new Comparator<ResolveInfo>() { 9478 public int compare(ResolveInfo r1, ResolveInfo r2) { 9479 int v1 = r1.priority; 9480 int v2 = r2.priority; 9481 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9482 if (v1 != v2) { 9483 return (v1 > v2) ? -1 : 1; 9484 } 9485 v1 = r1.preferredOrder; 9486 v2 = r2.preferredOrder; 9487 if (v1 != v2) { 9488 return (v1 > v2) ? -1 : 1; 9489 } 9490 if (r1.isDefault != r2.isDefault) { 9491 return r1.isDefault ? -1 : 1; 9492 } 9493 v1 = r1.match; 9494 v2 = r2.match; 9495 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9496 if (v1 != v2) { 9497 return (v1 > v2) ? -1 : 1; 9498 } 9499 if (r1.system != r2.system) { 9500 return r1.system ? -1 : 1; 9501 } 9502 return 0; 9503 } 9504 }; 9505 9506 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9507 new Comparator<ProviderInfo>() { 9508 public int compare(ProviderInfo p1, ProviderInfo p2) { 9509 final int v1 = p1.initOrder; 9510 final int v2 = p2.initOrder; 9511 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9512 } 9513 }; 9514 9515 final void sendPackageBroadcast(final String action, final String pkg, 9516 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9517 final int[] userIds) { 9518 mHandler.post(new Runnable() { 9519 @Override 9520 public void run() { 9521 try { 9522 final IActivityManager am = ActivityManagerNative.getDefault(); 9523 if (am == null) return; 9524 final int[] resolvedUserIds; 9525 if (userIds == null) { 9526 resolvedUserIds = am.getRunningUserIds(); 9527 } else { 9528 resolvedUserIds = userIds; 9529 } 9530 for (int id : resolvedUserIds) { 9531 final Intent intent = new Intent(action, 9532 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9533 if (extras != null) { 9534 intent.putExtras(extras); 9535 } 9536 if (targetPkg != null) { 9537 intent.setPackage(targetPkg); 9538 } 9539 // Modify the UID when posting to other users 9540 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9541 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9542 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9543 intent.putExtra(Intent.EXTRA_UID, uid); 9544 } 9545 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9546 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9547 if (DEBUG_BROADCASTS) { 9548 RuntimeException here = new RuntimeException("here"); 9549 here.fillInStackTrace(); 9550 Slog.d(TAG, "Sending to user " + id + ": " 9551 + intent.toShortString(false, true, false, false) 9552 + " " + intent.getExtras(), here); 9553 } 9554 am.broadcastIntent(null, intent, null, finishedReceiver, 9555 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9556 null, finishedReceiver != null, false, id); 9557 } 9558 } catch (RemoteException ex) { 9559 } 9560 } 9561 }); 9562 } 9563 9564 /** 9565 * Check if the external storage media is available. This is true if there 9566 * is a mounted external storage medium or if the external storage is 9567 * emulated. 9568 */ 9569 private boolean isExternalMediaAvailable() { 9570 return mMediaMounted || Environment.isExternalStorageEmulated(); 9571 } 9572 9573 @Override 9574 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9575 // writer 9576 synchronized (mPackages) { 9577 if (!isExternalMediaAvailable()) { 9578 // If the external storage is no longer mounted at this point, 9579 // the caller may not have been able to delete all of this 9580 // packages files and can not delete any more. Bail. 9581 return null; 9582 } 9583 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9584 if (lastPackage != null) { 9585 pkgs.remove(lastPackage); 9586 } 9587 if (pkgs.size() > 0) { 9588 return pkgs.get(0); 9589 } 9590 } 9591 return null; 9592 } 9593 9594 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9595 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9596 userId, andCode ? 1 : 0, packageName); 9597 if (mSystemReady) { 9598 msg.sendToTarget(); 9599 } else { 9600 if (mPostSystemReadyMessages == null) { 9601 mPostSystemReadyMessages = new ArrayList<>(); 9602 } 9603 mPostSystemReadyMessages.add(msg); 9604 } 9605 } 9606 9607 void startCleaningPackages() { 9608 // reader 9609 synchronized (mPackages) { 9610 if (!isExternalMediaAvailable()) { 9611 return; 9612 } 9613 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9614 return; 9615 } 9616 } 9617 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9618 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9619 IActivityManager am = ActivityManagerNative.getDefault(); 9620 if (am != null) { 9621 try { 9622 am.startService(null, intent, null, mContext.getOpPackageName(), 9623 UserHandle.USER_OWNER); 9624 } catch (RemoteException e) { 9625 } 9626 } 9627 } 9628 9629 @Override 9630 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9631 int installFlags, String installerPackageName, VerificationParams verificationParams, 9632 String packageAbiOverride) { 9633 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9634 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9635 } 9636 9637 @Override 9638 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9639 int installFlags, String installerPackageName, VerificationParams verificationParams, 9640 String packageAbiOverride, int userId) { 9641 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9642 9643 final int callingUid = Binder.getCallingUid(); 9644 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9645 9646 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9647 try { 9648 if (observer != null) { 9649 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9650 } 9651 } catch (RemoteException re) { 9652 } 9653 return; 9654 } 9655 9656 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9657 installFlags |= PackageManager.INSTALL_FROM_ADB; 9658 9659 } else { 9660 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9661 // about installerPackageName. 9662 9663 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9664 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9665 } 9666 9667 UserHandle user; 9668 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9669 user = UserHandle.ALL; 9670 } else { 9671 user = new UserHandle(userId); 9672 } 9673 9674 // Only system components can circumvent runtime permissions when installing. 9675 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9676 && mContext.checkCallingOrSelfPermission(Manifest.permission 9677 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9678 throw new SecurityException("You need the " 9679 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9680 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9681 } 9682 9683 verificationParams.setInstallerUid(callingUid); 9684 9685 final File originFile = new File(originPath); 9686 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9687 9688 final Message msg = mHandler.obtainMessage(INIT_COPY); 9689 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9690 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9691 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9692 msg.obj = params; 9693 9694 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9695 System.identityHashCode(msg.obj)); 9696 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9697 System.identityHashCode(msg.obj)); 9698 9699 mHandler.sendMessage(msg); 9700 } 9701 9702 void installStage(String packageName, File stagedDir, String stagedCid, 9703 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9704 String installerPackageName, int installerUid, UserHandle user) { 9705 final VerificationParams verifParams = new VerificationParams( 9706 null, sessionParams.originatingUri, sessionParams.referrerUri, installerUid, null); 9707 verifParams.setInstallerUid(installerUid); 9708 9709 final OriginInfo origin; 9710 if (stagedDir != null) { 9711 origin = OriginInfo.fromStagedFile(stagedDir); 9712 } else { 9713 origin = OriginInfo.fromStagedContainer(stagedCid); 9714 } 9715 9716 final Message msg = mHandler.obtainMessage(INIT_COPY); 9717 final InstallParams params = new InstallParams(origin, null, observer, 9718 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9719 verifParams, user, sessionParams.abiOverride, 9720 sessionParams.grantedRuntimePermissions); 9721 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9722 msg.obj = params; 9723 9724 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9725 System.identityHashCode(msg.obj)); 9726 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9727 System.identityHashCode(msg.obj)); 9728 9729 mHandler.sendMessage(msg); 9730 } 9731 9732 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9733 Bundle extras = new Bundle(1); 9734 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9735 9736 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9737 packageName, extras, null, null, new int[] {userId}); 9738 try { 9739 IActivityManager am = ActivityManagerNative.getDefault(); 9740 final boolean isSystem = 9741 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9742 if (isSystem && am.isUserRunning(userId, false)) { 9743 // The just-installed/enabled app is bundled on the system, so presumed 9744 // to be able to run automatically without needing an explicit launch. 9745 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9746 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9747 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9748 .setPackage(packageName); 9749 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9750 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9751 } 9752 } catch (RemoteException e) { 9753 // shouldn't happen 9754 Slog.w(TAG, "Unable to bootstrap installed package", e); 9755 } 9756 } 9757 9758 @Override 9759 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9760 int userId) { 9761 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9762 PackageSetting pkgSetting; 9763 final int uid = Binder.getCallingUid(); 9764 enforceCrossUserPermission(uid, userId, true, true, 9765 "setApplicationHiddenSetting for user " + userId); 9766 9767 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9768 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9769 return false; 9770 } 9771 9772 long callingId = Binder.clearCallingIdentity(); 9773 try { 9774 boolean sendAdded = false; 9775 boolean sendRemoved = false; 9776 // writer 9777 synchronized (mPackages) { 9778 pkgSetting = mSettings.mPackages.get(packageName); 9779 if (pkgSetting == null) { 9780 return false; 9781 } 9782 if (pkgSetting.getHidden(userId) != hidden) { 9783 pkgSetting.setHidden(hidden, userId); 9784 mSettings.writePackageRestrictionsLPr(userId); 9785 if (hidden) { 9786 sendRemoved = true; 9787 } else { 9788 sendAdded = true; 9789 } 9790 } 9791 } 9792 if (sendAdded) { 9793 sendPackageAddedForUser(packageName, pkgSetting, userId); 9794 return true; 9795 } 9796 if (sendRemoved) { 9797 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9798 "hiding pkg"); 9799 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9800 return true; 9801 } 9802 } finally { 9803 Binder.restoreCallingIdentity(callingId); 9804 } 9805 return false; 9806 } 9807 9808 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9809 int userId) { 9810 final PackageRemovedInfo info = new PackageRemovedInfo(); 9811 info.removedPackage = packageName; 9812 info.removedUsers = new int[] {userId}; 9813 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9814 info.sendBroadcast(false, false, false); 9815 } 9816 9817 /** 9818 * Returns true if application is not found or there was an error. Otherwise it returns 9819 * the hidden state of the package for the given user. 9820 */ 9821 @Override 9822 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9823 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9824 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9825 false, "getApplicationHidden for user " + userId); 9826 PackageSetting pkgSetting; 9827 long callingId = Binder.clearCallingIdentity(); 9828 try { 9829 // writer 9830 synchronized (mPackages) { 9831 pkgSetting = mSettings.mPackages.get(packageName); 9832 if (pkgSetting == null) { 9833 return true; 9834 } 9835 return pkgSetting.getHidden(userId); 9836 } 9837 } finally { 9838 Binder.restoreCallingIdentity(callingId); 9839 } 9840 } 9841 9842 /** 9843 * @hide 9844 */ 9845 @Override 9846 public int installExistingPackageAsUser(String packageName, int userId) { 9847 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9848 null); 9849 PackageSetting pkgSetting; 9850 final int uid = Binder.getCallingUid(); 9851 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9852 + userId); 9853 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9854 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9855 } 9856 9857 long callingId = Binder.clearCallingIdentity(); 9858 try { 9859 boolean sendAdded = false; 9860 9861 // writer 9862 synchronized (mPackages) { 9863 pkgSetting = mSettings.mPackages.get(packageName); 9864 if (pkgSetting == null) { 9865 return PackageManager.INSTALL_FAILED_INVALID_URI; 9866 } 9867 if (!pkgSetting.getInstalled(userId)) { 9868 pkgSetting.setInstalled(true, userId); 9869 pkgSetting.setHidden(false, userId); 9870 mSettings.writePackageRestrictionsLPr(userId); 9871 sendAdded = true; 9872 } 9873 } 9874 9875 if (sendAdded) { 9876 sendPackageAddedForUser(packageName, pkgSetting, userId); 9877 } 9878 } finally { 9879 Binder.restoreCallingIdentity(callingId); 9880 } 9881 9882 return PackageManager.INSTALL_SUCCEEDED; 9883 } 9884 9885 boolean isUserRestricted(int userId, String restrictionKey) { 9886 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9887 if (restrictions.getBoolean(restrictionKey, false)) { 9888 Log.w(TAG, "User is restricted: " + restrictionKey); 9889 return true; 9890 } 9891 return false; 9892 } 9893 9894 @Override 9895 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9896 mContext.enforceCallingOrSelfPermission( 9897 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9898 "Only package verification agents can verify applications"); 9899 9900 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9901 final PackageVerificationResponse response = new PackageVerificationResponse( 9902 verificationCode, Binder.getCallingUid()); 9903 msg.arg1 = id; 9904 msg.obj = response; 9905 mHandler.sendMessage(msg); 9906 } 9907 9908 @Override 9909 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9910 long millisecondsToDelay) { 9911 mContext.enforceCallingOrSelfPermission( 9912 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9913 "Only package verification agents can extend verification timeouts"); 9914 9915 final PackageVerificationState state = mPendingVerification.get(id); 9916 final PackageVerificationResponse response = new PackageVerificationResponse( 9917 verificationCodeAtTimeout, Binder.getCallingUid()); 9918 9919 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9920 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9921 } 9922 if (millisecondsToDelay < 0) { 9923 millisecondsToDelay = 0; 9924 } 9925 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9926 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9927 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9928 } 9929 9930 if ((state != null) && !state.timeoutExtended()) { 9931 state.extendTimeout(); 9932 9933 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9934 msg.arg1 = id; 9935 msg.obj = response; 9936 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9937 } 9938 } 9939 9940 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9941 int verificationCode, UserHandle user) { 9942 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9943 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9944 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9945 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9946 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9947 9948 mContext.sendBroadcastAsUser(intent, user, 9949 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9950 } 9951 9952 private ComponentName matchComponentForVerifier(String packageName, 9953 List<ResolveInfo> receivers) { 9954 ActivityInfo targetReceiver = null; 9955 9956 final int NR = receivers.size(); 9957 for (int i = 0; i < NR; i++) { 9958 final ResolveInfo info = receivers.get(i); 9959 if (info.activityInfo == null) { 9960 continue; 9961 } 9962 9963 if (packageName.equals(info.activityInfo.packageName)) { 9964 targetReceiver = info.activityInfo; 9965 break; 9966 } 9967 } 9968 9969 if (targetReceiver == null) { 9970 return null; 9971 } 9972 9973 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9974 } 9975 9976 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9977 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9978 if (pkgInfo.verifiers.length == 0) { 9979 return null; 9980 } 9981 9982 final int N = pkgInfo.verifiers.length; 9983 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9984 for (int i = 0; i < N; i++) { 9985 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9986 9987 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9988 receivers); 9989 if (comp == null) { 9990 continue; 9991 } 9992 9993 final int verifierUid = getUidForVerifier(verifierInfo); 9994 if (verifierUid == -1) { 9995 continue; 9996 } 9997 9998 if (DEBUG_VERIFY) { 9999 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10000 + " with the correct signature"); 10001 } 10002 sufficientVerifiers.add(comp); 10003 verificationState.addSufficientVerifier(verifierUid); 10004 } 10005 10006 return sufficientVerifiers; 10007 } 10008 10009 private int getUidForVerifier(VerifierInfo verifierInfo) { 10010 synchronized (mPackages) { 10011 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10012 if (pkg == null) { 10013 return -1; 10014 } else if (pkg.mSignatures.length != 1) { 10015 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10016 + " has more than one signature; ignoring"); 10017 return -1; 10018 } 10019 10020 /* 10021 * If the public key of the package's signature does not match 10022 * our expected public key, then this is a different package and 10023 * we should skip. 10024 */ 10025 10026 final byte[] expectedPublicKey; 10027 try { 10028 final Signature verifierSig = pkg.mSignatures[0]; 10029 final PublicKey publicKey = verifierSig.getPublicKey(); 10030 expectedPublicKey = publicKey.getEncoded(); 10031 } catch (CertificateException e) { 10032 return -1; 10033 } 10034 10035 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10036 10037 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10038 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10039 + " does not have the expected public key; ignoring"); 10040 return -1; 10041 } 10042 10043 return pkg.applicationInfo.uid; 10044 } 10045 } 10046 10047 @Override 10048 public void finishPackageInstall(int token) { 10049 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10050 10051 if (DEBUG_INSTALL) { 10052 Slog.v(TAG, "BM finishing package install for " + token); 10053 } 10054 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10055 10056 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10057 mHandler.sendMessage(msg); 10058 } 10059 10060 /** 10061 * Get the verification agent timeout. 10062 * 10063 * @return verification timeout in milliseconds 10064 */ 10065 private long getVerificationTimeout() { 10066 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10067 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10068 DEFAULT_VERIFICATION_TIMEOUT); 10069 } 10070 10071 /** 10072 * Get the default verification agent response code. 10073 * 10074 * @return default verification response code 10075 */ 10076 private int getDefaultVerificationResponse() { 10077 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10078 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10079 DEFAULT_VERIFICATION_RESPONSE); 10080 } 10081 10082 /** 10083 * Check whether or not package verification has been enabled. 10084 * 10085 * @return true if verification should be performed 10086 */ 10087 private boolean isVerificationEnabled(int userId, int installFlags) { 10088 if (!DEFAULT_VERIFY_ENABLE) { 10089 return false; 10090 } 10091 10092 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10093 10094 // Check if installing from ADB 10095 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10096 // Do not run verification in a test harness environment 10097 if (ActivityManager.isRunningInTestHarness()) { 10098 return false; 10099 } 10100 if (ensureVerifyAppsEnabled) { 10101 return true; 10102 } 10103 // Check if the developer does not want package verification for ADB installs 10104 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10105 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10106 return false; 10107 } 10108 } 10109 10110 if (ensureVerifyAppsEnabled) { 10111 return true; 10112 } 10113 10114 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10115 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10116 } 10117 10118 @Override 10119 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10120 throws RemoteException { 10121 mContext.enforceCallingOrSelfPermission( 10122 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10123 "Only intentfilter verification agents can verify applications"); 10124 10125 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10126 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10127 Binder.getCallingUid(), verificationCode, failedDomains); 10128 msg.arg1 = id; 10129 msg.obj = response; 10130 mHandler.sendMessage(msg); 10131 } 10132 10133 @Override 10134 public int getIntentVerificationStatus(String packageName, int userId) { 10135 synchronized (mPackages) { 10136 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10137 } 10138 } 10139 10140 @Override 10141 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10142 mContext.enforceCallingOrSelfPermission( 10143 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10144 10145 boolean result = false; 10146 synchronized (mPackages) { 10147 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10148 } 10149 if (result) { 10150 scheduleWritePackageRestrictionsLocked(userId); 10151 } 10152 return result; 10153 } 10154 10155 @Override 10156 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10157 synchronized (mPackages) { 10158 return mSettings.getIntentFilterVerificationsLPr(packageName); 10159 } 10160 } 10161 10162 @Override 10163 public List<IntentFilter> getAllIntentFilters(String packageName) { 10164 if (TextUtils.isEmpty(packageName)) { 10165 return Collections.<IntentFilter>emptyList(); 10166 } 10167 synchronized (mPackages) { 10168 PackageParser.Package pkg = mPackages.get(packageName); 10169 if (pkg == null || pkg.activities == null) { 10170 return Collections.<IntentFilter>emptyList(); 10171 } 10172 final int count = pkg.activities.size(); 10173 ArrayList<IntentFilter> result = new ArrayList<>(); 10174 for (int n=0; n<count; n++) { 10175 PackageParser.Activity activity = pkg.activities.get(n); 10176 if (activity.intents != null || activity.intents.size() > 0) { 10177 result.addAll(activity.intents); 10178 } 10179 } 10180 return result; 10181 } 10182 } 10183 10184 @Override 10185 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10186 mContext.enforceCallingOrSelfPermission( 10187 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10188 10189 synchronized (mPackages) { 10190 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10191 if (packageName != null) { 10192 result |= updateIntentVerificationStatus(packageName, 10193 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10194 userId); 10195 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10196 packageName, userId); 10197 } 10198 return result; 10199 } 10200 } 10201 10202 @Override 10203 public String getDefaultBrowserPackageName(int userId) { 10204 synchronized (mPackages) { 10205 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10206 } 10207 } 10208 10209 /** 10210 * Get the "allow unknown sources" setting. 10211 * 10212 * @return the current "allow unknown sources" setting 10213 */ 10214 private int getUnknownSourcesSettings() { 10215 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10216 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10217 -1); 10218 } 10219 10220 @Override 10221 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10222 final int uid = Binder.getCallingUid(); 10223 // writer 10224 synchronized (mPackages) { 10225 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10226 if (targetPackageSetting == null) { 10227 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10228 } 10229 10230 PackageSetting installerPackageSetting; 10231 if (installerPackageName != null) { 10232 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10233 if (installerPackageSetting == null) { 10234 throw new IllegalArgumentException("Unknown installer package: " 10235 + installerPackageName); 10236 } 10237 } else { 10238 installerPackageSetting = null; 10239 } 10240 10241 Signature[] callerSignature; 10242 Object obj = mSettings.getUserIdLPr(uid); 10243 if (obj != null) { 10244 if (obj instanceof SharedUserSetting) { 10245 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10246 } else if (obj instanceof PackageSetting) { 10247 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10248 } else { 10249 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10250 } 10251 } else { 10252 throw new SecurityException("Unknown calling uid " + uid); 10253 } 10254 10255 // Verify: can't set installerPackageName to a package that is 10256 // not signed with the same cert as the caller. 10257 if (installerPackageSetting != null) { 10258 if (compareSignatures(callerSignature, 10259 installerPackageSetting.signatures.mSignatures) 10260 != PackageManager.SIGNATURE_MATCH) { 10261 throw new SecurityException( 10262 "Caller does not have same cert as new installer package " 10263 + installerPackageName); 10264 } 10265 } 10266 10267 // Verify: if target already has an installer package, it must 10268 // be signed with the same cert as the caller. 10269 if (targetPackageSetting.installerPackageName != null) { 10270 PackageSetting setting = mSettings.mPackages.get( 10271 targetPackageSetting.installerPackageName); 10272 // If the currently set package isn't valid, then it's always 10273 // okay to change it. 10274 if (setting != null) { 10275 if (compareSignatures(callerSignature, 10276 setting.signatures.mSignatures) 10277 != PackageManager.SIGNATURE_MATCH) { 10278 throw new SecurityException( 10279 "Caller does not have same cert as old installer package " 10280 + targetPackageSetting.installerPackageName); 10281 } 10282 } 10283 } 10284 10285 // Okay! 10286 targetPackageSetting.installerPackageName = installerPackageName; 10287 scheduleWriteSettingsLocked(); 10288 } 10289 } 10290 10291 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10292 // Queue up an async operation since the package installation may take a little while. 10293 mHandler.post(new Runnable() { 10294 public void run() { 10295 mHandler.removeCallbacks(this); 10296 // Result object to be returned 10297 PackageInstalledInfo res = new PackageInstalledInfo(); 10298 res.returnCode = currentStatus; 10299 res.uid = -1; 10300 res.pkg = null; 10301 res.removedInfo = new PackageRemovedInfo(); 10302 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10303 args.doPreInstall(res.returnCode); 10304 synchronized (mInstallLock) { 10305 installPackageTracedLI(args, res); 10306 } 10307 args.doPostInstall(res.returnCode, res.uid); 10308 } 10309 10310 // A restore should be performed at this point if (a) the install 10311 // succeeded, (b) the operation is not an update, and (c) the new 10312 // package has not opted out of backup participation. 10313 final boolean update = res.removedInfo.removedPackage != null; 10314 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10315 boolean doRestore = !update 10316 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10317 10318 // Set up the post-install work request bookkeeping. This will be used 10319 // and cleaned up by the post-install event handling regardless of whether 10320 // there's a restore pass performed. Token values are >= 1. 10321 int token; 10322 if (mNextInstallToken < 0) mNextInstallToken = 1; 10323 token = mNextInstallToken++; 10324 10325 PostInstallData data = new PostInstallData(args, res); 10326 mRunningInstalls.put(token, data); 10327 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10328 10329 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10330 // Pass responsibility to the Backup Manager. It will perform a 10331 // restore if appropriate, then pass responsibility back to the 10332 // Package Manager to run the post-install observer callbacks 10333 // and broadcasts. 10334 IBackupManager bm = IBackupManager.Stub.asInterface( 10335 ServiceManager.getService(Context.BACKUP_SERVICE)); 10336 if (bm != null) { 10337 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10338 + " to BM for possible restore"); 10339 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10340 try { 10341 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10342 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10343 } else { 10344 doRestore = false; 10345 } 10346 } catch (RemoteException e) { 10347 // can't happen; the backup manager is local 10348 } catch (Exception e) { 10349 Slog.e(TAG, "Exception trying to enqueue restore", e); 10350 doRestore = false; 10351 } 10352 } else { 10353 Slog.e(TAG, "Backup Manager not found!"); 10354 doRestore = false; 10355 } 10356 } 10357 10358 if (!doRestore) { 10359 // No restore possible, or the Backup Manager was mysteriously not 10360 // available -- just fire the post-install work request directly. 10361 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10362 10363 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10364 10365 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10366 mHandler.sendMessage(msg); 10367 } 10368 } 10369 }); 10370 } 10371 10372 private abstract class HandlerParams { 10373 private static final int MAX_RETRIES = 4; 10374 10375 /** 10376 * Number of times startCopy() has been attempted and had a non-fatal 10377 * error. 10378 */ 10379 private int mRetries = 0; 10380 10381 /** User handle for the user requesting the information or installation. */ 10382 private final UserHandle mUser; 10383 String traceMethod; 10384 int traceCookie; 10385 10386 HandlerParams(UserHandle user) { 10387 mUser = user; 10388 } 10389 10390 UserHandle getUser() { 10391 return mUser; 10392 } 10393 10394 HandlerParams setTraceMethod(String traceMethod) { 10395 this.traceMethod = traceMethod; 10396 return this; 10397 } 10398 10399 HandlerParams setTraceCookie(int traceCookie) { 10400 this.traceCookie = traceCookie; 10401 return this; 10402 } 10403 10404 final boolean startCopy() { 10405 boolean res; 10406 try { 10407 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10408 10409 if (++mRetries > MAX_RETRIES) { 10410 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10411 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10412 handleServiceError(); 10413 return false; 10414 } else { 10415 handleStartCopy(); 10416 res = true; 10417 } 10418 } catch (RemoteException e) { 10419 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10420 mHandler.sendEmptyMessage(MCS_RECONNECT); 10421 res = false; 10422 } 10423 handleReturnCode(); 10424 return res; 10425 } 10426 10427 final void serviceError() { 10428 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10429 handleServiceError(); 10430 handleReturnCode(); 10431 } 10432 10433 abstract void handleStartCopy() throws RemoteException; 10434 abstract void handleServiceError(); 10435 abstract void handleReturnCode(); 10436 } 10437 10438 class MeasureParams extends HandlerParams { 10439 private final PackageStats mStats; 10440 private boolean mSuccess; 10441 10442 private final IPackageStatsObserver mObserver; 10443 10444 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10445 super(new UserHandle(stats.userHandle)); 10446 mObserver = observer; 10447 mStats = stats; 10448 } 10449 10450 @Override 10451 public String toString() { 10452 return "MeasureParams{" 10453 + Integer.toHexString(System.identityHashCode(this)) 10454 + " " + mStats.packageName + "}"; 10455 } 10456 10457 @Override 10458 void handleStartCopy() throws RemoteException { 10459 synchronized (mInstallLock) { 10460 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10461 } 10462 10463 if (mSuccess) { 10464 final boolean mounted; 10465 if (Environment.isExternalStorageEmulated()) { 10466 mounted = true; 10467 } else { 10468 final String status = Environment.getExternalStorageState(); 10469 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10470 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10471 } 10472 10473 if (mounted) { 10474 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10475 10476 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10477 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10478 10479 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10480 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10481 10482 // Always subtract cache size, since it's a subdirectory 10483 mStats.externalDataSize -= mStats.externalCacheSize; 10484 10485 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10486 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10487 10488 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10489 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10490 } 10491 } 10492 } 10493 10494 @Override 10495 void handleReturnCode() { 10496 if (mObserver != null) { 10497 try { 10498 mObserver.onGetStatsCompleted(mStats, mSuccess); 10499 } catch (RemoteException e) { 10500 Slog.i(TAG, "Observer no longer exists."); 10501 } 10502 } 10503 } 10504 10505 @Override 10506 void handleServiceError() { 10507 Slog.e(TAG, "Could not measure application " + mStats.packageName 10508 + " external storage"); 10509 } 10510 } 10511 10512 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10513 throws RemoteException { 10514 long result = 0; 10515 for (File path : paths) { 10516 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10517 } 10518 return result; 10519 } 10520 10521 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10522 for (File path : paths) { 10523 try { 10524 mcs.clearDirectory(path.getAbsolutePath()); 10525 } catch (RemoteException e) { 10526 } 10527 } 10528 } 10529 10530 static class OriginInfo { 10531 /** 10532 * Location where install is coming from, before it has been 10533 * copied/renamed into place. This could be a single monolithic APK 10534 * file, or a cluster directory. This location may be untrusted. 10535 */ 10536 final File file; 10537 final String cid; 10538 10539 /** 10540 * Flag indicating that {@link #file} or {@link #cid} has already been 10541 * staged, meaning downstream users don't need to defensively copy the 10542 * contents. 10543 */ 10544 final boolean staged; 10545 10546 /** 10547 * Flag indicating that {@link #file} or {@link #cid} is an already 10548 * installed app that is being moved. 10549 */ 10550 final boolean existing; 10551 10552 final String resolvedPath; 10553 final File resolvedFile; 10554 10555 static OriginInfo fromNothing() { 10556 return new OriginInfo(null, null, false, false); 10557 } 10558 10559 static OriginInfo fromUntrustedFile(File file) { 10560 return new OriginInfo(file, null, false, false); 10561 } 10562 10563 static OriginInfo fromExistingFile(File file) { 10564 return new OriginInfo(file, null, false, true); 10565 } 10566 10567 static OriginInfo fromStagedFile(File file) { 10568 return new OriginInfo(file, null, true, false); 10569 } 10570 10571 static OriginInfo fromStagedContainer(String cid) { 10572 return new OriginInfo(null, cid, true, false); 10573 } 10574 10575 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10576 this.file = file; 10577 this.cid = cid; 10578 this.staged = staged; 10579 this.existing = existing; 10580 10581 if (cid != null) { 10582 resolvedPath = PackageHelper.getSdDir(cid); 10583 resolvedFile = new File(resolvedPath); 10584 } else if (file != null) { 10585 resolvedPath = file.getAbsolutePath(); 10586 resolvedFile = file; 10587 } else { 10588 resolvedPath = null; 10589 resolvedFile = null; 10590 } 10591 } 10592 } 10593 10594 class MoveInfo { 10595 final int moveId; 10596 final String fromUuid; 10597 final String toUuid; 10598 final String packageName; 10599 final String dataAppName; 10600 final int appId; 10601 final String seinfo; 10602 10603 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10604 String dataAppName, int appId, String seinfo) { 10605 this.moveId = moveId; 10606 this.fromUuid = fromUuid; 10607 this.toUuid = toUuid; 10608 this.packageName = packageName; 10609 this.dataAppName = dataAppName; 10610 this.appId = appId; 10611 this.seinfo = seinfo; 10612 } 10613 } 10614 10615 class InstallParams extends HandlerParams { 10616 final OriginInfo origin; 10617 final MoveInfo move; 10618 final IPackageInstallObserver2 observer; 10619 int installFlags; 10620 final String installerPackageName; 10621 final String volumeUuid; 10622 final VerificationParams verificationParams; 10623 private InstallArgs mArgs; 10624 private int mRet; 10625 final String packageAbiOverride; 10626 final String[] grantedRuntimePermissions; 10627 10628 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10629 int installFlags, String installerPackageName, String volumeUuid, 10630 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10631 String[] grantedPermissions) { 10632 super(user); 10633 this.origin = origin; 10634 this.move = move; 10635 this.observer = observer; 10636 this.installFlags = installFlags; 10637 this.installerPackageName = installerPackageName; 10638 this.volumeUuid = volumeUuid; 10639 this.verificationParams = verificationParams; 10640 this.packageAbiOverride = packageAbiOverride; 10641 this.grantedRuntimePermissions = grantedPermissions; 10642 } 10643 10644 @Override 10645 public String toString() { 10646 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10647 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10648 } 10649 10650 public ManifestDigest getManifestDigest() { 10651 if (verificationParams == null) { 10652 return null; 10653 } 10654 return verificationParams.getManifestDigest(); 10655 } 10656 10657 private int installLocationPolicy(PackageInfoLite pkgLite) { 10658 String packageName = pkgLite.packageName; 10659 int installLocation = pkgLite.installLocation; 10660 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10661 // reader 10662 synchronized (mPackages) { 10663 PackageParser.Package pkg = mPackages.get(packageName); 10664 if (pkg != null) { 10665 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10666 // Check for downgrading. 10667 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10668 try { 10669 checkDowngrade(pkg, pkgLite); 10670 } catch (PackageManagerException e) { 10671 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10672 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10673 } 10674 } 10675 // Check for updated system application. 10676 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10677 if (onSd) { 10678 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10679 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10680 } 10681 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10682 } else { 10683 if (onSd) { 10684 // Install flag overrides everything. 10685 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10686 } 10687 // If current upgrade specifies particular preference 10688 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10689 // Application explicitly specified internal. 10690 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10691 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10692 // App explictly prefers external. Let policy decide 10693 } else { 10694 // Prefer previous location 10695 if (isExternal(pkg)) { 10696 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10697 } 10698 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10699 } 10700 } 10701 } else { 10702 // Invalid install. Return error code 10703 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10704 } 10705 } 10706 } 10707 // All the special cases have been taken care of. 10708 // Return result based on recommended install location. 10709 if (onSd) { 10710 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10711 } 10712 return pkgLite.recommendedInstallLocation; 10713 } 10714 10715 /* 10716 * Invoke remote method to get package information and install 10717 * location values. Override install location based on default 10718 * policy if needed and then create install arguments based 10719 * on the install location. 10720 */ 10721 public void handleStartCopy() throws RemoteException { 10722 int ret = PackageManager.INSTALL_SUCCEEDED; 10723 10724 // If we're already staged, we've firmly committed to an install location 10725 if (origin.staged) { 10726 if (origin.file != null) { 10727 installFlags |= PackageManager.INSTALL_INTERNAL; 10728 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10729 } else if (origin.cid != null) { 10730 installFlags |= PackageManager.INSTALL_EXTERNAL; 10731 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10732 } else { 10733 throw new IllegalStateException("Invalid stage location"); 10734 } 10735 } 10736 10737 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10738 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10739 PackageInfoLite pkgLite = null; 10740 10741 if (onInt && onSd) { 10742 // Check if both bits are set. 10743 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10744 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10745 } else { 10746 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10747 packageAbiOverride); 10748 10749 /* 10750 * If we have too little free space, try to free cache 10751 * before giving up. 10752 */ 10753 if (!origin.staged && pkgLite.recommendedInstallLocation 10754 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10755 // TODO: focus freeing disk space on the target device 10756 final StorageManager storage = StorageManager.from(mContext); 10757 final long lowThreshold = storage.getStorageLowBytes( 10758 Environment.getDataDirectory()); 10759 10760 final long sizeBytes = mContainerService.calculateInstalledSize( 10761 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10762 10763 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10764 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10765 installFlags, packageAbiOverride); 10766 } 10767 10768 /* 10769 * The cache free must have deleted the file we 10770 * downloaded to install. 10771 * 10772 * TODO: fix the "freeCache" call to not delete 10773 * the file we care about. 10774 */ 10775 if (pkgLite.recommendedInstallLocation 10776 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10777 pkgLite.recommendedInstallLocation 10778 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10779 } 10780 } 10781 } 10782 10783 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10784 int loc = pkgLite.recommendedInstallLocation; 10785 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10786 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10787 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10788 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10789 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10790 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10791 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10792 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10793 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10794 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10795 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10796 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10797 } else { 10798 // Override with defaults if needed. 10799 loc = installLocationPolicy(pkgLite); 10800 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10801 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10802 } else if (!onSd && !onInt) { 10803 // Override install location with flags 10804 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10805 // Set the flag to install on external media. 10806 installFlags |= PackageManager.INSTALL_EXTERNAL; 10807 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10808 } else { 10809 // Make sure the flag for installing on external 10810 // media is unset 10811 installFlags |= PackageManager.INSTALL_INTERNAL; 10812 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10813 } 10814 } 10815 } 10816 } 10817 10818 final InstallArgs args = createInstallArgs(this); 10819 mArgs = args; 10820 10821 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10822 /* 10823 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10824 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10825 */ 10826 int userIdentifier = getUser().getIdentifier(); 10827 if (userIdentifier == UserHandle.USER_ALL 10828 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10829 userIdentifier = UserHandle.USER_OWNER; 10830 } 10831 10832 /* 10833 * Determine if we have any installed package verifiers. If we 10834 * do, then we'll defer to them to verify the packages. 10835 */ 10836 final int requiredUid = mRequiredVerifierPackage == null ? -1 10837 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10838 if (!origin.existing && requiredUid != -1 10839 && isVerificationEnabled(userIdentifier, installFlags)) { 10840 final Intent verification = new Intent( 10841 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10842 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10843 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10844 PACKAGE_MIME_TYPE); 10845 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10846 10847 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10848 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10849 0 /* TODO: Which userId? */); 10850 10851 if (DEBUG_VERIFY) { 10852 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10853 + verification.toString() + " with " + pkgLite.verifiers.length 10854 + " optional verifiers"); 10855 } 10856 10857 final int verificationId = mPendingVerificationToken++; 10858 10859 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10860 10861 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10862 installerPackageName); 10863 10864 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10865 installFlags); 10866 10867 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10868 pkgLite.packageName); 10869 10870 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10871 pkgLite.versionCode); 10872 10873 if (verificationParams != null) { 10874 if (verificationParams.getVerificationURI() != null) { 10875 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10876 verificationParams.getVerificationURI()); 10877 } 10878 if (verificationParams.getOriginatingURI() != null) { 10879 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10880 verificationParams.getOriginatingURI()); 10881 } 10882 if (verificationParams.getReferrer() != null) { 10883 verification.putExtra(Intent.EXTRA_REFERRER, 10884 verificationParams.getReferrer()); 10885 } 10886 if (verificationParams.getOriginatingUid() >= 0) { 10887 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10888 verificationParams.getOriginatingUid()); 10889 } 10890 if (verificationParams.getInstallerUid() >= 0) { 10891 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10892 verificationParams.getInstallerUid()); 10893 } 10894 } 10895 10896 final PackageVerificationState verificationState = new PackageVerificationState( 10897 requiredUid, args); 10898 10899 mPendingVerification.append(verificationId, verificationState); 10900 10901 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10902 receivers, verificationState); 10903 10904 // Apps installed for "all" users use the device owner to verify the app 10905 UserHandle verifierUser = getUser(); 10906 if (verifierUser == UserHandle.ALL) { 10907 verifierUser = UserHandle.OWNER; 10908 } 10909 10910 /* 10911 * If any sufficient verifiers were listed in the package 10912 * manifest, attempt to ask them. 10913 */ 10914 if (sufficientVerifiers != null) { 10915 final int N = sufficientVerifiers.size(); 10916 if (N == 0) { 10917 Slog.i(TAG, "Additional verifiers required, but none installed."); 10918 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10919 } else { 10920 for (int i = 0; i < N; i++) { 10921 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10922 10923 final Intent sufficientIntent = new Intent(verification); 10924 sufficientIntent.setComponent(verifierComponent); 10925 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10926 } 10927 } 10928 } 10929 10930 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10931 mRequiredVerifierPackage, receivers); 10932 if (ret == PackageManager.INSTALL_SUCCEEDED 10933 && mRequiredVerifierPackage != null) { 10934 Trace.asyncTraceBegin( 10935 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10936 /* 10937 * Send the intent to the required verification agent, 10938 * but only start the verification timeout after the 10939 * target BroadcastReceivers have run. 10940 */ 10941 verification.setComponent(requiredVerifierComponent); 10942 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10943 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10944 new BroadcastReceiver() { 10945 @Override 10946 public void onReceive(Context context, Intent intent) { 10947 final Message msg = mHandler 10948 .obtainMessage(CHECK_PENDING_VERIFICATION); 10949 msg.arg1 = verificationId; 10950 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10951 } 10952 }, null, 0, null, null); 10953 10954 /* 10955 * We don't want the copy to proceed until verification 10956 * succeeds, so null out this field. 10957 */ 10958 mArgs = null; 10959 } 10960 } else { 10961 /* 10962 * No package verification is enabled, so immediately start 10963 * the remote call to initiate copy using temporary file. 10964 */ 10965 ret = args.copyApk(mContainerService, true); 10966 } 10967 } 10968 10969 mRet = ret; 10970 } 10971 10972 @Override 10973 void handleReturnCode() { 10974 // If mArgs is null, then MCS couldn't be reached. When it 10975 // reconnects, it will try again to install. At that point, this 10976 // will succeed. 10977 if (mArgs != null) { 10978 processPendingInstall(mArgs, mRet); 10979 } 10980 } 10981 10982 @Override 10983 void handleServiceError() { 10984 mArgs = createInstallArgs(this); 10985 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10986 } 10987 10988 public boolean isForwardLocked() { 10989 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10990 } 10991 } 10992 10993 /** 10994 * Used during creation of InstallArgs 10995 * 10996 * @param installFlags package installation flags 10997 * @return true if should be installed on external storage 10998 */ 10999 private static boolean installOnExternalAsec(int installFlags) { 11000 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11001 return false; 11002 } 11003 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11004 return true; 11005 } 11006 return false; 11007 } 11008 11009 /** 11010 * Used during creation of InstallArgs 11011 * 11012 * @param installFlags package installation flags 11013 * @return true if should be installed as forward locked 11014 */ 11015 private static boolean installForwardLocked(int installFlags) { 11016 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11017 } 11018 11019 private InstallArgs createInstallArgs(InstallParams params) { 11020 if (params.move != null) { 11021 return new MoveInstallArgs(params); 11022 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11023 return new AsecInstallArgs(params); 11024 } else { 11025 return new FileInstallArgs(params); 11026 } 11027 } 11028 11029 /** 11030 * Create args that describe an existing installed package. Typically used 11031 * when cleaning up old installs, or used as a move source. 11032 */ 11033 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11034 String resourcePath, String[] instructionSets) { 11035 final boolean isInAsec; 11036 if (installOnExternalAsec(installFlags)) { 11037 /* Apps on SD card are always in ASEC containers. */ 11038 isInAsec = true; 11039 } else if (installForwardLocked(installFlags) 11040 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11041 /* 11042 * Forward-locked apps are only in ASEC containers if they're the 11043 * new style 11044 */ 11045 isInAsec = true; 11046 } else { 11047 isInAsec = false; 11048 } 11049 11050 if (isInAsec) { 11051 return new AsecInstallArgs(codePath, instructionSets, 11052 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11053 } else { 11054 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11055 } 11056 } 11057 11058 static abstract class InstallArgs { 11059 /** @see InstallParams#origin */ 11060 final OriginInfo origin; 11061 /** @see InstallParams#move */ 11062 final MoveInfo move; 11063 11064 final IPackageInstallObserver2 observer; 11065 // Always refers to PackageManager flags only 11066 final int installFlags; 11067 final String installerPackageName; 11068 final String volumeUuid; 11069 final ManifestDigest manifestDigest; 11070 final UserHandle user; 11071 final String abiOverride; 11072 final String[] installGrantPermissions; 11073 /** If non-null, drop an async trace when the install completes */ 11074 final String traceMethod; 11075 final int traceCookie; 11076 11077 // The list of instruction sets supported by this app. This is currently 11078 // only used during the rmdex() phase to clean up resources. We can get rid of this 11079 // if we move dex files under the common app path. 11080 /* nullable */ String[] instructionSets; 11081 11082 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11083 int installFlags, String installerPackageName, String volumeUuid, 11084 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11085 String abiOverride, String[] installGrantPermissions, 11086 String traceMethod, int traceCookie) { 11087 this.origin = origin; 11088 this.move = move; 11089 this.installFlags = installFlags; 11090 this.observer = observer; 11091 this.installerPackageName = installerPackageName; 11092 this.volumeUuid = volumeUuid; 11093 this.manifestDigest = manifestDigest; 11094 this.user = user; 11095 this.instructionSets = instructionSets; 11096 this.abiOverride = abiOverride; 11097 this.installGrantPermissions = installGrantPermissions; 11098 this.traceMethod = traceMethod; 11099 this.traceCookie = traceCookie; 11100 } 11101 11102 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11103 abstract int doPreInstall(int status); 11104 11105 /** 11106 * Rename package into final resting place. All paths on the given 11107 * scanned package should be updated to reflect the rename. 11108 */ 11109 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11110 abstract int doPostInstall(int status, int uid); 11111 11112 /** @see PackageSettingBase#codePathString */ 11113 abstract String getCodePath(); 11114 /** @see PackageSettingBase#resourcePathString */ 11115 abstract String getResourcePath(); 11116 11117 // Need installer lock especially for dex file removal. 11118 abstract void cleanUpResourcesLI(); 11119 abstract boolean doPostDeleteLI(boolean delete); 11120 11121 /** 11122 * Called before the source arguments are copied. This is used mostly 11123 * for MoveParams when it needs to read the source file to put it in the 11124 * destination. 11125 */ 11126 int doPreCopy() { 11127 return PackageManager.INSTALL_SUCCEEDED; 11128 } 11129 11130 /** 11131 * Called after the source arguments are copied. This is used mostly for 11132 * MoveParams when it needs to read the source file to put it in the 11133 * destination. 11134 * 11135 * @return 11136 */ 11137 int doPostCopy(int uid) { 11138 return PackageManager.INSTALL_SUCCEEDED; 11139 } 11140 11141 protected boolean isFwdLocked() { 11142 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11143 } 11144 11145 protected boolean isExternalAsec() { 11146 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11147 } 11148 11149 UserHandle getUser() { 11150 return user; 11151 } 11152 } 11153 11154 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11155 if (!allCodePaths.isEmpty()) { 11156 if (instructionSets == null) { 11157 throw new IllegalStateException("instructionSet == null"); 11158 } 11159 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11160 for (String codePath : allCodePaths) { 11161 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11162 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11163 if (retCode < 0) { 11164 Slog.w(TAG, "Couldn't remove dex file for package: " 11165 + " at location " + codePath + ", retcode=" + retCode); 11166 // we don't consider this to be a failure of the core package deletion 11167 } 11168 } 11169 } 11170 } 11171 } 11172 11173 /** 11174 * Logic to handle installation of non-ASEC applications, including copying 11175 * and renaming logic. 11176 */ 11177 class FileInstallArgs extends InstallArgs { 11178 private File codeFile; 11179 private File resourceFile; 11180 11181 // Example topology: 11182 // /data/app/com.example/base.apk 11183 // /data/app/com.example/split_foo.apk 11184 // /data/app/com.example/lib/arm/libfoo.so 11185 // /data/app/com.example/lib/arm64/libfoo.so 11186 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11187 11188 /** New install */ 11189 FileInstallArgs(InstallParams params) { 11190 super(params.origin, params.move, params.observer, params.installFlags, 11191 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11192 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11193 params.grantedRuntimePermissions, 11194 params.traceMethod, params.traceCookie); 11195 if (isFwdLocked()) { 11196 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11197 } 11198 } 11199 11200 /** Existing install */ 11201 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11202 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11203 null, null, null, 0); 11204 this.codeFile = (codePath != null) ? new File(codePath) : null; 11205 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11206 } 11207 11208 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11209 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11210 try { 11211 return doCopyApk(imcs, temp); 11212 } finally { 11213 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11214 } 11215 } 11216 11217 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11218 if (origin.staged) { 11219 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11220 codeFile = origin.file; 11221 resourceFile = origin.file; 11222 return PackageManager.INSTALL_SUCCEEDED; 11223 } 11224 11225 try { 11226 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11227 codeFile = tempDir; 11228 resourceFile = tempDir; 11229 } catch (IOException e) { 11230 Slog.w(TAG, "Failed to create copy file: " + e); 11231 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11232 } 11233 11234 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11235 @Override 11236 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11237 if (!FileUtils.isValidExtFilename(name)) { 11238 throw new IllegalArgumentException("Invalid filename: " + name); 11239 } 11240 try { 11241 final File file = new File(codeFile, name); 11242 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11243 O_RDWR | O_CREAT, 0644); 11244 Os.chmod(file.getAbsolutePath(), 0644); 11245 return new ParcelFileDescriptor(fd); 11246 } catch (ErrnoException e) { 11247 throw new RemoteException("Failed to open: " + e.getMessage()); 11248 } 11249 } 11250 }; 11251 11252 int ret = PackageManager.INSTALL_SUCCEEDED; 11253 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11254 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11255 Slog.e(TAG, "Failed to copy package"); 11256 return ret; 11257 } 11258 11259 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11260 NativeLibraryHelper.Handle handle = null; 11261 try { 11262 handle = NativeLibraryHelper.Handle.create(codeFile); 11263 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11264 abiOverride); 11265 } catch (IOException e) { 11266 Slog.e(TAG, "Copying native libraries failed", e); 11267 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11268 } finally { 11269 IoUtils.closeQuietly(handle); 11270 } 11271 11272 return ret; 11273 } 11274 11275 int doPreInstall(int status) { 11276 if (status != PackageManager.INSTALL_SUCCEEDED) { 11277 cleanUp(); 11278 } 11279 return status; 11280 } 11281 11282 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11283 if (status != PackageManager.INSTALL_SUCCEEDED) { 11284 cleanUp(); 11285 return false; 11286 } 11287 11288 final File targetDir = codeFile.getParentFile(); 11289 final File beforeCodeFile = codeFile; 11290 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11291 11292 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11293 try { 11294 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11295 } catch (ErrnoException e) { 11296 Slog.w(TAG, "Failed to rename", e); 11297 return false; 11298 } 11299 11300 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11301 Slog.w(TAG, "Failed to restorecon"); 11302 return false; 11303 } 11304 11305 // Reflect the rename internally 11306 codeFile = afterCodeFile; 11307 resourceFile = afterCodeFile; 11308 11309 // Reflect the rename in scanned details 11310 pkg.codePath = afterCodeFile.getAbsolutePath(); 11311 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11312 pkg.baseCodePath); 11313 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11314 pkg.splitCodePaths); 11315 11316 // Reflect the rename in app info 11317 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11318 pkg.applicationInfo.setCodePath(pkg.codePath); 11319 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11320 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11321 pkg.applicationInfo.setResourcePath(pkg.codePath); 11322 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11323 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11324 11325 return true; 11326 } 11327 11328 int doPostInstall(int status, int uid) { 11329 if (status != PackageManager.INSTALL_SUCCEEDED) { 11330 cleanUp(); 11331 } 11332 return status; 11333 } 11334 11335 @Override 11336 String getCodePath() { 11337 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11338 } 11339 11340 @Override 11341 String getResourcePath() { 11342 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11343 } 11344 11345 private boolean cleanUp() { 11346 if (codeFile == null || !codeFile.exists()) { 11347 return false; 11348 } 11349 11350 if (codeFile.isDirectory()) { 11351 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11352 } else { 11353 codeFile.delete(); 11354 } 11355 11356 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11357 resourceFile.delete(); 11358 } 11359 11360 return true; 11361 } 11362 11363 void cleanUpResourcesLI() { 11364 // Try enumerating all code paths before deleting 11365 List<String> allCodePaths = Collections.EMPTY_LIST; 11366 if (codeFile != null && codeFile.exists()) { 11367 try { 11368 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11369 allCodePaths = pkg.getAllCodePaths(); 11370 } catch (PackageParserException e) { 11371 // Ignored; we tried our best 11372 } 11373 } 11374 11375 cleanUp(); 11376 removeDexFiles(allCodePaths, instructionSets); 11377 } 11378 11379 boolean doPostDeleteLI(boolean delete) { 11380 // XXX err, shouldn't we respect the delete flag? 11381 cleanUpResourcesLI(); 11382 return true; 11383 } 11384 } 11385 11386 private boolean isAsecExternal(String cid) { 11387 final String asecPath = PackageHelper.getSdFilesystem(cid); 11388 return !asecPath.startsWith(mAsecInternalPath); 11389 } 11390 11391 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11392 PackageManagerException { 11393 if (copyRet < 0) { 11394 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11395 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11396 throw new PackageManagerException(copyRet, message); 11397 } 11398 } 11399 } 11400 11401 /** 11402 * Extract the MountService "container ID" from the full code path of an 11403 * .apk. 11404 */ 11405 static String cidFromCodePath(String fullCodePath) { 11406 int eidx = fullCodePath.lastIndexOf("/"); 11407 String subStr1 = fullCodePath.substring(0, eidx); 11408 int sidx = subStr1.lastIndexOf("/"); 11409 return subStr1.substring(sidx+1, eidx); 11410 } 11411 11412 /** 11413 * Logic to handle installation of ASEC applications, including copying and 11414 * renaming logic. 11415 */ 11416 class AsecInstallArgs extends InstallArgs { 11417 static final String RES_FILE_NAME = "pkg.apk"; 11418 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11419 11420 String cid; 11421 String packagePath; 11422 String resourcePath; 11423 11424 /** New install */ 11425 AsecInstallArgs(InstallParams params) { 11426 super(params.origin, params.move, params.observer, params.installFlags, 11427 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11428 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11429 params.grantedRuntimePermissions, 11430 params.traceMethod, params.traceCookie); 11431 } 11432 11433 /** Existing install */ 11434 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11435 boolean isExternal, boolean isForwardLocked) { 11436 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11437 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11438 instructionSets, null, null, null, 0); 11439 // Hackily pretend we're still looking at a full code path 11440 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11441 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11442 } 11443 11444 // Extract cid from fullCodePath 11445 int eidx = fullCodePath.lastIndexOf("/"); 11446 String subStr1 = fullCodePath.substring(0, eidx); 11447 int sidx = subStr1.lastIndexOf("/"); 11448 cid = subStr1.substring(sidx+1, eidx); 11449 setMountPath(subStr1); 11450 } 11451 11452 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11453 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11454 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11455 instructionSets, null, null, null, 0); 11456 this.cid = cid; 11457 setMountPath(PackageHelper.getSdDir(cid)); 11458 } 11459 11460 void createCopyFile() { 11461 cid = mInstallerService.allocateExternalStageCidLegacy(); 11462 } 11463 11464 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11465 if (origin.staged) { 11466 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11467 cid = origin.cid; 11468 setMountPath(PackageHelper.getSdDir(cid)); 11469 return PackageManager.INSTALL_SUCCEEDED; 11470 } 11471 11472 if (temp) { 11473 createCopyFile(); 11474 } else { 11475 /* 11476 * Pre-emptively destroy the container since it's destroyed if 11477 * copying fails due to it existing anyway. 11478 */ 11479 PackageHelper.destroySdDir(cid); 11480 } 11481 11482 final String newMountPath = imcs.copyPackageToContainer( 11483 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11484 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11485 11486 if (newMountPath != null) { 11487 setMountPath(newMountPath); 11488 return PackageManager.INSTALL_SUCCEEDED; 11489 } else { 11490 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11491 } 11492 } 11493 11494 @Override 11495 String getCodePath() { 11496 return packagePath; 11497 } 11498 11499 @Override 11500 String getResourcePath() { 11501 return resourcePath; 11502 } 11503 11504 int doPreInstall(int status) { 11505 if (status != PackageManager.INSTALL_SUCCEEDED) { 11506 // Destroy container 11507 PackageHelper.destroySdDir(cid); 11508 } else { 11509 boolean mounted = PackageHelper.isContainerMounted(cid); 11510 if (!mounted) { 11511 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11512 Process.SYSTEM_UID); 11513 if (newMountPath != null) { 11514 setMountPath(newMountPath); 11515 } else { 11516 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11517 } 11518 } 11519 } 11520 return status; 11521 } 11522 11523 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11524 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11525 String newMountPath = null; 11526 if (PackageHelper.isContainerMounted(cid)) { 11527 // Unmount the container 11528 if (!PackageHelper.unMountSdDir(cid)) { 11529 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11530 return false; 11531 } 11532 } 11533 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11534 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11535 " which might be stale. Will try to clean up."); 11536 // Clean up the stale container and proceed to recreate. 11537 if (!PackageHelper.destroySdDir(newCacheId)) { 11538 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11539 return false; 11540 } 11541 // Successfully cleaned up stale container. Try to rename again. 11542 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11543 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11544 + " inspite of cleaning it up."); 11545 return false; 11546 } 11547 } 11548 if (!PackageHelper.isContainerMounted(newCacheId)) { 11549 Slog.w(TAG, "Mounting container " + newCacheId); 11550 newMountPath = PackageHelper.mountSdDir(newCacheId, 11551 getEncryptKey(), Process.SYSTEM_UID); 11552 } else { 11553 newMountPath = PackageHelper.getSdDir(newCacheId); 11554 } 11555 if (newMountPath == null) { 11556 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11557 return false; 11558 } 11559 Log.i(TAG, "Succesfully renamed " + cid + 11560 " to " + newCacheId + 11561 " at new path: " + newMountPath); 11562 cid = newCacheId; 11563 11564 final File beforeCodeFile = new File(packagePath); 11565 setMountPath(newMountPath); 11566 final File afterCodeFile = new File(packagePath); 11567 11568 // Reflect the rename in scanned details 11569 pkg.codePath = afterCodeFile.getAbsolutePath(); 11570 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11571 pkg.baseCodePath); 11572 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11573 pkg.splitCodePaths); 11574 11575 // Reflect the rename in app info 11576 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11577 pkg.applicationInfo.setCodePath(pkg.codePath); 11578 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11579 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11580 pkg.applicationInfo.setResourcePath(pkg.codePath); 11581 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11582 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11583 11584 return true; 11585 } 11586 11587 private void setMountPath(String mountPath) { 11588 final File mountFile = new File(mountPath); 11589 11590 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11591 if (monolithicFile.exists()) { 11592 packagePath = monolithicFile.getAbsolutePath(); 11593 if (isFwdLocked()) { 11594 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11595 } else { 11596 resourcePath = packagePath; 11597 } 11598 } else { 11599 packagePath = mountFile.getAbsolutePath(); 11600 resourcePath = packagePath; 11601 } 11602 } 11603 11604 int doPostInstall(int status, int uid) { 11605 if (status != PackageManager.INSTALL_SUCCEEDED) { 11606 cleanUp(); 11607 } else { 11608 final int groupOwner; 11609 final String protectedFile; 11610 if (isFwdLocked()) { 11611 groupOwner = UserHandle.getSharedAppGid(uid); 11612 protectedFile = RES_FILE_NAME; 11613 } else { 11614 groupOwner = -1; 11615 protectedFile = null; 11616 } 11617 11618 if (uid < Process.FIRST_APPLICATION_UID 11619 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11620 Slog.e(TAG, "Failed to finalize " + cid); 11621 PackageHelper.destroySdDir(cid); 11622 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11623 } 11624 11625 boolean mounted = PackageHelper.isContainerMounted(cid); 11626 if (!mounted) { 11627 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11628 } 11629 } 11630 return status; 11631 } 11632 11633 private void cleanUp() { 11634 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11635 11636 // Destroy secure container 11637 PackageHelper.destroySdDir(cid); 11638 } 11639 11640 private List<String> getAllCodePaths() { 11641 final File codeFile = new File(getCodePath()); 11642 if (codeFile != null && codeFile.exists()) { 11643 try { 11644 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11645 return pkg.getAllCodePaths(); 11646 } catch (PackageParserException e) { 11647 // Ignored; we tried our best 11648 } 11649 } 11650 return Collections.EMPTY_LIST; 11651 } 11652 11653 void cleanUpResourcesLI() { 11654 // Enumerate all code paths before deleting 11655 cleanUpResourcesLI(getAllCodePaths()); 11656 } 11657 11658 private void cleanUpResourcesLI(List<String> allCodePaths) { 11659 cleanUp(); 11660 removeDexFiles(allCodePaths, instructionSets); 11661 } 11662 11663 String getPackageName() { 11664 return getAsecPackageName(cid); 11665 } 11666 11667 boolean doPostDeleteLI(boolean delete) { 11668 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11669 final List<String> allCodePaths = getAllCodePaths(); 11670 boolean mounted = PackageHelper.isContainerMounted(cid); 11671 if (mounted) { 11672 // Unmount first 11673 if (PackageHelper.unMountSdDir(cid)) { 11674 mounted = false; 11675 } 11676 } 11677 if (!mounted && delete) { 11678 cleanUpResourcesLI(allCodePaths); 11679 } 11680 return !mounted; 11681 } 11682 11683 @Override 11684 int doPreCopy() { 11685 if (isFwdLocked()) { 11686 if (!PackageHelper.fixSdPermissions(cid, 11687 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11688 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11689 } 11690 } 11691 11692 return PackageManager.INSTALL_SUCCEEDED; 11693 } 11694 11695 @Override 11696 int doPostCopy(int uid) { 11697 if (isFwdLocked()) { 11698 if (uid < Process.FIRST_APPLICATION_UID 11699 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11700 RES_FILE_NAME)) { 11701 Slog.e(TAG, "Failed to finalize " + cid); 11702 PackageHelper.destroySdDir(cid); 11703 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11704 } 11705 } 11706 11707 return PackageManager.INSTALL_SUCCEEDED; 11708 } 11709 } 11710 11711 /** 11712 * Logic to handle movement of existing installed applications. 11713 */ 11714 class MoveInstallArgs extends InstallArgs { 11715 private File codeFile; 11716 private File resourceFile; 11717 11718 /** New install */ 11719 MoveInstallArgs(InstallParams params) { 11720 super(params.origin, params.move, params.observer, params.installFlags, 11721 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11722 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11723 params.grantedRuntimePermissions, 11724 params.traceMethod, params.traceCookie); 11725 } 11726 11727 int copyApk(IMediaContainerService imcs, boolean temp) { 11728 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11729 + move.fromUuid + " to " + move.toUuid); 11730 synchronized (mInstaller) { 11731 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11732 move.dataAppName, move.appId, move.seinfo) != 0) { 11733 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11734 } 11735 } 11736 11737 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11738 resourceFile = codeFile; 11739 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11740 11741 return PackageManager.INSTALL_SUCCEEDED; 11742 } 11743 11744 int doPreInstall(int status) { 11745 if (status != PackageManager.INSTALL_SUCCEEDED) { 11746 cleanUp(move.toUuid); 11747 } 11748 return status; 11749 } 11750 11751 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11752 if (status != PackageManager.INSTALL_SUCCEEDED) { 11753 cleanUp(move.toUuid); 11754 return false; 11755 } 11756 11757 // Reflect the move in app info 11758 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11759 pkg.applicationInfo.setCodePath(pkg.codePath); 11760 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11761 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11762 pkg.applicationInfo.setResourcePath(pkg.codePath); 11763 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11764 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11765 11766 return true; 11767 } 11768 11769 int doPostInstall(int status, int uid) { 11770 if (status == PackageManager.INSTALL_SUCCEEDED) { 11771 cleanUp(move.fromUuid); 11772 } else { 11773 cleanUp(move.toUuid); 11774 } 11775 return status; 11776 } 11777 11778 @Override 11779 String getCodePath() { 11780 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11781 } 11782 11783 @Override 11784 String getResourcePath() { 11785 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11786 } 11787 11788 private boolean cleanUp(String volumeUuid) { 11789 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11790 move.dataAppName); 11791 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11792 synchronized (mInstallLock) { 11793 // Clean up both app data and code 11794 removeDataDirsLI(volumeUuid, move.packageName); 11795 if (codeFile.isDirectory()) { 11796 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11797 } else { 11798 codeFile.delete(); 11799 } 11800 } 11801 return true; 11802 } 11803 11804 void cleanUpResourcesLI() { 11805 throw new UnsupportedOperationException(); 11806 } 11807 11808 boolean doPostDeleteLI(boolean delete) { 11809 throw new UnsupportedOperationException(); 11810 } 11811 } 11812 11813 static String getAsecPackageName(String packageCid) { 11814 int idx = packageCid.lastIndexOf("-"); 11815 if (idx == -1) { 11816 return packageCid; 11817 } 11818 return packageCid.substring(0, idx); 11819 } 11820 11821 // Utility method used to create code paths based on package name and available index. 11822 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11823 String idxStr = ""; 11824 int idx = 1; 11825 // Fall back to default value of idx=1 if prefix is not 11826 // part of oldCodePath 11827 if (oldCodePath != null) { 11828 String subStr = oldCodePath; 11829 // Drop the suffix right away 11830 if (suffix != null && subStr.endsWith(suffix)) { 11831 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11832 } 11833 // If oldCodePath already contains prefix find out the 11834 // ending index to either increment or decrement. 11835 int sidx = subStr.lastIndexOf(prefix); 11836 if (sidx != -1) { 11837 subStr = subStr.substring(sidx + prefix.length()); 11838 if (subStr != null) { 11839 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11840 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11841 } 11842 try { 11843 idx = Integer.parseInt(subStr); 11844 if (idx <= 1) { 11845 idx++; 11846 } else { 11847 idx--; 11848 } 11849 } catch(NumberFormatException e) { 11850 } 11851 } 11852 } 11853 } 11854 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11855 return prefix + idxStr; 11856 } 11857 11858 private File getNextCodePath(File targetDir, String packageName) { 11859 int suffix = 1; 11860 File result; 11861 do { 11862 result = new File(targetDir, packageName + "-" + suffix); 11863 suffix++; 11864 } while (result.exists()); 11865 return result; 11866 } 11867 11868 // Utility method that returns the relative package path with respect 11869 // to the installation directory. Like say for /data/data/com.test-1.apk 11870 // string com.test-1 is returned. 11871 static String deriveCodePathName(String codePath) { 11872 if (codePath == null) { 11873 return null; 11874 } 11875 final File codeFile = new File(codePath); 11876 final String name = codeFile.getName(); 11877 if (codeFile.isDirectory()) { 11878 return name; 11879 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11880 final int lastDot = name.lastIndexOf('.'); 11881 return name.substring(0, lastDot); 11882 } else { 11883 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11884 return null; 11885 } 11886 } 11887 11888 class PackageInstalledInfo { 11889 String name; 11890 int uid; 11891 // The set of users that originally had this package installed. 11892 int[] origUsers; 11893 // The set of users that now have this package installed. 11894 int[] newUsers; 11895 PackageParser.Package pkg; 11896 int returnCode; 11897 String returnMsg; 11898 PackageRemovedInfo removedInfo; 11899 11900 public void setError(int code, String msg) { 11901 returnCode = code; 11902 returnMsg = msg; 11903 Slog.w(TAG, msg); 11904 } 11905 11906 public void setError(String msg, PackageParserException e) { 11907 returnCode = e.error; 11908 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11909 Slog.w(TAG, msg, e); 11910 } 11911 11912 public void setError(String msg, PackageManagerException e) { 11913 returnCode = e.error; 11914 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11915 Slog.w(TAG, msg, e); 11916 } 11917 11918 // In some error cases we want to convey more info back to the observer 11919 String origPackage; 11920 String origPermission; 11921 } 11922 11923 /* 11924 * Install a non-existing package. 11925 */ 11926 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11927 UserHandle user, String installerPackageName, String volumeUuid, 11928 PackageInstalledInfo res) { 11929 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11930 11931 // Remember this for later, in case we need to rollback this install 11932 String pkgName = pkg.packageName; 11933 11934 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11935 // TODO: b/23350563 11936 final boolean dataDirExists = Environment 11937 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11938 11939 synchronized(mPackages) { 11940 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11941 // A package with the same name is already installed, though 11942 // it has been renamed to an older name. The package we 11943 // are trying to install should be installed as an update to 11944 // the existing one, but that has not been requested, so bail. 11945 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11946 + " without first uninstalling package running as " 11947 + mSettings.mRenamedPackages.get(pkgName)); 11948 return; 11949 } 11950 if (mPackages.containsKey(pkgName)) { 11951 // Don't allow installation over an existing package with the same name. 11952 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11953 + " without first uninstalling."); 11954 return; 11955 } 11956 } 11957 11958 try { 11959 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11960 System.currentTimeMillis(), user); 11961 11962 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11963 // delete the partially installed application. the data directory will have to be 11964 // restored if it was already existing 11965 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11966 // remove package from internal structures. Note that we want deletePackageX to 11967 // delete the package data and cache directories that it created in 11968 // scanPackageLocked, unless those directories existed before we even tried to 11969 // install. 11970 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11971 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11972 res.removedInfo, true); 11973 } 11974 11975 } catch (PackageManagerException e) { 11976 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11977 } 11978 11979 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11980 } 11981 11982 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11983 // Can't rotate keys during boot or if sharedUser. 11984 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11985 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11986 return false; 11987 } 11988 // app is using upgradeKeySets; make sure all are valid 11989 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11990 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11991 for (int i = 0; i < upgradeKeySets.length; i++) { 11992 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11993 Slog.wtf(TAG, "Package " 11994 + (oldPs.name != null ? oldPs.name : "<null>") 11995 + " contains upgrade-key-set reference to unknown key-set: " 11996 + upgradeKeySets[i] 11997 + " reverting to signatures check."); 11998 return false; 11999 } 12000 } 12001 return true; 12002 } 12003 12004 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12005 // Upgrade keysets are being used. Determine if new package has a superset of the 12006 // required keys. 12007 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12008 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12009 for (int i = 0; i < upgradeKeySets.length; i++) { 12010 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12011 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12012 return true; 12013 } 12014 } 12015 return false; 12016 } 12017 12018 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12019 UserHandle user, String installerPackageName, String volumeUuid, 12020 PackageInstalledInfo res) { 12021 final PackageParser.Package oldPackage; 12022 final String pkgName = pkg.packageName; 12023 final int[] allUsers; 12024 final boolean[] perUserInstalled; 12025 12026 // First find the old package info and check signatures 12027 synchronized(mPackages) { 12028 oldPackage = mPackages.get(pkgName); 12029 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12030 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12031 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12032 if(!checkUpgradeKeySetLP(ps, pkg)) { 12033 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12034 "New package not signed by keys specified by upgrade-keysets: " 12035 + pkgName); 12036 return; 12037 } 12038 } else { 12039 // default to original signature matching 12040 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12041 != PackageManager.SIGNATURE_MATCH) { 12042 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12043 "New package has a different signature: " + pkgName); 12044 return; 12045 } 12046 } 12047 12048 // In case of rollback, remember per-user/profile install state 12049 allUsers = sUserManager.getUserIds(); 12050 perUserInstalled = new boolean[allUsers.length]; 12051 for (int i = 0; i < allUsers.length; i++) { 12052 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12053 } 12054 } 12055 12056 boolean sysPkg = (isSystemApp(oldPackage)); 12057 if (sysPkg) { 12058 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12059 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12060 } else { 12061 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12062 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12063 } 12064 } 12065 12066 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12067 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12068 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12069 String volumeUuid, PackageInstalledInfo res) { 12070 String pkgName = deletedPackage.packageName; 12071 boolean deletedPkg = true; 12072 boolean updatedSettings = false; 12073 12074 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12075 + deletedPackage); 12076 long origUpdateTime; 12077 if (pkg.mExtras != null) { 12078 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12079 } else { 12080 origUpdateTime = 0; 12081 } 12082 12083 // First delete the existing package while retaining the data directory 12084 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12085 res.removedInfo, true)) { 12086 // If the existing package wasn't successfully deleted 12087 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12088 deletedPkg = false; 12089 } else { 12090 // Successfully deleted the old package; proceed with replace. 12091 12092 // If deleted package lived in a container, give users a chance to 12093 // relinquish resources before killing. 12094 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12095 if (DEBUG_INSTALL) { 12096 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12097 } 12098 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12099 final ArrayList<String> pkgList = new ArrayList<String>(1); 12100 pkgList.add(deletedPackage.applicationInfo.packageName); 12101 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12102 } 12103 12104 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12105 try { 12106 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12107 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12108 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12109 perUserInstalled, res, user); 12110 updatedSettings = true; 12111 } catch (PackageManagerException e) { 12112 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12113 } 12114 } 12115 12116 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12117 // remove package from internal structures. Note that we want deletePackageX to 12118 // delete the package data and cache directories that it created in 12119 // scanPackageLocked, unless those directories existed before we even tried to 12120 // install. 12121 if(updatedSettings) { 12122 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12123 deletePackageLI( 12124 pkgName, null, true, allUsers, perUserInstalled, 12125 PackageManager.DELETE_KEEP_DATA, 12126 res.removedInfo, true); 12127 } 12128 // Since we failed to install the new package we need to restore the old 12129 // package that we deleted. 12130 if (deletedPkg) { 12131 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12132 File restoreFile = new File(deletedPackage.codePath); 12133 // Parse old package 12134 boolean oldExternal = isExternal(deletedPackage); 12135 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12136 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12137 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12138 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12139 try { 12140 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 12141 } catch (PackageManagerException e) { 12142 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12143 + e.getMessage()); 12144 return; 12145 } 12146 // Restore of old package succeeded. Update permissions. 12147 // writer 12148 synchronized (mPackages) { 12149 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12150 UPDATE_PERMISSIONS_ALL); 12151 // can downgrade to reader 12152 mSettings.writeLPr(); 12153 } 12154 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12155 } 12156 } 12157 } 12158 12159 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12160 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12161 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12162 String volumeUuid, PackageInstalledInfo res) { 12163 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12164 + ", old=" + deletedPackage); 12165 boolean disabledSystem = false; 12166 boolean updatedSettings = false; 12167 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12168 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12169 != 0) { 12170 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12171 } 12172 String packageName = deletedPackage.packageName; 12173 if (packageName == null) { 12174 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12175 "Attempt to delete null packageName."); 12176 return; 12177 } 12178 PackageParser.Package oldPkg; 12179 PackageSetting oldPkgSetting; 12180 // reader 12181 synchronized (mPackages) { 12182 oldPkg = mPackages.get(packageName); 12183 oldPkgSetting = mSettings.mPackages.get(packageName); 12184 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12185 (oldPkgSetting == null)) { 12186 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12187 "Couldn't find package:" + packageName + " information"); 12188 return; 12189 } 12190 } 12191 12192 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12193 12194 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12195 res.removedInfo.removedPackage = packageName; 12196 // Remove existing system package 12197 removePackageLI(oldPkgSetting, true); 12198 // writer 12199 synchronized (mPackages) { 12200 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12201 if (!disabledSystem && deletedPackage != null) { 12202 // We didn't need to disable the .apk as a current system package, 12203 // which means we are replacing another update that is already 12204 // installed. We need to make sure to delete the older one's .apk. 12205 res.removedInfo.args = createInstallArgsForExisting(0, 12206 deletedPackage.applicationInfo.getCodePath(), 12207 deletedPackage.applicationInfo.getResourcePath(), 12208 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12209 } else { 12210 res.removedInfo.args = null; 12211 } 12212 } 12213 12214 // Successfully disabled the old package. Now proceed with re-installation 12215 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12216 12217 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12218 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12219 12220 PackageParser.Package newPackage = null; 12221 try { 12222 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12223 if (newPackage.mExtras != null) { 12224 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12225 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12226 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12227 12228 // is the update attempting to change shared user? that isn't going to work... 12229 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12230 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12231 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12232 + " to " + newPkgSetting.sharedUser); 12233 updatedSettings = true; 12234 } 12235 } 12236 12237 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12238 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12239 perUserInstalled, res, user); 12240 updatedSettings = true; 12241 } 12242 12243 } catch (PackageManagerException e) { 12244 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12245 } 12246 12247 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12248 // Re installation failed. Restore old information 12249 // Remove new pkg information 12250 if (newPackage != null) { 12251 removeInstalledPackageLI(newPackage, true); 12252 } 12253 // Add back the old system package 12254 try { 12255 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12256 } catch (PackageManagerException e) { 12257 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12258 } 12259 // Restore the old system information in Settings 12260 synchronized (mPackages) { 12261 if (disabledSystem) { 12262 mSettings.enableSystemPackageLPw(packageName); 12263 } 12264 if (updatedSettings) { 12265 mSettings.setInstallerPackageName(packageName, 12266 oldPkgSetting.installerPackageName); 12267 } 12268 mSettings.writeLPr(); 12269 } 12270 } 12271 } 12272 12273 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12274 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12275 UserHandle user) { 12276 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12277 12278 String pkgName = newPackage.packageName; 12279 synchronized (mPackages) { 12280 //write settings. the installStatus will be incomplete at this stage. 12281 //note that the new package setting would have already been 12282 //added to mPackages. It hasn't been persisted yet. 12283 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12284 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12285 mSettings.writeLPr(); 12286 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12287 } 12288 12289 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12290 synchronized (mPackages) { 12291 updatePermissionsLPw(newPackage.packageName, newPackage, 12292 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12293 ? UPDATE_PERMISSIONS_ALL : 0)); 12294 // For system-bundled packages, we assume that installing an upgraded version 12295 // of the package implies that the user actually wants to run that new code, 12296 // so we enable the package. 12297 PackageSetting ps = mSettings.mPackages.get(pkgName); 12298 if (ps != null) { 12299 if (isSystemApp(newPackage)) { 12300 // NB: implicit assumption that system package upgrades apply to all users 12301 if (DEBUG_INSTALL) { 12302 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12303 } 12304 if (res.origUsers != null) { 12305 for (int userHandle : res.origUsers) { 12306 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12307 userHandle, installerPackageName); 12308 } 12309 } 12310 // Also convey the prior install/uninstall state 12311 if (allUsers != null && perUserInstalled != null) { 12312 for (int i = 0; i < allUsers.length; i++) { 12313 if (DEBUG_INSTALL) { 12314 Slog.d(TAG, " user " + allUsers[i] 12315 + " => " + perUserInstalled[i]); 12316 } 12317 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12318 } 12319 // these install state changes will be persisted in the 12320 // upcoming call to mSettings.writeLPr(). 12321 } 12322 } 12323 // It's implied that when a user requests installation, they want the app to be 12324 // installed and enabled. 12325 int userId = user.getIdentifier(); 12326 if (userId != UserHandle.USER_ALL) { 12327 ps.setInstalled(true, userId); 12328 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12329 } 12330 } 12331 res.name = pkgName; 12332 res.uid = newPackage.applicationInfo.uid; 12333 res.pkg = newPackage; 12334 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12335 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12336 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12337 //to update install status 12338 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12339 mSettings.writeLPr(); 12340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12341 } 12342 12343 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12344 } 12345 12346 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12347 try { 12348 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12349 installPackageLI(args, res); 12350 } finally { 12351 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12352 } 12353 } 12354 12355 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12356 final int installFlags = args.installFlags; 12357 final String installerPackageName = args.installerPackageName; 12358 final String volumeUuid = args.volumeUuid; 12359 final File tmpPackageFile = new File(args.getCodePath()); 12360 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12361 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12362 || (args.volumeUuid != null)); 12363 boolean replace = false; 12364 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12365 if (args.move != null) { 12366 // moving a complete application; perfom an initial scan on the new install location 12367 scanFlags |= SCAN_INITIAL; 12368 } 12369 // Result object to be returned 12370 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12371 12372 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12373 12374 // Retrieve PackageSettings and parse package 12375 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12376 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12377 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12378 PackageParser pp = new PackageParser(); 12379 pp.setSeparateProcesses(mSeparateProcesses); 12380 pp.setDisplayMetrics(mMetrics); 12381 12382 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12383 final PackageParser.Package pkg; 12384 try { 12385 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12386 } catch (PackageParserException e) { 12387 res.setError("Failed parse during installPackageLI", e); 12388 return; 12389 } finally { 12390 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12391 } 12392 12393 // Mark that we have an install time CPU ABI override. 12394 pkg.cpuAbiOverride = args.abiOverride; 12395 12396 String pkgName = res.name = pkg.packageName; 12397 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12398 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12399 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12400 return; 12401 } 12402 } 12403 12404 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12405 try { 12406 pp.collectCertificates(pkg, parseFlags); 12407 pp.collectManifestDigest(pkg); 12408 } catch (PackageParserException e) { 12409 res.setError("Failed collect during installPackageLI", e); 12410 return; 12411 } finally { 12412 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12413 } 12414 12415 /* If the installer passed in a manifest digest, compare it now. */ 12416 if (args.manifestDigest != null) { 12417 if (DEBUG_INSTALL) { 12418 final String parsedManifest = pkg.manifestDigest == null ? "null" 12419 : pkg.manifestDigest.toString(); 12420 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12421 + parsedManifest); 12422 } 12423 12424 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12425 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12426 return; 12427 } 12428 } else if (DEBUG_INSTALL) { 12429 final String parsedManifest = pkg.manifestDigest == null 12430 ? "null" : pkg.manifestDigest.toString(); 12431 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12432 } 12433 12434 // Get rid of all references to package scan path via parser. 12435 pp = null; 12436 String oldCodePath = null; 12437 boolean systemApp = false; 12438 synchronized (mPackages) { 12439 // Check if installing already existing package 12440 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12441 String oldName = mSettings.mRenamedPackages.get(pkgName); 12442 if (pkg.mOriginalPackages != null 12443 && pkg.mOriginalPackages.contains(oldName) 12444 && mPackages.containsKey(oldName)) { 12445 // This package is derived from an original package, 12446 // and this device has been updating from that original 12447 // name. We must continue using the original name, so 12448 // rename the new package here. 12449 pkg.setPackageName(oldName); 12450 pkgName = pkg.packageName; 12451 replace = true; 12452 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12453 + oldName + " pkgName=" + pkgName); 12454 } else if (mPackages.containsKey(pkgName)) { 12455 // This package, under its official name, already exists 12456 // on the device; we should replace it. 12457 replace = true; 12458 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12459 } 12460 12461 // Prevent apps opting out from runtime permissions 12462 if (replace) { 12463 PackageParser.Package oldPackage = mPackages.get(pkgName); 12464 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12465 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12466 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12467 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12468 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12469 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12470 + " doesn't support runtime permissions but the old" 12471 + " target SDK " + oldTargetSdk + " does."); 12472 return; 12473 } 12474 } 12475 } 12476 12477 PackageSetting ps = mSettings.mPackages.get(pkgName); 12478 if (ps != null) { 12479 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12480 12481 // Quick sanity check that we're signed correctly if updating; 12482 // we'll check this again later when scanning, but we want to 12483 // bail early here before tripping over redefined permissions. 12484 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12485 if (!checkUpgradeKeySetLP(ps, pkg)) { 12486 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12487 + pkg.packageName + " upgrade keys do not match the " 12488 + "previously installed version"); 12489 return; 12490 } 12491 } else { 12492 try { 12493 verifySignaturesLP(ps, pkg); 12494 } catch (PackageManagerException e) { 12495 res.setError(e.error, e.getMessage()); 12496 return; 12497 } 12498 } 12499 12500 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12501 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12502 systemApp = (ps.pkg.applicationInfo.flags & 12503 ApplicationInfo.FLAG_SYSTEM) != 0; 12504 } 12505 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12506 } 12507 12508 // Check whether the newly-scanned package wants to define an already-defined perm 12509 int N = pkg.permissions.size(); 12510 for (int i = N-1; i >= 0; i--) { 12511 PackageParser.Permission perm = pkg.permissions.get(i); 12512 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12513 if (bp != null) { 12514 // If the defining package is signed with our cert, it's okay. This 12515 // also includes the "updating the same package" case, of course. 12516 // "updating same package" could also involve key-rotation. 12517 final boolean sigsOk; 12518 if (bp.sourcePackage.equals(pkg.packageName) 12519 && (bp.packageSetting instanceof PackageSetting) 12520 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12521 scanFlags))) { 12522 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12523 } else { 12524 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12525 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12526 } 12527 if (!sigsOk) { 12528 // If the owning package is the system itself, we log but allow 12529 // install to proceed; we fail the install on all other permission 12530 // redefinitions. 12531 if (!bp.sourcePackage.equals("android")) { 12532 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12533 + pkg.packageName + " attempting to redeclare permission " 12534 + perm.info.name + " already owned by " + bp.sourcePackage); 12535 res.origPermission = perm.info.name; 12536 res.origPackage = bp.sourcePackage; 12537 return; 12538 } else { 12539 Slog.w(TAG, "Package " + pkg.packageName 12540 + " attempting to redeclare system permission " 12541 + perm.info.name + "; ignoring new declaration"); 12542 pkg.permissions.remove(i); 12543 } 12544 } 12545 } 12546 } 12547 12548 } 12549 12550 if (systemApp && onExternal) { 12551 // Disable updates to system apps on sdcard 12552 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12553 "Cannot install updates to system apps on sdcard"); 12554 return; 12555 } 12556 12557 if (args.move != null) { 12558 // We did an in-place move, so dex is ready to roll 12559 scanFlags |= SCAN_NO_DEX; 12560 scanFlags |= SCAN_MOVE; 12561 12562 synchronized (mPackages) { 12563 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12564 if (ps == null) { 12565 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12566 "Missing settings for moved package " + pkgName); 12567 } 12568 12569 // We moved the entire application as-is, so bring over the 12570 // previously derived ABI information. 12571 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12572 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12573 } 12574 12575 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12576 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12577 scanFlags |= SCAN_NO_DEX; 12578 12579 try { 12580 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12581 true /* extract libs */); 12582 } catch (PackageManagerException pme) { 12583 Slog.e(TAG, "Error deriving application ABI", pme); 12584 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12585 return; 12586 } 12587 12588 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12589 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12590 12591 int result = mPackageDexOptimizer 12592 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12593 false /* defer */, false /* inclDependencies */); 12594 12595 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12596 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12597 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12598 return; 12599 } 12600 } 12601 12602 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12603 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12604 return; 12605 } 12606 12607 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12608 12609 if (replace) { 12610 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12611 installerPackageName, volumeUuid, res); 12612 } else { 12613 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12614 args.user, installerPackageName, volumeUuid, res); 12615 } 12616 synchronized (mPackages) { 12617 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12618 if (ps != null) { 12619 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12620 } 12621 } 12622 } 12623 12624 private void startIntentFilterVerifications(int userId, boolean replacing, 12625 PackageParser.Package pkg) { 12626 if (mIntentFilterVerifierComponent == null) { 12627 Slog.w(TAG, "No IntentFilter verification will not be done as " 12628 + "there is no IntentFilterVerifier available!"); 12629 return; 12630 } 12631 12632 final int verifierUid = getPackageUid( 12633 mIntentFilterVerifierComponent.getPackageName(), 12634 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12635 12636 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12637 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12638 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12639 mHandler.sendMessage(msg); 12640 } 12641 12642 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12643 PackageParser.Package pkg) { 12644 int size = pkg.activities.size(); 12645 if (size == 0) { 12646 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12647 "No activity, so no need to verify any IntentFilter!"); 12648 return; 12649 } 12650 12651 final boolean hasDomainURLs = hasDomainURLs(pkg); 12652 if (!hasDomainURLs) { 12653 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12654 "No domain URLs, so no need to verify any IntentFilter!"); 12655 return; 12656 } 12657 12658 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12659 + " if any IntentFilter from the " + size 12660 + " Activities needs verification ..."); 12661 12662 int count = 0; 12663 final String packageName = pkg.packageName; 12664 12665 synchronized (mPackages) { 12666 // If this is a new install and we see that we've already run verification for this 12667 // package, we have nothing to do: it means the state was restored from backup. 12668 if (!replacing) { 12669 IntentFilterVerificationInfo ivi = 12670 mSettings.getIntentFilterVerificationLPr(packageName); 12671 if (ivi != null) { 12672 if (DEBUG_DOMAIN_VERIFICATION) { 12673 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12674 + ivi.getStatusString()); 12675 } 12676 return; 12677 } 12678 } 12679 12680 // If any filters need to be verified, then all need to be. 12681 boolean needToVerify = false; 12682 for (PackageParser.Activity a : pkg.activities) { 12683 for (ActivityIntentInfo filter : a.intents) { 12684 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12685 if (DEBUG_DOMAIN_VERIFICATION) { 12686 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12687 } 12688 needToVerify = true; 12689 break; 12690 } 12691 } 12692 } 12693 12694 if (needToVerify) { 12695 final int verificationId = mIntentFilterVerificationToken++; 12696 for (PackageParser.Activity a : pkg.activities) { 12697 for (ActivityIntentInfo filter : a.intents) { 12698 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12699 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12700 "Verification needed for IntentFilter:" + filter.toString()); 12701 mIntentFilterVerifier.addOneIntentFilterVerification( 12702 verifierUid, userId, verificationId, filter, packageName); 12703 count++; 12704 } 12705 } 12706 } 12707 } 12708 } 12709 12710 if (count > 0) { 12711 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12712 + " IntentFilter verification" + (count > 1 ? "s" : "") 12713 + " for userId:" + userId); 12714 mIntentFilterVerifier.startVerifications(userId); 12715 } else { 12716 if (DEBUG_DOMAIN_VERIFICATION) { 12717 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12718 } 12719 } 12720 } 12721 12722 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12723 final ComponentName cn = filter.activity.getComponentName(); 12724 final String packageName = cn.getPackageName(); 12725 12726 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12727 packageName); 12728 if (ivi == null) { 12729 return true; 12730 } 12731 int status = ivi.getStatus(); 12732 switch (status) { 12733 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12734 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12735 return true; 12736 12737 default: 12738 // Nothing to do 12739 return false; 12740 } 12741 } 12742 12743 private static boolean isMultiArch(PackageSetting ps) { 12744 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12745 } 12746 12747 private static boolean isMultiArch(ApplicationInfo info) { 12748 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12749 } 12750 12751 private static boolean isExternal(PackageParser.Package pkg) { 12752 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12753 } 12754 12755 private static boolean isExternal(PackageSetting ps) { 12756 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12757 } 12758 12759 private static boolean isExternal(ApplicationInfo info) { 12760 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12761 } 12762 12763 private static boolean isSystemApp(PackageParser.Package pkg) { 12764 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12765 } 12766 12767 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12768 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12769 } 12770 12771 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12772 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12773 } 12774 12775 private static boolean isSystemApp(PackageSetting ps) { 12776 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12777 } 12778 12779 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12780 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12781 } 12782 12783 private int packageFlagsToInstallFlags(PackageSetting ps) { 12784 int installFlags = 0; 12785 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12786 // This existing package was an external ASEC install when we have 12787 // the external flag without a UUID 12788 installFlags |= PackageManager.INSTALL_EXTERNAL; 12789 } 12790 if (ps.isForwardLocked()) { 12791 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12792 } 12793 return installFlags; 12794 } 12795 12796 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12797 if (isExternal(pkg)) { 12798 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12799 return mSettings.getExternalVersion(); 12800 } else { 12801 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12802 } 12803 } else { 12804 return mSettings.getInternalVersion(); 12805 } 12806 } 12807 12808 private void deleteTempPackageFiles() { 12809 final FilenameFilter filter = new FilenameFilter() { 12810 public boolean accept(File dir, String name) { 12811 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12812 } 12813 }; 12814 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12815 file.delete(); 12816 } 12817 } 12818 12819 @Override 12820 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12821 int flags) { 12822 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12823 flags); 12824 } 12825 12826 @Override 12827 public void deletePackage(final String packageName, 12828 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12829 mContext.enforceCallingOrSelfPermission( 12830 android.Manifest.permission.DELETE_PACKAGES, null); 12831 Preconditions.checkNotNull(packageName); 12832 Preconditions.checkNotNull(observer); 12833 final int uid = Binder.getCallingUid(); 12834 if (UserHandle.getUserId(uid) != userId) { 12835 mContext.enforceCallingPermission( 12836 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12837 "deletePackage for user " + userId); 12838 } 12839 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12840 try { 12841 observer.onPackageDeleted(packageName, 12842 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12843 } catch (RemoteException re) { 12844 } 12845 return; 12846 } 12847 12848 boolean uninstallBlocked = false; 12849 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12850 int[] users = sUserManager.getUserIds(); 12851 for (int i = 0; i < users.length; ++i) { 12852 if (getBlockUninstallForUser(packageName, users[i])) { 12853 uninstallBlocked = true; 12854 break; 12855 } 12856 } 12857 } else { 12858 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12859 } 12860 if (uninstallBlocked) { 12861 try { 12862 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12863 null); 12864 } catch (RemoteException re) { 12865 } 12866 return; 12867 } 12868 12869 if (DEBUG_REMOVE) { 12870 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12871 } 12872 // Queue up an async operation since the package deletion may take a little while. 12873 mHandler.post(new Runnable() { 12874 public void run() { 12875 mHandler.removeCallbacks(this); 12876 final int returnCode = deletePackageX(packageName, userId, flags); 12877 if (observer != null) { 12878 try { 12879 observer.onPackageDeleted(packageName, returnCode, null); 12880 } catch (RemoteException e) { 12881 Log.i(TAG, "Observer no longer exists."); 12882 } //end catch 12883 } //end if 12884 } //end run 12885 }); 12886 } 12887 12888 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12889 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12890 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12891 try { 12892 if (dpm != null) { 12893 if (dpm.isDeviceOwner(packageName)) { 12894 return true; 12895 } 12896 int[] users; 12897 if (userId == UserHandle.USER_ALL) { 12898 users = sUserManager.getUserIds(); 12899 } else { 12900 users = new int[]{userId}; 12901 } 12902 for (int i = 0; i < users.length; ++i) { 12903 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12904 return true; 12905 } 12906 } 12907 } 12908 } catch (RemoteException e) { 12909 } 12910 return false; 12911 } 12912 12913 /** 12914 * This method is an internal method that could be get invoked either 12915 * to delete an installed package or to clean up a failed installation. 12916 * After deleting an installed package, a broadcast is sent to notify any 12917 * listeners that the package has been installed. For cleaning up a failed 12918 * installation, the broadcast is not necessary since the package's 12919 * installation wouldn't have sent the initial broadcast either 12920 * The key steps in deleting a package are 12921 * deleting the package information in internal structures like mPackages, 12922 * deleting the packages base directories through installd 12923 * updating mSettings to reflect current status 12924 * persisting settings for later use 12925 * sending a broadcast if necessary 12926 */ 12927 private int deletePackageX(String packageName, int userId, int flags) { 12928 final PackageRemovedInfo info = new PackageRemovedInfo(); 12929 final boolean res; 12930 12931 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12932 ? UserHandle.ALL : new UserHandle(userId); 12933 12934 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12935 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12936 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12937 } 12938 12939 boolean removedForAllUsers = false; 12940 boolean systemUpdate = false; 12941 12942 // for the uninstall-updates case and restricted profiles, remember the per- 12943 // userhandle installed state 12944 int[] allUsers; 12945 boolean[] perUserInstalled; 12946 synchronized (mPackages) { 12947 PackageSetting ps = mSettings.mPackages.get(packageName); 12948 allUsers = sUserManager.getUserIds(); 12949 perUserInstalled = new boolean[allUsers.length]; 12950 for (int i = 0; i < allUsers.length; i++) { 12951 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12952 } 12953 } 12954 12955 synchronized (mInstallLock) { 12956 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12957 res = deletePackageLI(packageName, removeForUser, 12958 true, allUsers, perUserInstalled, 12959 flags | REMOVE_CHATTY, info, true); 12960 systemUpdate = info.isRemovedPackageSystemUpdate; 12961 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12962 removedForAllUsers = true; 12963 } 12964 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12965 + " removedForAllUsers=" + removedForAllUsers); 12966 } 12967 12968 if (res) { 12969 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12970 12971 // If the removed package was a system update, the old system package 12972 // was re-enabled; we need to broadcast this information 12973 if (systemUpdate) { 12974 Bundle extras = new Bundle(1); 12975 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12976 ? info.removedAppId : info.uid); 12977 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12978 12979 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12980 extras, null, null, null); 12981 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12982 extras, null, null, null); 12983 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12984 null, packageName, null, null); 12985 } 12986 } 12987 // Force a gc here. 12988 Runtime.getRuntime().gc(); 12989 // Delete the resources here after sending the broadcast to let 12990 // other processes clean up before deleting resources. 12991 if (info.args != null) { 12992 synchronized (mInstallLock) { 12993 info.args.doPostDeleteLI(true); 12994 } 12995 } 12996 12997 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12998 } 12999 13000 class PackageRemovedInfo { 13001 String removedPackage; 13002 int uid = -1; 13003 int removedAppId = -1; 13004 int[] removedUsers = null; 13005 boolean isRemovedPackageSystemUpdate = false; 13006 // Clean up resources deleted packages. 13007 InstallArgs args = null; 13008 13009 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13010 Bundle extras = new Bundle(1); 13011 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13012 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13013 if (replacing) { 13014 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13015 } 13016 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13017 if (removedPackage != null) { 13018 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13019 extras, null, null, removedUsers); 13020 if (fullRemove && !replacing) { 13021 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13022 extras, null, null, removedUsers); 13023 } 13024 } 13025 if (removedAppId >= 0) { 13026 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 13027 removedUsers); 13028 } 13029 } 13030 } 13031 13032 /* 13033 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13034 * flag is not set, the data directory is removed as well. 13035 * make sure this flag is set for partially installed apps. If not its meaningless to 13036 * delete a partially installed application. 13037 */ 13038 private void removePackageDataLI(PackageSetting ps, 13039 int[] allUserHandles, boolean[] perUserInstalled, 13040 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13041 String packageName = ps.name; 13042 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13043 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13044 // Retrieve object to delete permissions for shared user later on 13045 final PackageSetting deletedPs; 13046 // reader 13047 synchronized (mPackages) { 13048 deletedPs = mSettings.mPackages.get(packageName); 13049 if (outInfo != null) { 13050 outInfo.removedPackage = packageName; 13051 outInfo.removedUsers = deletedPs != null 13052 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13053 : null; 13054 } 13055 } 13056 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13057 removeDataDirsLI(ps.volumeUuid, packageName); 13058 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13059 } 13060 // writer 13061 synchronized (mPackages) { 13062 if (deletedPs != null) { 13063 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13064 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13065 clearDefaultBrowserIfNeeded(packageName); 13066 if (outInfo != null) { 13067 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13068 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13069 } 13070 updatePermissionsLPw(deletedPs.name, null, 0); 13071 if (deletedPs.sharedUser != null) { 13072 // Remove permissions associated with package. Since runtime 13073 // permissions are per user we have to kill the removed package 13074 // or packages running under the shared user of the removed 13075 // package if revoking the permissions requested only by the removed 13076 // package is successful and this causes a change in gids. 13077 for (int userId : UserManagerService.getInstance().getUserIds()) { 13078 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13079 userId); 13080 if (userIdToKill == UserHandle.USER_ALL 13081 || userIdToKill >= UserHandle.USER_OWNER) { 13082 // If gids changed for this user, kill all affected packages. 13083 mHandler.post(new Runnable() { 13084 @Override 13085 public void run() { 13086 // This has to happen with no lock held. 13087 killApplication(deletedPs.name, deletedPs.appId, 13088 KILL_APP_REASON_GIDS_CHANGED); 13089 } 13090 }); 13091 break; 13092 } 13093 } 13094 } 13095 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13096 } 13097 // make sure to preserve per-user disabled state if this removal was just 13098 // a downgrade of a system app to the factory package 13099 if (allUserHandles != null && perUserInstalled != null) { 13100 if (DEBUG_REMOVE) { 13101 Slog.d(TAG, "Propagating install state across downgrade"); 13102 } 13103 for (int i = 0; i < allUserHandles.length; i++) { 13104 if (DEBUG_REMOVE) { 13105 Slog.d(TAG, " user " + allUserHandles[i] 13106 + " => " + perUserInstalled[i]); 13107 } 13108 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13109 } 13110 } 13111 } 13112 // can downgrade to reader 13113 if (writeSettings) { 13114 // Save settings now 13115 mSettings.writeLPr(); 13116 } 13117 } 13118 if (outInfo != null) { 13119 // A user ID was deleted here. Go through all users and remove it 13120 // from KeyStore. 13121 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13122 } 13123 } 13124 13125 static boolean locationIsPrivileged(File path) { 13126 try { 13127 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13128 .getCanonicalPath(); 13129 return path.getCanonicalPath().startsWith(privilegedAppDir); 13130 } catch (IOException e) { 13131 Slog.e(TAG, "Unable to access code path " + path); 13132 } 13133 return false; 13134 } 13135 13136 /* 13137 * Tries to delete system package. 13138 */ 13139 private boolean deleteSystemPackageLI(PackageSetting newPs, 13140 int[] allUserHandles, boolean[] perUserInstalled, 13141 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13142 final boolean applyUserRestrictions 13143 = (allUserHandles != null) && (perUserInstalled != null); 13144 PackageSetting disabledPs = null; 13145 // Confirm if the system package has been updated 13146 // An updated system app can be deleted. This will also have to restore 13147 // the system pkg from system partition 13148 // reader 13149 synchronized (mPackages) { 13150 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13151 } 13152 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13153 + " disabledPs=" + disabledPs); 13154 if (disabledPs == null) { 13155 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13156 return false; 13157 } else if (DEBUG_REMOVE) { 13158 Slog.d(TAG, "Deleting system pkg from data partition"); 13159 } 13160 if (DEBUG_REMOVE) { 13161 if (applyUserRestrictions) { 13162 Slog.d(TAG, "Remembering install states:"); 13163 for (int i = 0; i < allUserHandles.length; i++) { 13164 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13165 } 13166 } 13167 } 13168 // Delete the updated package 13169 outInfo.isRemovedPackageSystemUpdate = true; 13170 if (disabledPs.versionCode < newPs.versionCode) { 13171 // Delete data for downgrades 13172 flags &= ~PackageManager.DELETE_KEEP_DATA; 13173 } else { 13174 // Preserve data by setting flag 13175 flags |= PackageManager.DELETE_KEEP_DATA; 13176 } 13177 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13178 allUserHandles, perUserInstalled, outInfo, writeSettings); 13179 if (!ret) { 13180 return false; 13181 } 13182 // writer 13183 synchronized (mPackages) { 13184 // Reinstate the old system package 13185 mSettings.enableSystemPackageLPw(newPs.name); 13186 // Remove any native libraries from the upgraded package. 13187 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13188 } 13189 // Install the system package 13190 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13191 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13192 if (locationIsPrivileged(disabledPs.codePath)) { 13193 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13194 } 13195 13196 final PackageParser.Package newPkg; 13197 try { 13198 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13199 } catch (PackageManagerException e) { 13200 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13201 return false; 13202 } 13203 13204 // writer 13205 synchronized (mPackages) { 13206 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13207 13208 // Propagate the permissions state as we do not want to drop on the floor 13209 // runtime permissions. The update permissions method below will take 13210 // care of removing obsolete permissions and grant install permissions. 13211 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13212 updatePermissionsLPw(newPkg.packageName, newPkg, 13213 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13214 13215 if (applyUserRestrictions) { 13216 if (DEBUG_REMOVE) { 13217 Slog.d(TAG, "Propagating install state across reinstall"); 13218 } 13219 for (int i = 0; i < allUserHandles.length; i++) { 13220 if (DEBUG_REMOVE) { 13221 Slog.d(TAG, " user " + allUserHandles[i] 13222 + " => " + perUserInstalled[i]); 13223 } 13224 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13225 13226 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13227 } 13228 // Regardless of writeSettings we need to ensure that this restriction 13229 // state propagation is persisted 13230 mSettings.writeAllUsersPackageRestrictionsLPr(); 13231 } 13232 // can downgrade to reader here 13233 if (writeSettings) { 13234 mSettings.writeLPr(); 13235 } 13236 } 13237 return true; 13238 } 13239 13240 private boolean deleteInstalledPackageLI(PackageSetting ps, 13241 boolean deleteCodeAndResources, int flags, 13242 int[] allUserHandles, boolean[] perUserInstalled, 13243 PackageRemovedInfo outInfo, boolean writeSettings) { 13244 if (outInfo != null) { 13245 outInfo.uid = ps.appId; 13246 } 13247 13248 // Delete package data from internal structures and also remove data if flag is set 13249 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13250 13251 // Delete application code and resources 13252 if (deleteCodeAndResources && (outInfo != null)) { 13253 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13254 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13255 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13256 } 13257 return true; 13258 } 13259 13260 @Override 13261 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13262 int userId) { 13263 mContext.enforceCallingOrSelfPermission( 13264 android.Manifest.permission.DELETE_PACKAGES, null); 13265 synchronized (mPackages) { 13266 PackageSetting ps = mSettings.mPackages.get(packageName); 13267 if (ps == null) { 13268 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13269 return false; 13270 } 13271 if (!ps.getInstalled(userId)) { 13272 // Can't block uninstall for an app that is not installed or enabled. 13273 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13274 return false; 13275 } 13276 ps.setBlockUninstall(blockUninstall, userId); 13277 mSettings.writePackageRestrictionsLPr(userId); 13278 } 13279 return true; 13280 } 13281 13282 @Override 13283 public boolean getBlockUninstallForUser(String packageName, int userId) { 13284 synchronized (mPackages) { 13285 PackageSetting ps = mSettings.mPackages.get(packageName); 13286 if (ps == null) { 13287 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13288 return false; 13289 } 13290 return ps.getBlockUninstall(userId); 13291 } 13292 } 13293 13294 /* 13295 * This method handles package deletion in general 13296 */ 13297 private boolean deletePackageLI(String packageName, UserHandle user, 13298 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13299 int flags, PackageRemovedInfo outInfo, 13300 boolean writeSettings) { 13301 if (packageName == null) { 13302 Slog.w(TAG, "Attempt to delete null packageName."); 13303 return false; 13304 } 13305 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13306 PackageSetting ps; 13307 boolean dataOnly = false; 13308 int removeUser = -1; 13309 int appId = -1; 13310 synchronized (mPackages) { 13311 ps = mSettings.mPackages.get(packageName); 13312 if (ps == null) { 13313 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13314 return false; 13315 } 13316 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13317 && user.getIdentifier() != UserHandle.USER_ALL) { 13318 // The caller is asking that the package only be deleted for a single 13319 // user. To do this, we just mark its uninstalled state and delete 13320 // its data. If this is a system app, we only allow this to happen if 13321 // they have set the special DELETE_SYSTEM_APP which requests different 13322 // semantics than normal for uninstalling system apps. 13323 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13324 final int userId = user.getIdentifier(); 13325 ps.setUserState(userId, 13326 COMPONENT_ENABLED_STATE_DEFAULT, 13327 false, //installed 13328 true, //stopped 13329 true, //notLaunched 13330 false, //hidden 13331 null, null, null, 13332 false, // blockUninstall 13333 ps.readUserState(userId).domainVerificationStatus, 0); 13334 if (!isSystemApp(ps)) { 13335 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13336 // Other user still have this package installed, so all 13337 // we need to do is clear this user's data and save that 13338 // it is uninstalled. 13339 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13340 removeUser = user.getIdentifier(); 13341 appId = ps.appId; 13342 scheduleWritePackageRestrictionsLocked(removeUser); 13343 } else { 13344 // We need to set it back to 'installed' so the uninstall 13345 // broadcasts will be sent correctly. 13346 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13347 ps.setInstalled(true, user.getIdentifier()); 13348 } 13349 } else { 13350 // This is a system app, so we assume that the 13351 // other users still have this package installed, so all 13352 // we need to do is clear this user's data and save that 13353 // it is uninstalled. 13354 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13355 removeUser = user.getIdentifier(); 13356 appId = ps.appId; 13357 scheduleWritePackageRestrictionsLocked(removeUser); 13358 } 13359 } 13360 } 13361 13362 if (removeUser >= 0) { 13363 // From above, we determined that we are deleting this only 13364 // for a single user. Continue the work here. 13365 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13366 if (outInfo != null) { 13367 outInfo.removedPackage = packageName; 13368 outInfo.removedAppId = appId; 13369 outInfo.removedUsers = new int[] {removeUser}; 13370 } 13371 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13372 removeKeystoreDataIfNeeded(removeUser, appId); 13373 schedulePackageCleaning(packageName, removeUser, false); 13374 synchronized (mPackages) { 13375 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13376 scheduleWritePackageRestrictionsLocked(removeUser); 13377 } 13378 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13379 } 13380 return true; 13381 } 13382 13383 if (dataOnly) { 13384 // Delete application data first 13385 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13386 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13387 return true; 13388 } 13389 13390 boolean ret = false; 13391 if (isSystemApp(ps)) { 13392 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13393 // When an updated system application is deleted we delete the existing resources as well and 13394 // fall back to existing code in system partition 13395 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13396 flags, outInfo, writeSettings); 13397 } else { 13398 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13399 // Kill application pre-emptively especially for apps on sd. 13400 killApplication(packageName, ps.appId, "uninstall pkg"); 13401 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13402 allUserHandles, perUserInstalled, 13403 outInfo, writeSettings); 13404 } 13405 13406 return ret; 13407 } 13408 13409 private final class ClearStorageConnection implements ServiceConnection { 13410 IMediaContainerService mContainerService; 13411 13412 @Override 13413 public void onServiceConnected(ComponentName name, IBinder service) { 13414 synchronized (this) { 13415 mContainerService = IMediaContainerService.Stub.asInterface(service); 13416 notifyAll(); 13417 } 13418 } 13419 13420 @Override 13421 public void onServiceDisconnected(ComponentName name) { 13422 } 13423 } 13424 13425 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13426 final boolean mounted; 13427 if (Environment.isExternalStorageEmulated()) { 13428 mounted = true; 13429 } else { 13430 final String status = Environment.getExternalStorageState(); 13431 13432 mounted = status.equals(Environment.MEDIA_MOUNTED) 13433 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13434 } 13435 13436 if (!mounted) { 13437 return; 13438 } 13439 13440 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13441 int[] users; 13442 if (userId == UserHandle.USER_ALL) { 13443 users = sUserManager.getUserIds(); 13444 } else { 13445 users = new int[] { userId }; 13446 } 13447 final ClearStorageConnection conn = new ClearStorageConnection(); 13448 if (mContext.bindServiceAsUser( 13449 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13450 try { 13451 for (int curUser : users) { 13452 long timeout = SystemClock.uptimeMillis() + 5000; 13453 synchronized (conn) { 13454 long now = SystemClock.uptimeMillis(); 13455 while (conn.mContainerService == null && now < timeout) { 13456 try { 13457 conn.wait(timeout - now); 13458 } catch (InterruptedException e) { 13459 } 13460 } 13461 } 13462 if (conn.mContainerService == null) { 13463 return; 13464 } 13465 13466 final UserEnvironment userEnv = new UserEnvironment(curUser); 13467 clearDirectory(conn.mContainerService, 13468 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13469 if (allData) { 13470 clearDirectory(conn.mContainerService, 13471 userEnv.buildExternalStorageAppDataDirs(packageName)); 13472 clearDirectory(conn.mContainerService, 13473 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13474 } 13475 } 13476 } finally { 13477 mContext.unbindService(conn); 13478 } 13479 } 13480 } 13481 13482 @Override 13483 public void clearApplicationUserData(final String packageName, 13484 final IPackageDataObserver observer, final int userId) { 13485 mContext.enforceCallingOrSelfPermission( 13486 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13487 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13488 // Queue up an async operation since the package deletion may take a little while. 13489 mHandler.post(new Runnable() { 13490 public void run() { 13491 mHandler.removeCallbacks(this); 13492 final boolean succeeded; 13493 synchronized (mInstallLock) { 13494 succeeded = clearApplicationUserDataLI(packageName, userId); 13495 } 13496 clearExternalStorageDataSync(packageName, userId, true); 13497 if (succeeded) { 13498 // invoke DeviceStorageMonitor's update method to clear any notifications 13499 DeviceStorageMonitorInternal 13500 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13501 if (dsm != null) { 13502 dsm.checkMemory(); 13503 } 13504 } 13505 if(observer != null) { 13506 try { 13507 observer.onRemoveCompleted(packageName, succeeded); 13508 } catch (RemoteException e) { 13509 Log.i(TAG, "Observer no longer exists."); 13510 } 13511 } //end if observer 13512 } //end run 13513 }); 13514 } 13515 13516 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13517 if (packageName == null) { 13518 Slog.w(TAG, "Attempt to delete null packageName."); 13519 return false; 13520 } 13521 13522 // Try finding details about the requested package 13523 PackageParser.Package pkg; 13524 synchronized (mPackages) { 13525 pkg = mPackages.get(packageName); 13526 if (pkg == null) { 13527 final PackageSetting ps = mSettings.mPackages.get(packageName); 13528 if (ps != null) { 13529 pkg = ps.pkg; 13530 } 13531 } 13532 13533 if (pkg == null) { 13534 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13535 return false; 13536 } 13537 13538 PackageSetting ps = (PackageSetting) pkg.mExtras; 13539 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13540 } 13541 13542 // Always delete data directories for package, even if we found no other 13543 // record of app. This helps users recover from UID mismatches without 13544 // resorting to a full data wipe. 13545 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13546 if (retCode < 0) { 13547 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13548 return false; 13549 } 13550 13551 final int appId = pkg.applicationInfo.uid; 13552 removeKeystoreDataIfNeeded(userId, appId); 13553 13554 // Create a native library symlink only if we have native libraries 13555 // and if the native libraries are 32 bit libraries. We do not provide 13556 // this symlink for 64 bit libraries. 13557 if (pkg.applicationInfo.primaryCpuAbi != null && 13558 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13559 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13560 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13561 nativeLibPath, userId) < 0) { 13562 Slog.w(TAG, "Failed linking native library dir"); 13563 return false; 13564 } 13565 } 13566 13567 return true; 13568 } 13569 13570 /** 13571 * Reverts user permission state changes (permissions and flags) in 13572 * all packages for a given user. 13573 * 13574 * @param userId The device user for which to do a reset. 13575 */ 13576 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13577 final int packageCount = mPackages.size(); 13578 for (int i = 0; i < packageCount; i++) { 13579 PackageParser.Package pkg = mPackages.valueAt(i); 13580 PackageSetting ps = (PackageSetting) pkg.mExtras; 13581 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13582 } 13583 } 13584 13585 /** 13586 * Reverts user permission state changes (permissions and flags). 13587 * 13588 * @param ps The package for which to reset. 13589 * @param userId The device user for which to do a reset. 13590 */ 13591 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13592 final PackageSetting ps, final int userId) { 13593 if (ps.pkg == null) { 13594 return; 13595 } 13596 13597 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13598 | FLAG_PERMISSION_USER_FIXED 13599 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13600 13601 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13602 | FLAG_PERMISSION_POLICY_FIXED; 13603 13604 boolean writeInstallPermissions = false; 13605 boolean writeRuntimePermissions = false; 13606 13607 final int permissionCount = ps.pkg.requestedPermissions.size(); 13608 for (int i = 0; i < permissionCount; i++) { 13609 String permission = ps.pkg.requestedPermissions.get(i); 13610 13611 BasePermission bp = mSettings.mPermissions.get(permission); 13612 if (bp == null) { 13613 continue; 13614 } 13615 13616 // If shared user we just reset the state to which only this app contributed. 13617 if (ps.sharedUser != null) { 13618 boolean used = false; 13619 final int packageCount = ps.sharedUser.packages.size(); 13620 for (int j = 0; j < packageCount; j++) { 13621 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13622 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13623 && pkg.pkg.requestedPermissions.contains(permission)) { 13624 used = true; 13625 break; 13626 } 13627 } 13628 if (used) { 13629 continue; 13630 } 13631 } 13632 13633 PermissionsState permissionsState = ps.getPermissionsState(); 13634 13635 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13636 13637 // Always clear the user settable flags. 13638 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13639 bp.name) != null; 13640 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13641 if (hasInstallState) { 13642 writeInstallPermissions = true; 13643 } else { 13644 writeRuntimePermissions = true; 13645 } 13646 } 13647 13648 // Below is only runtime permission handling. 13649 if (!bp.isRuntime()) { 13650 continue; 13651 } 13652 13653 // Never clobber system or policy. 13654 if ((oldFlags & policyOrSystemFlags) != 0) { 13655 continue; 13656 } 13657 13658 // If this permission was granted by default, make sure it is. 13659 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13660 if (permissionsState.grantRuntimePermission(bp, userId) 13661 != PERMISSION_OPERATION_FAILURE) { 13662 writeRuntimePermissions = true; 13663 } 13664 } else { 13665 // Otherwise, reset the permission. 13666 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13667 switch (revokeResult) { 13668 case PERMISSION_OPERATION_SUCCESS: { 13669 writeRuntimePermissions = true; 13670 } break; 13671 13672 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13673 writeRuntimePermissions = true; 13674 final int appId = ps.appId; 13675 mHandler.post(new Runnable() { 13676 @Override 13677 public void run() { 13678 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13679 } 13680 }); 13681 } break; 13682 } 13683 } 13684 } 13685 13686 // Synchronously write as we are taking permissions away. 13687 if (writeRuntimePermissions) { 13688 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13689 } 13690 13691 // Synchronously write as we are taking permissions away. 13692 if (writeInstallPermissions) { 13693 mSettings.writeLPr(); 13694 } 13695 } 13696 13697 /** 13698 * Remove entries from the keystore daemon. Will only remove it if the 13699 * {@code appId} is valid. 13700 */ 13701 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13702 if (appId < 0) { 13703 return; 13704 } 13705 13706 final KeyStore keyStore = KeyStore.getInstance(); 13707 if (keyStore != null) { 13708 if (userId == UserHandle.USER_ALL) { 13709 for (final int individual : sUserManager.getUserIds()) { 13710 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13711 } 13712 } else { 13713 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13714 } 13715 } else { 13716 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13717 } 13718 } 13719 13720 @Override 13721 public void deleteApplicationCacheFiles(final String packageName, 13722 final IPackageDataObserver observer) { 13723 mContext.enforceCallingOrSelfPermission( 13724 android.Manifest.permission.DELETE_CACHE_FILES, null); 13725 // Queue up an async operation since the package deletion may take a little while. 13726 final int userId = UserHandle.getCallingUserId(); 13727 mHandler.post(new Runnable() { 13728 public void run() { 13729 mHandler.removeCallbacks(this); 13730 final boolean succeded; 13731 synchronized (mInstallLock) { 13732 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13733 } 13734 clearExternalStorageDataSync(packageName, userId, false); 13735 if (observer != null) { 13736 try { 13737 observer.onRemoveCompleted(packageName, succeded); 13738 } catch (RemoteException e) { 13739 Log.i(TAG, "Observer no longer exists."); 13740 } 13741 } //end if observer 13742 } //end run 13743 }); 13744 } 13745 13746 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13747 if (packageName == null) { 13748 Slog.w(TAG, "Attempt to delete null packageName."); 13749 return false; 13750 } 13751 PackageParser.Package p; 13752 synchronized (mPackages) { 13753 p = mPackages.get(packageName); 13754 } 13755 if (p == null) { 13756 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13757 return false; 13758 } 13759 final ApplicationInfo applicationInfo = p.applicationInfo; 13760 if (applicationInfo == null) { 13761 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13762 return false; 13763 } 13764 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13765 if (retCode < 0) { 13766 Slog.w(TAG, "Couldn't remove cache files for package: " 13767 + packageName + " u" + userId); 13768 return false; 13769 } 13770 return true; 13771 } 13772 13773 @Override 13774 public void getPackageSizeInfo(final String packageName, int userHandle, 13775 final IPackageStatsObserver observer) { 13776 mContext.enforceCallingOrSelfPermission( 13777 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13778 if (packageName == null) { 13779 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13780 } 13781 13782 PackageStats stats = new PackageStats(packageName, userHandle); 13783 13784 /* 13785 * Queue up an async operation since the package measurement may take a 13786 * little while. 13787 */ 13788 Message msg = mHandler.obtainMessage(INIT_COPY); 13789 msg.obj = new MeasureParams(stats, observer); 13790 mHandler.sendMessage(msg); 13791 } 13792 13793 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13794 PackageStats pStats) { 13795 if (packageName == null) { 13796 Slog.w(TAG, "Attempt to get size of null packageName."); 13797 return false; 13798 } 13799 PackageParser.Package p; 13800 boolean dataOnly = false; 13801 String libDirRoot = null; 13802 String asecPath = null; 13803 PackageSetting ps = null; 13804 synchronized (mPackages) { 13805 p = mPackages.get(packageName); 13806 ps = mSettings.mPackages.get(packageName); 13807 if(p == null) { 13808 dataOnly = true; 13809 if((ps == null) || (ps.pkg == null)) { 13810 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13811 return false; 13812 } 13813 p = ps.pkg; 13814 } 13815 if (ps != null) { 13816 libDirRoot = ps.legacyNativeLibraryPathString; 13817 } 13818 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13819 final long token = Binder.clearCallingIdentity(); 13820 try { 13821 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13822 if (secureContainerId != null) { 13823 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13824 } 13825 } finally { 13826 Binder.restoreCallingIdentity(token); 13827 } 13828 } 13829 } 13830 String publicSrcDir = null; 13831 if(!dataOnly) { 13832 final ApplicationInfo applicationInfo = p.applicationInfo; 13833 if (applicationInfo == null) { 13834 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13835 return false; 13836 } 13837 if (p.isForwardLocked()) { 13838 publicSrcDir = applicationInfo.getBaseResourcePath(); 13839 } 13840 } 13841 // TODO: extend to measure size of split APKs 13842 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13843 // not just the first level. 13844 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13845 // just the primary. 13846 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13847 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13848 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13849 if (res < 0) { 13850 return false; 13851 } 13852 13853 // Fix-up for forward-locked applications in ASEC containers. 13854 if (!isExternal(p)) { 13855 pStats.codeSize += pStats.externalCodeSize; 13856 pStats.externalCodeSize = 0L; 13857 } 13858 13859 return true; 13860 } 13861 13862 13863 @Override 13864 public void addPackageToPreferred(String packageName) { 13865 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13866 } 13867 13868 @Override 13869 public void removePackageFromPreferred(String packageName) { 13870 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13871 } 13872 13873 @Override 13874 public List<PackageInfo> getPreferredPackages(int flags) { 13875 return new ArrayList<PackageInfo>(); 13876 } 13877 13878 private int getUidTargetSdkVersionLockedLPr(int uid) { 13879 Object obj = mSettings.getUserIdLPr(uid); 13880 if (obj instanceof SharedUserSetting) { 13881 final SharedUserSetting sus = (SharedUserSetting) obj; 13882 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13883 final Iterator<PackageSetting> it = sus.packages.iterator(); 13884 while (it.hasNext()) { 13885 final PackageSetting ps = it.next(); 13886 if (ps.pkg != null) { 13887 int v = ps.pkg.applicationInfo.targetSdkVersion; 13888 if (v < vers) vers = v; 13889 } 13890 } 13891 return vers; 13892 } else if (obj instanceof PackageSetting) { 13893 final PackageSetting ps = (PackageSetting) obj; 13894 if (ps.pkg != null) { 13895 return ps.pkg.applicationInfo.targetSdkVersion; 13896 } 13897 } 13898 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13899 } 13900 13901 @Override 13902 public void addPreferredActivity(IntentFilter filter, int match, 13903 ComponentName[] set, ComponentName activity, int userId) { 13904 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13905 "Adding preferred"); 13906 } 13907 13908 private void addPreferredActivityInternal(IntentFilter filter, int match, 13909 ComponentName[] set, ComponentName activity, boolean always, int userId, 13910 String opname) { 13911 // writer 13912 int callingUid = Binder.getCallingUid(); 13913 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13914 if (filter.countActions() == 0) { 13915 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13916 return; 13917 } 13918 synchronized (mPackages) { 13919 if (mContext.checkCallingOrSelfPermission( 13920 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13921 != PackageManager.PERMISSION_GRANTED) { 13922 if (getUidTargetSdkVersionLockedLPr(callingUid) 13923 < Build.VERSION_CODES.FROYO) { 13924 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13925 + callingUid); 13926 return; 13927 } 13928 mContext.enforceCallingOrSelfPermission( 13929 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13930 } 13931 13932 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13933 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13934 + userId + ":"); 13935 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13936 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13937 scheduleWritePackageRestrictionsLocked(userId); 13938 } 13939 } 13940 13941 @Override 13942 public void replacePreferredActivity(IntentFilter filter, int match, 13943 ComponentName[] set, ComponentName activity, int userId) { 13944 if (filter.countActions() != 1) { 13945 throw new IllegalArgumentException( 13946 "replacePreferredActivity expects filter to have only 1 action."); 13947 } 13948 if (filter.countDataAuthorities() != 0 13949 || filter.countDataPaths() != 0 13950 || filter.countDataSchemes() > 1 13951 || filter.countDataTypes() != 0) { 13952 throw new IllegalArgumentException( 13953 "replacePreferredActivity expects filter to have no data authorities, " + 13954 "paths, or types; and at most one scheme."); 13955 } 13956 13957 final int callingUid = Binder.getCallingUid(); 13958 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13959 synchronized (mPackages) { 13960 if (mContext.checkCallingOrSelfPermission( 13961 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13962 != PackageManager.PERMISSION_GRANTED) { 13963 if (getUidTargetSdkVersionLockedLPr(callingUid) 13964 < Build.VERSION_CODES.FROYO) { 13965 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13966 + Binder.getCallingUid()); 13967 return; 13968 } 13969 mContext.enforceCallingOrSelfPermission( 13970 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13971 } 13972 13973 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13974 if (pir != null) { 13975 // Get all of the existing entries that exactly match this filter. 13976 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13977 if (existing != null && existing.size() == 1) { 13978 PreferredActivity cur = existing.get(0); 13979 if (DEBUG_PREFERRED) { 13980 Slog.i(TAG, "Checking replace of preferred:"); 13981 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13982 if (!cur.mPref.mAlways) { 13983 Slog.i(TAG, " -- CUR; not mAlways!"); 13984 } else { 13985 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13986 Slog.i(TAG, " -- CUR: mSet=" 13987 + Arrays.toString(cur.mPref.mSetComponents)); 13988 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13989 Slog.i(TAG, " -- NEW: mMatch=" 13990 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13991 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13992 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13993 } 13994 } 13995 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13996 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13997 && cur.mPref.sameSet(set)) { 13998 // Setting the preferred activity to what it happens to be already 13999 if (DEBUG_PREFERRED) { 14000 Slog.i(TAG, "Replacing with same preferred activity " 14001 + cur.mPref.mShortComponent + " for user " 14002 + userId + ":"); 14003 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14004 } 14005 return; 14006 } 14007 } 14008 14009 if (existing != null) { 14010 if (DEBUG_PREFERRED) { 14011 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14012 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14013 } 14014 for (int i = 0; i < existing.size(); i++) { 14015 PreferredActivity pa = existing.get(i); 14016 if (DEBUG_PREFERRED) { 14017 Slog.i(TAG, "Removing existing preferred activity " 14018 + pa.mPref.mComponent + ":"); 14019 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14020 } 14021 pir.removeFilter(pa); 14022 } 14023 } 14024 } 14025 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14026 "Replacing preferred"); 14027 } 14028 } 14029 14030 @Override 14031 public void clearPackagePreferredActivities(String packageName) { 14032 final int uid = Binder.getCallingUid(); 14033 // writer 14034 synchronized (mPackages) { 14035 PackageParser.Package pkg = mPackages.get(packageName); 14036 if (pkg == null || pkg.applicationInfo.uid != uid) { 14037 if (mContext.checkCallingOrSelfPermission( 14038 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14039 != PackageManager.PERMISSION_GRANTED) { 14040 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14041 < Build.VERSION_CODES.FROYO) { 14042 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14043 + Binder.getCallingUid()); 14044 return; 14045 } 14046 mContext.enforceCallingOrSelfPermission( 14047 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14048 } 14049 } 14050 14051 int user = UserHandle.getCallingUserId(); 14052 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14053 scheduleWritePackageRestrictionsLocked(user); 14054 } 14055 } 14056 } 14057 14058 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14059 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14060 ArrayList<PreferredActivity> removed = null; 14061 boolean changed = false; 14062 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14063 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14064 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14065 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14066 continue; 14067 } 14068 Iterator<PreferredActivity> it = pir.filterIterator(); 14069 while (it.hasNext()) { 14070 PreferredActivity pa = it.next(); 14071 // Mark entry for removal only if it matches the package name 14072 // and the entry is of type "always". 14073 if (packageName == null || 14074 (pa.mPref.mComponent.getPackageName().equals(packageName) 14075 && pa.mPref.mAlways)) { 14076 if (removed == null) { 14077 removed = new ArrayList<PreferredActivity>(); 14078 } 14079 removed.add(pa); 14080 } 14081 } 14082 if (removed != null) { 14083 for (int j=0; j<removed.size(); j++) { 14084 PreferredActivity pa = removed.get(j); 14085 pir.removeFilter(pa); 14086 } 14087 changed = true; 14088 } 14089 } 14090 return changed; 14091 } 14092 14093 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14094 private void clearIntentFilterVerificationsLPw(int userId) { 14095 final int packageCount = mPackages.size(); 14096 for (int i = 0; i < packageCount; i++) { 14097 PackageParser.Package pkg = mPackages.valueAt(i); 14098 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14099 } 14100 } 14101 14102 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14103 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14104 if (userId == UserHandle.USER_ALL) { 14105 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14106 sUserManager.getUserIds())) { 14107 for (int oneUserId : sUserManager.getUserIds()) { 14108 scheduleWritePackageRestrictionsLocked(oneUserId); 14109 } 14110 } 14111 } else { 14112 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14113 scheduleWritePackageRestrictionsLocked(userId); 14114 } 14115 } 14116 } 14117 14118 void clearDefaultBrowserIfNeeded(String packageName) { 14119 for (int oneUserId : sUserManager.getUserIds()) { 14120 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14121 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14122 if (packageName.equals(defaultBrowserPackageName)) { 14123 setDefaultBrowserPackageName(null, oneUserId); 14124 } 14125 } 14126 } 14127 14128 @Override 14129 public void resetApplicationPreferences(int userId) { 14130 mContext.enforceCallingOrSelfPermission( 14131 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14132 // writer 14133 synchronized (mPackages) { 14134 final long identity = Binder.clearCallingIdentity(); 14135 try { 14136 clearPackagePreferredActivitiesLPw(null, userId); 14137 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14138 // TODO: We have to reset the default SMS and Phone. This requires 14139 // significant refactoring to keep all default apps in the package 14140 // manager (cleaner but more work) or have the services provide 14141 // callbacks to the package manager to request a default app reset. 14142 applyFactoryDefaultBrowserLPw(userId); 14143 clearIntentFilterVerificationsLPw(userId); 14144 primeDomainVerificationsLPw(userId); 14145 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14146 scheduleWritePackageRestrictionsLocked(userId); 14147 } finally { 14148 Binder.restoreCallingIdentity(identity); 14149 } 14150 } 14151 } 14152 14153 @Override 14154 public int getPreferredActivities(List<IntentFilter> outFilters, 14155 List<ComponentName> outActivities, String packageName) { 14156 14157 int num = 0; 14158 final int userId = UserHandle.getCallingUserId(); 14159 // reader 14160 synchronized (mPackages) { 14161 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14162 if (pir != null) { 14163 final Iterator<PreferredActivity> it = pir.filterIterator(); 14164 while (it.hasNext()) { 14165 final PreferredActivity pa = it.next(); 14166 if (packageName == null 14167 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14168 && pa.mPref.mAlways)) { 14169 if (outFilters != null) { 14170 outFilters.add(new IntentFilter(pa)); 14171 } 14172 if (outActivities != null) { 14173 outActivities.add(pa.mPref.mComponent); 14174 } 14175 } 14176 } 14177 } 14178 } 14179 14180 return num; 14181 } 14182 14183 @Override 14184 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14185 int userId) { 14186 int callingUid = Binder.getCallingUid(); 14187 if (callingUid != Process.SYSTEM_UID) { 14188 throw new SecurityException( 14189 "addPersistentPreferredActivity can only be run by the system"); 14190 } 14191 if (filter.countActions() == 0) { 14192 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14193 return; 14194 } 14195 synchronized (mPackages) { 14196 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14197 " :"); 14198 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14199 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14200 new PersistentPreferredActivity(filter, activity)); 14201 scheduleWritePackageRestrictionsLocked(userId); 14202 } 14203 } 14204 14205 @Override 14206 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14207 int callingUid = Binder.getCallingUid(); 14208 if (callingUid != Process.SYSTEM_UID) { 14209 throw new SecurityException( 14210 "clearPackagePersistentPreferredActivities can only be run by the system"); 14211 } 14212 ArrayList<PersistentPreferredActivity> removed = null; 14213 boolean changed = false; 14214 synchronized (mPackages) { 14215 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14216 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14217 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14218 .valueAt(i); 14219 if (userId != thisUserId) { 14220 continue; 14221 } 14222 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14223 while (it.hasNext()) { 14224 PersistentPreferredActivity ppa = it.next(); 14225 // Mark entry for removal only if it matches the package name. 14226 if (ppa.mComponent.getPackageName().equals(packageName)) { 14227 if (removed == null) { 14228 removed = new ArrayList<PersistentPreferredActivity>(); 14229 } 14230 removed.add(ppa); 14231 } 14232 } 14233 if (removed != null) { 14234 for (int j=0; j<removed.size(); j++) { 14235 PersistentPreferredActivity ppa = removed.get(j); 14236 ppir.removeFilter(ppa); 14237 } 14238 changed = true; 14239 } 14240 } 14241 14242 if (changed) { 14243 scheduleWritePackageRestrictionsLocked(userId); 14244 } 14245 } 14246 } 14247 14248 /** 14249 * Common machinery for picking apart a restored XML blob and passing 14250 * it to a caller-supplied functor to be applied to the running system. 14251 */ 14252 private void restoreFromXml(XmlPullParser parser, int userId, 14253 String expectedStartTag, BlobXmlRestorer functor) 14254 throws IOException, XmlPullParserException { 14255 int type; 14256 while ((type = parser.next()) != XmlPullParser.START_TAG 14257 && type != XmlPullParser.END_DOCUMENT) { 14258 } 14259 if (type != XmlPullParser.START_TAG) { 14260 // oops didn't find a start tag?! 14261 if (DEBUG_BACKUP) { 14262 Slog.e(TAG, "Didn't find start tag during restore"); 14263 } 14264 return; 14265 } 14266 14267 // this is supposed to be TAG_PREFERRED_BACKUP 14268 if (!expectedStartTag.equals(parser.getName())) { 14269 if (DEBUG_BACKUP) { 14270 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14271 } 14272 return; 14273 } 14274 14275 // skip interfering stuff, then we're aligned with the backing implementation 14276 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14277 functor.apply(parser, userId); 14278 } 14279 14280 private interface BlobXmlRestorer { 14281 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14282 } 14283 14284 /** 14285 * Non-Binder method, support for the backup/restore mechanism: write the 14286 * full set of preferred activities in its canonical XML format. Returns the 14287 * XML output as a byte array, or null if there is none. 14288 */ 14289 @Override 14290 public byte[] getPreferredActivityBackup(int userId) { 14291 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14292 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14293 } 14294 14295 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14296 try { 14297 final XmlSerializer serializer = new FastXmlSerializer(); 14298 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14299 serializer.startDocument(null, true); 14300 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14301 14302 synchronized (mPackages) { 14303 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14304 } 14305 14306 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14307 serializer.endDocument(); 14308 serializer.flush(); 14309 } catch (Exception e) { 14310 if (DEBUG_BACKUP) { 14311 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14312 } 14313 return null; 14314 } 14315 14316 return dataStream.toByteArray(); 14317 } 14318 14319 @Override 14320 public void restorePreferredActivities(byte[] backup, int userId) { 14321 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14322 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14323 } 14324 14325 try { 14326 final XmlPullParser parser = Xml.newPullParser(); 14327 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14328 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14329 new BlobXmlRestorer() { 14330 @Override 14331 public void apply(XmlPullParser parser, int userId) 14332 throws XmlPullParserException, IOException { 14333 synchronized (mPackages) { 14334 mSettings.readPreferredActivitiesLPw(parser, userId); 14335 } 14336 } 14337 } ); 14338 } catch (Exception e) { 14339 if (DEBUG_BACKUP) { 14340 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14341 } 14342 } 14343 } 14344 14345 /** 14346 * Non-Binder method, support for the backup/restore mechanism: write the 14347 * default browser (etc) settings in its canonical XML format. Returns the default 14348 * browser XML representation as a byte array, or null if there is none. 14349 */ 14350 @Override 14351 public byte[] getDefaultAppsBackup(int userId) { 14352 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14353 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14354 } 14355 14356 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14357 try { 14358 final XmlSerializer serializer = new FastXmlSerializer(); 14359 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14360 serializer.startDocument(null, true); 14361 serializer.startTag(null, TAG_DEFAULT_APPS); 14362 14363 synchronized (mPackages) { 14364 mSettings.writeDefaultAppsLPr(serializer, userId); 14365 } 14366 14367 serializer.endTag(null, TAG_DEFAULT_APPS); 14368 serializer.endDocument(); 14369 serializer.flush(); 14370 } catch (Exception e) { 14371 if (DEBUG_BACKUP) { 14372 Slog.e(TAG, "Unable to write default apps for backup", e); 14373 } 14374 return null; 14375 } 14376 14377 return dataStream.toByteArray(); 14378 } 14379 14380 @Override 14381 public void restoreDefaultApps(byte[] backup, int userId) { 14382 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14383 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14384 } 14385 14386 try { 14387 final XmlPullParser parser = Xml.newPullParser(); 14388 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14389 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14390 new BlobXmlRestorer() { 14391 @Override 14392 public void apply(XmlPullParser parser, int userId) 14393 throws XmlPullParserException, IOException { 14394 synchronized (mPackages) { 14395 mSettings.readDefaultAppsLPw(parser, userId); 14396 } 14397 } 14398 } ); 14399 } catch (Exception e) { 14400 if (DEBUG_BACKUP) { 14401 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14402 } 14403 } 14404 } 14405 14406 @Override 14407 public byte[] getIntentFilterVerificationBackup(int userId) { 14408 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14409 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14410 } 14411 14412 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14413 try { 14414 final XmlSerializer serializer = new FastXmlSerializer(); 14415 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14416 serializer.startDocument(null, true); 14417 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14418 14419 synchronized (mPackages) { 14420 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14421 } 14422 14423 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14424 serializer.endDocument(); 14425 serializer.flush(); 14426 } catch (Exception e) { 14427 if (DEBUG_BACKUP) { 14428 Slog.e(TAG, "Unable to write default apps for backup", e); 14429 } 14430 return null; 14431 } 14432 14433 return dataStream.toByteArray(); 14434 } 14435 14436 @Override 14437 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14438 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14439 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14440 } 14441 14442 try { 14443 final XmlPullParser parser = Xml.newPullParser(); 14444 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14445 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14446 new BlobXmlRestorer() { 14447 @Override 14448 public void apply(XmlPullParser parser, int userId) 14449 throws XmlPullParserException, IOException { 14450 synchronized (mPackages) { 14451 mSettings.readAllDomainVerificationsLPr(parser, userId); 14452 mSettings.writeLPr(); 14453 } 14454 } 14455 } ); 14456 } catch (Exception e) { 14457 if (DEBUG_BACKUP) { 14458 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14459 } 14460 } 14461 } 14462 14463 @Override 14464 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14465 int sourceUserId, int targetUserId, int flags) { 14466 mContext.enforceCallingOrSelfPermission( 14467 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14468 int callingUid = Binder.getCallingUid(); 14469 enforceOwnerRights(ownerPackage, callingUid); 14470 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14471 if (intentFilter.countActions() == 0) { 14472 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14473 return; 14474 } 14475 synchronized (mPackages) { 14476 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14477 ownerPackage, targetUserId, flags); 14478 CrossProfileIntentResolver resolver = 14479 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14480 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14481 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14482 if (existing != null) { 14483 int size = existing.size(); 14484 for (int i = 0; i < size; i++) { 14485 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14486 return; 14487 } 14488 } 14489 } 14490 resolver.addFilter(newFilter); 14491 scheduleWritePackageRestrictionsLocked(sourceUserId); 14492 } 14493 } 14494 14495 @Override 14496 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14497 mContext.enforceCallingOrSelfPermission( 14498 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14499 int callingUid = Binder.getCallingUid(); 14500 enforceOwnerRights(ownerPackage, callingUid); 14501 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14502 synchronized (mPackages) { 14503 CrossProfileIntentResolver resolver = 14504 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14505 ArraySet<CrossProfileIntentFilter> set = 14506 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14507 for (CrossProfileIntentFilter filter : set) { 14508 if (filter.getOwnerPackage().equals(ownerPackage)) { 14509 resolver.removeFilter(filter); 14510 } 14511 } 14512 scheduleWritePackageRestrictionsLocked(sourceUserId); 14513 } 14514 } 14515 14516 // Enforcing that callingUid is owning pkg on userId 14517 private void enforceOwnerRights(String pkg, int callingUid) { 14518 // The system owns everything. 14519 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14520 return; 14521 } 14522 int callingUserId = UserHandle.getUserId(callingUid); 14523 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14524 if (pi == null) { 14525 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14526 + callingUserId); 14527 } 14528 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14529 throw new SecurityException("Calling uid " + callingUid 14530 + " does not own package " + pkg); 14531 } 14532 } 14533 14534 @Override 14535 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14536 Intent intent = new Intent(Intent.ACTION_MAIN); 14537 intent.addCategory(Intent.CATEGORY_HOME); 14538 14539 final int callingUserId = UserHandle.getCallingUserId(); 14540 List<ResolveInfo> list = queryIntentActivities(intent, null, 14541 PackageManager.GET_META_DATA, callingUserId); 14542 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14543 true, false, false, callingUserId); 14544 14545 allHomeCandidates.clear(); 14546 if (list != null) { 14547 for (ResolveInfo ri : list) { 14548 allHomeCandidates.add(ri); 14549 } 14550 } 14551 return (preferred == null || preferred.activityInfo == null) 14552 ? null 14553 : new ComponentName(preferred.activityInfo.packageName, 14554 preferred.activityInfo.name); 14555 } 14556 14557 @Override 14558 public void setApplicationEnabledSetting(String appPackageName, 14559 int newState, int flags, int userId, String callingPackage) { 14560 if (!sUserManager.exists(userId)) return; 14561 if (callingPackage == null) { 14562 callingPackage = Integer.toString(Binder.getCallingUid()); 14563 } 14564 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14565 } 14566 14567 @Override 14568 public void setComponentEnabledSetting(ComponentName componentName, 14569 int newState, int flags, int userId) { 14570 if (!sUserManager.exists(userId)) return; 14571 setEnabledSetting(componentName.getPackageName(), 14572 componentName.getClassName(), newState, flags, userId, null); 14573 } 14574 14575 private void setEnabledSetting(final String packageName, String className, int newState, 14576 final int flags, int userId, String callingPackage) { 14577 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14578 || newState == COMPONENT_ENABLED_STATE_ENABLED 14579 || newState == COMPONENT_ENABLED_STATE_DISABLED 14580 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14581 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14582 throw new IllegalArgumentException("Invalid new component state: " 14583 + newState); 14584 } 14585 PackageSetting pkgSetting; 14586 final int uid = Binder.getCallingUid(); 14587 final int permission = mContext.checkCallingOrSelfPermission( 14588 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14589 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14590 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14591 boolean sendNow = false; 14592 boolean isApp = (className == null); 14593 String componentName = isApp ? packageName : className; 14594 int packageUid = -1; 14595 ArrayList<String> components; 14596 14597 // writer 14598 synchronized (mPackages) { 14599 pkgSetting = mSettings.mPackages.get(packageName); 14600 if (pkgSetting == null) { 14601 if (className == null) { 14602 throw new IllegalArgumentException( 14603 "Unknown package: " + packageName); 14604 } 14605 throw new IllegalArgumentException( 14606 "Unknown component: " + packageName 14607 + "/" + className); 14608 } 14609 // Allow root and verify that userId is not being specified by a different user 14610 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14611 throw new SecurityException( 14612 "Permission Denial: attempt to change component state from pid=" 14613 + Binder.getCallingPid() 14614 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14615 } 14616 if (className == null) { 14617 // We're dealing with an application/package level state change 14618 if (pkgSetting.getEnabled(userId) == newState) { 14619 // Nothing to do 14620 return; 14621 } 14622 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14623 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14624 // Don't care about who enables an app. 14625 callingPackage = null; 14626 } 14627 pkgSetting.setEnabled(newState, userId, callingPackage); 14628 // pkgSetting.pkg.mSetEnabled = newState; 14629 } else { 14630 // We're dealing with a component level state change 14631 // First, verify that this is a valid class name. 14632 PackageParser.Package pkg = pkgSetting.pkg; 14633 if (pkg == null || !pkg.hasComponentClassName(className)) { 14634 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14635 throw new IllegalArgumentException("Component class " + className 14636 + " does not exist in " + packageName); 14637 } else { 14638 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14639 + className + " does not exist in " + packageName); 14640 } 14641 } 14642 switch (newState) { 14643 case COMPONENT_ENABLED_STATE_ENABLED: 14644 if (!pkgSetting.enableComponentLPw(className, userId)) { 14645 return; 14646 } 14647 break; 14648 case COMPONENT_ENABLED_STATE_DISABLED: 14649 if (!pkgSetting.disableComponentLPw(className, userId)) { 14650 return; 14651 } 14652 break; 14653 case COMPONENT_ENABLED_STATE_DEFAULT: 14654 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14655 return; 14656 } 14657 break; 14658 default: 14659 Slog.e(TAG, "Invalid new component state: " + newState); 14660 return; 14661 } 14662 } 14663 scheduleWritePackageRestrictionsLocked(userId); 14664 components = mPendingBroadcasts.get(userId, packageName); 14665 final boolean newPackage = components == null; 14666 if (newPackage) { 14667 components = new ArrayList<String>(); 14668 } 14669 if (!components.contains(componentName)) { 14670 components.add(componentName); 14671 } 14672 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14673 sendNow = true; 14674 // Purge entry from pending broadcast list if another one exists already 14675 // since we are sending one right away. 14676 mPendingBroadcasts.remove(userId, packageName); 14677 } else { 14678 if (newPackage) { 14679 mPendingBroadcasts.put(userId, packageName, components); 14680 } 14681 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14682 // Schedule a message 14683 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14684 } 14685 } 14686 } 14687 14688 long callingId = Binder.clearCallingIdentity(); 14689 try { 14690 if (sendNow) { 14691 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14692 sendPackageChangedBroadcast(packageName, 14693 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14694 } 14695 } finally { 14696 Binder.restoreCallingIdentity(callingId); 14697 } 14698 } 14699 14700 private void sendPackageChangedBroadcast(String packageName, 14701 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14702 if (DEBUG_INSTALL) 14703 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14704 + componentNames); 14705 Bundle extras = new Bundle(4); 14706 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14707 String nameList[] = new String[componentNames.size()]; 14708 componentNames.toArray(nameList); 14709 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14710 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14711 extras.putInt(Intent.EXTRA_UID, packageUid); 14712 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14713 new int[] {UserHandle.getUserId(packageUid)}); 14714 } 14715 14716 @Override 14717 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14718 if (!sUserManager.exists(userId)) return; 14719 final int uid = Binder.getCallingUid(); 14720 final int permission = mContext.checkCallingOrSelfPermission( 14721 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14722 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14723 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14724 // writer 14725 synchronized (mPackages) { 14726 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14727 allowedByPermission, uid, userId)) { 14728 scheduleWritePackageRestrictionsLocked(userId); 14729 } 14730 } 14731 } 14732 14733 @Override 14734 public String getInstallerPackageName(String packageName) { 14735 // reader 14736 synchronized (mPackages) { 14737 return mSettings.getInstallerPackageNameLPr(packageName); 14738 } 14739 } 14740 14741 @Override 14742 public int getApplicationEnabledSetting(String packageName, int userId) { 14743 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14744 int uid = Binder.getCallingUid(); 14745 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14746 // reader 14747 synchronized (mPackages) { 14748 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14749 } 14750 } 14751 14752 @Override 14753 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14754 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14755 int uid = Binder.getCallingUid(); 14756 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14757 // reader 14758 synchronized (mPackages) { 14759 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14760 } 14761 } 14762 14763 @Override 14764 public void enterSafeMode() { 14765 enforceSystemOrRoot("Only the system can request entering safe mode"); 14766 14767 if (!mSystemReady) { 14768 mSafeMode = true; 14769 } 14770 } 14771 14772 @Override 14773 public void systemReady() { 14774 mSystemReady = true; 14775 14776 // Read the compatibilty setting when the system is ready. 14777 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14778 mContext.getContentResolver(), 14779 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14780 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14781 if (DEBUG_SETTINGS) { 14782 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14783 } 14784 14785 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14786 14787 synchronized (mPackages) { 14788 // Verify that all of the preferred activity components actually 14789 // exist. It is possible for applications to be updated and at 14790 // that point remove a previously declared activity component that 14791 // had been set as a preferred activity. We try to clean this up 14792 // the next time we encounter that preferred activity, but it is 14793 // possible for the user flow to never be able to return to that 14794 // situation so here we do a sanity check to make sure we haven't 14795 // left any junk around. 14796 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14797 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14798 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14799 removed.clear(); 14800 for (PreferredActivity pa : pir.filterSet()) { 14801 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14802 removed.add(pa); 14803 } 14804 } 14805 if (removed.size() > 0) { 14806 for (int r=0; r<removed.size(); r++) { 14807 PreferredActivity pa = removed.get(r); 14808 Slog.w(TAG, "Removing dangling preferred activity: " 14809 + pa.mPref.mComponent); 14810 pir.removeFilter(pa); 14811 } 14812 mSettings.writePackageRestrictionsLPr( 14813 mSettings.mPreferredActivities.keyAt(i)); 14814 } 14815 } 14816 14817 for (int userId : UserManagerService.getInstance().getUserIds()) { 14818 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14819 grantPermissionsUserIds = ArrayUtils.appendInt( 14820 grantPermissionsUserIds, userId); 14821 } 14822 } 14823 } 14824 sUserManager.systemReady(); 14825 14826 // If we upgraded grant all default permissions before kicking off. 14827 for (int userId : grantPermissionsUserIds) { 14828 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14829 } 14830 14831 // Kick off any messages waiting for system ready 14832 if (mPostSystemReadyMessages != null) { 14833 for (Message msg : mPostSystemReadyMessages) { 14834 msg.sendToTarget(); 14835 } 14836 mPostSystemReadyMessages = null; 14837 } 14838 14839 // Watch for external volumes that come and go over time 14840 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14841 storage.registerListener(mStorageListener); 14842 14843 mInstallerService.systemReady(); 14844 mPackageDexOptimizer.systemReady(); 14845 14846 MountServiceInternal mountServiceInternal = LocalServices.getService( 14847 MountServiceInternal.class); 14848 mountServiceInternal.addExternalStoragePolicy( 14849 new MountServiceInternal.ExternalStorageMountPolicy() { 14850 @Override 14851 public int getMountMode(int uid, String packageName) { 14852 if (Process.isIsolated(uid)) { 14853 return Zygote.MOUNT_EXTERNAL_NONE; 14854 } 14855 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14856 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14857 } 14858 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14859 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14860 } 14861 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14862 return Zygote.MOUNT_EXTERNAL_READ; 14863 } 14864 return Zygote.MOUNT_EXTERNAL_WRITE; 14865 } 14866 14867 @Override 14868 public boolean hasExternalStorage(int uid, String packageName) { 14869 return true; 14870 } 14871 }); 14872 } 14873 14874 @Override 14875 public boolean isSafeMode() { 14876 return mSafeMode; 14877 } 14878 14879 @Override 14880 public boolean hasSystemUidErrors() { 14881 return mHasSystemUidErrors; 14882 } 14883 14884 static String arrayToString(int[] array) { 14885 StringBuffer buf = new StringBuffer(128); 14886 buf.append('['); 14887 if (array != null) { 14888 for (int i=0; i<array.length; i++) { 14889 if (i > 0) buf.append(", "); 14890 buf.append(array[i]); 14891 } 14892 } 14893 buf.append(']'); 14894 return buf.toString(); 14895 } 14896 14897 static class DumpState { 14898 public static final int DUMP_LIBS = 1 << 0; 14899 public static final int DUMP_FEATURES = 1 << 1; 14900 public static final int DUMP_RESOLVERS = 1 << 2; 14901 public static final int DUMP_PERMISSIONS = 1 << 3; 14902 public static final int DUMP_PACKAGES = 1 << 4; 14903 public static final int DUMP_SHARED_USERS = 1 << 5; 14904 public static final int DUMP_MESSAGES = 1 << 6; 14905 public static final int DUMP_PROVIDERS = 1 << 7; 14906 public static final int DUMP_VERIFIERS = 1 << 8; 14907 public static final int DUMP_PREFERRED = 1 << 9; 14908 public static final int DUMP_PREFERRED_XML = 1 << 10; 14909 public static final int DUMP_KEYSETS = 1 << 11; 14910 public static final int DUMP_VERSION = 1 << 12; 14911 public static final int DUMP_INSTALLS = 1 << 13; 14912 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14913 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14914 14915 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14916 14917 private int mTypes; 14918 14919 private int mOptions; 14920 14921 private boolean mTitlePrinted; 14922 14923 private SharedUserSetting mSharedUser; 14924 14925 public boolean isDumping(int type) { 14926 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14927 return true; 14928 } 14929 14930 return (mTypes & type) != 0; 14931 } 14932 14933 public void setDump(int type) { 14934 mTypes |= type; 14935 } 14936 14937 public boolean isOptionEnabled(int option) { 14938 return (mOptions & option) != 0; 14939 } 14940 14941 public void setOptionEnabled(int option) { 14942 mOptions |= option; 14943 } 14944 14945 public boolean onTitlePrinted() { 14946 final boolean printed = mTitlePrinted; 14947 mTitlePrinted = true; 14948 return printed; 14949 } 14950 14951 public boolean getTitlePrinted() { 14952 return mTitlePrinted; 14953 } 14954 14955 public void setTitlePrinted(boolean enabled) { 14956 mTitlePrinted = enabled; 14957 } 14958 14959 public SharedUserSetting getSharedUser() { 14960 return mSharedUser; 14961 } 14962 14963 public void setSharedUser(SharedUserSetting user) { 14964 mSharedUser = user; 14965 } 14966 } 14967 14968 @Override 14969 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14970 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14971 != PackageManager.PERMISSION_GRANTED) { 14972 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14973 + Binder.getCallingPid() 14974 + ", uid=" + Binder.getCallingUid() 14975 + " without permission " 14976 + android.Manifest.permission.DUMP); 14977 return; 14978 } 14979 14980 DumpState dumpState = new DumpState(); 14981 boolean fullPreferred = false; 14982 boolean checkin = false; 14983 14984 String packageName = null; 14985 ArraySet<String> permissionNames = null; 14986 14987 int opti = 0; 14988 while (opti < args.length) { 14989 String opt = args[opti]; 14990 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14991 break; 14992 } 14993 opti++; 14994 14995 if ("-a".equals(opt)) { 14996 // Right now we only know how to print all. 14997 } else if ("-h".equals(opt)) { 14998 pw.println("Package manager dump options:"); 14999 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15000 pw.println(" --checkin: dump for a checkin"); 15001 pw.println(" -f: print details of intent filters"); 15002 pw.println(" -h: print this help"); 15003 pw.println(" cmd may be one of:"); 15004 pw.println(" l[ibraries]: list known shared libraries"); 15005 pw.println(" f[ibraries]: list device features"); 15006 pw.println(" k[eysets]: print known keysets"); 15007 pw.println(" r[esolvers]: dump intent resolvers"); 15008 pw.println(" perm[issions]: dump permissions"); 15009 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15010 pw.println(" pref[erred]: print preferred package settings"); 15011 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15012 pw.println(" prov[iders]: dump content providers"); 15013 pw.println(" p[ackages]: dump installed packages"); 15014 pw.println(" s[hared-users]: dump shared user IDs"); 15015 pw.println(" m[essages]: print collected runtime messages"); 15016 pw.println(" v[erifiers]: print package verifier info"); 15017 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15018 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15019 pw.println(" version: print database version info"); 15020 pw.println(" write: write current settings now"); 15021 pw.println(" installs: details about install sessions"); 15022 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15023 pw.println(" <package.name>: info about given package"); 15024 return; 15025 } else if ("--checkin".equals(opt)) { 15026 checkin = true; 15027 } else if ("-f".equals(opt)) { 15028 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15029 } else { 15030 pw.println("Unknown argument: " + opt + "; use -h for help"); 15031 } 15032 } 15033 15034 // Is the caller requesting to dump a particular piece of data? 15035 if (opti < args.length) { 15036 String cmd = args[opti]; 15037 opti++; 15038 // Is this a package name? 15039 if ("android".equals(cmd) || cmd.contains(".")) { 15040 packageName = cmd; 15041 // When dumping a single package, we always dump all of its 15042 // filter information since the amount of data will be reasonable. 15043 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15044 } else if ("check-permission".equals(cmd)) { 15045 if (opti >= args.length) { 15046 pw.println("Error: check-permission missing permission argument"); 15047 return; 15048 } 15049 String perm = args[opti]; 15050 opti++; 15051 if (opti >= args.length) { 15052 pw.println("Error: check-permission missing package argument"); 15053 return; 15054 } 15055 String pkg = args[opti]; 15056 opti++; 15057 int user = UserHandle.getUserId(Binder.getCallingUid()); 15058 if (opti < args.length) { 15059 try { 15060 user = Integer.parseInt(args[opti]); 15061 } catch (NumberFormatException e) { 15062 pw.println("Error: check-permission user argument is not a number: " 15063 + args[opti]); 15064 return; 15065 } 15066 } 15067 pw.println(checkPermission(perm, pkg, user)); 15068 return; 15069 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15070 dumpState.setDump(DumpState.DUMP_LIBS); 15071 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15072 dumpState.setDump(DumpState.DUMP_FEATURES); 15073 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15074 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15075 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15076 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15077 } else if ("permission".equals(cmd)) { 15078 if (opti >= args.length) { 15079 pw.println("Error: permission requires permission name"); 15080 return; 15081 } 15082 permissionNames = new ArraySet<>(); 15083 while (opti < args.length) { 15084 permissionNames.add(args[opti]); 15085 opti++; 15086 } 15087 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15088 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15089 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15090 dumpState.setDump(DumpState.DUMP_PREFERRED); 15091 } else if ("preferred-xml".equals(cmd)) { 15092 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15093 if (opti < args.length && "--full".equals(args[opti])) { 15094 fullPreferred = true; 15095 opti++; 15096 } 15097 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15098 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15099 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15100 dumpState.setDump(DumpState.DUMP_PACKAGES); 15101 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15102 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15103 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15104 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15105 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15106 dumpState.setDump(DumpState.DUMP_MESSAGES); 15107 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15108 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15109 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15110 || "intent-filter-verifiers".equals(cmd)) { 15111 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15112 } else if ("version".equals(cmd)) { 15113 dumpState.setDump(DumpState.DUMP_VERSION); 15114 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15115 dumpState.setDump(DumpState.DUMP_KEYSETS); 15116 } else if ("installs".equals(cmd)) { 15117 dumpState.setDump(DumpState.DUMP_INSTALLS); 15118 } else if ("write".equals(cmd)) { 15119 synchronized (mPackages) { 15120 mSettings.writeLPr(); 15121 pw.println("Settings written."); 15122 return; 15123 } 15124 } 15125 } 15126 15127 if (checkin) { 15128 pw.println("vers,1"); 15129 } 15130 15131 // reader 15132 synchronized (mPackages) { 15133 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15134 if (!checkin) { 15135 if (dumpState.onTitlePrinted()) 15136 pw.println(); 15137 pw.println("Database versions:"); 15138 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15139 } 15140 } 15141 15142 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15143 if (!checkin) { 15144 if (dumpState.onTitlePrinted()) 15145 pw.println(); 15146 pw.println("Verifiers:"); 15147 pw.print(" Required: "); 15148 pw.print(mRequiredVerifierPackage); 15149 pw.print(" (uid="); 15150 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15151 pw.println(")"); 15152 } else if (mRequiredVerifierPackage != null) { 15153 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15154 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15155 } 15156 } 15157 15158 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15159 packageName == null) { 15160 if (mIntentFilterVerifierComponent != null) { 15161 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15162 if (!checkin) { 15163 if (dumpState.onTitlePrinted()) 15164 pw.println(); 15165 pw.println("Intent Filter Verifier:"); 15166 pw.print(" Using: "); 15167 pw.print(verifierPackageName); 15168 pw.print(" (uid="); 15169 pw.print(getPackageUid(verifierPackageName, 0)); 15170 pw.println(")"); 15171 } else if (verifierPackageName != null) { 15172 pw.print("ifv,"); pw.print(verifierPackageName); 15173 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15174 } 15175 } else { 15176 pw.println(); 15177 pw.println("No Intent Filter Verifier available!"); 15178 } 15179 } 15180 15181 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15182 boolean printedHeader = false; 15183 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15184 while (it.hasNext()) { 15185 String name = it.next(); 15186 SharedLibraryEntry ent = mSharedLibraries.get(name); 15187 if (!checkin) { 15188 if (!printedHeader) { 15189 if (dumpState.onTitlePrinted()) 15190 pw.println(); 15191 pw.println("Libraries:"); 15192 printedHeader = true; 15193 } 15194 pw.print(" "); 15195 } else { 15196 pw.print("lib,"); 15197 } 15198 pw.print(name); 15199 if (!checkin) { 15200 pw.print(" -> "); 15201 } 15202 if (ent.path != null) { 15203 if (!checkin) { 15204 pw.print("(jar) "); 15205 pw.print(ent.path); 15206 } else { 15207 pw.print(",jar,"); 15208 pw.print(ent.path); 15209 } 15210 } else { 15211 if (!checkin) { 15212 pw.print("(apk) "); 15213 pw.print(ent.apk); 15214 } else { 15215 pw.print(",apk,"); 15216 pw.print(ent.apk); 15217 } 15218 } 15219 pw.println(); 15220 } 15221 } 15222 15223 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15224 if (dumpState.onTitlePrinted()) 15225 pw.println(); 15226 if (!checkin) { 15227 pw.println("Features:"); 15228 } 15229 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15230 while (it.hasNext()) { 15231 String name = it.next(); 15232 if (!checkin) { 15233 pw.print(" "); 15234 } else { 15235 pw.print("feat,"); 15236 } 15237 pw.println(name); 15238 } 15239 } 15240 15241 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15242 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15243 : "Activity Resolver Table:", " ", packageName, 15244 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15245 dumpState.setTitlePrinted(true); 15246 } 15247 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15248 : "Receiver Resolver Table:", " ", packageName, 15249 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15250 dumpState.setTitlePrinted(true); 15251 } 15252 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15253 : "Service Resolver Table:", " ", packageName, 15254 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15255 dumpState.setTitlePrinted(true); 15256 } 15257 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15258 : "Provider Resolver Table:", " ", packageName, 15259 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15260 dumpState.setTitlePrinted(true); 15261 } 15262 } 15263 15264 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15265 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15266 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15267 int user = mSettings.mPreferredActivities.keyAt(i); 15268 if (pir.dump(pw, 15269 dumpState.getTitlePrinted() 15270 ? "\nPreferred Activities User " + user + ":" 15271 : "Preferred Activities User " + user + ":", " ", 15272 packageName, true, false)) { 15273 dumpState.setTitlePrinted(true); 15274 } 15275 } 15276 } 15277 15278 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15279 pw.flush(); 15280 FileOutputStream fout = new FileOutputStream(fd); 15281 BufferedOutputStream str = new BufferedOutputStream(fout); 15282 XmlSerializer serializer = new FastXmlSerializer(); 15283 try { 15284 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15285 serializer.startDocument(null, true); 15286 serializer.setFeature( 15287 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15288 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15289 serializer.endDocument(); 15290 serializer.flush(); 15291 } catch (IllegalArgumentException e) { 15292 pw.println("Failed writing: " + e); 15293 } catch (IllegalStateException e) { 15294 pw.println("Failed writing: " + e); 15295 } catch (IOException e) { 15296 pw.println("Failed writing: " + e); 15297 } 15298 } 15299 15300 if (!checkin 15301 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15302 && packageName == null) { 15303 pw.println(); 15304 int count = mSettings.mPackages.size(); 15305 if (count == 0) { 15306 pw.println("No applications!"); 15307 pw.println(); 15308 } else { 15309 final String prefix = " "; 15310 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15311 if (allPackageSettings.size() == 0) { 15312 pw.println("No domain preferred apps!"); 15313 pw.println(); 15314 } else { 15315 pw.println("App verification status:"); 15316 pw.println(); 15317 count = 0; 15318 for (PackageSetting ps : allPackageSettings) { 15319 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15320 if (ivi == null || ivi.getPackageName() == null) continue; 15321 pw.println(prefix + "Package: " + ivi.getPackageName()); 15322 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15323 pw.println(prefix + "Status: " + ivi.getStatusString()); 15324 pw.println(); 15325 count++; 15326 } 15327 if (count == 0) { 15328 pw.println(prefix + "No app verification established."); 15329 pw.println(); 15330 } 15331 for (int userId : sUserManager.getUserIds()) { 15332 pw.println("App linkages for user " + userId + ":"); 15333 pw.println(); 15334 count = 0; 15335 for (PackageSetting ps : allPackageSettings) { 15336 final long status = ps.getDomainVerificationStatusForUser(userId); 15337 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15338 continue; 15339 } 15340 pw.println(prefix + "Package: " + ps.name); 15341 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15342 String statusStr = IntentFilterVerificationInfo. 15343 getStatusStringFromValue(status); 15344 pw.println(prefix + "Status: " + statusStr); 15345 pw.println(); 15346 count++; 15347 } 15348 if (count == 0) { 15349 pw.println(prefix + "No configured app linkages."); 15350 pw.println(); 15351 } 15352 } 15353 } 15354 } 15355 } 15356 15357 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15358 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15359 if (packageName == null && permissionNames == null) { 15360 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15361 if (iperm == 0) { 15362 if (dumpState.onTitlePrinted()) 15363 pw.println(); 15364 pw.println("AppOp Permissions:"); 15365 } 15366 pw.print(" AppOp Permission "); 15367 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15368 pw.println(":"); 15369 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15370 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15371 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15372 } 15373 } 15374 } 15375 } 15376 15377 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15378 boolean printedSomething = false; 15379 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15380 if (packageName != null && !packageName.equals(p.info.packageName)) { 15381 continue; 15382 } 15383 if (!printedSomething) { 15384 if (dumpState.onTitlePrinted()) 15385 pw.println(); 15386 pw.println("Registered ContentProviders:"); 15387 printedSomething = true; 15388 } 15389 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15390 pw.print(" "); pw.println(p.toString()); 15391 } 15392 printedSomething = false; 15393 for (Map.Entry<String, PackageParser.Provider> entry : 15394 mProvidersByAuthority.entrySet()) { 15395 PackageParser.Provider p = entry.getValue(); 15396 if (packageName != null && !packageName.equals(p.info.packageName)) { 15397 continue; 15398 } 15399 if (!printedSomething) { 15400 if (dumpState.onTitlePrinted()) 15401 pw.println(); 15402 pw.println("ContentProvider Authorities:"); 15403 printedSomething = true; 15404 } 15405 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15406 pw.print(" "); pw.println(p.toString()); 15407 if (p.info != null && p.info.applicationInfo != null) { 15408 final String appInfo = p.info.applicationInfo.toString(); 15409 pw.print(" applicationInfo="); pw.println(appInfo); 15410 } 15411 } 15412 } 15413 15414 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15415 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15416 } 15417 15418 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15419 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15420 } 15421 15422 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15423 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15424 } 15425 15426 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15427 // XXX should handle packageName != null by dumping only install data that 15428 // the given package is involved with. 15429 if (dumpState.onTitlePrinted()) pw.println(); 15430 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15431 } 15432 15433 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15434 if (dumpState.onTitlePrinted()) pw.println(); 15435 mSettings.dumpReadMessagesLPr(pw, dumpState); 15436 15437 pw.println(); 15438 pw.println("Package warning messages:"); 15439 BufferedReader in = null; 15440 String line = null; 15441 try { 15442 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15443 while ((line = in.readLine()) != null) { 15444 if (line.contains("ignored: updated version")) continue; 15445 pw.println(line); 15446 } 15447 } catch (IOException ignored) { 15448 } finally { 15449 IoUtils.closeQuietly(in); 15450 } 15451 } 15452 15453 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15454 BufferedReader in = null; 15455 String line = null; 15456 try { 15457 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15458 while ((line = in.readLine()) != null) { 15459 if (line.contains("ignored: updated version")) continue; 15460 pw.print("msg,"); 15461 pw.println(line); 15462 } 15463 } catch (IOException ignored) { 15464 } finally { 15465 IoUtils.closeQuietly(in); 15466 } 15467 } 15468 } 15469 } 15470 15471 private String dumpDomainString(String packageName) { 15472 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15473 List<IntentFilter> filters = getAllIntentFilters(packageName); 15474 15475 ArraySet<String> result = new ArraySet<>(); 15476 if (iviList.size() > 0) { 15477 for (IntentFilterVerificationInfo ivi : iviList) { 15478 for (String host : ivi.getDomains()) { 15479 result.add(host); 15480 } 15481 } 15482 } 15483 if (filters != null && filters.size() > 0) { 15484 for (IntentFilter filter : filters) { 15485 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15486 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15487 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15488 result.addAll(filter.getHostsList()); 15489 } 15490 } 15491 } 15492 15493 StringBuilder sb = new StringBuilder(result.size() * 16); 15494 for (String domain : result) { 15495 if (sb.length() > 0) sb.append(" "); 15496 sb.append(domain); 15497 } 15498 return sb.toString(); 15499 } 15500 15501 // ------- apps on sdcard specific code ------- 15502 static final boolean DEBUG_SD_INSTALL = false; 15503 15504 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15505 15506 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15507 15508 private boolean mMediaMounted = false; 15509 15510 static String getEncryptKey() { 15511 try { 15512 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15513 SD_ENCRYPTION_KEYSTORE_NAME); 15514 if (sdEncKey == null) { 15515 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15516 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15517 if (sdEncKey == null) { 15518 Slog.e(TAG, "Failed to create encryption keys"); 15519 return null; 15520 } 15521 } 15522 return sdEncKey; 15523 } catch (NoSuchAlgorithmException nsae) { 15524 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15525 return null; 15526 } catch (IOException ioe) { 15527 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15528 return null; 15529 } 15530 } 15531 15532 /* 15533 * Update media status on PackageManager. 15534 */ 15535 @Override 15536 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15537 int callingUid = Binder.getCallingUid(); 15538 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15539 throw new SecurityException("Media status can only be updated by the system"); 15540 } 15541 // reader; this apparently protects mMediaMounted, but should probably 15542 // be a different lock in that case. 15543 synchronized (mPackages) { 15544 Log.i(TAG, "Updating external media status from " 15545 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15546 + (mediaStatus ? "mounted" : "unmounted")); 15547 if (DEBUG_SD_INSTALL) 15548 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15549 + ", mMediaMounted=" + mMediaMounted); 15550 if (mediaStatus == mMediaMounted) { 15551 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15552 : 0, -1); 15553 mHandler.sendMessage(msg); 15554 return; 15555 } 15556 mMediaMounted = mediaStatus; 15557 } 15558 // Queue up an async operation since the package installation may take a 15559 // little while. 15560 mHandler.post(new Runnable() { 15561 public void run() { 15562 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15563 } 15564 }); 15565 } 15566 15567 /** 15568 * Called by MountService when the initial ASECs to scan are available. 15569 * Should block until all the ASEC containers are finished being scanned. 15570 */ 15571 public void scanAvailableAsecs() { 15572 updateExternalMediaStatusInner(true, false, false); 15573 if (mShouldRestoreconData) { 15574 SELinuxMMAC.setRestoreconDone(); 15575 mShouldRestoreconData = false; 15576 } 15577 } 15578 15579 /* 15580 * Collect information of applications on external media, map them against 15581 * existing containers and update information based on current mount status. 15582 * Please note that we always have to report status if reportStatus has been 15583 * set to true especially when unloading packages. 15584 */ 15585 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15586 boolean externalStorage) { 15587 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15588 int[] uidArr = EmptyArray.INT; 15589 15590 final String[] list = PackageHelper.getSecureContainerList(); 15591 if (ArrayUtils.isEmpty(list)) { 15592 Log.i(TAG, "No secure containers found"); 15593 } else { 15594 // Process list of secure containers and categorize them 15595 // as active or stale based on their package internal state. 15596 15597 // reader 15598 synchronized (mPackages) { 15599 for (String cid : list) { 15600 // Leave stages untouched for now; installer service owns them 15601 if (PackageInstallerService.isStageName(cid)) continue; 15602 15603 if (DEBUG_SD_INSTALL) 15604 Log.i(TAG, "Processing container " + cid); 15605 String pkgName = getAsecPackageName(cid); 15606 if (pkgName == null) { 15607 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15608 continue; 15609 } 15610 if (DEBUG_SD_INSTALL) 15611 Log.i(TAG, "Looking for pkg : " + pkgName); 15612 15613 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15614 if (ps == null) { 15615 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15616 continue; 15617 } 15618 15619 /* 15620 * Skip packages that are not external if we're unmounting 15621 * external storage. 15622 */ 15623 if (externalStorage && !isMounted && !isExternal(ps)) { 15624 continue; 15625 } 15626 15627 final AsecInstallArgs args = new AsecInstallArgs(cid, 15628 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15629 // The package status is changed only if the code path 15630 // matches between settings and the container id. 15631 if (ps.codePathString != null 15632 && ps.codePathString.startsWith(args.getCodePath())) { 15633 if (DEBUG_SD_INSTALL) { 15634 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15635 + " at code path: " + ps.codePathString); 15636 } 15637 15638 // We do have a valid package installed on sdcard 15639 processCids.put(args, ps.codePathString); 15640 final int uid = ps.appId; 15641 if (uid != -1) { 15642 uidArr = ArrayUtils.appendInt(uidArr, uid); 15643 } 15644 } else { 15645 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15646 + ps.codePathString); 15647 } 15648 } 15649 } 15650 15651 Arrays.sort(uidArr); 15652 } 15653 15654 // Process packages with valid entries. 15655 if (isMounted) { 15656 if (DEBUG_SD_INSTALL) 15657 Log.i(TAG, "Loading packages"); 15658 loadMediaPackages(processCids, uidArr); 15659 startCleaningPackages(); 15660 mInstallerService.onSecureContainersAvailable(); 15661 } else { 15662 if (DEBUG_SD_INSTALL) 15663 Log.i(TAG, "Unloading packages"); 15664 unloadMediaPackages(processCids, uidArr, reportStatus); 15665 } 15666 } 15667 15668 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15669 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15670 final int size = infos.size(); 15671 final String[] packageNames = new String[size]; 15672 final int[] packageUids = new int[size]; 15673 for (int i = 0; i < size; i++) { 15674 final ApplicationInfo info = infos.get(i); 15675 packageNames[i] = info.packageName; 15676 packageUids[i] = info.uid; 15677 } 15678 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15679 finishedReceiver); 15680 } 15681 15682 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15683 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15684 sendResourcesChangedBroadcast(mediaStatus, replacing, 15685 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15686 } 15687 15688 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15689 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15690 int size = pkgList.length; 15691 if (size > 0) { 15692 // Send broadcasts here 15693 Bundle extras = new Bundle(); 15694 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15695 if (uidArr != null) { 15696 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15697 } 15698 if (replacing) { 15699 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15700 } 15701 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15702 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15703 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15704 } 15705 } 15706 15707 /* 15708 * Look at potentially valid container ids from processCids If package 15709 * information doesn't match the one on record or package scanning fails, 15710 * the cid is added to list of removeCids. We currently don't delete stale 15711 * containers. 15712 */ 15713 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15714 ArrayList<String> pkgList = new ArrayList<String>(); 15715 Set<AsecInstallArgs> keys = processCids.keySet(); 15716 15717 for (AsecInstallArgs args : keys) { 15718 String codePath = processCids.get(args); 15719 if (DEBUG_SD_INSTALL) 15720 Log.i(TAG, "Loading container : " + args.cid); 15721 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15722 try { 15723 // Make sure there are no container errors first. 15724 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15725 Slog.e(TAG, "Failed to mount cid : " + args.cid 15726 + " when installing from sdcard"); 15727 continue; 15728 } 15729 // Check code path here. 15730 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15731 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15732 + " does not match one in settings " + codePath); 15733 continue; 15734 } 15735 // Parse package 15736 int parseFlags = mDefParseFlags; 15737 if (args.isExternalAsec()) { 15738 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15739 } 15740 if (args.isFwdLocked()) { 15741 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15742 } 15743 15744 synchronized (mInstallLock) { 15745 PackageParser.Package pkg = null; 15746 try { 15747 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15748 } catch (PackageManagerException e) { 15749 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15750 } 15751 // Scan the package 15752 if (pkg != null) { 15753 /* 15754 * TODO why is the lock being held? doPostInstall is 15755 * called in other places without the lock. This needs 15756 * to be straightened out. 15757 */ 15758 // writer 15759 synchronized (mPackages) { 15760 retCode = PackageManager.INSTALL_SUCCEEDED; 15761 pkgList.add(pkg.packageName); 15762 // Post process args 15763 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15764 pkg.applicationInfo.uid); 15765 } 15766 } else { 15767 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15768 } 15769 } 15770 15771 } finally { 15772 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15773 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15774 } 15775 } 15776 } 15777 // writer 15778 synchronized (mPackages) { 15779 // If the platform SDK has changed since the last time we booted, 15780 // we need to re-grant app permission to catch any new ones that 15781 // appear. This is really a hack, and means that apps can in some 15782 // cases get permissions that the user didn't initially explicitly 15783 // allow... it would be nice to have some better way to handle 15784 // this situation. 15785 final VersionInfo ver = mSettings.getExternalVersion(); 15786 15787 int updateFlags = UPDATE_PERMISSIONS_ALL; 15788 if (ver.sdkVersion != mSdkVersion) { 15789 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15790 + mSdkVersion + "; regranting permissions for external"); 15791 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15792 } 15793 updatePermissionsLPw(null, null, updateFlags); 15794 15795 // Yay, everything is now upgraded 15796 ver.forceCurrent(); 15797 15798 // can downgrade to reader 15799 // Persist settings 15800 mSettings.writeLPr(); 15801 } 15802 // Send a broadcast to let everyone know we are done processing 15803 if (pkgList.size() > 0) { 15804 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15805 } 15806 } 15807 15808 /* 15809 * Utility method to unload a list of specified containers 15810 */ 15811 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15812 // Just unmount all valid containers. 15813 for (AsecInstallArgs arg : cidArgs) { 15814 synchronized (mInstallLock) { 15815 arg.doPostDeleteLI(false); 15816 } 15817 } 15818 } 15819 15820 /* 15821 * Unload packages mounted on external media. This involves deleting package 15822 * data from internal structures, sending broadcasts about diabled packages, 15823 * gc'ing to free up references, unmounting all secure containers 15824 * corresponding to packages on external media, and posting a 15825 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15826 * that we always have to post this message if status has been requested no 15827 * matter what. 15828 */ 15829 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15830 final boolean reportStatus) { 15831 if (DEBUG_SD_INSTALL) 15832 Log.i(TAG, "unloading media packages"); 15833 ArrayList<String> pkgList = new ArrayList<String>(); 15834 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15835 final Set<AsecInstallArgs> keys = processCids.keySet(); 15836 for (AsecInstallArgs args : keys) { 15837 String pkgName = args.getPackageName(); 15838 if (DEBUG_SD_INSTALL) 15839 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15840 // Delete package internally 15841 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15842 synchronized (mInstallLock) { 15843 boolean res = deletePackageLI(pkgName, null, false, null, null, 15844 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15845 if (res) { 15846 pkgList.add(pkgName); 15847 } else { 15848 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15849 failedList.add(args); 15850 } 15851 } 15852 } 15853 15854 // reader 15855 synchronized (mPackages) { 15856 // We didn't update the settings after removing each package; 15857 // write them now for all packages. 15858 mSettings.writeLPr(); 15859 } 15860 15861 // We have to absolutely send UPDATED_MEDIA_STATUS only 15862 // after confirming that all the receivers processed the ordered 15863 // broadcast when packages get disabled, force a gc to clean things up. 15864 // and unload all the containers. 15865 if (pkgList.size() > 0) { 15866 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15867 new IIntentReceiver.Stub() { 15868 public void performReceive(Intent intent, int resultCode, String data, 15869 Bundle extras, boolean ordered, boolean sticky, 15870 int sendingUser) throws RemoteException { 15871 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15872 reportStatus ? 1 : 0, 1, keys); 15873 mHandler.sendMessage(msg); 15874 } 15875 }); 15876 } else { 15877 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15878 keys); 15879 mHandler.sendMessage(msg); 15880 } 15881 } 15882 15883 private void loadPrivatePackages(VolumeInfo vol) { 15884 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15885 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15886 synchronized (mInstallLock) { 15887 synchronized (mPackages) { 15888 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15889 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15890 for (PackageSetting ps : packages) { 15891 final PackageParser.Package pkg; 15892 try { 15893 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15894 loaded.add(pkg.applicationInfo); 15895 } catch (PackageManagerException e) { 15896 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15897 } 15898 15899 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15900 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15901 } 15902 } 15903 15904 int updateFlags = UPDATE_PERMISSIONS_ALL; 15905 if (ver.sdkVersion != mSdkVersion) { 15906 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15907 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15908 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15909 } 15910 updatePermissionsLPw(null, null, updateFlags); 15911 15912 // Yay, everything is now upgraded 15913 ver.forceCurrent(); 15914 15915 mSettings.writeLPr(); 15916 } 15917 } 15918 15919 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15920 sendResourcesChangedBroadcast(true, false, loaded, null); 15921 } 15922 15923 private void unloadPrivatePackages(VolumeInfo vol) { 15924 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15925 synchronized (mInstallLock) { 15926 synchronized (mPackages) { 15927 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15928 for (PackageSetting ps : packages) { 15929 if (ps.pkg == null) continue; 15930 15931 final ApplicationInfo info = ps.pkg.applicationInfo; 15932 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15933 if (deletePackageLI(ps.name, null, false, null, null, 15934 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15935 unloaded.add(info); 15936 } else { 15937 Slog.w(TAG, "Failed to unload " + ps.codePath); 15938 } 15939 } 15940 15941 mSettings.writeLPr(); 15942 } 15943 } 15944 15945 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15946 sendResourcesChangedBroadcast(false, false, unloaded, null); 15947 } 15948 15949 /** 15950 * Examine all users present on given mounted volume, and destroy data 15951 * belonging to users that are no longer valid, or whose user ID has been 15952 * recycled. 15953 */ 15954 private void reconcileUsers(String volumeUuid) { 15955 final File[] files = FileUtils 15956 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15957 for (File file : files) { 15958 if (!file.isDirectory()) continue; 15959 15960 final int userId; 15961 final UserInfo info; 15962 try { 15963 userId = Integer.parseInt(file.getName()); 15964 info = sUserManager.getUserInfo(userId); 15965 } catch (NumberFormatException e) { 15966 Slog.w(TAG, "Invalid user directory " + file); 15967 continue; 15968 } 15969 15970 boolean destroyUser = false; 15971 if (info == null) { 15972 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15973 + " because no matching user was found"); 15974 destroyUser = true; 15975 } else { 15976 try { 15977 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15978 } catch (IOException e) { 15979 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15980 + " because we failed to enforce serial number: " + e); 15981 destroyUser = true; 15982 } 15983 } 15984 15985 if (destroyUser) { 15986 synchronized (mInstallLock) { 15987 mInstaller.removeUserDataDirs(volumeUuid, userId); 15988 } 15989 } 15990 } 15991 15992 final UserManager um = mContext.getSystemService(UserManager.class); 15993 for (UserInfo user : um.getUsers()) { 15994 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15995 if (userDir.exists()) continue; 15996 15997 try { 15998 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15999 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16000 } catch (IOException e) { 16001 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16002 } 16003 } 16004 } 16005 16006 /** 16007 * Examine all apps present on given mounted volume, and destroy apps that 16008 * aren't expected, either due to uninstallation or reinstallation on 16009 * another volume. 16010 */ 16011 private void reconcileApps(String volumeUuid) { 16012 final File[] files = FileUtils 16013 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16014 for (File file : files) { 16015 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16016 && !PackageInstallerService.isStageName(file.getName()); 16017 if (!isPackage) { 16018 // Ignore entries which are not packages 16019 continue; 16020 } 16021 16022 boolean destroyApp = false; 16023 String packageName = null; 16024 try { 16025 final PackageLite pkg = PackageParser.parsePackageLite(file, 16026 PackageParser.PARSE_MUST_BE_APK); 16027 packageName = pkg.packageName; 16028 16029 synchronized (mPackages) { 16030 final PackageSetting ps = mSettings.mPackages.get(packageName); 16031 if (ps == null) { 16032 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16033 + volumeUuid + " because we found no install record"); 16034 destroyApp = true; 16035 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16036 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16037 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16038 destroyApp = true; 16039 } 16040 } 16041 16042 } catch (PackageParserException e) { 16043 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16044 destroyApp = true; 16045 } 16046 16047 if (destroyApp) { 16048 synchronized (mInstallLock) { 16049 if (packageName != null) { 16050 removeDataDirsLI(volumeUuid, packageName); 16051 } 16052 if (file.isDirectory()) { 16053 mInstaller.rmPackageDir(file.getAbsolutePath()); 16054 } else { 16055 file.delete(); 16056 } 16057 } 16058 } 16059 } 16060 } 16061 16062 private void unfreezePackage(String packageName) { 16063 synchronized (mPackages) { 16064 final PackageSetting ps = mSettings.mPackages.get(packageName); 16065 if (ps != null) { 16066 ps.frozen = false; 16067 } 16068 } 16069 } 16070 16071 @Override 16072 public int movePackage(final String packageName, final String volumeUuid) { 16073 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16074 16075 final int moveId = mNextMoveId.getAndIncrement(); 16076 try { 16077 movePackageInternal(packageName, volumeUuid, moveId); 16078 } catch (PackageManagerException e) { 16079 Slog.w(TAG, "Failed to move " + packageName, e); 16080 mMoveCallbacks.notifyStatusChanged(moveId, 16081 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16082 } 16083 return moveId; 16084 } 16085 16086 private void movePackageInternal(final String packageName, final String volumeUuid, 16087 final int moveId) throws PackageManagerException { 16088 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16089 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16090 final PackageManager pm = mContext.getPackageManager(); 16091 16092 final boolean currentAsec; 16093 final String currentVolumeUuid; 16094 final File codeFile; 16095 final String installerPackageName; 16096 final String packageAbiOverride; 16097 final int appId; 16098 final String seinfo; 16099 final String label; 16100 16101 // reader 16102 synchronized (mPackages) { 16103 final PackageParser.Package pkg = mPackages.get(packageName); 16104 final PackageSetting ps = mSettings.mPackages.get(packageName); 16105 if (pkg == null || ps == null) { 16106 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16107 } 16108 16109 if (pkg.applicationInfo.isSystemApp()) { 16110 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16111 "Cannot move system application"); 16112 } 16113 16114 if (pkg.applicationInfo.isExternalAsec()) { 16115 currentAsec = true; 16116 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16117 } else if (pkg.applicationInfo.isForwardLocked()) { 16118 currentAsec = true; 16119 currentVolumeUuid = "forward_locked"; 16120 } else { 16121 currentAsec = false; 16122 currentVolumeUuid = ps.volumeUuid; 16123 16124 final File probe = new File(pkg.codePath); 16125 final File probeOat = new File(probe, "oat"); 16126 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16127 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16128 "Move only supported for modern cluster style installs"); 16129 } 16130 } 16131 16132 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16133 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16134 "Package already moved to " + volumeUuid); 16135 } 16136 16137 if (ps.frozen) { 16138 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16139 "Failed to move already frozen package"); 16140 } 16141 ps.frozen = true; 16142 16143 codeFile = new File(pkg.codePath); 16144 installerPackageName = ps.installerPackageName; 16145 packageAbiOverride = ps.cpuAbiOverrideString; 16146 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16147 seinfo = pkg.applicationInfo.seinfo; 16148 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16149 } 16150 16151 // Now that we're guarded by frozen state, kill app during move 16152 final long token = Binder.clearCallingIdentity(); 16153 try { 16154 killApplication(packageName, appId, "move pkg"); 16155 } finally { 16156 Binder.restoreCallingIdentity(token); 16157 } 16158 16159 final Bundle extras = new Bundle(); 16160 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16161 extras.putString(Intent.EXTRA_TITLE, label); 16162 mMoveCallbacks.notifyCreated(moveId, extras); 16163 16164 int installFlags; 16165 final boolean moveCompleteApp; 16166 final File measurePath; 16167 16168 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16169 installFlags = INSTALL_INTERNAL; 16170 moveCompleteApp = !currentAsec; 16171 measurePath = Environment.getDataAppDirectory(volumeUuid); 16172 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16173 installFlags = INSTALL_EXTERNAL; 16174 moveCompleteApp = false; 16175 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16176 } else { 16177 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16178 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16179 || !volume.isMountedWritable()) { 16180 unfreezePackage(packageName); 16181 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16182 "Move location not mounted private volume"); 16183 } 16184 16185 Preconditions.checkState(!currentAsec); 16186 16187 installFlags = INSTALL_INTERNAL; 16188 moveCompleteApp = true; 16189 measurePath = Environment.getDataAppDirectory(volumeUuid); 16190 } 16191 16192 final PackageStats stats = new PackageStats(null, -1); 16193 synchronized (mInstaller) { 16194 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16195 unfreezePackage(packageName); 16196 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16197 "Failed to measure package size"); 16198 } 16199 } 16200 16201 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16202 + stats.dataSize); 16203 16204 final long startFreeBytes = measurePath.getFreeSpace(); 16205 final long sizeBytes; 16206 if (moveCompleteApp) { 16207 sizeBytes = stats.codeSize + stats.dataSize; 16208 } else { 16209 sizeBytes = stats.codeSize; 16210 } 16211 16212 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16213 unfreezePackage(packageName); 16214 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16215 "Not enough free space to move"); 16216 } 16217 16218 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16219 16220 final CountDownLatch installedLatch = new CountDownLatch(1); 16221 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16222 @Override 16223 public void onUserActionRequired(Intent intent) throws RemoteException { 16224 throw new IllegalStateException(); 16225 } 16226 16227 @Override 16228 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16229 Bundle extras) throws RemoteException { 16230 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16231 + PackageManager.installStatusToString(returnCode, msg)); 16232 16233 installedLatch.countDown(); 16234 16235 // Regardless of success or failure of the move operation, 16236 // always unfreeze the package 16237 unfreezePackage(packageName); 16238 16239 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16240 switch (status) { 16241 case PackageInstaller.STATUS_SUCCESS: 16242 mMoveCallbacks.notifyStatusChanged(moveId, 16243 PackageManager.MOVE_SUCCEEDED); 16244 break; 16245 case PackageInstaller.STATUS_FAILURE_STORAGE: 16246 mMoveCallbacks.notifyStatusChanged(moveId, 16247 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16248 break; 16249 default: 16250 mMoveCallbacks.notifyStatusChanged(moveId, 16251 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16252 break; 16253 } 16254 } 16255 }; 16256 16257 final MoveInfo move; 16258 if (moveCompleteApp) { 16259 // Kick off a thread to report progress estimates 16260 new Thread() { 16261 @Override 16262 public void run() { 16263 while (true) { 16264 try { 16265 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16266 break; 16267 } 16268 } catch (InterruptedException ignored) { 16269 } 16270 16271 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16272 final int progress = 10 + (int) MathUtils.constrain( 16273 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16274 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16275 } 16276 } 16277 }.start(); 16278 16279 final String dataAppName = codeFile.getName(); 16280 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16281 dataAppName, appId, seinfo); 16282 } else { 16283 move = null; 16284 } 16285 16286 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16287 16288 final Message msg = mHandler.obtainMessage(INIT_COPY); 16289 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16290 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16291 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16292 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16293 msg.obj = params; 16294 16295 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16296 System.identityHashCode(msg.obj)); 16297 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16298 System.identityHashCode(msg.obj)); 16299 16300 mHandler.sendMessage(msg); 16301 } 16302 16303 @Override 16304 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16305 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16306 16307 final int realMoveId = mNextMoveId.getAndIncrement(); 16308 final Bundle extras = new Bundle(); 16309 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16310 mMoveCallbacks.notifyCreated(realMoveId, extras); 16311 16312 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16313 @Override 16314 public void onCreated(int moveId, Bundle extras) { 16315 // Ignored 16316 } 16317 16318 @Override 16319 public void onStatusChanged(int moveId, int status, long estMillis) { 16320 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16321 } 16322 }; 16323 16324 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16325 storage.setPrimaryStorageUuid(volumeUuid, callback); 16326 return realMoveId; 16327 } 16328 16329 @Override 16330 public int getMoveStatus(int moveId) { 16331 mContext.enforceCallingOrSelfPermission( 16332 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16333 return mMoveCallbacks.mLastStatus.get(moveId); 16334 } 16335 16336 @Override 16337 public void registerMoveCallback(IPackageMoveObserver callback) { 16338 mContext.enforceCallingOrSelfPermission( 16339 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16340 mMoveCallbacks.register(callback); 16341 } 16342 16343 @Override 16344 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16345 mContext.enforceCallingOrSelfPermission( 16346 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16347 mMoveCallbacks.unregister(callback); 16348 } 16349 16350 @Override 16351 public boolean setInstallLocation(int loc) { 16352 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16353 null); 16354 if (getInstallLocation() == loc) { 16355 return true; 16356 } 16357 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16358 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16359 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16360 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16361 return true; 16362 } 16363 return false; 16364 } 16365 16366 @Override 16367 public int getInstallLocation() { 16368 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16369 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16370 PackageHelper.APP_INSTALL_AUTO); 16371 } 16372 16373 /** Called by UserManagerService */ 16374 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16375 mDirtyUsers.remove(userHandle); 16376 mSettings.removeUserLPw(userHandle); 16377 mPendingBroadcasts.remove(userHandle); 16378 if (mInstaller != null) { 16379 // Technically, we shouldn't be doing this with the package lock 16380 // held. However, this is very rare, and there is already so much 16381 // other disk I/O going on, that we'll let it slide for now. 16382 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16383 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16384 final String volumeUuid = vol.getFsUuid(); 16385 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16386 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16387 } 16388 } 16389 mUserNeedsBadging.delete(userHandle); 16390 removeUnusedPackagesLILPw(userManager, userHandle); 16391 } 16392 16393 /** 16394 * We're removing userHandle and would like to remove any downloaded packages 16395 * that are no longer in use by any other user. 16396 * @param userHandle the user being removed 16397 */ 16398 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16399 final boolean DEBUG_CLEAN_APKS = false; 16400 int [] users = userManager.getUserIdsLPr(); 16401 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16402 while (psit.hasNext()) { 16403 PackageSetting ps = psit.next(); 16404 if (ps.pkg == null) { 16405 continue; 16406 } 16407 final String packageName = ps.pkg.packageName; 16408 // Skip over if system app 16409 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16410 continue; 16411 } 16412 if (DEBUG_CLEAN_APKS) { 16413 Slog.i(TAG, "Checking package " + packageName); 16414 } 16415 boolean keep = false; 16416 for (int i = 0; i < users.length; i++) { 16417 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16418 keep = true; 16419 if (DEBUG_CLEAN_APKS) { 16420 Slog.i(TAG, " Keeping package " + packageName + " for user " 16421 + users[i]); 16422 } 16423 break; 16424 } 16425 } 16426 if (!keep) { 16427 if (DEBUG_CLEAN_APKS) { 16428 Slog.i(TAG, " Removing package " + packageName); 16429 } 16430 mHandler.post(new Runnable() { 16431 public void run() { 16432 deletePackageX(packageName, userHandle, 0); 16433 } //end run 16434 }); 16435 } 16436 } 16437 } 16438 16439 /** Called by UserManagerService */ 16440 void createNewUserLILPw(int userHandle) { 16441 if (mInstaller != null) { 16442 mInstaller.createUserConfig(userHandle); 16443 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16444 applyFactoryDefaultBrowserLPw(userHandle); 16445 primeDomainVerificationsLPw(userHandle); 16446 } 16447 } 16448 16449 void newUserCreated(final int userHandle) { 16450 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16451 } 16452 16453 @Override 16454 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16455 mContext.enforceCallingOrSelfPermission( 16456 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16457 "Only package verification agents can read the verifier device identity"); 16458 16459 synchronized (mPackages) { 16460 return mSettings.getVerifierDeviceIdentityLPw(); 16461 } 16462 } 16463 16464 @Override 16465 public void setPermissionEnforced(String permission, boolean enforced) { 16466 // TODO: Now that we no longer change GID for storage, this should to away. 16467 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16468 "setPermissionEnforced"); 16469 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16470 synchronized (mPackages) { 16471 if (mSettings.mReadExternalStorageEnforced == null 16472 || mSettings.mReadExternalStorageEnforced != enforced) { 16473 mSettings.mReadExternalStorageEnforced = enforced; 16474 mSettings.writeLPr(); 16475 } 16476 } 16477 // kill any non-foreground processes so we restart them and 16478 // grant/revoke the GID. 16479 final IActivityManager am = ActivityManagerNative.getDefault(); 16480 if (am != null) { 16481 final long token = Binder.clearCallingIdentity(); 16482 try { 16483 am.killProcessesBelowForeground("setPermissionEnforcement"); 16484 } catch (RemoteException e) { 16485 } finally { 16486 Binder.restoreCallingIdentity(token); 16487 } 16488 } 16489 } else { 16490 throw new IllegalArgumentException("No selective enforcement for " + permission); 16491 } 16492 } 16493 16494 @Override 16495 @Deprecated 16496 public boolean isPermissionEnforced(String permission) { 16497 return true; 16498 } 16499 16500 @Override 16501 public boolean isStorageLow() { 16502 final long token = Binder.clearCallingIdentity(); 16503 try { 16504 final DeviceStorageMonitorInternal 16505 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16506 if (dsm != null) { 16507 return dsm.isMemoryLow(); 16508 } else { 16509 return false; 16510 } 16511 } finally { 16512 Binder.restoreCallingIdentity(token); 16513 } 16514 } 16515 16516 @Override 16517 public IPackageInstaller getPackageInstaller() { 16518 return mInstallerService; 16519 } 16520 16521 private boolean userNeedsBadging(int userId) { 16522 int index = mUserNeedsBadging.indexOfKey(userId); 16523 if (index < 0) { 16524 final UserInfo userInfo; 16525 final long token = Binder.clearCallingIdentity(); 16526 try { 16527 userInfo = sUserManager.getUserInfo(userId); 16528 } finally { 16529 Binder.restoreCallingIdentity(token); 16530 } 16531 final boolean b; 16532 if (userInfo != null && userInfo.isManagedProfile()) { 16533 b = true; 16534 } else { 16535 b = false; 16536 } 16537 mUserNeedsBadging.put(userId, b); 16538 return b; 16539 } 16540 return mUserNeedsBadging.valueAt(index); 16541 } 16542 16543 @Override 16544 public KeySet getKeySetByAlias(String packageName, String alias) { 16545 if (packageName == null || alias == null) { 16546 return null; 16547 } 16548 synchronized(mPackages) { 16549 final PackageParser.Package pkg = mPackages.get(packageName); 16550 if (pkg == null) { 16551 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16552 throw new IllegalArgumentException("Unknown package: " + packageName); 16553 } 16554 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16555 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16556 } 16557 } 16558 16559 @Override 16560 public KeySet getSigningKeySet(String packageName) { 16561 if (packageName == null) { 16562 return null; 16563 } 16564 synchronized(mPackages) { 16565 final PackageParser.Package pkg = mPackages.get(packageName); 16566 if (pkg == null) { 16567 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16568 throw new IllegalArgumentException("Unknown package: " + packageName); 16569 } 16570 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16571 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16572 throw new SecurityException("May not access signing KeySet of other apps."); 16573 } 16574 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16575 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16576 } 16577 } 16578 16579 @Override 16580 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16581 if (packageName == null || ks == null) { 16582 return false; 16583 } 16584 synchronized(mPackages) { 16585 final PackageParser.Package pkg = mPackages.get(packageName); 16586 if (pkg == null) { 16587 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16588 throw new IllegalArgumentException("Unknown package: " + packageName); 16589 } 16590 IBinder ksh = ks.getToken(); 16591 if (ksh instanceof KeySetHandle) { 16592 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16593 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16594 } 16595 return false; 16596 } 16597 } 16598 16599 @Override 16600 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16601 if (packageName == null || ks == null) { 16602 return false; 16603 } 16604 synchronized(mPackages) { 16605 final PackageParser.Package pkg = mPackages.get(packageName); 16606 if (pkg == null) { 16607 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16608 throw new IllegalArgumentException("Unknown package: " + packageName); 16609 } 16610 IBinder ksh = ks.getToken(); 16611 if (ksh instanceof KeySetHandle) { 16612 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16613 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16614 } 16615 return false; 16616 } 16617 } 16618 16619 public void getUsageStatsIfNoPackageUsageInfo() { 16620 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16621 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16622 if (usm == null) { 16623 throw new IllegalStateException("UsageStatsManager must be initialized"); 16624 } 16625 long now = System.currentTimeMillis(); 16626 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16627 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16628 String packageName = entry.getKey(); 16629 PackageParser.Package pkg = mPackages.get(packageName); 16630 if (pkg == null) { 16631 continue; 16632 } 16633 UsageStats usage = entry.getValue(); 16634 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16635 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16636 } 16637 } 16638 } 16639 16640 /** 16641 * Check and throw if the given before/after packages would be considered a 16642 * downgrade. 16643 */ 16644 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16645 throws PackageManagerException { 16646 if (after.versionCode < before.mVersionCode) { 16647 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16648 "Update version code " + after.versionCode + " is older than current " 16649 + before.mVersionCode); 16650 } else if (after.versionCode == before.mVersionCode) { 16651 if (after.baseRevisionCode < before.baseRevisionCode) { 16652 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16653 "Update base revision code " + after.baseRevisionCode 16654 + " is older than current " + before.baseRevisionCode); 16655 } 16656 16657 if (!ArrayUtils.isEmpty(after.splitNames)) { 16658 for (int i = 0; i < after.splitNames.length; i++) { 16659 final String splitName = after.splitNames[i]; 16660 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16661 if (j != -1) { 16662 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16663 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16664 "Update split " + splitName + " revision code " 16665 + after.splitRevisionCodes[i] + " is older than current " 16666 + before.splitRevisionCodes[j]); 16667 } 16668 } 16669 } 16670 } 16671 } 16672 } 16673 16674 private static class MoveCallbacks extends Handler { 16675 private static final int MSG_CREATED = 1; 16676 private static final int MSG_STATUS_CHANGED = 2; 16677 16678 private final RemoteCallbackList<IPackageMoveObserver> 16679 mCallbacks = new RemoteCallbackList<>(); 16680 16681 private final SparseIntArray mLastStatus = new SparseIntArray(); 16682 16683 public MoveCallbacks(Looper looper) { 16684 super(looper); 16685 } 16686 16687 public void register(IPackageMoveObserver callback) { 16688 mCallbacks.register(callback); 16689 } 16690 16691 public void unregister(IPackageMoveObserver callback) { 16692 mCallbacks.unregister(callback); 16693 } 16694 16695 @Override 16696 public void handleMessage(Message msg) { 16697 final SomeArgs args = (SomeArgs) msg.obj; 16698 final int n = mCallbacks.beginBroadcast(); 16699 for (int i = 0; i < n; i++) { 16700 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16701 try { 16702 invokeCallback(callback, msg.what, args); 16703 } catch (RemoteException ignored) { 16704 } 16705 } 16706 mCallbacks.finishBroadcast(); 16707 args.recycle(); 16708 } 16709 16710 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16711 throws RemoteException { 16712 switch (what) { 16713 case MSG_CREATED: { 16714 callback.onCreated(args.argi1, (Bundle) args.arg2); 16715 break; 16716 } 16717 case MSG_STATUS_CHANGED: { 16718 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16719 break; 16720 } 16721 } 16722 } 16723 16724 private void notifyCreated(int moveId, Bundle extras) { 16725 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16726 16727 final SomeArgs args = SomeArgs.obtain(); 16728 args.argi1 = moveId; 16729 args.arg2 = extras; 16730 obtainMessage(MSG_CREATED, args).sendToTarget(); 16731 } 16732 16733 private void notifyStatusChanged(int moveId, int status) { 16734 notifyStatusChanged(moveId, status, -1); 16735 } 16736 16737 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16738 Slog.v(TAG, "Move " + moveId + " status " + status); 16739 16740 final SomeArgs args = SomeArgs.obtain(); 16741 args.argi1 = moveId; 16742 args.argi2 = status; 16743 args.arg3 = estMillis; 16744 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16745 16746 synchronized (mLastStatus) { 16747 mLastStatus.put(moveId, status); 16748 } 16749 } 16750 } 16751 16752 private final class OnPermissionChangeListeners extends Handler { 16753 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16754 16755 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16756 new RemoteCallbackList<>(); 16757 16758 public OnPermissionChangeListeners(Looper looper) { 16759 super(looper); 16760 } 16761 16762 @Override 16763 public void handleMessage(Message msg) { 16764 switch (msg.what) { 16765 case MSG_ON_PERMISSIONS_CHANGED: { 16766 final int uid = msg.arg1; 16767 handleOnPermissionsChanged(uid); 16768 } break; 16769 } 16770 } 16771 16772 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16773 mPermissionListeners.register(listener); 16774 16775 } 16776 16777 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16778 mPermissionListeners.unregister(listener); 16779 } 16780 16781 public void onPermissionsChanged(int uid) { 16782 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16783 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16784 } 16785 } 16786 16787 private void handleOnPermissionsChanged(int uid) { 16788 final int count = mPermissionListeners.beginBroadcast(); 16789 try { 16790 for (int i = 0; i < count; i++) { 16791 IOnPermissionsChangeListener callback = mPermissionListeners 16792 .getBroadcastItem(i); 16793 try { 16794 callback.onPermissionsChanged(uid); 16795 } catch (RemoteException e) { 16796 Log.e(TAG, "Permission listener is dead", e); 16797 } 16798 } 16799 } finally { 16800 mPermissionListeners.finishBroadcast(); 16801 } 16802 } 16803 } 16804 16805 private class PackageManagerInternalImpl extends PackageManagerInternal { 16806 @Override 16807 public void setLocationPackagesProvider(PackagesProvider provider) { 16808 synchronized (mPackages) { 16809 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16810 } 16811 } 16812 16813 @Override 16814 public void setImePackagesProvider(PackagesProvider provider) { 16815 synchronized (mPackages) { 16816 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16817 } 16818 } 16819 16820 @Override 16821 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16822 synchronized (mPackages) { 16823 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16824 } 16825 } 16826 16827 @Override 16828 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16829 synchronized (mPackages) { 16830 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16831 } 16832 } 16833 16834 @Override 16835 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16836 synchronized (mPackages) { 16837 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16838 } 16839 } 16840 16841 @Override 16842 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16843 synchronized (mPackages) { 16844 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16845 } 16846 } 16847 16848 @Override 16849 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16850 synchronized (mPackages) { 16851 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16852 } 16853 } 16854 16855 @Override 16856 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16857 synchronized (mPackages) { 16858 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16859 packageName, userId); 16860 } 16861 } 16862 16863 @Override 16864 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16865 synchronized (mPackages) { 16866 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16867 packageName, userId); 16868 } 16869 } 16870 @Override 16871 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16872 synchronized (mPackages) { 16873 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16874 packageName, userId); 16875 } 16876 } 16877 } 16878 16879 @Override 16880 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16881 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16882 synchronized (mPackages) { 16883 final long identity = Binder.clearCallingIdentity(); 16884 try { 16885 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16886 packageNames, userId); 16887 } finally { 16888 Binder.restoreCallingIdentity(identity); 16889 } 16890 } 16891 } 16892 16893 private static void enforceSystemOrPhoneCaller(String tag) { 16894 int callingUid = Binder.getCallingUid(); 16895 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16896 throw new SecurityException( 16897 "Cannot call " + tag + " from UID " + callingUid); 16898 } 16899 } 16900} 16901