PackageManagerService.java revision 27c24fb8b85c36298de053699b1967a808c6d308
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.Installer.DEXOPT_PUBLIC; 79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 87 88import android.Manifest; 89import android.app.ActivityManager; 90import android.app.ActivityManagerNative; 91import android.app.AppGlobals; 92import android.app.IActivityManager; 93import android.app.admin.IDevicePolicyManager; 94import android.app.backup.IBackupManager; 95import android.app.usage.UsageStats; 96import android.app.usage.UsageStatsManager; 97import android.content.BroadcastReceiver; 98import android.content.ComponentName; 99import android.content.Context; 100import android.content.IIntentReceiver; 101import android.content.Intent; 102import android.content.IntentFilter; 103import android.content.IntentSender; 104import android.content.IntentSender.SendIntentException; 105import android.content.ServiceConnection; 106import android.content.pm.ActivityInfo; 107import android.content.pm.ApplicationInfo; 108import android.content.pm.FeatureInfo; 109import android.content.pm.IOnPermissionsChangeListener; 110import android.content.pm.IPackageDataObserver; 111import android.content.pm.IPackageDeleteObserver; 112import android.content.pm.IPackageDeleteObserver2; 113import android.content.pm.IPackageInstallObserver2; 114import android.content.pm.IPackageInstaller; 115import android.content.pm.IPackageManager; 116import android.content.pm.IPackageMoveObserver; 117import android.content.pm.IPackageStatsObserver; 118import android.content.pm.InstrumentationInfo; 119import android.content.pm.IntentFilterVerificationInfo; 120import android.content.pm.KeySet; 121import android.content.pm.ManifestDigest; 122import android.content.pm.PackageCleanItem; 123import android.content.pm.PackageInfo; 124import android.content.pm.PackageInfoLite; 125import android.content.pm.PackageInstaller; 126import android.content.pm.PackageManager; 127import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 128import android.content.pm.PackageManagerInternal; 129import android.content.pm.PackageParser; 130import android.content.pm.PackageParser.ActivityIntentInfo; 131import android.content.pm.PackageParser.PackageLite; 132import android.content.pm.PackageParser.PackageParserException; 133import android.content.pm.PackageStats; 134import android.content.pm.PackageUserState; 135import android.content.pm.ParceledListSlice; 136import android.content.pm.PermissionGroupInfo; 137import android.content.pm.PermissionInfo; 138import android.content.pm.ProviderInfo; 139import android.content.pm.ResolveInfo; 140import android.content.pm.ServiceInfo; 141import android.content.pm.Signature; 142import android.content.pm.UserInfo; 143import android.content.pm.VerificationParams; 144import android.content.pm.VerifierDeviceIdentity; 145import android.content.pm.VerifierInfo; 146import android.content.res.Resources; 147import android.hardware.display.DisplayManager; 148import android.net.Uri; 149import android.os.Debug; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Environment; 154import android.os.Environment.UserEnvironment; 155import android.os.FileUtils; 156import android.os.Handler; 157import android.os.IBinder; 158import android.os.Looper; 159import android.os.Message; 160import android.os.Parcel; 161import android.os.ParcelFileDescriptor; 162import android.os.Process; 163import android.os.RemoteCallbackList; 164import android.os.RemoteException; 165import android.os.SELinux; 166import android.os.ServiceManager; 167import android.os.SystemClock; 168import android.os.SystemProperties; 169import android.os.Trace; 170import android.os.UserHandle; 171import android.os.UserManager; 172import android.os.storage.IMountService; 173import android.os.storage.MountServiceInternal; 174import android.os.storage.StorageEventListener; 175import android.os.storage.StorageManager; 176import android.os.storage.VolumeInfo; 177import android.os.storage.VolumeRecord; 178import android.security.KeyStore; 179import android.security.SystemKeyStore; 180import android.system.ErrnoException; 181import android.system.Os; 182import android.system.StructStat; 183import android.text.TextUtils; 184import android.text.format.DateUtils; 185import android.util.ArrayMap; 186import android.util.ArraySet; 187import android.util.AtomicFile; 188import android.util.DisplayMetrics; 189import android.util.EventLog; 190import android.util.ExceptionUtils; 191import android.util.Log; 192import android.util.LogPrinter; 193import android.util.MathUtils; 194import android.util.PrintStreamPrinter; 195import android.util.Slog; 196import android.util.SparseArray; 197import android.util.SparseBooleanArray; 198import android.util.SparseIntArray; 199import android.util.Xml; 200import android.view.Display; 201 202import dalvik.system.DexFile; 203import dalvik.system.VMRuntime; 204 205import libcore.io.IoUtils; 206import libcore.util.EmptyArray; 207 208import com.android.internal.R; 209import com.android.internal.annotations.GuardedBy; 210import com.android.internal.app.IMediaContainerService; 211import com.android.internal.app.ResolverActivity; 212import com.android.internal.content.NativeLibraryHelper; 213import com.android.internal.content.PackageHelper; 214import com.android.internal.os.IParcelFileDescriptorFactory; 215import com.android.internal.os.SomeArgs; 216import com.android.internal.os.Zygote; 217import com.android.internal.util.ArrayUtils; 218import com.android.internal.util.FastPrintWriter; 219import com.android.internal.util.FastXmlSerializer; 220import com.android.internal.util.IndentingPrintWriter; 221import com.android.internal.util.Preconditions; 222import com.android.server.EventLogTags; 223import com.android.server.FgThread; 224import com.android.server.IntentResolver; 225import com.android.server.LocalServices; 226import com.android.server.ServiceThread; 227import com.android.server.SystemConfig; 228import com.android.server.Watchdog; 229import com.android.server.pm.PermissionsState.PermissionState; 230import com.android.server.pm.Settings.DatabaseVersion; 231import com.android.server.pm.Settings.VersionInfo; 232import com.android.server.storage.DeviceStorageMonitorInternal; 233 234import org.xmlpull.v1.XmlPullParser; 235import org.xmlpull.v1.XmlPullParserException; 236import org.xmlpull.v1.XmlSerializer; 237 238import java.io.BufferedInputStream; 239import java.io.BufferedOutputStream; 240import java.io.BufferedReader; 241import java.io.ByteArrayInputStream; 242import java.io.ByteArrayOutputStream; 243import java.io.File; 244import java.io.FileDescriptor; 245import java.io.FileNotFoundException; 246import java.io.FileOutputStream; 247import java.io.FileReader; 248import java.io.FilenameFilter; 249import java.io.IOException; 250import java.io.InputStream; 251import java.io.PrintWriter; 252import java.nio.charset.StandardCharsets; 253import java.security.NoSuchAlgorithmException; 254import java.security.PublicKey; 255import java.security.cert.CertificateEncodingException; 256import java.security.cert.CertificateException; 257import java.text.SimpleDateFormat; 258import java.util.ArrayList; 259import java.util.Arrays; 260import java.util.Collection; 261import java.util.Collections; 262import java.util.Comparator; 263import java.util.Date; 264import java.util.Iterator; 265import java.util.List; 266import java.util.Map; 267import java.util.Objects; 268import java.util.Set; 269import java.util.concurrent.CountDownLatch; 270import java.util.concurrent.TimeUnit; 271import java.util.concurrent.atomic.AtomicBoolean; 272import java.util.concurrent.atomic.AtomicInteger; 273import java.util.concurrent.atomic.AtomicLong; 274 275/** 276 * Keep track of all those .apks everywhere. 277 * 278 * This is very central to the platform's security; please run the unit 279 * tests whenever making modifications here: 280 * 281runtest -c android.content.pm.PackageManagerTests frameworks-core 282 * 283 * {@hide} 284 */ 285public class PackageManagerService extends IPackageManager.Stub { 286 static final String TAG = "PackageManager"; 287 static final boolean DEBUG_SETTINGS = false; 288 static final boolean DEBUG_PREFERRED = false; 289 static final boolean DEBUG_UPGRADE = false; 290 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 291 private static final boolean DEBUG_BACKUP = false; 292 private static final boolean DEBUG_INSTALL = false; 293 private static final boolean DEBUG_REMOVE = false; 294 private static final boolean DEBUG_BROADCASTS = false; 295 private static final boolean DEBUG_SHOW_INFO = false; 296 private static final boolean DEBUG_PACKAGE_INFO = false; 297 private static final boolean DEBUG_INTENT_MATCHING = false; 298 private static final boolean DEBUG_PACKAGE_SCANNING = false; 299 private static final boolean DEBUG_VERIFY = false; 300 private static final boolean DEBUG_DEXOPT = false; 301 private static final boolean DEBUG_ABI_SELECTION = false; 302 303 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 304 305 private static final int RADIO_UID = Process.PHONE_UID; 306 private static final int LOG_UID = Process.LOG_UID; 307 private static final int NFC_UID = Process.NFC_UID; 308 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 309 private static final int SHELL_UID = Process.SHELL_UID; 310 311 // Cap the size of permission trees that 3rd party apps can define 312 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 313 314 // Suffix used during package installation when copying/moving 315 // package apks to install directory. 316 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 317 318 static final int SCAN_NO_DEX = 1<<1; 319 static final int SCAN_FORCE_DEX = 1<<2; 320 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 321 static final int SCAN_NEW_INSTALL = 1<<4; 322 static final int SCAN_NO_PATHS = 1<<5; 323 static final int SCAN_UPDATE_TIME = 1<<6; 324 static final int SCAN_DEFER_DEX = 1<<7; 325 static final int SCAN_BOOTING = 1<<8; 326 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 327 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 328 static final int SCAN_REPLACING = 1<<11; 329 static final int SCAN_REQUIRE_KNOWN = 1<<12; 330 static final int SCAN_MOVE = 1<<13; 331 static final int SCAN_INITIAL = 1<<14; 332 333 static final int REMOVE_CHATTY = 1<<16; 334 335 private static final int[] EMPTY_INT_ARRAY = new int[0]; 336 337 /** 338 * Timeout (in milliseconds) after which the watchdog should declare that 339 * our handler thread is wedged. The usual default for such things is one 340 * minute but we sometimes do very lengthy I/O operations on this thread, 341 * such as installing multi-gigabyte applications, so ours needs to be longer. 342 */ 343 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 344 345 /** 346 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 347 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 348 * settings entry if available, otherwise we use the hardcoded default. If it's been 349 * more than this long since the last fstrim, we force one during the boot sequence. 350 * 351 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 352 * one gets run at the next available charging+idle time. This final mandatory 353 * no-fstrim check kicks in only of the other scheduling criteria is never met. 354 */ 355 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 356 357 /** 358 * Whether verification is enabled by default. 359 */ 360 private static final boolean DEFAULT_VERIFY_ENABLE = true; 361 362 /** 363 * The default maximum time to wait for the verification agent to return in 364 * milliseconds. 365 */ 366 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 367 368 /** 369 * The default response for package verification timeout. 370 * 371 * This can be either PackageManager.VERIFICATION_ALLOW or 372 * PackageManager.VERIFICATION_REJECT. 373 */ 374 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 375 376 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 377 378 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 379 DEFAULT_CONTAINER_PACKAGE, 380 "com.android.defcontainer.DefaultContainerService"); 381 382 private static final String KILL_APP_REASON_GIDS_CHANGED = 383 "permission grant or revoke changed gids"; 384 385 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 386 "permissions revoked"; 387 388 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 389 390 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 391 392 /** Permission grant: not grant the permission. */ 393 private static final int GRANT_DENIED = 1; 394 395 /** Permission grant: grant the permission as an install permission. */ 396 private static final int GRANT_INSTALL = 2; 397 398 /** Permission grant: grant the permission as an install permission for a legacy app. */ 399 private static final int GRANT_INSTALL_LEGACY = 3; 400 401 /** Permission grant: grant the permission as a runtime one. */ 402 private static final int GRANT_RUNTIME = 4; 403 404 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 405 private static final int GRANT_UPGRADE = 5; 406 407 /** Canonical intent used to identify what counts as a "web browser" app */ 408 private static final Intent sBrowserIntent; 409 static { 410 sBrowserIntent = new Intent(); 411 sBrowserIntent.setAction(Intent.ACTION_VIEW); 412 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 413 sBrowserIntent.setData(Uri.parse("http:")); 414 } 415 416 final ServiceThread mHandlerThread; 417 418 final PackageHandler mHandler; 419 420 /** 421 * Messages for {@link #mHandler} that need to wait for system ready before 422 * being dispatched. 423 */ 424 private ArrayList<Message> mPostSystemReadyMessages; 425 426 final int mSdkVersion = Build.VERSION.SDK_INT; 427 428 final Context mContext; 429 final boolean mFactoryTest; 430 final boolean mOnlyCore; 431 final boolean mLazyDexOpt; 432 final long mDexOptLRUThresholdInMills; 433 final DisplayMetrics mMetrics; 434 final int mDefParseFlags; 435 final String[] mSeparateProcesses; 436 final boolean mIsUpgrade; 437 438 // This is where all application persistent data goes. 439 final File mAppDataDir; 440 441 // This is where all application persistent data goes for secondary users. 442 final File mUserAppDataDir; 443 444 /** The location for ASEC container files on internal storage. */ 445 final String mAsecInternalPath; 446 447 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 448 // LOCK HELD. Can be called with mInstallLock held. 449 @GuardedBy("mInstallLock") 450 final Installer mInstaller; 451 452 /** Directory where installed third-party apps stored */ 453 final File mAppInstallDir; 454 455 /** 456 * Directory to which applications installed internally have their 457 * 32 bit native libraries copied. 458 */ 459 private File mAppLib32InstallDir; 460 461 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 462 // apps. 463 final File mDrmAppPrivateInstallDir; 464 465 // ---------------------------------------------------------------- 466 467 // Lock for state used when installing and doing other long running 468 // operations. Methods that must be called with this lock held have 469 // the suffix "LI". 470 final Object mInstallLock = new Object(); 471 472 // ---------------------------------------------------------------- 473 474 // Keys are String (package name), values are Package. This also serves 475 // as the lock for the global state. Methods that must be called with 476 // this lock held have the prefix "LP". 477 @GuardedBy("mPackages") 478 final ArrayMap<String, PackageParser.Package> mPackages = 479 new ArrayMap<String, PackageParser.Package>(); 480 481 // Tracks available target package names -> overlay package paths. 482 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 483 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 484 485 /** 486 * Tracks new system packages [received in an OTA] that we expect to 487 * find updated user-installed versions. Keys are package name, values 488 * are package location. 489 */ 490 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 491 492 /** 493 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 494 */ 495 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 496 /** 497 * Whether or not system app permissions should be promoted from install to runtime. 498 */ 499 boolean mPromoteSystemApps; 500 501 final Settings mSettings; 502 boolean mRestoredSettings; 503 504 // System configuration read by SystemConfig. 505 final int[] mGlobalGids; 506 final SparseArray<ArraySet<String>> mSystemPermissions; 507 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 508 509 // If mac_permissions.xml was found for seinfo labeling. 510 boolean mFoundPolicyFile; 511 512 // If a recursive restorecon of /data/data/<pkg> is needed. 513 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 514 515 public static final class SharedLibraryEntry { 516 public final String path; 517 public final String apk; 518 519 SharedLibraryEntry(String _path, String _apk) { 520 path = _path; 521 apk = _apk; 522 } 523 } 524 525 // Currently known shared libraries. 526 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 527 new ArrayMap<String, SharedLibraryEntry>(); 528 529 // All available activities, for your resolving pleasure. 530 final ActivityIntentResolver mActivities = 531 new ActivityIntentResolver(); 532 533 // All available receivers, for your resolving pleasure. 534 final ActivityIntentResolver mReceivers = 535 new ActivityIntentResolver(); 536 537 // All available services, for your resolving pleasure. 538 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 539 540 // All available providers, for your resolving pleasure. 541 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 542 543 // Mapping from provider base names (first directory in content URI codePath) 544 // to the provider information. 545 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 546 new ArrayMap<String, PackageParser.Provider>(); 547 548 // Mapping from instrumentation class names to info about them. 549 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 550 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 551 552 // Mapping from permission names to info about them. 553 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 554 new ArrayMap<String, PackageParser.PermissionGroup>(); 555 556 // Packages whose data we have transfered into another package, thus 557 // should no longer exist. 558 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 559 560 // Broadcast actions that are only available to the system. 561 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 562 563 /** List of packages waiting for verification. */ 564 final SparseArray<PackageVerificationState> mPendingVerification 565 = new SparseArray<PackageVerificationState>(); 566 567 /** Set of packages associated with each app op permission. */ 568 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 569 570 final PackageInstallerService mInstallerService; 571 572 private final PackageDexOptimizer mPackageDexOptimizer; 573 574 private AtomicInteger mNextMoveId = new AtomicInteger(); 575 private final MoveCallbacks mMoveCallbacks; 576 577 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 578 579 // Cache of users who need badging. 580 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 581 582 /** Token for keys in mPendingVerification. */ 583 private int mPendingVerificationToken = 0; 584 585 volatile boolean mSystemReady; 586 volatile boolean mSafeMode; 587 volatile boolean mHasSystemUidErrors; 588 589 ApplicationInfo mAndroidApplication; 590 final ActivityInfo mResolveActivity = new ActivityInfo(); 591 final ResolveInfo mResolveInfo = new ResolveInfo(); 592 ComponentName mResolveComponentName; 593 PackageParser.Package mPlatformPackage; 594 ComponentName mCustomResolverComponentName; 595 596 boolean mResolverReplaced = false; 597 598 private final ComponentName mIntentFilterVerifierComponent; 599 private int mIntentFilterVerificationToken = 0; 600 601 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 602 = new SparseArray<IntentFilterVerificationState>(); 603 604 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 605 new DefaultPermissionGrantPolicy(this); 606 607 private static class IFVerificationParams { 608 PackageParser.Package pkg; 609 boolean replacing; 610 int userId; 611 int verifierUid; 612 613 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 614 int _userId, int _verifierUid) { 615 pkg = _pkg; 616 replacing = _replacing; 617 userId = _userId; 618 replacing = _replacing; 619 verifierUid = _verifierUid; 620 } 621 } 622 623 private interface IntentFilterVerifier<T extends IntentFilter> { 624 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 625 T filter, String packageName); 626 void startVerifications(int userId); 627 void receiveVerificationResponse(int verificationId); 628 } 629 630 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 631 private Context mContext; 632 private ComponentName mIntentFilterVerifierComponent; 633 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 634 635 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 636 mContext = context; 637 mIntentFilterVerifierComponent = verifierComponent; 638 } 639 640 private String getDefaultScheme() { 641 return IntentFilter.SCHEME_HTTPS; 642 } 643 644 @Override 645 public void startVerifications(int userId) { 646 // Launch verifications requests 647 int count = mCurrentIntentFilterVerifications.size(); 648 for (int n=0; n<count; n++) { 649 int verificationId = mCurrentIntentFilterVerifications.get(n); 650 final IntentFilterVerificationState ivs = 651 mIntentFilterVerificationStates.get(verificationId); 652 653 String packageName = ivs.getPackageName(); 654 655 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 656 final int filterCount = filters.size(); 657 ArraySet<String> domainsSet = new ArraySet<>(); 658 for (int m=0; m<filterCount; m++) { 659 PackageParser.ActivityIntentInfo filter = filters.get(m); 660 domainsSet.addAll(filter.getHostsList()); 661 } 662 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 663 synchronized (mPackages) { 664 if (mSettings.createIntentFilterVerificationIfNeededLPw( 665 packageName, domainsList) != null) { 666 scheduleWriteSettingsLocked(); 667 } 668 } 669 sendVerificationRequest(userId, verificationId, ivs); 670 } 671 mCurrentIntentFilterVerifications.clear(); 672 } 673 674 private void sendVerificationRequest(int userId, int verificationId, 675 IntentFilterVerificationState ivs) { 676 677 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 678 verificationIntent.putExtra( 679 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 680 verificationId); 681 verificationIntent.putExtra( 682 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 683 getDefaultScheme()); 684 verificationIntent.putExtra( 685 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 686 ivs.getHostsString()); 687 verificationIntent.putExtra( 688 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 689 ivs.getPackageName()); 690 verificationIntent.setComponent(mIntentFilterVerifierComponent); 691 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 692 693 UserHandle user = new UserHandle(userId); 694 mContext.sendBroadcastAsUser(verificationIntent, user); 695 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 696 "Sending IntentFilter verification broadcast"); 697 } 698 699 public void receiveVerificationResponse(int verificationId) { 700 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 701 702 final boolean verified = ivs.isVerified(); 703 704 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 705 final int count = filters.size(); 706 if (DEBUG_DOMAIN_VERIFICATION) { 707 Slog.i(TAG, "Received verification response " + verificationId 708 + " for " + count + " filters, verified=" + verified); 709 } 710 for (int n=0; n<count; n++) { 711 PackageParser.ActivityIntentInfo filter = filters.get(n); 712 filter.setVerified(verified); 713 714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 715 + " verified with result:" + verified + " and hosts:" 716 + ivs.getHostsString()); 717 } 718 719 mIntentFilterVerificationStates.remove(verificationId); 720 721 final String packageName = ivs.getPackageName(); 722 IntentFilterVerificationInfo ivi = null; 723 724 synchronized (mPackages) { 725 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 726 } 727 if (ivi == null) { 728 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 729 + verificationId + " packageName:" + packageName); 730 return; 731 } 732 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 733 "Updating IntentFilterVerificationInfo for package " + packageName 734 +" verificationId:" + verificationId); 735 736 synchronized (mPackages) { 737 if (verified) { 738 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 739 } else { 740 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 741 } 742 scheduleWriteSettingsLocked(); 743 744 final int userId = ivs.getUserId(); 745 if (userId != UserHandle.USER_ALL) { 746 final int userStatus = 747 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 748 749 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 750 boolean needUpdate = false; 751 752 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 753 // already been set by the User thru the Disambiguation dialog 754 switch (userStatus) { 755 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 756 if (verified) { 757 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 758 } else { 759 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 760 } 761 needUpdate = true; 762 break; 763 764 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 765 if (verified) { 766 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 767 needUpdate = true; 768 } 769 break; 770 771 default: 772 // Nothing to do 773 } 774 775 if (needUpdate) { 776 mSettings.updateIntentFilterVerificationStatusLPw( 777 packageName, updatedStatus, userId); 778 scheduleWritePackageRestrictionsLocked(userId); 779 } 780 } 781 } 782 } 783 784 @Override 785 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 786 ActivityIntentInfo filter, String packageName) { 787 if (!hasValidDomains(filter)) { 788 return false; 789 } 790 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 791 if (ivs == null) { 792 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 793 packageName); 794 } 795 if (DEBUG_DOMAIN_VERIFICATION) { 796 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 797 } 798 ivs.addFilter(filter); 799 return true; 800 } 801 802 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 803 int userId, int verificationId, String packageName) { 804 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 805 verifierUid, userId, packageName); 806 ivs.setPendingState(); 807 synchronized (mPackages) { 808 mIntentFilterVerificationStates.append(verificationId, ivs); 809 mCurrentIntentFilterVerifications.add(verificationId); 810 } 811 return ivs; 812 } 813 } 814 815 private static boolean hasValidDomains(ActivityIntentInfo filter) { 816 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 817 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 818 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 819 } 820 821 private IntentFilterVerifier mIntentFilterVerifier; 822 823 // Set of pending broadcasts for aggregating enable/disable of components. 824 static class PendingPackageBroadcasts { 825 // for each user id, a map of <package name -> components within that package> 826 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 827 828 public PendingPackageBroadcasts() { 829 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 830 } 831 832 public ArrayList<String> get(int userId, String packageName) { 833 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 834 return packages.get(packageName); 835 } 836 837 public void put(int userId, String packageName, ArrayList<String> components) { 838 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 839 packages.put(packageName, components); 840 } 841 842 public void remove(int userId, String packageName) { 843 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 844 if (packages != null) { 845 packages.remove(packageName); 846 } 847 } 848 849 public void remove(int userId) { 850 mUidMap.remove(userId); 851 } 852 853 public int userIdCount() { 854 return mUidMap.size(); 855 } 856 857 public int userIdAt(int n) { 858 return mUidMap.keyAt(n); 859 } 860 861 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 862 return mUidMap.get(userId); 863 } 864 865 public int size() { 866 // total number of pending broadcast entries across all userIds 867 int num = 0; 868 for (int i = 0; i< mUidMap.size(); i++) { 869 num += mUidMap.valueAt(i).size(); 870 } 871 return num; 872 } 873 874 public void clear() { 875 mUidMap.clear(); 876 } 877 878 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 879 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 880 if (map == null) { 881 map = new ArrayMap<String, ArrayList<String>>(); 882 mUidMap.put(userId, map); 883 } 884 return map; 885 } 886 } 887 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 888 889 // Service Connection to remote media container service to copy 890 // package uri's from external media onto secure containers 891 // or internal storage. 892 private IMediaContainerService mContainerService = null; 893 894 static final int SEND_PENDING_BROADCAST = 1; 895 static final int MCS_BOUND = 3; 896 static final int END_COPY = 4; 897 static final int INIT_COPY = 5; 898 static final int MCS_UNBIND = 6; 899 static final int START_CLEANING_PACKAGE = 7; 900 static final int FIND_INSTALL_LOC = 8; 901 static final int POST_INSTALL = 9; 902 static final int MCS_RECONNECT = 10; 903 static final int MCS_GIVE_UP = 11; 904 static final int UPDATED_MEDIA_STATUS = 12; 905 static final int WRITE_SETTINGS = 13; 906 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 907 static final int PACKAGE_VERIFIED = 15; 908 static final int CHECK_PENDING_VERIFICATION = 16; 909 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 910 static final int INTENT_FILTER_VERIFIED = 18; 911 912 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 913 914 // Delay time in millisecs 915 static final int BROADCAST_DELAY = 10 * 1000; 916 917 static UserManagerService sUserManager; 918 919 // Stores a list of users whose package restrictions file needs to be updated 920 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 921 922 final private DefaultContainerConnection mDefContainerConn = 923 new DefaultContainerConnection(); 924 class DefaultContainerConnection implements ServiceConnection { 925 public void onServiceConnected(ComponentName name, IBinder service) { 926 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 927 IMediaContainerService imcs = 928 IMediaContainerService.Stub.asInterface(service); 929 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 930 } 931 932 public void onServiceDisconnected(ComponentName name) { 933 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 934 } 935 } 936 937 // Recordkeeping of restore-after-install operations that are currently in flight 938 // between the Package Manager and the Backup Manager 939 class PostInstallData { 940 public InstallArgs args; 941 public PackageInstalledInfo res; 942 943 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 944 args = _a; 945 res = _r; 946 } 947 } 948 949 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 950 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 951 952 // XML tags for backup/restore of various bits of state 953 private static final String TAG_PREFERRED_BACKUP = "pa"; 954 private static final String TAG_DEFAULT_APPS = "da"; 955 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 956 957 final String mRequiredVerifierPackage; 958 final String mRequiredInstallerPackage; 959 960 private final PackageUsage mPackageUsage = new PackageUsage(); 961 962 private class PackageUsage { 963 private static final int WRITE_INTERVAL 964 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 965 966 private final Object mFileLock = new Object(); 967 private final AtomicLong mLastWritten = new AtomicLong(0); 968 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 969 970 private boolean mIsHistoricalPackageUsageAvailable = true; 971 972 boolean isHistoricalPackageUsageAvailable() { 973 return mIsHistoricalPackageUsageAvailable; 974 } 975 976 void write(boolean force) { 977 if (force) { 978 writeInternal(); 979 return; 980 } 981 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 982 && !DEBUG_DEXOPT) { 983 return; 984 } 985 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 986 new Thread("PackageUsage_DiskWriter") { 987 @Override 988 public void run() { 989 try { 990 writeInternal(); 991 } finally { 992 mBackgroundWriteRunning.set(false); 993 } 994 } 995 }.start(); 996 } 997 } 998 999 private void writeInternal() { 1000 synchronized (mPackages) { 1001 synchronized (mFileLock) { 1002 AtomicFile file = getFile(); 1003 FileOutputStream f = null; 1004 try { 1005 f = file.startWrite(); 1006 BufferedOutputStream out = new BufferedOutputStream(f); 1007 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1008 StringBuilder sb = new StringBuilder(); 1009 for (PackageParser.Package pkg : mPackages.values()) { 1010 if (pkg.mLastPackageUsageTimeInMills == 0) { 1011 continue; 1012 } 1013 sb.setLength(0); 1014 sb.append(pkg.packageName); 1015 sb.append(' '); 1016 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1017 sb.append('\n'); 1018 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1019 } 1020 out.flush(); 1021 file.finishWrite(f); 1022 } catch (IOException e) { 1023 if (f != null) { 1024 file.failWrite(f); 1025 } 1026 Log.e(TAG, "Failed to write package usage times", e); 1027 } 1028 } 1029 } 1030 mLastWritten.set(SystemClock.elapsedRealtime()); 1031 } 1032 1033 void readLP() { 1034 synchronized (mFileLock) { 1035 AtomicFile file = getFile(); 1036 BufferedInputStream in = null; 1037 try { 1038 in = new BufferedInputStream(file.openRead()); 1039 StringBuffer sb = new StringBuffer(); 1040 while (true) { 1041 String packageName = readToken(in, sb, ' '); 1042 if (packageName == null) { 1043 break; 1044 } 1045 String timeInMillisString = readToken(in, sb, '\n'); 1046 if (timeInMillisString == null) { 1047 throw new IOException("Failed to find last usage time for package " 1048 + packageName); 1049 } 1050 PackageParser.Package pkg = mPackages.get(packageName); 1051 if (pkg == null) { 1052 continue; 1053 } 1054 long timeInMillis; 1055 try { 1056 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1057 } catch (NumberFormatException e) { 1058 throw new IOException("Failed to parse " + timeInMillisString 1059 + " as a long.", e); 1060 } 1061 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1062 } 1063 } catch (FileNotFoundException expected) { 1064 mIsHistoricalPackageUsageAvailable = false; 1065 } catch (IOException e) { 1066 Log.w(TAG, "Failed to read package usage times", e); 1067 } finally { 1068 IoUtils.closeQuietly(in); 1069 } 1070 } 1071 mLastWritten.set(SystemClock.elapsedRealtime()); 1072 } 1073 1074 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1075 throws IOException { 1076 sb.setLength(0); 1077 while (true) { 1078 int ch = in.read(); 1079 if (ch == -1) { 1080 if (sb.length() == 0) { 1081 return null; 1082 } 1083 throw new IOException("Unexpected EOF"); 1084 } 1085 if (ch == endOfToken) { 1086 return sb.toString(); 1087 } 1088 sb.append((char)ch); 1089 } 1090 } 1091 1092 private AtomicFile getFile() { 1093 File dataDir = Environment.getDataDirectory(); 1094 File systemDir = new File(dataDir, "system"); 1095 File fname = new File(systemDir, "package-usage.list"); 1096 return new AtomicFile(fname); 1097 } 1098 } 1099 1100 class PackageHandler extends Handler { 1101 private boolean mBound = false; 1102 final ArrayList<HandlerParams> mPendingInstalls = 1103 new ArrayList<HandlerParams>(); 1104 1105 private boolean connectToService() { 1106 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1107 " DefaultContainerService"); 1108 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1111 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 mBound = true; 1114 return true; 1115 } 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1117 return false; 1118 } 1119 1120 private void disconnectService() { 1121 mContainerService = null; 1122 mBound = false; 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1124 mContext.unbindService(mDefContainerConn); 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 1128 PackageHandler(Looper looper) { 1129 super(looper); 1130 } 1131 1132 public void handleMessage(Message msg) { 1133 try { 1134 doHandleMessage(msg); 1135 } finally { 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } 1138 } 1139 1140 void doHandleMessage(Message msg) { 1141 switch (msg.what) { 1142 case INIT_COPY: { 1143 HandlerParams params = (HandlerParams) msg.obj; 1144 int idx = mPendingInstalls.size(); 1145 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1146 // If a bind was already initiated we dont really 1147 // need to do anything. The pending install 1148 // will be processed later on. 1149 if (!mBound) { 1150 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1151 System.identityHashCode(mHandler)); 1152 // If this is the only one pending we might 1153 // have to bind to the service again. 1154 if (!connectToService()) { 1155 Slog.e(TAG, "Failed to bind to media container service"); 1156 params.serviceError(); 1157 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1158 System.identityHashCode(mHandler)); 1159 if (params.traceMethod != null) { 1160 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1161 params.traceCookie); 1162 } 1163 return; 1164 } else { 1165 // Once we bind to the service, the first 1166 // pending request will be processed. 1167 mPendingInstalls.add(idx, params); 1168 } 1169 } else { 1170 mPendingInstalls.add(idx, params); 1171 // Already bound to the service. Just make 1172 // sure we trigger off processing the first request. 1173 if (idx == 0) { 1174 mHandler.sendEmptyMessage(MCS_BOUND); 1175 } 1176 } 1177 break; 1178 } 1179 case MCS_BOUND: { 1180 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1181 if (msg.obj != null) { 1182 mContainerService = (IMediaContainerService) msg.obj; 1183 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1184 System.identityHashCode(mHandler)); 1185 } 1186 if (mContainerService == null) { 1187 if (!mBound) { 1188 // Something seriously wrong since we are not bound and we are not 1189 // waiting for connection. Bail out. 1190 Slog.e(TAG, "Cannot bind to media container service"); 1191 for (HandlerParams params : mPendingInstalls) { 1192 // Indicate service bind error 1193 params.serviceError(); 1194 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1195 System.identityHashCode(params)); 1196 if (params.traceMethod != null) { 1197 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1198 params.traceMethod, params.traceCookie); 1199 } 1200 return; 1201 } 1202 mPendingInstalls.clear(); 1203 } else { 1204 Slog.w(TAG, "Waiting to connect to media container service"); 1205 } 1206 } else if (mPendingInstalls.size() > 0) { 1207 HandlerParams params = mPendingInstalls.get(0); 1208 if (params != null) { 1209 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1210 System.identityHashCode(params)); 1211 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1212 if (params.startCopy()) { 1213 // We are done... look for more work or to 1214 // go idle. 1215 if (DEBUG_SD_INSTALL) Log.i(TAG, 1216 "Checking for more work or unbind..."); 1217 // Delete pending install 1218 if (mPendingInstalls.size() > 0) { 1219 mPendingInstalls.remove(0); 1220 } 1221 if (mPendingInstalls.size() == 0) { 1222 if (mBound) { 1223 if (DEBUG_SD_INSTALL) Log.i(TAG, 1224 "Posting delayed MCS_UNBIND"); 1225 removeMessages(MCS_UNBIND); 1226 Message ubmsg = obtainMessage(MCS_UNBIND); 1227 // Unbind after a little delay, to avoid 1228 // continual thrashing. 1229 sendMessageDelayed(ubmsg, 10000); 1230 } 1231 } else { 1232 // There are more pending requests in queue. 1233 // Just post MCS_BOUND message to trigger processing 1234 // of next pending install. 1235 if (DEBUG_SD_INSTALL) Log.i(TAG, 1236 "Posting MCS_BOUND for next work"); 1237 mHandler.sendEmptyMessage(MCS_BOUND); 1238 } 1239 } 1240 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1241 } 1242 } else { 1243 // Should never happen ideally. 1244 Slog.w(TAG, "Empty queue"); 1245 } 1246 break; 1247 } 1248 case MCS_RECONNECT: { 1249 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1250 if (mPendingInstalls.size() > 0) { 1251 if (mBound) { 1252 disconnectService(); 1253 } 1254 if (!connectToService()) { 1255 Slog.e(TAG, "Failed to bind to media container service"); 1256 for (HandlerParams params : mPendingInstalls) { 1257 // Indicate service bind error 1258 params.serviceError(); 1259 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1260 System.identityHashCode(params)); 1261 } 1262 mPendingInstalls.clear(); 1263 } 1264 } 1265 break; 1266 } 1267 case MCS_UNBIND: { 1268 // If there is no actual work left, then time to unbind. 1269 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1270 1271 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1272 if (mBound) { 1273 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1274 1275 disconnectService(); 1276 } 1277 } else if (mPendingInstalls.size() > 0) { 1278 // There are more pending requests in queue. 1279 // Just post MCS_BOUND message to trigger processing 1280 // of next pending install. 1281 mHandler.sendEmptyMessage(MCS_BOUND); 1282 } 1283 1284 break; 1285 } 1286 case MCS_GIVE_UP: { 1287 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1288 HandlerParams params = mPendingInstalls.remove(0); 1289 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1290 System.identityHashCode(params)); 1291 break; 1292 } 1293 case SEND_PENDING_BROADCAST: { 1294 String packages[]; 1295 ArrayList<String> components[]; 1296 int size = 0; 1297 int uids[]; 1298 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1299 synchronized (mPackages) { 1300 if (mPendingBroadcasts == null) { 1301 return; 1302 } 1303 size = mPendingBroadcasts.size(); 1304 if (size <= 0) { 1305 // Nothing to be done. Just return 1306 return; 1307 } 1308 packages = new String[size]; 1309 components = new ArrayList[size]; 1310 uids = new int[size]; 1311 int i = 0; // filling out the above arrays 1312 1313 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1314 int packageUserId = mPendingBroadcasts.userIdAt(n); 1315 Iterator<Map.Entry<String, ArrayList<String>>> it 1316 = mPendingBroadcasts.packagesForUserId(packageUserId) 1317 .entrySet().iterator(); 1318 while (it.hasNext() && i < size) { 1319 Map.Entry<String, ArrayList<String>> ent = it.next(); 1320 packages[i] = ent.getKey(); 1321 components[i] = ent.getValue(); 1322 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1323 uids[i] = (ps != null) 1324 ? UserHandle.getUid(packageUserId, ps.appId) 1325 : -1; 1326 i++; 1327 } 1328 } 1329 size = i; 1330 mPendingBroadcasts.clear(); 1331 } 1332 // Send broadcasts 1333 for (int i = 0; i < size; i++) { 1334 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 break; 1338 } 1339 case START_CLEANING_PACKAGE: { 1340 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1341 final String packageName = (String)msg.obj; 1342 final int userId = msg.arg1; 1343 final boolean andCode = msg.arg2 != 0; 1344 synchronized (mPackages) { 1345 if (userId == UserHandle.USER_ALL) { 1346 int[] users = sUserManager.getUserIds(); 1347 for (int user : users) { 1348 mSettings.addPackageToCleanLPw( 1349 new PackageCleanItem(user, packageName, andCode)); 1350 } 1351 } else { 1352 mSettings.addPackageToCleanLPw( 1353 new PackageCleanItem(userId, packageName, andCode)); 1354 } 1355 } 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 startCleaningPackages(); 1358 } break; 1359 case POST_INSTALL: { 1360 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1361 PostInstallData data = mRunningInstalls.get(msg.arg1); 1362 mRunningInstalls.delete(msg.arg1); 1363 boolean deleteOld = false; 1364 1365 if (data != null) { 1366 InstallArgs args = data.args; 1367 PackageInstalledInfo res = data.res; 1368 1369 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1370 final String packageName = res.pkg.applicationInfo.packageName; 1371 res.removedInfo.sendBroadcast(false, true, false); 1372 Bundle extras = new Bundle(1); 1373 extras.putInt(Intent.EXTRA_UID, res.uid); 1374 1375 // Now that we successfully installed the package, grant runtime 1376 // permissions if requested before broadcasting the install. 1377 if ((args.installFlags 1378 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1379 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1380 args.installGrantPermissions); 1381 } 1382 1383 // Determine the set of users who are adding this 1384 // package for the first time vs. those who are seeing 1385 // an update. 1386 int[] firstUsers; 1387 int[] updateUsers = new int[0]; 1388 if (res.origUsers == null || res.origUsers.length == 0) { 1389 firstUsers = res.newUsers; 1390 } else { 1391 firstUsers = new int[0]; 1392 for (int i=0; i<res.newUsers.length; i++) { 1393 int user = res.newUsers[i]; 1394 boolean isNew = true; 1395 for (int j=0; j<res.origUsers.length; j++) { 1396 if (res.origUsers[j] == user) { 1397 isNew = false; 1398 break; 1399 } 1400 } 1401 if (isNew) { 1402 int[] newFirst = new int[firstUsers.length+1]; 1403 System.arraycopy(firstUsers, 0, newFirst, 0, 1404 firstUsers.length); 1405 newFirst[firstUsers.length] = user; 1406 firstUsers = newFirst; 1407 } else { 1408 int[] newUpdate = new int[updateUsers.length+1]; 1409 System.arraycopy(updateUsers, 0, newUpdate, 0, 1410 updateUsers.length); 1411 newUpdate[updateUsers.length] = user; 1412 updateUsers = newUpdate; 1413 } 1414 } 1415 } 1416 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1417 packageName, extras, null, null, firstUsers); 1418 final boolean update = res.removedInfo.removedPackage != null; 1419 if (update) { 1420 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1421 } 1422 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1423 packageName, extras, null, null, updateUsers); 1424 if (update) { 1425 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1426 packageName, extras, null, null, updateUsers); 1427 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1428 null, null, packageName, null, updateUsers); 1429 1430 // treat asec-hosted packages like removable media on upgrade 1431 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1432 if (DEBUG_INSTALL) { 1433 Slog.i(TAG, "upgrading pkg " + res.pkg 1434 + " is ASEC-hosted -> AVAILABLE"); 1435 } 1436 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1437 ArrayList<String> pkgList = new ArrayList<String>(1); 1438 pkgList.add(packageName); 1439 sendResourcesChangedBroadcast(true, true, 1440 pkgList,uidArray, null); 1441 } 1442 } 1443 if (res.removedInfo.args != null) { 1444 // Remove the replaced package's older resources safely now 1445 deleteOld = true; 1446 } 1447 1448 // If this app is a browser and it's newly-installed for some 1449 // users, clear any default-browser state in those users 1450 if (firstUsers.length > 0) { 1451 // the app's nature doesn't depend on the user, so we can just 1452 // check its browser nature in any user and generalize. 1453 if (packageIsBrowser(packageName, firstUsers[0])) { 1454 synchronized (mPackages) { 1455 for (int userId : firstUsers) { 1456 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1457 } 1458 } 1459 } 1460 } 1461 // Log current value of "unknown sources" setting 1462 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1463 getUnknownSourcesSettings()); 1464 } 1465 // Force a gc to clear up things 1466 Runtime.getRuntime().gc(); 1467 // We delete after a gc for applications on sdcard. 1468 if (deleteOld) { 1469 synchronized (mInstallLock) { 1470 res.removedInfo.args.doPostDeleteLI(true); 1471 } 1472 } 1473 if (args.observer != null) { 1474 try { 1475 Bundle extras = extrasForInstallResult(res); 1476 args.observer.onPackageInstalled(res.name, res.returnCode, 1477 res.returnMsg, extras); 1478 } catch (RemoteException e) { 1479 Slog.i(TAG, "Observer no longer exists."); 1480 } 1481 } 1482 if (args.traceMethod != null) { 1483 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1484 args.traceCookie); 1485 } 1486 return; 1487 } else { 1488 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1489 } 1490 1491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1492 } break; 1493 case UPDATED_MEDIA_STATUS: { 1494 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1495 boolean reportStatus = msg.arg1 == 1; 1496 boolean doGc = msg.arg2 == 1; 1497 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1498 if (doGc) { 1499 // Force a gc to clear up stale containers. 1500 Runtime.getRuntime().gc(); 1501 } 1502 if (msg.obj != null) { 1503 @SuppressWarnings("unchecked") 1504 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1506 // Unload containers 1507 unloadAllContainers(args); 1508 } 1509 if (reportStatus) { 1510 try { 1511 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1512 PackageHelper.getMountService().finishMediaUpdate(); 1513 } catch (RemoteException e) { 1514 Log.e(TAG, "MountService not running?"); 1515 } 1516 } 1517 } break; 1518 case WRITE_SETTINGS: { 1519 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1520 synchronized (mPackages) { 1521 removeMessages(WRITE_SETTINGS); 1522 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1523 mSettings.writeLPr(); 1524 mDirtyUsers.clear(); 1525 } 1526 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1527 } break; 1528 case WRITE_PACKAGE_RESTRICTIONS: { 1529 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1530 synchronized (mPackages) { 1531 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1532 for (int userId : mDirtyUsers) { 1533 mSettings.writePackageRestrictionsLPr(userId); 1534 } 1535 mDirtyUsers.clear(); 1536 } 1537 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1538 } break; 1539 case CHECK_PENDING_VERIFICATION: { 1540 final int verificationId = msg.arg1; 1541 final PackageVerificationState state = mPendingVerification.get(verificationId); 1542 1543 if ((state != null) && !state.timeoutExtended()) { 1544 final InstallArgs args = state.getInstallArgs(); 1545 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1546 1547 Slog.i(TAG, "Verification timed out for " + originUri); 1548 mPendingVerification.remove(verificationId); 1549 1550 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1551 1552 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1553 Slog.i(TAG, "Continuing with installation of " + originUri); 1554 state.setVerifierResponse(Binder.getCallingUid(), 1555 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1556 broadcastPackageVerified(verificationId, originUri, 1557 PackageManager.VERIFICATION_ALLOW, 1558 state.getInstallArgs().getUser()); 1559 try { 1560 ret = args.copyApk(mContainerService, true); 1561 } catch (RemoteException e) { 1562 Slog.e(TAG, "Could not contact the ContainerService"); 1563 } 1564 } else { 1565 broadcastPackageVerified(verificationId, originUri, 1566 PackageManager.VERIFICATION_REJECT, 1567 state.getInstallArgs().getUser()); 1568 } 1569 1570 Trace.asyncTraceEnd( 1571 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1572 1573 processPendingInstall(args, ret); 1574 mHandler.sendEmptyMessage(MCS_UNBIND); 1575 } 1576 break; 1577 } 1578 case PACKAGE_VERIFIED: { 1579 final int verificationId = msg.arg1; 1580 1581 final PackageVerificationState state = mPendingVerification.get(verificationId); 1582 if (state == null) { 1583 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1584 break; 1585 } 1586 1587 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1588 1589 state.setVerifierResponse(response.callerUid, response.code); 1590 1591 if (state.isVerificationComplete()) { 1592 mPendingVerification.remove(verificationId); 1593 1594 final InstallArgs args = state.getInstallArgs(); 1595 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1596 1597 int ret; 1598 if (state.isInstallAllowed()) { 1599 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1600 broadcastPackageVerified(verificationId, originUri, 1601 response.code, state.getInstallArgs().getUser()); 1602 try { 1603 ret = args.copyApk(mContainerService, true); 1604 } catch (RemoteException e) { 1605 Slog.e(TAG, "Could not contact the ContainerService"); 1606 } 1607 } else { 1608 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1609 } 1610 1611 Trace.asyncTraceEnd( 1612 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1613 1614 processPendingInstall(args, ret); 1615 mHandler.sendEmptyMessage(MCS_UNBIND); 1616 } 1617 1618 break; 1619 } 1620 case START_INTENT_FILTER_VERIFICATIONS: { 1621 IFVerificationParams params = (IFVerificationParams) msg.obj; 1622 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1623 params.replacing, params.pkg); 1624 break; 1625 } 1626 case INTENT_FILTER_VERIFIED: { 1627 final int verificationId = msg.arg1; 1628 1629 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1630 verificationId); 1631 if (state == null) { 1632 Slog.w(TAG, "Invalid IntentFilter verification token " 1633 + verificationId + " received"); 1634 break; 1635 } 1636 1637 final int userId = state.getUserId(); 1638 1639 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1640 "Processing IntentFilter verification with token:" 1641 + verificationId + " and userId:" + userId); 1642 1643 final IntentFilterVerificationResponse response = 1644 (IntentFilterVerificationResponse) msg.obj; 1645 1646 state.setVerifierResponse(response.callerUid, response.code); 1647 1648 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1649 "IntentFilter verification with token:" + verificationId 1650 + " and userId:" + userId 1651 + " is settings verifier response with response code:" 1652 + response.code); 1653 1654 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1655 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1656 + response.getFailedDomainsString()); 1657 } 1658 1659 if (state.isVerificationComplete()) { 1660 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1661 } else { 1662 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1663 "IntentFilter verification with token:" + verificationId 1664 + " was not said to be complete"); 1665 } 1666 1667 break; 1668 } 1669 } 1670 } 1671 } 1672 1673 private StorageEventListener mStorageListener = new StorageEventListener() { 1674 @Override 1675 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1676 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1677 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1678 final String volumeUuid = vol.getFsUuid(); 1679 1680 // Clean up any users or apps that were removed or recreated 1681 // while this volume was missing 1682 reconcileUsers(volumeUuid); 1683 reconcileApps(volumeUuid); 1684 1685 // Clean up any install sessions that expired or were 1686 // cancelled while this volume was missing 1687 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1688 1689 loadPrivatePackages(vol); 1690 1691 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1692 unloadPrivatePackages(vol); 1693 } 1694 } 1695 1696 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1697 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1698 updateExternalMediaStatus(true, false); 1699 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1700 updateExternalMediaStatus(false, false); 1701 } 1702 } 1703 } 1704 1705 @Override 1706 public void onVolumeForgotten(String fsUuid) { 1707 if (TextUtils.isEmpty(fsUuid)) { 1708 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1709 return; 1710 } 1711 1712 // Remove any apps installed on the forgotten volume 1713 synchronized (mPackages) { 1714 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1715 for (PackageSetting ps : packages) { 1716 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1717 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1718 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1719 } 1720 1721 mSettings.onVolumeForgotten(fsUuid); 1722 mSettings.writeLPr(); 1723 } 1724 } 1725 }; 1726 1727 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1728 String[] grantedPermissions) { 1729 if (userId >= UserHandle.USER_SYSTEM) { 1730 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1731 } else if (userId == UserHandle.USER_ALL) { 1732 final int[] userIds; 1733 synchronized (mPackages) { 1734 userIds = UserManagerService.getInstance().getUserIds(); 1735 } 1736 for (int someUserId : userIds) { 1737 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1738 } 1739 } 1740 1741 // We could have touched GID membership, so flush out packages.list 1742 synchronized (mPackages) { 1743 mSettings.writePackageListLPr(); 1744 } 1745 } 1746 1747 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1748 String[] grantedPermissions) { 1749 SettingBase sb = (SettingBase) pkg.mExtras; 1750 if (sb == null) { 1751 return; 1752 } 1753 1754 PermissionsState permissionsState = sb.getPermissionsState(); 1755 1756 for (String permission : pkg.requestedPermissions) { 1757 BasePermission bp = mSettings.mPermissions.get(permission); 1758 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1759 || ArrayUtils.contains(grantedPermissions, permission))) { 1760 permissionsState.grantRuntimePermission(bp, userId); 1761 } 1762 } 1763 } 1764 1765 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1766 Bundle extras = null; 1767 switch (res.returnCode) { 1768 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1769 extras = new Bundle(); 1770 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1771 res.origPermission); 1772 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1773 res.origPackage); 1774 break; 1775 } 1776 case PackageManager.INSTALL_SUCCEEDED: { 1777 extras = new Bundle(); 1778 extras.putBoolean(Intent.EXTRA_REPLACING, 1779 res.removedInfo != null && res.removedInfo.removedPackage != null); 1780 break; 1781 } 1782 } 1783 return extras; 1784 } 1785 1786 void scheduleWriteSettingsLocked() { 1787 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1788 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1789 } 1790 } 1791 1792 void scheduleWritePackageRestrictionsLocked(int userId) { 1793 if (!sUserManager.exists(userId)) return; 1794 mDirtyUsers.add(userId); 1795 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1796 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1797 } 1798 } 1799 1800 public static PackageManagerService main(Context context, Installer installer, 1801 boolean factoryTest, boolean onlyCore) { 1802 PackageManagerService m = new PackageManagerService(context, installer, 1803 factoryTest, onlyCore); 1804 ServiceManager.addService("package", m); 1805 return m; 1806 } 1807 1808 static String[] splitString(String str, char sep) { 1809 int count = 1; 1810 int i = 0; 1811 while ((i=str.indexOf(sep, i)) >= 0) { 1812 count++; 1813 i++; 1814 } 1815 1816 String[] res = new String[count]; 1817 i=0; 1818 count = 0; 1819 int lastI=0; 1820 while ((i=str.indexOf(sep, i)) >= 0) { 1821 res[count] = str.substring(lastI, i); 1822 count++; 1823 i++; 1824 lastI = i; 1825 } 1826 res[count] = str.substring(lastI, str.length()); 1827 return res; 1828 } 1829 1830 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1831 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1832 Context.DISPLAY_SERVICE); 1833 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1834 } 1835 1836 public PackageManagerService(Context context, Installer installer, 1837 boolean factoryTest, boolean onlyCore) { 1838 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1839 SystemClock.uptimeMillis()); 1840 1841 if (mSdkVersion <= 0) { 1842 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1843 } 1844 1845 mContext = context; 1846 mFactoryTest = factoryTest; 1847 mOnlyCore = onlyCore; 1848 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1849 mMetrics = new DisplayMetrics(); 1850 mSettings = new Settings(mPackages); 1851 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1852 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1853 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1854 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1855 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1856 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1857 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1858 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1859 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1860 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1861 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1862 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1863 1864 // TODO: add a property to control this? 1865 long dexOptLRUThresholdInMinutes; 1866 if (mLazyDexOpt) { 1867 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1868 } else { 1869 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1870 } 1871 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1872 1873 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1874 if (separateProcesses != null && separateProcesses.length() > 0) { 1875 if ("*".equals(separateProcesses)) { 1876 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1877 mSeparateProcesses = null; 1878 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1879 } else { 1880 mDefParseFlags = 0; 1881 mSeparateProcesses = separateProcesses.split(","); 1882 Slog.w(TAG, "Running with debug.separate_processes: " 1883 + separateProcesses); 1884 } 1885 } else { 1886 mDefParseFlags = 0; 1887 mSeparateProcesses = null; 1888 } 1889 1890 mInstaller = installer; 1891 mPackageDexOptimizer = new PackageDexOptimizer(this); 1892 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1893 1894 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1895 FgThread.get().getLooper()); 1896 1897 getDefaultDisplayMetrics(context, mMetrics); 1898 1899 SystemConfig systemConfig = SystemConfig.getInstance(); 1900 mGlobalGids = systemConfig.getGlobalGids(); 1901 mSystemPermissions = systemConfig.getSystemPermissions(); 1902 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1903 1904 synchronized (mInstallLock) { 1905 // writer 1906 synchronized (mPackages) { 1907 mHandlerThread = new ServiceThread(TAG, 1908 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1909 mHandlerThread.start(); 1910 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1911 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1912 1913 File dataDir = Environment.getDataDirectory(); 1914 mAppDataDir = new File(dataDir, "data"); 1915 mAppInstallDir = new File(dataDir, "app"); 1916 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1917 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1918 mUserAppDataDir = new File(dataDir, "user"); 1919 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1920 1921 sUserManager = new UserManagerService(context, this, 1922 mInstallLock, mPackages); 1923 1924 // Propagate permission configuration in to package manager. 1925 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1926 = systemConfig.getPermissions(); 1927 for (int i=0; i<permConfig.size(); i++) { 1928 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1929 BasePermission bp = mSettings.mPermissions.get(perm.name); 1930 if (bp == null) { 1931 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1932 mSettings.mPermissions.put(perm.name, bp); 1933 } 1934 if (perm.gids != null) { 1935 bp.setGids(perm.gids, perm.perUser); 1936 } 1937 } 1938 1939 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1940 for (int i=0; i<libConfig.size(); i++) { 1941 mSharedLibraries.put(libConfig.keyAt(i), 1942 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1943 } 1944 1945 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1946 1947 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1948 1949 String customResolverActivity = Resources.getSystem().getString( 1950 R.string.config_customResolverActivity); 1951 if (TextUtils.isEmpty(customResolverActivity)) { 1952 customResolverActivity = null; 1953 } else { 1954 mCustomResolverComponentName = ComponentName.unflattenFromString( 1955 customResolverActivity); 1956 } 1957 1958 long startTime = SystemClock.uptimeMillis(); 1959 1960 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1961 startTime); 1962 1963 // Set flag to monitor and not change apk file paths when 1964 // scanning install directories. 1965 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1966 1967 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1968 1969 /** 1970 * Add everything in the in the boot class path to the 1971 * list of process files because dexopt will have been run 1972 * if necessary during zygote startup. 1973 */ 1974 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1975 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1976 1977 if (bootClassPath != null) { 1978 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1979 for (String element : bootClassPathElements) { 1980 alreadyDexOpted.add(element); 1981 } 1982 } else { 1983 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1984 } 1985 1986 if (systemServerClassPath != null) { 1987 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1988 for (String element : systemServerClassPathElements) { 1989 alreadyDexOpted.add(element); 1990 } 1991 } else { 1992 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1993 } 1994 1995 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1996 final String[] dexCodeInstructionSets = 1997 getDexCodeInstructionSets( 1998 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1999 2000 /** 2001 * Ensure all external libraries have had dexopt run on them. 2002 */ 2003 if (mSharedLibraries.size() > 0) { 2004 // NOTE: For now, we're compiling these system "shared libraries" 2005 // (and framework jars) into all available architectures. It's possible 2006 // to compile them only when we come across an app that uses them (there's 2007 // already logic for that in scanPackageLI) but that adds some complexity. 2008 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2009 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2010 final String lib = libEntry.path; 2011 if (lib == null) { 2012 continue; 2013 } 2014 2015 try { 2016 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2017 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2018 alreadyDexOpted.add(lib); 2019 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2020 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2021 } 2022 } catch (FileNotFoundException e) { 2023 Slog.w(TAG, "Library not found: " + lib); 2024 } catch (IOException e) { 2025 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2026 + e.getMessage()); 2027 } 2028 } 2029 } 2030 } 2031 2032 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2033 2034 // Gross hack for now: we know this file doesn't contain any 2035 // code, so don't dexopt it to avoid the resulting log spew. 2036 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2037 2038 // Gross hack for now: we know this file is only part of 2039 // the boot class path for art, so don't dexopt it to 2040 // avoid the resulting log spew. 2041 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2042 2043 /** 2044 * There are a number of commands implemented in Java, which 2045 * we currently need to do the dexopt on so that they can be 2046 * run from a non-root shell. 2047 */ 2048 String[] frameworkFiles = frameworkDir.list(); 2049 if (frameworkFiles != null) { 2050 // TODO: We could compile these only for the most preferred ABI. We should 2051 // first double check that the dex files for these commands are not referenced 2052 // by other system apps. 2053 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2054 for (int i=0; i<frameworkFiles.length; i++) { 2055 File libPath = new File(frameworkDir, frameworkFiles[i]); 2056 String path = libPath.getPath(); 2057 // Skip the file if we already did it. 2058 if (alreadyDexOpted.contains(path)) { 2059 continue; 2060 } 2061 // Skip the file if it is not a type we want to dexopt. 2062 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2063 continue; 2064 } 2065 try { 2066 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2067 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2068 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 2069 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2070 } 2071 } catch (FileNotFoundException e) { 2072 Slog.w(TAG, "Jar not found: " + path); 2073 } catch (IOException e) { 2074 Slog.w(TAG, "Exception reading jar: " + path, e); 2075 } 2076 } 2077 } 2078 } 2079 2080 final VersionInfo ver = mSettings.getInternalVersion(); 2081 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2082 // when upgrading from pre-M, promote system app permissions from install to runtime 2083 mPromoteSystemApps = 2084 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2085 2086 // save off the names of pre-existing system packages prior to scanning; we don't 2087 // want to automatically grant runtime permissions for new system apps 2088 if (mPromoteSystemApps) { 2089 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2090 while (pkgSettingIter.hasNext()) { 2091 PackageSetting ps = pkgSettingIter.next(); 2092 if (isSystemApp(ps)) { 2093 mExistingSystemPackages.add(ps.name); 2094 } 2095 } 2096 } 2097 2098 // Collect vendor overlay packages. 2099 // (Do this before scanning any apps.) 2100 // For security and version matching reason, only consider 2101 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2102 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2103 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2104 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2105 2106 // Find base frameworks (resource packages without code). 2107 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2108 | PackageParser.PARSE_IS_SYSTEM_DIR 2109 | PackageParser.PARSE_IS_PRIVILEGED, 2110 scanFlags | SCAN_NO_DEX, 0); 2111 2112 // Collected privileged system packages. 2113 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2114 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR 2116 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2117 2118 // Collect ordinary system packages. 2119 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2120 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2121 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2122 2123 // Collect all vendor packages. 2124 File vendorAppDir = new File("/vendor/app"); 2125 try { 2126 vendorAppDir = vendorAppDir.getCanonicalFile(); 2127 } catch (IOException e) { 2128 // failed to look up canonical path, continue with original one 2129 } 2130 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2131 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2132 2133 // Collect all OEM packages. 2134 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2135 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2136 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2137 2138 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2139 mInstaller.moveFiles(); 2140 2141 // Prune any system packages that no longer exist. 2142 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2143 if (!mOnlyCore) { 2144 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2145 while (psit.hasNext()) { 2146 PackageSetting ps = psit.next(); 2147 2148 /* 2149 * If this is not a system app, it can't be a 2150 * disable system app. 2151 */ 2152 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2153 continue; 2154 } 2155 2156 /* 2157 * If the package is scanned, it's not erased. 2158 */ 2159 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2160 if (scannedPkg != null) { 2161 /* 2162 * If the system app is both scanned and in the 2163 * disabled packages list, then it must have been 2164 * added via OTA. Remove it from the currently 2165 * scanned package so the previously user-installed 2166 * application can be scanned. 2167 */ 2168 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2169 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2170 + ps.name + "; removing system app. Last known codePath=" 2171 + ps.codePathString + ", installStatus=" + ps.installStatus 2172 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2173 + scannedPkg.mVersionCode); 2174 removePackageLI(ps, true); 2175 mExpectingBetter.put(ps.name, ps.codePath); 2176 } 2177 2178 continue; 2179 } 2180 2181 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2182 psit.remove(); 2183 logCriticalInfo(Log.WARN, "System package " + ps.name 2184 + " no longer exists; wiping its data"); 2185 removeDataDirsLI(null, ps.name); 2186 } else { 2187 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2188 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2189 possiblyDeletedUpdatedSystemApps.add(ps.name); 2190 } 2191 } 2192 } 2193 } 2194 2195 //look for any incomplete package installations 2196 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2197 //clean up list 2198 for(int i = 0; i < deletePkgsList.size(); i++) { 2199 //clean up here 2200 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2201 } 2202 //delete tmp files 2203 deleteTempPackageFiles(); 2204 2205 // Remove any shared userIDs that have no associated packages 2206 mSettings.pruneSharedUsersLPw(); 2207 2208 if (!mOnlyCore) { 2209 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2210 SystemClock.uptimeMillis()); 2211 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2212 2213 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2214 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2215 2216 /** 2217 * Remove disable package settings for any updated system 2218 * apps that were removed via an OTA. If they're not a 2219 * previously-updated app, remove them completely. 2220 * Otherwise, just revoke their system-level permissions. 2221 */ 2222 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2223 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2224 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2225 2226 String msg; 2227 if (deletedPkg == null) { 2228 msg = "Updated system package " + deletedAppName 2229 + " no longer exists; wiping its data"; 2230 removeDataDirsLI(null, deletedAppName); 2231 } else { 2232 msg = "Updated system app + " + deletedAppName 2233 + " no longer present; removing system privileges for " 2234 + deletedAppName; 2235 2236 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2237 2238 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2239 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2240 } 2241 logCriticalInfo(Log.WARN, msg); 2242 } 2243 2244 /** 2245 * Make sure all system apps that we expected to appear on 2246 * the userdata partition actually showed up. If they never 2247 * appeared, crawl back and revive the system version. 2248 */ 2249 for (int i = 0; i < mExpectingBetter.size(); i++) { 2250 final String packageName = mExpectingBetter.keyAt(i); 2251 if (!mPackages.containsKey(packageName)) { 2252 final File scanFile = mExpectingBetter.valueAt(i); 2253 2254 logCriticalInfo(Log.WARN, "Expected better " + packageName 2255 + " but never showed up; reverting to system"); 2256 2257 final int reparseFlags; 2258 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2259 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2260 | PackageParser.PARSE_IS_SYSTEM_DIR 2261 | PackageParser.PARSE_IS_PRIVILEGED; 2262 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2263 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2264 | PackageParser.PARSE_IS_SYSTEM_DIR; 2265 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2266 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2267 | PackageParser.PARSE_IS_SYSTEM_DIR; 2268 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2269 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2270 | PackageParser.PARSE_IS_SYSTEM_DIR; 2271 } else { 2272 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2273 continue; 2274 } 2275 2276 mSettings.enableSystemPackageLPw(packageName); 2277 2278 try { 2279 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, UserHandle.SYSTEM); 2280 } catch (PackageManagerException e) { 2281 Slog.e(TAG, "Failed to parse original system package: " 2282 + e.getMessage()); 2283 } 2284 } 2285 } 2286 } 2287 mExpectingBetter.clear(); 2288 2289 // Now that we know all of the shared libraries, update all clients to have 2290 // the correct library paths. 2291 updateAllSharedLibrariesLPw(); 2292 2293 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2294 // NOTE: We ignore potential failures here during a system scan (like 2295 // the rest of the commands above) because there's precious little we 2296 // can do about it. A settings error is reported, though. 2297 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2298 false /* force dexopt */, false /* defer dexopt */, 2299 false /* boot complete */); 2300 } 2301 2302 // Now that we know all the packages we are keeping, 2303 // read and update their last usage times. 2304 mPackageUsage.readLP(); 2305 2306 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2307 SystemClock.uptimeMillis()); 2308 Slog.i(TAG, "Time to scan packages: " 2309 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2310 + " seconds"); 2311 2312 // If the platform SDK has changed since the last time we booted, 2313 // we need to re-grant app permission to catch any new ones that 2314 // appear. This is really a hack, and means that apps can in some 2315 // cases get permissions that the user didn't initially explicitly 2316 // allow... it would be nice to have some better way to handle 2317 // this situation. 2318 int updateFlags = UPDATE_PERMISSIONS_ALL; 2319 if (ver.sdkVersion != mSdkVersion) { 2320 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2321 + mSdkVersion + "; regranting permissions for internal storage"); 2322 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2323 } 2324 updatePermissionsLPw(null, null, updateFlags); 2325 ver.sdkVersion = mSdkVersion; 2326 2327 // If this is the first boot or an update from pre-M, and it is a normal 2328 // boot, then we need to initialize the default preferred apps across 2329 // all defined users. 2330 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2331 for (UserInfo user : sUserManager.getUsers(true)) { 2332 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2333 applyFactoryDefaultBrowserLPw(user.id); 2334 primeDomainVerificationsLPw(user.id); 2335 } 2336 } 2337 2338 // If this is first boot after an OTA, and a normal boot, then 2339 // we need to clear code cache directories. 2340 if (mIsUpgrade && !onlyCore) { 2341 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2342 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2343 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2344 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2345 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2346 } 2347 } 2348 ver.fingerprint = Build.FINGERPRINT; 2349 } 2350 2351 checkDefaultBrowser(); 2352 2353 // clear only after permissions and other defaults have been updated 2354 mExistingSystemPackages.clear(); 2355 mPromoteSystemApps = false; 2356 2357 // All the changes are done during package scanning. 2358 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2359 2360 // can downgrade to reader 2361 mSettings.writeLPr(); 2362 2363 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2364 SystemClock.uptimeMillis()); 2365 2366 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2367 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2368 2369 mInstallerService = new PackageInstallerService(context, this); 2370 2371 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2372 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2373 mIntentFilterVerifierComponent); 2374 2375 } // synchronized (mPackages) 2376 } // synchronized (mInstallLock) 2377 2378 // Now after opening every single application zip, make sure they 2379 // are all flushed. Not really needed, but keeps things nice and 2380 // tidy. 2381 Runtime.getRuntime().gc(); 2382 2383 // Expose private service for system components to use. 2384 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2385 } 2386 2387 @Override 2388 public boolean isFirstBoot() { 2389 return !mRestoredSettings; 2390 } 2391 2392 @Override 2393 public boolean isOnlyCoreApps() { 2394 return mOnlyCore; 2395 } 2396 2397 @Override 2398 public boolean isUpgrade() { 2399 return mIsUpgrade; 2400 } 2401 2402 private String getRequiredVerifierLPr() { 2403 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2404 // We only care about verifier that's installed under system user. 2405 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2406 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2407 2408 String requiredVerifier = null; 2409 2410 final int N = receivers.size(); 2411 for (int i = 0; i < N; i++) { 2412 final ResolveInfo info = receivers.get(i); 2413 2414 if (info.activityInfo == null) { 2415 continue; 2416 } 2417 2418 final String packageName = info.activityInfo.packageName; 2419 2420 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2421 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2422 continue; 2423 } 2424 2425 if (requiredVerifier != null) { 2426 throw new RuntimeException("There can be only one required verifier"); 2427 } 2428 2429 requiredVerifier = packageName; 2430 } 2431 2432 return requiredVerifier; 2433 } 2434 2435 private String getRequiredInstallerLPr() { 2436 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2437 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2438 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2439 2440 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2441 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2442 2443 String requiredInstaller = null; 2444 2445 final int N = installers.size(); 2446 for (int i = 0; i < N; i++) { 2447 final ResolveInfo info = installers.get(i); 2448 final String packageName = info.activityInfo.packageName; 2449 2450 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2451 continue; 2452 } 2453 2454 if (requiredInstaller != null) { 2455 throw new RuntimeException("There must be one required installer"); 2456 } 2457 2458 requiredInstaller = packageName; 2459 } 2460 2461 if (requiredInstaller == null) { 2462 throw new RuntimeException("There must be one required installer"); 2463 } 2464 2465 return requiredInstaller; 2466 } 2467 2468 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2469 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2470 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2471 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2472 2473 ComponentName verifierComponentName = null; 2474 2475 int priority = -1000; 2476 final int N = receivers.size(); 2477 for (int i = 0; i < N; i++) { 2478 final ResolveInfo info = receivers.get(i); 2479 2480 if (info.activityInfo == null) { 2481 continue; 2482 } 2483 2484 final String packageName = info.activityInfo.packageName; 2485 2486 final PackageSetting ps = mSettings.mPackages.get(packageName); 2487 if (ps == null) { 2488 continue; 2489 } 2490 2491 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2492 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2493 continue; 2494 } 2495 2496 // Select the IntentFilterVerifier with the highest priority 2497 if (priority < info.priority) { 2498 priority = info.priority; 2499 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2500 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2501 + verifierComponentName + " with priority: " + info.priority); 2502 } 2503 } 2504 2505 return verifierComponentName; 2506 } 2507 2508 private void primeDomainVerificationsLPw(int userId) { 2509 if (DEBUG_DOMAIN_VERIFICATION) { 2510 Slog.d(TAG, "Priming domain verifications in user " + userId); 2511 } 2512 2513 SystemConfig systemConfig = SystemConfig.getInstance(); 2514 ArraySet<String> packages = systemConfig.getLinkedApps(); 2515 ArraySet<String> domains = new ArraySet<String>(); 2516 2517 for (String packageName : packages) { 2518 PackageParser.Package pkg = mPackages.get(packageName); 2519 if (pkg != null) { 2520 if (!pkg.isSystemApp()) { 2521 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2522 continue; 2523 } 2524 2525 domains.clear(); 2526 for (PackageParser.Activity a : pkg.activities) { 2527 for (ActivityIntentInfo filter : a.intents) { 2528 if (hasValidDomains(filter)) { 2529 domains.addAll(filter.getHostsList()); 2530 } 2531 } 2532 } 2533 2534 if (domains.size() > 0) { 2535 if (DEBUG_DOMAIN_VERIFICATION) { 2536 Slog.v(TAG, " + " + packageName); 2537 } 2538 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2539 // state w.r.t. the formal app-linkage "no verification attempted" state; 2540 // and then 'always' in the per-user state actually used for intent resolution. 2541 final IntentFilterVerificationInfo ivi; 2542 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2543 new ArrayList<String>(domains)); 2544 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2545 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2546 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2547 } else { 2548 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2549 + "' does not handle web links"); 2550 } 2551 } else { 2552 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2553 } 2554 } 2555 2556 scheduleWritePackageRestrictionsLocked(userId); 2557 scheduleWriteSettingsLocked(); 2558 } 2559 2560 private void applyFactoryDefaultBrowserLPw(int userId) { 2561 // The default browser app's package name is stored in a string resource, 2562 // with a product-specific overlay used for vendor customization. 2563 String browserPkg = mContext.getResources().getString( 2564 com.android.internal.R.string.default_browser); 2565 if (!TextUtils.isEmpty(browserPkg)) { 2566 // non-empty string => required to be a known package 2567 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2568 if (ps == null) { 2569 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2570 browserPkg = null; 2571 } else { 2572 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2573 } 2574 } 2575 2576 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2577 // default. If there's more than one, just leave everything alone. 2578 if (browserPkg == null) { 2579 calculateDefaultBrowserLPw(userId); 2580 } 2581 } 2582 2583 private void calculateDefaultBrowserLPw(int userId) { 2584 List<String> allBrowsers = resolveAllBrowserApps(userId); 2585 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2586 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2587 } 2588 2589 private List<String> resolveAllBrowserApps(int userId) { 2590 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2591 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2592 PackageManager.MATCH_ALL, userId); 2593 2594 final int count = list.size(); 2595 List<String> result = new ArrayList<String>(count); 2596 for (int i=0; i<count; i++) { 2597 ResolveInfo info = list.get(i); 2598 if (info.activityInfo == null 2599 || !info.handleAllWebDataURI 2600 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2601 || result.contains(info.activityInfo.packageName)) { 2602 continue; 2603 } 2604 result.add(info.activityInfo.packageName); 2605 } 2606 2607 return result; 2608 } 2609 2610 private boolean packageIsBrowser(String packageName, int userId) { 2611 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2612 PackageManager.MATCH_ALL, userId); 2613 final int N = list.size(); 2614 for (int i = 0; i < N; i++) { 2615 ResolveInfo info = list.get(i); 2616 if (packageName.equals(info.activityInfo.packageName)) { 2617 return true; 2618 } 2619 } 2620 return false; 2621 } 2622 2623 private void checkDefaultBrowser() { 2624 final int myUserId = UserHandle.myUserId(); 2625 final String packageName = getDefaultBrowserPackageName(myUserId); 2626 if (packageName != null) { 2627 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2628 if (info == null) { 2629 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2630 synchronized (mPackages) { 2631 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2632 } 2633 } 2634 } 2635 } 2636 2637 @Override 2638 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2639 throws RemoteException { 2640 try { 2641 return super.onTransact(code, data, reply, flags); 2642 } catch (RuntimeException e) { 2643 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2644 Slog.wtf(TAG, "Package Manager Crash", e); 2645 } 2646 throw e; 2647 } 2648 } 2649 2650 void cleanupInstallFailedPackage(PackageSetting ps) { 2651 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2652 2653 removeDataDirsLI(ps.volumeUuid, ps.name); 2654 if (ps.codePath != null) { 2655 if (ps.codePath.isDirectory()) { 2656 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2657 } else { 2658 ps.codePath.delete(); 2659 } 2660 } 2661 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2662 if (ps.resourcePath.isDirectory()) { 2663 FileUtils.deleteContents(ps.resourcePath); 2664 } 2665 ps.resourcePath.delete(); 2666 } 2667 mSettings.removePackageLPw(ps.name); 2668 } 2669 2670 static int[] appendInts(int[] cur, int[] add) { 2671 if (add == null) return cur; 2672 if (cur == null) return add; 2673 final int N = add.length; 2674 for (int i=0; i<N; i++) { 2675 cur = appendInt(cur, add[i]); 2676 } 2677 return cur; 2678 } 2679 2680 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2681 if (!sUserManager.exists(userId)) return null; 2682 final PackageSetting ps = (PackageSetting) p.mExtras; 2683 if (ps == null) { 2684 return null; 2685 } 2686 2687 final PermissionsState permissionsState = ps.getPermissionsState(); 2688 2689 final int[] gids = permissionsState.computeGids(userId); 2690 final Set<String> permissions = permissionsState.getPermissions(userId); 2691 final PackageUserState state = ps.readUserState(userId); 2692 2693 return PackageParser.generatePackageInfo(p, gids, flags, 2694 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2695 } 2696 2697 @Override 2698 public boolean isPackageFrozen(String packageName) { 2699 synchronized (mPackages) { 2700 final PackageSetting ps = mSettings.mPackages.get(packageName); 2701 if (ps != null) { 2702 return ps.frozen; 2703 } 2704 } 2705 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2706 return true; 2707 } 2708 2709 @Override 2710 public boolean isPackageAvailable(String packageName, int userId) { 2711 if (!sUserManager.exists(userId)) return false; 2712 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2713 synchronized (mPackages) { 2714 PackageParser.Package p = mPackages.get(packageName); 2715 if (p != null) { 2716 final PackageSetting ps = (PackageSetting) p.mExtras; 2717 if (ps != null) { 2718 final PackageUserState state = ps.readUserState(userId); 2719 if (state != null) { 2720 return PackageParser.isAvailable(state); 2721 } 2722 } 2723 } 2724 } 2725 return false; 2726 } 2727 2728 @Override 2729 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2730 if (!sUserManager.exists(userId)) return null; 2731 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2732 // reader 2733 synchronized (mPackages) { 2734 PackageParser.Package p = mPackages.get(packageName); 2735 if (DEBUG_PACKAGE_INFO) 2736 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2737 if (p != null) { 2738 return generatePackageInfo(p, flags, userId); 2739 } 2740 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2741 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2742 } 2743 } 2744 return null; 2745 } 2746 2747 @Override 2748 public String[] currentToCanonicalPackageNames(String[] names) { 2749 String[] out = new String[names.length]; 2750 // reader 2751 synchronized (mPackages) { 2752 for (int i=names.length-1; i>=0; i--) { 2753 PackageSetting ps = mSettings.mPackages.get(names[i]); 2754 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2755 } 2756 } 2757 return out; 2758 } 2759 2760 @Override 2761 public String[] canonicalToCurrentPackageNames(String[] names) { 2762 String[] out = new String[names.length]; 2763 // reader 2764 synchronized (mPackages) { 2765 for (int i=names.length-1; i>=0; i--) { 2766 String cur = mSettings.mRenamedPackages.get(names[i]); 2767 out[i] = cur != null ? cur : names[i]; 2768 } 2769 } 2770 return out; 2771 } 2772 2773 @Override 2774 public int getPackageUid(String packageName, int userId) { 2775 if (!sUserManager.exists(userId)) return -1; 2776 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2777 2778 // reader 2779 synchronized (mPackages) { 2780 PackageParser.Package p = mPackages.get(packageName); 2781 if(p != null) { 2782 return UserHandle.getUid(userId, p.applicationInfo.uid); 2783 } 2784 PackageSetting ps = mSettings.mPackages.get(packageName); 2785 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2786 return -1; 2787 } 2788 return UserHandle.getUid(userId, ps.pkg.applicationInfo.uid); 2789 } 2790 } 2791 2792 @Override 2793 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2794 if (!sUserManager.exists(userId)) { 2795 return null; 2796 } 2797 2798 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2799 "getPackageGids"); 2800 2801 // reader 2802 synchronized (mPackages) { 2803 PackageParser.Package p = mPackages.get(packageName); 2804 if (DEBUG_PACKAGE_INFO) { 2805 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2806 } 2807 if (p != null) { 2808 PackageSetting ps = (PackageSetting) p.mExtras; 2809 return ps.getPermissionsState().computeGids(userId); 2810 } 2811 } 2812 2813 return null; 2814 } 2815 2816 static PermissionInfo generatePermissionInfo( 2817 BasePermission bp, int flags) { 2818 if (bp.perm != null) { 2819 return PackageParser.generatePermissionInfo(bp.perm, flags); 2820 } 2821 PermissionInfo pi = new PermissionInfo(); 2822 pi.name = bp.name; 2823 pi.packageName = bp.sourcePackage; 2824 pi.nonLocalizedLabel = bp.name; 2825 pi.protectionLevel = bp.protectionLevel; 2826 return pi; 2827 } 2828 2829 @Override 2830 public PermissionInfo getPermissionInfo(String name, int flags) { 2831 // reader 2832 synchronized (mPackages) { 2833 final BasePermission p = mSettings.mPermissions.get(name); 2834 if (p != null) { 2835 return generatePermissionInfo(p, flags); 2836 } 2837 return null; 2838 } 2839 } 2840 2841 @Override 2842 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2843 // reader 2844 synchronized (mPackages) { 2845 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2846 for (BasePermission p : mSettings.mPermissions.values()) { 2847 if (group == null) { 2848 if (p.perm == null || p.perm.info.group == null) { 2849 out.add(generatePermissionInfo(p, flags)); 2850 } 2851 } else { 2852 if (p.perm != null && group.equals(p.perm.info.group)) { 2853 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2854 } 2855 } 2856 } 2857 2858 if (out.size() > 0) { 2859 return out; 2860 } 2861 return mPermissionGroups.containsKey(group) ? out : null; 2862 } 2863 } 2864 2865 @Override 2866 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2867 // reader 2868 synchronized (mPackages) { 2869 return PackageParser.generatePermissionGroupInfo( 2870 mPermissionGroups.get(name), flags); 2871 } 2872 } 2873 2874 @Override 2875 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2876 // reader 2877 synchronized (mPackages) { 2878 final int N = mPermissionGroups.size(); 2879 ArrayList<PermissionGroupInfo> out 2880 = new ArrayList<PermissionGroupInfo>(N); 2881 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2882 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2883 } 2884 return out; 2885 } 2886 } 2887 2888 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2889 int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 PackageSetting ps = mSettings.mPackages.get(packageName); 2892 if (ps != null) { 2893 if (ps.pkg == null) { 2894 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2895 flags, userId); 2896 if (pInfo != null) { 2897 return pInfo.applicationInfo; 2898 } 2899 return null; 2900 } 2901 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2902 ps.readUserState(userId), userId); 2903 } 2904 return null; 2905 } 2906 2907 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2908 int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 PackageSetting ps = mSettings.mPackages.get(packageName); 2911 if (ps != null) { 2912 PackageParser.Package pkg = ps.pkg; 2913 if (pkg == null) { 2914 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2915 return null; 2916 } 2917 // Only data remains, so we aren't worried about code paths 2918 pkg = new PackageParser.Package(packageName); 2919 pkg.applicationInfo.packageName = packageName; 2920 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2921 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2922 pkg.applicationInfo.dataDir = Environment 2923 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2924 .getAbsolutePath(); 2925 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2926 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2927 } 2928 return generatePackageInfo(pkg, flags, userId); 2929 } 2930 return null; 2931 } 2932 2933 @Override 2934 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2935 if (!sUserManager.exists(userId)) return null; 2936 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2937 // writer 2938 synchronized (mPackages) { 2939 PackageParser.Package p = mPackages.get(packageName); 2940 if (DEBUG_PACKAGE_INFO) Log.v( 2941 TAG, "getApplicationInfo " + packageName 2942 + ": " + p); 2943 if (p != null) { 2944 PackageSetting ps = mSettings.mPackages.get(packageName); 2945 if (ps == null) return null; 2946 // Note: isEnabledLP() does not apply here - always return info 2947 return PackageParser.generateApplicationInfo( 2948 p, flags, ps.readUserState(userId), userId); 2949 } 2950 if ("android".equals(packageName)||"system".equals(packageName)) { 2951 return mAndroidApplication; 2952 } 2953 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2954 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2955 } 2956 } 2957 return null; 2958 } 2959 2960 @Override 2961 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2962 final IPackageDataObserver observer) { 2963 mContext.enforceCallingOrSelfPermission( 2964 android.Manifest.permission.CLEAR_APP_CACHE, null); 2965 // Queue up an async operation since clearing cache may take a little while. 2966 mHandler.post(new Runnable() { 2967 public void run() { 2968 mHandler.removeCallbacks(this); 2969 int retCode = -1; 2970 synchronized (mInstallLock) { 2971 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2972 if (retCode < 0) { 2973 Slog.w(TAG, "Couldn't clear application caches"); 2974 } 2975 } 2976 if (observer != null) { 2977 try { 2978 observer.onRemoveCompleted(null, (retCode >= 0)); 2979 } catch (RemoteException e) { 2980 Slog.w(TAG, "RemoveException when invoking call back"); 2981 } 2982 } 2983 } 2984 }); 2985 } 2986 2987 @Override 2988 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2989 final IntentSender pi) { 2990 mContext.enforceCallingOrSelfPermission( 2991 android.Manifest.permission.CLEAR_APP_CACHE, null); 2992 // Queue up an async operation since clearing cache may take a little while. 2993 mHandler.post(new Runnable() { 2994 public void run() { 2995 mHandler.removeCallbacks(this); 2996 int retCode = -1; 2997 synchronized (mInstallLock) { 2998 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2999 if (retCode < 0) { 3000 Slog.w(TAG, "Couldn't clear application caches"); 3001 } 3002 } 3003 if(pi != null) { 3004 try { 3005 // Callback via pending intent 3006 int code = (retCode >= 0) ? 1 : 0; 3007 pi.sendIntent(null, code, null, 3008 null, null); 3009 } catch (SendIntentException e1) { 3010 Slog.i(TAG, "Failed to send pending intent"); 3011 } 3012 } 3013 } 3014 }); 3015 } 3016 3017 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3018 synchronized (mInstallLock) { 3019 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3020 throw new IOException("Failed to free enough space"); 3021 } 3022 } 3023 } 3024 3025 @Override 3026 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3027 if (!sUserManager.exists(userId)) return null; 3028 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3029 synchronized (mPackages) { 3030 PackageParser.Activity a = mActivities.mActivities.get(component); 3031 3032 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3033 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3034 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3035 if (ps == null) return null; 3036 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3037 userId); 3038 } 3039 if (mResolveComponentName.equals(component)) { 3040 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3041 new PackageUserState(), userId); 3042 } 3043 } 3044 return null; 3045 } 3046 3047 @Override 3048 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3049 String resolvedType) { 3050 synchronized (mPackages) { 3051 if (component.equals(mResolveComponentName)) { 3052 // The resolver supports EVERYTHING! 3053 return true; 3054 } 3055 PackageParser.Activity a = mActivities.mActivities.get(component); 3056 if (a == null) { 3057 return false; 3058 } 3059 for (int i=0; i<a.intents.size(); i++) { 3060 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3061 intent.getData(), intent.getCategories(), TAG) >= 0) { 3062 return true; 3063 } 3064 } 3065 return false; 3066 } 3067 } 3068 3069 @Override 3070 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3071 if (!sUserManager.exists(userId)) return null; 3072 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3073 synchronized (mPackages) { 3074 PackageParser.Activity a = mReceivers.mActivities.get(component); 3075 if (DEBUG_PACKAGE_INFO) Log.v( 3076 TAG, "getReceiverInfo " + component + ": " + a); 3077 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3078 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3079 if (ps == null) return null; 3080 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3081 userId); 3082 } 3083 } 3084 return null; 3085 } 3086 3087 @Override 3088 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3089 if (!sUserManager.exists(userId)) return null; 3090 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3091 synchronized (mPackages) { 3092 PackageParser.Service s = mServices.mServices.get(component); 3093 if (DEBUG_PACKAGE_INFO) Log.v( 3094 TAG, "getServiceInfo " + component + ": " + s); 3095 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3096 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3097 if (ps == null) return null; 3098 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3099 userId); 3100 } 3101 } 3102 return null; 3103 } 3104 3105 @Override 3106 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3107 if (!sUserManager.exists(userId)) return null; 3108 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3109 synchronized (mPackages) { 3110 PackageParser.Provider p = mProviders.mProviders.get(component); 3111 if (DEBUG_PACKAGE_INFO) Log.v( 3112 TAG, "getProviderInfo " + component + ": " + p); 3113 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3114 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3115 if (ps == null) return null; 3116 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3117 userId); 3118 } 3119 } 3120 return null; 3121 } 3122 3123 @Override 3124 public String[] getSystemSharedLibraryNames() { 3125 Set<String> libSet; 3126 synchronized (mPackages) { 3127 libSet = mSharedLibraries.keySet(); 3128 int size = libSet.size(); 3129 if (size > 0) { 3130 String[] libs = new String[size]; 3131 libSet.toArray(libs); 3132 return libs; 3133 } 3134 } 3135 return null; 3136 } 3137 3138 /** 3139 * @hide 3140 */ 3141 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3142 synchronized (mPackages) { 3143 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3144 if (lib != null && lib.apk != null) { 3145 return mPackages.get(lib.apk); 3146 } 3147 } 3148 return null; 3149 } 3150 3151 @Override 3152 public FeatureInfo[] getSystemAvailableFeatures() { 3153 Collection<FeatureInfo> featSet; 3154 synchronized (mPackages) { 3155 featSet = mAvailableFeatures.values(); 3156 int size = featSet.size(); 3157 if (size > 0) { 3158 FeatureInfo[] features = new FeatureInfo[size+1]; 3159 featSet.toArray(features); 3160 FeatureInfo fi = new FeatureInfo(); 3161 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3162 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3163 features[size] = fi; 3164 return features; 3165 } 3166 } 3167 return null; 3168 } 3169 3170 @Override 3171 public boolean hasSystemFeature(String name) { 3172 synchronized (mPackages) { 3173 return mAvailableFeatures.containsKey(name); 3174 } 3175 } 3176 3177 private void checkValidCaller(int uid, int userId) { 3178 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3179 return; 3180 3181 throw new SecurityException("Caller uid=" + uid 3182 + " is not privileged to communicate with user=" + userId); 3183 } 3184 3185 @Override 3186 public int checkPermission(String permName, String pkgName, int userId) { 3187 if (!sUserManager.exists(userId)) { 3188 return PackageManager.PERMISSION_DENIED; 3189 } 3190 3191 synchronized (mPackages) { 3192 final PackageParser.Package p = mPackages.get(pkgName); 3193 if (p != null && p.mExtras != null) { 3194 final PackageSetting ps = (PackageSetting) p.mExtras; 3195 final PermissionsState permissionsState = ps.getPermissionsState(); 3196 if (permissionsState.hasPermission(permName, userId)) { 3197 return PackageManager.PERMISSION_GRANTED; 3198 } 3199 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3200 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3201 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3202 return PackageManager.PERMISSION_GRANTED; 3203 } 3204 } 3205 } 3206 3207 return PackageManager.PERMISSION_DENIED; 3208 } 3209 3210 @Override 3211 public int checkUidPermission(String permName, int uid) { 3212 final int userId = UserHandle.getUserId(uid); 3213 3214 if (!sUserManager.exists(userId)) { 3215 return PackageManager.PERMISSION_DENIED; 3216 } 3217 3218 synchronized (mPackages) { 3219 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3220 if (obj != null) { 3221 final SettingBase ps = (SettingBase) obj; 3222 final PermissionsState permissionsState = ps.getPermissionsState(); 3223 if (permissionsState.hasPermission(permName, userId)) { 3224 return PackageManager.PERMISSION_GRANTED; 3225 } 3226 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3227 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3228 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3229 return PackageManager.PERMISSION_GRANTED; 3230 } 3231 } else { 3232 ArraySet<String> perms = mSystemPermissions.get(uid); 3233 if (perms != null) { 3234 if (perms.contains(permName)) { 3235 return PackageManager.PERMISSION_GRANTED; 3236 } 3237 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3238 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3239 return PackageManager.PERMISSION_GRANTED; 3240 } 3241 } 3242 } 3243 } 3244 3245 return PackageManager.PERMISSION_DENIED; 3246 } 3247 3248 @Override 3249 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3250 if (UserHandle.getCallingUserId() != userId) { 3251 mContext.enforceCallingPermission( 3252 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3253 "isPermissionRevokedByPolicy for user " + userId); 3254 } 3255 3256 if (checkPermission(permission, packageName, userId) 3257 == PackageManager.PERMISSION_GRANTED) { 3258 return false; 3259 } 3260 3261 final long identity = Binder.clearCallingIdentity(); 3262 try { 3263 final int flags = getPermissionFlags(permission, packageName, userId); 3264 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3265 } finally { 3266 Binder.restoreCallingIdentity(identity); 3267 } 3268 } 3269 3270 @Override 3271 public String getPermissionControllerPackageName() { 3272 synchronized (mPackages) { 3273 return mRequiredInstallerPackage; 3274 } 3275 } 3276 3277 /** 3278 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3279 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3280 * @param checkShell TODO(yamasani): 3281 * @param message the message to log on security exception 3282 */ 3283 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3284 boolean checkShell, String message) { 3285 if (userId < 0) { 3286 throw new IllegalArgumentException("Invalid userId " + userId); 3287 } 3288 if (checkShell) { 3289 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3290 } 3291 if (userId == UserHandle.getUserId(callingUid)) return; 3292 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3293 if (requireFullPermission) { 3294 mContext.enforceCallingOrSelfPermission( 3295 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3296 } else { 3297 try { 3298 mContext.enforceCallingOrSelfPermission( 3299 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3300 } catch (SecurityException se) { 3301 mContext.enforceCallingOrSelfPermission( 3302 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3303 } 3304 } 3305 } 3306 } 3307 3308 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3309 if (callingUid == Process.SHELL_UID) { 3310 if (userHandle >= 0 3311 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3312 throw new SecurityException("Shell does not have permission to access user " 3313 + userHandle); 3314 } else if (userHandle < 0) { 3315 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3316 + Debug.getCallers(3)); 3317 } 3318 } 3319 } 3320 3321 private BasePermission findPermissionTreeLP(String permName) { 3322 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3323 if (permName.startsWith(bp.name) && 3324 permName.length() > bp.name.length() && 3325 permName.charAt(bp.name.length()) == '.') { 3326 return bp; 3327 } 3328 } 3329 return null; 3330 } 3331 3332 private BasePermission checkPermissionTreeLP(String permName) { 3333 if (permName != null) { 3334 BasePermission bp = findPermissionTreeLP(permName); 3335 if (bp != null) { 3336 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3337 return bp; 3338 } 3339 throw new SecurityException("Calling uid " 3340 + Binder.getCallingUid() 3341 + " is not allowed to add to permission tree " 3342 + bp.name + " owned by uid " + bp.uid); 3343 } 3344 } 3345 throw new SecurityException("No permission tree found for " + permName); 3346 } 3347 3348 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3349 if (s1 == null) { 3350 return s2 == null; 3351 } 3352 if (s2 == null) { 3353 return false; 3354 } 3355 if (s1.getClass() != s2.getClass()) { 3356 return false; 3357 } 3358 return s1.equals(s2); 3359 } 3360 3361 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3362 if (pi1.icon != pi2.icon) return false; 3363 if (pi1.logo != pi2.logo) return false; 3364 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3365 if (!compareStrings(pi1.name, pi2.name)) return false; 3366 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3367 // We'll take care of setting this one. 3368 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3369 // These are not currently stored in settings. 3370 //if (!compareStrings(pi1.group, pi2.group)) return false; 3371 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3372 //if (pi1.labelRes != pi2.labelRes) return false; 3373 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3374 return true; 3375 } 3376 3377 int permissionInfoFootprint(PermissionInfo info) { 3378 int size = info.name.length(); 3379 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3380 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3381 return size; 3382 } 3383 3384 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3385 int size = 0; 3386 for (BasePermission perm : mSettings.mPermissions.values()) { 3387 if (perm.uid == tree.uid) { 3388 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3389 } 3390 } 3391 return size; 3392 } 3393 3394 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3395 // We calculate the max size of permissions defined by this uid and throw 3396 // if that plus the size of 'info' would exceed our stated maximum. 3397 if (tree.uid != Process.SYSTEM_UID) { 3398 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3399 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3400 throw new SecurityException("Permission tree size cap exceeded"); 3401 } 3402 } 3403 } 3404 3405 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3406 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3407 throw new SecurityException("Label must be specified in permission"); 3408 } 3409 BasePermission tree = checkPermissionTreeLP(info.name); 3410 BasePermission bp = mSettings.mPermissions.get(info.name); 3411 boolean added = bp == null; 3412 boolean changed = true; 3413 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3414 if (added) { 3415 enforcePermissionCapLocked(info, tree); 3416 bp = new BasePermission(info.name, tree.sourcePackage, 3417 BasePermission.TYPE_DYNAMIC); 3418 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3419 throw new SecurityException( 3420 "Not allowed to modify non-dynamic permission " 3421 + info.name); 3422 } else { 3423 if (bp.protectionLevel == fixedLevel 3424 && bp.perm.owner.equals(tree.perm.owner) 3425 && bp.uid == tree.uid 3426 && comparePermissionInfos(bp.perm.info, info)) { 3427 changed = false; 3428 } 3429 } 3430 bp.protectionLevel = fixedLevel; 3431 info = new PermissionInfo(info); 3432 info.protectionLevel = fixedLevel; 3433 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3434 bp.perm.info.packageName = tree.perm.info.packageName; 3435 bp.uid = tree.uid; 3436 if (added) { 3437 mSettings.mPermissions.put(info.name, bp); 3438 } 3439 if (changed) { 3440 if (!async) { 3441 mSettings.writeLPr(); 3442 } else { 3443 scheduleWriteSettingsLocked(); 3444 } 3445 } 3446 return added; 3447 } 3448 3449 @Override 3450 public boolean addPermission(PermissionInfo info) { 3451 synchronized (mPackages) { 3452 return addPermissionLocked(info, false); 3453 } 3454 } 3455 3456 @Override 3457 public boolean addPermissionAsync(PermissionInfo info) { 3458 synchronized (mPackages) { 3459 return addPermissionLocked(info, true); 3460 } 3461 } 3462 3463 @Override 3464 public void removePermission(String name) { 3465 synchronized (mPackages) { 3466 checkPermissionTreeLP(name); 3467 BasePermission bp = mSettings.mPermissions.get(name); 3468 if (bp != null) { 3469 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3470 throw new SecurityException( 3471 "Not allowed to modify non-dynamic permission " 3472 + name); 3473 } 3474 mSettings.mPermissions.remove(name); 3475 mSettings.writeLPr(); 3476 } 3477 } 3478 } 3479 3480 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3481 BasePermission bp) { 3482 int index = pkg.requestedPermissions.indexOf(bp.name); 3483 if (index == -1) { 3484 throw new SecurityException("Package " + pkg.packageName 3485 + " has not requested permission " + bp.name); 3486 } 3487 if (!bp.isRuntime() && !bp.isDevelopment()) { 3488 throw new SecurityException("Permission " + bp.name 3489 + " is not a changeable permission type"); 3490 } 3491 } 3492 3493 @Override 3494 public void grantRuntimePermission(String packageName, String name, final int userId) { 3495 if (!sUserManager.exists(userId)) { 3496 Log.e(TAG, "No such user:" + userId); 3497 return; 3498 } 3499 3500 mContext.enforceCallingOrSelfPermission( 3501 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3502 "grantRuntimePermission"); 3503 3504 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3505 "grantRuntimePermission"); 3506 3507 final int uid; 3508 final SettingBase sb; 3509 3510 synchronized (mPackages) { 3511 final PackageParser.Package pkg = mPackages.get(packageName); 3512 if (pkg == null) { 3513 throw new IllegalArgumentException("Unknown package: " + packageName); 3514 } 3515 3516 final BasePermission bp = mSettings.mPermissions.get(name); 3517 if (bp == null) { 3518 throw new IllegalArgumentException("Unknown permission: " + name); 3519 } 3520 3521 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3522 3523 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3524 sb = (SettingBase) pkg.mExtras; 3525 if (sb == null) { 3526 throw new IllegalArgumentException("Unknown package: " + packageName); 3527 } 3528 3529 final PermissionsState permissionsState = sb.getPermissionsState(); 3530 3531 final int flags = permissionsState.getPermissionFlags(name, userId); 3532 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3533 throw new SecurityException("Cannot grant system fixed permission: " 3534 + name + " for package: " + packageName); 3535 } 3536 3537 if (bp.isDevelopment()) { 3538 // Development permissions must be handled specially, since they are not 3539 // normal runtime permissions. For now they apply to all users. 3540 if (permissionsState.grantInstallPermission(bp) != 3541 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3542 scheduleWriteSettingsLocked(); 3543 } 3544 return; 3545 } 3546 3547 final int result = permissionsState.grantRuntimePermission(bp, userId); 3548 switch (result) { 3549 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3550 return; 3551 } 3552 3553 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3554 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3555 mHandler.post(new Runnable() { 3556 @Override 3557 public void run() { 3558 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3559 } 3560 }); 3561 } break; 3562 } 3563 3564 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3565 3566 // Not critical if that is lost - app has to request again. 3567 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3568 } 3569 3570 // Only need to do this if user is initialized. Otherwise it's a new user 3571 // and there are no processes running as the user yet and there's no need 3572 // to make an expensive call to remount processes for the changed permissions. 3573 if (READ_EXTERNAL_STORAGE.equals(name) 3574 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3575 final long token = Binder.clearCallingIdentity(); 3576 try { 3577 if (sUserManager.isInitialized(userId)) { 3578 MountServiceInternal mountServiceInternal = LocalServices.getService( 3579 MountServiceInternal.class); 3580 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3581 } 3582 } finally { 3583 Binder.restoreCallingIdentity(token); 3584 } 3585 } 3586 } 3587 3588 @Override 3589 public void revokeRuntimePermission(String packageName, String name, int userId) { 3590 if (!sUserManager.exists(userId)) { 3591 Log.e(TAG, "No such user:" + userId); 3592 return; 3593 } 3594 3595 mContext.enforceCallingOrSelfPermission( 3596 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3597 "revokeRuntimePermission"); 3598 3599 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3600 "revokeRuntimePermission"); 3601 3602 final int appId; 3603 3604 synchronized (mPackages) { 3605 final PackageParser.Package pkg = mPackages.get(packageName); 3606 if (pkg == null) { 3607 throw new IllegalArgumentException("Unknown package: " + packageName); 3608 } 3609 3610 final BasePermission bp = mSettings.mPermissions.get(name); 3611 if (bp == null) { 3612 throw new IllegalArgumentException("Unknown permission: " + name); 3613 } 3614 3615 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3616 3617 SettingBase sb = (SettingBase) pkg.mExtras; 3618 if (sb == null) { 3619 throw new IllegalArgumentException("Unknown package: " + packageName); 3620 } 3621 3622 final PermissionsState permissionsState = sb.getPermissionsState(); 3623 3624 final int flags = permissionsState.getPermissionFlags(name, userId); 3625 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3626 throw new SecurityException("Cannot revoke system fixed permission: " 3627 + name + " for package: " + packageName); 3628 } 3629 3630 if (bp.isDevelopment()) { 3631 // Development permissions must be handled specially, since they are not 3632 // normal runtime permissions. For now they apply to all users. 3633 if (permissionsState.revokeInstallPermission(bp) != 3634 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3635 scheduleWriteSettingsLocked(); 3636 } 3637 return; 3638 } 3639 3640 if (permissionsState.revokeRuntimePermission(bp, userId) == 3641 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3642 return; 3643 } 3644 3645 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3646 3647 // Critical, after this call app should never have the permission. 3648 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3649 3650 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3651 } 3652 3653 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3654 } 3655 3656 @Override 3657 public void resetRuntimePermissions() { 3658 mContext.enforceCallingOrSelfPermission( 3659 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3660 "revokeRuntimePermission"); 3661 3662 int callingUid = Binder.getCallingUid(); 3663 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3664 mContext.enforceCallingOrSelfPermission( 3665 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3666 "resetRuntimePermissions"); 3667 } 3668 3669 synchronized (mPackages) { 3670 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3671 for (int userId : UserManagerService.getInstance().getUserIds()) { 3672 final int packageCount = mPackages.size(); 3673 for (int i = 0; i < packageCount; i++) { 3674 PackageParser.Package pkg = mPackages.valueAt(i); 3675 if (!(pkg.mExtras instanceof PackageSetting)) { 3676 continue; 3677 } 3678 PackageSetting ps = (PackageSetting) pkg.mExtras; 3679 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3680 } 3681 } 3682 } 3683 } 3684 3685 @Override 3686 public int getPermissionFlags(String name, String packageName, int userId) { 3687 if (!sUserManager.exists(userId)) { 3688 return 0; 3689 } 3690 3691 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3692 3693 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3694 "getPermissionFlags"); 3695 3696 synchronized (mPackages) { 3697 final PackageParser.Package pkg = mPackages.get(packageName); 3698 if (pkg == null) { 3699 throw new IllegalArgumentException("Unknown package: " + packageName); 3700 } 3701 3702 final BasePermission bp = mSettings.mPermissions.get(name); 3703 if (bp == null) { 3704 throw new IllegalArgumentException("Unknown permission: " + name); 3705 } 3706 3707 SettingBase sb = (SettingBase) pkg.mExtras; 3708 if (sb == null) { 3709 throw new IllegalArgumentException("Unknown package: " + packageName); 3710 } 3711 3712 PermissionsState permissionsState = sb.getPermissionsState(); 3713 return permissionsState.getPermissionFlags(name, userId); 3714 } 3715 } 3716 3717 @Override 3718 public void updatePermissionFlags(String name, String packageName, int flagMask, 3719 int flagValues, int userId) { 3720 if (!sUserManager.exists(userId)) { 3721 return; 3722 } 3723 3724 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3725 3726 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3727 "updatePermissionFlags"); 3728 3729 // Only the system can change these flags and nothing else. 3730 if (getCallingUid() != Process.SYSTEM_UID) { 3731 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3732 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3733 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3734 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3735 } 3736 3737 synchronized (mPackages) { 3738 final PackageParser.Package pkg = mPackages.get(packageName); 3739 if (pkg == null) { 3740 throw new IllegalArgumentException("Unknown package: " + packageName); 3741 } 3742 3743 final BasePermission bp = mSettings.mPermissions.get(name); 3744 if (bp == null) { 3745 throw new IllegalArgumentException("Unknown permission: " + name); 3746 } 3747 3748 SettingBase sb = (SettingBase) pkg.mExtras; 3749 if (sb == null) { 3750 throw new IllegalArgumentException("Unknown package: " + packageName); 3751 } 3752 3753 PermissionsState permissionsState = sb.getPermissionsState(); 3754 3755 // Only the package manager can change flags for system component permissions. 3756 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3757 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3758 return; 3759 } 3760 3761 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3762 3763 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3764 // Install and runtime permissions are stored in different places, 3765 // so figure out what permission changed and persist the change. 3766 if (permissionsState.getInstallPermissionState(name) != null) { 3767 scheduleWriteSettingsLocked(); 3768 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3769 || hadState) { 3770 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3771 } 3772 } 3773 } 3774 } 3775 3776 /** 3777 * Update the permission flags for all packages and runtime permissions of a user in order 3778 * to allow device or profile owner to remove POLICY_FIXED. 3779 */ 3780 @Override 3781 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3782 if (!sUserManager.exists(userId)) { 3783 return; 3784 } 3785 3786 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3787 3788 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3789 "updatePermissionFlagsForAllApps"); 3790 3791 // Only the system can change system fixed flags. 3792 if (getCallingUid() != Process.SYSTEM_UID) { 3793 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3794 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3795 } 3796 3797 synchronized (mPackages) { 3798 boolean changed = false; 3799 final int packageCount = mPackages.size(); 3800 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3801 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3802 SettingBase sb = (SettingBase) pkg.mExtras; 3803 if (sb == null) { 3804 continue; 3805 } 3806 PermissionsState permissionsState = sb.getPermissionsState(); 3807 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3808 userId, flagMask, flagValues); 3809 } 3810 if (changed) { 3811 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3812 } 3813 } 3814 } 3815 3816 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3817 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3818 != PackageManager.PERMISSION_GRANTED 3819 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3820 != PackageManager.PERMISSION_GRANTED) { 3821 throw new SecurityException(message + " requires " 3822 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3823 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3824 } 3825 } 3826 3827 @Override 3828 public boolean shouldShowRequestPermissionRationale(String permissionName, 3829 String packageName, int userId) { 3830 if (UserHandle.getCallingUserId() != userId) { 3831 mContext.enforceCallingPermission( 3832 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3833 "canShowRequestPermissionRationale for user " + userId); 3834 } 3835 3836 final int uid = getPackageUid(packageName, userId); 3837 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3838 return false; 3839 } 3840 3841 if (checkPermission(permissionName, packageName, userId) 3842 == PackageManager.PERMISSION_GRANTED) { 3843 return false; 3844 } 3845 3846 final int flags; 3847 3848 final long identity = Binder.clearCallingIdentity(); 3849 try { 3850 flags = getPermissionFlags(permissionName, 3851 packageName, userId); 3852 } finally { 3853 Binder.restoreCallingIdentity(identity); 3854 } 3855 3856 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3857 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3858 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3859 3860 if ((flags & fixedFlags) != 0) { 3861 return false; 3862 } 3863 3864 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3865 } 3866 3867 @Override 3868 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3869 mContext.enforceCallingOrSelfPermission( 3870 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3871 "addOnPermissionsChangeListener"); 3872 3873 synchronized (mPackages) { 3874 mOnPermissionChangeListeners.addListenerLocked(listener); 3875 } 3876 } 3877 3878 @Override 3879 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3880 synchronized (mPackages) { 3881 mOnPermissionChangeListeners.removeListenerLocked(listener); 3882 } 3883 } 3884 3885 @Override 3886 public boolean isProtectedBroadcast(String actionName) { 3887 synchronized (mPackages) { 3888 return mProtectedBroadcasts.contains(actionName); 3889 } 3890 } 3891 3892 @Override 3893 public int checkSignatures(String pkg1, String pkg2) { 3894 synchronized (mPackages) { 3895 final PackageParser.Package p1 = mPackages.get(pkg1); 3896 final PackageParser.Package p2 = mPackages.get(pkg2); 3897 if (p1 == null || p1.mExtras == null 3898 || p2 == null || p2.mExtras == null) { 3899 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3900 } 3901 return compareSignatures(p1.mSignatures, p2.mSignatures); 3902 } 3903 } 3904 3905 @Override 3906 public int checkUidSignatures(int uid1, int uid2) { 3907 // Map to base uids. 3908 uid1 = UserHandle.getAppId(uid1); 3909 uid2 = UserHandle.getAppId(uid2); 3910 // reader 3911 synchronized (mPackages) { 3912 Signature[] s1; 3913 Signature[] s2; 3914 Object obj = mSettings.getUserIdLPr(uid1); 3915 if (obj != null) { 3916 if (obj instanceof SharedUserSetting) { 3917 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3918 } else if (obj instanceof PackageSetting) { 3919 s1 = ((PackageSetting)obj).signatures.mSignatures; 3920 } else { 3921 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3922 } 3923 } else { 3924 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3925 } 3926 obj = mSettings.getUserIdLPr(uid2); 3927 if (obj != null) { 3928 if (obj instanceof SharedUserSetting) { 3929 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3930 } else if (obj instanceof PackageSetting) { 3931 s2 = ((PackageSetting)obj).signatures.mSignatures; 3932 } else { 3933 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3934 } 3935 } else { 3936 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3937 } 3938 return compareSignatures(s1, s2); 3939 } 3940 } 3941 3942 private void killUid(int appId, int userId, String reason) { 3943 final long identity = Binder.clearCallingIdentity(); 3944 try { 3945 IActivityManager am = ActivityManagerNative.getDefault(); 3946 if (am != null) { 3947 try { 3948 am.killUid(appId, userId, reason); 3949 } catch (RemoteException e) { 3950 /* ignore - same process */ 3951 } 3952 } 3953 } finally { 3954 Binder.restoreCallingIdentity(identity); 3955 } 3956 } 3957 3958 /** 3959 * Compares two sets of signatures. Returns: 3960 * <br /> 3961 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3962 * <br /> 3963 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3964 * <br /> 3965 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3966 * <br /> 3967 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3968 * <br /> 3969 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3970 */ 3971 static int compareSignatures(Signature[] s1, Signature[] s2) { 3972 if (s1 == null) { 3973 return s2 == null 3974 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3975 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3976 } 3977 3978 if (s2 == null) { 3979 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3980 } 3981 3982 if (s1.length != s2.length) { 3983 return PackageManager.SIGNATURE_NO_MATCH; 3984 } 3985 3986 // Since both signature sets are of size 1, we can compare without HashSets. 3987 if (s1.length == 1) { 3988 return s1[0].equals(s2[0]) ? 3989 PackageManager.SIGNATURE_MATCH : 3990 PackageManager.SIGNATURE_NO_MATCH; 3991 } 3992 3993 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3994 for (Signature sig : s1) { 3995 set1.add(sig); 3996 } 3997 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3998 for (Signature sig : s2) { 3999 set2.add(sig); 4000 } 4001 // Make sure s2 contains all signatures in s1. 4002 if (set1.equals(set2)) { 4003 return PackageManager.SIGNATURE_MATCH; 4004 } 4005 return PackageManager.SIGNATURE_NO_MATCH; 4006 } 4007 4008 /** 4009 * If the database version for this type of package (internal storage or 4010 * external storage) is less than the version where package signatures 4011 * were updated, return true. 4012 */ 4013 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4014 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4015 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4016 } 4017 4018 /** 4019 * Used for backward compatibility to make sure any packages with 4020 * certificate chains get upgraded to the new style. {@code existingSigs} 4021 * will be in the old format (since they were stored on disk from before the 4022 * system upgrade) and {@code scannedSigs} will be in the newer format. 4023 */ 4024 private int compareSignaturesCompat(PackageSignatures existingSigs, 4025 PackageParser.Package scannedPkg) { 4026 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4027 return PackageManager.SIGNATURE_NO_MATCH; 4028 } 4029 4030 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4031 for (Signature sig : existingSigs.mSignatures) { 4032 existingSet.add(sig); 4033 } 4034 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4035 for (Signature sig : scannedPkg.mSignatures) { 4036 try { 4037 Signature[] chainSignatures = sig.getChainSignatures(); 4038 for (Signature chainSig : chainSignatures) { 4039 scannedCompatSet.add(chainSig); 4040 } 4041 } catch (CertificateEncodingException e) { 4042 scannedCompatSet.add(sig); 4043 } 4044 } 4045 /* 4046 * Make sure the expanded scanned set contains all signatures in the 4047 * existing one. 4048 */ 4049 if (scannedCompatSet.equals(existingSet)) { 4050 // Migrate the old signatures to the new scheme. 4051 existingSigs.assignSignatures(scannedPkg.mSignatures); 4052 // The new KeySets will be re-added later in the scanning process. 4053 synchronized (mPackages) { 4054 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4055 } 4056 return PackageManager.SIGNATURE_MATCH; 4057 } 4058 return PackageManager.SIGNATURE_NO_MATCH; 4059 } 4060 4061 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4062 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4063 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4064 } 4065 4066 private int compareSignaturesRecover(PackageSignatures existingSigs, 4067 PackageParser.Package scannedPkg) { 4068 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4069 return PackageManager.SIGNATURE_NO_MATCH; 4070 } 4071 4072 String msg = null; 4073 try { 4074 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4075 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4076 + scannedPkg.packageName); 4077 return PackageManager.SIGNATURE_MATCH; 4078 } 4079 } catch (CertificateException e) { 4080 msg = e.getMessage(); 4081 } 4082 4083 logCriticalInfo(Log.INFO, 4084 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4085 return PackageManager.SIGNATURE_NO_MATCH; 4086 } 4087 4088 @Override 4089 public String[] getPackagesForUid(int uid) { 4090 uid = UserHandle.getAppId(uid); 4091 // reader 4092 synchronized (mPackages) { 4093 Object obj = mSettings.getUserIdLPr(uid); 4094 if (obj instanceof SharedUserSetting) { 4095 final SharedUserSetting sus = (SharedUserSetting) obj; 4096 final int N = sus.packages.size(); 4097 final String[] res = new String[N]; 4098 final Iterator<PackageSetting> it = sus.packages.iterator(); 4099 int i = 0; 4100 while (it.hasNext()) { 4101 res[i++] = it.next().name; 4102 } 4103 return res; 4104 } else if (obj instanceof PackageSetting) { 4105 final PackageSetting ps = (PackageSetting) obj; 4106 return new String[] { ps.name }; 4107 } 4108 } 4109 return null; 4110 } 4111 4112 @Override 4113 public String getNameForUid(int uid) { 4114 // reader 4115 synchronized (mPackages) { 4116 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4117 if (obj instanceof SharedUserSetting) { 4118 final SharedUserSetting sus = (SharedUserSetting) obj; 4119 return sus.name + ":" + sus.userId; 4120 } else if (obj instanceof PackageSetting) { 4121 final PackageSetting ps = (PackageSetting) obj; 4122 return ps.name; 4123 } 4124 } 4125 return null; 4126 } 4127 4128 @Override 4129 public int getUidForSharedUser(String sharedUserName) { 4130 if(sharedUserName == null) { 4131 return -1; 4132 } 4133 // reader 4134 synchronized (mPackages) { 4135 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4136 if (suid == null) { 4137 return -1; 4138 } 4139 return suid.userId; 4140 } 4141 } 4142 4143 @Override 4144 public int getFlagsForUid(int uid) { 4145 synchronized (mPackages) { 4146 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4147 if (obj instanceof SharedUserSetting) { 4148 final SharedUserSetting sus = (SharedUserSetting) obj; 4149 return sus.pkgFlags; 4150 } else if (obj instanceof PackageSetting) { 4151 final PackageSetting ps = (PackageSetting) obj; 4152 return ps.pkgFlags; 4153 } 4154 } 4155 return 0; 4156 } 4157 4158 @Override 4159 public int getPrivateFlagsForUid(int uid) { 4160 synchronized (mPackages) { 4161 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4162 if (obj instanceof SharedUserSetting) { 4163 final SharedUserSetting sus = (SharedUserSetting) obj; 4164 return sus.pkgPrivateFlags; 4165 } else if (obj instanceof PackageSetting) { 4166 final PackageSetting ps = (PackageSetting) obj; 4167 return ps.pkgPrivateFlags; 4168 } 4169 } 4170 return 0; 4171 } 4172 4173 @Override 4174 public boolean isUidPrivileged(int uid) { 4175 uid = UserHandle.getAppId(uid); 4176 // reader 4177 synchronized (mPackages) { 4178 Object obj = mSettings.getUserIdLPr(uid); 4179 if (obj instanceof SharedUserSetting) { 4180 final SharedUserSetting sus = (SharedUserSetting) obj; 4181 final Iterator<PackageSetting> it = sus.packages.iterator(); 4182 while (it.hasNext()) { 4183 if (it.next().isPrivileged()) { 4184 return true; 4185 } 4186 } 4187 } else if (obj instanceof PackageSetting) { 4188 final PackageSetting ps = (PackageSetting) obj; 4189 return ps.isPrivileged(); 4190 } 4191 } 4192 return false; 4193 } 4194 4195 @Override 4196 public String[] getAppOpPermissionPackages(String permissionName) { 4197 synchronized (mPackages) { 4198 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4199 if (pkgs == null) { 4200 return null; 4201 } 4202 return pkgs.toArray(new String[pkgs.size()]); 4203 } 4204 } 4205 4206 @Override 4207 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4208 int flags, int userId) { 4209 if (!sUserManager.exists(userId)) return null; 4210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4211 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4212 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4213 } 4214 4215 @Override 4216 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4217 IntentFilter filter, int match, ComponentName activity) { 4218 final int userId = UserHandle.getCallingUserId(); 4219 if (DEBUG_PREFERRED) { 4220 Log.v(TAG, "setLastChosenActivity intent=" + intent 4221 + " resolvedType=" + resolvedType 4222 + " flags=" + flags 4223 + " filter=" + filter 4224 + " match=" + match 4225 + " activity=" + activity); 4226 filter.dump(new PrintStreamPrinter(System.out), " "); 4227 } 4228 intent.setComponent(null); 4229 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4230 // Find any earlier preferred or last chosen entries and nuke them 4231 findPreferredActivity(intent, resolvedType, 4232 flags, query, 0, false, true, false, userId); 4233 // Add the new activity as the last chosen for this filter 4234 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4235 "Setting last chosen"); 4236 } 4237 4238 @Override 4239 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4240 final int userId = UserHandle.getCallingUserId(); 4241 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4242 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4243 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4244 false, false, false, userId); 4245 } 4246 4247 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4248 int flags, List<ResolveInfo> query, int userId) { 4249 if (query != null) { 4250 final int N = query.size(); 4251 if (N == 1) { 4252 return query.get(0); 4253 } else if (N > 1) { 4254 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4255 // If there is more than one activity with the same priority, 4256 // then let the user decide between them. 4257 ResolveInfo r0 = query.get(0); 4258 ResolveInfo r1 = query.get(1); 4259 if (DEBUG_INTENT_MATCHING || debug) { 4260 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4261 + r1.activityInfo.name + "=" + r1.priority); 4262 } 4263 // If the first activity has a higher priority, or a different 4264 // default, then it is always desireable to pick it. 4265 if (r0.priority != r1.priority 4266 || r0.preferredOrder != r1.preferredOrder 4267 || r0.isDefault != r1.isDefault) { 4268 return query.get(0); 4269 } 4270 // If we have saved a preference for a preferred activity for 4271 // this Intent, use that. 4272 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4273 flags, query, r0.priority, true, false, debug, userId); 4274 if (ri != null) { 4275 return ri; 4276 } 4277 ri = new ResolveInfo(mResolveInfo); 4278 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4279 ri.activityInfo.applicationInfo = new ApplicationInfo( 4280 ri.activityInfo.applicationInfo); 4281 if (userId != 0) { 4282 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4283 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4284 } 4285 // Make sure that the resolver is displayable in car mode 4286 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4287 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4288 return ri; 4289 } 4290 } 4291 return null; 4292 } 4293 4294 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4295 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4296 final int N = query.size(); 4297 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4298 .get(userId); 4299 // Get the list of persistent preferred activities that handle the intent 4300 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4301 List<PersistentPreferredActivity> pprefs = ppir != null 4302 ? ppir.queryIntent(intent, resolvedType, 4303 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4304 : null; 4305 if (pprefs != null && pprefs.size() > 0) { 4306 final int M = pprefs.size(); 4307 for (int i=0; i<M; i++) { 4308 final PersistentPreferredActivity ppa = pprefs.get(i); 4309 if (DEBUG_PREFERRED || debug) { 4310 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4311 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4312 + "\n component=" + ppa.mComponent); 4313 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4314 } 4315 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4316 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4317 if (DEBUG_PREFERRED || debug) { 4318 Slog.v(TAG, "Found persistent preferred activity:"); 4319 if (ai != null) { 4320 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4321 } else { 4322 Slog.v(TAG, " null"); 4323 } 4324 } 4325 if (ai == null) { 4326 // This previously registered persistent preferred activity 4327 // component is no longer known. Ignore it and do NOT remove it. 4328 continue; 4329 } 4330 for (int j=0; j<N; j++) { 4331 final ResolveInfo ri = query.get(j); 4332 if (!ri.activityInfo.applicationInfo.packageName 4333 .equals(ai.applicationInfo.packageName)) { 4334 continue; 4335 } 4336 if (!ri.activityInfo.name.equals(ai.name)) { 4337 continue; 4338 } 4339 // Found a persistent preference that can handle the intent. 4340 if (DEBUG_PREFERRED || debug) { 4341 Slog.v(TAG, "Returning persistent preferred activity: " + 4342 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4343 } 4344 return ri; 4345 } 4346 } 4347 } 4348 return null; 4349 } 4350 4351 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4352 List<ResolveInfo> query, int priority, boolean always, 4353 boolean removeMatches, boolean debug, int userId) { 4354 if (!sUserManager.exists(userId)) return null; 4355 // writer 4356 synchronized (mPackages) { 4357 if (intent.getSelector() != null) { 4358 intent = intent.getSelector(); 4359 } 4360 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4361 4362 // Try to find a matching persistent preferred activity. 4363 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4364 debug, userId); 4365 4366 // If a persistent preferred activity matched, use it. 4367 if (pri != null) { 4368 return pri; 4369 } 4370 4371 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4372 // Get the list of preferred activities that handle the intent 4373 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4374 List<PreferredActivity> prefs = pir != null 4375 ? pir.queryIntent(intent, resolvedType, 4376 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4377 : null; 4378 if (prefs != null && prefs.size() > 0) { 4379 boolean changed = false; 4380 try { 4381 // First figure out how good the original match set is. 4382 // We will only allow preferred activities that came 4383 // from the same match quality. 4384 int match = 0; 4385 4386 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4387 4388 final int N = query.size(); 4389 for (int j=0; j<N; j++) { 4390 final ResolveInfo ri = query.get(j); 4391 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4392 + ": 0x" + Integer.toHexString(match)); 4393 if (ri.match > match) { 4394 match = ri.match; 4395 } 4396 } 4397 4398 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4399 + Integer.toHexString(match)); 4400 4401 match &= IntentFilter.MATCH_CATEGORY_MASK; 4402 final int M = prefs.size(); 4403 for (int i=0; i<M; i++) { 4404 final PreferredActivity pa = prefs.get(i); 4405 if (DEBUG_PREFERRED || debug) { 4406 Slog.v(TAG, "Checking PreferredActivity ds=" 4407 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4408 + "\n component=" + pa.mPref.mComponent); 4409 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4410 } 4411 if (pa.mPref.mMatch != match) { 4412 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4413 + Integer.toHexString(pa.mPref.mMatch)); 4414 continue; 4415 } 4416 // If it's not an "always" type preferred activity and that's what we're 4417 // looking for, skip it. 4418 if (always && !pa.mPref.mAlways) { 4419 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4420 continue; 4421 } 4422 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4423 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4424 if (DEBUG_PREFERRED || debug) { 4425 Slog.v(TAG, "Found preferred activity:"); 4426 if (ai != null) { 4427 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4428 } else { 4429 Slog.v(TAG, " null"); 4430 } 4431 } 4432 if (ai == null) { 4433 // This previously registered preferred activity 4434 // component is no longer known. Most likely an update 4435 // to the app was installed and in the new version this 4436 // component no longer exists. Clean it up by removing 4437 // it from the preferred activities list, and skip it. 4438 Slog.w(TAG, "Removing dangling preferred activity: " 4439 + pa.mPref.mComponent); 4440 pir.removeFilter(pa); 4441 changed = true; 4442 continue; 4443 } 4444 for (int j=0; j<N; j++) { 4445 final ResolveInfo ri = query.get(j); 4446 if (!ri.activityInfo.applicationInfo.packageName 4447 .equals(ai.applicationInfo.packageName)) { 4448 continue; 4449 } 4450 if (!ri.activityInfo.name.equals(ai.name)) { 4451 continue; 4452 } 4453 4454 if (removeMatches) { 4455 pir.removeFilter(pa); 4456 changed = true; 4457 if (DEBUG_PREFERRED) { 4458 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4459 } 4460 break; 4461 } 4462 4463 // Okay we found a previously set preferred or last chosen app. 4464 // If the result set is different from when this 4465 // was created, we need to clear it and re-ask the 4466 // user their preference, if we're looking for an "always" type entry. 4467 if (always && !pa.mPref.sameSet(query)) { 4468 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4469 + intent + " type " + resolvedType); 4470 if (DEBUG_PREFERRED) { 4471 Slog.v(TAG, "Removing preferred activity since set changed " 4472 + pa.mPref.mComponent); 4473 } 4474 pir.removeFilter(pa); 4475 // Re-add the filter as a "last chosen" entry (!always) 4476 PreferredActivity lastChosen = new PreferredActivity( 4477 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4478 pir.addFilter(lastChosen); 4479 changed = true; 4480 return null; 4481 } 4482 4483 // Yay! Either the set matched or we're looking for the last chosen 4484 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4485 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4486 return ri; 4487 } 4488 } 4489 } finally { 4490 if (changed) { 4491 if (DEBUG_PREFERRED) { 4492 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4493 } 4494 scheduleWritePackageRestrictionsLocked(userId); 4495 } 4496 } 4497 } 4498 } 4499 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4500 return null; 4501 } 4502 4503 /* 4504 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4505 */ 4506 @Override 4507 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4508 int targetUserId) { 4509 mContext.enforceCallingOrSelfPermission( 4510 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4511 List<CrossProfileIntentFilter> matches = 4512 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4513 if (matches != null) { 4514 int size = matches.size(); 4515 for (int i = 0; i < size; i++) { 4516 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4517 } 4518 } 4519 if (hasWebURI(intent)) { 4520 // cross-profile app linking works only towards the parent. 4521 final UserInfo parent = getProfileParent(sourceUserId); 4522 synchronized(mPackages) { 4523 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4524 intent, resolvedType, 0, sourceUserId, parent.id); 4525 return xpDomainInfo != null; 4526 } 4527 } 4528 return false; 4529 } 4530 4531 private UserInfo getProfileParent(int userId) { 4532 final long identity = Binder.clearCallingIdentity(); 4533 try { 4534 return sUserManager.getProfileParent(userId); 4535 } finally { 4536 Binder.restoreCallingIdentity(identity); 4537 } 4538 } 4539 4540 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4541 String resolvedType, int userId) { 4542 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4543 if (resolver != null) { 4544 return resolver.queryIntent(intent, resolvedType, false, userId); 4545 } 4546 return null; 4547 } 4548 4549 @Override 4550 public List<ResolveInfo> queryIntentActivities(Intent intent, 4551 String resolvedType, int flags, int userId) { 4552 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4553 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4554 ComponentName comp = intent.getComponent(); 4555 if (comp == null) { 4556 if (intent.getSelector() != null) { 4557 intent = intent.getSelector(); 4558 comp = intent.getComponent(); 4559 } 4560 } 4561 4562 if (comp != null) { 4563 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4564 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4565 if (ai != null) { 4566 final ResolveInfo ri = new ResolveInfo(); 4567 ri.activityInfo = ai; 4568 list.add(ri); 4569 } 4570 return list; 4571 } 4572 4573 // reader 4574 synchronized (mPackages) { 4575 final String pkgName = intent.getPackage(); 4576 if (pkgName == null) { 4577 List<CrossProfileIntentFilter> matchingFilters = 4578 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4579 // Check for results that need to skip the current profile. 4580 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4581 resolvedType, flags, userId); 4582 if (xpResolveInfo != null) { 4583 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4584 result.add(xpResolveInfo); 4585 return filterIfNotSystemUser(result, userId); 4586 } 4587 4588 // Check for results in the current profile. 4589 List<ResolveInfo> result = mActivities.queryIntent( 4590 intent, resolvedType, flags, userId); 4591 4592 // Check for cross profile results. 4593 xpResolveInfo = queryCrossProfileIntents( 4594 matchingFilters, intent, resolvedType, flags, userId); 4595 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4596 result.add(xpResolveInfo); 4597 Collections.sort(result, mResolvePrioritySorter); 4598 } 4599 result = filterIfNotSystemUser(result, userId); 4600 if (hasWebURI(intent)) { 4601 CrossProfileDomainInfo xpDomainInfo = null; 4602 final UserInfo parent = getProfileParent(userId); 4603 if (parent != null) { 4604 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4605 flags, userId, parent.id); 4606 } 4607 if (xpDomainInfo != null) { 4608 if (xpResolveInfo != null) { 4609 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4610 // in the result. 4611 result.remove(xpResolveInfo); 4612 } 4613 if (result.size() == 0) { 4614 result.add(xpDomainInfo.resolveInfo); 4615 return result; 4616 } 4617 } else if (result.size() <= 1) { 4618 return result; 4619 } 4620 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4621 xpDomainInfo, userId); 4622 Collections.sort(result, mResolvePrioritySorter); 4623 } 4624 return result; 4625 } 4626 final PackageParser.Package pkg = mPackages.get(pkgName); 4627 if (pkg != null) { 4628 return filterIfNotSystemUser( 4629 mActivities.queryIntentForPackage( 4630 intent, resolvedType, flags, pkg.activities, userId), 4631 userId); 4632 } 4633 return new ArrayList<ResolveInfo>(); 4634 } 4635 } 4636 4637 private static class CrossProfileDomainInfo { 4638 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4639 ResolveInfo resolveInfo; 4640 /* Best domain verification status of the activities found in the other profile */ 4641 int bestDomainVerificationStatus; 4642 } 4643 4644 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4645 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4646 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4647 sourceUserId)) { 4648 return null; 4649 } 4650 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4651 resolvedType, flags, parentUserId); 4652 4653 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4654 return null; 4655 } 4656 CrossProfileDomainInfo result = null; 4657 int size = resultTargetUser.size(); 4658 for (int i = 0; i < size; i++) { 4659 ResolveInfo riTargetUser = resultTargetUser.get(i); 4660 // Intent filter verification is only for filters that specify a host. So don't return 4661 // those that handle all web uris. 4662 if (riTargetUser.handleAllWebDataURI) { 4663 continue; 4664 } 4665 String packageName = riTargetUser.activityInfo.packageName; 4666 PackageSetting ps = mSettings.mPackages.get(packageName); 4667 if (ps == null) { 4668 continue; 4669 } 4670 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4671 int status = (int)(verificationState >> 32); 4672 if (result == null) { 4673 result = new CrossProfileDomainInfo(); 4674 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4675 sourceUserId, parentUserId); 4676 result.bestDomainVerificationStatus = status; 4677 } else { 4678 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4679 result.bestDomainVerificationStatus); 4680 } 4681 } 4682 // Don't consider matches with status NEVER across profiles. 4683 if (result != null && result.bestDomainVerificationStatus 4684 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4685 return null; 4686 } 4687 return result; 4688 } 4689 4690 /** 4691 * Verification statuses are ordered from the worse to the best, except for 4692 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4693 */ 4694 private int bestDomainVerificationStatus(int status1, int status2) { 4695 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4696 return status2; 4697 } 4698 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4699 return status1; 4700 } 4701 return (int) MathUtils.max(status1, status2); 4702 } 4703 4704 private boolean isUserEnabled(int userId) { 4705 long callingId = Binder.clearCallingIdentity(); 4706 try { 4707 UserInfo userInfo = sUserManager.getUserInfo(userId); 4708 return userInfo != null && userInfo.isEnabled(); 4709 } finally { 4710 Binder.restoreCallingIdentity(callingId); 4711 } 4712 } 4713 4714 /** 4715 * Filter out activities with systemUserOnly flag set, when current user is not System. 4716 * 4717 * @return filtered list 4718 */ 4719 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4720 if (userId == UserHandle.USER_SYSTEM) { 4721 return resolveInfos; 4722 } 4723 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4724 ResolveInfo info = resolveInfos.get(i); 4725 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4726 resolveInfos.remove(i); 4727 } 4728 } 4729 return resolveInfos; 4730 } 4731 4732 private static boolean hasWebURI(Intent intent) { 4733 if (intent.getData() == null) { 4734 return false; 4735 } 4736 final String scheme = intent.getScheme(); 4737 if (TextUtils.isEmpty(scheme)) { 4738 return false; 4739 } 4740 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4741 } 4742 4743 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4744 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4745 int userId) { 4746 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4747 4748 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4749 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4750 candidates.size()); 4751 } 4752 4753 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4754 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4755 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4756 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4757 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4758 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4759 4760 synchronized (mPackages) { 4761 final int count = candidates.size(); 4762 // First, try to use linked apps. Partition the candidates into four lists: 4763 // one for the final results, one for the "do not use ever", one for "undefined status" 4764 // and finally one for "browser app type". 4765 for (int n=0; n<count; n++) { 4766 ResolveInfo info = candidates.get(n); 4767 String packageName = info.activityInfo.packageName; 4768 PackageSetting ps = mSettings.mPackages.get(packageName); 4769 if (ps != null) { 4770 // Add to the special match all list (Browser use case) 4771 if (info.handleAllWebDataURI) { 4772 matchAllList.add(info); 4773 continue; 4774 } 4775 // Try to get the status from User settings first 4776 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4777 int status = (int)(packedStatus >> 32); 4778 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4779 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4780 if (DEBUG_DOMAIN_VERIFICATION) { 4781 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4782 + " : linkgen=" + linkGeneration); 4783 } 4784 // Use link-enabled generation as preferredOrder, i.e. 4785 // prefer newly-enabled over earlier-enabled. 4786 info.preferredOrder = linkGeneration; 4787 alwaysList.add(info); 4788 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4789 if (DEBUG_DOMAIN_VERIFICATION) { 4790 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4791 } 4792 neverList.add(info); 4793 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4794 if (DEBUG_DOMAIN_VERIFICATION) { 4795 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4796 } 4797 alwaysAskList.add(info); 4798 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4799 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4800 if (DEBUG_DOMAIN_VERIFICATION) { 4801 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4802 } 4803 undefinedList.add(info); 4804 } 4805 } 4806 } 4807 4808 // We'll want to include browser possibilities in a few cases 4809 boolean includeBrowser = false; 4810 4811 // First try to add the "always" resolution(s) for the current user, if any 4812 if (alwaysList.size() > 0) { 4813 result.addAll(alwaysList); 4814 // if there is an "always" for the parent user, add it. 4815 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4816 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4817 result.add(xpDomainInfo.resolveInfo); 4818 } else { 4819 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4820 result.addAll(undefinedList); 4821 if (xpDomainInfo != null && ( 4822 xpDomainInfo.bestDomainVerificationStatus 4823 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4824 || xpDomainInfo.bestDomainVerificationStatus 4825 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4826 result.add(xpDomainInfo.resolveInfo); 4827 } 4828 includeBrowser = true; 4829 } 4830 4831 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4832 // If there were 'always' entries their preferred order has been set, so we also 4833 // back that off to make the alternatives equivalent 4834 if (alwaysAskList.size() > 0) { 4835 for (ResolveInfo i : result) { 4836 i.preferredOrder = 0; 4837 } 4838 result.addAll(alwaysAskList); 4839 includeBrowser = true; 4840 } 4841 4842 if (includeBrowser) { 4843 // Also add browsers (all of them or only the default one) 4844 if (DEBUG_DOMAIN_VERIFICATION) { 4845 Slog.v(TAG, " ...including browsers in candidate set"); 4846 } 4847 if ((matchFlags & MATCH_ALL) != 0) { 4848 result.addAll(matchAllList); 4849 } else { 4850 // Browser/generic handling case. If there's a default browser, go straight 4851 // to that (but only if there is no other higher-priority match). 4852 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4853 int maxMatchPrio = 0; 4854 ResolveInfo defaultBrowserMatch = null; 4855 final int numCandidates = matchAllList.size(); 4856 for (int n = 0; n < numCandidates; n++) { 4857 ResolveInfo info = matchAllList.get(n); 4858 // track the highest overall match priority... 4859 if (info.priority > maxMatchPrio) { 4860 maxMatchPrio = info.priority; 4861 } 4862 // ...and the highest-priority default browser match 4863 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4864 if (defaultBrowserMatch == null 4865 || (defaultBrowserMatch.priority < info.priority)) { 4866 if (debug) { 4867 Slog.v(TAG, "Considering default browser match " + info); 4868 } 4869 defaultBrowserMatch = info; 4870 } 4871 } 4872 } 4873 if (defaultBrowserMatch != null 4874 && defaultBrowserMatch.priority >= maxMatchPrio 4875 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4876 { 4877 if (debug) { 4878 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4879 } 4880 result.add(defaultBrowserMatch); 4881 } else { 4882 result.addAll(matchAllList); 4883 } 4884 } 4885 4886 // If there is nothing selected, add all candidates and remove the ones that the user 4887 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4888 if (result.size() == 0) { 4889 result.addAll(candidates); 4890 result.removeAll(neverList); 4891 } 4892 } 4893 } 4894 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4895 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4896 result.size()); 4897 for (ResolveInfo info : result) { 4898 Slog.v(TAG, " + " + info.activityInfo); 4899 } 4900 } 4901 return result; 4902 } 4903 4904 // Returns a packed value as a long: 4905 // 4906 // high 'int'-sized word: link status: undefined/ask/never/always. 4907 // low 'int'-sized word: relative priority among 'always' results. 4908 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4909 long result = ps.getDomainVerificationStatusForUser(userId); 4910 // if none available, get the master status 4911 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4912 if (ps.getIntentFilterVerificationInfo() != null) { 4913 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4914 } 4915 } 4916 return result; 4917 } 4918 4919 private ResolveInfo querySkipCurrentProfileIntents( 4920 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4921 int flags, int sourceUserId) { 4922 if (matchingFilters != null) { 4923 int size = matchingFilters.size(); 4924 for (int i = 0; i < size; i ++) { 4925 CrossProfileIntentFilter filter = matchingFilters.get(i); 4926 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4927 // Checking if there are activities in the target user that can handle the 4928 // intent. 4929 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4930 resolvedType, flags, sourceUserId); 4931 if (resolveInfo != null) { 4932 return resolveInfo; 4933 } 4934 } 4935 } 4936 } 4937 return null; 4938 } 4939 4940 // Return matching ResolveInfo if any for skip current profile intent filters. 4941 private ResolveInfo queryCrossProfileIntents( 4942 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4943 int flags, int sourceUserId) { 4944 if (matchingFilters != null) { 4945 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4946 // match the same intent. For performance reasons, it is better not to 4947 // run queryIntent twice for the same userId 4948 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4949 int size = matchingFilters.size(); 4950 for (int i = 0; i < size; i++) { 4951 CrossProfileIntentFilter filter = matchingFilters.get(i); 4952 int targetUserId = filter.getTargetUserId(); 4953 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4954 && !alreadyTriedUserIds.get(targetUserId)) { 4955 // Checking if there are activities in the target user that can handle the 4956 // intent. 4957 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4958 resolvedType, flags, sourceUserId); 4959 if (resolveInfo != null) return resolveInfo; 4960 alreadyTriedUserIds.put(targetUserId, true); 4961 } 4962 } 4963 } 4964 return null; 4965 } 4966 4967 /** 4968 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4969 * will forward the intent to the filter's target user. 4970 * Otherwise, returns null. 4971 */ 4972 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4973 String resolvedType, int flags, int sourceUserId) { 4974 int targetUserId = filter.getTargetUserId(); 4975 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4976 resolvedType, flags, targetUserId); 4977 if (resultTargetUser != null && !resultTargetUser.isEmpty() 4978 && isUserEnabled(targetUserId)) { 4979 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 4980 } 4981 return null; 4982 } 4983 4984 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 4985 int sourceUserId, int targetUserId) { 4986 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4987 long ident = Binder.clearCallingIdentity(); 4988 boolean targetIsProfile; 4989 try { 4990 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4991 } finally { 4992 Binder.restoreCallingIdentity(ident); 4993 } 4994 String className; 4995 if (targetIsProfile) { 4996 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4997 } else { 4998 className = FORWARD_INTENT_TO_PARENT; 4999 } 5000 ComponentName forwardingActivityComponentName = new ComponentName( 5001 mAndroidApplication.packageName, className); 5002 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5003 sourceUserId); 5004 if (!targetIsProfile) { 5005 forwardingActivityInfo.showUserIcon = targetUserId; 5006 forwardingResolveInfo.noResourceId = true; 5007 } 5008 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5009 forwardingResolveInfo.priority = 0; 5010 forwardingResolveInfo.preferredOrder = 0; 5011 forwardingResolveInfo.match = 0; 5012 forwardingResolveInfo.isDefault = true; 5013 forwardingResolveInfo.filter = filter; 5014 forwardingResolveInfo.targetUserId = targetUserId; 5015 return forwardingResolveInfo; 5016 } 5017 5018 @Override 5019 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5020 Intent[] specifics, String[] specificTypes, Intent intent, 5021 String resolvedType, int flags, int userId) { 5022 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5023 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5024 false, "query intent activity options"); 5025 final String resultsAction = intent.getAction(); 5026 5027 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5028 | PackageManager.GET_RESOLVED_FILTER, userId); 5029 5030 if (DEBUG_INTENT_MATCHING) { 5031 Log.v(TAG, "Query " + intent + ": " + results); 5032 } 5033 5034 int specificsPos = 0; 5035 int N; 5036 5037 // todo: note that the algorithm used here is O(N^2). This 5038 // isn't a problem in our current environment, but if we start running 5039 // into situations where we have more than 5 or 10 matches then this 5040 // should probably be changed to something smarter... 5041 5042 // First we go through and resolve each of the specific items 5043 // that were supplied, taking care of removing any corresponding 5044 // duplicate items in the generic resolve list. 5045 if (specifics != null) { 5046 for (int i=0; i<specifics.length; i++) { 5047 final Intent sintent = specifics[i]; 5048 if (sintent == null) { 5049 continue; 5050 } 5051 5052 if (DEBUG_INTENT_MATCHING) { 5053 Log.v(TAG, "Specific #" + i + ": " + sintent); 5054 } 5055 5056 String action = sintent.getAction(); 5057 if (resultsAction != null && resultsAction.equals(action)) { 5058 // If this action was explicitly requested, then don't 5059 // remove things that have it. 5060 action = null; 5061 } 5062 5063 ResolveInfo ri = null; 5064 ActivityInfo ai = null; 5065 5066 ComponentName comp = sintent.getComponent(); 5067 if (comp == null) { 5068 ri = resolveIntent( 5069 sintent, 5070 specificTypes != null ? specificTypes[i] : null, 5071 flags, userId); 5072 if (ri == null) { 5073 continue; 5074 } 5075 if (ri == mResolveInfo) { 5076 // ACK! Must do something better with this. 5077 } 5078 ai = ri.activityInfo; 5079 comp = new ComponentName(ai.applicationInfo.packageName, 5080 ai.name); 5081 } else { 5082 ai = getActivityInfo(comp, flags, userId); 5083 if (ai == null) { 5084 continue; 5085 } 5086 } 5087 5088 // Look for any generic query activities that are duplicates 5089 // of this specific one, and remove them from the results. 5090 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5091 N = results.size(); 5092 int j; 5093 for (j=specificsPos; j<N; j++) { 5094 ResolveInfo sri = results.get(j); 5095 if ((sri.activityInfo.name.equals(comp.getClassName()) 5096 && sri.activityInfo.applicationInfo.packageName.equals( 5097 comp.getPackageName())) 5098 || (action != null && sri.filter.matchAction(action))) { 5099 results.remove(j); 5100 if (DEBUG_INTENT_MATCHING) Log.v( 5101 TAG, "Removing duplicate item from " + j 5102 + " due to specific " + specificsPos); 5103 if (ri == null) { 5104 ri = sri; 5105 } 5106 j--; 5107 N--; 5108 } 5109 } 5110 5111 // Add this specific item to its proper place. 5112 if (ri == null) { 5113 ri = new ResolveInfo(); 5114 ri.activityInfo = ai; 5115 } 5116 results.add(specificsPos, ri); 5117 ri.specificIndex = i; 5118 specificsPos++; 5119 } 5120 } 5121 5122 // Now we go through the remaining generic results and remove any 5123 // duplicate actions that are found here. 5124 N = results.size(); 5125 for (int i=specificsPos; i<N-1; i++) { 5126 final ResolveInfo rii = results.get(i); 5127 if (rii.filter == null) { 5128 continue; 5129 } 5130 5131 // Iterate over all of the actions of this result's intent 5132 // filter... typically this should be just one. 5133 final Iterator<String> it = rii.filter.actionsIterator(); 5134 if (it == null) { 5135 continue; 5136 } 5137 while (it.hasNext()) { 5138 final String action = it.next(); 5139 if (resultsAction != null && resultsAction.equals(action)) { 5140 // If this action was explicitly requested, then don't 5141 // remove things that have it. 5142 continue; 5143 } 5144 for (int j=i+1; j<N; j++) { 5145 final ResolveInfo rij = results.get(j); 5146 if (rij.filter != null && rij.filter.hasAction(action)) { 5147 results.remove(j); 5148 if (DEBUG_INTENT_MATCHING) Log.v( 5149 TAG, "Removing duplicate item from " + j 5150 + " due to action " + action + " at " + i); 5151 j--; 5152 N--; 5153 } 5154 } 5155 } 5156 5157 // If the caller didn't request filter information, drop it now 5158 // so we don't have to marshall/unmarshall it. 5159 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5160 rii.filter = null; 5161 } 5162 } 5163 5164 // Filter out the caller activity if so requested. 5165 if (caller != null) { 5166 N = results.size(); 5167 for (int i=0; i<N; i++) { 5168 ActivityInfo ainfo = results.get(i).activityInfo; 5169 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5170 && caller.getClassName().equals(ainfo.name)) { 5171 results.remove(i); 5172 break; 5173 } 5174 } 5175 } 5176 5177 // If the caller didn't request filter information, 5178 // drop them now so we don't have to 5179 // marshall/unmarshall it. 5180 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5181 N = results.size(); 5182 for (int i=0; i<N; i++) { 5183 results.get(i).filter = null; 5184 } 5185 } 5186 5187 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5188 return results; 5189 } 5190 5191 @Override 5192 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5193 int userId) { 5194 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5195 ComponentName comp = intent.getComponent(); 5196 if (comp == null) { 5197 if (intent.getSelector() != null) { 5198 intent = intent.getSelector(); 5199 comp = intent.getComponent(); 5200 } 5201 } 5202 if (comp != null) { 5203 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5204 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5205 if (ai != null) { 5206 ResolveInfo ri = new ResolveInfo(); 5207 ri.activityInfo = ai; 5208 list.add(ri); 5209 } 5210 return list; 5211 } 5212 5213 // reader 5214 synchronized (mPackages) { 5215 String pkgName = intent.getPackage(); 5216 if (pkgName == null) { 5217 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5218 } 5219 final PackageParser.Package pkg = mPackages.get(pkgName); 5220 if (pkg != null) { 5221 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5222 userId); 5223 } 5224 return null; 5225 } 5226 } 5227 5228 @Override 5229 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5230 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5231 if (!sUserManager.exists(userId)) return null; 5232 if (query != null) { 5233 if (query.size() >= 1) { 5234 // If there is more than one service with the same priority, 5235 // just arbitrarily pick the first one. 5236 return query.get(0); 5237 } 5238 } 5239 return null; 5240 } 5241 5242 @Override 5243 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5244 int userId) { 5245 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5246 ComponentName comp = intent.getComponent(); 5247 if (comp == null) { 5248 if (intent.getSelector() != null) { 5249 intent = intent.getSelector(); 5250 comp = intent.getComponent(); 5251 } 5252 } 5253 if (comp != null) { 5254 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5255 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5256 if (si != null) { 5257 final ResolveInfo ri = new ResolveInfo(); 5258 ri.serviceInfo = si; 5259 list.add(ri); 5260 } 5261 return list; 5262 } 5263 5264 // reader 5265 synchronized (mPackages) { 5266 String pkgName = intent.getPackage(); 5267 if (pkgName == null) { 5268 return mServices.queryIntent(intent, resolvedType, flags, userId); 5269 } 5270 final PackageParser.Package pkg = mPackages.get(pkgName); 5271 if (pkg != null) { 5272 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5273 userId); 5274 } 5275 return null; 5276 } 5277 } 5278 5279 @Override 5280 public List<ResolveInfo> queryIntentContentProviders( 5281 Intent intent, String resolvedType, int flags, int userId) { 5282 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5283 ComponentName comp = intent.getComponent(); 5284 if (comp == null) { 5285 if (intent.getSelector() != null) { 5286 intent = intent.getSelector(); 5287 comp = intent.getComponent(); 5288 } 5289 } 5290 if (comp != null) { 5291 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5292 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5293 if (pi != null) { 5294 final ResolveInfo ri = new ResolveInfo(); 5295 ri.providerInfo = pi; 5296 list.add(ri); 5297 } 5298 return list; 5299 } 5300 5301 // reader 5302 synchronized (mPackages) { 5303 String pkgName = intent.getPackage(); 5304 if (pkgName == null) { 5305 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5306 } 5307 final PackageParser.Package pkg = mPackages.get(pkgName); 5308 if (pkg != null) { 5309 return mProviders.queryIntentForPackage( 5310 intent, resolvedType, flags, pkg.providers, userId); 5311 } 5312 return null; 5313 } 5314 } 5315 5316 @Override 5317 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5318 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5319 5320 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5321 5322 // writer 5323 synchronized (mPackages) { 5324 ArrayList<PackageInfo> list; 5325 if (listUninstalled) { 5326 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5327 for (PackageSetting ps : mSettings.mPackages.values()) { 5328 PackageInfo pi; 5329 if (ps.pkg != null) { 5330 pi = generatePackageInfo(ps.pkg, flags, userId); 5331 } else { 5332 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5333 } 5334 if (pi != null) { 5335 list.add(pi); 5336 } 5337 } 5338 } else { 5339 list = new ArrayList<PackageInfo>(mPackages.size()); 5340 for (PackageParser.Package p : mPackages.values()) { 5341 PackageInfo pi = generatePackageInfo(p, flags, userId); 5342 if (pi != null) { 5343 list.add(pi); 5344 } 5345 } 5346 } 5347 5348 return new ParceledListSlice<PackageInfo>(list); 5349 } 5350 } 5351 5352 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5353 String[] permissions, boolean[] tmp, int flags, int userId) { 5354 int numMatch = 0; 5355 final PermissionsState permissionsState = ps.getPermissionsState(); 5356 for (int i=0; i<permissions.length; i++) { 5357 final String permission = permissions[i]; 5358 if (permissionsState.hasPermission(permission, userId)) { 5359 tmp[i] = true; 5360 numMatch++; 5361 } else { 5362 tmp[i] = false; 5363 } 5364 } 5365 if (numMatch == 0) { 5366 return; 5367 } 5368 PackageInfo pi; 5369 if (ps.pkg != null) { 5370 pi = generatePackageInfo(ps.pkg, flags, userId); 5371 } else { 5372 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5373 } 5374 // The above might return null in cases of uninstalled apps or install-state 5375 // skew across users/profiles. 5376 if (pi != null) { 5377 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5378 if (numMatch == permissions.length) { 5379 pi.requestedPermissions = permissions; 5380 } else { 5381 pi.requestedPermissions = new String[numMatch]; 5382 numMatch = 0; 5383 for (int i=0; i<permissions.length; i++) { 5384 if (tmp[i]) { 5385 pi.requestedPermissions[numMatch] = permissions[i]; 5386 numMatch++; 5387 } 5388 } 5389 } 5390 } 5391 list.add(pi); 5392 } 5393 } 5394 5395 @Override 5396 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5397 String[] permissions, int flags, int userId) { 5398 if (!sUserManager.exists(userId)) return null; 5399 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5400 5401 // writer 5402 synchronized (mPackages) { 5403 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5404 boolean[] tmpBools = new boolean[permissions.length]; 5405 if (listUninstalled) { 5406 for (PackageSetting ps : mSettings.mPackages.values()) { 5407 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5408 } 5409 } else { 5410 for (PackageParser.Package pkg : mPackages.values()) { 5411 PackageSetting ps = (PackageSetting)pkg.mExtras; 5412 if (ps != null) { 5413 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5414 userId); 5415 } 5416 } 5417 } 5418 5419 return new ParceledListSlice<PackageInfo>(list); 5420 } 5421 } 5422 5423 @Override 5424 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5425 if (!sUserManager.exists(userId)) return null; 5426 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5427 5428 // writer 5429 synchronized (mPackages) { 5430 ArrayList<ApplicationInfo> list; 5431 if (listUninstalled) { 5432 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5433 for (PackageSetting ps : mSettings.mPackages.values()) { 5434 ApplicationInfo ai; 5435 if (ps.pkg != null) { 5436 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5437 ps.readUserState(userId), userId); 5438 } else { 5439 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5440 } 5441 if (ai != null) { 5442 list.add(ai); 5443 } 5444 } 5445 } else { 5446 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5447 for (PackageParser.Package p : mPackages.values()) { 5448 if (p.mExtras != null) { 5449 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5450 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5451 if (ai != null) { 5452 list.add(ai); 5453 } 5454 } 5455 } 5456 } 5457 5458 return new ParceledListSlice<ApplicationInfo>(list); 5459 } 5460 } 5461 5462 public List<ApplicationInfo> getPersistentApplications(int flags) { 5463 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5464 5465 // reader 5466 synchronized (mPackages) { 5467 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5468 final int userId = UserHandle.getCallingUserId(); 5469 while (i.hasNext()) { 5470 final PackageParser.Package p = i.next(); 5471 if (p.applicationInfo != null 5472 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5473 && (!mSafeMode || isSystemApp(p))) { 5474 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5475 if (ps != null) { 5476 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5477 ps.readUserState(userId), userId); 5478 if (ai != null) { 5479 finalList.add(ai); 5480 } 5481 } 5482 } 5483 } 5484 } 5485 5486 return finalList; 5487 } 5488 5489 @Override 5490 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5491 if (!sUserManager.exists(userId)) return null; 5492 // reader 5493 synchronized (mPackages) { 5494 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5495 PackageSetting ps = provider != null 5496 ? mSettings.mPackages.get(provider.owner.packageName) 5497 : null; 5498 return ps != null 5499 && mSettings.isEnabledLPr(provider.info, flags, userId) 5500 && (!mSafeMode || (provider.info.applicationInfo.flags 5501 &ApplicationInfo.FLAG_SYSTEM) != 0) 5502 ? PackageParser.generateProviderInfo(provider, flags, 5503 ps.readUserState(userId), userId) 5504 : null; 5505 } 5506 } 5507 5508 /** 5509 * @deprecated 5510 */ 5511 @Deprecated 5512 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5513 // reader 5514 synchronized (mPackages) { 5515 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5516 .entrySet().iterator(); 5517 final int userId = UserHandle.getCallingUserId(); 5518 while (i.hasNext()) { 5519 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5520 PackageParser.Provider p = entry.getValue(); 5521 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5522 5523 if (ps != null && p.syncable 5524 && (!mSafeMode || (p.info.applicationInfo.flags 5525 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5526 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5527 ps.readUserState(userId), userId); 5528 if (info != null) { 5529 outNames.add(entry.getKey()); 5530 outInfo.add(info); 5531 } 5532 } 5533 } 5534 } 5535 } 5536 5537 @Override 5538 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5539 int uid, int flags) { 5540 ArrayList<ProviderInfo> finalList = null; 5541 // reader 5542 synchronized (mPackages) { 5543 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5544 final int userId = processName != null ? 5545 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5546 while (i.hasNext()) { 5547 final PackageParser.Provider p = i.next(); 5548 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5549 if (ps != null && p.info.authority != null 5550 && (processName == null 5551 || (p.info.processName.equals(processName) 5552 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5553 && mSettings.isEnabledLPr(p.info, flags, userId) 5554 && (!mSafeMode 5555 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5556 if (finalList == null) { 5557 finalList = new ArrayList<ProviderInfo>(3); 5558 } 5559 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5560 ps.readUserState(userId), userId); 5561 if (info != null) { 5562 finalList.add(info); 5563 } 5564 } 5565 } 5566 } 5567 5568 if (finalList != null) { 5569 Collections.sort(finalList, mProviderInitOrderSorter); 5570 return new ParceledListSlice<ProviderInfo>(finalList); 5571 } 5572 5573 return null; 5574 } 5575 5576 @Override 5577 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5578 int flags) { 5579 // reader 5580 synchronized (mPackages) { 5581 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5582 return PackageParser.generateInstrumentationInfo(i, flags); 5583 } 5584 } 5585 5586 @Override 5587 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5588 int flags) { 5589 ArrayList<InstrumentationInfo> finalList = 5590 new ArrayList<InstrumentationInfo>(); 5591 5592 // reader 5593 synchronized (mPackages) { 5594 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5595 while (i.hasNext()) { 5596 final PackageParser.Instrumentation p = i.next(); 5597 if (targetPackage == null 5598 || targetPackage.equals(p.info.targetPackage)) { 5599 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5600 flags); 5601 if (ii != null) { 5602 finalList.add(ii); 5603 } 5604 } 5605 } 5606 } 5607 5608 return finalList; 5609 } 5610 5611 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5612 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5613 if (overlays == null) { 5614 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5615 return; 5616 } 5617 for (PackageParser.Package opkg : overlays.values()) { 5618 // Not much to do if idmap fails: we already logged the error 5619 // and we certainly don't want to abort installation of pkg simply 5620 // because an overlay didn't fit properly. For these reasons, 5621 // ignore the return value of createIdmapForPackagePairLI. 5622 createIdmapForPackagePairLI(pkg, opkg); 5623 } 5624 } 5625 5626 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5627 PackageParser.Package opkg) { 5628 if (!opkg.mTrustedOverlay) { 5629 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5630 opkg.baseCodePath + ": overlay not trusted"); 5631 return false; 5632 } 5633 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5634 if (overlaySet == null) { 5635 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5636 opkg.baseCodePath + " but target package has no known overlays"); 5637 return false; 5638 } 5639 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5640 // TODO: generate idmap for split APKs 5641 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5642 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5643 + opkg.baseCodePath); 5644 return false; 5645 } 5646 PackageParser.Package[] overlayArray = 5647 overlaySet.values().toArray(new PackageParser.Package[0]); 5648 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5649 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5650 return p1.mOverlayPriority - p2.mOverlayPriority; 5651 } 5652 }; 5653 Arrays.sort(overlayArray, cmp); 5654 5655 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5656 int i = 0; 5657 for (PackageParser.Package p : overlayArray) { 5658 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5659 } 5660 return true; 5661 } 5662 5663 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5664 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5665 try { 5666 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5667 } finally { 5668 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5669 } 5670 } 5671 5672 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5673 final File[] files = dir.listFiles(); 5674 if (ArrayUtils.isEmpty(files)) { 5675 Log.d(TAG, "No files in app dir " + dir); 5676 return; 5677 } 5678 5679 if (DEBUG_PACKAGE_SCANNING) { 5680 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5681 + " flags=0x" + Integer.toHexString(parseFlags)); 5682 } 5683 5684 for (File file : files) { 5685 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5686 && !PackageInstallerService.isStageName(file.getName()); 5687 if (!isPackage) { 5688 // Ignore entries which are not packages 5689 continue; 5690 } 5691 try { 5692 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5693 scanFlags, currentTime, UserHandle.SYSTEM); 5694 } catch (PackageManagerException e) { 5695 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5696 5697 // Delete invalid userdata apps 5698 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5699 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5700 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5701 if (file.isDirectory()) { 5702 mInstaller.rmPackageDir(file.getAbsolutePath()); 5703 } else { 5704 file.delete(); 5705 } 5706 } 5707 } 5708 } 5709 } 5710 5711 private static File getSettingsProblemFile() { 5712 File dataDir = Environment.getDataDirectory(); 5713 File systemDir = new File(dataDir, "system"); 5714 File fname = new File(systemDir, "uiderrors.txt"); 5715 return fname; 5716 } 5717 5718 static void reportSettingsProblem(int priority, String msg) { 5719 logCriticalInfo(priority, msg); 5720 } 5721 5722 static void logCriticalInfo(int priority, String msg) { 5723 Slog.println(priority, TAG, msg); 5724 EventLogTags.writePmCriticalInfo(msg); 5725 try { 5726 File fname = getSettingsProblemFile(); 5727 FileOutputStream out = new FileOutputStream(fname, true); 5728 PrintWriter pw = new FastPrintWriter(out); 5729 SimpleDateFormat formatter = new SimpleDateFormat(); 5730 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5731 pw.println(dateString + ": " + msg); 5732 pw.close(); 5733 FileUtils.setPermissions( 5734 fname.toString(), 5735 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5736 -1, -1); 5737 } catch (java.io.IOException e) { 5738 } 5739 } 5740 5741 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5742 PackageParser.Package pkg, File srcFile, int parseFlags) 5743 throws PackageManagerException { 5744 if (ps != null 5745 && ps.codePath.equals(srcFile) 5746 && ps.timeStamp == srcFile.lastModified() 5747 && !isCompatSignatureUpdateNeeded(pkg) 5748 && !isRecoverSignatureUpdateNeeded(pkg)) { 5749 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5750 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5751 ArraySet<PublicKey> signingKs; 5752 synchronized (mPackages) { 5753 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5754 } 5755 if (ps.signatures.mSignatures != null 5756 && ps.signatures.mSignatures.length != 0 5757 && signingKs != null) { 5758 // Optimization: reuse the existing cached certificates 5759 // if the package appears to be unchanged. 5760 pkg.mSignatures = ps.signatures.mSignatures; 5761 pkg.mSigningKeys = signingKs; 5762 return; 5763 } 5764 5765 Slog.w(TAG, "PackageSetting for " + ps.name 5766 + " is missing signatures. Collecting certs again to recover them."); 5767 } else { 5768 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5769 } 5770 5771 try { 5772 pp.collectCertificates(pkg, parseFlags); 5773 pp.collectManifestDigest(pkg); 5774 } catch (PackageParserException e) { 5775 throw PackageManagerException.from(e); 5776 } 5777 } 5778 5779 /** 5780 * Traces a package scan. 5781 * @see #scanPackageLI(File, int, int, long, UserHandle) 5782 */ 5783 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5784 long currentTime, UserHandle user) throws PackageManagerException { 5785 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5786 try { 5787 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5788 } finally { 5789 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5790 } 5791 } 5792 5793 /** 5794 * Scans a package and returns the newly parsed package. 5795 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5796 */ 5797 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5798 long currentTime, UserHandle user) throws PackageManagerException { 5799 Preconditions.checkNotNull(user); 5800 5801 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5802 parseFlags |= mDefParseFlags; 5803 PackageParser pp = new PackageParser(); 5804 pp.setSeparateProcesses(mSeparateProcesses); 5805 pp.setOnlyCoreApps(mOnlyCore); 5806 pp.setDisplayMetrics(mMetrics); 5807 5808 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5809 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5810 } 5811 5812 final PackageParser.Package pkg; 5813 try { 5814 pkg = pp.parsePackage(scanFile, parseFlags); 5815 } catch (PackageParserException e) { 5816 throw PackageManagerException.from(e); 5817 } 5818 5819 PackageSetting ps = null; 5820 PackageSetting updatedPkg; 5821 // reader 5822 synchronized (mPackages) { 5823 // Look to see if we already know about this package. 5824 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5825 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5826 // This package has been renamed to its original name. Let's 5827 // use that. 5828 ps = mSettings.peekPackageLPr(oldName); 5829 } 5830 // If there was no original package, see one for the real package name. 5831 if (ps == null) { 5832 ps = mSettings.peekPackageLPr(pkg.packageName); 5833 } 5834 // Check to see if this package could be hiding/updating a system 5835 // package. Must look for it either under the original or real 5836 // package name depending on our state. 5837 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5838 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5839 } 5840 boolean updatedPkgBetter = false; 5841 // First check if this is a system package that may involve an update 5842 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 5843 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5844 // it needs to drop FLAG_PRIVILEGED. 5845 if (locationIsPrivileged(scanFile)) { 5846 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5847 } else { 5848 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5849 } 5850 5851 if (ps != null && !ps.codePath.equals(scanFile)) { 5852 // The path has changed from what was last scanned... check the 5853 // version of the new path against what we have stored to determine 5854 // what to do. 5855 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5856 if (pkg.mVersionCode <= ps.versionCode) { 5857 // The system package has been updated and the code path does not match 5858 // Ignore entry. Skip it. 5859 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5860 + " ignored: updated version " + ps.versionCode 5861 + " better than this " + pkg.mVersionCode); 5862 if (!updatedPkg.codePath.equals(scanFile)) { 5863 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5864 + ps.name + " changing from " + updatedPkg.codePathString 5865 + " to " + scanFile); 5866 updatedPkg.codePath = scanFile; 5867 updatedPkg.codePathString = scanFile.toString(); 5868 updatedPkg.resourcePath = scanFile; 5869 updatedPkg.resourcePathString = scanFile.toString(); 5870 } 5871 updatedPkg.pkg = pkg; 5872 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5873 "Package " + ps.name + " at " + scanFile 5874 + " ignored: updated version " + ps.versionCode 5875 + " better than this " + pkg.mVersionCode); 5876 } else { 5877 // The current app on the system partition is better than 5878 // what we have updated to on the data partition; switch 5879 // back to the system partition version. 5880 // At this point, its safely assumed that package installation for 5881 // apps in system partition will go through. If not there won't be a working 5882 // version of the app 5883 // writer 5884 synchronized (mPackages) { 5885 // Just remove the loaded entries from package lists. 5886 mPackages.remove(ps.name); 5887 } 5888 5889 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5890 + " reverting from " + ps.codePathString 5891 + ": new version " + pkg.mVersionCode 5892 + " better than installed " + ps.versionCode); 5893 5894 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5895 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5896 synchronized (mInstallLock) { 5897 args.cleanUpResourcesLI(); 5898 } 5899 synchronized (mPackages) { 5900 mSettings.enableSystemPackageLPw(ps.name); 5901 } 5902 updatedPkgBetter = true; 5903 } 5904 } 5905 } 5906 5907 if (updatedPkg != null) { 5908 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5909 // initially 5910 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5911 5912 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5913 // flag set initially 5914 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5915 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5916 } 5917 } 5918 5919 // Verify certificates against what was last scanned 5920 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5921 5922 /* 5923 * A new system app appeared, but we already had a non-system one of the 5924 * same name installed earlier. 5925 */ 5926 boolean shouldHideSystemApp = false; 5927 if (updatedPkg == null && ps != null 5928 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5929 /* 5930 * Check to make sure the signatures match first. If they don't, 5931 * wipe the installed application and its data. 5932 */ 5933 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5934 != PackageManager.SIGNATURE_MATCH) { 5935 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5936 + " signatures don't match existing userdata copy; removing"); 5937 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5938 ps = null; 5939 } else { 5940 /* 5941 * If the newly-added system app is an older version than the 5942 * already installed version, hide it. It will be scanned later 5943 * and re-added like an update. 5944 */ 5945 if (pkg.mVersionCode <= ps.versionCode) { 5946 shouldHideSystemApp = true; 5947 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5948 + " but new version " + pkg.mVersionCode + " better than installed " 5949 + ps.versionCode + "; hiding system"); 5950 } else { 5951 /* 5952 * The newly found system app is a newer version that the 5953 * one previously installed. Simply remove the 5954 * already-installed application and replace it with our own 5955 * while keeping the application data. 5956 */ 5957 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5958 + " reverting from " + ps.codePathString + ": new version " 5959 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5960 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5961 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5962 synchronized (mInstallLock) { 5963 args.cleanUpResourcesLI(); 5964 } 5965 } 5966 } 5967 } 5968 5969 // The apk is forward locked (not public) if its code and resources 5970 // are kept in different files. (except for app in either system or 5971 // vendor path). 5972 // TODO grab this value from PackageSettings 5973 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5974 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5975 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5976 } 5977 } 5978 5979 // TODO: extend to support forward-locked splits 5980 String resourcePath = null; 5981 String baseResourcePath = null; 5982 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5983 if (ps != null && ps.resourcePathString != null) { 5984 resourcePath = ps.resourcePathString; 5985 baseResourcePath = ps.resourcePathString; 5986 } else { 5987 // Should not happen at all. Just log an error. 5988 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5989 } 5990 } else { 5991 resourcePath = pkg.codePath; 5992 baseResourcePath = pkg.baseCodePath; 5993 } 5994 5995 // Set application objects path explicitly. 5996 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5997 pkg.applicationInfo.setCodePath(pkg.codePath); 5998 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5999 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6000 pkg.applicationInfo.setResourcePath(resourcePath); 6001 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6002 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6003 6004 // Note that we invoke the following method only if we are about to unpack an application 6005 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6006 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6007 6008 /* 6009 * If the system app should be overridden by a previously installed 6010 * data, hide the system app now and let the /data/app scan pick it up 6011 * again. 6012 */ 6013 if (shouldHideSystemApp) { 6014 synchronized (mPackages) { 6015 mSettings.disableSystemPackageLPw(pkg.packageName); 6016 } 6017 } 6018 6019 return scannedPkg; 6020 } 6021 6022 private static String fixProcessName(String defProcessName, 6023 String processName, int uid) { 6024 if (processName == null) { 6025 return defProcessName; 6026 } 6027 return processName; 6028 } 6029 6030 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6031 throws PackageManagerException { 6032 if (pkgSetting.signatures.mSignatures != null) { 6033 // Already existing package. Make sure signatures match 6034 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6035 == PackageManager.SIGNATURE_MATCH; 6036 if (!match) { 6037 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6038 == PackageManager.SIGNATURE_MATCH; 6039 } 6040 if (!match) { 6041 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6042 == PackageManager.SIGNATURE_MATCH; 6043 } 6044 if (!match) { 6045 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6046 + pkg.packageName + " signatures do not match the " 6047 + "previously installed version; ignoring!"); 6048 } 6049 } 6050 6051 // Check for shared user signatures 6052 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6053 // Already existing package. Make sure signatures match 6054 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6055 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6056 if (!match) { 6057 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6058 == PackageManager.SIGNATURE_MATCH; 6059 } 6060 if (!match) { 6061 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6062 == PackageManager.SIGNATURE_MATCH; 6063 } 6064 if (!match) { 6065 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6066 "Package " + pkg.packageName 6067 + " has no signatures that match those in shared user " 6068 + pkgSetting.sharedUser.name + "; ignoring!"); 6069 } 6070 } 6071 } 6072 6073 /** 6074 * Enforces that only the system UID or root's UID can call a method exposed 6075 * via Binder. 6076 * 6077 * @param message used as message if SecurityException is thrown 6078 * @throws SecurityException if the caller is not system or root 6079 */ 6080 private static final void enforceSystemOrRoot(String message) { 6081 final int uid = Binder.getCallingUid(); 6082 if (uid != Process.SYSTEM_UID && uid != 0) { 6083 throw new SecurityException(message); 6084 } 6085 } 6086 6087 @Override 6088 public void performBootDexOpt() { 6089 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6090 6091 // Before everything else, see whether we need to fstrim. 6092 try { 6093 IMountService ms = PackageHelper.getMountService(); 6094 if (ms != null) { 6095 final boolean isUpgrade = isUpgrade(); 6096 boolean doTrim = isUpgrade; 6097 if (doTrim) { 6098 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6099 } else { 6100 final long interval = android.provider.Settings.Global.getLong( 6101 mContext.getContentResolver(), 6102 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6103 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6104 if (interval > 0) { 6105 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6106 if (timeSinceLast > interval) { 6107 doTrim = true; 6108 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6109 + "; running immediately"); 6110 } 6111 } 6112 } 6113 if (doTrim) { 6114 if (!isFirstBoot()) { 6115 try { 6116 ActivityManagerNative.getDefault().showBootMessage( 6117 mContext.getResources().getString( 6118 R.string.android_upgrading_fstrim), true); 6119 } catch (RemoteException e) { 6120 } 6121 } 6122 ms.runMaintenance(); 6123 } 6124 } else { 6125 Slog.e(TAG, "Mount service unavailable!"); 6126 } 6127 } catch (RemoteException e) { 6128 // Can't happen; MountService is local 6129 } 6130 6131 final ArraySet<PackageParser.Package> pkgs; 6132 synchronized (mPackages) { 6133 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6134 } 6135 6136 if (pkgs != null) { 6137 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6138 // in case the device runs out of space. 6139 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6140 // Give priority to core apps. 6141 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6142 PackageParser.Package pkg = it.next(); 6143 if (pkg.coreApp) { 6144 if (DEBUG_DEXOPT) { 6145 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6146 } 6147 sortedPkgs.add(pkg); 6148 it.remove(); 6149 } 6150 } 6151 // Give priority to system apps that listen for pre boot complete. 6152 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6153 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6154 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6155 PackageParser.Package pkg = it.next(); 6156 if (pkgNames.contains(pkg.packageName)) { 6157 if (DEBUG_DEXOPT) { 6158 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6159 } 6160 sortedPkgs.add(pkg); 6161 it.remove(); 6162 } 6163 } 6164 // Filter out packages that aren't recently used. 6165 filterRecentlyUsedApps(pkgs); 6166 // Add all remaining apps. 6167 for (PackageParser.Package pkg : pkgs) { 6168 if (DEBUG_DEXOPT) { 6169 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6170 } 6171 sortedPkgs.add(pkg); 6172 } 6173 6174 // If we want to be lazy, filter everything that wasn't recently used. 6175 if (mLazyDexOpt) { 6176 filterRecentlyUsedApps(sortedPkgs); 6177 } 6178 6179 int i = 0; 6180 int total = sortedPkgs.size(); 6181 File dataDir = Environment.getDataDirectory(); 6182 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6183 if (lowThreshold == 0) { 6184 throw new IllegalStateException("Invalid low memory threshold"); 6185 } 6186 for (PackageParser.Package pkg : sortedPkgs) { 6187 long usableSpace = dataDir.getUsableSpace(); 6188 if (usableSpace < lowThreshold) { 6189 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6190 break; 6191 } 6192 performBootDexOpt(pkg, ++i, total); 6193 } 6194 } 6195 } 6196 6197 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6198 // Filter out packages that aren't recently used. 6199 // 6200 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6201 // should do a full dexopt. 6202 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6203 int total = pkgs.size(); 6204 int skipped = 0; 6205 long now = System.currentTimeMillis(); 6206 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6207 PackageParser.Package pkg = i.next(); 6208 long then = pkg.mLastPackageUsageTimeInMills; 6209 if (then + mDexOptLRUThresholdInMills < now) { 6210 if (DEBUG_DEXOPT) { 6211 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6212 ((then == 0) ? "never" : new Date(then))); 6213 } 6214 i.remove(); 6215 skipped++; 6216 } 6217 } 6218 if (DEBUG_DEXOPT) { 6219 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6220 } 6221 } 6222 } 6223 6224 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6225 List<ResolveInfo> ris = null; 6226 try { 6227 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6228 intent, null, 0, userId); 6229 } catch (RemoteException e) { 6230 } 6231 ArraySet<String> pkgNames = new ArraySet<String>(); 6232 if (ris != null) { 6233 for (ResolveInfo ri : ris) { 6234 pkgNames.add(ri.activityInfo.packageName); 6235 } 6236 } 6237 return pkgNames; 6238 } 6239 6240 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6241 if (DEBUG_DEXOPT) { 6242 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6243 } 6244 if (!isFirstBoot()) { 6245 try { 6246 ActivityManagerNative.getDefault().showBootMessage( 6247 mContext.getResources().getString(R.string.android_upgrading_apk, 6248 curr, total), true); 6249 } catch (RemoteException e) { 6250 } 6251 } 6252 PackageParser.Package p = pkg; 6253 synchronized (mInstallLock) { 6254 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6255 false /* force dex */, false /* defer */, true /* include dependencies */, 6256 false /* boot complete */, false /*useJit*/); 6257 } 6258 } 6259 6260 @Override 6261 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6262 return performDexOptTraced(packageName, instructionSet, false); 6263 } 6264 6265 public boolean performDexOpt( 6266 String packageName, String instructionSet, boolean backgroundDexopt) { 6267 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6268 } 6269 6270 private boolean performDexOptTraced( 6271 String packageName, String instructionSet, boolean backgroundDexopt) { 6272 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6273 try { 6274 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6275 } finally { 6276 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6277 } 6278 } 6279 6280 private boolean performDexOptInternal( 6281 String packageName, String instructionSet, boolean backgroundDexopt) { 6282 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6283 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6284 if (!dexopt && !updateUsage) { 6285 // We aren't going to dexopt or update usage, so bail early. 6286 return false; 6287 } 6288 PackageParser.Package p; 6289 final String targetInstructionSet; 6290 synchronized (mPackages) { 6291 p = mPackages.get(packageName); 6292 if (p == null) { 6293 return false; 6294 } 6295 if (updateUsage) { 6296 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6297 } 6298 mPackageUsage.write(false); 6299 if (!dexopt) { 6300 // We aren't going to dexopt, so bail early. 6301 return false; 6302 } 6303 6304 targetInstructionSet = instructionSet != null ? instructionSet : 6305 getPrimaryInstructionSet(p.applicationInfo); 6306 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6307 return false; 6308 } 6309 } 6310 long callingId = Binder.clearCallingIdentity(); 6311 try { 6312 synchronized (mInstallLock) { 6313 final String[] instructionSets = new String[] { targetInstructionSet }; 6314 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6315 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6316 true /* boot complete */, false /*useJit*/); 6317 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6318 } 6319 } finally { 6320 Binder.restoreCallingIdentity(callingId); 6321 } 6322 } 6323 6324 public ArraySet<String> getPackagesThatNeedDexOpt() { 6325 ArraySet<String> pkgs = null; 6326 synchronized (mPackages) { 6327 for (PackageParser.Package p : mPackages.values()) { 6328 if (DEBUG_DEXOPT) { 6329 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6330 } 6331 if (!p.mDexOptPerformed.isEmpty()) { 6332 continue; 6333 } 6334 if (pkgs == null) { 6335 pkgs = new ArraySet<String>(); 6336 } 6337 pkgs.add(p.packageName); 6338 } 6339 } 6340 return pkgs; 6341 } 6342 6343 public void shutdown() { 6344 mPackageUsage.write(true); 6345 } 6346 6347 @Override 6348 public void forceDexOpt(String packageName) { 6349 enforceSystemOrRoot("forceDexOpt"); 6350 6351 PackageParser.Package pkg; 6352 synchronized (mPackages) { 6353 pkg = mPackages.get(packageName); 6354 if (pkg == null) { 6355 throw new IllegalArgumentException("Missing package: " + packageName); 6356 } 6357 } 6358 6359 synchronized (mInstallLock) { 6360 final String[] instructionSets = new String[] { 6361 getPrimaryInstructionSet(pkg.applicationInfo) }; 6362 6363 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6364 6365 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6366 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6367 true /* boot complete */, false /*useJit*/); 6368 6369 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6370 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6371 throw new IllegalStateException("Failed to dexopt: " + res); 6372 } 6373 } 6374 } 6375 6376 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6377 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6378 Slog.w(TAG, "Unable to update from " + oldPkg.name 6379 + " to " + newPkg.packageName 6380 + ": old package not in system partition"); 6381 return false; 6382 } else if (mPackages.get(oldPkg.name) != null) { 6383 Slog.w(TAG, "Unable to update from " + oldPkg.name 6384 + " to " + newPkg.packageName 6385 + ": old package still exists"); 6386 return false; 6387 } 6388 return true; 6389 } 6390 6391 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6392 int[] users = sUserManager.getUserIds(); 6393 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6394 if (res < 0) { 6395 return res; 6396 } 6397 for (int user : users) { 6398 if (user != 0) { 6399 res = mInstaller.createUserData(volumeUuid, packageName, 6400 UserHandle.getUid(user, uid), user, seinfo); 6401 if (res < 0) { 6402 return res; 6403 } 6404 } 6405 } 6406 return res; 6407 } 6408 6409 private int removeDataDirsLI(String volumeUuid, String packageName) { 6410 int[] users = sUserManager.getUserIds(); 6411 int res = 0; 6412 for (int user : users) { 6413 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6414 if (resInner < 0) { 6415 res = resInner; 6416 } 6417 } 6418 6419 return res; 6420 } 6421 6422 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6423 int[] users = sUserManager.getUserIds(); 6424 int res = 0; 6425 for (int user : users) { 6426 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6427 if (resInner < 0) { 6428 res = resInner; 6429 } 6430 } 6431 return res; 6432 } 6433 6434 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6435 PackageParser.Package changingLib) { 6436 if (file.path != null) { 6437 usesLibraryFiles.add(file.path); 6438 return; 6439 } 6440 PackageParser.Package p = mPackages.get(file.apk); 6441 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6442 // If we are doing this while in the middle of updating a library apk, 6443 // then we need to make sure to use that new apk for determining the 6444 // dependencies here. (We haven't yet finished committing the new apk 6445 // to the package manager state.) 6446 if (p == null || p.packageName.equals(changingLib.packageName)) { 6447 p = changingLib; 6448 } 6449 } 6450 if (p != null) { 6451 usesLibraryFiles.addAll(p.getAllCodePaths()); 6452 } 6453 } 6454 6455 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6456 PackageParser.Package changingLib) throws PackageManagerException { 6457 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6458 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6459 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6460 for (int i=0; i<N; i++) { 6461 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6462 if (file == null) { 6463 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6464 "Package " + pkg.packageName + " requires unavailable shared library " 6465 + pkg.usesLibraries.get(i) + "; failing!"); 6466 } 6467 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6468 } 6469 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6470 for (int i=0; i<N; i++) { 6471 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6472 if (file == null) { 6473 Slog.w(TAG, "Package " + pkg.packageName 6474 + " desires unavailable shared library " 6475 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6476 } else { 6477 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6478 } 6479 } 6480 N = usesLibraryFiles.size(); 6481 if (N > 0) { 6482 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6483 } else { 6484 pkg.usesLibraryFiles = null; 6485 } 6486 } 6487 } 6488 6489 private static boolean hasString(List<String> list, List<String> which) { 6490 if (list == null) { 6491 return false; 6492 } 6493 for (int i=list.size()-1; i>=0; i--) { 6494 for (int j=which.size()-1; j>=0; j--) { 6495 if (which.get(j).equals(list.get(i))) { 6496 return true; 6497 } 6498 } 6499 } 6500 return false; 6501 } 6502 6503 private void updateAllSharedLibrariesLPw() { 6504 for (PackageParser.Package pkg : mPackages.values()) { 6505 try { 6506 updateSharedLibrariesLPw(pkg, null); 6507 } catch (PackageManagerException e) { 6508 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6509 } 6510 } 6511 } 6512 6513 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6514 PackageParser.Package changingPkg) { 6515 ArrayList<PackageParser.Package> res = null; 6516 for (PackageParser.Package pkg : mPackages.values()) { 6517 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6518 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6519 if (res == null) { 6520 res = new ArrayList<PackageParser.Package>(); 6521 } 6522 res.add(pkg); 6523 try { 6524 updateSharedLibrariesLPw(pkg, changingPkg); 6525 } catch (PackageManagerException e) { 6526 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6527 } 6528 } 6529 } 6530 return res; 6531 } 6532 6533 /** 6534 * Derive the value of the {@code cpuAbiOverride} based on the provided 6535 * value and an optional stored value from the package settings. 6536 */ 6537 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6538 String cpuAbiOverride = null; 6539 6540 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6541 cpuAbiOverride = null; 6542 } else if (abiOverride != null) { 6543 cpuAbiOverride = abiOverride; 6544 } else if (settings != null) { 6545 cpuAbiOverride = settings.cpuAbiOverrideString; 6546 } 6547 6548 return cpuAbiOverride; 6549 } 6550 6551 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6552 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6553 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6554 try { 6555 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6556 } finally { 6557 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6558 } 6559 } 6560 6561 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6562 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6563 boolean success = false; 6564 try { 6565 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6566 currentTime, user); 6567 success = true; 6568 return res; 6569 } finally { 6570 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6571 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6572 } 6573 } 6574 } 6575 6576 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6577 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6578 final File scanFile = new File(pkg.codePath); 6579 if (pkg.applicationInfo.getCodePath() == null || 6580 pkg.applicationInfo.getResourcePath() == null) { 6581 // Bail out. The resource and code paths haven't been set. 6582 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6583 "Code and resource paths haven't been set correctly"); 6584 } 6585 6586 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6587 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6588 } else { 6589 // Only allow system apps to be flagged as core apps. 6590 pkg.coreApp = false; 6591 } 6592 6593 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6594 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6595 } 6596 6597 if (mCustomResolverComponentName != null && 6598 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6599 setUpCustomResolverActivity(pkg); 6600 } 6601 6602 if (pkg.packageName.equals("android")) { 6603 synchronized (mPackages) { 6604 if (mAndroidApplication != null) { 6605 Slog.w(TAG, "*************************************************"); 6606 Slog.w(TAG, "Core android package being redefined. Skipping."); 6607 Slog.w(TAG, " file=" + scanFile); 6608 Slog.w(TAG, "*************************************************"); 6609 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6610 "Core android package being redefined. Skipping."); 6611 } 6612 6613 // Set up information for our fall-back user intent resolution activity. 6614 mPlatformPackage = pkg; 6615 pkg.mVersionCode = mSdkVersion; 6616 mAndroidApplication = pkg.applicationInfo; 6617 6618 if (!mResolverReplaced) { 6619 mResolveActivity.applicationInfo = mAndroidApplication; 6620 mResolveActivity.name = ResolverActivity.class.getName(); 6621 mResolveActivity.packageName = mAndroidApplication.packageName; 6622 mResolveActivity.processName = "system:ui"; 6623 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6624 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6625 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6626 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6627 mResolveActivity.exported = true; 6628 mResolveActivity.enabled = true; 6629 mResolveInfo.activityInfo = mResolveActivity; 6630 mResolveInfo.priority = 0; 6631 mResolveInfo.preferredOrder = 0; 6632 mResolveInfo.match = 0; 6633 mResolveComponentName = new ComponentName( 6634 mAndroidApplication.packageName, mResolveActivity.name); 6635 } 6636 } 6637 } 6638 6639 if (DEBUG_PACKAGE_SCANNING) { 6640 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6641 Log.d(TAG, "Scanning package " + pkg.packageName); 6642 } 6643 6644 if (mPackages.containsKey(pkg.packageName) 6645 || mSharedLibraries.containsKey(pkg.packageName)) { 6646 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6647 "Application package " + pkg.packageName 6648 + " already installed. Skipping duplicate."); 6649 } 6650 6651 // If we're only installing presumed-existing packages, require that the 6652 // scanned APK is both already known and at the path previously established 6653 // for it. Previously unknown packages we pick up normally, but if we have an 6654 // a priori expectation about this package's install presence, enforce it. 6655 // With a singular exception for new system packages. When an OTA contains 6656 // a new system package, we allow the codepath to change from a system location 6657 // to the user-installed location. If we don't allow this change, any newer, 6658 // user-installed version of the application will be ignored. 6659 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6660 if (mExpectingBetter.containsKey(pkg.packageName)) { 6661 logCriticalInfo(Log.WARN, 6662 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6663 } else { 6664 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6665 if (known != null) { 6666 if (DEBUG_PACKAGE_SCANNING) { 6667 Log.d(TAG, "Examining " + pkg.codePath 6668 + " and requiring known paths " + known.codePathString 6669 + " & " + known.resourcePathString); 6670 } 6671 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6672 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6673 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6674 "Application package " + pkg.packageName 6675 + " found at " + pkg.applicationInfo.getCodePath() 6676 + " but expected at " + known.codePathString + "; ignoring."); 6677 } 6678 } 6679 } 6680 } 6681 6682 // Initialize package source and resource directories 6683 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6684 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6685 6686 SharedUserSetting suid = null; 6687 PackageSetting pkgSetting = null; 6688 6689 if (!isSystemApp(pkg)) { 6690 // Only system apps can use these features. 6691 pkg.mOriginalPackages = null; 6692 pkg.mRealPackage = null; 6693 pkg.mAdoptPermissions = null; 6694 } 6695 6696 // writer 6697 synchronized (mPackages) { 6698 if (pkg.mSharedUserId != null) { 6699 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6700 if (suid == null) { 6701 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6702 "Creating application package " + pkg.packageName 6703 + " for shared user failed"); 6704 } 6705 if (DEBUG_PACKAGE_SCANNING) { 6706 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6707 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6708 + "): packages=" + suid.packages); 6709 } 6710 } 6711 6712 // Check if we are renaming from an original package name. 6713 PackageSetting origPackage = null; 6714 String realName = null; 6715 if (pkg.mOriginalPackages != null) { 6716 // This package may need to be renamed to a previously 6717 // installed name. Let's check on that... 6718 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6719 if (pkg.mOriginalPackages.contains(renamed)) { 6720 // This package had originally been installed as the 6721 // original name, and we have already taken care of 6722 // transitioning to the new one. Just update the new 6723 // one to continue using the old name. 6724 realName = pkg.mRealPackage; 6725 if (!pkg.packageName.equals(renamed)) { 6726 // Callers into this function may have already taken 6727 // care of renaming the package; only do it here if 6728 // it is not already done. 6729 pkg.setPackageName(renamed); 6730 } 6731 6732 } else { 6733 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6734 if ((origPackage = mSettings.peekPackageLPr( 6735 pkg.mOriginalPackages.get(i))) != null) { 6736 // We do have the package already installed under its 6737 // original name... should we use it? 6738 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6739 // New package is not compatible with original. 6740 origPackage = null; 6741 continue; 6742 } else if (origPackage.sharedUser != null) { 6743 // Make sure uid is compatible between packages. 6744 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6745 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6746 + " to " + pkg.packageName + ": old uid " 6747 + origPackage.sharedUser.name 6748 + " differs from " + pkg.mSharedUserId); 6749 origPackage = null; 6750 continue; 6751 } 6752 } else { 6753 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6754 + pkg.packageName + " to old name " + origPackage.name); 6755 } 6756 break; 6757 } 6758 } 6759 } 6760 } 6761 6762 if (mTransferedPackages.contains(pkg.packageName)) { 6763 Slog.w(TAG, "Package " + pkg.packageName 6764 + " was transferred to another, but its .apk remains"); 6765 } 6766 6767 // Just create the setting, don't add it yet. For already existing packages 6768 // the PkgSetting exists already and doesn't have to be created. 6769 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6770 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6771 pkg.applicationInfo.primaryCpuAbi, 6772 pkg.applicationInfo.secondaryCpuAbi, 6773 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6774 user, false); 6775 if (pkgSetting == null) { 6776 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6777 "Creating application package " + pkg.packageName + " failed"); 6778 } 6779 6780 if (pkgSetting.origPackage != null) { 6781 // If we are first transitioning from an original package, 6782 // fix up the new package's name now. We need to do this after 6783 // looking up the package under its new name, so getPackageLP 6784 // can take care of fiddling things correctly. 6785 pkg.setPackageName(origPackage.name); 6786 6787 // File a report about this. 6788 String msg = "New package " + pkgSetting.realName 6789 + " renamed to replace old package " + pkgSetting.name; 6790 reportSettingsProblem(Log.WARN, msg); 6791 6792 // Make a note of it. 6793 mTransferedPackages.add(origPackage.name); 6794 6795 // No longer need to retain this. 6796 pkgSetting.origPackage = null; 6797 } 6798 6799 if (realName != null) { 6800 // Make a note of it. 6801 mTransferedPackages.add(pkg.packageName); 6802 } 6803 6804 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6805 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6806 } 6807 6808 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6809 // Check all shared libraries and map to their actual file path. 6810 // We only do this here for apps not on a system dir, because those 6811 // are the only ones that can fail an install due to this. We 6812 // will take care of the system apps by updating all of their 6813 // library paths after the scan is done. 6814 updateSharedLibrariesLPw(pkg, null); 6815 } 6816 6817 if (mFoundPolicyFile) { 6818 SELinuxMMAC.assignSeinfoValue(pkg); 6819 } 6820 6821 pkg.applicationInfo.uid = pkgSetting.appId; 6822 pkg.mExtras = pkgSetting; 6823 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6824 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6825 // We just determined the app is signed correctly, so bring 6826 // over the latest parsed certs. 6827 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6828 } else { 6829 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6830 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6831 "Package " + pkg.packageName + " upgrade keys do not match the " 6832 + "previously installed version"); 6833 } else { 6834 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6835 String msg = "System package " + pkg.packageName 6836 + " signature changed; retaining data."; 6837 reportSettingsProblem(Log.WARN, msg); 6838 } 6839 } 6840 } else { 6841 try { 6842 verifySignaturesLP(pkgSetting, pkg); 6843 // We just determined the app is signed correctly, so bring 6844 // over the latest parsed certs. 6845 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6846 } catch (PackageManagerException e) { 6847 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6848 throw e; 6849 } 6850 // The signature has changed, but this package is in the system 6851 // image... let's recover! 6852 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6853 // However... if this package is part of a shared user, but it 6854 // doesn't match the signature of the shared user, let's fail. 6855 // What this means is that you can't change the signatures 6856 // associated with an overall shared user, which doesn't seem all 6857 // that unreasonable. 6858 if (pkgSetting.sharedUser != null) { 6859 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6860 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6861 throw new PackageManagerException( 6862 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6863 "Signature mismatch for shared user : " 6864 + pkgSetting.sharedUser); 6865 } 6866 } 6867 // File a report about this. 6868 String msg = "System package " + pkg.packageName 6869 + " signature changed; retaining data."; 6870 reportSettingsProblem(Log.WARN, msg); 6871 } 6872 } 6873 // Verify that this new package doesn't have any content providers 6874 // that conflict with existing packages. Only do this if the 6875 // package isn't already installed, since we don't want to break 6876 // things that are installed. 6877 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6878 final int N = pkg.providers.size(); 6879 int i; 6880 for (i=0; i<N; i++) { 6881 PackageParser.Provider p = pkg.providers.get(i); 6882 if (p.info.authority != null) { 6883 String names[] = p.info.authority.split(";"); 6884 for (int j = 0; j < names.length; j++) { 6885 if (mProvidersByAuthority.containsKey(names[j])) { 6886 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6887 final String otherPackageName = 6888 ((other != null && other.getComponentName() != null) ? 6889 other.getComponentName().getPackageName() : "?"); 6890 throw new PackageManagerException( 6891 INSTALL_FAILED_CONFLICTING_PROVIDER, 6892 "Can't install because provider name " + names[j] 6893 + " (in package " + pkg.applicationInfo.packageName 6894 + ") is already used by " + otherPackageName); 6895 } 6896 } 6897 } 6898 } 6899 } 6900 6901 if (pkg.mAdoptPermissions != null) { 6902 // This package wants to adopt ownership of permissions from 6903 // another package. 6904 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6905 final String origName = pkg.mAdoptPermissions.get(i); 6906 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6907 if (orig != null) { 6908 if (verifyPackageUpdateLPr(orig, pkg)) { 6909 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6910 + pkg.packageName); 6911 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6912 } 6913 } 6914 } 6915 } 6916 } 6917 6918 final String pkgName = pkg.packageName; 6919 6920 final long scanFileTime = scanFile.lastModified(); 6921 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6922 pkg.applicationInfo.processName = fixProcessName( 6923 pkg.applicationInfo.packageName, 6924 pkg.applicationInfo.processName, 6925 pkg.applicationInfo.uid); 6926 6927 File dataPath; 6928 if (mPlatformPackage == pkg) { 6929 // The system package is special. 6930 dataPath = new File(Environment.getDataDirectory(), "system"); 6931 6932 pkg.applicationInfo.dataDir = dataPath.getPath(); 6933 6934 } else { 6935 // This is a normal package, need to make its data directory. 6936 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6937 UserHandle.USER_SYSTEM, pkg.packageName); 6938 6939 boolean uidError = false; 6940 if (dataPath.exists()) { 6941 int currentUid = 0; 6942 try { 6943 StructStat stat = Os.stat(dataPath.getPath()); 6944 currentUid = stat.st_uid; 6945 } catch (ErrnoException e) { 6946 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6947 } 6948 6949 // If we have mismatched owners for the data path, we have a problem. 6950 if (currentUid != pkg.applicationInfo.uid) { 6951 boolean recovered = false; 6952 if (currentUid == 0) { 6953 // The directory somehow became owned by root. Wow. 6954 // This is probably because the system was stopped while 6955 // installd was in the middle of messing with its libs 6956 // directory. Ask installd to fix that. 6957 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6958 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6959 if (ret >= 0) { 6960 recovered = true; 6961 String msg = "Package " + pkg.packageName 6962 + " unexpectedly changed to uid 0; recovered to " + 6963 + pkg.applicationInfo.uid; 6964 reportSettingsProblem(Log.WARN, msg); 6965 } 6966 } 6967 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6968 || (scanFlags&SCAN_BOOTING) != 0)) { 6969 // If this is a system app, we can at least delete its 6970 // current data so the application will still work. 6971 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6972 if (ret >= 0) { 6973 // TODO: Kill the processes first 6974 // Old data gone! 6975 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6976 ? "System package " : "Third party package "; 6977 String msg = prefix + pkg.packageName 6978 + " has changed from uid: " 6979 + currentUid + " to " 6980 + pkg.applicationInfo.uid + "; old data erased"; 6981 reportSettingsProblem(Log.WARN, msg); 6982 recovered = true; 6983 6984 // And now re-install the app. 6985 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6986 pkg.applicationInfo.seinfo); 6987 if (ret == -1) { 6988 // Ack should not happen! 6989 msg = prefix + pkg.packageName 6990 + " could not have data directory re-created after delete."; 6991 reportSettingsProblem(Log.WARN, msg); 6992 throw new PackageManagerException( 6993 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6994 } 6995 } 6996 if (!recovered) { 6997 mHasSystemUidErrors = true; 6998 } 6999 } else if (!recovered) { 7000 // If we allow this install to proceed, we will be broken. 7001 // Abort, abort! 7002 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7003 "scanPackageLI"); 7004 } 7005 if (!recovered) { 7006 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7007 + pkg.applicationInfo.uid + "/fs_" 7008 + currentUid; 7009 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7010 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7011 String msg = "Package " + pkg.packageName 7012 + " has mismatched uid: " 7013 + currentUid + " on disk, " 7014 + pkg.applicationInfo.uid + " in settings"; 7015 // writer 7016 synchronized (mPackages) { 7017 mSettings.mReadMessages.append(msg); 7018 mSettings.mReadMessages.append('\n'); 7019 uidError = true; 7020 if (!pkgSetting.uidError) { 7021 reportSettingsProblem(Log.ERROR, msg); 7022 } 7023 } 7024 } 7025 } 7026 pkg.applicationInfo.dataDir = dataPath.getPath(); 7027 if (mShouldRestoreconData) { 7028 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7029 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7030 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7031 } 7032 } else { 7033 if (DEBUG_PACKAGE_SCANNING) { 7034 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7035 Log.v(TAG, "Want this data dir: " + dataPath); 7036 } 7037 //invoke installer to do the actual installation 7038 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7039 pkg.applicationInfo.seinfo); 7040 if (ret < 0) { 7041 // Error from installer 7042 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7043 "Unable to create data dirs [errorCode=" + ret + "]"); 7044 } 7045 7046 if (dataPath.exists()) { 7047 pkg.applicationInfo.dataDir = dataPath.getPath(); 7048 } else { 7049 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7050 pkg.applicationInfo.dataDir = null; 7051 } 7052 } 7053 7054 pkgSetting.uidError = uidError; 7055 } 7056 7057 final String path = scanFile.getPath(); 7058 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7059 7060 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7061 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7062 7063 // Some system apps still use directory structure for native libraries 7064 // in which case we might end up not detecting abi solely based on apk 7065 // structure. Try to detect abi based on directory structure. 7066 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7067 pkg.applicationInfo.primaryCpuAbi == null) { 7068 setBundledAppAbisAndRoots(pkg, pkgSetting); 7069 setNativeLibraryPaths(pkg); 7070 } 7071 7072 } else { 7073 if ((scanFlags & SCAN_MOVE) != 0) { 7074 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7075 // but we already have this packages package info in the PackageSetting. We just 7076 // use that and derive the native library path based on the new codepath. 7077 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7078 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7079 } 7080 7081 // Set native library paths again. For moves, the path will be updated based on the 7082 // ABIs we've determined above. For non-moves, the path will be updated based on the 7083 // ABIs we determined during compilation, but the path will depend on the final 7084 // package path (after the rename away from the stage path). 7085 setNativeLibraryPaths(pkg); 7086 } 7087 7088 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7089 final int[] userIds = sUserManager.getUserIds(); 7090 synchronized (mInstallLock) { 7091 // Make sure all user data directories are ready to roll; we're okay 7092 // if they already exist 7093 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7094 for (int userId : userIds) { 7095 if (userId != UserHandle.USER_SYSTEM) { 7096 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7097 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7098 pkg.applicationInfo.seinfo); 7099 } 7100 } 7101 } 7102 7103 // Create a native library symlink only if we have native libraries 7104 // and if the native libraries are 32 bit libraries. We do not provide 7105 // this symlink for 64 bit libraries. 7106 if (pkg.applicationInfo.primaryCpuAbi != null && 7107 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7108 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7109 try { 7110 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7111 for (int userId : userIds) { 7112 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7113 nativeLibPath, userId) < 0) { 7114 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7115 "Failed linking native library dir (user=" + userId + ")"); 7116 } 7117 } 7118 } finally { 7119 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7120 } 7121 } 7122 } 7123 7124 // This is a special case for the "system" package, where the ABI is 7125 // dictated by the zygote configuration (and init.rc). We should keep track 7126 // of this ABI so that we can deal with "normal" applications that run under 7127 // the same UID correctly. 7128 if (mPlatformPackage == pkg) { 7129 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7130 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7131 } 7132 7133 // If there's a mismatch between the abi-override in the package setting 7134 // and the abiOverride specified for the install. Warn about this because we 7135 // would've already compiled the app without taking the package setting into 7136 // account. 7137 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7138 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7139 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7140 " for package: " + pkg.packageName); 7141 } 7142 } 7143 7144 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7145 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7146 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7147 7148 // Copy the derived override back to the parsed package, so that we can 7149 // update the package settings accordingly. 7150 pkg.cpuAbiOverride = cpuAbiOverride; 7151 7152 if (DEBUG_ABI_SELECTION) { 7153 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7154 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7155 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7156 } 7157 7158 // Push the derived path down into PackageSettings so we know what to 7159 // clean up at uninstall time. 7160 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7161 7162 if (DEBUG_ABI_SELECTION) { 7163 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7164 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7165 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7166 } 7167 7168 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7169 // We don't do this here during boot because we can do it all 7170 // at once after scanning all existing packages. 7171 // 7172 // We also do this *before* we perform dexopt on this package, so that 7173 // we can avoid redundant dexopts, and also to make sure we've got the 7174 // code and package path correct. 7175 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7176 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7177 } 7178 7179 if ((scanFlags & SCAN_NO_DEX) == 0) { 7180 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7181 7182 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7183 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7184 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7185 7186 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7187 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7188 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7189 } 7190 } 7191 if (mFactoryTest && pkg.requestedPermissions.contains( 7192 android.Manifest.permission.FACTORY_TEST)) { 7193 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7194 } 7195 7196 ArrayList<PackageParser.Package> clientLibPkgs = null; 7197 7198 // writer 7199 synchronized (mPackages) { 7200 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7201 // Only system apps can add new shared libraries. 7202 if (pkg.libraryNames != null) { 7203 for (int i=0; i<pkg.libraryNames.size(); i++) { 7204 String name = pkg.libraryNames.get(i); 7205 boolean allowed = false; 7206 if (pkg.isUpdatedSystemApp()) { 7207 // New library entries can only be added through the 7208 // system image. This is important to get rid of a lot 7209 // of nasty edge cases: for example if we allowed a non- 7210 // system update of the app to add a library, then uninstalling 7211 // the update would make the library go away, and assumptions 7212 // we made such as through app install filtering would now 7213 // have allowed apps on the device which aren't compatible 7214 // with it. Better to just have the restriction here, be 7215 // conservative, and create many fewer cases that can negatively 7216 // impact the user experience. 7217 final PackageSetting sysPs = mSettings 7218 .getDisabledSystemPkgLPr(pkg.packageName); 7219 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7220 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7221 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7222 allowed = true; 7223 break; 7224 } 7225 } 7226 } 7227 } else { 7228 allowed = true; 7229 } 7230 if (allowed) { 7231 if (!mSharedLibraries.containsKey(name)) { 7232 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7233 } else if (!name.equals(pkg.packageName)) { 7234 Slog.w(TAG, "Package " + pkg.packageName + " library " 7235 + name + " already exists; skipping"); 7236 } 7237 } else { 7238 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7239 + name + " that is not declared on system image; skipping"); 7240 } 7241 } 7242 if ((scanFlags&SCAN_BOOTING) == 0) { 7243 // If we are not booting, we need to update any applications 7244 // that are clients of our shared library. If we are booting, 7245 // this will all be done once the scan is complete. 7246 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7247 } 7248 } 7249 } 7250 } 7251 7252 // We also need to dexopt any apps that are dependent on this library. Note that 7253 // if these fail, we should abort the install since installing the library will 7254 // result in some apps being broken. 7255 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7256 try { 7257 if (clientLibPkgs != null) { 7258 if ((scanFlags & SCAN_NO_DEX) == 0) { 7259 for (int i = 0; i < clientLibPkgs.size(); i++) { 7260 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7261 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7262 null /* instruction sets */, forceDex, 7263 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7264 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7265 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7266 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7267 "scanPackageLI failed to dexopt clientLibPkgs"); 7268 } 7269 } 7270 } 7271 } 7272 } finally { 7273 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7274 } 7275 7276 // Request the ActivityManager to kill the process(only for existing packages) 7277 // so that we do not end up in a confused state while the user is still using the older 7278 // version of the application while the new one gets installed. 7279 if ((scanFlags & SCAN_REPLACING) != 0) { 7280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7281 7282 killApplication(pkg.applicationInfo.packageName, 7283 pkg.applicationInfo.uid, "replace pkg"); 7284 7285 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7286 } 7287 7288 // Also need to kill any apps that are dependent on the library. 7289 if (clientLibPkgs != null) { 7290 for (int i=0; i<clientLibPkgs.size(); i++) { 7291 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7292 killApplication(clientPkg.applicationInfo.packageName, 7293 clientPkg.applicationInfo.uid, "update lib"); 7294 } 7295 } 7296 7297 // Make sure we're not adding any bogus keyset info 7298 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7299 ksms.assertScannedPackageValid(pkg); 7300 7301 // writer 7302 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7303 7304 boolean createIdmapFailed = false; 7305 synchronized (mPackages) { 7306 // We don't expect installation to fail beyond this point 7307 7308 // Add the new setting to mSettings 7309 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7310 // Add the new setting to mPackages 7311 mPackages.put(pkg.applicationInfo.packageName, pkg); 7312 // Make sure we don't accidentally delete its data. 7313 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7314 while (iter.hasNext()) { 7315 PackageCleanItem item = iter.next(); 7316 if (pkgName.equals(item.packageName)) { 7317 iter.remove(); 7318 } 7319 } 7320 7321 // Take care of first install / last update times. 7322 if (currentTime != 0) { 7323 if (pkgSetting.firstInstallTime == 0) { 7324 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7325 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7326 pkgSetting.lastUpdateTime = currentTime; 7327 } 7328 } else if (pkgSetting.firstInstallTime == 0) { 7329 // We need *something*. Take time time stamp of the file. 7330 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7331 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7332 if (scanFileTime != pkgSetting.timeStamp) { 7333 // A package on the system image has changed; consider this 7334 // to be an update. 7335 pkgSetting.lastUpdateTime = scanFileTime; 7336 } 7337 } 7338 7339 // Add the package's KeySets to the global KeySetManagerService 7340 ksms.addScannedPackageLPw(pkg); 7341 7342 int N = pkg.providers.size(); 7343 StringBuilder r = null; 7344 int i; 7345 for (i=0; i<N; i++) { 7346 PackageParser.Provider p = pkg.providers.get(i); 7347 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7348 p.info.processName, pkg.applicationInfo.uid); 7349 mProviders.addProvider(p); 7350 p.syncable = p.info.isSyncable; 7351 if (p.info.authority != null) { 7352 String names[] = p.info.authority.split(";"); 7353 p.info.authority = null; 7354 for (int j = 0; j < names.length; j++) { 7355 if (j == 1 && p.syncable) { 7356 // We only want the first authority for a provider to possibly be 7357 // syncable, so if we already added this provider using a different 7358 // authority clear the syncable flag. We copy the provider before 7359 // changing it because the mProviders object contains a reference 7360 // to a provider that we don't want to change. 7361 // Only do this for the second authority since the resulting provider 7362 // object can be the same for all future authorities for this provider. 7363 p = new PackageParser.Provider(p); 7364 p.syncable = false; 7365 } 7366 if (!mProvidersByAuthority.containsKey(names[j])) { 7367 mProvidersByAuthority.put(names[j], p); 7368 if (p.info.authority == null) { 7369 p.info.authority = names[j]; 7370 } else { 7371 p.info.authority = p.info.authority + ";" + names[j]; 7372 } 7373 if (DEBUG_PACKAGE_SCANNING) { 7374 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7375 Log.d(TAG, "Registered content provider: " + names[j] 7376 + ", className = " + p.info.name + ", isSyncable = " 7377 + p.info.isSyncable); 7378 } 7379 } else { 7380 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7381 Slog.w(TAG, "Skipping provider name " + names[j] + 7382 " (in package " + pkg.applicationInfo.packageName + 7383 "): name already used by " 7384 + ((other != null && other.getComponentName() != null) 7385 ? other.getComponentName().getPackageName() : "?")); 7386 } 7387 } 7388 } 7389 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7390 if (r == null) { 7391 r = new StringBuilder(256); 7392 } else { 7393 r.append(' '); 7394 } 7395 r.append(p.info.name); 7396 } 7397 } 7398 if (r != null) { 7399 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7400 } 7401 7402 N = pkg.services.size(); 7403 r = null; 7404 for (i=0; i<N; i++) { 7405 PackageParser.Service s = pkg.services.get(i); 7406 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7407 s.info.processName, pkg.applicationInfo.uid); 7408 mServices.addService(s); 7409 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7410 if (r == null) { 7411 r = new StringBuilder(256); 7412 } else { 7413 r.append(' '); 7414 } 7415 r.append(s.info.name); 7416 } 7417 } 7418 if (r != null) { 7419 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7420 } 7421 7422 N = pkg.receivers.size(); 7423 r = null; 7424 for (i=0; i<N; i++) { 7425 PackageParser.Activity a = pkg.receivers.get(i); 7426 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7427 a.info.processName, pkg.applicationInfo.uid); 7428 mReceivers.addActivity(a, "receiver"); 7429 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7430 if (r == null) { 7431 r = new StringBuilder(256); 7432 } else { 7433 r.append(' '); 7434 } 7435 r.append(a.info.name); 7436 } 7437 } 7438 if (r != null) { 7439 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7440 } 7441 7442 N = pkg.activities.size(); 7443 r = null; 7444 for (i=0; i<N; i++) { 7445 PackageParser.Activity a = pkg.activities.get(i); 7446 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7447 a.info.processName, pkg.applicationInfo.uid); 7448 mActivities.addActivity(a, "activity"); 7449 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7450 if (r == null) { 7451 r = new StringBuilder(256); 7452 } else { 7453 r.append(' '); 7454 } 7455 r.append(a.info.name); 7456 } 7457 } 7458 if (r != null) { 7459 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7460 } 7461 7462 N = pkg.permissionGroups.size(); 7463 r = null; 7464 for (i=0; i<N; i++) { 7465 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7466 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7467 if (cur == null) { 7468 mPermissionGroups.put(pg.info.name, pg); 7469 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7470 if (r == null) { 7471 r = new StringBuilder(256); 7472 } else { 7473 r.append(' '); 7474 } 7475 r.append(pg.info.name); 7476 } 7477 } else { 7478 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7479 + pg.info.packageName + " ignored: original from " 7480 + cur.info.packageName); 7481 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7482 if (r == null) { 7483 r = new StringBuilder(256); 7484 } else { 7485 r.append(' '); 7486 } 7487 r.append("DUP:"); 7488 r.append(pg.info.name); 7489 } 7490 } 7491 } 7492 if (r != null) { 7493 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7494 } 7495 7496 N = pkg.permissions.size(); 7497 r = null; 7498 for (i=0; i<N; i++) { 7499 PackageParser.Permission p = pkg.permissions.get(i); 7500 7501 // Assume by default that we did not install this permission into the system. 7502 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7503 7504 // Now that permission groups have a special meaning, we ignore permission 7505 // groups for legacy apps to prevent unexpected behavior. In particular, 7506 // permissions for one app being granted to someone just becuase they happen 7507 // to be in a group defined by another app (before this had no implications). 7508 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7509 p.group = mPermissionGroups.get(p.info.group); 7510 // Warn for a permission in an unknown group. 7511 if (p.info.group != null && p.group == null) { 7512 Slog.w(TAG, "Permission " + p.info.name + " from package " 7513 + p.info.packageName + " in an unknown group " + p.info.group); 7514 } 7515 } 7516 7517 ArrayMap<String, BasePermission> permissionMap = 7518 p.tree ? mSettings.mPermissionTrees 7519 : mSettings.mPermissions; 7520 BasePermission bp = permissionMap.get(p.info.name); 7521 7522 // Allow system apps to redefine non-system permissions 7523 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7524 final boolean currentOwnerIsSystem = (bp.perm != null 7525 && isSystemApp(bp.perm.owner)); 7526 if (isSystemApp(p.owner)) { 7527 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7528 // It's a built-in permission and no owner, take ownership now 7529 bp.packageSetting = pkgSetting; 7530 bp.perm = p; 7531 bp.uid = pkg.applicationInfo.uid; 7532 bp.sourcePackage = p.info.packageName; 7533 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7534 } else if (!currentOwnerIsSystem) { 7535 String msg = "New decl " + p.owner + " of permission " 7536 + p.info.name + " is system; overriding " + bp.sourcePackage; 7537 reportSettingsProblem(Log.WARN, msg); 7538 bp = null; 7539 } 7540 } 7541 } 7542 7543 if (bp == null) { 7544 bp = new BasePermission(p.info.name, p.info.packageName, 7545 BasePermission.TYPE_NORMAL); 7546 permissionMap.put(p.info.name, bp); 7547 } 7548 7549 if (bp.perm == null) { 7550 if (bp.sourcePackage == null 7551 || bp.sourcePackage.equals(p.info.packageName)) { 7552 BasePermission tree = findPermissionTreeLP(p.info.name); 7553 if (tree == null 7554 || tree.sourcePackage.equals(p.info.packageName)) { 7555 bp.packageSetting = pkgSetting; 7556 bp.perm = p; 7557 bp.uid = pkg.applicationInfo.uid; 7558 bp.sourcePackage = p.info.packageName; 7559 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7560 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7561 if (r == null) { 7562 r = new StringBuilder(256); 7563 } else { 7564 r.append(' '); 7565 } 7566 r.append(p.info.name); 7567 } 7568 } else { 7569 Slog.w(TAG, "Permission " + p.info.name + " from package " 7570 + p.info.packageName + " ignored: base tree " 7571 + tree.name + " is from package " 7572 + tree.sourcePackage); 7573 } 7574 } else { 7575 Slog.w(TAG, "Permission " + p.info.name + " from package " 7576 + p.info.packageName + " ignored: original from " 7577 + bp.sourcePackage); 7578 } 7579 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7580 if (r == null) { 7581 r = new StringBuilder(256); 7582 } else { 7583 r.append(' '); 7584 } 7585 r.append("DUP:"); 7586 r.append(p.info.name); 7587 } 7588 if (bp.perm == p) { 7589 bp.protectionLevel = p.info.protectionLevel; 7590 } 7591 } 7592 7593 if (r != null) { 7594 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7595 } 7596 7597 N = pkg.instrumentation.size(); 7598 r = null; 7599 for (i=0; i<N; i++) { 7600 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7601 a.info.packageName = pkg.applicationInfo.packageName; 7602 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7603 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7604 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7605 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7606 a.info.dataDir = pkg.applicationInfo.dataDir; 7607 7608 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7609 // need other information about the application, like the ABI and what not ? 7610 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7611 mInstrumentation.put(a.getComponentName(), a); 7612 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7613 if (r == null) { 7614 r = new StringBuilder(256); 7615 } else { 7616 r.append(' '); 7617 } 7618 r.append(a.info.name); 7619 } 7620 } 7621 if (r != null) { 7622 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7623 } 7624 7625 if (pkg.protectedBroadcasts != null) { 7626 N = pkg.protectedBroadcasts.size(); 7627 for (i=0; i<N; i++) { 7628 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7629 } 7630 } 7631 7632 pkgSetting.setTimeStamp(scanFileTime); 7633 7634 // Create idmap files for pairs of (packages, overlay packages). 7635 // Note: "android", ie framework-res.apk, is handled by native layers. 7636 if (pkg.mOverlayTarget != null) { 7637 // This is an overlay package. 7638 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7639 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7640 mOverlays.put(pkg.mOverlayTarget, 7641 new ArrayMap<String, PackageParser.Package>()); 7642 } 7643 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7644 map.put(pkg.packageName, pkg); 7645 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7646 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7647 createIdmapFailed = true; 7648 } 7649 } 7650 } else if (mOverlays.containsKey(pkg.packageName) && 7651 !pkg.packageName.equals("android")) { 7652 // This is a regular package, with one or more known overlay packages. 7653 createIdmapsForPackageLI(pkg); 7654 } 7655 } 7656 7657 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7658 7659 if (createIdmapFailed) { 7660 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7661 "scanPackageLI failed to createIdmap"); 7662 } 7663 return pkg; 7664 } 7665 7666 /** 7667 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7668 * is derived purely on the basis of the contents of {@code scanFile} and 7669 * {@code cpuAbiOverride}. 7670 * 7671 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7672 */ 7673 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7674 String cpuAbiOverride, boolean extractLibs) 7675 throws PackageManagerException { 7676 // TODO: We can probably be smarter about this stuff. For installed apps, 7677 // we can calculate this information at install time once and for all. For 7678 // system apps, we can probably assume that this information doesn't change 7679 // after the first boot scan. As things stand, we do lots of unnecessary work. 7680 7681 // Give ourselves some initial paths; we'll come back for another 7682 // pass once we've determined ABI below. 7683 setNativeLibraryPaths(pkg); 7684 7685 // We would never need to extract libs for forward-locked and external packages, 7686 // since the container service will do it for us. We shouldn't attempt to 7687 // extract libs from system app when it was not updated. 7688 if (pkg.isForwardLocked() || isExternal(pkg) || 7689 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7690 extractLibs = false; 7691 } 7692 7693 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7694 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7695 7696 NativeLibraryHelper.Handle handle = null; 7697 try { 7698 handle = NativeLibraryHelper.Handle.create(pkg); 7699 // TODO(multiArch): This can be null for apps that didn't go through the 7700 // usual installation process. We can calculate it again, like we 7701 // do during install time. 7702 // 7703 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7704 // unnecessary. 7705 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7706 7707 // Null out the abis so that they can be recalculated. 7708 pkg.applicationInfo.primaryCpuAbi = null; 7709 pkg.applicationInfo.secondaryCpuAbi = null; 7710 if (isMultiArch(pkg.applicationInfo)) { 7711 // Warn if we've set an abiOverride for multi-lib packages.. 7712 // By definition, we need to copy both 32 and 64 bit libraries for 7713 // such packages. 7714 if (pkg.cpuAbiOverride != null 7715 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7716 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7717 } 7718 7719 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7720 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7721 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7722 if (extractLibs) { 7723 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7724 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7725 useIsaSpecificSubdirs); 7726 } else { 7727 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7728 } 7729 } 7730 7731 maybeThrowExceptionForMultiArchCopy( 7732 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7733 7734 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7735 if (extractLibs) { 7736 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7737 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7738 useIsaSpecificSubdirs); 7739 } else { 7740 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7741 } 7742 } 7743 7744 maybeThrowExceptionForMultiArchCopy( 7745 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7746 7747 if (abi64 >= 0) { 7748 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7749 } 7750 7751 if (abi32 >= 0) { 7752 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7753 if (abi64 >= 0) { 7754 pkg.applicationInfo.secondaryCpuAbi = abi; 7755 } else { 7756 pkg.applicationInfo.primaryCpuAbi = abi; 7757 } 7758 } 7759 } else { 7760 String[] abiList = (cpuAbiOverride != null) ? 7761 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7762 7763 // Enable gross and lame hacks for apps that are built with old 7764 // SDK tools. We must scan their APKs for renderscript bitcode and 7765 // not launch them if it's present. Don't bother checking on devices 7766 // that don't have 64 bit support. 7767 boolean needsRenderScriptOverride = false; 7768 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7769 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7770 abiList = Build.SUPPORTED_32_BIT_ABIS; 7771 needsRenderScriptOverride = true; 7772 } 7773 7774 final int copyRet; 7775 if (extractLibs) { 7776 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7777 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7778 } else { 7779 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7780 } 7781 7782 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7783 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7784 "Error unpackaging native libs for app, errorCode=" + copyRet); 7785 } 7786 7787 if (copyRet >= 0) { 7788 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7789 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7790 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7791 } else if (needsRenderScriptOverride) { 7792 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7793 } 7794 } 7795 } catch (IOException ioe) { 7796 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7797 } finally { 7798 IoUtils.closeQuietly(handle); 7799 } 7800 7801 // Now that we've calculated the ABIs and determined if it's an internal app, 7802 // we will go ahead and populate the nativeLibraryPath. 7803 setNativeLibraryPaths(pkg); 7804 } 7805 7806 /** 7807 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7808 * i.e, so that all packages can be run inside a single process if required. 7809 * 7810 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7811 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7812 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7813 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7814 * updating a package that belongs to a shared user. 7815 * 7816 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7817 * adds unnecessary complexity. 7818 */ 7819 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7820 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7821 boolean bootComplete) { 7822 String requiredInstructionSet = null; 7823 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7824 requiredInstructionSet = VMRuntime.getInstructionSet( 7825 scannedPackage.applicationInfo.primaryCpuAbi); 7826 } 7827 7828 PackageSetting requirer = null; 7829 for (PackageSetting ps : packagesForUser) { 7830 // If packagesForUser contains scannedPackage, we skip it. This will happen 7831 // when scannedPackage is an update of an existing package. Without this check, 7832 // we will never be able to change the ABI of any package belonging to a shared 7833 // user, even if it's compatible with other packages. 7834 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7835 if (ps.primaryCpuAbiString == null) { 7836 continue; 7837 } 7838 7839 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7840 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7841 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7842 // this but there's not much we can do. 7843 String errorMessage = "Instruction set mismatch, " 7844 + ((requirer == null) ? "[caller]" : requirer) 7845 + " requires " + requiredInstructionSet + " whereas " + ps 7846 + " requires " + instructionSet; 7847 Slog.w(TAG, errorMessage); 7848 } 7849 7850 if (requiredInstructionSet == null) { 7851 requiredInstructionSet = instructionSet; 7852 requirer = ps; 7853 } 7854 } 7855 } 7856 7857 if (requiredInstructionSet != null) { 7858 String adjustedAbi; 7859 if (requirer != null) { 7860 // requirer != null implies that either scannedPackage was null or that scannedPackage 7861 // did not require an ABI, in which case we have to adjust scannedPackage to match 7862 // the ABI of the set (which is the same as requirer's ABI) 7863 adjustedAbi = requirer.primaryCpuAbiString; 7864 if (scannedPackage != null) { 7865 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7866 } 7867 } else { 7868 // requirer == null implies that we're updating all ABIs in the set to 7869 // match scannedPackage. 7870 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7871 } 7872 7873 for (PackageSetting ps : packagesForUser) { 7874 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7875 if (ps.primaryCpuAbiString != null) { 7876 continue; 7877 } 7878 7879 ps.primaryCpuAbiString = adjustedAbi; 7880 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7881 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7882 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7883 7884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7885 7886 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7887 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7888 bootComplete, false /*useJit*/); 7889 7890 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7891 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7892 ps.primaryCpuAbiString = null; 7893 ps.pkg.applicationInfo.primaryCpuAbi = null; 7894 return; 7895 } else { 7896 mInstaller.rmdex(ps.codePathString, 7897 getDexCodeInstructionSet(getPreferredInstructionSet())); 7898 } 7899 } 7900 } 7901 } 7902 } 7903 } 7904 7905 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7906 synchronized (mPackages) { 7907 mResolverReplaced = true; 7908 // Set up information for custom user intent resolution activity. 7909 mResolveActivity.applicationInfo = pkg.applicationInfo; 7910 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7911 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7912 mResolveActivity.processName = pkg.applicationInfo.packageName; 7913 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7914 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7915 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7916 mResolveActivity.theme = 0; 7917 mResolveActivity.exported = true; 7918 mResolveActivity.enabled = true; 7919 mResolveInfo.activityInfo = mResolveActivity; 7920 mResolveInfo.priority = 0; 7921 mResolveInfo.preferredOrder = 0; 7922 mResolveInfo.match = 0; 7923 mResolveComponentName = mCustomResolverComponentName; 7924 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7925 mResolveComponentName); 7926 } 7927 } 7928 7929 private static String calculateBundledApkRoot(final String codePathString) { 7930 final File codePath = new File(codePathString); 7931 final File codeRoot; 7932 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7933 codeRoot = Environment.getRootDirectory(); 7934 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7935 codeRoot = Environment.getOemDirectory(); 7936 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7937 codeRoot = Environment.getVendorDirectory(); 7938 } else { 7939 // Unrecognized code path; take its top real segment as the apk root: 7940 // e.g. /something/app/blah.apk => /something 7941 try { 7942 File f = codePath.getCanonicalFile(); 7943 File parent = f.getParentFile(); // non-null because codePath is a file 7944 File tmp; 7945 while ((tmp = parent.getParentFile()) != null) { 7946 f = parent; 7947 parent = tmp; 7948 } 7949 codeRoot = f; 7950 Slog.w(TAG, "Unrecognized code path " 7951 + codePath + " - using " + codeRoot); 7952 } catch (IOException e) { 7953 // Can't canonicalize the code path -- shenanigans? 7954 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7955 return Environment.getRootDirectory().getPath(); 7956 } 7957 } 7958 return codeRoot.getPath(); 7959 } 7960 7961 /** 7962 * Derive and set the location of native libraries for the given package, 7963 * which varies depending on where and how the package was installed. 7964 */ 7965 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7966 final ApplicationInfo info = pkg.applicationInfo; 7967 final String codePath = pkg.codePath; 7968 final File codeFile = new File(codePath); 7969 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7970 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7971 7972 info.nativeLibraryRootDir = null; 7973 info.nativeLibraryRootRequiresIsa = false; 7974 info.nativeLibraryDir = null; 7975 info.secondaryNativeLibraryDir = null; 7976 7977 if (isApkFile(codeFile)) { 7978 // Monolithic install 7979 if (bundledApp) { 7980 // If "/system/lib64/apkname" exists, assume that is the per-package 7981 // native library directory to use; otherwise use "/system/lib/apkname". 7982 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7983 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7984 getPrimaryInstructionSet(info)); 7985 7986 // This is a bundled system app so choose the path based on the ABI. 7987 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7988 // is just the default path. 7989 final String apkName = deriveCodePathName(codePath); 7990 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7991 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7992 apkName).getAbsolutePath(); 7993 7994 if (info.secondaryCpuAbi != null) { 7995 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7996 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7997 secondaryLibDir, apkName).getAbsolutePath(); 7998 } 7999 } else if (asecApp) { 8000 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8001 .getAbsolutePath(); 8002 } else { 8003 final String apkName = deriveCodePathName(codePath); 8004 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8005 .getAbsolutePath(); 8006 } 8007 8008 info.nativeLibraryRootRequiresIsa = false; 8009 info.nativeLibraryDir = info.nativeLibraryRootDir; 8010 } else { 8011 // Cluster install 8012 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8013 info.nativeLibraryRootRequiresIsa = true; 8014 8015 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8016 getPrimaryInstructionSet(info)).getAbsolutePath(); 8017 8018 if (info.secondaryCpuAbi != null) { 8019 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8020 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8021 } 8022 } 8023 } 8024 8025 /** 8026 * Calculate the abis and roots for a bundled app. These can uniquely 8027 * be determined from the contents of the system partition, i.e whether 8028 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8029 * of this information, and instead assume that the system was built 8030 * sensibly. 8031 */ 8032 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8033 PackageSetting pkgSetting) { 8034 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8035 8036 // If "/system/lib64/apkname" exists, assume that is the per-package 8037 // native library directory to use; otherwise use "/system/lib/apkname". 8038 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8039 setBundledAppAbi(pkg, apkRoot, apkName); 8040 // pkgSetting might be null during rescan following uninstall of updates 8041 // to a bundled app, so accommodate that possibility. The settings in 8042 // that case will be established later from the parsed package. 8043 // 8044 // If the settings aren't null, sync them up with what we've just derived. 8045 // note that apkRoot isn't stored in the package settings. 8046 if (pkgSetting != null) { 8047 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8048 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8049 } 8050 } 8051 8052 /** 8053 * Deduces the ABI of a bundled app and sets the relevant fields on the 8054 * parsed pkg object. 8055 * 8056 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8057 * under which system libraries are installed. 8058 * @param apkName the name of the installed package. 8059 */ 8060 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8061 final File codeFile = new File(pkg.codePath); 8062 8063 final boolean has64BitLibs; 8064 final boolean has32BitLibs; 8065 if (isApkFile(codeFile)) { 8066 // Monolithic install 8067 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8068 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8069 } else { 8070 // Cluster install 8071 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8072 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8073 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8074 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8075 has64BitLibs = (new File(rootDir, isa)).exists(); 8076 } else { 8077 has64BitLibs = false; 8078 } 8079 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8080 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8081 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8082 has32BitLibs = (new File(rootDir, isa)).exists(); 8083 } else { 8084 has32BitLibs = false; 8085 } 8086 } 8087 8088 if (has64BitLibs && !has32BitLibs) { 8089 // The package has 64 bit libs, but not 32 bit libs. Its primary 8090 // ABI should be 64 bit. We can safely assume here that the bundled 8091 // native libraries correspond to the most preferred ABI in the list. 8092 8093 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8094 pkg.applicationInfo.secondaryCpuAbi = null; 8095 } else if (has32BitLibs && !has64BitLibs) { 8096 // The package has 32 bit libs but not 64 bit libs. Its primary 8097 // ABI should be 32 bit. 8098 8099 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8100 pkg.applicationInfo.secondaryCpuAbi = null; 8101 } else if (has32BitLibs && has64BitLibs) { 8102 // The application has both 64 and 32 bit bundled libraries. We check 8103 // here that the app declares multiArch support, and warn if it doesn't. 8104 // 8105 // We will be lenient here and record both ABIs. The primary will be the 8106 // ABI that's higher on the list, i.e, a device that's configured to prefer 8107 // 64 bit apps will see a 64 bit primary ABI, 8108 8109 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8110 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8111 } 8112 8113 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8114 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8115 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8116 } else { 8117 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8118 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8119 } 8120 } else { 8121 pkg.applicationInfo.primaryCpuAbi = null; 8122 pkg.applicationInfo.secondaryCpuAbi = null; 8123 } 8124 } 8125 8126 private void killApplication(String pkgName, int appId, String reason) { 8127 // Request the ActivityManager to kill the process(only for existing packages) 8128 // so that we do not end up in a confused state while the user is still using the older 8129 // version of the application while the new one gets installed. 8130 IActivityManager am = ActivityManagerNative.getDefault(); 8131 if (am != null) { 8132 try { 8133 am.killApplicationWithAppId(pkgName, appId, reason); 8134 } catch (RemoteException e) { 8135 } 8136 } 8137 } 8138 8139 void removePackageLI(PackageSetting ps, boolean chatty) { 8140 if (DEBUG_INSTALL) { 8141 if (chatty) 8142 Log.d(TAG, "Removing package " + ps.name); 8143 } 8144 8145 // writer 8146 synchronized (mPackages) { 8147 mPackages.remove(ps.name); 8148 final PackageParser.Package pkg = ps.pkg; 8149 if (pkg != null) { 8150 cleanPackageDataStructuresLILPw(pkg, chatty); 8151 } 8152 } 8153 } 8154 8155 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8156 if (DEBUG_INSTALL) { 8157 if (chatty) 8158 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8159 } 8160 8161 // writer 8162 synchronized (mPackages) { 8163 mPackages.remove(pkg.applicationInfo.packageName); 8164 cleanPackageDataStructuresLILPw(pkg, chatty); 8165 } 8166 } 8167 8168 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8169 int N = pkg.providers.size(); 8170 StringBuilder r = null; 8171 int i; 8172 for (i=0; i<N; i++) { 8173 PackageParser.Provider p = pkg.providers.get(i); 8174 mProviders.removeProvider(p); 8175 if (p.info.authority == null) { 8176 8177 /* There was another ContentProvider with this authority when 8178 * this app was installed so this authority is null, 8179 * Ignore it as we don't have to unregister the provider. 8180 */ 8181 continue; 8182 } 8183 String names[] = p.info.authority.split(";"); 8184 for (int j = 0; j < names.length; j++) { 8185 if (mProvidersByAuthority.get(names[j]) == p) { 8186 mProvidersByAuthority.remove(names[j]); 8187 if (DEBUG_REMOVE) { 8188 if (chatty) 8189 Log.d(TAG, "Unregistered content provider: " + names[j] 8190 + ", className = " + p.info.name + ", isSyncable = " 8191 + p.info.isSyncable); 8192 } 8193 } 8194 } 8195 if (DEBUG_REMOVE && chatty) { 8196 if (r == null) { 8197 r = new StringBuilder(256); 8198 } else { 8199 r.append(' '); 8200 } 8201 r.append(p.info.name); 8202 } 8203 } 8204 if (r != null) { 8205 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8206 } 8207 8208 N = pkg.services.size(); 8209 r = null; 8210 for (i=0; i<N; i++) { 8211 PackageParser.Service s = pkg.services.get(i); 8212 mServices.removeService(s); 8213 if (chatty) { 8214 if (r == null) { 8215 r = new StringBuilder(256); 8216 } else { 8217 r.append(' '); 8218 } 8219 r.append(s.info.name); 8220 } 8221 } 8222 if (r != null) { 8223 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8224 } 8225 8226 N = pkg.receivers.size(); 8227 r = null; 8228 for (i=0; i<N; i++) { 8229 PackageParser.Activity a = pkg.receivers.get(i); 8230 mReceivers.removeActivity(a, "receiver"); 8231 if (DEBUG_REMOVE && chatty) { 8232 if (r == null) { 8233 r = new StringBuilder(256); 8234 } else { 8235 r.append(' '); 8236 } 8237 r.append(a.info.name); 8238 } 8239 } 8240 if (r != null) { 8241 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8242 } 8243 8244 N = pkg.activities.size(); 8245 r = null; 8246 for (i=0; i<N; i++) { 8247 PackageParser.Activity a = pkg.activities.get(i); 8248 mActivities.removeActivity(a, "activity"); 8249 if (DEBUG_REMOVE && chatty) { 8250 if (r == null) { 8251 r = new StringBuilder(256); 8252 } else { 8253 r.append(' '); 8254 } 8255 r.append(a.info.name); 8256 } 8257 } 8258 if (r != null) { 8259 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8260 } 8261 8262 N = pkg.permissions.size(); 8263 r = null; 8264 for (i=0; i<N; i++) { 8265 PackageParser.Permission p = pkg.permissions.get(i); 8266 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8267 if (bp == null) { 8268 bp = mSettings.mPermissionTrees.get(p.info.name); 8269 } 8270 if (bp != null && bp.perm == p) { 8271 bp.perm = null; 8272 if (DEBUG_REMOVE && chatty) { 8273 if (r == null) { 8274 r = new StringBuilder(256); 8275 } else { 8276 r.append(' '); 8277 } 8278 r.append(p.info.name); 8279 } 8280 } 8281 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8282 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8283 if (appOpPerms != null) { 8284 appOpPerms.remove(pkg.packageName); 8285 } 8286 } 8287 } 8288 if (r != null) { 8289 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8290 } 8291 8292 N = pkg.requestedPermissions.size(); 8293 r = null; 8294 for (i=0; i<N; i++) { 8295 String perm = pkg.requestedPermissions.get(i); 8296 BasePermission bp = mSettings.mPermissions.get(perm); 8297 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8298 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8299 if (appOpPerms != null) { 8300 appOpPerms.remove(pkg.packageName); 8301 if (appOpPerms.isEmpty()) { 8302 mAppOpPermissionPackages.remove(perm); 8303 } 8304 } 8305 } 8306 } 8307 if (r != null) { 8308 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8309 } 8310 8311 N = pkg.instrumentation.size(); 8312 r = null; 8313 for (i=0; i<N; i++) { 8314 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8315 mInstrumentation.remove(a.getComponentName()); 8316 if (DEBUG_REMOVE && chatty) { 8317 if (r == null) { 8318 r = new StringBuilder(256); 8319 } else { 8320 r.append(' '); 8321 } 8322 r.append(a.info.name); 8323 } 8324 } 8325 if (r != null) { 8326 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8327 } 8328 8329 r = null; 8330 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8331 // Only system apps can hold shared libraries. 8332 if (pkg.libraryNames != null) { 8333 for (i=0; i<pkg.libraryNames.size(); i++) { 8334 String name = pkg.libraryNames.get(i); 8335 SharedLibraryEntry cur = mSharedLibraries.get(name); 8336 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8337 mSharedLibraries.remove(name); 8338 if (DEBUG_REMOVE && chatty) { 8339 if (r == null) { 8340 r = new StringBuilder(256); 8341 } else { 8342 r.append(' '); 8343 } 8344 r.append(name); 8345 } 8346 } 8347 } 8348 } 8349 } 8350 if (r != null) { 8351 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8352 } 8353 } 8354 8355 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8356 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8357 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8358 return true; 8359 } 8360 } 8361 return false; 8362 } 8363 8364 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8365 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8366 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8367 8368 private void updatePermissionsLPw(String changingPkg, 8369 PackageParser.Package pkgInfo, int flags) { 8370 // Make sure there are no dangling permission trees. 8371 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8372 while (it.hasNext()) { 8373 final BasePermission bp = it.next(); 8374 if (bp.packageSetting == null) { 8375 // We may not yet have parsed the package, so just see if 8376 // we still know about its settings. 8377 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8378 } 8379 if (bp.packageSetting == null) { 8380 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8381 + " from package " + bp.sourcePackage); 8382 it.remove(); 8383 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8384 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8385 Slog.i(TAG, "Removing old permission tree: " + bp.name 8386 + " from package " + bp.sourcePackage); 8387 flags |= UPDATE_PERMISSIONS_ALL; 8388 it.remove(); 8389 } 8390 } 8391 } 8392 8393 // Make sure all dynamic permissions have been assigned to a package, 8394 // and make sure there are no dangling permissions. 8395 it = mSettings.mPermissions.values().iterator(); 8396 while (it.hasNext()) { 8397 final BasePermission bp = it.next(); 8398 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8399 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8400 + bp.name + " pkg=" + bp.sourcePackage 8401 + " info=" + bp.pendingInfo); 8402 if (bp.packageSetting == null && bp.pendingInfo != null) { 8403 final BasePermission tree = findPermissionTreeLP(bp.name); 8404 if (tree != null && tree.perm != null) { 8405 bp.packageSetting = tree.packageSetting; 8406 bp.perm = new PackageParser.Permission(tree.perm.owner, 8407 new PermissionInfo(bp.pendingInfo)); 8408 bp.perm.info.packageName = tree.perm.info.packageName; 8409 bp.perm.info.name = bp.name; 8410 bp.uid = tree.uid; 8411 } 8412 } 8413 } 8414 if (bp.packageSetting == null) { 8415 // We may not yet have parsed the package, so just see if 8416 // we still know about its settings. 8417 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8418 } 8419 if (bp.packageSetting == null) { 8420 Slog.w(TAG, "Removing dangling permission: " + bp.name 8421 + " from package " + bp.sourcePackage); 8422 it.remove(); 8423 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8424 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8425 Slog.i(TAG, "Removing old permission: " + bp.name 8426 + " from package " + bp.sourcePackage); 8427 flags |= UPDATE_PERMISSIONS_ALL; 8428 it.remove(); 8429 } 8430 } 8431 } 8432 8433 // Now update the permissions for all packages, in particular 8434 // replace the granted permissions of the system packages. 8435 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8436 for (PackageParser.Package pkg : mPackages.values()) { 8437 if (pkg != pkgInfo) { 8438 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8439 changingPkg); 8440 } 8441 } 8442 } 8443 8444 if (pkgInfo != null) { 8445 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8446 } 8447 } 8448 8449 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8450 String packageOfInterest) { 8451 // IMPORTANT: There are two types of permissions: install and runtime. 8452 // Install time permissions are granted when the app is installed to 8453 // all device users and users added in the future. Runtime permissions 8454 // are granted at runtime explicitly to specific users. Normal and signature 8455 // protected permissions are install time permissions. Dangerous permissions 8456 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8457 // otherwise they are runtime permissions. This function does not manage 8458 // runtime permissions except for the case an app targeting Lollipop MR1 8459 // being upgraded to target a newer SDK, in which case dangerous permissions 8460 // are transformed from install time to runtime ones. 8461 8462 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8463 if (ps == null) { 8464 return; 8465 } 8466 8467 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8468 8469 PermissionsState permissionsState = ps.getPermissionsState(); 8470 PermissionsState origPermissions = permissionsState; 8471 8472 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8473 8474 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8475 8476 boolean changedInstallPermission = false; 8477 8478 if (replace) { 8479 ps.installPermissionsFixed = false; 8480 if (!ps.isSharedUser()) { 8481 origPermissions = new PermissionsState(permissionsState); 8482 permissionsState.reset(); 8483 } 8484 } 8485 8486 permissionsState.setGlobalGids(mGlobalGids); 8487 8488 final int N = pkg.requestedPermissions.size(); 8489 for (int i=0; i<N; i++) { 8490 final String name = pkg.requestedPermissions.get(i); 8491 final BasePermission bp = mSettings.mPermissions.get(name); 8492 8493 if (DEBUG_INSTALL) { 8494 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8495 } 8496 8497 if (bp == null || bp.packageSetting == null) { 8498 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8499 Slog.w(TAG, "Unknown permission " + name 8500 + " in package " + pkg.packageName); 8501 } 8502 continue; 8503 } 8504 8505 final String perm = bp.name; 8506 boolean allowedSig = false; 8507 int grant = GRANT_DENIED; 8508 8509 // Keep track of app op permissions. 8510 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8511 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8512 if (pkgs == null) { 8513 pkgs = new ArraySet<>(); 8514 mAppOpPermissionPackages.put(bp.name, pkgs); 8515 } 8516 pkgs.add(pkg.packageName); 8517 } 8518 8519 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8520 switch (level) { 8521 case PermissionInfo.PROTECTION_NORMAL: { 8522 // For all apps normal permissions are install time ones. 8523 grant = GRANT_INSTALL; 8524 } break; 8525 8526 case PermissionInfo.PROTECTION_DANGEROUS: { 8527 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8528 // For legacy apps dangerous permissions are install time ones. 8529 grant = GRANT_INSTALL_LEGACY; 8530 } else if (origPermissions.hasInstallPermission(bp.name)) { 8531 // For legacy apps that became modern, install becomes runtime. 8532 grant = GRANT_UPGRADE; 8533 } else if (mPromoteSystemApps 8534 && isSystemApp(ps) 8535 && mExistingSystemPackages.contains(ps.name)) { 8536 // For legacy system apps, install becomes runtime. 8537 // We cannot check hasInstallPermission() for system apps since those 8538 // permissions were granted implicitly and not persisted pre-M. 8539 grant = GRANT_UPGRADE; 8540 } else { 8541 // For modern apps keep runtime permissions unchanged. 8542 grant = GRANT_RUNTIME; 8543 } 8544 } break; 8545 8546 case PermissionInfo.PROTECTION_SIGNATURE: { 8547 // For all apps signature permissions are install time ones. 8548 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8549 if (allowedSig) { 8550 grant = GRANT_INSTALL; 8551 } 8552 } break; 8553 } 8554 8555 if (DEBUG_INSTALL) { 8556 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8557 } 8558 8559 if (grant != GRANT_DENIED) { 8560 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8561 // If this is an existing, non-system package, then 8562 // we can't add any new permissions to it. 8563 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8564 // Except... if this is a permission that was added 8565 // to the platform (note: need to only do this when 8566 // updating the platform). 8567 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8568 grant = GRANT_DENIED; 8569 } 8570 } 8571 } 8572 8573 switch (grant) { 8574 case GRANT_INSTALL: { 8575 // Revoke this as runtime permission to handle the case of 8576 // a runtime permission being downgraded to an install one. 8577 for (int userId : UserManagerService.getInstance().getUserIds()) { 8578 if (origPermissions.getRuntimePermissionState( 8579 bp.name, userId) != null) { 8580 // Revoke the runtime permission and clear the flags. 8581 origPermissions.revokeRuntimePermission(bp, userId); 8582 origPermissions.updatePermissionFlags(bp, userId, 8583 PackageManager.MASK_PERMISSION_FLAGS, 0); 8584 // If we revoked a permission permission, we have to write. 8585 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8586 changedRuntimePermissionUserIds, userId); 8587 } 8588 } 8589 // Grant an install permission. 8590 if (permissionsState.grantInstallPermission(bp) != 8591 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8592 changedInstallPermission = true; 8593 } 8594 } break; 8595 8596 case GRANT_INSTALL_LEGACY: { 8597 // Grant an install permission. 8598 if (permissionsState.grantInstallPermission(bp) != 8599 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8600 changedInstallPermission = true; 8601 } 8602 } break; 8603 8604 case GRANT_RUNTIME: { 8605 // Grant previously granted runtime permissions. 8606 for (int userId : UserManagerService.getInstance().getUserIds()) { 8607 PermissionState permissionState = origPermissions 8608 .getRuntimePermissionState(bp.name, userId); 8609 final int flags = permissionState != null 8610 ? permissionState.getFlags() : 0; 8611 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8612 if (permissionsState.grantRuntimePermission(bp, userId) == 8613 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8614 // If we cannot put the permission as it was, we have to write. 8615 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8616 changedRuntimePermissionUserIds, userId); 8617 } 8618 } 8619 // Propagate the permission flags. 8620 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8621 } 8622 } break; 8623 8624 case GRANT_UPGRADE: { 8625 // Grant runtime permissions for a previously held install permission. 8626 PermissionState permissionState = origPermissions 8627 .getInstallPermissionState(bp.name); 8628 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8629 8630 if (origPermissions.revokeInstallPermission(bp) 8631 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8632 // We will be transferring the permission flags, so clear them. 8633 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8634 PackageManager.MASK_PERMISSION_FLAGS, 0); 8635 changedInstallPermission = true; 8636 } 8637 8638 // If the permission is not to be promoted to runtime we ignore it and 8639 // also its other flags as they are not applicable to install permissions. 8640 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8641 for (int userId : currentUserIds) { 8642 if (permissionsState.grantRuntimePermission(bp, userId) != 8643 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8644 // Transfer the permission flags. 8645 permissionsState.updatePermissionFlags(bp, userId, 8646 flags, flags); 8647 // If we granted the permission, we have to write. 8648 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8649 changedRuntimePermissionUserIds, userId); 8650 } 8651 } 8652 } 8653 } break; 8654 8655 default: { 8656 if (packageOfInterest == null 8657 || packageOfInterest.equals(pkg.packageName)) { 8658 Slog.w(TAG, "Not granting permission " + perm 8659 + " to package " + pkg.packageName 8660 + " because it was previously installed without"); 8661 } 8662 } break; 8663 } 8664 } else { 8665 if (permissionsState.revokeInstallPermission(bp) != 8666 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8667 // Also drop the permission flags. 8668 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8669 PackageManager.MASK_PERMISSION_FLAGS, 0); 8670 changedInstallPermission = true; 8671 Slog.i(TAG, "Un-granting permission " + perm 8672 + " from package " + pkg.packageName 8673 + " (protectionLevel=" + bp.protectionLevel 8674 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8675 + ")"); 8676 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8677 // Don't print warning for app op permissions, since it is fine for them 8678 // not to be granted, there is a UI for the user to decide. 8679 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8680 Slog.w(TAG, "Not granting permission " + perm 8681 + " to package " + pkg.packageName 8682 + " (protectionLevel=" + bp.protectionLevel 8683 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8684 + ")"); 8685 } 8686 } 8687 } 8688 } 8689 8690 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8691 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8692 // This is the first that we have heard about this package, so the 8693 // permissions we have now selected are fixed until explicitly 8694 // changed. 8695 ps.installPermissionsFixed = true; 8696 } 8697 8698 // Persist the runtime permissions state for users with changes. 8699 for (int userId : changedRuntimePermissionUserIds) { 8700 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8701 } 8702 8703 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8704 } 8705 8706 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8707 boolean allowed = false; 8708 final int NP = PackageParser.NEW_PERMISSIONS.length; 8709 for (int ip=0; ip<NP; ip++) { 8710 final PackageParser.NewPermissionInfo npi 8711 = PackageParser.NEW_PERMISSIONS[ip]; 8712 if (npi.name.equals(perm) 8713 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8714 allowed = true; 8715 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8716 + pkg.packageName); 8717 break; 8718 } 8719 } 8720 return allowed; 8721 } 8722 8723 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8724 BasePermission bp, PermissionsState origPermissions) { 8725 boolean allowed; 8726 allowed = (compareSignatures( 8727 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8728 == PackageManager.SIGNATURE_MATCH) 8729 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8730 == PackageManager.SIGNATURE_MATCH); 8731 if (!allowed && (bp.protectionLevel 8732 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8733 if (isSystemApp(pkg)) { 8734 // For updated system applications, a system permission 8735 // is granted only if it had been defined by the original application. 8736 if (pkg.isUpdatedSystemApp()) { 8737 final PackageSetting sysPs = mSettings 8738 .getDisabledSystemPkgLPr(pkg.packageName); 8739 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8740 // If the original was granted this permission, we take 8741 // that grant decision as read and propagate it to the 8742 // update. 8743 if (sysPs.isPrivileged()) { 8744 allowed = true; 8745 } 8746 } else { 8747 // The system apk may have been updated with an older 8748 // version of the one on the data partition, but which 8749 // granted a new system permission that it didn't have 8750 // before. In this case we do want to allow the app to 8751 // now get the new permission if the ancestral apk is 8752 // privileged to get it. 8753 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8754 for (int j=0; 8755 j<sysPs.pkg.requestedPermissions.size(); j++) { 8756 if (perm.equals( 8757 sysPs.pkg.requestedPermissions.get(j))) { 8758 allowed = true; 8759 break; 8760 } 8761 } 8762 } 8763 } 8764 } else { 8765 allowed = isPrivilegedApp(pkg); 8766 } 8767 } 8768 } 8769 if (!allowed) { 8770 if (!allowed && (bp.protectionLevel 8771 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8772 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8773 // If this was a previously normal/dangerous permission that got moved 8774 // to a system permission as part of the runtime permission redesign, then 8775 // we still want to blindly grant it to old apps. 8776 allowed = true; 8777 } 8778 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8779 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8780 // If this permission is to be granted to the system installer and 8781 // this app is an installer, then it gets the permission. 8782 allowed = true; 8783 } 8784 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8785 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8786 // If this permission is to be granted to the system verifier and 8787 // this app is a verifier, then it gets the permission. 8788 allowed = true; 8789 } 8790 if (!allowed && (bp.protectionLevel 8791 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8792 && isSystemApp(pkg)) { 8793 // Any pre-installed system app is allowed to get this permission. 8794 allowed = true; 8795 } 8796 if (!allowed && (bp.protectionLevel 8797 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8798 // For development permissions, a development permission 8799 // is granted only if it was already granted. 8800 allowed = origPermissions.hasInstallPermission(perm); 8801 } 8802 } 8803 return allowed; 8804 } 8805 8806 final class ActivityIntentResolver 8807 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8808 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8809 boolean defaultOnly, int userId) { 8810 if (!sUserManager.exists(userId)) return null; 8811 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8812 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8813 } 8814 8815 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8816 int userId) { 8817 if (!sUserManager.exists(userId)) return null; 8818 mFlags = flags; 8819 return super.queryIntent(intent, resolvedType, 8820 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8821 } 8822 8823 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8824 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8825 if (!sUserManager.exists(userId)) return null; 8826 if (packageActivities == null) { 8827 return null; 8828 } 8829 mFlags = flags; 8830 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8831 final int N = packageActivities.size(); 8832 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8833 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8834 8835 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8836 for (int i = 0; i < N; ++i) { 8837 intentFilters = packageActivities.get(i).intents; 8838 if (intentFilters != null && intentFilters.size() > 0) { 8839 PackageParser.ActivityIntentInfo[] array = 8840 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8841 intentFilters.toArray(array); 8842 listCut.add(array); 8843 } 8844 } 8845 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8846 } 8847 8848 public final void addActivity(PackageParser.Activity a, String type) { 8849 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8850 mActivities.put(a.getComponentName(), a); 8851 if (DEBUG_SHOW_INFO) 8852 Log.v( 8853 TAG, " " + type + " " + 8854 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8855 if (DEBUG_SHOW_INFO) 8856 Log.v(TAG, " Class=" + a.info.name); 8857 final int NI = a.intents.size(); 8858 for (int j=0; j<NI; j++) { 8859 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8860 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8861 intent.setPriority(0); 8862 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8863 + a.className + " with priority > 0, forcing to 0"); 8864 } 8865 if (DEBUG_SHOW_INFO) { 8866 Log.v(TAG, " IntentFilter:"); 8867 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8868 } 8869 if (!intent.debugCheck()) { 8870 Log.w(TAG, "==> For Activity " + a.info.name); 8871 } 8872 addFilter(intent); 8873 } 8874 } 8875 8876 public final void removeActivity(PackageParser.Activity a, String type) { 8877 mActivities.remove(a.getComponentName()); 8878 if (DEBUG_SHOW_INFO) { 8879 Log.v(TAG, " " + type + " " 8880 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8881 : a.info.name) + ":"); 8882 Log.v(TAG, " Class=" + a.info.name); 8883 } 8884 final int NI = a.intents.size(); 8885 for (int j=0; j<NI; j++) { 8886 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8887 if (DEBUG_SHOW_INFO) { 8888 Log.v(TAG, " IntentFilter:"); 8889 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8890 } 8891 removeFilter(intent); 8892 } 8893 } 8894 8895 @Override 8896 protected boolean allowFilterResult( 8897 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8898 ActivityInfo filterAi = filter.activity.info; 8899 for (int i=dest.size()-1; i>=0; i--) { 8900 ActivityInfo destAi = dest.get(i).activityInfo; 8901 if (destAi.name == filterAi.name 8902 && destAi.packageName == filterAi.packageName) { 8903 return false; 8904 } 8905 } 8906 return true; 8907 } 8908 8909 @Override 8910 protected ActivityIntentInfo[] newArray(int size) { 8911 return new ActivityIntentInfo[size]; 8912 } 8913 8914 @Override 8915 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8916 if (!sUserManager.exists(userId)) return true; 8917 PackageParser.Package p = filter.activity.owner; 8918 if (p != null) { 8919 PackageSetting ps = (PackageSetting)p.mExtras; 8920 if (ps != null) { 8921 // System apps are never considered stopped for purposes of 8922 // filtering, because there may be no way for the user to 8923 // actually re-launch them. 8924 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8925 && ps.getStopped(userId); 8926 } 8927 } 8928 return false; 8929 } 8930 8931 @Override 8932 protected boolean isPackageForFilter(String packageName, 8933 PackageParser.ActivityIntentInfo info) { 8934 return packageName.equals(info.activity.owner.packageName); 8935 } 8936 8937 @Override 8938 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8939 int match, int userId) { 8940 if (!sUserManager.exists(userId)) return null; 8941 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8942 return null; 8943 } 8944 final PackageParser.Activity activity = info.activity; 8945 if (mSafeMode && (activity.info.applicationInfo.flags 8946 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8947 return null; 8948 } 8949 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8950 if (ps == null) { 8951 return null; 8952 } 8953 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8954 ps.readUserState(userId), userId); 8955 if (ai == null) { 8956 return null; 8957 } 8958 final ResolveInfo res = new ResolveInfo(); 8959 res.activityInfo = ai; 8960 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8961 res.filter = info; 8962 } 8963 if (info != null) { 8964 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8965 } 8966 res.priority = info.getPriority(); 8967 res.preferredOrder = activity.owner.mPreferredOrder; 8968 //System.out.println("Result: " + res.activityInfo.className + 8969 // " = " + res.priority); 8970 res.match = match; 8971 res.isDefault = info.hasDefault; 8972 res.labelRes = info.labelRes; 8973 res.nonLocalizedLabel = info.nonLocalizedLabel; 8974 if (userNeedsBadging(userId)) { 8975 res.noResourceId = true; 8976 } else { 8977 res.icon = info.icon; 8978 } 8979 res.iconResourceId = info.icon; 8980 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8981 return res; 8982 } 8983 8984 @Override 8985 protected void sortResults(List<ResolveInfo> results) { 8986 Collections.sort(results, mResolvePrioritySorter); 8987 } 8988 8989 @Override 8990 protected void dumpFilter(PrintWriter out, String prefix, 8991 PackageParser.ActivityIntentInfo filter) { 8992 out.print(prefix); out.print( 8993 Integer.toHexString(System.identityHashCode(filter.activity))); 8994 out.print(' '); 8995 filter.activity.printComponentShortName(out); 8996 out.print(" filter "); 8997 out.println(Integer.toHexString(System.identityHashCode(filter))); 8998 } 8999 9000 @Override 9001 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9002 return filter.activity; 9003 } 9004 9005 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9006 PackageParser.Activity activity = (PackageParser.Activity)label; 9007 out.print(prefix); out.print( 9008 Integer.toHexString(System.identityHashCode(activity))); 9009 out.print(' '); 9010 activity.printComponentShortName(out); 9011 if (count > 1) { 9012 out.print(" ("); out.print(count); out.print(" filters)"); 9013 } 9014 out.println(); 9015 } 9016 9017// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9018// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9019// final List<ResolveInfo> retList = Lists.newArrayList(); 9020// while (i.hasNext()) { 9021// final ResolveInfo resolveInfo = i.next(); 9022// if (isEnabledLP(resolveInfo.activityInfo)) { 9023// retList.add(resolveInfo); 9024// } 9025// } 9026// return retList; 9027// } 9028 9029 // Keys are String (activity class name), values are Activity. 9030 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9031 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9032 private int mFlags; 9033 } 9034 9035 private final class ServiceIntentResolver 9036 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9037 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9038 boolean defaultOnly, int userId) { 9039 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9040 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9041 } 9042 9043 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9044 int userId) { 9045 if (!sUserManager.exists(userId)) return null; 9046 mFlags = flags; 9047 return super.queryIntent(intent, resolvedType, 9048 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9049 } 9050 9051 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9052 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9053 if (!sUserManager.exists(userId)) return null; 9054 if (packageServices == null) { 9055 return null; 9056 } 9057 mFlags = flags; 9058 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9059 final int N = packageServices.size(); 9060 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9061 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9062 9063 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9064 for (int i = 0; i < N; ++i) { 9065 intentFilters = packageServices.get(i).intents; 9066 if (intentFilters != null && intentFilters.size() > 0) { 9067 PackageParser.ServiceIntentInfo[] array = 9068 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9069 intentFilters.toArray(array); 9070 listCut.add(array); 9071 } 9072 } 9073 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9074 } 9075 9076 public final void addService(PackageParser.Service s) { 9077 mServices.put(s.getComponentName(), s); 9078 if (DEBUG_SHOW_INFO) { 9079 Log.v(TAG, " " 9080 + (s.info.nonLocalizedLabel != null 9081 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9082 Log.v(TAG, " Class=" + s.info.name); 9083 } 9084 final int NI = s.intents.size(); 9085 int j; 9086 for (j=0; j<NI; j++) { 9087 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9088 if (DEBUG_SHOW_INFO) { 9089 Log.v(TAG, " IntentFilter:"); 9090 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9091 } 9092 if (!intent.debugCheck()) { 9093 Log.w(TAG, "==> For Service " + s.info.name); 9094 } 9095 addFilter(intent); 9096 } 9097 } 9098 9099 public final void removeService(PackageParser.Service s) { 9100 mServices.remove(s.getComponentName()); 9101 if (DEBUG_SHOW_INFO) { 9102 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9103 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9104 Log.v(TAG, " Class=" + s.info.name); 9105 } 9106 final int NI = s.intents.size(); 9107 int j; 9108 for (j=0; j<NI; j++) { 9109 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9110 if (DEBUG_SHOW_INFO) { 9111 Log.v(TAG, " IntentFilter:"); 9112 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9113 } 9114 removeFilter(intent); 9115 } 9116 } 9117 9118 @Override 9119 protected boolean allowFilterResult( 9120 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9121 ServiceInfo filterSi = filter.service.info; 9122 for (int i=dest.size()-1; i>=0; i--) { 9123 ServiceInfo destAi = dest.get(i).serviceInfo; 9124 if (destAi.name == filterSi.name 9125 && destAi.packageName == filterSi.packageName) { 9126 return false; 9127 } 9128 } 9129 return true; 9130 } 9131 9132 @Override 9133 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9134 return new PackageParser.ServiceIntentInfo[size]; 9135 } 9136 9137 @Override 9138 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9139 if (!sUserManager.exists(userId)) return true; 9140 PackageParser.Package p = filter.service.owner; 9141 if (p != null) { 9142 PackageSetting ps = (PackageSetting)p.mExtras; 9143 if (ps != null) { 9144 // System apps are never considered stopped for purposes of 9145 // filtering, because there may be no way for the user to 9146 // actually re-launch them. 9147 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9148 && ps.getStopped(userId); 9149 } 9150 } 9151 return false; 9152 } 9153 9154 @Override 9155 protected boolean isPackageForFilter(String packageName, 9156 PackageParser.ServiceIntentInfo info) { 9157 return packageName.equals(info.service.owner.packageName); 9158 } 9159 9160 @Override 9161 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9162 int match, int userId) { 9163 if (!sUserManager.exists(userId)) return null; 9164 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9165 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9166 return null; 9167 } 9168 final PackageParser.Service service = info.service; 9169 if (mSafeMode && (service.info.applicationInfo.flags 9170 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9171 return null; 9172 } 9173 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9174 if (ps == null) { 9175 return null; 9176 } 9177 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9178 ps.readUserState(userId), userId); 9179 if (si == null) { 9180 return null; 9181 } 9182 final ResolveInfo res = new ResolveInfo(); 9183 res.serviceInfo = si; 9184 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9185 res.filter = filter; 9186 } 9187 res.priority = info.getPriority(); 9188 res.preferredOrder = service.owner.mPreferredOrder; 9189 res.match = match; 9190 res.isDefault = info.hasDefault; 9191 res.labelRes = info.labelRes; 9192 res.nonLocalizedLabel = info.nonLocalizedLabel; 9193 res.icon = info.icon; 9194 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9195 return res; 9196 } 9197 9198 @Override 9199 protected void sortResults(List<ResolveInfo> results) { 9200 Collections.sort(results, mResolvePrioritySorter); 9201 } 9202 9203 @Override 9204 protected void dumpFilter(PrintWriter out, String prefix, 9205 PackageParser.ServiceIntentInfo filter) { 9206 out.print(prefix); out.print( 9207 Integer.toHexString(System.identityHashCode(filter.service))); 9208 out.print(' '); 9209 filter.service.printComponentShortName(out); 9210 out.print(" filter "); 9211 out.println(Integer.toHexString(System.identityHashCode(filter))); 9212 } 9213 9214 @Override 9215 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9216 return filter.service; 9217 } 9218 9219 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9220 PackageParser.Service service = (PackageParser.Service)label; 9221 out.print(prefix); out.print( 9222 Integer.toHexString(System.identityHashCode(service))); 9223 out.print(' '); 9224 service.printComponentShortName(out); 9225 if (count > 1) { 9226 out.print(" ("); out.print(count); out.print(" filters)"); 9227 } 9228 out.println(); 9229 } 9230 9231// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9232// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9233// final List<ResolveInfo> retList = Lists.newArrayList(); 9234// while (i.hasNext()) { 9235// final ResolveInfo resolveInfo = (ResolveInfo) i; 9236// if (isEnabledLP(resolveInfo.serviceInfo)) { 9237// retList.add(resolveInfo); 9238// } 9239// } 9240// return retList; 9241// } 9242 9243 // Keys are String (activity class name), values are Activity. 9244 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9245 = new ArrayMap<ComponentName, PackageParser.Service>(); 9246 private int mFlags; 9247 }; 9248 9249 private final class ProviderIntentResolver 9250 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9251 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9252 boolean defaultOnly, int userId) { 9253 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9254 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9255 } 9256 9257 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9258 int userId) { 9259 if (!sUserManager.exists(userId)) 9260 return null; 9261 mFlags = flags; 9262 return super.queryIntent(intent, resolvedType, 9263 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9264 } 9265 9266 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9267 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9268 if (!sUserManager.exists(userId)) 9269 return null; 9270 if (packageProviders == null) { 9271 return null; 9272 } 9273 mFlags = flags; 9274 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9275 final int N = packageProviders.size(); 9276 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9277 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9278 9279 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9280 for (int i = 0; i < N; ++i) { 9281 intentFilters = packageProviders.get(i).intents; 9282 if (intentFilters != null && intentFilters.size() > 0) { 9283 PackageParser.ProviderIntentInfo[] array = 9284 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9285 intentFilters.toArray(array); 9286 listCut.add(array); 9287 } 9288 } 9289 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9290 } 9291 9292 public final void addProvider(PackageParser.Provider p) { 9293 if (mProviders.containsKey(p.getComponentName())) { 9294 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9295 return; 9296 } 9297 9298 mProviders.put(p.getComponentName(), p); 9299 if (DEBUG_SHOW_INFO) { 9300 Log.v(TAG, " " 9301 + (p.info.nonLocalizedLabel != null 9302 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9303 Log.v(TAG, " Class=" + p.info.name); 9304 } 9305 final int NI = p.intents.size(); 9306 int j; 9307 for (j = 0; j < NI; j++) { 9308 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9309 if (DEBUG_SHOW_INFO) { 9310 Log.v(TAG, " IntentFilter:"); 9311 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9312 } 9313 if (!intent.debugCheck()) { 9314 Log.w(TAG, "==> For Provider " + p.info.name); 9315 } 9316 addFilter(intent); 9317 } 9318 } 9319 9320 public final void removeProvider(PackageParser.Provider p) { 9321 mProviders.remove(p.getComponentName()); 9322 if (DEBUG_SHOW_INFO) { 9323 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9324 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9325 Log.v(TAG, " Class=" + p.info.name); 9326 } 9327 final int NI = p.intents.size(); 9328 int j; 9329 for (j = 0; j < NI; j++) { 9330 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9331 if (DEBUG_SHOW_INFO) { 9332 Log.v(TAG, " IntentFilter:"); 9333 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9334 } 9335 removeFilter(intent); 9336 } 9337 } 9338 9339 @Override 9340 protected boolean allowFilterResult( 9341 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9342 ProviderInfo filterPi = filter.provider.info; 9343 for (int i = dest.size() - 1; i >= 0; i--) { 9344 ProviderInfo destPi = dest.get(i).providerInfo; 9345 if (destPi.name == filterPi.name 9346 && destPi.packageName == filterPi.packageName) { 9347 return false; 9348 } 9349 } 9350 return true; 9351 } 9352 9353 @Override 9354 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9355 return new PackageParser.ProviderIntentInfo[size]; 9356 } 9357 9358 @Override 9359 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9360 if (!sUserManager.exists(userId)) 9361 return true; 9362 PackageParser.Package p = filter.provider.owner; 9363 if (p != null) { 9364 PackageSetting ps = (PackageSetting) p.mExtras; 9365 if (ps != null) { 9366 // System apps are never considered stopped for purposes of 9367 // filtering, because there may be no way for the user to 9368 // actually re-launch them. 9369 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9370 && ps.getStopped(userId); 9371 } 9372 } 9373 return false; 9374 } 9375 9376 @Override 9377 protected boolean isPackageForFilter(String packageName, 9378 PackageParser.ProviderIntentInfo info) { 9379 return packageName.equals(info.provider.owner.packageName); 9380 } 9381 9382 @Override 9383 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9384 int match, int userId) { 9385 if (!sUserManager.exists(userId)) 9386 return null; 9387 final PackageParser.ProviderIntentInfo info = filter; 9388 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9389 return null; 9390 } 9391 final PackageParser.Provider provider = info.provider; 9392 if (mSafeMode && (provider.info.applicationInfo.flags 9393 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9394 return null; 9395 } 9396 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9397 if (ps == null) { 9398 return null; 9399 } 9400 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9401 ps.readUserState(userId), userId); 9402 if (pi == null) { 9403 return null; 9404 } 9405 final ResolveInfo res = new ResolveInfo(); 9406 res.providerInfo = pi; 9407 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9408 res.filter = filter; 9409 } 9410 res.priority = info.getPriority(); 9411 res.preferredOrder = provider.owner.mPreferredOrder; 9412 res.match = match; 9413 res.isDefault = info.hasDefault; 9414 res.labelRes = info.labelRes; 9415 res.nonLocalizedLabel = info.nonLocalizedLabel; 9416 res.icon = info.icon; 9417 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9418 return res; 9419 } 9420 9421 @Override 9422 protected void sortResults(List<ResolveInfo> results) { 9423 Collections.sort(results, mResolvePrioritySorter); 9424 } 9425 9426 @Override 9427 protected void dumpFilter(PrintWriter out, String prefix, 9428 PackageParser.ProviderIntentInfo filter) { 9429 out.print(prefix); 9430 out.print( 9431 Integer.toHexString(System.identityHashCode(filter.provider))); 9432 out.print(' '); 9433 filter.provider.printComponentShortName(out); 9434 out.print(" filter "); 9435 out.println(Integer.toHexString(System.identityHashCode(filter))); 9436 } 9437 9438 @Override 9439 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9440 return filter.provider; 9441 } 9442 9443 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9444 PackageParser.Provider provider = (PackageParser.Provider)label; 9445 out.print(prefix); out.print( 9446 Integer.toHexString(System.identityHashCode(provider))); 9447 out.print(' '); 9448 provider.printComponentShortName(out); 9449 if (count > 1) { 9450 out.print(" ("); out.print(count); out.print(" filters)"); 9451 } 9452 out.println(); 9453 } 9454 9455 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9456 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9457 private int mFlags; 9458 }; 9459 9460 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9461 new Comparator<ResolveInfo>() { 9462 public int compare(ResolveInfo r1, ResolveInfo r2) { 9463 int v1 = r1.priority; 9464 int v2 = r2.priority; 9465 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9466 if (v1 != v2) { 9467 return (v1 > v2) ? -1 : 1; 9468 } 9469 v1 = r1.preferredOrder; 9470 v2 = r2.preferredOrder; 9471 if (v1 != v2) { 9472 return (v1 > v2) ? -1 : 1; 9473 } 9474 if (r1.isDefault != r2.isDefault) { 9475 return r1.isDefault ? -1 : 1; 9476 } 9477 v1 = r1.match; 9478 v2 = r2.match; 9479 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9480 if (v1 != v2) { 9481 return (v1 > v2) ? -1 : 1; 9482 } 9483 if (r1.system != r2.system) { 9484 return r1.system ? -1 : 1; 9485 } 9486 return 0; 9487 } 9488 }; 9489 9490 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9491 new Comparator<ProviderInfo>() { 9492 public int compare(ProviderInfo p1, ProviderInfo p2) { 9493 final int v1 = p1.initOrder; 9494 final int v2 = p2.initOrder; 9495 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9496 } 9497 }; 9498 9499 final void sendPackageBroadcast(final String action, final String pkg, 9500 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9501 final int[] userIds) { 9502 mHandler.post(new Runnable() { 9503 @Override 9504 public void run() { 9505 try { 9506 final IActivityManager am = ActivityManagerNative.getDefault(); 9507 if (am == null) return; 9508 final int[] resolvedUserIds; 9509 if (userIds == null) { 9510 resolvedUserIds = am.getRunningUserIds(); 9511 } else { 9512 resolvedUserIds = userIds; 9513 } 9514 for (int id : resolvedUserIds) { 9515 final Intent intent = new Intent(action, 9516 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9517 if (extras != null) { 9518 intent.putExtras(extras); 9519 } 9520 if (targetPkg != null) { 9521 intent.setPackage(targetPkg); 9522 } 9523 // Modify the UID when posting to other users 9524 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9525 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9526 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9527 intent.putExtra(Intent.EXTRA_UID, uid); 9528 } 9529 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9530 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9531 if (DEBUG_BROADCASTS) { 9532 RuntimeException here = new RuntimeException("here"); 9533 here.fillInStackTrace(); 9534 Slog.d(TAG, "Sending to user " + id + ": " 9535 + intent.toShortString(false, true, false, false) 9536 + " " + intent.getExtras(), here); 9537 } 9538 am.broadcastIntent(null, intent, null, finishedReceiver, 9539 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9540 null, finishedReceiver != null, false, id); 9541 } 9542 } catch (RemoteException ex) { 9543 } 9544 } 9545 }); 9546 } 9547 9548 /** 9549 * Check if the external storage media is available. This is true if there 9550 * is a mounted external storage medium or if the external storage is 9551 * emulated. 9552 */ 9553 private boolean isExternalMediaAvailable() { 9554 return mMediaMounted || Environment.isExternalStorageEmulated(); 9555 } 9556 9557 @Override 9558 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9559 // writer 9560 synchronized (mPackages) { 9561 if (!isExternalMediaAvailable()) { 9562 // If the external storage is no longer mounted at this point, 9563 // the caller may not have been able to delete all of this 9564 // packages files and can not delete any more. Bail. 9565 return null; 9566 } 9567 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9568 if (lastPackage != null) { 9569 pkgs.remove(lastPackage); 9570 } 9571 if (pkgs.size() > 0) { 9572 return pkgs.get(0); 9573 } 9574 } 9575 return null; 9576 } 9577 9578 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9579 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9580 userId, andCode ? 1 : 0, packageName); 9581 if (mSystemReady) { 9582 msg.sendToTarget(); 9583 } else { 9584 if (mPostSystemReadyMessages == null) { 9585 mPostSystemReadyMessages = new ArrayList<>(); 9586 } 9587 mPostSystemReadyMessages.add(msg); 9588 } 9589 } 9590 9591 void startCleaningPackages() { 9592 // reader 9593 synchronized (mPackages) { 9594 if (!isExternalMediaAvailable()) { 9595 return; 9596 } 9597 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9598 return; 9599 } 9600 } 9601 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9602 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9603 IActivityManager am = ActivityManagerNative.getDefault(); 9604 if (am != null) { 9605 try { 9606 am.startService(null, intent, null, mContext.getOpPackageName(), 9607 UserHandle.USER_SYSTEM); 9608 } catch (RemoteException e) { 9609 } 9610 } 9611 } 9612 9613 @Override 9614 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9615 int installFlags, String installerPackageName, VerificationParams verificationParams, 9616 String packageAbiOverride) { 9617 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9618 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9619 } 9620 9621 @Override 9622 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9623 int installFlags, String installerPackageName, VerificationParams verificationParams, 9624 String packageAbiOverride, int userId) { 9625 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9626 9627 final int callingUid = Binder.getCallingUid(); 9628 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9629 9630 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9631 try { 9632 if (observer != null) { 9633 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9634 } 9635 } catch (RemoteException re) { 9636 } 9637 return; 9638 } 9639 9640 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9641 installFlags |= PackageManager.INSTALL_FROM_ADB; 9642 9643 } else { 9644 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9645 // about installerPackageName. 9646 9647 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9648 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9649 } 9650 9651 UserHandle user; 9652 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9653 user = UserHandle.ALL; 9654 } else { 9655 user = new UserHandle(userId); 9656 } 9657 9658 // Only system components can circumvent runtime permissions when installing. 9659 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9660 && mContext.checkCallingOrSelfPermission(Manifest.permission 9661 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9662 throw new SecurityException("You need the " 9663 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9664 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9665 } 9666 9667 verificationParams.setInstallerUid(callingUid); 9668 9669 final File originFile = new File(originPath); 9670 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9671 9672 final Message msg = mHandler.obtainMessage(INIT_COPY); 9673 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9674 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9675 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9676 msg.obj = params; 9677 9678 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9679 System.identityHashCode(msg.obj)); 9680 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9681 System.identityHashCode(msg.obj)); 9682 9683 mHandler.sendMessage(msg); 9684 } 9685 9686 void installStage(String packageName, File stagedDir, String stagedCid, 9687 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9688 String installerPackageName, int installerUid, UserHandle user) { 9689 final VerificationParams verifParams = new VerificationParams( 9690 null, sessionParams.originatingUri, sessionParams.referrerUri, 9691 sessionParams.originatingUid, null); 9692 verifParams.setInstallerUid(installerUid); 9693 9694 final OriginInfo origin; 9695 if (stagedDir != null) { 9696 origin = OriginInfo.fromStagedFile(stagedDir); 9697 } else { 9698 origin = OriginInfo.fromStagedContainer(stagedCid); 9699 } 9700 9701 final Message msg = mHandler.obtainMessage(INIT_COPY); 9702 final InstallParams params = new InstallParams(origin, null, observer, 9703 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9704 verifParams, user, sessionParams.abiOverride, 9705 sessionParams.grantedRuntimePermissions); 9706 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9707 msg.obj = params; 9708 9709 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9710 System.identityHashCode(msg.obj)); 9711 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9712 System.identityHashCode(msg.obj)); 9713 9714 mHandler.sendMessage(msg); 9715 } 9716 9717 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9718 Bundle extras = new Bundle(1); 9719 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9720 9721 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9722 packageName, extras, null, null, new int[] {userId}); 9723 try { 9724 IActivityManager am = ActivityManagerNative.getDefault(); 9725 final boolean isSystem = 9726 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9727 if (isSystem && am.isUserRunning(userId, false)) { 9728 // The just-installed/enabled app is bundled on the system, so presumed 9729 // to be able to run automatically without needing an explicit launch. 9730 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9731 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9732 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9733 .setPackage(packageName); 9734 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9735 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9736 } 9737 } catch (RemoteException e) { 9738 // shouldn't happen 9739 Slog.w(TAG, "Unable to bootstrap installed package", e); 9740 } 9741 } 9742 9743 @Override 9744 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9745 int userId) { 9746 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9747 PackageSetting pkgSetting; 9748 final int uid = Binder.getCallingUid(); 9749 enforceCrossUserPermission(uid, userId, true, true, 9750 "setApplicationHiddenSetting for user " + userId); 9751 9752 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9753 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9754 return false; 9755 } 9756 9757 long callingId = Binder.clearCallingIdentity(); 9758 try { 9759 boolean sendAdded = false; 9760 boolean sendRemoved = false; 9761 // writer 9762 synchronized (mPackages) { 9763 pkgSetting = mSettings.mPackages.get(packageName); 9764 if (pkgSetting == null) { 9765 return false; 9766 } 9767 if (pkgSetting.getHidden(userId) != hidden) { 9768 pkgSetting.setHidden(hidden, userId); 9769 mSettings.writePackageRestrictionsLPr(userId); 9770 if (hidden) { 9771 sendRemoved = true; 9772 } else { 9773 sendAdded = true; 9774 } 9775 } 9776 } 9777 if (sendAdded) { 9778 sendPackageAddedForUser(packageName, pkgSetting, userId); 9779 return true; 9780 } 9781 if (sendRemoved) { 9782 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9783 "hiding pkg"); 9784 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9785 return true; 9786 } 9787 } finally { 9788 Binder.restoreCallingIdentity(callingId); 9789 } 9790 return false; 9791 } 9792 9793 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9794 int userId) { 9795 final PackageRemovedInfo info = new PackageRemovedInfo(); 9796 info.removedPackage = packageName; 9797 info.removedUsers = new int[] {userId}; 9798 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9799 info.sendBroadcast(false, false, false); 9800 } 9801 9802 /** 9803 * Returns true if application is not found or there was an error. Otherwise it returns 9804 * the hidden state of the package for the given user. 9805 */ 9806 @Override 9807 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9808 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9809 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9810 false, "getApplicationHidden for user " + userId); 9811 PackageSetting pkgSetting; 9812 long callingId = Binder.clearCallingIdentity(); 9813 try { 9814 // writer 9815 synchronized (mPackages) { 9816 pkgSetting = mSettings.mPackages.get(packageName); 9817 if (pkgSetting == null) { 9818 return true; 9819 } 9820 return pkgSetting.getHidden(userId); 9821 } 9822 } finally { 9823 Binder.restoreCallingIdentity(callingId); 9824 } 9825 } 9826 9827 /** 9828 * @hide 9829 */ 9830 @Override 9831 public int installExistingPackageAsUser(String packageName, int userId) { 9832 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9833 null); 9834 PackageSetting pkgSetting; 9835 final int uid = Binder.getCallingUid(); 9836 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9837 + userId); 9838 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9839 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9840 } 9841 9842 long callingId = Binder.clearCallingIdentity(); 9843 try { 9844 boolean sendAdded = false; 9845 9846 // writer 9847 synchronized (mPackages) { 9848 pkgSetting = mSettings.mPackages.get(packageName); 9849 if (pkgSetting == null) { 9850 return PackageManager.INSTALL_FAILED_INVALID_URI; 9851 } 9852 if (!pkgSetting.getInstalled(userId)) { 9853 pkgSetting.setInstalled(true, userId); 9854 pkgSetting.setHidden(false, userId); 9855 mSettings.writePackageRestrictionsLPr(userId); 9856 sendAdded = true; 9857 } 9858 } 9859 9860 if (sendAdded) { 9861 sendPackageAddedForUser(packageName, pkgSetting, userId); 9862 } 9863 } finally { 9864 Binder.restoreCallingIdentity(callingId); 9865 } 9866 9867 return PackageManager.INSTALL_SUCCEEDED; 9868 } 9869 9870 boolean isUserRestricted(int userId, String restrictionKey) { 9871 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9872 if (restrictions.getBoolean(restrictionKey, false)) { 9873 Log.w(TAG, "User is restricted: " + restrictionKey); 9874 return true; 9875 } 9876 return false; 9877 } 9878 9879 @Override 9880 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9881 mContext.enforceCallingOrSelfPermission( 9882 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9883 "Only package verification agents can verify applications"); 9884 9885 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9886 final PackageVerificationResponse response = new PackageVerificationResponse( 9887 verificationCode, Binder.getCallingUid()); 9888 msg.arg1 = id; 9889 msg.obj = response; 9890 mHandler.sendMessage(msg); 9891 } 9892 9893 @Override 9894 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9895 long millisecondsToDelay) { 9896 mContext.enforceCallingOrSelfPermission( 9897 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9898 "Only package verification agents can extend verification timeouts"); 9899 9900 final PackageVerificationState state = mPendingVerification.get(id); 9901 final PackageVerificationResponse response = new PackageVerificationResponse( 9902 verificationCodeAtTimeout, Binder.getCallingUid()); 9903 9904 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9905 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9906 } 9907 if (millisecondsToDelay < 0) { 9908 millisecondsToDelay = 0; 9909 } 9910 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9911 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9912 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9913 } 9914 9915 if ((state != null) && !state.timeoutExtended()) { 9916 state.extendTimeout(); 9917 9918 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9919 msg.arg1 = id; 9920 msg.obj = response; 9921 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9922 } 9923 } 9924 9925 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9926 int verificationCode, UserHandle user) { 9927 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9928 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9929 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9930 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9931 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9932 9933 mContext.sendBroadcastAsUser(intent, user, 9934 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9935 } 9936 9937 private ComponentName matchComponentForVerifier(String packageName, 9938 List<ResolveInfo> receivers) { 9939 ActivityInfo targetReceiver = null; 9940 9941 final int NR = receivers.size(); 9942 for (int i = 0; i < NR; i++) { 9943 final ResolveInfo info = receivers.get(i); 9944 if (info.activityInfo == null) { 9945 continue; 9946 } 9947 9948 if (packageName.equals(info.activityInfo.packageName)) { 9949 targetReceiver = info.activityInfo; 9950 break; 9951 } 9952 } 9953 9954 if (targetReceiver == null) { 9955 return null; 9956 } 9957 9958 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9959 } 9960 9961 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9962 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9963 if (pkgInfo.verifiers.length == 0) { 9964 return null; 9965 } 9966 9967 final int N = pkgInfo.verifiers.length; 9968 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9969 for (int i = 0; i < N; i++) { 9970 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9971 9972 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9973 receivers); 9974 if (comp == null) { 9975 continue; 9976 } 9977 9978 final int verifierUid = getUidForVerifier(verifierInfo); 9979 if (verifierUid == -1) { 9980 continue; 9981 } 9982 9983 if (DEBUG_VERIFY) { 9984 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9985 + " with the correct signature"); 9986 } 9987 sufficientVerifiers.add(comp); 9988 verificationState.addSufficientVerifier(verifierUid); 9989 } 9990 9991 return sufficientVerifiers; 9992 } 9993 9994 private int getUidForVerifier(VerifierInfo verifierInfo) { 9995 synchronized (mPackages) { 9996 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9997 if (pkg == null) { 9998 return -1; 9999 } else if (pkg.mSignatures.length != 1) { 10000 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10001 + " has more than one signature; ignoring"); 10002 return -1; 10003 } 10004 10005 /* 10006 * If the public key of the package's signature does not match 10007 * our expected public key, then this is a different package and 10008 * we should skip. 10009 */ 10010 10011 final byte[] expectedPublicKey; 10012 try { 10013 final Signature verifierSig = pkg.mSignatures[0]; 10014 final PublicKey publicKey = verifierSig.getPublicKey(); 10015 expectedPublicKey = publicKey.getEncoded(); 10016 } catch (CertificateException e) { 10017 return -1; 10018 } 10019 10020 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10021 10022 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10023 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10024 + " does not have the expected public key; ignoring"); 10025 return -1; 10026 } 10027 10028 return pkg.applicationInfo.uid; 10029 } 10030 } 10031 10032 @Override 10033 public void finishPackageInstall(int token) { 10034 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10035 10036 if (DEBUG_INSTALL) { 10037 Slog.v(TAG, "BM finishing package install for " + token); 10038 } 10039 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10040 10041 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10042 mHandler.sendMessage(msg); 10043 } 10044 10045 /** 10046 * Get the verification agent timeout. 10047 * 10048 * @return verification timeout in milliseconds 10049 */ 10050 private long getVerificationTimeout() { 10051 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10052 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10053 DEFAULT_VERIFICATION_TIMEOUT); 10054 } 10055 10056 /** 10057 * Get the default verification agent response code. 10058 * 10059 * @return default verification response code 10060 */ 10061 private int getDefaultVerificationResponse() { 10062 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10063 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10064 DEFAULT_VERIFICATION_RESPONSE); 10065 } 10066 10067 /** 10068 * Check whether or not package verification has been enabled. 10069 * 10070 * @return true if verification should be performed 10071 */ 10072 private boolean isVerificationEnabled(int userId, int installFlags) { 10073 if (!DEFAULT_VERIFY_ENABLE) { 10074 return false; 10075 } 10076 // TODO: fix b/25118622; don't bypass verification 10077 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10078 return false; 10079 } 10080 10081 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10082 10083 // Check if installing from ADB 10084 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10085 // Do not run verification in a test harness environment 10086 if (ActivityManager.isRunningInTestHarness()) { 10087 return false; 10088 } 10089 if (ensureVerifyAppsEnabled) { 10090 return true; 10091 } 10092 // Check if the developer does not want package verification for ADB installs 10093 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10094 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10095 return false; 10096 } 10097 } 10098 10099 if (ensureVerifyAppsEnabled) { 10100 return true; 10101 } 10102 10103 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10104 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10105 } 10106 10107 @Override 10108 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10109 throws RemoteException { 10110 mContext.enforceCallingOrSelfPermission( 10111 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10112 "Only intentfilter verification agents can verify applications"); 10113 10114 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10115 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10116 Binder.getCallingUid(), verificationCode, failedDomains); 10117 msg.arg1 = id; 10118 msg.obj = response; 10119 mHandler.sendMessage(msg); 10120 } 10121 10122 @Override 10123 public int getIntentVerificationStatus(String packageName, int userId) { 10124 synchronized (mPackages) { 10125 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10126 } 10127 } 10128 10129 @Override 10130 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10131 mContext.enforceCallingOrSelfPermission( 10132 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10133 10134 boolean result = false; 10135 synchronized (mPackages) { 10136 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10137 } 10138 if (result) { 10139 scheduleWritePackageRestrictionsLocked(userId); 10140 } 10141 return result; 10142 } 10143 10144 @Override 10145 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10146 synchronized (mPackages) { 10147 return mSettings.getIntentFilterVerificationsLPr(packageName); 10148 } 10149 } 10150 10151 @Override 10152 public List<IntentFilter> getAllIntentFilters(String packageName) { 10153 if (TextUtils.isEmpty(packageName)) { 10154 return Collections.<IntentFilter>emptyList(); 10155 } 10156 synchronized (mPackages) { 10157 PackageParser.Package pkg = mPackages.get(packageName); 10158 if (pkg == null || pkg.activities == null) { 10159 return Collections.<IntentFilter>emptyList(); 10160 } 10161 final int count = pkg.activities.size(); 10162 ArrayList<IntentFilter> result = new ArrayList<>(); 10163 for (int n=0; n<count; n++) { 10164 PackageParser.Activity activity = pkg.activities.get(n); 10165 if (activity.intents != null || activity.intents.size() > 0) { 10166 result.addAll(activity.intents); 10167 } 10168 } 10169 return result; 10170 } 10171 } 10172 10173 @Override 10174 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10175 mContext.enforceCallingOrSelfPermission( 10176 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10177 10178 synchronized (mPackages) { 10179 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10180 if (packageName != null) { 10181 result |= updateIntentVerificationStatus(packageName, 10182 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10183 userId); 10184 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10185 packageName, userId); 10186 } 10187 return result; 10188 } 10189 } 10190 10191 @Override 10192 public String getDefaultBrowserPackageName(int userId) { 10193 synchronized (mPackages) { 10194 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10195 } 10196 } 10197 10198 /** 10199 * Get the "allow unknown sources" setting. 10200 * 10201 * @return the current "allow unknown sources" setting 10202 */ 10203 private int getUnknownSourcesSettings() { 10204 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10205 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10206 -1); 10207 } 10208 10209 @Override 10210 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10211 final int uid = Binder.getCallingUid(); 10212 // writer 10213 synchronized (mPackages) { 10214 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10215 if (targetPackageSetting == null) { 10216 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10217 } 10218 10219 PackageSetting installerPackageSetting; 10220 if (installerPackageName != null) { 10221 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10222 if (installerPackageSetting == null) { 10223 throw new IllegalArgumentException("Unknown installer package: " 10224 + installerPackageName); 10225 } 10226 } else { 10227 installerPackageSetting = null; 10228 } 10229 10230 Signature[] callerSignature; 10231 Object obj = mSettings.getUserIdLPr(uid); 10232 if (obj != null) { 10233 if (obj instanceof SharedUserSetting) { 10234 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10235 } else if (obj instanceof PackageSetting) { 10236 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10237 } else { 10238 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10239 } 10240 } else { 10241 throw new SecurityException("Unknown calling uid " + uid); 10242 } 10243 10244 // Verify: can't set installerPackageName to a package that is 10245 // not signed with the same cert as the caller. 10246 if (installerPackageSetting != null) { 10247 if (compareSignatures(callerSignature, 10248 installerPackageSetting.signatures.mSignatures) 10249 != PackageManager.SIGNATURE_MATCH) { 10250 throw new SecurityException( 10251 "Caller does not have same cert as new installer package " 10252 + installerPackageName); 10253 } 10254 } 10255 10256 // Verify: if target already has an installer package, it must 10257 // be signed with the same cert as the caller. 10258 if (targetPackageSetting.installerPackageName != null) { 10259 PackageSetting setting = mSettings.mPackages.get( 10260 targetPackageSetting.installerPackageName); 10261 // If the currently set package isn't valid, then it's always 10262 // okay to change it. 10263 if (setting != null) { 10264 if (compareSignatures(callerSignature, 10265 setting.signatures.mSignatures) 10266 != PackageManager.SIGNATURE_MATCH) { 10267 throw new SecurityException( 10268 "Caller does not have same cert as old installer package " 10269 + targetPackageSetting.installerPackageName); 10270 } 10271 } 10272 } 10273 10274 // Okay! 10275 targetPackageSetting.installerPackageName = installerPackageName; 10276 scheduleWriteSettingsLocked(); 10277 } 10278 } 10279 10280 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10281 // Queue up an async operation since the package installation may take a little while. 10282 mHandler.post(new Runnable() { 10283 public void run() { 10284 mHandler.removeCallbacks(this); 10285 // Result object to be returned 10286 PackageInstalledInfo res = new PackageInstalledInfo(); 10287 res.returnCode = currentStatus; 10288 res.uid = -1; 10289 res.pkg = null; 10290 res.removedInfo = new PackageRemovedInfo(); 10291 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10292 args.doPreInstall(res.returnCode); 10293 synchronized (mInstallLock) { 10294 installPackageTracedLI(args, res); 10295 } 10296 args.doPostInstall(res.returnCode, res.uid); 10297 } 10298 10299 // A restore should be performed at this point if (a) the install 10300 // succeeded, (b) the operation is not an update, and (c) the new 10301 // package has not opted out of backup participation. 10302 final boolean update = res.removedInfo.removedPackage != null; 10303 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10304 boolean doRestore = !update 10305 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10306 10307 // Set up the post-install work request bookkeeping. This will be used 10308 // and cleaned up by the post-install event handling regardless of whether 10309 // there's a restore pass performed. Token values are >= 1. 10310 int token; 10311 if (mNextInstallToken < 0) mNextInstallToken = 1; 10312 token = mNextInstallToken++; 10313 10314 PostInstallData data = new PostInstallData(args, res); 10315 mRunningInstalls.put(token, data); 10316 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10317 10318 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10319 // Pass responsibility to the Backup Manager. It will perform a 10320 // restore if appropriate, then pass responsibility back to the 10321 // Package Manager to run the post-install observer callbacks 10322 // and broadcasts. 10323 IBackupManager bm = IBackupManager.Stub.asInterface( 10324 ServiceManager.getService(Context.BACKUP_SERVICE)); 10325 if (bm != null) { 10326 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10327 + " to BM for possible restore"); 10328 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10329 try { 10330 // TODO: http://b/22388012 10331 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10332 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10333 } else { 10334 doRestore = false; 10335 } 10336 } catch (RemoteException e) { 10337 // can't happen; the backup manager is local 10338 } catch (Exception e) { 10339 Slog.e(TAG, "Exception trying to enqueue restore", e); 10340 doRestore = false; 10341 } 10342 } else { 10343 Slog.e(TAG, "Backup Manager not found!"); 10344 doRestore = false; 10345 } 10346 } 10347 10348 if (!doRestore) { 10349 // No restore possible, or the Backup Manager was mysteriously not 10350 // available -- just fire the post-install work request directly. 10351 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10352 10353 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10354 10355 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10356 mHandler.sendMessage(msg); 10357 } 10358 } 10359 }); 10360 } 10361 10362 private abstract class HandlerParams { 10363 private static final int MAX_RETRIES = 4; 10364 10365 /** 10366 * Number of times startCopy() has been attempted and had a non-fatal 10367 * error. 10368 */ 10369 private int mRetries = 0; 10370 10371 /** User handle for the user requesting the information or installation. */ 10372 private final UserHandle mUser; 10373 String traceMethod; 10374 int traceCookie; 10375 10376 HandlerParams(UserHandle user) { 10377 mUser = user; 10378 } 10379 10380 UserHandle getUser() { 10381 return mUser; 10382 } 10383 10384 HandlerParams setTraceMethod(String traceMethod) { 10385 this.traceMethod = traceMethod; 10386 return this; 10387 } 10388 10389 HandlerParams setTraceCookie(int traceCookie) { 10390 this.traceCookie = traceCookie; 10391 return this; 10392 } 10393 10394 final boolean startCopy() { 10395 boolean res; 10396 try { 10397 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10398 10399 if (++mRetries > MAX_RETRIES) { 10400 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10401 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10402 handleServiceError(); 10403 return false; 10404 } else { 10405 handleStartCopy(); 10406 res = true; 10407 } 10408 } catch (RemoteException e) { 10409 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10410 mHandler.sendEmptyMessage(MCS_RECONNECT); 10411 res = false; 10412 } 10413 handleReturnCode(); 10414 return res; 10415 } 10416 10417 final void serviceError() { 10418 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10419 handleServiceError(); 10420 handleReturnCode(); 10421 } 10422 10423 abstract void handleStartCopy() throws RemoteException; 10424 abstract void handleServiceError(); 10425 abstract void handleReturnCode(); 10426 } 10427 10428 class MeasureParams extends HandlerParams { 10429 private final PackageStats mStats; 10430 private boolean mSuccess; 10431 10432 private final IPackageStatsObserver mObserver; 10433 10434 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10435 super(new UserHandle(stats.userHandle)); 10436 mObserver = observer; 10437 mStats = stats; 10438 } 10439 10440 @Override 10441 public String toString() { 10442 return "MeasureParams{" 10443 + Integer.toHexString(System.identityHashCode(this)) 10444 + " " + mStats.packageName + "}"; 10445 } 10446 10447 @Override 10448 void handleStartCopy() throws RemoteException { 10449 synchronized (mInstallLock) { 10450 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10451 } 10452 10453 if (mSuccess) { 10454 final boolean mounted; 10455 if (Environment.isExternalStorageEmulated()) { 10456 mounted = true; 10457 } else { 10458 final String status = Environment.getExternalStorageState(); 10459 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10460 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10461 } 10462 10463 if (mounted) { 10464 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10465 10466 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10467 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10468 10469 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10470 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10471 10472 // Always subtract cache size, since it's a subdirectory 10473 mStats.externalDataSize -= mStats.externalCacheSize; 10474 10475 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10476 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10477 10478 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10479 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10480 } 10481 } 10482 } 10483 10484 @Override 10485 void handleReturnCode() { 10486 if (mObserver != null) { 10487 try { 10488 mObserver.onGetStatsCompleted(mStats, mSuccess); 10489 } catch (RemoteException e) { 10490 Slog.i(TAG, "Observer no longer exists."); 10491 } 10492 } 10493 } 10494 10495 @Override 10496 void handleServiceError() { 10497 Slog.e(TAG, "Could not measure application " + mStats.packageName 10498 + " external storage"); 10499 } 10500 } 10501 10502 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10503 throws RemoteException { 10504 long result = 0; 10505 for (File path : paths) { 10506 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10507 } 10508 return result; 10509 } 10510 10511 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10512 for (File path : paths) { 10513 try { 10514 mcs.clearDirectory(path.getAbsolutePath()); 10515 } catch (RemoteException e) { 10516 } 10517 } 10518 } 10519 10520 static class OriginInfo { 10521 /** 10522 * Location where install is coming from, before it has been 10523 * copied/renamed into place. This could be a single monolithic APK 10524 * file, or a cluster directory. This location may be untrusted. 10525 */ 10526 final File file; 10527 final String cid; 10528 10529 /** 10530 * Flag indicating that {@link #file} or {@link #cid} has already been 10531 * staged, meaning downstream users don't need to defensively copy the 10532 * contents. 10533 */ 10534 final boolean staged; 10535 10536 /** 10537 * Flag indicating that {@link #file} or {@link #cid} is an already 10538 * installed app that is being moved. 10539 */ 10540 final boolean existing; 10541 10542 final String resolvedPath; 10543 final File resolvedFile; 10544 10545 static OriginInfo fromNothing() { 10546 return new OriginInfo(null, null, false, false); 10547 } 10548 10549 static OriginInfo fromUntrustedFile(File file) { 10550 return new OriginInfo(file, null, false, false); 10551 } 10552 10553 static OriginInfo fromExistingFile(File file) { 10554 return new OriginInfo(file, null, false, true); 10555 } 10556 10557 static OriginInfo fromStagedFile(File file) { 10558 return new OriginInfo(file, null, true, false); 10559 } 10560 10561 static OriginInfo fromStagedContainer(String cid) { 10562 return new OriginInfo(null, cid, true, false); 10563 } 10564 10565 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10566 this.file = file; 10567 this.cid = cid; 10568 this.staged = staged; 10569 this.existing = existing; 10570 10571 if (cid != null) { 10572 resolvedPath = PackageHelper.getSdDir(cid); 10573 resolvedFile = new File(resolvedPath); 10574 } else if (file != null) { 10575 resolvedPath = file.getAbsolutePath(); 10576 resolvedFile = file; 10577 } else { 10578 resolvedPath = null; 10579 resolvedFile = null; 10580 } 10581 } 10582 } 10583 10584 class MoveInfo { 10585 final int moveId; 10586 final String fromUuid; 10587 final String toUuid; 10588 final String packageName; 10589 final String dataAppName; 10590 final int appId; 10591 final String seinfo; 10592 10593 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10594 String dataAppName, int appId, String seinfo) { 10595 this.moveId = moveId; 10596 this.fromUuid = fromUuid; 10597 this.toUuid = toUuid; 10598 this.packageName = packageName; 10599 this.dataAppName = dataAppName; 10600 this.appId = appId; 10601 this.seinfo = seinfo; 10602 } 10603 } 10604 10605 class InstallParams extends HandlerParams { 10606 final OriginInfo origin; 10607 final MoveInfo move; 10608 final IPackageInstallObserver2 observer; 10609 int installFlags; 10610 final String installerPackageName; 10611 final String volumeUuid; 10612 final VerificationParams verificationParams; 10613 private InstallArgs mArgs; 10614 private int mRet; 10615 final String packageAbiOverride; 10616 final String[] grantedRuntimePermissions; 10617 10618 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10619 int installFlags, String installerPackageName, String volumeUuid, 10620 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10621 String[] grantedPermissions) { 10622 super(user); 10623 this.origin = origin; 10624 this.move = move; 10625 this.observer = observer; 10626 this.installFlags = installFlags; 10627 this.installerPackageName = installerPackageName; 10628 this.volumeUuid = volumeUuid; 10629 this.verificationParams = verificationParams; 10630 this.packageAbiOverride = packageAbiOverride; 10631 this.grantedRuntimePermissions = grantedPermissions; 10632 } 10633 10634 @Override 10635 public String toString() { 10636 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10637 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10638 } 10639 10640 public ManifestDigest getManifestDigest() { 10641 if (verificationParams == null) { 10642 return null; 10643 } 10644 return verificationParams.getManifestDigest(); 10645 } 10646 10647 private int installLocationPolicy(PackageInfoLite pkgLite) { 10648 String packageName = pkgLite.packageName; 10649 int installLocation = pkgLite.installLocation; 10650 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10651 // reader 10652 synchronized (mPackages) { 10653 PackageParser.Package pkg = mPackages.get(packageName); 10654 if (pkg != null) { 10655 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10656 // Check for downgrading. 10657 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10658 try { 10659 checkDowngrade(pkg, pkgLite); 10660 } catch (PackageManagerException e) { 10661 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10662 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10663 } 10664 } 10665 // Check for updated system application. 10666 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10667 if (onSd) { 10668 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10669 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10670 } 10671 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10672 } else { 10673 if (onSd) { 10674 // Install flag overrides everything. 10675 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10676 } 10677 // If current upgrade specifies particular preference 10678 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10679 // Application explicitly specified internal. 10680 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10681 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10682 // App explictly prefers external. Let policy decide 10683 } else { 10684 // Prefer previous location 10685 if (isExternal(pkg)) { 10686 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10687 } 10688 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10689 } 10690 } 10691 } else { 10692 // Invalid install. Return error code 10693 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10694 } 10695 } 10696 } 10697 // All the special cases have been taken care of. 10698 // Return result based on recommended install location. 10699 if (onSd) { 10700 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10701 } 10702 return pkgLite.recommendedInstallLocation; 10703 } 10704 10705 /* 10706 * Invoke remote method to get package information and install 10707 * location values. Override install location based on default 10708 * policy if needed and then create install arguments based 10709 * on the install location. 10710 */ 10711 public void handleStartCopy() throws RemoteException { 10712 int ret = PackageManager.INSTALL_SUCCEEDED; 10713 10714 // If we're already staged, we've firmly committed to an install location 10715 if (origin.staged) { 10716 if (origin.file != null) { 10717 installFlags |= PackageManager.INSTALL_INTERNAL; 10718 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10719 } else if (origin.cid != null) { 10720 installFlags |= PackageManager.INSTALL_EXTERNAL; 10721 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10722 } else { 10723 throw new IllegalStateException("Invalid stage location"); 10724 } 10725 } 10726 10727 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10728 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10729 PackageInfoLite pkgLite = null; 10730 10731 if (onInt && onSd) { 10732 // Check if both bits are set. 10733 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10734 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10735 } else { 10736 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10737 packageAbiOverride); 10738 10739 /* 10740 * If we have too little free space, try to free cache 10741 * before giving up. 10742 */ 10743 if (!origin.staged && pkgLite.recommendedInstallLocation 10744 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10745 // TODO: focus freeing disk space on the target device 10746 final StorageManager storage = StorageManager.from(mContext); 10747 final long lowThreshold = storage.getStorageLowBytes( 10748 Environment.getDataDirectory()); 10749 10750 final long sizeBytes = mContainerService.calculateInstalledSize( 10751 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10752 10753 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10754 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10755 installFlags, packageAbiOverride); 10756 } 10757 10758 /* 10759 * The cache free must have deleted the file we 10760 * downloaded to install. 10761 * 10762 * TODO: fix the "freeCache" call to not delete 10763 * the file we care about. 10764 */ 10765 if (pkgLite.recommendedInstallLocation 10766 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10767 pkgLite.recommendedInstallLocation 10768 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10769 } 10770 } 10771 } 10772 10773 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10774 int loc = pkgLite.recommendedInstallLocation; 10775 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10776 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10777 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10778 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10779 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10780 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10781 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10782 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10783 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10784 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10785 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10786 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10787 } else { 10788 // Override with defaults if needed. 10789 loc = installLocationPolicy(pkgLite); 10790 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10791 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10792 } else if (!onSd && !onInt) { 10793 // Override install location with flags 10794 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10795 // Set the flag to install on external media. 10796 installFlags |= PackageManager.INSTALL_EXTERNAL; 10797 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10798 } else { 10799 // Make sure the flag for installing on external 10800 // media is unset 10801 installFlags |= PackageManager.INSTALL_INTERNAL; 10802 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10803 } 10804 } 10805 } 10806 } 10807 10808 final InstallArgs args = createInstallArgs(this); 10809 mArgs = args; 10810 10811 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10812 // TODO: http://b/22976637 10813 // Apps installed for "all" users use the device owner to verify the app 10814 UserHandle verifierUser = getUser(); 10815 if (verifierUser == UserHandle.ALL) { 10816 verifierUser = UserHandle.SYSTEM; 10817 } 10818 10819 /* 10820 * Determine if we have any installed package verifiers. If we 10821 * do, then we'll defer to them to verify the packages. 10822 */ 10823 final int requiredUid = mRequiredVerifierPackage == null ? -1 10824 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10825 if (!origin.existing && requiredUid != -1 10826 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10827 final Intent verification = new Intent( 10828 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10829 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10830 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10831 PACKAGE_MIME_TYPE); 10832 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10833 10834 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10835 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10836 verifierUser.getIdentifier()); 10837 10838 if (DEBUG_VERIFY) { 10839 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10840 + verification.toString() + " with " + pkgLite.verifiers.length 10841 + " optional verifiers"); 10842 } 10843 10844 final int verificationId = mPendingVerificationToken++; 10845 10846 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10847 10848 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10849 installerPackageName); 10850 10851 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10852 installFlags); 10853 10854 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10855 pkgLite.packageName); 10856 10857 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10858 pkgLite.versionCode); 10859 10860 if (verificationParams != null) { 10861 if (verificationParams.getVerificationURI() != null) { 10862 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10863 verificationParams.getVerificationURI()); 10864 } 10865 if (verificationParams.getOriginatingURI() != null) { 10866 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10867 verificationParams.getOriginatingURI()); 10868 } 10869 if (verificationParams.getReferrer() != null) { 10870 verification.putExtra(Intent.EXTRA_REFERRER, 10871 verificationParams.getReferrer()); 10872 } 10873 if (verificationParams.getOriginatingUid() >= 0) { 10874 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10875 verificationParams.getOriginatingUid()); 10876 } 10877 if (verificationParams.getInstallerUid() >= 0) { 10878 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10879 verificationParams.getInstallerUid()); 10880 } 10881 } 10882 10883 final PackageVerificationState verificationState = new PackageVerificationState( 10884 requiredUid, args); 10885 10886 mPendingVerification.append(verificationId, verificationState); 10887 10888 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10889 receivers, verificationState); 10890 10891 /* 10892 * If any sufficient verifiers were listed in the package 10893 * manifest, attempt to ask them. 10894 */ 10895 if (sufficientVerifiers != null) { 10896 final int N = sufficientVerifiers.size(); 10897 if (N == 0) { 10898 Slog.i(TAG, "Additional verifiers required, but none installed."); 10899 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10900 } else { 10901 for (int i = 0; i < N; i++) { 10902 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10903 10904 final Intent sufficientIntent = new Intent(verification); 10905 sufficientIntent.setComponent(verifierComponent); 10906 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10907 } 10908 } 10909 } 10910 10911 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10912 mRequiredVerifierPackage, receivers); 10913 if (ret == PackageManager.INSTALL_SUCCEEDED 10914 && mRequiredVerifierPackage != null) { 10915 Trace.asyncTraceBegin( 10916 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10917 /* 10918 * Send the intent to the required verification agent, 10919 * but only start the verification timeout after the 10920 * target BroadcastReceivers have run. 10921 */ 10922 verification.setComponent(requiredVerifierComponent); 10923 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10924 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10925 new BroadcastReceiver() { 10926 @Override 10927 public void onReceive(Context context, Intent intent) { 10928 final Message msg = mHandler 10929 .obtainMessage(CHECK_PENDING_VERIFICATION); 10930 msg.arg1 = verificationId; 10931 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10932 } 10933 }, null, 0, null, null); 10934 10935 /* 10936 * We don't want the copy to proceed until verification 10937 * succeeds, so null out this field. 10938 */ 10939 mArgs = null; 10940 } 10941 } else { 10942 /* 10943 * No package verification is enabled, so immediately start 10944 * the remote call to initiate copy using temporary file. 10945 */ 10946 ret = args.copyApk(mContainerService, true); 10947 } 10948 } 10949 10950 mRet = ret; 10951 } 10952 10953 @Override 10954 void handleReturnCode() { 10955 // If mArgs is null, then MCS couldn't be reached. When it 10956 // reconnects, it will try again to install. At that point, this 10957 // will succeed. 10958 if (mArgs != null) { 10959 processPendingInstall(mArgs, mRet); 10960 } 10961 } 10962 10963 @Override 10964 void handleServiceError() { 10965 mArgs = createInstallArgs(this); 10966 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10967 } 10968 10969 public boolean isForwardLocked() { 10970 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10971 } 10972 } 10973 10974 /** 10975 * Used during creation of InstallArgs 10976 * 10977 * @param installFlags package installation flags 10978 * @return true if should be installed on external storage 10979 */ 10980 private static boolean installOnExternalAsec(int installFlags) { 10981 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10982 return false; 10983 } 10984 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10985 return true; 10986 } 10987 return false; 10988 } 10989 10990 /** 10991 * Used during creation of InstallArgs 10992 * 10993 * @param installFlags package installation flags 10994 * @return true if should be installed as forward locked 10995 */ 10996 private static boolean installForwardLocked(int installFlags) { 10997 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10998 } 10999 11000 private InstallArgs createInstallArgs(InstallParams params) { 11001 if (params.move != null) { 11002 return new MoveInstallArgs(params); 11003 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11004 return new AsecInstallArgs(params); 11005 } else { 11006 return new FileInstallArgs(params); 11007 } 11008 } 11009 11010 /** 11011 * Create args that describe an existing installed package. Typically used 11012 * when cleaning up old installs, or used as a move source. 11013 */ 11014 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11015 String resourcePath, String[] instructionSets) { 11016 final boolean isInAsec; 11017 if (installOnExternalAsec(installFlags)) { 11018 /* Apps on SD card are always in ASEC containers. */ 11019 isInAsec = true; 11020 } else if (installForwardLocked(installFlags) 11021 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11022 /* 11023 * Forward-locked apps are only in ASEC containers if they're the 11024 * new style 11025 */ 11026 isInAsec = true; 11027 } else { 11028 isInAsec = false; 11029 } 11030 11031 if (isInAsec) { 11032 return new AsecInstallArgs(codePath, instructionSets, 11033 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11034 } else { 11035 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11036 } 11037 } 11038 11039 static abstract class InstallArgs { 11040 /** @see InstallParams#origin */ 11041 final OriginInfo origin; 11042 /** @see InstallParams#move */ 11043 final MoveInfo move; 11044 11045 final IPackageInstallObserver2 observer; 11046 // Always refers to PackageManager flags only 11047 final int installFlags; 11048 final String installerPackageName; 11049 final String volumeUuid; 11050 final ManifestDigest manifestDigest; 11051 final UserHandle user; 11052 final String abiOverride; 11053 final String[] installGrantPermissions; 11054 /** If non-null, drop an async trace when the install completes */ 11055 final String traceMethod; 11056 final int traceCookie; 11057 11058 // The list of instruction sets supported by this app. This is currently 11059 // only used during the rmdex() phase to clean up resources. We can get rid of this 11060 // if we move dex files under the common app path. 11061 /* nullable */ String[] instructionSets; 11062 11063 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11064 int installFlags, String installerPackageName, String volumeUuid, 11065 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11066 String abiOverride, String[] installGrantPermissions, 11067 String traceMethod, int traceCookie) { 11068 this.origin = origin; 11069 this.move = move; 11070 this.installFlags = installFlags; 11071 this.observer = observer; 11072 this.installerPackageName = installerPackageName; 11073 this.volumeUuid = volumeUuid; 11074 this.manifestDigest = manifestDigest; 11075 this.user = user; 11076 this.instructionSets = instructionSets; 11077 this.abiOverride = abiOverride; 11078 this.installGrantPermissions = installGrantPermissions; 11079 this.traceMethod = traceMethod; 11080 this.traceCookie = traceCookie; 11081 } 11082 11083 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11084 abstract int doPreInstall(int status); 11085 11086 /** 11087 * Rename package into final resting place. All paths on the given 11088 * scanned package should be updated to reflect the rename. 11089 */ 11090 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11091 abstract int doPostInstall(int status, int uid); 11092 11093 /** @see PackageSettingBase#codePathString */ 11094 abstract String getCodePath(); 11095 /** @see PackageSettingBase#resourcePathString */ 11096 abstract String getResourcePath(); 11097 11098 // Need installer lock especially for dex file removal. 11099 abstract void cleanUpResourcesLI(); 11100 abstract boolean doPostDeleteLI(boolean delete); 11101 11102 /** 11103 * Called before the source arguments are copied. This is used mostly 11104 * for MoveParams when it needs to read the source file to put it in the 11105 * destination. 11106 */ 11107 int doPreCopy() { 11108 return PackageManager.INSTALL_SUCCEEDED; 11109 } 11110 11111 /** 11112 * Called after the source arguments are copied. This is used mostly for 11113 * MoveParams when it needs to read the source file to put it in the 11114 * destination. 11115 * 11116 * @return 11117 */ 11118 int doPostCopy(int uid) { 11119 return PackageManager.INSTALL_SUCCEEDED; 11120 } 11121 11122 protected boolean isFwdLocked() { 11123 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11124 } 11125 11126 protected boolean isExternalAsec() { 11127 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11128 } 11129 11130 UserHandle getUser() { 11131 return user; 11132 } 11133 } 11134 11135 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11136 if (!allCodePaths.isEmpty()) { 11137 if (instructionSets == null) { 11138 throw new IllegalStateException("instructionSet == null"); 11139 } 11140 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11141 for (String codePath : allCodePaths) { 11142 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11143 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11144 if (retCode < 0) { 11145 Slog.w(TAG, "Couldn't remove dex file for package: " 11146 + " at location " + codePath + ", retcode=" + retCode); 11147 // we don't consider this to be a failure of the core package deletion 11148 } 11149 } 11150 } 11151 } 11152 } 11153 11154 /** 11155 * Logic to handle installation of non-ASEC applications, including copying 11156 * and renaming logic. 11157 */ 11158 class FileInstallArgs extends InstallArgs { 11159 private File codeFile; 11160 private File resourceFile; 11161 11162 // Example topology: 11163 // /data/app/com.example/base.apk 11164 // /data/app/com.example/split_foo.apk 11165 // /data/app/com.example/lib/arm/libfoo.so 11166 // /data/app/com.example/lib/arm64/libfoo.so 11167 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11168 11169 /** New install */ 11170 FileInstallArgs(InstallParams params) { 11171 super(params.origin, params.move, params.observer, params.installFlags, 11172 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11173 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11174 params.grantedRuntimePermissions, 11175 params.traceMethod, params.traceCookie); 11176 if (isFwdLocked()) { 11177 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11178 } 11179 } 11180 11181 /** Existing install */ 11182 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11183 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11184 null, null, null, 0); 11185 this.codeFile = (codePath != null) ? new File(codePath) : null; 11186 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11187 } 11188 11189 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11190 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11191 try { 11192 return doCopyApk(imcs, temp); 11193 } finally { 11194 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11195 } 11196 } 11197 11198 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11199 if (origin.staged) { 11200 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11201 codeFile = origin.file; 11202 resourceFile = origin.file; 11203 return PackageManager.INSTALL_SUCCEEDED; 11204 } 11205 11206 try { 11207 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11208 codeFile = tempDir; 11209 resourceFile = tempDir; 11210 } catch (IOException e) { 11211 Slog.w(TAG, "Failed to create copy file: " + e); 11212 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11213 } 11214 11215 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11216 @Override 11217 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11218 if (!FileUtils.isValidExtFilename(name)) { 11219 throw new IllegalArgumentException("Invalid filename: " + name); 11220 } 11221 try { 11222 final File file = new File(codeFile, name); 11223 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11224 O_RDWR | O_CREAT, 0644); 11225 Os.chmod(file.getAbsolutePath(), 0644); 11226 return new ParcelFileDescriptor(fd); 11227 } catch (ErrnoException e) { 11228 throw new RemoteException("Failed to open: " + e.getMessage()); 11229 } 11230 } 11231 }; 11232 11233 int ret = PackageManager.INSTALL_SUCCEEDED; 11234 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11235 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11236 Slog.e(TAG, "Failed to copy package"); 11237 return ret; 11238 } 11239 11240 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11241 NativeLibraryHelper.Handle handle = null; 11242 try { 11243 handle = NativeLibraryHelper.Handle.create(codeFile); 11244 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11245 abiOverride); 11246 } catch (IOException e) { 11247 Slog.e(TAG, "Copying native libraries failed", e); 11248 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11249 } finally { 11250 IoUtils.closeQuietly(handle); 11251 } 11252 11253 return ret; 11254 } 11255 11256 int doPreInstall(int status) { 11257 if (status != PackageManager.INSTALL_SUCCEEDED) { 11258 cleanUp(); 11259 } 11260 return status; 11261 } 11262 11263 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11264 if (status != PackageManager.INSTALL_SUCCEEDED) { 11265 cleanUp(); 11266 return false; 11267 } 11268 11269 final File targetDir = codeFile.getParentFile(); 11270 final File beforeCodeFile = codeFile; 11271 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11272 11273 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11274 try { 11275 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11276 } catch (ErrnoException e) { 11277 Slog.w(TAG, "Failed to rename", e); 11278 return false; 11279 } 11280 11281 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11282 Slog.w(TAG, "Failed to restorecon"); 11283 return false; 11284 } 11285 11286 // Reflect the rename internally 11287 codeFile = afterCodeFile; 11288 resourceFile = afterCodeFile; 11289 11290 // Reflect the rename in scanned details 11291 pkg.codePath = afterCodeFile.getAbsolutePath(); 11292 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11293 pkg.baseCodePath); 11294 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11295 pkg.splitCodePaths); 11296 11297 // Reflect the rename in app info 11298 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11299 pkg.applicationInfo.setCodePath(pkg.codePath); 11300 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11301 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11302 pkg.applicationInfo.setResourcePath(pkg.codePath); 11303 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11304 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11305 11306 return true; 11307 } 11308 11309 int doPostInstall(int status, int uid) { 11310 if (status != PackageManager.INSTALL_SUCCEEDED) { 11311 cleanUp(); 11312 } 11313 return status; 11314 } 11315 11316 @Override 11317 String getCodePath() { 11318 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11319 } 11320 11321 @Override 11322 String getResourcePath() { 11323 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11324 } 11325 11326 private boolean cleanUp() { 11327 if (codeFile == null || !codeFile.exists()) { 11328 return false; 11329 } 11330 11331 if (codeFile.isDirectory()) { 11332 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11333 } else { 11334 codeFile.delete(); 11335 } 11336 11337 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11338 resourceFile.delete(); 11339 } 11340 11341 return true; 11342 } 11343 11344 void cleanUpResourcesLI() { 11345 // Try enumerating all code paths before deleting 11346 List<String> allCodePaths = Collections.EMPTY_LIST; 11347 if (codeFile != null && codeFile.exists()) { 11348 try { 11349 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11350 allCodePaths = pkg.getAllCodePaths(); 11351 } catch (PackageParserException e) { 11352 // Ignored; we tried our best 11353 } 11354 } 11355 11356 cleanUp(); 11357 removeDexFiles(allCodePaths, instructionSets); 11358 } 11359 11360 boolean doPostDeleteLI(boolean delete) { 11361 // XXX err, shouldn't we respect the delete flag? 11362 cleanUpResourcesLI(); 11363 return true; 11364 } 11365 } 11366 11367 private boolean isAsecExternal(String cid) { 11368 final String asecPath = PackageHelper.getSdFilesystem(cid); 11369 return !asecPath.startsWith(mAsecInternalPath); 11370 } 11371 11372 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11373 PackageManagerException { 11374 if (copyRet < 0) { 11375 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11376 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11377 throw new PackageManagerException(copyRet, message); 11378 } 11379 } 11380 } 11381 11382 /** 11383 * Extract the MountService "container ID" from the full code path of an 11384 * .apk. 11385 */ 11386 static String cidFromCodePath(String fullCodePath) { 11387 int eidx = fullCodePath.lastIndexOf("/"); 11388 String subStr1 = fullCodePath.substring(0, eidx); 11389 int sidx = subStr1.lastIndexOf("/"); 11390 return subStr1.substring(sidx+1, eidx); 11391 } 11392 11393 /** 11394 * Logic to handle installation of ASEC applications, including copying and 11395 * renaming logic. 11396 */ 11397 class AsecInstallArgs extends InstallArgs { 11398 static final String RES_FILE_NAME = "pkg.apk"; 11399 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11400 11401 String cid; 11402 String packagePath; 11403 String resourcePath; 11404 11405 /** New install */ 11406 AsecInstallArgs(InstallParams params) { 11407 super(params.origin, params.move, params.observer, params.installFlags, 11408 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11409 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11410 params.grantedRuntimePermissions, 11411 params.traceMethod, params.traceCookie); 11412 } 11413 11414 /** Existing install */ 11415 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11416 boolean isExternal, boolean isForwardLocked) { 11417 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11418 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11419 instructionSets, null, null, null, 0); 11420 // Hackily pretend we're still looking at a full code path 11421 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11422 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11423 } 11424 11425 // Extract cid from fullCodePath 11426 int eidx = fullCodePath.lastIndexOf("/"); 11427 String subStr1 = fullCodePath.substring(0, eidx); 11428 int sidx = subStr1.lastIndexOf("/"); 11429 cid = subStr1.substring(sidx+1, eidx); 11430 setMountPath(subStr1); 11431 } 11432 11433 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11434 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11435 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11436 instructionSets, null, null, null, 0); 11437 this.cid = cid; 11438 setMountPath(PackageHelper.getSdDir(cid)); 11439 } 11440 11441 void createCopyFile() { 11442 cid = mInstallerService.allocateExternalStageCidLegacy(); 11443 } 11444 11445 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11446 if (origin.staged) { 11447 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11448 cid = origin.cid; 11449 setMountPath(PackageHelper.getSdDir(cid)); 11450 return PackageManager.INSTALL_SUCCEEDED; 11451 } 11452 11453 if (temp) { 11454 createCopyFile(); 11455 } else { 11456 /* 11457 * Pre-emptively destroy the container since it's destroyed if 11458 * copying fails due to it existing anyway. 11459 */ 11460 PackageHelper.destroySdDir(cid); 11461 } 11462 11463 final String newMountPath = imcs.copyPackageToContainer( 11464 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11465 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11466 11467 if (newMountPath != null) { 11468 setMountPath(newMountPath); 11469 return PackageManager.INSTALL_SUCCEEDED; 11470 } else { 11471 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11472 } 11473 } 11474 11475 @Override 11476 String getCodePath() { 11477 return packagePath; 11478 } 11479 11480 @Override 11481 String getResourcePath() { 11482 return resourcePath; 11483 } 11484 11485 int doPreInstall(int status) { 11486 if (status != PackageManager.INSTALL_SUCCEEDED) { 11487 // Destroy container 11488 PackageHelper.destroySdDir(cid); 11489 } else { 11490 boolean mounted = PackageHelper.isContainerMounted(cid); 11491 if (!mounted) { 11492 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11493 Process.SYSTEM_UID); 11494 if (newMountPath != null) { 11495 setMountPath(newMountPath); 11496 } else { 11497 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11498 } 11499 } 11500 } 11501 return status; 11502 } 11503 11504 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11505 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11506 String newMountPath = null; 11507 if (PackageHelper.isContainerMounted(cid)) { 11508 // Unmount the container 11509 if (!PackageHelper.unMountSdDir(cid)) { 11510 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11511 return false; 11512 } 11513 } 11514 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11515 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11516 " which might be stale. Will try to clean up."); 11517 // Clean up the stale container and proceed to recreate. 11518 if (!PackageHelper.destroySdDir(newCacheId)) { 11519 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11520 return false; 11521 } 11522 // Successfully cleaned up stale container. Try to rename again. 11523 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11524 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11525 + " inspite of cleaning it up."); 11526 return false; 11527 } 11528 } 11529 if (!PackageHelper.isContainerMounted(newCacheId)) { 11530 Slog.w(TAG, "Mounting container " + newCacheId); 11531 newMountPath = PackageHelper.mountSdDir(newCacheId, 11532 getEncryptKey(), Process.SYSTEM_UID); 11533 } else { 11534 newMountPath = PackageHelper.getSdDir(newCacheId); 11535 } 11536 if (newMountPath == null) { 11537 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11538 return false; 11539 } 11540 Log.i(TAG, "Succesfully renamed " + cid + 11541 " to " + newCacheId + 11542 " at new path: " + newMountPath); 11543 cid = newCacheId; 11544 11545 final File beforeCodeFile = new File(packagePath); 11546 setMountPath(newMountPath); 11547 final File afterCodeFile = new File(packagePath); 11548 11549 // Reflect the rename in scanned details 11550 pkg.codePath = afterCodeFile.getAbsolutePath(); 11551 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11552 pkg.baseCodePath); 11553 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11554 pkg.splitCodePaths); 11555 11556 // Reflect the rename in app info 11557 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11558 pkg.applicationInfo.setCodePath(pkg.codePath); 11559 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11560 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11561 pkg.applicationInfo.setResourcePath(pkg.codePath); 11562 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11563 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11564 11565 return true; 11566 } 11567 11568 private void setMountPath(String mountPath) { 11569 final File mountFile = new File(mountPath); 11570 11571 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11572 if (monolithicFile.exists()) { 11573 packagePath = monolithicFile.getAbsolutePath(); 11574 if (isFwdLocked()) { 11575 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11576 } else { 11577 resourcePath = packagePath; 11578 } 11579 } else { 11580 packagePath = mountFile.getAbsolutePath(); 11581 resourcePath = packagePath; 11582 } 11583 } 11584 11585 int doPostInstall(int status, int uid) { 11586 if (status != PackageManager.INSTALL_SUCCEEDED) { 11587 cleanUp(); 11588 } else { 11589 final int groupOwner; 11590 final String protectedFile; 11591 if (isFwdLocked()) { 11592 groupOwner = UserHandle.getSharedAppGid(uid); 11593 protectedFile = RES_FILE_NAME; 11594 } else { 11595 groupOwner = -1; 11596 protectedFile = null; 11597 } 11598 11599 if (uid < Process.FIRST_APPLICATION_UID 11600 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11601 Slog.e(TAG, "Failed to finalize " + cid); 11602 PackageHelper.destroySdDir(cid); 11603 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11604 } 11605 11606 boolean mounted = PackageHelper.isContainerMounted(cid); 11607 if (!mounted) { 11608 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11609 } 11610 } 11611 return status; 11612 } 11613 11614 private void cleanUp() { 11615 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11616 11617 // Destroy secure container 11618 PackageHelper.destroySdDir(cid); 11619 } 11620 11621 private List<String> getAllCodePaths() { 11622 final File codeFile = new File(getCodePath()); 11623 if (codeFile != null && codeFile.exists()) { 11624 try { 11625 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11626 return pkg.getAllCodePaths(); 11627 } catch (PackageParserException e) { 11628 // Ignored; we tried our best 11629 } 11630 } 11631 return Collections.EMPTY_LIST; 11632 } 11633 11634 void cleanUpResourcesLI() { 11635 // Enumerate all code paths before deleting 11636 cleanUpResourcesLI(getAllCodePaths()); 11637 } 11638 11639 private void cleanUpResourcesLI(List<String> allCodePaths) { 11640 cleanUp(); 11641 removeDexFiles(allCodePaths, instructionSets); 11642 } 11643 11644 String getPackageName() { 11645 return getAsecPackageName(cid); 11646 } 11647 11648 boolean doPostDeleteLI(boolean delete) { 11649 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11650 final List<String> allCodePaths = getAllCodePaths(); 11651 boolean mounted = PackageHelper.isContainerMounted(cid); 11652 if (mounted) { 11653 // Unmount first 11654 if (PackageHelper.unMountSdDir(cid)) { 11655 mounted = false; 11656 } 11657 } 11658 if (!mounted && delete) { 11659 cleanUpResourcesLI(allCodePaths); 11660 } 11661 return !mounted; 11662 } 11663 11664 @Override 11665 int doPreCopy() { 11666 if (isFwdLocked()) { 11667 if (!PackageHelper.fixSdPermissions(cid, 11668 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11669 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11670 } 11671 } 11672 11673 return PackageManager.INSTALL_SUCCEEDED; 11674 } 11675 11676 @Override 11677 int doPostCopy(int uid) { 11678 if (isFwdLocked()) { 11679 if (uid < Process.FIRST_APPLICATION_UID 11680 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11681 RES_FILE_NAME)) { 11682 Slog.e(TAG, "Failed to finalize " + cid); 11683 PackageHelper.destroySdDir(cid); 11684 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11685 } 11686 } 11687 11688 return PackageManager.INSTALL_SUCCEEDED; 11689 } 11690 } 11691 11692 /** 11693 * Logic to handle movement of existing installed applications. 11694 */ 11695 class MoveInstallArgs extends InstallArgs { 11696 private File codeFile; 11697 private File resourceFile; 11698 11699 /** New install */ 11700 MoveInstallArgs(InstallParams params) { 11701 super(params.origin, params.move, params.observer, params.installFlags, 11702 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11703 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11704 params.grantedRuntimePermissions, 11705 params.traceMethod, params.traceCookie); 11706 } 11707 11708 int copyApk(IMediaContainerService imcs, boolean temp) { 11709 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11710 + move.fromUuid + " to " + move.toUuid); 11711 synchronized (mInstaller) { 11712 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11713 move.dataAppName, move.appId, move.seinfo) != 0) { 11714 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11715 } 11716 } 11717 11718 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11719 resourceFile = codeFile; 11720 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11721 11722 return PackageManager.INSTALL_SUCCEEDED; 11723 } 11724 11725 int doPreInstall(int status) { 11726 if (status != PackageManager.INSTALL_SUCCEEDED) { 11727 cleanUp(move.toUuid); 11728 } 11729 return status; 11730 } 11731 11732 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11733 if (status != PackageManager.INSTALL_SUCCEEDED) { 11734 cleanUp(move.toUuid); 11735 return false; 11736 } 11737 11738 // Reflect the move in app info 11739 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11740 pkg.applicationInfo.setCodePath(pkg.codePath); 11741 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11742 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11743 pkg.applicationInfo.setResourcePath(pkg.codePath); 11744 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11745 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11746 11747 return true; 11748 } 11749 11750 int doPostInstall(int status, int uid) { 11751 if (status == PackageManager.INSTALL_SUCCEEDED) { 11752 cleanUp(move.fromUuid); 11753 } else { 11754 cleanUp(move.toUuid); 11755 } 11756 return status; 11757 } 11758 11759 @Override 11760 String getCodePath() { 11761 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11762 } 11763 11764 @Override 11765 String getResourcePath() { 11766 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11767 } 11768 11769 private boolean cleanUp(String volumeUuid) { 11770 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11771 move.dataAppName); 11772 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11773 synchronized (mInstallLock) { 11774 // Clean up both app data and code 11775 removeDataDirsLI(volumeUuid, move.packageName); 11776 if (codeFile.isDirectory()) { 11777 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11778 } else { 11779 codeFile.delete(); 11780 } 11781 } 11782 return true; 11783 } 11784 11785 void cleanUpResourcesLI() { 11786 throw new UnsupportedOperationException(); 11787 } 11788 11789 boolean doPostDeleteLI(boolean delete) { 11790 throw new UnsupportedOperationException(); 11791 } 11792 } 11793 11794 static String getAsecPackageName(String packageCid) { 11795 int idx = packageCid.lastIndexOf("-"); 11796 if (idx == -1) { 11797 return packageCid; 11798 } 11799 return packageCid.substring(0, idx); 11800 } 11801 11802 // Utility method used to create code paths based on package name and available index. 11803 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11804 String idxStr = ""; 11805 int idx = 1; 11806 // Fall back to default value of idx=1 if prefix is not 11807 // part of oldCodePath 11808 if (oldCodePath != null) { 11809 String subStr = oldCodePath; 11810 // Drop the suffix right away 11811 if (suffix != null && subStr.endsWith(suffix)) { 11812 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11813 } 11814 // If oldCodePath already contains prefix find out the 11815 // ending index to either increment or decrement. 11816 int sidx = subStr.lastIndexOf(prefix); 11817 if (sidx != -1) { 11818 subStr = subStr.substring(sidx + prefix.length()); 11819 if (subStr != null) { 11820 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11821 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11822 } 11823 try { 11824 idx = Integer.parseInt(subStr); 11825 if (idx <= 1) { 11826 idx++; 11827 } else { 11828 idx--; 11829 } 11830 } catch(NumberFormatException e) { 11831 } 11832 } 11833 } 11834 } 11835 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11836 return prefix + idxStr; 11837 } 11838 11839 private File getNextCodePath(File targetDir, String packageName) { 11840 int suffix = 1; 11841 File result; 11842 do { 11843 result = new File(targetDir, packageName + "-" + suffix); 11844 suffix++; 11845 } while (result.exists()); 11846 return result; 11847 } 11848 11849 // Utility method that returns the relative package path with respect 11850 // to the installation directory. Like say for /data/data/com.test-1.apk 11851 // string com.test-1 is returned. 11852 static String deriveCodePathName(String codePath) { 11853 if (codePath == null) { 11854 return null; 11855 } 11856 final File codeFile = new File(codePath); 11857 final String name = codeFile.getName(); 11858 if (codeFile.isDirectory()) { 11859 return name; 11860 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11861 final int lastDot = name.lastIndexOf('.'); 11862 return name.substring(0, lastDot); 11863 } else { 11864 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11865 return null; 11866 } 11867 } 11868 11869 class PackageInstalledInfo { 11870 String name; 11871 int uid; 11872 // The set of users that originally had this package installed. 11873 int[] origUsers; 11874 // The set of users that now have this package installed. 11875 int[] newUsers; 11876 PackageParser.Package pkg; 11877 int returnCode; 11878 String returnMsg; 11879 PackageRemovedInfo removedInfo; 11880 11881 public void setError(int code, String msg) { 11882 returnCode = code; 11883 returnMsg = msg; 11884 Slog.w(TAG, msg); 11885 } 11886 11887 public void setError(String msg, PackageParserException e) { 11888 returnCode = e.error; 11889 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11890 Slog.w(TAG, msg, e); 11891 } 11892 11893 public void setError(String msg, PackageManagerException e) { 11894 returnCode = e.error; 11895 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11896 Slog.w(TAG, msg, e); 11897 } 11898 11899 // In some error cases we want to convey more info back to the observer 11900 String origPackage; 11901 String origPermission; 11902 } 11903 11904 /* 11905 * Install a non-existing package. 11906 */ 11907 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11908 UserHandle user, String installerPackageName, String volumeUuid, 11909 PackageInstalledInfo res) { 11910 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11911 11912 // Remember this for later, in case we need to rollback this install 11913 String pkgName = pkg.packageName; 11914 11915 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11916 // TODO: b/23350563 11917 final boolean dataDirExists = Environment 11918 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11919 11920 synchronized(mPackages) { 11921 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11922 // A package with the same name is already installed, though 11923 // it has been renamed to an older name. The package we 11924 // are trying to install should be installed as an update to 11925 // the existing one, but that has not been requested, so bail. 11926 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11927 + " without first uninstalling package running as " 11928 + mSettings.mRenamedPackages.get(pkgName)); 11929 return; 11930 } 11931 if (mPackages.containsKey(pkgName)) { 11932 // Don't allow installation over an existing package with the same name. 11933 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11934 + " without first uninstalling."); 11935 return; 11936 } 11937 } 11938 11939 try { 11940 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11941 System.currentTimeMillis(), user); 11942 11943 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11944 // delete the partially installed application. the data directory will have to be 11945 // restored if it was already existing 11946 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11947 // remove package from internal structures. Note that we want deletePackageX to 11948 // delete the package data and cache directories that it created in 11949 // scanPackageLocked, unless those directories existed before we even tried to 11950 // install. 11951 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11952 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11953 res.removedInfo, true); 11954 } 11955 11956 } catch (PackageManagerException e) { 11957 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11958 } 11959 11960 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11961 } 11962 11963 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11964 // Can't rotate keys during boot or if sharedUser. 11965 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11966 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11967 return false; 11968 } 11969 // app is using upgradeKeySets; make sure all are valid 11970 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11971 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11972 for (int i = 0; i < upgradeKeySets.length; i++) { 11973 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11974 Slog.wtf(TAG, "Package " 11975 + (oldPs.name != null ? oldPs.name : "<null>") 11976 + " contains upgrade-key-set reference to unknown key-set: " 11977 + upgradeKeySets[i] 11978 + " reverting to signatures check."); 11979 return false; 11980 } 11981 } 11982 return true; 11983 } 11984 11985 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11986 // Upgrade keysets are being used. Determine if new package has a superset of the 11987 // required keys. 11988 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11989 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11990 for (int i = 0; i < upgradeKeySets.length; i++) { 11991 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11992 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11993 return true; 11994 } 11995 } 11996 return false; 11997 } 11998 11999 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12000 UserHandle user, String installerPackageName, String volumeUuid, 12001 PackageInstalledInfo res) { 12002 final PackageParser.Package oldPackage; 12003 final String pkgName = pkg.packageName; 12004 final int[] allUsers; 12005 final boolean[] perUserInstalled; 12006 12007 // First find the old package info and check signatures 12008 synchronized(mPackages) { 12009 oldPackage = mPackages.get(pkgName); 12010 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12011 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12012 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12013 if(!checkUpgradeKeySetLP(ps, pkg)) { 12014 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12015 "New package not signed by keys specified by upgrade-keysets: " 12016 + pkgName); 12017 return; 12018 } 12019 } else { 12020 // default to original signature matching 12021 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12022 != PackageManager.SIGNATURE_MATCH) { 12023 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12024 "New package has a different signature: " + pkgName); 12025 return; 12026 } 12027 } 12028 12029 // In case of rollback, remember per-user/profile install state 12030 allUsers = sUserManager.getUserIds(); 12031 perUserInstalled = new boolean[allUsers.length]; 12032 for (int i = 0; i < allUsers.length; i++) { 12033 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12034 } 12035 } 12036 12037 boolean sysPkg = (isSystemApp(oldPackage)); 12038 if (sysPkg) { 12039 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12040 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12041 } else { 12042 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12043 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12044 } 12045 } 12046 12047 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12048 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12049 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12050 String volumeUuid, PackageInstalledInfo res) { 12051 String pkgName = deletedPackage.packageName; 12052 boolean deletedPkg = true; 12053 boolean updatedSettings = false; 12054 12055 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12056 + deletedPackage); 12057 long origUpdateTime; 12058 if (pkg.mExtras != null) { 12059 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12060 } else { 12061 origUpdateTime = 0; 12062 } 12063 12064 // First delete the existing package while retaining the data directory 12065 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12066 res.removedInfo, true)) { 12067 // If the existing package wasn't successfully deleted 12068 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12069 deletedPkg = false; 12070 } else { 12071 // Successfully deleted the old package; proceed with replace. 12072 12073 // If deleted package lived in a container, give users a chance to 12074 // relinquish resources before killing. 12075 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12076 if (DEBUG_INSTALL) { 12077 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12078 } 12079 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12080 final ArrayList<String> pkgList = new ArrayList<String>(1); 12081 pkgList.add(deletedPackage.applicationInfo.packageName); 12082 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12083 } 12084 12085 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12086 try { 12087 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12088 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12089 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12090 perUserInstalled, res, user); 12091 updatedSettings = true; 12092 } catch (PackageManagerException e) { 12093 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12094 } 12095 } 12096 12097 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12098 // remove package from internal structures. Note that we want deletePackageX to 12099 // delete the package data and cache directories that it created in 12100 // scanPackageLocked, unless those directories existed before we even tried to 12101 // install. 12102 if(updatedSettings) { 12103 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12104 deletePackageLI( 12105 pkgName, null, true, allUsers, perUserInstalled, 12106 PackageManager.DELETE_KEEP_DATA, 12107 res.removedInfo, true); 12108 } 12109 // Since we failed to install the new package we need to restore the old 12110 // package that we deleted. 12111 if (deletedPkg) { 12112 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12113 File restoreFile = new File(deletedPackage.codePath); 12114 // Parse old package 12115 boolean oldExternal = isExternal(deletedPackage); 12116 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12117 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12118 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12119 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12120 try { 12121 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12122 UserHandle.SYSTEM); 12123 } catch (PackageManagerException e) { 12124 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12125 + e.getMessage()); 12126 return; 12127 } 12128 // Restore of old package succeeded. Update permissions. 12129 // writer 12130 synchronized (mPackages) { 12131 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12132 UPDATE_PERMISSIONS_ALL); 12133 // can downgrade to reader 12134 mSettings.writeLPr(); 12135 } 12136 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12137 } 12138 } 12139 } 12140 12141 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12142 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12143 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12144 String volumeUuid, PackageInstalledInfo res) { 12145 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12146 + ", old=" + deletedPackage); 12147 boolean disabledSystem = false; 12148 boolean updatedSettings = false; 12149 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12150 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12151 != 0) { 12152 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12153 } 12154 String packageName = deletedPackage.packageName; 12155 if (packageName == null) { 12156 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12157 "Attempt to delete null packageName."); 12158 return; 12159 } 12160 PackageParser.Package oldPkg; 12161 PackageSetting oldPkgSetting; 12162 // reader 12163 synchronized (mPackages) { 12164 oldPkg = mPackages.get(packageName); 12165 oldPkgSetting = mSettings.mPackages.get(packageName); 12166 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12167 (oldPkgSetting == null)) { 12168 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12169 "Couldn't find package:" + packageName + " information"); 12170 return; 12171 } 12172 } 12173 12174 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12175 12176 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12177 res.removedInfo.removedPackage = packageName; 12178 // Remove existing system package 12179 removePackageLI(oldPkgSetting, true); 12180 // writer 12181 synchronized (mPackages) { 12182 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12183 if (!disabledSystem && deletedPackage != null) { 12184 // We didn't need to disable the .apk as a current system package, 12185 // which means we are replacing another update that is already 12186 // installed. We need to make sure to delete the older one's .apk. 12187 res.removedInfo.args = createInstallArgsForExisting(0, 12188 deletedPackage.applicationInfo.getCodePath(), 12189 deletedPackage.applicationInfo.getResourcePath(), 12190 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12191 } else { 12192 res.removedInfo.args = null; 12193 } 12194 } 12195 12196 // Successfully disabled the old package. Now proceed with re-installation 12197 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12198 12199 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12200 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12201 12202 PackageParser.Package newPackage = null; 12203 try { 12204 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12205 if (newPackage.mExtras != null) { 12206 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12207 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12208 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12209 12210 // is the update attempting to change shared user? that isn't going to work... 12211 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12212 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12213 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12214 + " to " + newPkgSetting.sharedUser); 12215 updatedSettings = true; 12216 } 12217 } 12218 12219 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12220 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12221 perUserInstalled, res, user); 12222 updatedSettings = true; 12223 } 12224 12225 } catch (PackageManagerException e) { 12226 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12227 } 12228 12229 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12230 // Re installation failed. Restore old information 12231 // Remove new pkg information 12232 if (newPackage != null) { 12233 removeInstalledPackageLI(newPackage, true); 12234 } 12235 // Add back the old system package 12236 try { 12237 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12238 } catch (PackageManagerException e) { 12239 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12240 } 12241 // Restore the old system information in Settings 12242 synchronized (mPackages) { 12243 if (disabledSystem) { 12244 mSettings.enableSystemPackageLPw(packageName); 12245 } 12246 if (updatedSettings) { 12247 mSettings.setInstallerPackageName(packageName, 12248 oldPkgSetting.installerPackageName); 12249 } 12250 mSettings.writeLPr(); 12251 } 12252 } 12253 } 12254 12255 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12256 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12257 UserHandle user) { 12258 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12259 12260 String pkgName = newPackage.packageName; 12261 synchronized (mPackages) { 12262 //write settings. the installStatus will be incomplete at this stage. 12263 //note that the new package setting would have already been 12264 //added to mPackages. It hasn't been persisted yet. 12265 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12266 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12267 mSettings.writeLPr(); 12268 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12269 } 12270 12271 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12272 synchronized (mPackages) { 12273 updatePermissionsLPw(newPackage.packageName, newPackage, 12274 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12275 ? UPDATE_PERMISSIONS_ALL : 0)); 12276 // For system-bundled packages, we assume that installing an upgraded version 12277 // of the package implies that the user actually wants to run that new code, 12278 // so we enable the package. 12279 PackageSetting ps = mSettings.mPackages.get(pkgName); 12280 if (ps != null) { 12281 if (isSystemApp(newPackage)) { 12282 // NB: implicit assumption that system package upgrades apply to all users 12283 if (DEBUG_INSTALL) { 12284 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12285 } 12286 if (res.origUsers != null) { 12287 for (int userHandle : res.origUsers) { 12288 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12289 userHandle, installerPackageName); 12290 } 12291 } 12292 // Also convey the prior install/uninstall state 12293 if (allUsers != null && perUserInstalled != null) { 12294 for (int i = 0; i < allUsers.length; i++) { 12295 if (DEBUG_INSTALL) { 12296 Slog.d(TAG, " user " + allUsers[i] 12297 + " => " + perUserInstalled[i]); 12298 } 12299 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12300 } 12301 // these install state changes will be persisted in the 12302 // upcoming call to mSettings.writeLPr(). 12303 } 12304 } 12305 // It's implied that when a user requests installation, they want the app to be 12306 // installed and enabled. 12307 int userId = user.getIdentifier(); 12308 if (userId != UserHandle.USER_ALL) { 12309 ps.setInstalled(true, userId); 12310 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12311 } 12312 } 12313 res.name = pkgName; 12314 res.uid = newPackage.applicationInfo.uid; 12315 res.pkg = newPackage; 12316 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12317 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12318 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12319 //to update install status 12320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12321 mSettings.writeLPr(); 12322 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12323 } 12324 12325 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12326 } 12327 12328 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12329 try { 12330 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12331 installPackageLI(args, res); 12332 } finally { 12333 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12334 } 12335 } 12336 12337 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12338 final int installFlags = args.installFlags; 12339 final String installerPackageName = args.installerPackageName; 12340 final String volumeUuid = args.volumeUuid; 12341 final File tmpPackageFile = new File(args.getCodePath()); 12342 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12343 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12344 || (args.volumeUuid != null)); 12345 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12346 boolean replace = false; 12347 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12348 if (args.move != null) { 12349 // moving a complete application; perfom an initial scan on the new install location 12350 scanFlags |= SCAN_INITIAL; 12351 } 12352 // Result object to be returned 12353 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12354 12355 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12356 12357 // Retrieve PackageSettings and parse package 12358 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12359 | PackageParser.PARSE_ENFORCE_CODE 12360 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12361 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12362 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12363 PackageParser pp = new PackageParser(); 12364 pp.setSeparateProcesses(mSeparateProcesses); 12365 pp.setDisplayMetrics(mMetrics); 12366 12367 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12368 final PackageParser.Package pkg; 12369 try { 12370 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12371 } catch (PackageParserException e) { 12372 res.setError("Failed parse during installPackageLI", e); 12373 return; 12374 } finally { 12375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12376 } 12377 12378 // Mark that we have an install time CPU ABI override. 12379 pkg.cpuAbiOverride = args.abiOverride; 12380 12381 String pkgName = res.name = pkg.packageName; 12382 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12383 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12384 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12385 return; 12386 } 12387 } 12388 12389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12390 try { 12391 pp.collectCertificates(pkg, parseFlags); 12392 } catch (PackageParserException e) { 12393 res.setError("Failed collect during installPackageLI", e); 12394 return; 12395 } finally { 12396 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12397 } 12398 12399 /* If the installer passed in a manifest digest, compare it now. */ 12400 if (args.manifestDigest != null) { 12401 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12402 try { 12403 pp.collectManifestDigest(pkg); 12404 } catch (PackageParserException e) { 12405 res.setError("Failed collect during installPackageLI", e); 12406 return; 12407 } finally { 12408 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12409 } 12410 12411 if (DEBUG_INSTALL) { 12412 final String parsedManifest = pkg.manifestDigest == null ? "null" 12413 : pkg.manifestDigest.toString(); 12414 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12415 + parsedManifest); 12416 } 12417 12418 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12419 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12420 return; 12421 } 12422 } else if (DEBUG_INSTALL) { 12423 final String parsedManifest = pkg.manifestDigest == null 12424 ? "null" : pkg.manifestDigest.toString(); 12425 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12426 } 12427 12428 // Get rid of all references to package scan path via parser. 12429 pp = null; 12430 String oldCodePath = null; 12431 boolean systemApp = false; 12432 synchronized (mPackages) { 12433 // Check if installing already existing package 12434 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12435 String oldName = mSettings.mRenamedPackages.get(pkgName); 12436 if (pkg.mOriginalPackages != null 12437 && pkg.mOriginalPackages.contains(oldName) 12438 && mPackages.containsKey(oldName)) { 12439 // This package is derived from an original package, 12440 // and this device has been updating from that original 12441 // name. We must continue using the original name, so 12442 // rename the new package here. 12443 pkg.setPackageName(oldName); 12444 pkgName = pkg.packageName; 12445 replace = true; 12446 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12447 + oldName + " pkgName=" + pkgName); 12448 } else if (mPackages.containsKey(pkgName)) { 12449 // This package, under its official name, already exists 12450 // on the device; we should replace it. 12451 replace = true; 12452 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12453 } 12454 12455 // Prevent apps opting out from runtime permissions 12456 if (replace) { 12457 PackageParser.Package oldPackage = mPackages.get(pkgName); 12458 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12459 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12460 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12461 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12462 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12463 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12464 + " doesn't support runtime permissions but the old" 12465 + " target SDK " + oldTargetSdk + " does."); 12466 return; 12467 } 12468 } 12469 } 12470 12471 PackageSetting ps = mSettings.mPackages.get(pkgName); 12472 if (ps != null) { 12473 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12474 12475 // Quick sanity check that we're signed correctly if updating; 12476 // we'll check this again later when scanning, but we want to 12477 // bail early here before tripping over redefined permissions. 12478 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12479 if (!checkUpgradeKeySetLP(ps, pkg)) { 12480 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12481 + pkg.packageName + " upgrade keys do not match the " 12482 + "previously installed version"); 12483 return; 12484 } 12485 } else { 12486 try { 12487 verifySignaturesLP(ps, pkg); 12488 } catch (PackageManagerException e) { 12489 res.setError(e.error, e.getMessage()); 12490 return; 12491 } 12492 } 12493 12494 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12495 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12496 systemApp = (ps.pkg.applicationInfo.flags & 12497 ApplicationInfo.FLAG_SYSTEM) != 0; 12498 } 12499 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12500 } 12501 12502 // Check whether the newly-scanned package wants to define an already-defined perm 12503 int N = pkg.permissions.size(); 12504 for (int i = N-1; i >= 0; i--) { 12505 PackageParser.Permission perm = pkg.permissions.get(i); 12506 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12507 if (bp != null) { 12508 // If the defining package is signed with our cert, it's okay. This 12509 // also includes the "updating the same package" case, of course. 12510 // "updating same package" could also involve key-rotation. 12511 final boolean sigsOk; 12512 if (bp.sourcePackage.equals(pkg.packageName) 12513 && (bp.packageSetting instanceof PackageSetting) 12514 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12515 scanFlags))) { 12516 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12517 } else { 12518 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12519 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12520 } 12521 if (!sigsOk) { 12522 // If the owning package is the system itself, we log but allow 12523 // install to proceed; we fail the install on all other permission 12524 // redefinitions. 12525 if (!bp.sourcePackage.equals("android")) { 12526 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12527 + pkg.packageName + " attempting to redeclare permission " 12528 + perm.info.name + " already owned by " + bp.sourcePackage); 12529 res.origPermission = perm.info.name; 12530 res.origPackage = bp.sourcePackage; 12531 return; 12532 } else { 12533 Slog.w(TAG, "Package " + pkg.packageName 12534 + " attempting to redeclare system permission " 12535 + perm.info.name + "; ignoring new declaration"); 12536 pkg.permissions.remove(i); 12537 } 12538 } 12539 } 12540 } 12541 12542 } 12543 12544 if (systemApp && onExternal) { 12545 // Disable updates to system apps on sdcard 12546 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12547 "Cannot install updates to system apps on sdcard"); 12548 return; 12549 } 12550 12551 if (args.move != null) { 12552 // We did an in-place move, so dex is ready to roll 12553 scanFlags |= SCAN_NO_DEX; 12554 scanFlags |= SCAN_MOVE; 12555 12556 synchronized (mPackages) { 12557 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12558 if (ps == null) { 12559 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12560 "Missing settings for moved package " + pkgName); 12561 } 12562 12563 // We moved the entire application as-is, so bring over the 12564 // previously derived ABI information. 12565 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12566 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12567 } 12568 12569 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12570 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12571 scanFlags |= SCAN_NO_DEX; 12572 12573 try { 12574 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12575 true /* extract libs */); 12576 } catch (PackageManagerException pme) { 12577 Slog.e(TAG, "Error deriving application ABI", pme); 12578 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12579 return; 12580 } 12581 12582 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12583 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12584 12585 int result = mPackageDexOptimizer 12586 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12587 false /* defer */, false /* inclDependencies */, 12588 true /*bootComplete*/, quickInstall /*useJit*/); 12589 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12590 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12591 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12592 return; 12593 } 12594 } 12595 12596 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12597 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12598 return; 12599 } 12600 12601 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12602 12603 if (replace) { 12604 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12605 installerPackageName, volumeUuid, res); 12606 } else { 12607 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12608 args.user, installerPackageName, volumeUuid, res); 12609 } 12610 synchronized (mPackages) { 12611 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12612 if (ps != null) { 12613 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12614 } 12615 } 12616 } 12617 12618 private void startIntentFilterVerifications(int userId, boolean replacing, 12619 PackageParser.Package pkg) { 12620 if (mIntentFilterVerifierComponent == null) { 12621 Slog.w(TAG, "No IntentFilter verification will not be done as " 12622 + "there is no IntentFilterVerifier available!"); 12623 return; 12624 } 12625 12626 final int verifierUid = getPackageUid( 12627 mIntentFilterVerifierComponent.getPackageName(), 12628 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12629 12630 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12631 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12632 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12633 mHandler.sendMessage(msg); 12634 } 12635 12636 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12637 PackageParser.Package pkg) { 12638 int size = pkg.activities.size(); 12639 if (size == 0) { 12640 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12641 "No activity, so no need to verify any IntentFilter!"); 12642 return; 12643 } 12644 12645 final boolean hasDomainURLs = hasDomainURLs(pkg); 12646 if (!hasDomainURLs) { 12647 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12648 "No domain URLs, so no need to verify any IntentFilter!"); 12649 return; 12650 } 12651 12652 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12653 + " if any IntentFilter from the " + size 12654 + " Activities needs verification ..."); 12655 12656 int count = 0; 12657 final String packageName = pkg.packageName; 12658 12659 synchronized (mPackages) { 12660 // If this is a new install and we see that we've already run verification for this 12661 // package, we have nothing to do: it means the state was restored from backup. 12662 if (!replacing) { 12663 IntentFilterVerificationInfo ivi = 12664 mSettings.getIntentFilterVerificationLPr(packageName); 12665 if (ivi != null) { 12666 if (DEBUG_DOMAIN_VERIFICATION) { 12667 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12668 + ivi.getStatusString()); 12669 } 12670 return; 12671 } 12672 } 12673 12674 // If any filters need to be verified, then all need to be. 12675 boolean needToVerify = false; 12676 for (PackageParser.Activity a : pkg.activities) { 12677 for (ActivityIntentInfo filter : a.intents) { 12678 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12679 if (DEBUG_DOMAIN_VERIFICATION) { 12680 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12681 } 12682 needToVerify = true; 12683 break; 12684 } 12685 } 12686 } 12687 12688 if (needToVerify) { 12689 final int verificationId = mIntentFilterVerificationToken++; 12690 for (PackageParser.Activity a : pkg.activities) { 12691 for (ActivityIntentInfo filter : a.intents) { 12692 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12693 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12694 "Verification needed for IntentFilter:" + filter.toString()); 12695 mIntentFilterVerifier.addOneIntentFilterVerification( 12696 verifierUid, userId, verificationId, filter, packageName); 12697 count++; 12698 } 12699 } 12700 } 12701 } 12702 } 12703 12704 if (count > 0) { 12705 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12706 + " IntentFilter verification" + (count > 1 ? "s" : "") 12707 + " for userId:" + userId); 12708 mIntentFilterVerifier.startVerifications(userId); 12709 } else { 12710 if (DEBUG_DOMAIN_VERIFICATION) { 12711 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12712 } 12713 } 12714 } 12715 12716 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12717 final ComponentName cn = filter.activity.getComponentName(); 12718 final String packageName = cn.getPackageName(); 12719 12720 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12721 packageName); 12722 if (ivi == null) { 12723 return true; 12724 } 12725 int status = ivi.getStatus(); 12726 switch (status) { 12727 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12728 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12729 return true; 12730 12731 default: 12732 // Nothing to do 12733 return false; 12734 } 12735 } 12736 12737 private static boolean isMultiArch(PackageSetting ps) { 12738 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12739 } 12740 12741 private static boolean isMultiArch(ApplicationInfo info) { 12742 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12743 } 12744 12745 private static boolean isExternal(PackageParser.Package pkg) { 12746 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12747 } 12748 12749 private static boolean isExternal(PackageSetting ps) { 12750 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12751 } 12752 12753 private static boolean isExternal(ApplicationInfo info) { 12754 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12755 } 12756 12757 private static boolean isSystemApp(PackageParser.Package pkg) { 12758 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12759 } 12760 12761 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12762 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12763 } 12764 12765 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12766 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12767 } 12768 12769 private static boolean isSystemApp(PackageSetting ps) { 12770 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12771 } 12772 12773 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12774 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12775 } 12776 12777 private int packageFlagsToInstallFlags(PackageSetting ps) { 12778 int installFlags = 0; 12779 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12780 // This existing package was an external ASEC install when we have 12781 // the external flag without a UUID 12782 installFlags |= PackageManager.INSTALL_EXTERNAL; 12783 } 12784 if (ps.isForwardLocked()) { 12785 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12786 } 12787 return installFlags; 12788 } 12789 12790 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12791 if (isExternal(pkg)) { 12792 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12793 return mSettings.getExternalVersion(); 12794 } else { 12795 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12796 } 12797 } else { 12798 return mSettings.getInternalVersion(); 12799 } 12800 } 12801 12802 private void deleteTempPackageFiles() { 12803 final FilenameFilter filter = new FilenameFilter() { 12804 public boolean accept(File dir, String name) { 12805 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12806 } 12807 }; 12808 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12809 file.delete(); 12810 } 12811 } 12812 12813 @Override 12814 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12815 int flags) { 12816 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12817 flags); 12818 } 12819 12820 @Override 12821 public void deletePackage(final String packageName, 12822 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12823 mContext.enforceCallingOrSelfPermission( 12824 android.Manifest.permission.DELETE_PACKAGES, null); 12825 Preconditions.checkNotNull(packageName); 12826 Preconditions.checkNotNull(observer); 12827 final int uid = Binder.getCallingUid(); 12828 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 12829 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 12830 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 12831 mContext.enforceCallingPermission( 12832 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12833 "deletePackage for user " + userId); 12834 } 12835 12836 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12837 try { 12838 observer.onPackageDeleted(packageName, 12839 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12840 } catch (RemoteException re) { 12841 } 12842 return; 12843 } 12844 12845 for (int currentUserId : users) { 12846 if (getBlockUninstallForUser(packageName, currentUserId)) { 12847 try { 12848 observer.onPackageDeleted(packageName, 12849 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 12850 } catch (RemoteException re) { 12851 } 12852 return; 12853 } 12854 } 12855 12856 if (DEBUG_REMOVE) { 12857 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12858 } 12859 // Queue up an async operation since the package deletion may take a little while. 12860 mHandler.post(new Runnable() { 12861 public void run() { 12862 mHandler.removeCallbacks(this); 12863 final int returnCode = deletePackageX(packageName, userId, flags); 12864 try { 12865 observer.onPackageDeleted(packageName, returnCode, null); 12866 } catch (RemoteException e) { 12867 Log.i(TAG, "Observer no longer exists."); 12868 } //end catch 12869 } //end run 12870 }); 12871 } 12872 12873 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12874 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12875 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12876 try { 12877 if (dpm != null) { 12878 if (dpm.isDeviceOwner(packageName)) { 12879 return true; 12880 } 12881 int[] users; 12882 if (userId == UserHandle.USER_ALL) { 12883 users = sUserManager.getUserIds(); 12884 } else { 12885 users = new int[]{userId}; 12886 } 12887 for (int i = 0; i < users.length; ++i) { 12888 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12889 return true; 12890 } 12891 } 12892 } 12893 } catch (RemoteException e) { 12894 } 12895 return false; 12896 } 12897 12898 /** 12899 * This method is an internal method that could be get invoked either 12900 * to delete an installed package or to clean up a failed installation. 12901 * After deleting an installed package, a broadcast is sent to notify any 12902 * listeners that the package has been installed. For cleaning up a failed 12903 * installation, the broadcast is not necessary since the package's 12904 * installation wouldn't have sent the initial broadcast either 12905 * The key steps in deleting a package are 12906 * deleting the package information in internal structures like mPackages, 12907 * deleting the packages base directories through installd 12908 * updating mSettings to reflect current status 12909 * persisting settings for later use 12910 * sending a broadcast if necessary 12911 */ 12912 private int deletePackageX(String packageName, int userId, int flags) { 12913 final PackageRemovedInfo info = new PackageRemovedInfo(); 12914 final boolean res; 12915 12916 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12917 ? UserHandle.ALL : new UserHandle(userId); 12918 12919 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12920 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12921 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12922 } 12923 12924 boolean removedForAllUsers = false; 12925 boolean systemUpdate = false; 12926 12927 // for the uninstall-updates case and restricted profiles, remember the per- 12928 // userhandle installed state 12929 int[] allUsers; 12930 boolean[] perUserInstalled; 12931 synchronized (mPackages) { 12932 PackageSetting ps = mSettings.mPackages.get(packageName); 12933 allUsers = sUserManager.getUserIds(); 12934 perUserInstalled = new boolean[allUsers.length]; 12935 for (int i = 0; i < allUsers.length; i++) { 12936 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12937 } 12938 } 12939 12940 synchronized (mInstallLock) { 12941 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12942 res = deletePackageLI(packageName, removeForUser, 12943 true, allUsers, perUserInstalled, 12944 flags | REMOVE_CHATTY, info, true); 12945 systemUpdate = info.isRemovedPackageSystemUpdate; 12946 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12947 removedForAllUsers = true; 12948 } 12949 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12950 + " removedForAllUsers=" + removedForAllUsers); 12951 } 12952 12953 if (res) { 12954 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12955 12956 // If the removed package was a system update, the old system package 12957 // was re-enabled; we need to broadcast this information 12958 if (systemUpdate) { 12959 Bundle extras = new Bundle(1); 12960 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12961 ? info.removedAppId : info.uid); 12962 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12963 12964 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12965 extras, null, null, null); 12966 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12967 extras, null, null, null); 12968 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12969 null, packageName, null, null); 12970 } 12971 } 12972 // Force a gc here. 12973 Runtime.getRuntime().gc(); 12974 // Delete the resources here after sending the broadcast to let 12975 // other processes clean up before deleting resources. 12976 if (info.args != null) { 12977 synchronized (mInstallLock) { 12978 info.args.doPostDeleteLI(true); 12979 } 12980 } 12981 12982 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12983 } 12984 12985 class PackageRemovedInfo { 12986 String removedPackage; 12987 int uid = -1; 12988 int removedAppId = -1; 12989 int[] removedUsers = null; 12990 boolean isRemovedPackageSystemUpdate = false; 12991 // Clean up resources deleted packages. 12992 InstallArgs args = null; 12993 12994 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12995 Bundle extras = new Bundle(1); 12996 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12997 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12998 if (replacing) { 12999 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13000 } 13001 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13002 if (removedPackage != null) { 13003 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13004 extras, null, null, removedUsers); 13005 if (fullRemove && !replacing) { 13006 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13007 extras, null, null, removedUsers); 13008 } 13009 } 13010 if (removedAppId >= 0) { 13011 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 13012 removedUsers); 13013 } 13014 } 13015 } 13016 13017 /* 13018 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13019 * flag is not set, the data directory is removed as well. 13020 * make sure this flag is set for partially installed apps. If not its meaningless to 13021 * delete a partially installed application. 13022 */ 13023 private void removePackageDataLI(PackageSetting ps, 13024 int[] allUserHandles, boolean[] perUserInstalled, 13025 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13026 String packageName = ps.name; 13027 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13028 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13029 // Retrieve object to delete permissions for shared user later on 13030 final PackageSetting deletedPs; 13031 // reader 13032 synchronized (mPackages) { 13033 deletedPs = mSettings.mPackages.get(packageName); 13034 if (outInfo != null) { 13035 outInfo.removedPackage = packageName; 13036 outInfo.removedUsers = deletedPs != null 13037 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13038 : null; 13039 } 13040 } 13041 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13042 removeDataDirsLI(ps.volumeUuid, packageName); 13043 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13044 } 13045 // writer 13046 synchronized (mPackages) { 13047 if (deletedPs != null) { 13048 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13049 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13050 clearDefaultBrowserIfNeeded(packageName); 13051 if (outInfo != null) { 13052 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13053 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13054 } 13055 updatePermissionsLPw(deletedPs.name, null, 0); 13056 if (deletedPs.sharedUser != null) { 13057 // Remove permissions associated with package. Since runtime 13058 // permissions are per user we have to kill the removed package 13059 // or packages running under the shared user of the removed 13060 // package if revoking the permissions requested only by the removed 13061 // package is successful and this causes a change in gids. 13062 for (int userId : UserManagerService.getInstance().getUserIds()) { 13063 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13064 userId); 13065 if (userIdToKill == UserHandle.USER_ALL 13066 || userIdToKill >= UserHandle.USER_SYSTEM) { 13067 // If gids changed for this user, kill all affected packages. 13068 mHandler.post(new Runnable() { 13069 @Override 13070 public void run() { 13071 // This has to happen with no lock held. 13072 killApplication(deletedPs.name, deletedPs.appId, 13073 KILL_APP_REASON_GIDS_CHANGED); 13074 } 13075 }); 13076 break; 13077 } 13078 } 13079 } 13080 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13081 } 13082 // make sure to preserve per-user disabled state if this removal was just 13083 // a downgrade of a system app to the factory package 13084 if (allUserHandles != null && perUserInstalled != null) { 13085 if (DEBUG_REMOVE) { 13086 Slog.d(TAG, "Propagating install state across downgrade"); 13087 } 13088 for (int i = 0; i < allUserHandles.length; i++) { 13089 if (DEBUG_REMOVE) { 13090 Slog.d(TAG, " user " + allUserHandles[i] 13091 + " => " + perUserInstalled[i]); 13092 } 13093 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13094 } 13095 } 13096 } 13097 // can downgrade to reader 13098 if (writeSettings) { 13099 // Save settings now 13100 mSettings.writeLPr(); 13101 } 13102 } 13103 if (outInfo != null) { 13104 // A user ID was deleted here. Go through all users and remove it 13105 // from KeyStore. 13106 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13107 } 13108 } 13109 13110 static boolean locationIsPrivileged(File path) { 13111 try { 13112 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13113 .getCanonicalPath(); 13114 return path.getCanonicalPath().startsWith(privilegedAppDir); 13115 } catch (IOException e) { 13116 Slog.e(TAG, "Unable to access code path " + path); 13117 } 13118 return false; 13119 } 13120 13121 /* 13122 * Tries to delete system package. 13123 */ 13124 private boolean deleteSystemPackageLI(PackageSetting newPs, 13125 int[] allUserHandles, boolean[] perUserInstalled, 13126 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13127 final boolean applyUserRestrictions 13128 = (allUserHandles != null) && (perUserInstalled != null); 13129 PackageSetting disabledPs = null; 13130 // Confirm if the system package has been updated 13131 // An updated system app can be deleted. This will also have to restore 13132 // the system pkg from system partition 13133 // reader 13134 synchronized (mPackages) { 13135 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13136 } 13137 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13138 + " disabledPs=" + disabledPs); 13139 if (disabledPs == null) { 13140 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13141 return false; 13142 } else if (DEBUG_REMOVE) { 13143 Slog.d(TAG, "Deleting system pkg from data partition"); 13144 } 13145 if (DEBUG_REMOVE) { 13146 if (applyUserRestrictions) { 13147 Slog.d(TAG, "Remembering install states:"); 13148 for (int i = 0; i < allUserHandles.length; i++) { 13149 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13150 } 13151 } 13152 } 13153 // Delete the updated package 13154 outInfo.isRemovedPackageSystemUpdate = true; 13155 if (disabledPs.versionCode < newPs.versionCode) { 13156 // Delete data for downgrades 13157 flags &= ~PackageManager.DELETE_KEEP_DATA; 13158 } else { 13159 // Preserve data by setting flag 13160 flags |= PackageManager.DELETE_KEEP_DATA; 13161 } 13162 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13163 allUserHandles, perUserInstalled, outInfo, writeSettings); 13164 if (!ret) { 13165 return false; 13166 } 13167 // writer 13168 synchronized (mPackages) { 13169 // Reinstate the old system package 13170 mSettings.enableSystemPackageLPw(newPs.name); 13171 // Remove any native libraries from the upgraded package. 13172 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13173 } 13174 // Install the system package 13175 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13176 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13177 if (locationIsPrivileged(disabledPs.codePath)) { 13178 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13179 } 13180 13181 final PackageParser.Package newPkg; 13182 try { 13183 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, 13184 UserHandle.SYSTEM); 13185 } catch (PackageManagerException e) { 13186 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13187 return false; 13188 } 13189 13190 // writer 13191 synchronized (mPackages) { 13192 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13193 13194 // Propagate the permissions state as we do not want to drop on the floor 13195 // runtime permissions. The update permissions method below will take 13196 // care of removing obsolete permissions and grant install permissions. 13197 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13198 updatePermissionsLPw(newPkg.packageName, newPkg, 13199 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13200 13201 if (applyUserRestrictions) { 13202 if (DEBUG_REMOVE) { 13203 Slog.d(TAG, "Propagating install state across reinstall"); 13204 } 13205 for (int i = 0; i < allUserHandles.length; i++) { 13206 if (DEBUG_REMOVE) { 13207 Slog.d(TAG, " user " + allUserHandles[i] 13208 + " => " + perUserInstalled[i]); 13209 } 13210 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13211 13212 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13213 } 13214 // Regardless of writeSettings we need to ensure that this restriction 13215 // state propagation is persisted 13216 mSettings.writeAllUsersPackageRestrictionsLPr(); 13217 } 13218 // can downgrade to reader here 13219 if (writeSettings) { 13220 mSettings.writeLPr(); 13221 } 13222 } 13223 return true; 13224 } 13225 13226 private boolean deleteInstalledPackageLI(PackageSetting ps, 13227 boolean deleteCodeAndResources, int flags, 13228 int[] allUserHandles, boolean[] perUserInstalled, 13229 PackageRemovedInfo outInfo, boolean writeSettings) { 13230 if (outInfo != null) { 13231 outInfo.uid = ps.appId; 13232 } 13233 13234 // Delete package data from internal structures and also remove data if flag is set 13235 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13236 13237 // Delete application code and resources 13238 if (deleteCodeAndResources && (outInfo != null)) { 13239 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13240 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13241 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13242 } 13243 return true; 13244 } 13245 13246 @Override 13247 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13248 int userId) { 13249 mContext.enforceCallingOrSelfPermission( 13250 android.Manifest.permission.DELETE_PACKAGES, null); 13251 synchronized (mPackages) { 13252 PackageSetting ps = mSettings.mPackages.get(packageName); 13253 if (ps == null) { 13254 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13255 return false; 13256 } 13257 if (!ps.getInstalled(userId)) { 13258 // Can't block uninstall for an app that is not installed or enabled. 13259 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13260 return false; 13261 } 13262 ps.setBlockUninstall(blockUninstall, userId); 13263 mSettings.writePackageRestrictionsLPr(userId); 13264 } 13265 return true; 13266 } 13267 13268 @Override 13269 public boolean getBlockUninstallForUser(String packageName, int userId) { 13270 synchronized (mPackages) { 13271 PackageSetting ps = mSettings.mPackages.get(packageName); 13272 if (ps == null) { 13273 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13274 return false; 13275 } 13276 return ps.getBlockUninstall(userId); 13277 } 13278 } 13279 13280 /* 13281 * This method handles package deletion in general 13282 */ 13283 private boolean deletePackageLI(String packageName, UserHandle user, 13284 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13285 int flags, PackageRemovedInfo outInfo, 13286 boolean writeSettings) { 13287 if (packageName == null) { 13288 Slog.w(TAG, "Attempt to delete null packageName."); 13289 return false; 13290 } 13291 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13292 PackageSetting ps; 13293 boolean dataOnly = false; 13294 int removeUser = -1; 13295 int appId = -1; 13296 synchronized (mPackages) { 13297 ps = mSettings.mPackages.get(packageName); 13298 if (ps == null) { 13299 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13300 return false; 13301 } 13302 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13303 && user.getIdentifier() != UserHandle.USER_ALL) { 13304 // The caller is asking that the package only be deleted for a single 13305 // user. To do this, we just mark its uninstalled state and delete 13306 // its data. If this is a system app, we only allow this to happen if 13307 // they have set the special DELETE_SYSTEM_APP which requests different 13308 // semantics than normal for uninstalling system apps. 13309 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13310 final int userId = user.getIdentifier(); 13311 ps.setUserState(userId, 13312 COMPONENT_ENABLED_STATE_DEFAULT, 13313 false, //installed 13314 true, //stopped 13315 true, //notLaunched 13316 false, //hidden 13317 null, null, null, 13318 false, // blockUninstall 13319 ps.readUserState(userId).domainVerificationStatus, 0); 13320 if (!isSystemApp(ps)) { 13321 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13322 // Other user still have this package installed, so all 13323 // we need to do is clear this user's data and save that 13324 // it is uninstalled. 13325 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13326 removeUser = user.getIdentifier(); 13327 appId = ps.appId; 13328 scheduleWritePackageRestrictionsLocked(removeUser); 13329 } else { 13330 // We need to set it back to 'installed' so the uninstall 13331 // broadcasts will be sent correctly. 13332 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13333 ps.setInstalled(true, user.getIdentifier()); 13334 } 13335 } else { 13336 // This is a system app, so we assume that the 13337 // other users still have this package installed, so all 13338 // we need to do is clear this user's data and save that 13339 // it is uninstalled. 13340 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13341 removeUser = user.getIdentifier(); 13342 appId = ps.appId; 13343 scheduleWritePackageRestrictionsLocked(removeUser); 13344 } 13345 } 13346 } 13347 13348 if (removeUser >= 0) { 13349 // From above, we determined that we are deleting this only 13350 // for a single user. Continue the work here. 13351 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13352 if (outInfo != null) { 13353 outInfo.removedPackage = packageName; 13354 outInfo.removedAppId = appId; 13355 outInfo.removedUsers = new int[] {removeUser}; 13356 } 13357 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13358 removeKeystoreDataIfNeeded(removeUser, appId); 13359 schedulePackageCleaning(packageName, removeUser, false); 13360 synchronized (mPackages) { 13361 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13362 scheduleWritePackageRestrictionsLocked(removeUser); 13363 } 13364 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13365 } 13366 return true; 13367 } 13368 13369 if (dataOnly) { 13370 // Delete application data first 13371 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13372 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13373 return true; 13374 } 13375 13376 boolean ret = false; 13377 if (isSystemApp(ps)) { 13378 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13379 // When an updated system application is deleted we delete the existing resources as well and 13380 // fall back to existing code in system partition 13381 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13382 flags, outInfo, writeSettings); 13383 } else { 13384 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13385 // Kill application pre-emptively especially for apps on sd. 13386 killApplication(packageName, ps.appId, "uninstall pkg"); 13387 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13388 allUserHandles, perUserInstalled, 13389 outInfo, writeSettings); 13390 } 13391 13392 return ret; 13393 } 13394 13395 private final class ClearStorageConnection implements ServiceConnection { 13396 IMediaContainerService mContainerService; 13397 13398 @Override 13399 public void onServiceConnected(ComponentName name, IBinder service) { 13400 synchronized (this) { 13401 mContainerService = IMediaContainerService.Stub.asInterface(service); 13402 notifyAll(); 13403 } 13404 } 13405 13406 @Override 13407 public void onServiceDisconnected(ComponentName name) { 13408 } 13409 } 13410 13411 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13412 final boolean mounted; 13413 if (Environment.isExternalStorageEmulated()) { 13414 mounted = true; 13415 } else { 13416 final String status = Environment.getExternalStorageState(); 13417 13418 mounted = status.equals(Environment.MEDIA_MOUNTED) 13419 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13420 } 13421 13422 if (!mounted) { 13423 return; 13424 } 13425 13426 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13427 int[] users; 13428 if (userId == UserHandle.USER_ALL) { 13429 users = sUserManager.getUserIds(); 13430 } else { 13431 users = new int[] { userId }; 13432 } 13433 final ClearStorageConnection conn = new ClearStorageConnection(); 13434 if (mContext.bindServiceAsUser( 13435 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13436 try { 13437 for (int curUser : users) { 13438 long timeout = SystemClock.uptimeMillis() + 5000; 13439 synchronized (conn) { 13440 long now = SystemClock.uptimeMillis(); 13441 while (conn.mContainerService == null && now < timeout) { 13442 try { 13443 conn.wait(timeout - now); 13444 } catch (InterruptedException e) { 13445 } 13446 } 13447 } 13448 if (conn.mContainerService == null) { 13449 return; 13450 } 13451 13452 final UserEnvironment userEnv = new UserEnvironment(curUser); 13453 clearDirectory(conn.mContainerService, 13454 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13455 if (allData) { 13456 clearDirectory(conn.mContainerService, 13457 userEnv.buildExternalStorageAppDataDirs(packageName)); 13458 clearDirectory(conn.mContainerService, 13459 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13460 } 13461 } 13462 } finally { 13463 mContext.unbindService(conn); 13464 } 13465 } 13466 } 13467 13468 @Override 13469 public void clearApplicationUserData(final String packageName, 13470 final IPackageDataObserver observer, final int userId) { 13471 mContext.enforceCallingOrSelfPermission( 13472 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13473 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13474 // Queue up an async operation since the package deletion may take a little while. 13475 mHandler.post(new Runnable() { 13476 public void run() { 13477 mHandler.removeCallbacks(this); 13478 final boolean succeeded; 13479 synchronized (mInstallLock) { 13480 succeeded = clearApplicationUserDataLI(packageName, userId); 13481 } 13482 clearExternalStorageDataSync(packageName, userId, true); 13483 if (succeeded) { 13484 // invoke DeviceStorageMonitor's update method to clear any notifications 13485 DeviceStorageMonitorInternal 13486 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13487 if (dsm != null) { 13488 dsm.checkMemory(); 13489 } 13490 } 13491 if(observer != null) { 13492 try { 13493 observer.onRemoveCompleted(packageName, succeeded); 13494 } catch (RemoteException e) { 13495 Log.i(TAG, "Observer no longer exists."); 13496 } 13497 } //end if observer 13498 } //end run 13499 }); 13500 } 13501 13502 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13503 if (packageName == null) { 13504 Slog.w(TAG, "Attempt to delete null packageName."); 13505 return false; 13506 } 13507 13508 // Try finding details about the requested package 13509 PackageParser.Package pkg; 13510 synchronized (mPackages) { 13511 pkg = mPackages.get(packageName); 13512 if (pkg == null) { 13513 final PackageSetting ps = mSettings.mPackages.get(packageName); 13514 if (ps != null) { 13515 pkg = ps.pkg; 13516 } 13517 } 13518 13519 if (pkg == null) { 13520 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13521 return false; 13522 } 13523 13524 PackageSetting ps = (PackageSetting) pkg.mExtras; 13525 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13526 } 13527 13528 // Always delete data directories for package, even if we found no other 13529 // record of app. This helps users recover from UID mismatches without 13530 // resorting to a full data wipe. 13531 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13532 if (retCode < 0) { 13533 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13534 return false; 13535 } 13536 13537 final int appId = pkg.applicationInfo.uid; 13538 removeKeystoreDataIfNeeded(userId, appId); 13539 13540 // Create a native library symlink only if we have native libraries 13541 // and if the native libraries are 32 bit libraries. We do not provide 13542 // this symlink for 64 bit libraries. 13543 if (pkg.applicationInfo.primaryCpuAbi != null && 13544 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13545 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13546 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13547 nativeLibPath, userId) < 0) { 13548 Slog.w(TAG, "Failed linking native library dir"); 13549 return false; 13550 } 13551 } 13552 13553 return true; 13554 } 13555 13556 /** 13557 * Reverts user permission state changes (permissions and flags) in 13558 * all packages for a given user. 13559 * 13560 * @param userId The device user for which to do a reset. 13561 */ 13562 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13563 final int packageCount = mPackages.size(); 13564 for (int i = 0; i < packageCount; i++) { 13565 PackageParser.Package pkg = mPackages.valueAt(i); 13566 PackageSetting ps = (PackageSetting) pkg.mExtras; 13567 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13568 } 13569 } 13570 13571 /** 13572 * Reverts user permission state changes (permissions and flags). 13573 * 13574 * @param ps The package for which to reset. 13575 * @param userId The device user for which to do a reset. 13576 */ 13577 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13578 final PackageSetting ps, final int userId) { 13579 if (ps.pkg == null) { 13580 return; 13581 } 13582 13583 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13584 | FLAG_PERMISSION_USER_FIXED 13585 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13586 13587 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13588 | FLAG_PERMISSION_POLICY_FIXED; 13589 13590 boolean writeInstallPermissions = false; 13591 boolean writeRuntimePermissions = false; 13592 13593 final int permissionCount = ps.pkg.requestedPermissions.size(); 13594 for (int i = 0; i < permissionCount; i++) { 13595 String permission = ps.pkg.requestedPermissions.get(i); 13596 13597 BasePermission bp = mSettings.mPermissions.get(permission); 13598 if (bp == null) { 13599 continue; 13600 } 13601 13602 // If shared user we just reset the state to which only this app contributed. 13603 if (ps.sharedUser != null) { 13604 boolean used = false; 13605 final int packageCount = ps.sharedUser.packages.size(); 13606 for (int j = 0; j < packageCount; j++) { 13607 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13608 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13609 && pkg.pkg.requestedPermissions.contains(permission)) { 13610 used = true; 13611 break; 13612 } 13613 } 13614 if (used) { 13615 continue; 13616 } 13617 } 13618 13619 PermissionsState permissionsState = ps.getPermissionsState(); 13620 13621 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13622 13623 // Always clear the user settable flags. 13624 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13625 bp.name) != null; 13626 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13627 if (hasInstallState) { 13628 writeInstallPermissions = true; 13629 } else { 13630 writeRuntimePermissions = true; 13631 } 13632 } 13633 13634 // Below is only runtime permission handling. 13635 if (!bp.isRuntime()) { 13636 continue; 13637 } 13638 13639 // Never clobber system or policy. 13640 if ((oldFlags & policyOrSystemFlags) != 0) { 13641 continue; 13642 } 13643 13644 // If this permission was granted by default, make sure it is. 13645 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13646 if (permissionsState.grantRuntimePermission(bp, userId) 13647 != PERMISSION_OPERATION_FAILURE) { 13648 writeRuntimePermissions = true; 13649 } 13650 } else { 13651 // Otherwise, reset the permission. 13652 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13653 switch (revokeResult) { 13654 case PERMISSION_OPERATION_SUCCESS: { 13655 writeRuntimePermissions = true; 13656 } break; 13657 13658 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13659 writeRuntimePermissions = true; 13660 final int appId = ps.appId; 13661 mHandler.post(new Runnable() { 13662 @Override 13663 public void run() { 13664 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13665 } 13666 }); 13667 } break; 13668 } 13669 } 13670 } 13671 13672 // Synchronously write as we are taking permissions away. 13673 if (writeRuntimePermissions) { 13674 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13675 } 13676 13677 // Synchronously write as we are taking permissions away. 13678 if (writeInstallPermissions) { 13679 mSettings.writeLPr(); 13680 } 13681 } 13682 13683 /** 13684 * Remove entries from the keystore daemon. Will only remove it if the 13685 * {@code appId} is valid. 13686 */ 13687 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13688 if (appId < 0) { 13689 return; 13690 } 13691 13692 final KeyStore keyStore = KeyStore.getInstance(); 13693 if (keyStore != null) { 13694 if (userId == UserHandle.USER_ALL) { 13695 for (final int individual : sUserManager.getUserIds()) { 13696 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13697 } 13698 } else { 13699 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13700 } 13701 } else { 13702 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13703 } 13704 } 13705 13706 @Override 13707 public void deleteApplicationCacheFiles(final String packageName, 13708 final IPackageDataObserver observer) { 13709 mContext.enforceCallingOrSelfPermission( 13710 android.Manifest.permission.DELETE_CACHE_FILES, null); 13711 // Queue up an async operation since the package deletion may take a little while. 13712 final int userId = UserHandle.getCallingUserId(); 13713 mHandler.post(new Runnable() { 13714 public void run() { 13715 mHandler.removeCallbacks(this); 13716 final boolean succeded; 13717 synchronized (mInstallLock) { 13718 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13719 } 13720 clearExternalStorageDataSync(packageName, userId, false); 13721 if (observer != null) { 13722 try { 13723 observer.onRemoveCompleted(packageName, succeded); 13724 } catch (RemoteException e) { 13725 Log.i(TAG, "Observer no longer exists."); 13726 } 13727 } //end if observer 13728 } //end run 13729 }); 13730 } 13731 13732 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13733 if (packageName == null) { 13734 Slog.w(TAG, "Attempt to delete null packageName."); 13735 return false; 13736 } 13737 PackageParser.Package p; 13738 synchronized (mPackages) { 13739 p = mPackages.get(packageName); 13740 } 13741 if (p == null) { 13742 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13743 return false; 13744 } 13745 final ApplicationInfo applicationInfo = p.applicationInfo; 13746 if (applicationInfo == null) { 13747 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13748 return false; 13749 } 13750 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13751 if (retCode < 0) { 13752 Slog.w(TAG, "Couldn't remove cache files for package: " 13753 + packageName + " u" + userId); 13754 return false; 13755 } 13756 return true; 13757 } 13758 13759 @Override 13760 public void getPackageSizeInfo(final String packageName, int userHandle, 13761 final IPackageStatsObserver observer) { 13762 mContext.enforceCallingOrSelfPermission( 13763 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13764 if (packageName == null) { 13765 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13766 } 13767 13768 PackageStats stats = new PackageStats(packageName, userHandle); 13769 13770 /* 13771 * Queue up an async operation since the package measurement may take a 13772 * little while. 13773 */ 13774 Message msg = mHandler.obtainMessage(INIT_COPY); 13775 msg.obj = new MeasureParams(stats, observer); 13776 mHandler.sendMessage(msg); 13777 } 13778 13779 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13780 PackageStats pStats) { 13781 if (packageName == null) { 13782 Slog.w(TAG, "Attempt to get size of null packageName."); 13783 return false; 13784 } 13785 PackageParser.Package p; 13786 boolean dataOnly = false; 13787 String libDirRoot = null; 13788 String asecPath = null; 13789 PackageSetting ps = null; 13790 synchronized (mPackages) { 13791 p = mPackages.get(packageName); 13792 ps = mSettings.mPackages.get(packageName); 13793 if(p == null) { 13794 dataOnly = true; 13795 if((ps == null) || (ps.pkg == null)) { 13796 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13797 return false; 13798 } 13799 p = ps.pkg; 13800 } 13801 if (ps != null) { 13802 libDirRoot = ps.legacyNativeLibraryPathString; 13803 } 13804 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13805 final long token = Binder.clearCallingIdentity(); 13806 try { 13807 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13808 if (secureContainerId != null) { 13809 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13810 } 13811 } finally { 13812 Binder.restoreCallingIdentity(token); 13813 } 13814 } 13815 } 13816 String publicSrcDir = null; 13817 if(!dataOnly) { 13818 final ApplicationInfo applicationInfo = p.applicationInfo; 13819 if (applicationInfo == null) { 13820 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13821 return false; 13822 } 13823 if (p.isForwardLocked()) { 13824 publicSrcDir = applicationInfo.getBaseResourcePath(); 13825 } 13826 } 13827 // TODO: extend to measure size of split APKs 13828 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13829 // not just the first level. 13830 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13831 // just the primary. 13832 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13833 13834 String apkPath; 13835 File packageDir = new File(p.codePath); 13836 13837 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13838 apkPath = packageDir.getAbsolutePath(); 13839 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13840 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13841 libDirRoot = null; 13842 } 13843 } else { 13844 apkPath = p.baseCodePath; 13845 } 13846 13847 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 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, 15748 UserHandle.SYSTEM); 15749 } catch (PackageManagerException e) { 15750 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15751 } 15752 // Scan the package 15753 if (pkg != null) { 15754 /* 15755 * TODO why is the lock being held? doPostInstall is 15756 * called in other places without the lock. This needs 15757 * to be straightened out. 15758 */ 15759 // writer 15760 synchronized (mPackages) { 15761 retCode = PackageManager.INSTALL_SUCCEEDED; 15762 pkgList.add(pkg.packageName); 15763 // Post process args 15764 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15765 pkg.applicationInfo.uid); 15766 } 15767 } else { 15768 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15769 } 15770 } 15771 15772 } finally { 15773 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15774 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15775 } 15776 } 15777 } 15778 // writer 15779 synchronized (mPackages) { 15780 // If the platform SDK has changed since the last time we booted, 15781 // we need to re-grant app permission to catch any new ones that 15782 // appear. This is really a hack, and means that apps can in some 15783 // cases get permissions that the user didn't initially explicitly 15784 // allow... it would be nice to have some better way to handle 15785 // this situation. 15786 final VersionInfo ver = mSettings.getExternalVersion(); 15787 15788 int updateFlags = UPDATE_PERMISSIONS_ALL; 15789 if (ver.sdkVersion != mSdkVersion) { 15790 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15791 + mSdkVersion + "; regranting permissions for external"); 15792 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15793 } 15794 updatePermissionsLPw(null, null, updateFlags); 15795 15796 // Yay, everything is now upgraded 15797 ver.forceCurrent(); 15798 15799 // can downgrade to reader 15800 // Persist settings 15801 mSettings.writeLPr(); 15802 } 15803 // Send a broadcast to let everyone know we are done processing 15804 if (pkgList.size() > 0) { 15805 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15806 } 15807 } 15808 15809 /* 15810 * Utility method to unload a list of specified containers 15811 */ 15812 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15813 // Just unmount all valid containers. 15814 for (AsecInstallArgs arg : cidArgs) { 15815 synchronized (mInstallLock) { 15816 arg.doPostDeleteLI(false); 15817 } 15818 } 15819 } 15820 15821 /* 15822 * Unload packages mounted on external media. This involves deleting package 15823 * data from internal structures, sending broadcasts about diabled packages, 15824 * gc'ing to free up references, unmounting all secure containers 15825 * corresponding to packages on external media, and posting a 15826 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15827 * that we always have to post this message if status has been requested no 15828 * matter what. 15829 */ 15830 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15831 final boolean reportStatus) { 15832 if (DEBUG_SD_INSTALL) 15833 Log.i(TAG, "unloading media packages"); 15834 ArrayList<String> pkgList = new ArrayList<String>(); 15835 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15836 final Set<AsecInstallArgs> keys = processCids.keySet(); 15837 for (AsecInstallArgs args : keys) { 15838 String pkgName = args.getPackageName(); 15839 if (DEBUG_SD_INSTALL) 15840 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15841 // Delete package internally 15842 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15843 synchronized (mInstallLock) { 15844 boolean res = deletePackageLI(pkgName, null, false, null, null, 15845 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15846 if (res) { 15847 pkgList.add(pkgName); 15848 } else { 15849 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15850 failedList.add(args); 15851 } 15852 } 15853 } 15854 15855 // reader 15856 synchronized (mPackages) { 15857 // We didn't update the settings after removing each package; 15858 // write them now for all packages. 15859 mSettings.writeLPr(); 15860 } 15861 15862 // We have to absolutely send UPDATED_MEDIA_STATUS only 15863 // after confirming that all the receivers processed the ordered 15864 // broadcast when packages get disabled, force a gc to clean things up. 15865 // and unload all the containers. 15866 if (pkgList.size() > 0) { 15867 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15868 new IIntentReceiver.Stub() { 15869 public void performReceive(Intent intent, int resultCode, String data, 15870 Bundle extras, boolean ordered, boolean sticky, 15871 int sendingUser) throws RemoteException { 15872 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15873 reportStatus ? 1 : 0, 1, keys); 15874 mHandler.sendMessage(msg); 15875 } 15876 }); 15877 } else { 15878 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15879 keys); 15880 mHandler.sendMessage(msg); 15881 } 15882 } 15883 15884 private void loadPrivatePackages(final VolumeInfo vol) { 15885 mHandler.post(new Runnable() { 15886 @Override 15887 public void run() { 15888 loadPrivatePackagesInner(vol); 15889 } 15890 }); 15891 } 15892 15893 private void loadPrivatePackagesInner(VolumeInfo vol) { 15894 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15895 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15896 15897 final VersionInfo ver; 15898 final List<PackageSetting> packages; 15899 synchronized (mPackages) { 15900 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15901 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15902 } 15903 15904 for (PackageSetting ps : packages) { 15905 synchronized (mInstallLock) { 15906 final PackageParser.Package pkg; 15907 try { 15908 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, 15909 UserHandle.SYSTEM); 15910 loaded.add(pkg.applicationInfo); 15911 } catch (PackageManagerException e) { 15912 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15913 } 15914 15915 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15916 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15917 } 15918 } 15919 } 15920 15921 synchronized (mPackages) { 15922 int updateFlags = UPDATE_PERMISSIONS_ALL; 15923 if (ver.sdkVersion != mSdkVersion) { 15924 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15925 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15926 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15927 } 15928 updatePermissionsLPw(null, null, updateFlags); 15929 15930 // Yay, everything is now upgraded 15931 ver.forceCurrent(); 15932 15933 mSettings.writeLPr(); 15934 } 15935 15936 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15937 sendResourcesChangedBroadcast(true, false, loaded, null); 15938 } 15939 15940 private void unloadPrivatePackages(final VolumeInfo vol) { 15941 mHandler.post(new Runnable() { 15942 @Override 15943 public void run() { 15944 unloadPrivatePackagesInner(vol); 15945 } 15946 }); 15947 } 15948 15949 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15950 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15951 synchronized (mInstallLock) { 15952 synchronized (mPackages) { 15953 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15954 for (PackageSetting ps : packages) { 15955 if (ps.pkg == null) continue; 15956 15957 final ApplicationInfo info = ps.pkg.applicationInfo; 15958 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15959 if (deletePackageLI(ps.name, null, false, null, null, 15960 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15961 unloaded.add(info); 15962 } else { 15963 Slog.w(TAG, "Failed to unload " + ps.codePath); 15964 } 15965 } 15966 15967 mSettings.writeLPr(); 15968 } 15969 } 15970 15971 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15972 sendResourcesChangedBroadcast(false, false, unloaded, null); 15973 } 15974 15975 /** 15976 * Examine all users present on given mounted volume, and destroy data 15977 * belonging to users that are no longer valid, or whose user ID has been 15978 * recycled. 15979 */ 15980 private void reconcileUsers(String volumeUuid) { 15981 final File[] files = FileUtils 15982 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15983 for (File file : files) { 15984 if (!file.isDirectory()) continue; 15985 15986 final int userId; 15987 final UserInfo info; 15988 try { 15989 userId = Integer.parseInt(file.getName()); 15990 info = sUserManager.getUserInfo(userId); 15991 } catch (NumberFormatException e) { 15992 Slog.w(TAG, "Invalid user directory " + file); 15993 continue; 15994 } 15995 15996 boolean destroyUser = false; 15997 if (info == null) { 15998 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15999 + " because no matching user was found"); 16000 destroyUser = true; 16001 } else { 16002 try { 16003 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16004 } catch (IOException e) { 16005 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16006 + " because we failed to enforce serial number: " + e); 16007 destroyUser = true; 16008 } 16009 } 16010 16011 if (destroyUser) { 16012 synchronized (mInstallLock) { 16013 mInstaller.removeUserDataDirs(volumeUuid, userId); 16014 } 16015 } 16016 } 16017 16018 final UserManager um = mContext.getSystemService(UserManager.class); 16019 for (UserInfo user : um.getUsers()) { 16020 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16021 if (userDir.exists()) continue; 16022 16023 try { 16024 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 16025 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16026 } catch (IOException e) { 16027 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16028 } 16029 } 16030 } 16031 16032 /** 16033 * Examine all apps present on given mounted volume, and destroy apps that 16034 * aren't expected, either due to uninstallation or reinstallation on 16035 * another volume. 16036 */ 16037 private void reconcileApps(String volumeUuid) { 16038 final File[] files = FileUtils 16039 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16040 for (File file : files) { 16041 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16042 && !PackageInstallerService.isStageName(file.getName()); 16043 if (!isPackage) { 16044 // Ignore entries which are not packages 16045 continue; 16046 } 16047 16048 boolean destroyApp = false; 16049 String packageName = null; 16050 try { 16051 final PackageLite pkg = PackageParser.parsePackageLite(file, 16052 PackageParser.PARSE_MUST_BE_APK); 16053 packageName = pkg.packageName; 16054 16055 synchronized (mPackages) { 16056 final PackageSetting ps = mSettings.mPackages.get(packageName); 16057 if (ps == null) { 16058 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16059 + volumeUuid + " because we found no install record"); 16060 destroyApp = true; 16061 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16062 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16063 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16064 destroyApp = true; 16065 } 16066 } 16067 16068 } catch (PackageParserException e) { 16069 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16070 destroyApp = true; 16071 } 16072 16073 if (destroyApp) { 16074 synchronized (mInstallLock) { 16075 if (packageName != null) { 16076 removeDataDirsLI(volumeUuid, packageName); 16077 } 16078 if (file.isDirectory()) { 16079 mInstaller.rmPackageDir(file.getAbsolutePath()); 16080 } else { 16081 file.delete(); 16082 } 16083 } 16084 } 16085 } 16086 } 16087 16088 private void unfreezePackage(String packageName) { 16089 synchronized (mPackages) { 16090 final PackageSetting ps = mSettings.mPackages.get(packageName); 16091 if (ps != null) { 16092 ps.frozen = false; 16093 } 16094 } 16095 } 16096 16097 @Override 16098 public int movePackage(final String packageName, final String volumeUuid) { 16099 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16100 16101 final int moveId = mNextMoveId.getAndIncrement(); 16102 try { 16103 movePackageInternal(packageName, volumeUuid, moveId); 16104 } catch (PackageManagerException e) { 16105 Slog.w(TAG, "Failed to move " + packageName, e); 16106 mMoveCallbacks.notifyStatusChanged(moveId, 16107 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16108 } 16109 return moveId; 16110 } 16111 16112 private void movePackageInternal(final String packageName, final String volumeUuid, 16113 final int moveId) throws PackageManagerException { 16114 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16115 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16116 final PackageManager pm = mContext.getPackageManager(); 16117 16118 final boolean currentAsec; 16119 final String currentVolumeUuid; 16120 final File codeFile; 16121 final String installerPackageName; 16122 final String packageAbiOverride; 16123 final int appId; 16124 final String seinfo; 16125 final String label; 16126 16127 // reader 16128 synchronized (mPackages) { 16129 final PackageParser.Package pkg = mPackages.get(packageName); 16130 final PackageSetting ps = mSettings.mPackages.get(packageName); 16131 if (pkg == null || ps == null) { 16132 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16133 } 16134 16135 if (pkg.applicationInfo.isSystemApp()) { 16136 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16137 "Cannot move system application"); 16138 } 16139 16140 if (pkg.applicationInfo.isExternalAsec()) { 16141 currentAsec = true; 16142 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16143 } else if (pkg.applicationInfo.isForwardLocked()) { 16144 currentAsec = true; 16145 currentVolumeUuid = "forward_locked"; 16146 } else { 16147 currentAsec = false; 16148 currentVolumeUuid = ps.volumeUuid; 16149 16150 final File probe = new File(pkg.codePath); 16151 final File probeOat = new File(probe, "oat"); 16152 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16153 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16154 "Move only supported for modern cluster style installs"); 16155 } 16156 } 16157 16158 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16159 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16160 "Package already moved to " + volumeUuid); 16161 } 16162 16163 if (ps.frozen) { 16164 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16165 "Failed to move already frozen package"); 16166 } 16167 ps.frozen = true; 16168 16169 codeFile = new File(pkg.codePath); 16170 installerPackageName = ps.installerPackageName; 16171 packageAbiOverride = ps.cpuAbiOverrideString; 16172 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16173 seinfo = pkg.applicationInfo.seinfo; 16174 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16175 } 16176 16177 // Now that we're guarded by frozen state, kill app during move 16178 final long token = Binder.clearCallingIdentity(); 16179 try { 16180 killApplication(packageName, appId, "move pkg"); 16181 } finally { 16182 Binder.restoreCallingIdentity(token); 16183 } 16184 16185 final Bundle extras = new Bundle(); 16186 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16187 extras.putString(Intent.EXTRA_TITLE, label); 16188 mMoveCallbacks.notifyCreated(moveId, extras); 16189 16190 int installFlags; 16191 final boolean moveCompleteApp; 16192 final File measurePath; 16193 16194 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16195 installFlags = INSTALL_INTERNAL; 16196 moveCompleteApp = !currentAsec; 16197 measurePath = Environment.getDataAppDirectory(volumeUuid); 16198 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16199 installFlags = INSTALL_EXTERNAL; 16200 moveCompleteApp = false; 16201 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16202 } else { 16203 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16204 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16205 || !volume.isMountedWritable()) { 16206 unfreezePackage(packageName); 16207 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16208 "Move location not mounted private volume"); 16209 } 16210 16211 Preconditions.checkState(!currentAsec); 16212 16213 installFlags = INSTALL_INTERNAL; 16214 moveCompleteApp = true; 16215 measurePath = Environment.getDataAppDirectory(volumeUuid); 16216 } 16217 16218 final PackageStats stats = new PackageStats(null, -1); 16219 synchronized (mInstaller) { 16220 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16221 unfreezePackage(packageName); 16222 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16223 "Failed to measure package size"); 16224 } 16225 } 16226 16227 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16228 + stats.dataSize); 16229 16230 final long startFreeBytes = measurePath.getFreeSpace(); 16231 final long sizeBytes; 16232 if (moveCompleteApp) { 16233 sizeBytes = stats.codeSize + stats.dataSize; 16234 } else { 16235 sizeBytes = stats.codeSize; 16236 } 16237 16238 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16239 unfreezePackage(packageName); 16240 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16241 "Not enough free space to move"); 16242 } 16243 16244 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16245 16246 final CountDownLatch installedLatch = new CountDownLatch(1); 16247 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16248 @Override 16249 public void onUserActionRequired(Intent intent) throws RemoteException { 16250 throw new IllegalStateException(); 16251 } 16252 16253 @Override 16254 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16255 Bundle extras) throws RemoteException { 16256 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16257 + PackageManager.installStatusToString(returnCode, msg)); 16258 16259 installedLatch.countDown(); 16260 16261 // Regardless of success or failure of the move operation, 16262 // always unfreeze the package 16263 unfreezePackage(packageName); 16264 16265 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16266 switch (status) { 16267 case PackageInstaller.STATUS_SUCCESS: 16268 mMoveCallbacks.notifyStatusChanged(moveId, 16269 PackageManager.MOVE_SUCCEEDED); 16270 break; 16271 case PackageInstaller.STATUS_FAILURE_STORAGE: 16272 mMoveCallbacks.notifyStatusChanged(moveId, 16273 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16274 break; 16275 default: 16276 mMoveCallbacks.notifyStatusChanged(moveId, 16277 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16278 break; 16279 } 16280 } 16281 }; 16282 16283 final MoveInfo move; 16284 if (moveCompleteApp) { 16285 // Kick off a thread to report progress estimates 16286 new Thread() { 16287 @Override 16288 public void run() { 16289 while (true) { 16290 try { 16291 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16292 break; 16293 } 16294 } catch (InterruptedException ignored) { 16295 } 16296 16297 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16298 final int progress = 10 + (int) MathUtils.constrain( 16299 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16300 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16301 } 16302 } 16303 }.start(); 16304 16305 final String dataAppName = codeFile.getName(); 16306 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16307 dataAppName, appId, seinfo); 16308 } else { 16309 move = null; 16310 } 16311 16312 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16313 16314 final Message msg = mHandler.obtainMessage(INIT_COPY); 16315 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16316 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16317 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16318 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16319 msg.obj = params; 16320 16321 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16322 System.identityHashCode(msg.obj)); 16323 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16324 System.identityHashCode(msg.obj)); 16325 16326 mHandler.sendMessage(msg); 16327 } 16328 16329 @Override 16330 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16331 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16332 16333 final int realMoveId = mNextMoveId.getAndIncrement(); 16334 final Bundle extras = new Bundle(); 16335 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16336 mMoveCallbacks.notifyCreated(realMoveId, extras); 16337 16338 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16339 @Override 16340 public void onCreated(int moveId, Bundle extras) { 16341 // Ignored 16342 } 16343 16344 @Override 16345 public void onStatusChanged(int moveId, int status, long estMillis) { 16346 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16347 } 16348 }; 16349 16350 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16351 storage.setPrimaryStorageUuid(volumeUuid, callback); 16352 return realMoveId; 16353 } 16354 16355 @Override 16356 public int getMoveStatus(int moveId) { 16357 mContext.enforceCallingOrSelfPermission( 16358 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16359 return mMoveCallbacks.mLastStatus.get(moveId); 16360 } 16361 16362 @Override 16363 public void registerMoveCallback(IPackageMoveObserver callback) { 16364 mContext.enforceCallingOrSelfPermission( 16365 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16366 mMoveCallbacks.register(callback); 16367 } 16368 16369 @Override 16370 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16371 mContext.enforceCallingOrSelfPermission( 16372 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16373 mMoveCallbacks.unregister(callback); 16374 } 16375 16376 @Override 16377 public boolean setInstallLocation(int loc) { 16378 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16379 null); 16380 if (getInstallLocation() == loc) { 16381 return true; 16382 } 16383 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16384 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16385 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16386 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16387 return true; 16388 } 16389 return false; 16390 } 16391 16392 @Override 16393 public int getInstallLocation() { 16394 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16395 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16396 PackageHelper.APP_INSTALL_AUTO); 16397 } 16398 16399 /** Called by UserManagerService */ 16400 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16401 mDirtyUsers.remove(userHandle); 16402 mSettings.removeUserLPw(userHandle); 16403 mPendingBroadcasts.remove(userHandle); 16404 if (mInstaller != null) { 16405 // Technically, we shouldn't be doing this with the package lock 16406 // held. However, this is very rare, and there is already so much 16407 // other disk I/O going on, that we'll let it slide for now. 16408 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16409 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16410 final String volumeUuid = vol.getFsUuid(); 16411 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16412 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16413 } 16414 } 16415 mUserNeedsBadging.delete(userHandle); 16416 removeUnusedPackagesLILPw(userManager, userHandle); 16417 } 16418 16419 /** 16420 * We're removing userHandle and would like to remove any downloaded packages 16421 * that are no longer in use by any other user. 16422 * @param userHandle the user being removed 16423 */ 16424 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16425 final boolean DEBUG_CLEAN_APKS = false; 16426 int [] users = userManager.getUserIdsLPr(); 16427 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16428 while (psit.hasNext()) { 16429 PackageSetting ps = psit.next(); 16430 if (ps.pkg == null) { 16431 continue; 16432 } 16433 final String packageName = ps.pkg.packageName; 16434 // Skip over if system app 16435 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16436 continue; 16437 } 16438 if (DEBUG_CLEAN_APKS) { 16439 Slog.i(TAG, "Checking package " + packageName); 16440 } 16441 boolean keep = false; 16442 for (int i = 0; i < users.length; i++) { 16443 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16444 keep = true; 16445 if (DEBUG_CLEAN_APKS) { 16446 Slog.i(TAG, " Keeping package " + packageName + " for user " 16447 + users[i]); 16448 } 16449 break; 16450 } 16451 } 16452 if (!keep) { 16453 if (DEBUG_CLEAN_APKS) { 16454 Slog.i(TAG, " Removing package " + packageName); 16455 } 16456 mHandler.post(new Runnable() { 16457 public void run() { 16458 deletePackageX(packageName, userHandle, 0); 16459 } //end run 16460 }); 16461 } 16462 } 16463 } 16464 16465 /** Called by UserManagerService */ 16466 void createNewUserLILPw(int userHandle) { 16467 if (mInstaller != null) { 16468 mInstaller.createUserConfig(userHandle); 16469 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16470 applyFactoryDefaultBrowserLPw(userHandle); 16471 primeDomainVerificationsLPw(userHandle); 16472 } 16473 } 16474 16475 void newUserCreated(final int userHandle) { 16476 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16477 } 16478 16479 @Override 16480 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16481 mContext.enforceCallingOrSelfPermission( 16482 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16483 "Only package verification agents can read the verifier device identity"); 16484 16485 synchronized (mPackages) { 16486 return mSettings.getVerifierDeviceIdentityLPw(); 16487 } 16488 } 16489 16490 @Override 16491 public void setPermissionEnforced(String permission, boolean enforced) { 16492 // TODO: Now that we no longer change GID for storage, this should to away. 16493 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16494 "setPermissionEnforced"); 16495 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16496 synchronized (mPackages) { 16497 if (mSettings.mReadExternalStorageEnforced == null 16498 || mSettings.mReadExternalStorageEnforced != enforced) { 16499 mSettings.mReadExternalStorageEnforced = enforced; 16500 mSettings.writeLPr(); 16501 } 16502 } 16503 // kill any non-foreground processes so we restart them and 16504 // grant/revoke the GID. 16505 final IActivityManager am = ActivityManagerNative.getDefault(); 16506 if (am != null) { 16507 final long token = Binder.clearCallingIdentity(); 16508 try { 16509 am.killProcessesBelowForeground("setPermissionEnforcement"); 16510 } catch (RemoteException e) { 16511 } finally { 16512 Binder.restoreCallingIdentity(token); 16513 } 16514 } 16515 } else { 16516 throw new IllegalArgumentException("No selective enforcement for " + permission); 16517 } 16518 } 16519 16520 @Override 16521 @Deprecated 16522 public boolean isPermissionEnforced(String permission) { 16523 return true; 16524 } 16525 16526 @Override 16527 public boolean isStorageLow() { 16528 final long token = Binder.clearCallingIdentity(); 16529 try { 16530 final DeviceStorageMonitorInternal 16531 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16532 if (dsm != null) { 16533 return dsm.isMemoryLow(); 16534 } else { 16535 return false; 16536 } 16537 } finally { 16538 Binder.restoreCallingIdentity(token); 16539 } 16540 } 16541 16542 @Override 16543 public IPackageInstaller getPackageInstaller() { 16544 return mInstallerService; 16545 } 16546 16547 private boolean userNeedsBadging(int userId) { 16548 int index = mUserNeedsBadging.indexOfKey(userId); 16549 if (index < 0) { 16550 final UserInfo userInfo; 16551 final long token = Binder.clearCallingIdentity(); 16552 try { 16553 userInfo = sUserManager.getUserInfo(userId); 16554 } finally { 16555 Binder.restoreCallingIdentity(token); 16556 } 16557 final boolean b; 16558 if (userInfo != null && userInfo.isManagedProfile()) { 16559 b = true; 16560 } else { 16561 b = false; 16562 } 16563 mUserNeedsBadging.put(userId, b); 16564 return b; 16565 } 16566 return mUserNeedsBadging.valueAt(index); 16567 } 16568 16569 @Override 16570 public KeySet getKeySetByAlias(String packageName, String alias) { 16571 if (packageName == null || alias == null) { 16572 return null; 16573 } 16574 synchronized(mPackages) { 16575 final PackageParser.Package pkg = mPackages.get(packageName); 16576 if (pkg == null) { 16577 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16578 throw new IllegalArgumentException("Unknown package: " + packageName); 16579 } 16580 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16581 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16582 } 16583 } 16584 16585 @Override 16586 public KeySet getSigningKeySet(String packageName) { 16587 if (packageName == null) { 16588 return null; 16589 } 16590 synchronized(mPackages) { 16591 final PackageParser.Package pkg = mPackages.get(packageName); 16592 if (pkg == null) { 16593 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16594 throw new IllegalArgumentException("Unknown package: " + packageName); 16595 } 16596 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16597 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16598 throw new SecurityException("May not access signing KeySet of other apps."); 16599 } 16600 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16601 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16602 } 16603 } 16604 16605 @Override 16606 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16607 if (packageName == null || ks == null) { 16608 return false; 16609 } 16610 synchronized(mPackages) { 16611 final PackageParser.Package pkg = mPackages.get(packageName); 16612 if (pkg == null) { 16613 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16614 throw new IllegalArgumentException("Unknown package: " + packageName); 16615 } 16616 IBinder ksh = ks.getToken(); 16617 if (ksh instanceof KeySetHandle) { 16618 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16619 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16620 } 16621 return false; 16622 } 16623 } 16624 16625 @Override 16626 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16627 if (packageName == null || ks == null) { 16628 return false; 16629 } 16630 synchronized(mPackages) { 16631 final PackageParser.Package pkg = mPackages.get(packageName); 16632 if (pkg == null) { 16633 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16634 throw new IllegalArgumentException("Unknown package: " + packageName); 16635 } 16636 IBinder ksh = ks.getToken(); 16637 if (ksh instanceof KeySetHandle) { 16638 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16639 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16640 } 16641 return false; 16642 } 16643 } 16644 16645 public void getUsageStatsIfNoPackageUsageInfo() { 16646 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16647 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16648 if (usm == null) { 16649 throw new IllegalStateException("UsageStatsManager must be initialized"); 16650 } 16651 long now = System.currentTimeMillis(); 16652 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16653 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16654 String packageName = entry.getKey(); 16655 PackageParser.Package pkg = mPackages.get(packageName); 16656 if (pkg == null) { 16657 continue; 16658 } 16659 UsageStats usage = entry.getValue(); 16660 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16661 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16662 } 16663 } 16664 } 16665 16666 /** 16667 * Check and throw if the given before/after packages would be considered a 16668 * downgrade. 16669 */ 16670 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16671 throws PackageManagerException { 16672 if (after.versionCode < before.mVersionCode) { 16673 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16674 "Update version code " + after.versionCode + " is older than current " 16675 + before.mVersionCode); 16676 } else if (after.versionCode == before.mVersionCode) { 16677 if (after.baseRevisionCode < before.baseRevisionCode) { 16678 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16679 "Update base revision code " + after.baseRevisionCode 16680 + " is older than current " + before.baseRevisionCode); 16681 } 16682 16683 if (!ArrayUtils.isEmpty(after.splitNames)) { 16684 for (int i = 0; i < after.splitNames.length; i++) { 16685 final String splitName = after.splitNames[i]; 16686 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16687 if (j != -1) { 16688 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16689 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16690 "Update split " + splitName + " revision code " 16691 + after.splitRevisionCodes[i] + " is older than current " 16692 + before.splitRevisionCodes[j]); 16693 } 16694 } 16695 } 16696 } 16697 } 16698 } 16699 16700 private static class MoveCallbacks extends Handler { 16701 private static final int MSG_CREATED = 1; 16702 private static final int MSG_STATUS_CHANGED = 2; 16703 16704 private final RemoteCallbackList<IPackageMoveObserver> 16705 mCallbacks = new RemoteCallbackList<>(); 16706 16707 private final SparseIntArray mLastStatus = new SparseIntArray(); 16708 16709 public MoveCallbacks(Looper looper) { 16710 super(looper); 16711 } 16712 16713 public void register(IPackageMoveObserver callback) { 16714 mCallbacks.register(callback); 16715 } 16716 16717 public void unregister(IPackageMoveObserver callback) { 16718 mCallbacks.unregister(callback); 16719 } 16720 16721 @Override 16722 public void handleMessage(Message msg) { 16723 final SomeArgs args = (SomeArgs) msg.obj; 16724 final int n = mCallbacks.beginBroadcast(); 16725 for (int i = 0; i < n; i++) { 16726 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16727 try { 16728 invokeCallback(callback, msg.what, args); 16729 } catch (RemoteException ignored) { 16730 } 16731 } 16732 mCallbacks.finishBroadcast(); 16733 args.recycle(); 16734 } 16735 16736 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16737 throws RemoteException { 16738 switch (what) { 16739 case MSG_CREATED: { 16740 callback.onCreated(args.argi1, (Bundle) args.arg2); 16741 break; 16742 } 16743 case MSG_STATUS_CHANGED: { 16744 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16745 break; 16746 } 16747 } 16748 } 16749 16750 private void notifyCreated(int moveId, Bundle extras) { 16751 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16752 16753 final SomeArgs args = SomeArgs.obtain(); 16754 args.argi1 = moveId; 16755 args.arg2 = extras; 16756 obtainMessage(MSG_CREATED, args).sendToTarget(); 16757 } 16758 16759 private void notifyStatusChanged(int moveId, int status) { 16760 notifyStatusChanged(moveId, status, -1); 16761 } 16762 16763 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16764 Slog.v(TAG, "Move " + moveId + " status " + status); 16765 16766 final SomeArgs args = SomeArgs.obtain(); 16767 args.argi1 = moveId; 16768 args.argi2 = status; 16769 args.arg3 = estMillis; 16770 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16771 16772 synchronized (mLastStatus) { 16773 mLastStatus.put(moveId, status); 16774 } 16775 } 16776 } 16777 16778 private final class OnPermissionChangeListeners extends Handler { 16779 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16780 16781 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16782 new RemoteCallbackList<>(); 16783 16784 public OnPermissionChangeListeners(Looper looper) { 16785 super(looper); 16786 } 16787 16788 @Override 16789 public void handleMessage(Message msg) { 16790 switch (msg.what) { 16791 case MSG_ON_PERMISSIONS_CHANGED: { 16792 final int uid = msg.arg1; 16793 handleOnPermissionsChanged(uid); 16794 } break; 16795 } 16796 } 16797 16798 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16799 mPermissionListeners.register(listener); 16800 16801 } 16802 16803 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16804 mPermissionListeners.unregister(listener); 16805 } 16806 16807 public void onPermissionsChanged(int uid) { 16808 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16809 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16810 } 16811 } 16812 16813 private void handleOnPermissionsChanged(int uid) { 16814 final int count = mPermissionListeners.beginBroadcast(); 16815 try { 16816 for (int i = 0; i < count; i++) { 16817 IOnPermissionsChangeListener callback = mPermissionListeners 16818 .getBroadcastItem(i); 16819 try { 16820 callback.onPermissionsChanged(uid); 16821 } catch (RemoteException e) { 16822 Log.e(TAG, "Permission listener is dead", e); 16823 } 16824 } 16825 } finally { 16826 mPermissionListeners.finishBroadcast(); 16827 } 16828 } 16829 } 16830 16831 private class PackageManagerInternalImpl extends PackageManagerInternal { 16832 @Override 16833 public void setLocationPackagesProvider(PackagesProvider provider) { 16834 synchronized (mPackages) { 16835 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16836 } 16837 } 16838 16839 @Override 16840 public void setImePackagesProvider(PackagesProvider provider) { 16841 synchronized (mPackages) { 16842 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16843 } 16844 } 16845 16846 @Override 16847 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16848 synchronized (mPackages) { 16849 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16850 } 16851 } 16852 16853 @Override 16854 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16855 synchronized (mPackages) { 16856 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16857 } 16858 } 16859 16860 @Override 16861 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16862 synchronized (mPackages) { 16863 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16864 } 16865 } 16866 16867 @Override 16868 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16869 synchronized (mPackages) { 16870 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16871 } 16872 } 16873 16874 @Override 16875 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16876 synchronized (mPackages) { 16877 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16878 } 16879 } 16880 16881 @Override 16882 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16883 synchronized (mPackages) { 16884 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16885 packageName, userId); 16886 } 16887 } 16888 16889 @Override 16890 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16891 synchronized (mPackages) { 16892 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16893 packageName, userId); 16894 } 16895 } 16896 @Override 16897 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16898 synchronized (mPackages) { 16899 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16900 packageName, userId); 16901 } 16902 } 16903 } 16904 16905 @Override 16906 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16907 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16908 synchronized (mPackages) { 16909 final long identity = Binder.clearCallingIdentity(); 16910 try { 16911 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16912 packageNames, userId); 16913 } finally { 16914 Binder.restoreCallingIdentity(identity); 16915 } 16916 } 16917 } 16918 16919 private static void enforceSystemOrPhoneCaller(String tag) { 16920 int callingUid = Binder.getCallingUid(); 16921 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16922 throw new SecurityException( 16923 "Cannot call " + tag + " from UID " + callingUid); 16924 } 16925 } 16926} 16927