PackageManagerService.java revision 1682dad7ed303fc43a07e70d0bb5cb42103a7624
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.AppsQueryHelper; 109import android.content.pm.FeatureInfo; 110import android.content.pm.IOnPermissionsChangeListener; 111import android.content.pm.IPackageDataObserver; 112import android.content.pm.IPackageDeleteObserver; 113import android.content.pm.IPackageDeleteObserver2; 114import android.content.pm.IPackageInstallObserver2; 115import android.content.pm.IPackageInstaller; 116import android.content.pm.IPackageManager; 117import android.content.pm.IPackageMoveObserver; 118import android.content.pm.IPackageStatsObserver; 119import android.content.pm.InstrumentationInfo; 120import android.content.pm.IntentFilterVerificationInfo; 121import android.content.pm.KeySet; 122import android.content.pm.ManifestDigest; 123import android.content.pm.PackageCleanItem; 124import android.content.pm.PackageInfo; 125import android.content.pm.PackageInfoLite; 126import android.content.pm.PackageInstaller; 127import android.content.pm.PackageManager; 128import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 129import android.content.pm.PackageManagerInternal; 130import android.content.pm.PackageParser; 131import android.content.pm.PackageParser.ActivityIntentInfo; 132import android.content.pm.PackageParser.PackageLite; 133import android.content.pm.PackageParser.PackageParserException; 134import android.content.pm.PackageStats; 135import android.content.pm.PackageUserState; 136import android.content.pm.ParceledListSlice; 137import android.content.pm.PermissionGroupInfo; 138import android.content.pm.PermissionInfo; 139import android.content.pm.ProviderInfo; 140import android.content.pm.ResolveInfo; 141import android.content.pm.ServiceInfo; 142import android.content.pm.Signature; 143import android.content.pm.UserInfo; 144import android.content.pm.VerificationParams; 145import android.content.pm.VerifierDeviceIdentity; 146import android.content.pm.VerifierInfo; 147import android.content.res.Resources; 148import android.hardware.display.DisplayManager; 149import android.net.Uri; 150import android.os.Debug; 151import android.os.Binder; 152import android.os.Build; 153import android.os.Bundle; 154import android.os.Environment; 155import android.os.Environment.UserEnvironment; 156import android.os.FileUtils; 157import android.os.Handler; 158import android.os.IBinder; 159import android.os.Looper; 160import android.os.Message; 161import android.os.Parcel; 162import android.os.ParcelFileDescriptor; 163import android.os.Process; 164import android.os.RemoteCallbackList; 165import android.os.RemoteException; 166import android.os.ResultReceiver; 167import android.os.SELinux; 168import android.os.ServiceManager; 169import android.os.SystemClock; 170import android.os.SystemProperties; 171import android.os.Trace; 172import android.os.UserHandle; 173import android.os.UserManager; 174import android.os.storage.IMountService; 175import android.os.storage.MountServiceInternal; 176import android.os.storage.StorageEventListener; 177import android.os.storage.StorageManager; 178import android.os.storage.VolumeInfo; 179import android.os.storage.VolumeRecord; 180import android.security.KeyStore; 181import android.security.SystemKeyStore; 182import android.system.ErrnoException; 183import android.system.Os; 184import android.system.StructStat; 185import android.text.TextUtils; 186import android.text.format.DateUtils; 187import android.util.ArrayMap; 188import android.util.ArraySet; 189import android.util.AtomicFile; 190import android.util.DisplayMetrics; 191import android.util.EventLog; 192import android.util.ExceptionUtils; 193import android.util.Log; 194import android.util.LogPrinter; 195import android.util.MathUtils; 196import android.util.PrintStreamPrinter; 197import android.util.Slog; 198import android.util.SparseArray; 199import android.util.SparseBooleanArray; 200import android.util.SparseIntArray; 201import android.util.Xml; 202import android.view.Display; 203 204import dalvik.system.DexFile; 205import dalvik.system.VMRuntime; 206 207import libcore.io.IoUtils; 208import libcore.util.EmptyArray; 209 210import com.android.internal.R; 211import com.android.internal.annotations.GuardedBy; 212import com.android.internal.app.IMediaContainerService; 213import com.android.internal.app.ResolverActivity; 214import com.android.internal.content.NativeLibraryHelper; 215import com.android.internal.content.PackageHelper; 216import com.android.internal.os.IParcelFileDescriptorFactory; 217import com.android.internal.os.SomeArgs; 218import com.android.internal.os.Zygote; 219import com.android.internal.util.ArrayUtils; 220import com.android.internal.util.FastPrintWriter; 221import com.android.internal.util.FastXmlSerializer; 222import com.android.internal.util.IndentingPrintWriter; 223import com.android.internal.util.Preconditions; 224import com.android.server.EventLogTags; 225import com.android.server.FgThread; 226import com.android.server.IntentResolver; 227import com.android.server.LocalServices; 228import com.android.server.ServiceThread; 229import com.android.server.SystemConfig; 230import com.android.server.Watchdog; 231import com.android.server.pm.PermissionsState.PermissionState; 232import com.android.server.pm.Settings.DatabaseVersion; 233import com.android.server.pm.Settings.VersionInfo; 234import com.android.server.storage.DeviceStorageMonitorInternal; 235 236import org.xmlpull.v1.XmlPullParser; 237import org.xmlpull.v1.XmlPullParserException; 238import org.xmlpull.v1.XmlSerializer; 239 240import java.io.BufferedInputStream; 241import java.io.BufferedOutputStream; 242import java.io.BufferedReader; 243import java.io.ByteArrayInputStream; 244import java.io.ByteArrayOutputStream; 245import java.io.File; 246import java.io.FileDescriptor; 247import java.io.FileNotFoundException; 248import java.io.FileOutputStream; 249import java.io.FileReader; 250import java.io.FilenameFilter; 251import java.io.IOException; 252import java.io.InputStream; 253import java.io.PrintWriter; 254import java.nio.charset.StandardCharsets; 255import java.security.NoSuchAlgorithmException; 256import java.security.PublicKey; 257import java.security.cert.CertificateEncodingException; 258import java.security.cert.CertificateException; 259import java.text.SimpleDateFormat; 260import java.util.ArrayList; 261import java.util.Arrays; 262import java.util.Collection; 263import java.util.Collections; 264import java.util.Comparator; 265import java.util.Date; 266import java.util.Iterator; 267import java.util.List; 268import java.util.Map; 269import java.util.Objects; 270import java.util.Set; 271import java.util.concurrent.CountDownLatch; 272import java.util.concurrent.TimeUnit; 273import java.util.concurrent.atomic.AtomicBoolean; 274import java.util.concurrent.atomic.AtomicInteger; 275import java.util.concurrent.atomic.AtomicLong; 276 277/** 278 * Keep track of all those .apks everywhere. 279 * 280 * This is very central to the platform's security; please run the unit 281 * tests whenever making modifications here: 282 * 283runtest -c android.content.pm.PackageManagerTests frameworks-core 284 * 285 * {@hide} 286 */ 287public class PackageManagerService extends IPackageManager.Stub { 288 static final String TAG = "PackageManager"; 289 static final boolean DEBUG_SETTINGS = false; 290 static final boolean DEBUG_PREFERRED = false; 291 static final boolean DEBUG_UPGRADE = false; 292 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 293 private static final boolean DEBUG_BACKUP = false; 294 private static final boolean DEBUG_INSTALL = false; 295 private static final boolean DEBUG_REMOVE = false; 296 private static final boolean DEBUG_BROADCASTS = false; 297 private static final boolean DEBUG_SHOW_INFO = false; 298 private static final boolean DEBUG_PACKAGE_INFO = false; 299 private static final boolean DEBUG_INTENT_MATCHING = false; 300 private static final boolean DEBUG_PACKAGE_SCANNING = false; 301 private static final boolean DEBUG_VERIFY = false; 302 private static final boolean DEBUG_DEXOPT = false; 303 private static final boolean DEBUG_ABI_SELECTION = false; 304 305 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 306 307 private static final int RADIO_UID = Process.PHONE_UID; 308 private static final int LOG_UID = Process.LOG_UID; 309 private static final int NFC_UID = Process.NFC_UID; 310 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 311 private static final int SHELL_UID = Process.SHELL_UID; 312 313 // Cap the size of permission trees that 3rd party apps can define 314 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 315 316 // Suffix used during package installation when copying/moving 317 // package apks to install directory. 318 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 319 320 static final int SCAN_NO_DEX = 1<<1; 321 static final int SCAN_FORCE_DEX = 1<<2; 322 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 323 static final int SCAN_NEW_INSTALL = 1<<4; 324 static final int SCAN_NO_PATHS = 1<<5; 325 static final int SCAN_UPDATE_TIME = 1<<6; 326 static final int SCAN_DEFER_DEX = 1<<7; 327 static final int SCAN_BOOTING = 1<<8; 328 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 329 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 330 static final int SCAN_REPLACING = 1<<11; 331 static final int SCAN_REQUIRE_KNOWN = 1<<12; 332 static final int SCAN_MOVE = 1<<13; 333 static final int SCAN_INITIAL = 1<<14; 334 335 static final int REMOVE_CHATTY = 1<<16; 336 337 private static final int[] EMPTY_INT_ARRAY = new int[0]; 338 339 /** 340 * Timeout (in milliseconds) after which the watchdog should declare that 341 * our handler thread is wedged. The usual default for such things is one 342 * minute but we sometimes do very lengthy I/O operations on this thread, 343 * such as installing multi-gigabyte applications, so ours needs to be longer. 344 */ 345 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 346 347 /** 348 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 349 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 350 * settings entry if available, otherwise we use the hardcoded default. If it's been 351 * more than this long since the last fstrim, we force one during the boot sequence. 352 * 353 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 354 * one gets run at the next available charging+idle time. This final mandatory 355 * no-fstrim check kicks in only of the other scheduling criteria is never met. 356 */ 357 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 358 359 /** 360 * Whether verification is enabled by default. 361 */ 362 private static final boolean DEFAULT_VERIFY_ENABLE = true; 363 364 /** 365 * The default maximum time to wait for the verification agent to return in 366 * milliseconds. 367 */ 368 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 369 370 /** 371 * The default response for package verification timeout. 372 * 373 * This can be either PackageManager.VERIFICATION_ALLOW or 374 * PackageManager.VERIFICATION_REJECT. 375 */ 376 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 377 378 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 379 380 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 381 DEFAULT_CONTAINER_PACKAGE, 382 "com.android.defcontainer.DefaultContainerService"); 383 384 private static final String KILL_APP_REASON_GIDS_CHANGED = 385 "permission grant or revoke changed gids"; 386 387 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 388 "permissions revoked"; 389 390 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 391 392 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 393 394 /** Permission grant: not grant the permission. */ 395 private static final int GRANT_DENIED = 1; 396 397 /** Permission grant: grant the permission as an install permission. */ 398 private static final int GRANT_INSTALL = 2; 399 400 /** Permission grant: grant the permission as an install permission for a legacy app. */ 401 private static final int GRANT_INSTALL_LEGACY = 3; 402 403 /** Permission grant: grant the permission as a runtime one. */ 404 private static final int GRANT_RUNTIME = 4; 405 406 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 407 private static final int GRANT_UPGRADE = 5; 408 409 /** Canonical intent used to identify what counts as a "web browser" app */ 410 private static final Intent sBrowserIntent; 411 static { 412 sBrowserIntent = new Intent(); 413 sBrowserIntent.setAction(Intent.ACTION_VIEW); 414 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 415 sBrowserIntent.setData(Uri.parse("http:")); 416 } 417 418 final ServiceThread mHandlerThread; 419 420 final PackageHandler mHandler; 421 422 /** 423 * Messages for {@link #mHandler} that need to wait for system ready before 424 * being dispatched. 425 */ 426 private ArrayList<Message> mPostSystemReadyMessages; 427 428 final int mSdkVersion = Build.VERSION.SDK_INT; 429 430 final Context mContext; 431 final boolean mFactoryTest; 432 final boolean mOnlyCore; 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 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1757 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1758 1759 synchronized (mPackages) { 1760 for (String permission : pkg.requestedPermissions) { 1761 BasePermission bp = mSettings.mPermissions.get(permission); 1762 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1763 && (grantedPermissions == null 1764 || ArrayUtils.contains(grantedPermissions, permission))) { 1765 final int flags = permissionsState.getPermissionFlags(permission, userId); 1766 // Installer cannot change immutable permissions. 1767 if ((flags & immutableFlags) == 0) { 1768 grantRuntimePermission(pkg.packageName, permission, userId); 1769 } 1770 } 1771 } 1772 } 1773 } 1774 1775 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1776 Bundle extras = null; 1777 switch (res.returnCode) { 1778 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1779 extras = new Bundle(); 1780 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1781 res.origPermission); 1782 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1783 res.origPackage); 1784 break; 1785 } 1786 case PackageManager.INSTALL_SUCCEEDED: { 1787 extras = new Bundle(); 1788 extras.putBoolean(Intent.EXTRA_REPLACING, 1789 res.removedInfo != null && res.removedInfo.removedPackage != null); 1790 break; 1791 } 1792 } 1793 return extras; 1794 } 1795 1796 void scheduleWriteSettingsLocked() { 1797 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1798 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1799 } 1800 } 1801 1802 void scheduleWritePackageRestrictionsLocked(int userId) { 1803 if (!sUserManager.exists(userId)) return; 1804 mDirtyUsers.add(userId); 1805 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1806 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1807 } 1808 } 1809 1810 public static PackageManagerService main(Context context, Installer installer, 1811 boolean factoryTest, boolean onlyCore) { 1812 PackageManagerService m = new PackageManagerService(context, installer, 1813 factoryTest, onlyCore); 1814 m.enableSystemUserApps(); 1815 ServiceManager.addService("package", m); 1816 return m; 1817 } 1818 1819 private void enableSystemUserApps() { 1820 if (!UserManager.isSplitSystemUser()) { 1821 return; 1822 } 1823 // For system user, enable apps based on the following conditions: 1824 // - app is whitelisted or belong to one of these groups: 1825 // -- system app which has no launcher icons 1826 // -- system app which has INTERACT_ACROSS_USERS permission 1827 // -- system IME app 1828 // - app is not in the blacklist 1829 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1830 Set<String> enableApps = new ArraySet<>(); 1831 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1832 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1833 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1834 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1835 enableApps.addAll(wlApps); 1836 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1837 enableApps.removeAll(blApps); 1838 1839 List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true, 1840 UserHandle.SYSTEM); 1841 final int systemAppsSize = systemApps.size(); 1842 synchronized (mPackages) { 1843 for (int i = 0; i < systemAppsSize; i++) { 1844 String pName = systemApps.get(i); 1845 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1846 // Should not happen, but we shouldn't be failing if it does 1847 if (pkgSetting == null) { 1848 continue; 1849 } 1850 boolean installed = enableApps.contains(pName); 1851 pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM); 1852 } 1853 } 1854 } 1855 1856 static String[] splitString(String str, char sep) { 1857 int count = 1; 1858 int i = 0; 1859 while ((i=str.indexOf(sep, i)) >= 0) { 1860 count++; 1861 i++; 1862 } 1863 1864 String[] res = new String[count]; 1865 i=0; 1866 count = 0; 1867 int lastI=0; 1868 while ((i=str.indexOf(sep, i)) >= 0) { 1869 res[count] = str.substring(lastI, i); 1870 count++; 1871 i++; 1872 lastI = i; 1873 } 1874 res[count] = str.substring(lastI, str.length()); 1875 return res; 1876 } 1877 1878 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1879 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1880 Context.DISPLAY_SERVICE); 1881 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1882 } 1883 1884 public PackageManagerService(Context context, Installer installer, 1885 boolean factoryTest, boolean onlyCore) { 1886 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1887 SystemClock.uptimeMillis()); 1888 1889 if (mSdkVersion <= 0) { 1890 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1891 } 1892 1893 mContext = context; 1894 mFactoryTest = factoryTest; 1895 mOnlyCore = onlyCore; 1896 mMetrics = new DisplayMetrics(); 1897 mSettings = new Settings(mPackages); 1898 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1899 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1900 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1901 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1902 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1903 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1904 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1905 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1906 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1907 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1908 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1909 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1910 1911 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1912 if (separateProcesses != null && separateProcesses.length() > 0) { 1913 if ("*".equals(separateProcesses)) { 1914 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1915 mSeparateProcesses = null; 1916 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1917 } else { 1918 mDefParseFlags = 0; 1919 mSeparateProcesses = separateProcesses.split(","); 1920 Slog.w(TAG, "Running with debug.separate_processes: " 1921 + separateProcesses); 1922 } 1923 } else { 1924 mDefParseFlags = 0; 1925 mSeparateProcesses = null; 1926 } 1927 1928 mInstaller = installer; 1929 mPackageDexOptimizer = new PackageDexOptimizer(this); 1930 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1931 1932 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1933 FgThread.get().getLooper()); 1934 1935 getDefaultDisplayMetrics(context, mMetrics); 1936 1937 SystemConfig systemConfig = SystemConfig.getInstance(); 1938 mGlobalGids = systemConfig.getGlobalGids(); 1939 mSystemPermissions = systemConfig.getSystemPermissions(); 1940 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1941 1942 synchronized (mInstallLock) { 1943 // writer 1944 synchronized (mPackages) { 1945 mHandlerThread = new ServiceThread(TAG, 1946 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1947 mHandlerThread.start(); 1948 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1949 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1950 1951 File dataDir = Environment.getDataDirectory(); 1952 mAppDataDir = new File(dataDir, "data"); 1953 mAppInstallDir = new File(dataDir, "app"); 1954 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1955 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1956 mUserAppDataDir = new File(dataDir, "user"); 1957 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1958 1959 sUserManager = new UserManagerService(context, this, 1960 mInstallLock, mPackages); 1961 1962 // Propagate permission configuration in to package manager. 1963 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1964 = systemConfig.getPermissions(); 1965 for (int i=0; i<permConfig.size(); i++) { 1966 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1967 BasePermission bp = mSettings.mPermissions.get(perm.name); 1968 if (bp == null) { 1969 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1970 mSettings.mPermissions.put(perm.name, bp); 1971 } 1972 if (perm.gids != null) { 1973 bp.setGids(perm.gids, perm.perUser); 1974 } 1975 } 1976 1977 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1978 for (int i=0; i<libConfig.size(); i++) { 1979 mSharedLibraries.put(libConfig.keyAt(i), 1980 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1981 } 1982 1983 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1984 1985 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1986 1987 String customResolverActivity = Resources.getSystem().getString( 1988 R.string.config_customResolverActivity); 1989 if (TextUtils.isEmpty(customResolverActivity)) { 1990 customResolverActivity = null; 1991 } else { 1992 mCustomResolverComponentName = ComponentName.unflattenFromString( 1993 customResolverActivity); 1994 } 1995 1996 long startTime = SystemClock.uptimeMillis(); 1997 1998 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1999 startTime); 2000 2001 // Set flag to monitor and not change apk file paths when 2002 // scanning install directories. 2003 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2004 2005 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2006 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2007 2008 if (bootClassPath == null) { 2009 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2010 } 2011 2012 if (systemServerClassPath == null) { 2013 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2014 } 2015 2016 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2017 final String[] dexCodeInstructionSets = 2018 getDexCodeInstructionSets( 2019 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2020 2021 /** 2022 * Ensure all external libraries have had dexopt run on them. 2023 */ 2024 if (mSharedLibraries.size() > 0) { 2025 // NOTE: For now, we're compiling these system "shared libraries" 2026 // (and framework jars) into all available architectures. It's possible 2027 // to compile them only when we come across an app that uses them (there's 2028 // already logic for that in scanPackageLI) but that adds some complexity. 2029 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2030 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2031 final String lib = libEntry.path; 2032 if (lib == null) { 2033 continue; 2034 } 2035 2036 try { 2037 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2038 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2039 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2040 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2041 } 2042 } catch (FileNotFoundException e) { 2043 Slog.w(TAG, "Library not found: " + lib); 2044 } catch (IOException e) { 2045 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2046 + e.getMessage()); 2047 } 2048 } 2049 } 2050 } 2051 2052 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2053 2054 final VersionInfo ver = mSettings.getInternalVersion(); 2055 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2056 // when upgrading from pre-M, promote system app permissions from install to runtime 2057 mPromoteSystemApps = 2058 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2059 2060 // save off the names of pre-existing system packages prior to scanning; we don't 2061 // want to automatically grant runtime permissions for new system apps 2062 if (mPromoteSystemApps) { 2063 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2064 while (pkgSettingIter.hasNext()) { 2065 PackageSetting ps = pkgSettingIter.next(); 2066 if (isSystemApp(ps)) { 2067 mExistingSystemPackages.add(ps.name); 2068 } 2069 } 2070 } 2071 2072 // Collect vendor overlay packages. 2073 // (Do this before scanning any apps.) 2074 // For security and version matching reason, only consider 2075 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2076 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2077 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2078 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2079 2080 // Find base frameworks (resource packages without code). 2081 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2082 | PackageParser.PARSE_IS_SYSTEM_DIR 2083 | PackageParser.PARSE_IS_PRIVILEGED, 2084 scanFlags | SCAN_NO_DEX, 0); 2085 2086 // Collected privileged system packages. 2087 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2088 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2089 | PackageParser.PARSE_IS_SYSTEM_DIR 2090 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2091 2092 // Collect ordinary system packages. 2093 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2094 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2095 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2096 2097 // Collect all vendor packages. 2098 File vendorAppDir = new File("/vendor/app"); 2099 try { 2100 vendorAppDir = vendorAppDir.getCanonicalFile(); 2101 } catch (IOException e) { 2102 // failed to look up canonical path, continue with original one 2103 } 2104 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2105 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2106 2107 // Collect all OEM packages. 2108 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2109 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2110 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2111 2112 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2113 mInstaller.moveFiles(); 2114 2115 // Prune any system packages that no longer exist. 2116 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2117 if (!mOnlyCore) { 2118 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2119 while (psit.hasNext()) { 2120 PackageSetting ps = psit.next(); 2121 2122 /* 2123 * If this is not a system app, it can't be a 2124 * disable system app. 2125 */ 2126 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2127 continue; 2128 } 2129 2130 /* 2131 * If the package is scanned, it's not erased. 2132 */ 2133 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2134 if (scannedPkg != null) { 2135 /* 2136 * If the system app is both scanned and in the 2137 * disabled packages list, then it must have been 2138 * added via OTA. Remove it from the currently 2139 * scanned package so the previously user-installed 2140 * application can be scanned. 2141 */ 2142 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2143 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2144 + ps.name + "; removing system app. Last known codePath=" 2145 + ps.codePathString + ", installStatus=" + ps.installStatus 2146 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2147 + scannedPkg.mVersionCode); 2148 removePackageLI(ps, true); 2149 mExpectingBetter.put(ps.name, ps.codePath); 2150 } 2151 2152 continue; 2153 } 2154 2155 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2156 psit.remove(); 2157 logCriticalInfo(Log.WARN, "System package " + ps.name 2158 + " no longer exists; wiping its data"); 2159 removeDataDirsLI(null, ps.name); 2160 } else { 2161 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2162 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2163 possiblyDeletedUpdatedSystemApps.add(ps.name); 2164 } 2165 } 2166 } 2167 } 2168 2169 //look for any incomplete package installations 2170 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2171 //clean up list 2172 for(int i = 0; i < deletePkgsList.size(); i++) { 2173 //clean up here 2174 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2175 } 2176 //delete tmp files 2177 deleteTempPackageFiles(); 2178 2179 // Remove any shared userIDs that have no associated packages 2180 mSettings.pruneSharedUsersLPw(); 2181 2182 if (!mOnlyCore) { 2183 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2184 SystemClock.uptimeMillis()); 2185 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2186 2187 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2188 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2189 2190 /** 2191 * Remove disable package settings for any updated system 2192 * apps that were removed via an OTA. If they're not a 2193 * previously-updated app, remove them completely. 2194 * Otherwise, just revoke their system-level permissions. 2195 */ 2196 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2197 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2198 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2199 2200 String msg; 2201 if (deletedPkg == null) { 2202 msg = "Updated system package " + deletedAppName 2203 + " no longer exists; wiping its data"; 2204 removeDataDirsLI(null, deletedAppName); 2205 } else { 2206 msg = "Updated system app + " + deletedAppName 2207 + " no longer present; removing system privileges for " 2208 + deletedAppName; 2209 2210 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2211 2212 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2213 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2214 } 2215 logCriticalInfo(Log.WARN, msg); 2216 } 2217 2218 /** 2219 * Make sure all system apps that we expected to appear on 2220 * the userdata partition actually showed up. If they never 2221 * appeared, crawl back and revive the system version. 2222 */ 2223 for (int i = 0; i < mExpectingBetter.size(); i++) { 2224 final String packageName = mExpectingBetter.keyAt(i); 2225 if (!mPackages.containsKey(packageName)) { 2226 final File scanFile = mExpectingBetter.valueAt(i); 2227 2228 logCriticalInfo(Log.WARN, "Expected better " + packageName 2229 + " but never showed up; reverting to system"); 2230 2231 final int reparseFlags; 2232 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2233 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2234 | PackageParser.PARSE_IS_SYSTEM_DIR 2235 | PackageParser.PARSE_IS_PRIVILEGED; 2236 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2237 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2238 | PackageParser.PARSE_IS_SYSTEM_DIR; 2239 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2240 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2241 | PackageParser.PARSE_IS_SYSTEM_DIR; 2242 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2243 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2244 | PackageParser.PARSE_IS_SYSTEM_DIR; 2245 } else { 2246 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2247 continue; 2248 } 2249 2250 mSettings.enableSystemPackageLPw(packageName); 2251 2252 try { 2253 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2254 } catch (PackageManagerException e) { 2255 Slog.e(TAG, "Failed to parse original system package: " 2256 + e.getMessage()); 2257 } 2258 } 2259 } 2260 } 2261 mExpectingBetter.clear(); 2262 2263 // Now that we know all of the shared libraries, update all clients to have 2264 // the correct library paths. 2265 updateAllSharedLibrariesLPw(); 2266 2267 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2268 // NOTE: We ignore potential failures here during a system scan (like 2269 // the rest of the commands above) because there's precious little we 2270 // can do about it. A settings error is reported, though. 2271 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2272 false /* boot complete */); 2273 } 2274 2275 // Now that we know all the packages we are keeping, 2276 // read and update their last usage times. 2277 mPackageUsage.readLP(); 2278 2279 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2280 SystemClock.uptimeMillis()); 2281 Slog.i(TAG, "Time to scan packages: " 2282 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2283 + " seconds"); 2284 2285 // If the platform SDK has changed since the last time we booted, 2286 // we need to re-grant app permission to catch any new ones that 2287 // appear. This is really a hack, and means that apps can in some 2288 // cases get permissions that the user didn't initially explicitly 2289 // allow... it would be nice to have some better way to handle 2290 // this situation. 2291 int updateFlags = UPDATE_PERMISSIONS_ALL; 2292 if (ver.sdkVersion != mSdkVersion) { 2293 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2294 + mSdkVersion + "; regranting permissions for internal storage"); 2295 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2296 } 2297 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2298 ver.sdkVersion = mSdkVersion; 2299 2300 // If this is the first boot or an update from pre-M, and it is a normal 2301 // boot, then we need to initialize the default preferred apps across 2302 // all defined users. 2303 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2304 for (UserInfo user : sUserManager.getUsers(true)) { 2305 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2306 applyFactoryDefaultBrowserLPw(user.id); 2307 primeDomainVerificationsLPw(user.id); 2308 } 2309 } 2310 2311 // If this is first boot after an OTA, and a normal boot, then 2312 // we need to clear code cache directories. 2313 if (mIsUpgrade && !onlyCore) { 2314 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2315 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2316 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2317 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2318 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2319 } 2320 } 2321 ver.fingerprint = Build.FINGERPRINT; 2322 } 2323 2324 checkDefaultBrowser(); 2325 2326 // clear only after permissions and other defaults have been updated 2327 mExistingSystemPackages.clear(); 2328 mPromoteSystemApps = false; 2329 2330 // All the changes are done during package scanning. 2331 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2332 2333 // can downgrade to reader 2334 mSettings.writeLPr(); 2335 2336 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2337 SystemClock.uptimeMillis()); 2338 2339 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2340 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2341 2342 mInstallerService = new PackageInstallerService(context, this); 2343 2344 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2345 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2346 mIntentFilterVerifierComponent); 2347 2348 } // synchronized (mPackages) 2349 } // synchronized (mInstallLock) 2350 2351 // Now after opening every single application zip, make sure they 2352 // are all flushed. Not really needed, but keeps things nice and 2353 // tidy. 2354 Runtime.getRuntime().gc(); 2355 2356 // The initial scanning above does many calls into installd while 2357 // holding the mPackages lock, but we're mostly interested in yelling 2358 // once we have a booted system. 2359 mInstaller.setWarnIfHeld(mPackages); 2360 2361 // Expose private service for system components to use. 2362 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2363 } 2364 2365 @Override 2366 public boolean isFirstBoot() { 2367 return !mRestoredSettings; 2368 } 2369 2370 @Override 2371 public boolean isOnlyCoreApps() { 2372 return mOnlyCore; 2373 } 2374 2375 @Override 2376 public boolean isUpgrade() { 2377 return mIsUpgrade; 2378 } 2379 2380 private String getRequiredVerifierLPr() { 2381 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2382 // We only care about verifier that's installed under system user. 2383 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2384 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2385 2386 String requiredVerifier = null; 2387 2388 final int N = receivers.size(); 2389 for (int i = 0; i < N; i++) { 2390 final ResolveInfo info = receivers.get(i); 2391 2392 if (info.activityInfo == null) { 2393 continue; 2394 } 2395 2396 final String packageName = info.activityInfo.packageName; 2397 2398 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2399 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2400 continue; 2401 } 2402 2403 if (requiredVerifier != null) { 2404 throw new RuntimeException("There can be only one required verifier"); 2405 } 2406 2407 requiredVerifier = packageName; 2408 } 2409 2410 return requiredVerifier; 2411 } 2412 2413 private String getRequiredInstallerLPr() { 2414 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2415 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2416 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2417 2418 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2419 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2420 2421 String requiredInstaller = null; 2422 2423 final int N = installers.size(); 2424 for (int i = 0; i < N; i++) { 2425 final ResolveInfo info = installers.get(i); 2426 final String packageName = info.activityInfo.packageName; 2427 2428 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2429 continue; 2430 } 2431 2432 if (requiredInstaller != null) { 2433 throw new RuntimeException("There must be one required installer"); 2434 } 2435 2436 requiredInstaller = packageName; 2437 } 2438 2439 if (requiredInstaller == null) { 2440 throw new RuntimeException("There must be one required installer"); 2441 } 2442 2443 return requiredInstaller; 2444 } 2445 2446 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2447 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2448 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2449 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2450 2451 ComponentName verifierComponentName = null; 2452 2453 int priority = -1000; 2454 final int N = receivers.size(); 2455 for (int i = 0; i < N; i++) { 2456 final ResolveInfo info = receivers.get(i); 2457 2458 if (info.activityInfo == null) { 2459 continue; 2460 } 2461 2462 final String packageName = info.activityInfo.packageName; 2463 2464 final PackageSetting ps = mSettings.mPackages.get(packageName); 2465 if (ps == null) { 2466 continue; 2467 } 2468 2469 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2470 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2471 continue; 2472 } 2473 2474 // Select the IntentFilterVerifier with the highest priority 2475 if (priority < info.priority) { 2476 priority = info.priority; 2477 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2478 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2479 + verifierComponentName + " with priority: " + info.priority); 2480 } 2481 } 2482 2483 return verifierComponentName; 2484 } 2485 2486 private void primeDomainVerificationsLPw(int userId) { 2487 if (DEBUG_DOMAIN_VERIFICATION) { 2488 Slog.d(TAG, "Priming domain verifications in user " + userId); 2489 } 2490 2491 SystemConfig systemConfig = SystemConfig.getInstance(); 2492 ArraySet<String> packages = systemConfig.getLinkedApps(); 2493 ArraySet<String> domains = new ArraySet<String>(); 2494 2495 for (String packageName : packages) { 2496 PackageParser.Package pkg = mPackages.get(packageName); 2497 if (pkg != null) { 2498 if (!pkg.isSystemApp()) { 2499 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2500 continue; 2501 } 2502 2503 domains.clear(); 2504 for (PackageParser.Activity a : pkg.activities) { 2505 for (ActivityIntentInfo filter : a.intents) { 2506 if (hasValidDomains(filter)) { 2507 domains.addAll(filter.getHostsList()); 2508 } 2509 } 2510 } 2511 2512 if (domains.size() > 0) { 2513 if (DEBUG_DOMAIN_VERIFICATION) { 2514 Slog.v(TAG, " + " + packageName); 2515 } 2516 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2517 // state w.r.t. the formal app-linkage "no verification attempted" state; 2518 // and then 'always' in the per-user state actually used for intent resolution. 2519 final IntentFilterVerificationInfo ivi; 2520 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2521 new ArrayList<String>(domains)); 2522 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2523 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2524 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2525 } else { 2526 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2527 + "' does not handle web links"); 2528 } 2529 } else { 2530 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2531 } 2532 } 2533 2534 scheduleWritePackageRestrictionsLocked(userId); 2535 scheduleWriteSettingsLocked(); 2536 } 2537 2538 private void applyFactoryDefaultBrowserLPw(int userId) { 2539 // The default browser app's package name is stored in a string resource, 2540 // with a product-specific overlay used for vendor customization. 2541 String browserPkg = mContext.getResources().getString( 2542 com.android.internal.R.string.default_browser); 2543 if (!TextUtils.isEmpty(browserPkg)) { 2544 // non-empty string => required to be a known package 2545 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2546 if (ps == null) { 2547 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2548 browserPkg = null; 2549 } else { 2550 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2551 } 2552 } 2553 2554 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2555 // default. If there's more than one, just leave everything alone. 2556 if (browserPkg == null) { 2557 calculateDefaultBrowserLPw(userId); 2558 } 2559 } 2560 2561 private void calculateDefaultBrowserLPw(int userId) { 2562 List<String> allBrowsers = resolveAllBrowserApps(userId); 2563 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2564 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2565 } 2566 2567 private List<String> resolveAllBrowserApps(int userId) { 2568 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2569 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2570 PackageManager.MATCH_ALL, userId); 2571 2572 final int count = list.size(); 2573 List<String> result = new ArrayList<String>(count); 2574 for (int i=0; i<count; i++) { 2575 ResolveInfo info = list.get(i); 2576 if (info.activityInfo == null 2577 || !info.handleAllWebDataURI 2578 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2579 || result.contains(info.activityInfo.packageName)) { 2580 continue; 2581 } 2582 result.add(info.activityInfo.packageName); 2583 } 2584 2585 return result; 2586 } 2587 2588 private boolean packageIsBrowser(String packageName, int userId) { 2589 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2590 PackageManager.MATCH_ALL, userId); 2591 final int N = list.size(); 2592 for (int i = 0; i < N; i++) { 2593 ResolveInfo info = list.get(i); 2594 if (packageName.equals(info.activityInfo.packageName)) { 2595 return true; 2596 } 2597 } 2598 return false; 2599 } 2600 2601 private void checkDefaultBrowser() { 2602 final int myUserId = UserHandle.myUserId(); 2603 final String packageName = getDefaultBrowserPackageName(myUserId); 2604 if (packageName != null) { 2605 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2606 if (info == null) { 2607 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2608 synchronized (mPackages) { 2609 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2610 } 2611 } 2612 } 2613 } 2614 2615 @Override 2616 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2617 throws RemoteException { 2618 try { 2619 return super.onTransact(code, data, reply, flags); 2620 } catch (RuntimeException e) { 2621 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2622 Slog.wtf(TAG, "Package Manager Crash", e); 2623 } 2624 throw e; 2625 } 2626 } 2627 2628 void cleanupInstallFailedPackage(PackageSetting ps) { 2629 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2630 2631 removeDataDirsLI(ps.volumeUuid, ps.name); 2632 if (ps.codePath != null) { 2633 if (ps.codePath.isDirectory()) { 2634 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2635 } else { 2636 ps.codePath.delete(); 2637 } 2638 } 2639 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2640 if (ps.resourcePath.isDirectory()) { 2641 FileUtils.deleteContents(ps.resourcePath); 2642 } 2643 ps.resourcePath.delete(); 2644 } 2645 mSettings.removePackageLPw(ps.name); 2646 } 2647 2648 static int[] appendInts(int[] cur, int[] add) { 2649 if (add == null) return cur; 2650 if (cur == null) return add; 2651 final int N = add.length; 2652 for (int i=0; i<N; i++) { 2653 cur = appendInt(cur, add[i]); 2654 } 2655 return cur; 2656 } 2657 2658 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2659 if (!sUserManager.exists(userId)) return null; 2660 final PackageSetting ps = (PackageSetting) p.mExtras; 2661 if (ps == null) { 2662 return null; 2663 } 2664 2665 final PermissionsState permissionsState = ps.getPermissionsState(); 2666 2667 final int[] gids = permissionsState.computeGids(userId); 2668 final Set<String> permissions = permissionsState.getPermissions(userId); 2669 final PackageUserState state = ps.readUserState(userId); 2670 2671 return PackageParser.generatePackageInfo(p, gids, flags, 2672 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2673 } 2674 2675 @Override 2676 public boolean isPackageFrozen(String packageName) { 2677 synchronized (mPackages) { 2678 final PackageSetting ps = mSettings.mPackages.get(packageName); 2679 if (ps != null) { 2680 return ps.frozen; 2681 } 2682 } 2683 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2684 return true; 2685 } 2686 2687 @Override 2688 public boolean isPackageAvailable(String packageName, int userId) { 2689 if (!sUserManager.exists(userId)) return false; 2690 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2691 synchronized (mPackages) { 2692 PackageParser.Package p = mPackages.get(packageName); 2693 if (p != null) { 2694 final PackageSetting ps = (PackageSetting) p.mExtras; 2695 if (ps != null) { 2696 final PackageUserState state = ps.readUserState(userId); 2697 if (state != null) { 2698 return PackageParser.isAvailable(state); 2699 } 2700 } 2701 } 2702 } 2703 return false; 2704 } 2705 2706 @Override 2707 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2708 if (!sUserManager.exists(userId)) return null; 2709 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2710 // reader 2711 synchronized (mPackages) { 2712 PackageParser.Package p = mPackages.get(packageName); 2713 if (DEBUG_PACKAGE_INFO) 2714 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2715 if (p != null) { 2716 return generatePackageInfo(p, flags, userId); 2717 } 2718 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2719 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2720 } 2721 } 2722 return null; 2723 } 2724 2725 @Override 2726 public String[] currentToCanonicalPackageNames(String[] names) { 2727 String[] out = new String[names.length]; 2728 // reader 2729 synchronized (mPackages) { 2730 for (int i=names.length-1; i>=0; i--) { 2731 PackageSetting ps = mSettings.mPackages.get(names[i]); 2732 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2733 } 2734 } 2735 return out; 2736 } 2737 2738 @Override 2739 public String[] canonicalToCurrentPackageNames(String[] names) { 2740 String[] out = new String[names.length]; 2741 // reader 2742 synchronized (mPackages) { 2743 for (int i=names.length-1; i>=0; i--) { 2744 String cur = mSettings.mRenamedPackages.get(names[i]); 2745 out[i] = cur != null ? cur : names[i]; 2746 } 2747 } 2748 return out; 2749 } 2750 2751 @Override 2752 public int getPackageUid(String packageName, int userId) { 2753 return getPackageUidEtc(packageName, 0, userId); 2754 } 2755 2756 @Override 2757 public int getPackageUidEtc(String packageName, int flags, int userId) { 2758 if (!sUserManager.exists(userId)) return -1; 2759 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2760 2761 // reader 2762 synchronized (mPackages) { 2763 final PackageParser.Package p = mPackages.get(packageName); 2764 if (p != null) { 2765 return UserHandle.getUid(userId, p.applicationInfo.uid); 2766 } 2767 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2768 final PackageSetting ps = mSettings.mPackages.get(packageName); 2769 if (ps != null) { 2770 return UserHandle.getUid(userId, ps.appId); 2771 } 2772 } 2773 } 2774 2775 return -1; 2776 } 2777 2778 @Override 2779 public int[] getPackageGids(String packageName, int userId) { 2780 return getPackageGidsEtc(packageName, 0, userId); 2781 } 2782 2783 @Override 2784 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2785 if (!sUserManager.exists(userId)) { 2786 return null; 2787 } 2788 2789 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2790 "getPackageGids"); 2791 2792 // reader 2793 synchronized (mPackages) { 2794 final PackageParser.Package p = mPackages.get(packageName); 2795 if (p != null) { 2796 PackageSetting ps = (PackageSetting) p.mExtras; 2797 return ps.getPermissionsState().computeGids(userId); 2798 } 2799 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2800 final PackageSetting ps = mSettings.mPackages.get(packageName); 2801 if (ps != null) { 2802 return ps.getPermissionsState().computeGids(userId); 2803 } 2804 } 2805 } 2806 2807 return null; 2808 } 2809 2810 static PermissionInfo generatePermissionInfo( 2811 BasePermission bp, int flags) { 2812 if (bp.perm != null) { 2813 return PackageParser.generatePermissionInfo(bp.perm, flags); 2814 } 2815 PermissionInfo pi = new PermissionInfo(); 2816 pi.name = bp.name; 2817 pi.packageName = bp.sourcePackage; 2818 pi.nonLocalizedLabel = bp.name; 2819 pi.protectionLevel = bp.protectionLevel; 2820 return pi; 2821 } 2822 2823 @Override 2824 public PermissionInfo getPermissionInfo(String name, int flags) { 2825 // reader 2826 synchronized (mPackages) { 2827 final BasePermission p = mSettings.mPermissions.get(name); 2828 if (p != null) { 2829 return generatePermissionInfo(p, flags); 2830 } 2831 return null; 2832 } 2833 } 2834 2835 @Override 2836 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2837 // reader 2838 synchronized (mPackages) { 2839 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2840 for (BasePermission p : mSettings.mPermissions.values()) { 2841 if (group == null) { 2842 if (p.perm == null || p.perm.info.group == null) { 2843 out.add(generatePermissionInfo(p, flags)); 2844 } 2845 } else { 2846 if (p.perm != null && group.equals(p.perm.info.group)) { 2847 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2848 } 2849 } 2850 } 2851 2852 if (out.size() > 0) { 2853 return out; 2854 } 2855 return mPermissionGroups.containsKey(group) ? out : null; 2856 } 2857 } 2858 2859 @Override 2860 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2861 // reader 2862 synchronized (mPackages) { 2863 return PackageParser.generatePermissionGroupInfo( 2864 mPermissionGroups.get(name), flags); 2865 } 2866 } 2867 2868 @Override 2869 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2870 // reader 2871 synchronized (mPackages) { 2872 final int N = mPermissionGroups.size(); 2873 ArrayList<PermissionGroupInfo> out 2874 = new ArrayList<PermissionGroupInfo>(N); 2875 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2876 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2877 } 2878 return out; 2879 } 2880 } 2881 2882 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2883 int userId) { 2884 if (!sUserManager.exists(userId)) return null; 2885 PackageSetting ps = mSettings.mPackages.get(packageName); 2886 if (ps != null) { 2887 if (ps.pkg == null) { 2888 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2889 flags, userId); 2890 if (pInfo != null) { 2891 return pInfo.applicationInfo; 2892 } 2893 return null; 2894 } 2895 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2896 ps.readUserState(userId), userId); 2897 } 2898 return null; 2899 } 2900 2901 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2902 int userId) { 2903 if (!sUserManager.exists(userId)) return null; 2904 PackageSetting ps = mSettings.mPackages.get(packageName); 2905 if (ps != null) { 2906 PackageParser.Package pkg = ps.pkg; 2907 if (pkg == null) { 2908 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2909 return null; 2910 } 2911 // Only data remains, so we aren't worried about code paths 2912 pkg = new PackageParser.Package(packageName); 2913 pkg.applicationInfo.packageName = packageName; 2914 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2915 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2916 pkg.applicationInfo.uid = ps.appId; 2917 pkg.applicationInfo.initForUser(userId); 2918 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2919 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2920 } 2921 return generatePackageInfo(pkg, flags, userId); 2922 } 2923 return null; 2924 } 2925 2926 @Override 2927 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2928 if (!sUserManager.exists(userId)) return null; 2929 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2930 // writer 2931 synchronized (mPackages) { 2932 PackageParser.Package p = mPackages.get(packageName); 2933 if (DEBUG_PACKAGE_INFO) Log.v( 2934 TAG, "getApplicationInfo " + packageName 2935 + ": " + p); 2936 if (p != null) { 2937 PackageSetting ps = mSettings.mPackages.get(packageName); 2938 if (ps == null) return null; 2939 // Note: isEnabledLP() does not apply here - always return info 2940 return PackageParser.generateApplicationInfo( 2941 p, flags, ps.readUserState(userId), userId); 2942 } 2943 if ("android".equals(packageName)||"system".equals(packageName)) { 2944 return mAndroidApplication; 2945 } 2946 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2947 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2948 } 2949 } 2950 return null; 2951 } 2952 2953 @Override 2954 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2955 final IPackageDataObserver observer) { 2956 mContext.enforceCallingOrSelfPermission( 2957 android.Manifest.permission.CLEAR_APP_CACHE, null); 2958 // Queue up an async operation since clearing cache may take a little while. 2959 mHandler.post(new Runnable() { 2960 public void run() { 2961 mHandler.removeCallbacks(this); 2962 int retCode = -1; 2963 synchronized (mInstallLock) { 2964 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2965 if (retCode < 0) { 2966 Slog.w(TAG, "Couldn't clear application caches"); 2967 } 2968 } 2969 if (observer != null) { 2970 try { 2971 observer.onRemoveCompleted(null, (retCode >= 0)); 2972 } catch (RemoteException e) { 2973 Slog.w(TAG, "RemoveException when invoking call back"); 2974 } 2975 } 2976 } 2977 }); 2978 } 2979 2980 @Override 2981 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2982 final IntentSender pi) { 2983 mContext.enforceCallingOrSelfPermission( 2984 android.Manifest.permission.CLEAR_APP_CACHE, null); 2985 // Queue up an async operation since clearing cache may take a little while. 2986 mHandler.post(new Runnable() { 2987 public void run() { 2988 mHandler.removeCallbacks(this); 2989 int retCode = -1; 2990 synchronized (mInstallLock) { 2991 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2992 if (retCode < 0) { 2993 Slog.w(TAG, "Couldn't clear application caches"); 2994 } 2995 } 2996 if(pi != null) { 2997 try { 2998 // Callback via pending intent 2999 int code = (retCode >= 0) ? 1 : 0; 3000 pi.sendIntent(null, code, null, 3001 null, null); 3002 } catch (SendIntentException e1) { 3003 Slog.i(TAG, "Failed to send pending intent"); 3004 } 3005 } 3006 } 3007 }); 3008 } 3009 3010 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3011 synchronized (mInstallLock) { 3012 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3013 throw new IOException("Failed to free enough space"); 3014 } 3015 } 3016 } 3017 3018 /** 3019 * Augment the given flags depending on current user running state. This is 3020 * purposefully done before acquiring {@link #mPackages} lock. 3021 */ 3022 private int augmentFlagsForUser(int flags, int userId) { 3023 if (SystemProperties.getBoolean(StorageManager.PROP_HAS_FBE, false)) { 3024 final IMountService mount = IMountService.Stub 3025 .asInterface(ServiceManager.getService(Context.STORAGE_SERVICE)); 3026 if (mount == null) { 3027 // We must be early in boot, so the best we can do is assume the 3028 // user is fully running. 3029 return flags; 3030 } 3031 final long token = Binder.clearCallingIdentity(); 3032 try { 3033 if (!mount.isUserKeyUnlocked(userId)) { 3034 flags |= PackageManager.FLAG_USER_RUNNING_WITH_AMNESIA; 3035 } 3036 } catch (RemoteException e) { 3037 throw e.rethrowAsRuntimeException(); 3038 } finally { 3039 Binder.restoreCallingIdentity(token); 3040 } 3041 } 3042 return flags; 3043 } 3044 3045 @Override 3046 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3047 if (!sUserManager.exists(userId)) return null; 3048 flags = augmentFlagsForUser(flags, userId); 3049 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3050 synchronized (mPackages) { 3051 PackageParser.Activity a = mActivities.mActivities.get(component); 3052 3053 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3054 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3055 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3056 if (ps == null) return null; 3057 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3058 userId); 3059 } 3060 if (mResolveComponentName.equals(component)) { 3061 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3062 new PackageUserState(), userId); 3063 } 3064 } 3065 return null; 3066 } 3067 3068 @Override 3069 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3070 String resolvedType) { 3071 synchronized (mPackages) { 3072 if (component.equals(mResolveComponentName)) { 3073 // The resolver supports EVERYTHING! 3074 return true; 3075 } 3076 PackageParser.Activity a = mActivities.mActivities.get(component); 3077 if (a == null) { 3078 return false; 3079 } 3080 for (int i=0; i<a.intents.size(); i++) { 3081 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3082 intent.getData(), intent.getCategories(), TAG) >= 0) { 3083 return true; 3084 } 3085 } 3086 return false; 3087 } 3088 } 3089 3090 @Override 3091 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3092 if (!sUserManager.exists(userId)) return null; 3093 flags = augmentFlagsForUser(flags, userId); 3094 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3095 synchronized (mPackages) { 3096 PackageParser.Activity a = mReceivers.mActivities.get(component); 3097 if (DEBUG_PACKAGE_INFO) Log.v( 3098 TAG, "getReceiverInfo " + component + ": " + a); 3099 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3100 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3101 if (ps == null) return null; 3102 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3103 userId); 3104 } 3105 } 3106 return null; 3107 } 3108 3109 @Override 3110 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3111 if (!sUserManager.exists(userId)) return null; 3112 flags = augmentFlagsForUser(flags, userId); 3113 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3114 synchronized (mPackages) { 3115 PackageParser.Service s = mServices.mServices.get(component); 3116 if (DEBUG_PACKAGE_INFO) Log.v( 3117 TAG, "getServiceInfo " + component + ": " + s); 3118 if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) { 3119 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3120 if (ps == null) return null; 3121 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3122 userId); 3123 } 3124 } 3125 return null; 3126 } 3127 3128 @Override 3129 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3130 if (!sUserManager.exists(userId)) return null; 3131 flags = augmentFlagsForUser(flags, userId); 3132 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3133 synchronized (mPackages) { 3134 PackageParser.Provider p = mProviders.mProviders.get(component); 3135 if (DEBUG_PACKAGE_INFO) Log.v( 3136 TAG, "getProviderInfo " + component + ": " + p); 3137 if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) { 3138 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3139 if (ps == null) return null; 3140 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3141 userId); 3142 } 3143 } 3144 return null; 3145 } 3146 3147 @Override 3148 public String[] getSystemSharedLibraryNames() { 3149 Set<String> libSet; 3150 synchronized (mPackages) { 3151 libSet = mSharedLibraries.keySet(); 3152 int size = libSet.size(); 3153 if (size > 0) { 3154 String[] libs = new String[size]; 3155 libSet.toArray(libs); 3156 return libs; 3157 } 3158 } 3159 return null; 3160 } 3161 3162 /** 3163 * @hide 3164 */ 3165 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3166 synchronized (mPackages) { 3167 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3168 if (lib != null && lib.apk != null) { 3169 return mPackages.get(lib.apk); 3170 } 3171 } 3172 return null; 3173 } 3174 3175 @Override 3176 public FeatureInfo[] getSystemAvailableFeatures() { 3177 Collection<FeatureInfo> featSet; 3178 synchronized (mPackages) { 3179 featSet = mAvailableFeatures.values(); 3180 int size = featSet.size(); 3181 if (size > 0) { 3182 FeatureInfo[] features = new FeatureInfo[size+1]; 3183 featSet.toArray(features); 3184 FeatureInfo fi = new FeatureInfo(); 3185 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3186 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3187 features[size] = fi; 3188 return features; 3189 } 3190 } 3191 return null; 3192 } 3193 3194 @Override 3195 public boolean hasSystemFeature(String name) { 3196 synchronized (mPackages) { 3197 return mAvailableFeatures.containsKey(name); 3198 } 3199 } 3200 3201 private void checkValidCaller(int uid, int userId) { 3202 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3203 return; 3204 3205 throw new SecurityException("Caller uid=" + uid 3206 + " is not privileged to communicate with user=" + userId); 3207 } 3208 3209 @Override 3210 public int checkPermission(String permName, String pkgName, int userId) { 3211 if (!sUserManager.exists(userId)) { 3212 return PackageManager.PERMISSION_DENIED; 3213 } 3214 3215 synchronized (mPackages) { 3216 final PackageParser.Package p = mPackages.get(pkgName); 3217 if (p != null && p.mExtras != null) { 3218 final PackageSetting ps = (PackageSetting) p.mExtras; 3219 final PermissionsState permissionsState = ps.getPermissionsState(); 3220 if (permissionsState.hasPermission(permName, userId)) { 3221 return PackageManager.PERMISSION_GRANTED; 3222 } 3223 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3224 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3225 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3226 return PackageManager.PERMISSION_GRANTED; 3227 } 3228 } 3229 } 3230 3231 return PackageManager.PERMISSION_DENIED; 3232 } 3233 3234 @Override 3235 public int checkUidPermission(String permName, int uid) { 3236 final int userId = UserHandle.getUserId(uid); 3237 3238 if (!sUserManager.exists(userId)) { 3239 return PackageManager.PERMISSION_DENIED; 3240 } 3241 3242 synchronized (mPackages) { 3243 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3244 if (obj != null) { 3245 final SettingBase ps = (SettingBase) obj; 3246 final PermissionsState permissionsState = ps.getPermissionsState(); 3247 if (permissionsState.hasPermission(permName, userId)) { 3248 return PackageManager.PERMISSION_GRANTED; 3249 } 3250 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3251 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3252 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3253 return PackageManager.PERMISSION_GRANTED; 3254 } 3255 } else { 3256 ArraySet<String> perms = mSystemPermissions.get(uid); 3257 if (perms != null) { 3258 if (perms.contains(permName)) { 3259 return PackageManager.PERMISSION_GRANTED; 3260 } 3261 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3262 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3263 return PackageManager.PERMISSION_GRANTED; 3264 } 3265 } 3266 } 3267 } 3268 3269 return PackageManager.PERMISSION_DENIED; 3270 } 3271 3272 @Override 3273 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3274 if (UserHandle.getCallingUserId() != userId) { 3275 mContext.enforceCallingPermission( 3276 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3277 "isPermissionRevokedByPolicy for user " + userId); 3278 } 3279 3280 if (checkPermission(permission, packageName, userId) 3281 == PackageManager.PERMISSION_GRANTED) { 3282 return false; 3283 } 3284 3285 final long identity = Binder.clearCallingIdentity(); 3286 try { 3287 final int flags = getPermissionFlags(permission, packageName, userId); 3288 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3289 } finally { 3290 Binder.restoreCallingIdentity(identity); 3291 } 3292 } 3293 3294 @Override 3295 public String getPermissionControllerPackageName() { 3296 synchronized (mPackages) { 3297 return mRequiredInstallerPackage; 3298 } 3299 } 3300 3301 /** 3302 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3303 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3304 * @param checkShell TODO(yamasani): 3305 * @param message the message to log on security exception 3306 */ 3307 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3308 boolean checkShell, String message) { 3309 if (userId < 0) { 3310 throw new IllegalArgumentException("Invalid userId " + userId); 3311 } 3312 if (checkShell) { 3313 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3314 } 3315 if (userId == UserHandle.getUserId(callingUid)) return; 3316 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3317 if (requireFullPermission) { 3318 mContext.enforceCallingOrSelfPermission( 3319 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3320 } else { 3321 try { 3322 mContext.enforceCallingOrSelfPermission( 3323 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3324 } catch (SecurityException se) { 3325 mContext.enforceCallingOrSelfPermission( 3326 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3327 } 3328 } 3329 } 3330 } 3331 3332 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3333 if (callingUid == Process.SHELL_UID) { 3334 if (userHandle >= 0 3335 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3336 throw new SecurityException("Shell does not have permission to access user " 3337 + userHandle); 3338 } else if (userHandle < 0) { 3339 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3340 + Debug.getCallers(3)); 3341 } 3342 } 3343 } 3344 3345 private BasePermission findPermissionTreeLP(String permName) { 3346 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3347 if (permName.startsWith(bp.name) && 3348 permName.length() > bp.name.length() && 3349 permName.charAt(bp.name.length()) == '.') { 3350 return bp; 3351 } 3352 } 3353 return null; 3354 } 3355 3356 private BasePermission checkPermissionTreeLP(String permName) { 3357 if (permName != null) { 3358 BasePermission bp = findPermissionTreeLP(permName); 3359 if (bp != null) { 3360 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3361 return bp; 3362 } 3363 throw new SecurityException("Calling uid " 3364 + Binder.getCallingUid() 3365 + " is not allowed to add to permission tree " 3366 + bp.name + " owned by uid " + bp.uid); 3367 } 3368 } 3369 throw new SecurityException("No permission tree found for " + permName); 3370 } 3371 3372 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3373 if (s1 == null) { 3374 return s2 == null; 3375 } 3376 if (s2 == null) { 3377 return false; 3378 } 3379 if (s1.getClass() != s2.getClass()) { 3380 return false; 3381 } 3382 return s1.equals(s2); 3383 } 3384 3385 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3386 if (pi1.icon != pi2.icon) return false; 3387 if (pi1.logo != pi2.logo) return false; 3388 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3389 if (!compareStrings(pi1.name, pi2.name)) return false; 3390 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3391 // We'll take care of setting this one. 3392 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3393 // These are not currently stored in settings. 3394 //if (!compareStrings(pi1.group, pi2.group)) return false; 3395 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3396 //if (pi1.labelRes != pi2.labelRes) return false; 3397 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3398 return true; 3399 } 3400 3401 int permissionInfoFootprint(PermissionInfo info) { 3402 int size = info.name.length(); 3403 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3404 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3405 return size; 3406 } 3407 3408 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3409 int size = 0; 3410 for (BasePermission perm : mSettings.mPermissions.values()) { 3411 if (perm.uid == tree.uid) { 3412 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3413 } 3414 } 3415 return size; 3416 } 3417 3418 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3419 // We calculate the max size of permissions defined by this uid and throw 3420 // if that plus the size of 'info' would exceed our stated maximum. 3421 if (tree.uid != Process.SYSTEM_UID) { 3422 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3423 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3424 throw new SecurityException("Permission tree size cap exceeded"); 3425 } 3426 } 3427 } 3428 3429 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3430 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3431 throw new SecurityException("Label must be specified in permission"); 3432 } 3433 BasePermission tree = checkPermissionTreeLP(info.name); 3434 BasePermission bp = mSettings.mPermissions.get(info.name); 3435 boolean added = bp == null; 3436 boolean changed = true; 3437 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3438 if (added) { 3439 enforcePermissionCapLocked(info, tree); 3440 bp = new BasePermission(info.name, tree.sourcePackage, 3441 BasePermission.TYPE_DYNAMIC); 3442 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3443 throw new SecurityException( 3444 "Not allowed to modify non-dynamic permission " 3445 + info.name); 3446 } else { 3447 if (bp.protectionLevel == fixedLevel 3448 && bp.perm.owner.equals(tree.perm.owner) 3449 && bp.uid == tree.uid 3450 && comparePermissionInfos(bp.perm.info, info)) { 3451 changed = false; 3452 } 3453 } 3454 bp.protectionLevel = fixedLevel; 3455 info = new PermissionInfo(info); 3456 info.protectionLevel = fixedLevel; 3457 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3458 bp.perm.info.packageName = tree.perm.info.packageName; 3459 bp.uid = tree.uid; 3460 if (added) { 3461 mSettings.mPermissions.put(info.name, bp); 3462 } 3463 if (changed) { 3464 if (!async) { 3465 mSettings.writeLPr(); 3466 } else { 3467 scheduleWriteSettingsLocked(); 3468 } 3469 } 3470 return added; 3471 } 3472 3473 @Override 3474 public boolean addPermission(PermissionInfo info) { 3475 synchronized (mPackages) { 3476 return addPermissionLocked(info, false); 3477 } 3478 } 3479 3480 @Override 3481 public boolean addPermissionAsync(PermissionInfo info) { 3482 synchronized (mPackages) { 3483 return addPermissionLocked(info, true); 3484 } 3485 } 3486 3487 @Override 3488 public void removePermission(String name) { 3489 synchronized (mPackages) { 3490 checkPermissionTreeLP(name); 3491 BasePermission bp = mSettings.mPermissions.get(name); 3492 if (bp != null) { 3493 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3494 throw new SecurityException( 3495 "Not allowed to modify non-dynamic permission " 3496 + name); 3497 } 3498 mSettings.mPermissions.remove(name); 3499 mSettings.writeLPr(); 3500 } 3501 } 3502 } 3503 3504 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3505 BasePermission bp) { 3506 int index = pkg.requestedPermissions.indexOf(bp.name); 3507 if (index == -1) { 3508 throw new SecurityException("Package " + pkg.packageName 3509 + " has not requested permission " + bp.name); 3510 } 3511 if (!bp.isRuntime() && !bp.isDevelopment()) { 3512 throw new SecurityException("Permission " + bp.name 3513 + " is not a changeable permission type"); 3514 } 3515 } 3516 3517 @Override 3518 public void grantRuntimePermission(String packageName, String name, final int userId) { 3519 if (!sUserManager.exists(userId)) { 3520 Log.e(TAG, "No such user:" + userId); 3521 return; 3522 } 3523 3524 mContext.enforceCallingOrSelfPermission( 3525 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3526 "grantRuntimePermission"); 3527 3528 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3529 "grantRuntimePermission"); 3530 3531 final int uid; 3532 final SettingBase sb; 3533 3534 synchronized (mPackages) { 3535 final PackageParser.Package pkg = mPackages.get(packageName); 3536 if (pkg == null) { 3537 throw new IllegalArgumentException("Unknown package: " + packageName); 3538 } 3539 3540 final BasePermission bp = mSettings.mPermissions.get(name); 3541 if (bp == null) { 3542 throw new IllegalArgumentException("Unknown permission: " + name); 3543 } 3544 3545 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3546 3547 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3548 sb = (SettingBase) pkg.mExtras; 3549 if (sb == null) { 3550 throw new IllegalArgumentException("Unknown package: " + packageName); 3551 } 3552 3553 final PermissionsState permissionsState = sb.getPermissionsState(); 3554 3555 final int flags = permissionsState.getPermissionFlags(name, userId); 3556 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3557 throw new SecurityException("Cannot grant system fixed permission: " 3558 + name + " for package: " + packageName); 3559 } 3560 3561 if (bp.isDevelopment()) { 3562 // Development permissions must be handled specially, since they are not 3563 // normal runtime permissions. For now they apply to all users. 3564 if (permissionsState.grantInstallPermission(bp) != 3565 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3566 scheduleWriteSettingsLocked(); 3567 } 3568 return; 3569 } 3570 3571 final int result = permissionsState.grantRuntimePermission(bp, userId); 3572 switch (result) { 3573 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3574 return; 3575 } 3576 3577 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3578 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3579 mHandler.post(new Runnable() { 3580 @Override 3581 public void run() { 3582 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3583 } 3584 }); 3585 } 3586 break; 3587 } 3588 3589 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3590 3591 // Not critical if that is lost - app has to request again. 3592 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3593 } 3594 3595 // Only need to do this if user is initialized. Otherwise it's a new user 3596 // and there are no processes running as the user yet and there's no need 3597 // to make an expensive call to remount processes for the changed permissions. 3598 if (READ_EXTERNAL_STORAGE.equals(name) 3599 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3600 final long token = Binder.clearCallingIdentity(); 3601 try { 3602 if (sUserManager.isInitialized(userId)) { 3603 MountServiceInternal mountServiceInternal = LocalServices.getService( 3604 MountServiceInternal.class); 3605 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3606 } 3607 } finally { 3608 Binder.restoreCallingIdentity(token); 3609 } 3610 } 3611 } 3612 3613 @Override 3614 public void revokeRuntimePermission(String packageName, String name, int userId) { 3615 if (!sUserManager.exists(userId)) { 3616 Log.e(TAG, "No such user:" + userId); 3617 return; 3618 } 3619 3620 mContext.enforceCallingOrSelfPermission( 3621 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3622 "revokeRuntimePermission"); 3623 3624 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3625 "revokeRuntimePermission"); 3626 3627 final int appId; 3628 3629 synchronized (mPackages) { 3630 final PackageParser.Package pkg = mPackages.get(packageName); 3631 if (pkg == null) { 3632 throw new IllegalArgumentException("Unknown package: " + packageName); 3633 } 3634 3635 final BasePermission bp = mSettings.mPermissions.get(name); 3636 if (bp == null) { 3637 throw new IllegalArgumentException("Unknown permission: " + name); 3638 } 3639 3640 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3641 3642 SettingBase sb = (SettingBase) pkg.mExtras; 3643 if (sb == null) { 3644 throw new IllegalArgumentException("Unknown package: " + packageName); 3645 } 3646 3647 final PermissionsState permissionsState = sb.getPermissionsState(); 3648 3649 final int flags = permissionsState.getPermissionFlags(name, userId); 3650 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3651 throw new SecurityException("Cannot revoke system fixed permission: " 3652 + name + " for package: " + packageName); 3653 } 3654 3655 if (bp.isDevelopment()) { 3656 // Development permissions must be handled specially, since they are not 3657 // normal runtime permissions. For now they apply to all users. 3658 if (permissionsState.revokeInstallPermission(bp) != 3659 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3660 scheduleWriteSettingsLocked(); 3661 } 3662 return; 3663 } 3664 3665 if (permissionsState.revokeRuntimePermission(bp, userId) == 3666 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3667 return; 3668 } 3669 3670 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3671 3672 // Critical, after this call app should never have the permission. 3673 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3674 3675 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3676 } 3677 3678 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3679 } 3680 3681 @Override 3682 public void resetRuntimePermissions() { 3683 mContext.enforceCallingOrSelfPermission( 3684 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3685 "revokeRuntimePermission"); 3686 3687 int callingUid = Binder.getCallingUid(); 3688 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3689 mContext.enforceCallingOrSelfPermission( 3690 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3691 "resetRuntimePermissions"); 3692 } 3693 3694 synchronized (mPackages) { 3695 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3696 for (int userId : UserManagerService.getInstance().getUserIds()) { 3697 final int packageCount = mPackages.size(); 3698 for (int i = 0; i < packageCount; i++) { 3699 PackageParser.Package pkg = mPackages.valueAt(i); 3700 if (!(pkg.mExtras instanceof PackageSetting)) { 3701 continue; 3702 } 3703 PackageSetting ps = (PackageSetting) pkg.mExtras; 3704 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3705 } 3706 } 3707 } 3708 } 3709 3710 @Override 3711 public int getPermissionFlags(String name, String packageName, int userId) { 3712 if (!sUserManager.exists(userId)) { 3713 return 0; 3714 } 3715 3716 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3717 3718 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3719 "getPermissionFlags"); 3720 3721 synchronized (mPackages) { 3722 final PackageParser.Package pkg = mPackages.get(packageName); 3723 if (pkg == null) { 3724 throw new IllegalArgumentException("Unknown package: " + packageName); 3725 } 3726 3727 final BasePermission bp = mSettings.mPermissions.get(name); 3728 if (bp == null) { 3729 throw new IllegalArgumentException("Unknown permission: " + name); 3730 } 3731 3732 SettingBase sb = (SettingBase) pkg.mExtras; 3733 if (sb == null) { 3734 throw new IllegalArgumentException("Unknown package: " + packageName); 3735 } 3736 3737 PermissionsState permissionsState = sb.getPermissionsState(); 3738 return permissionsState.getPermissionFlags(name, userId); 3739 } 3740 } 3741 3742 @Override 3743 public void updatePermissionFlags(String name, String packageName, int flagMask, 3744 int flagValues, int userId) { 3745 if (!sUserManager.exists(userId)) { 3746 return; 3747 } 3748 3749 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3750 3751 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3752 "updatePermissionFlags"); 3753 3754 // Only the system can change these flags and nothing else. 3755 if (getCallingUid() != Process.SYSTEM_UID) { 3756 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3757 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3758 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3759 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3760 } 3761 3762 synchronized (mPackages) { 3763 final PackageParser.Package pkg = mPackages.get(packageName); 3764 if (pkg == null) { 3765 throw new IllegalArgumentException("Unknown package: " + packageName); 3766 } 3767 3768 final BasePermission bp = mSettings.mPermissions.get(name); 3769 if (bp == null) { 3770 throw new IllegalArgumentException("Unknown permission: " + name); 3771 } 3772 3773 SettingBase sb = (SettingBase) pkg.mExtras; 3774 if (sb == null) { 3775 throw new IllegalArgumentException("Unknown package: " + packageName); 3776 } 3777 3778 PermissionsState permissionsState = sb.getPermissionsState(); 3779 3780 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3781 3782 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3783 // Install and runtime permissions are stored in different places, 3784 // so figure out what permission changed and persist the change. 3785 if (permissionsState.getInstallPermissionState(name) != null) { 3786 scheduleWriteSettingsLocked(); 3787 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3788 || hadState) { 3789 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3790 } 3791 } 3792 } 3793 } 3794 3795 /** 3796 * Update the permission flags for all packages and runtime permissions of a user in order 3797 * to allow device or profile owner to remove POLICY_FIXED. 3798 */ 3799 @Override 3800 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3801 if (!sUserManager.exists(userId)) { 3802 return; 3803 } 3804 3805 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3806 3807 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3808 "updatePermissionFlagsForAllApps"); 3809 3810 // Only the system can change system fixed flags. 3811 if (getCallingUid() != Process.SYSTEM_UID) { 3812 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3813 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3814 } 3815 3816 synchronized (mPackages) { 3817 boolean changed = false; 3818 final int packageCount = mPackages.size(); 3819 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3820 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3821 SettingBase sb = (SettingBase) pkg.mExtras; 3822 if (sb == null) { 3823 continue; 3824 } 3825 PermissionsState permissionsState = sb.getPermissionsState(); 3826 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3827 userId, flagMask, flagValues); 3828 } 3829 if (changed) { 3830 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3831 } 3832 } 3833 } 3834 3835 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3836 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3837 != PackageManager.PERMISSION_GRANTED 3838 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3839 != PackageManager.PERMISSION_GRANTED) { 3840 throw new SecurityException(message + " requires " 3841 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3842 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3843 } 3844 } 3845 3846 @Override 3847 public boolean shouldShowRequestPermissionRationale(String permissionName, 3848 String packageName, int userId) { 3849 if (UserHandle.getCallingUserId() != userId) { 3850 mContext.enforceCallingPermission( 3851 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3852 "canShowRequestPermissionRationale for user " + userId); 3853 } 3854 3855 final int uid = getPackageUid(packageName, userId); 3856 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3857 return false; 3858 } 3859 3860 if (checkPermission(permissionName, packageName, userId) 3861 == PackageManager.PERMISSION_GRANTED) { 3862 return false; 3863 } 3864 3865 final int flags; 3866 3867 final long identity = Binder.clearCallingIdentity(); 3868 try { 3869 flags = getPermissionFlags(permissionName, 3870 packageName, userId); 3871 } finally { 3872 Binder.restoreCallingIdentity(identity); 3873 } 3874 3875 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3876 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3877 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3878 3879 if ((flags & fixedFlags) != 0) { 3880 return false; 3881 } 3882 3883 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3884 } 3885 3886 @Override 3887 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3888 mContext.enforceCallingOrSelfPermission( 3889 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3890 "addOnPermissionsChangeListener"); 3891 3892 synchronized (mPackages) { 3893 mOnPermissionChangeListeners.addListenerLocked(listener); 3894 } 3895 } 3896 3897 @Override 3898 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3899 synchronized (mPackages) { 3900 mOnPermissionChangeListeners.removeListenerLocked(listener); 3901 } 3902 } 3903 3904 @Override 3905 public boolean isProtectedBroadcast(String actionName) { 3906 synchronized (mPackages) { 3907 return mProtectedBroadcasts.contains(actionName); 3908 } 3909 } 3910 3911 @Override 3912 public int checkSignatures(String pkg1, String pkg2) { 3913 synchronized (mPackages) { 3914 final PackageParser.Package p1 = mPackages.get(pkg1); 3915 final PackageParser.Package p2 = mPackages.get(pkg2); 3916 if (p1 == null || p1.mExtras == null 3917 || p2 == null || p2.mExtras == null) { 3918 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3919 } 3920 return compareSignatures(p1.mSignatures, p2.mSignatures); 3921 } 3922 } 3923 3924 @Override 3925 public int checkUidSignatures(int uid1, int uid2) { 3926 // Map to base uids. 3927 uid1 = UserHandle.getAppId(uid1); 3928 uid2 = UserHandle.getAppId(uid2); 3929 // reader 3930 synchronized (mPackages) { 3931 Signature[] s1; 3932 Signature[] s2; 3933 Object obj = mSettings.getUserIdLPr(uid1); 3934 if (obj != null) { 3935 if (obj instanceof SharedUserSetting) { 3936 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3937 } else if (obj instanceof PackageSetting) { 3938 s1 = ((PackageSetting)obj).signatures.mSignatures; 3939 } else { 3940 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3941 } 3942 } else { 3943 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3944 } 3945 obj = mSettings.getUserIdLPr(uid2); 3946 if (obj != null) { 3947 if (obj instanceof SharedUserSetting) { 3948 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3949 } else if (obj instanceof PackageSetting) { 3950 s2 = ((PackageSetting)obj).signatures.mSignatures; 3951 } else { 3952 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3953 } 3954 } else { 3955 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3956 } 3957 return compareSignatures(s1, s2); 3958 } 3959 } 3960 3961 private void killUid(int appId, int userId, String reason) { 3962 final long identity = Binder.clearCallingIdentity(); 3963 try { 3964 IActivityManager am = ActivityManagerNative.getDefault(); 3965 if (am != null) { 3966 try { 3967 am.killUid(appId, userId, reason); 3968 } catch (RemoteException e) { 3969 /* ignore - same process */ 3970 } 3971 } 3972 } finally { 3973 Binder.restoreCallingIdentity(identity); 3974 } 3975 } 3976 3977 /** 3978 * Compares two sets of signatures. Returns: 3979 * <br /> 3980 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3981 * <br /> 3982 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3983 * <br /> 3984 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3985 * <br /> 3986 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3987 * <br /> 3988 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3989 */ 3990 static int compareSignatures(Signature[] s1, Signature[] s2) { 3991 if (s1 == null) { 3992 return s2 == null 3993 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3994 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3995 } 3996 3997 if (s2 == null) { 3998 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3999 } 4000 4001 if (s1.length != s2.length) { 4002 return PackageManager.SIGNATURE_NO_MATCH; 4003 } 4004 4005 // Since both signature sets are of size 1, we can compare without HashSets. 4006 if (s1.length == 1) { 4007 return s1[0].equals(s2[0]) ? 4008 PackageManager.SIGNATURE_MATCH : 4009 PackageManager.SIGNATURE_NO_MATCH; 4010 } 4011 4012 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4013 for (Signature sig : s1) { 4014 set1.add(sig); 4015 } 4016 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4017 for (Signature sig : s2) { 4018 set2.add(sig); 4019 } 4020 // Make sure s2 contains all signatures in s1. 4021 if (set1.equals(set2)) { 4022 return PackageManager.SIGNATURE_MATCH; 4023 } 4024 return PackageManager.SIGNATURE_NO_MATCH; 4025 } 4026 4027 /** 4028 * If the database version for this type of package (internal storage or 4029 * external storage) is less than the version where package signatures 4030 * were updated, return true. 4031 */ 4032 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4033 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4034 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4035 } 4036 4037 /** 4038 * Used for backward compatibility to make sure any packages with 4039 * certificate chains get upgraded to the new style. {@code existingSigs} 4040 * will be in the old format (since they were stored on disk from before the 4041 * system upgrade) and {@code scannedSigs} will be in the newer format. 4042 */ 4043 private int compareSignaturesCompat(PackageSignatures existingSigs, 4044 PackageParser.Package scannedPkg) { 4045 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4046 return PackageManager.SIGNATURE_NO_MATCH; 4047 } 4048 4049 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4050 for (Signature sig : existingSigs.mSignatures) { 4051 existingSet.add(sig); 4052 } 4053 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4054 for (Signature sig : scannedPkg.mSignatures) { 4055 try { 4056 Signature[] chainSignatures = sig.getChainSignatures(); 4057 for (Signature chainSig : chainSignatures) { 4058 scannedCompatSet.add(chainSig); 4059 } 4060 } catch (CertificateEncodingException e) { 4061 scannedCompatSet.add(sig); 4062 } 4063 } 4064 /* 4065 * Make sure the expanded scanned set contains all signatures in the 4066 * existing one. 4067 */ 4068 if (scannedCompatSet.equals(existingSet)) { 4069 // Migrate the old signatures to the new scheme. 4070 existingSigs.assignSignatures(scannedPkg.mSignatures); 4071 // The new KeySets will be re-added later in the scanning process. 4072 synchronized (mPackages) { 4073 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4074 } 4075 return PackageManager.SIGNATURE_MATCH; 4076 } 4077 return PackageManager.SIGNATURE_NO_MATCH; 4078 } 4079 4080 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4081 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4082 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4083 } 4084 4085 private int compareSignaturesRecover(PackageSignatures existingSigs, 4086 PackageParser.Package scannedPkg) { 4087 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4088 return PackageManager.SIGNATURE_NO_MATCH; 4089 } 4090 4091 String msg = null; 4092 try { 4093 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4094 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4095 + scannedPkg.packageName); 4096 return PackageManager.SIGNATURE_MATCH; 4097 } 4098 } catch (CertificateException e) { 4099 msg = e.getMessage(); 4100 } 4101 4102 logCriticalInfo(Log.INFO, 4103 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4104 return PackageManager.SIGNATURE_NO_MATCH; 4105 } 4106 4107 @Override 4108 public String[] getPackagesForUid(int uid) { 4109 uid = UserHandle.getAppId(uid); 4110 // reader 4111 synchronized (mPackages) { 4112 Object obj = mSettings.getUserIdLPr(uid); 4113 if (obj instanceof SharedUserSetting) { 4114 final SharedUserSetting sus = (SharedUserSetting) obj; 4115 final int N = sus.packages.size(); 4116 final String[] res = new String[N]; 4117 final Iterator<PackageSetting> it = sus.packages.iterator(); 4118 int i = 0; 4119 while (it.hasNext()) { 4120 res[i++] = it.next().name; 4121 } 4122 return res; 4123 } else if (obj instanceof PackageSetting) { 4124 final PackageSetting ps = (PackageSetting) obj; 4125 return new String[] { ps.name }; 4126 } 4127 } 4128 return null; 4129 } 4130 4131 @Override 4132 public String getNameForUid(int uid) { 4133 // reader 4134 synchronized (mPackages) { 4135 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4136 if (obj instanceof SharedUserSetting) { 4137 final SharedUserSetting sus = (SharedUserSetting) obj; 4138 return sus.name + ":" + sus.userId; 4139 } else if (obj instanceof PackageSetting) { 4140 final PackageSetting ps = (PackageSetting) obj; 4141 return ps.name; 4142 } 4143 } 4144 return null; 4145 } 4146 4147 @Override 4148 public int getUidForSharedUser(String sharedUserName) { 4149 if(sharedUserName == null) { 4150 return -1; 4151 } 4152 // reader 4153 synchronized (mPackages) { 4154 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4155 if (suid == null) { 4156 return -1; 4157 } 4158 return suid.userId; 4159 } 4160 } 4161 4162 @Override 4163 public int getFlagsForUid(int uid) { 4164 synchronized (mPackages) { 4165 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4166 if (obj instanceof SharedUserSetting) { 4167 final SharedUserSetting sus = (SharedUserSetting) obj; 4168 return sus.pkgFlags; 4169 } else if (obj instanceof PackageSetting) { 4170 final PackageSetting ps = (PackageSetting) obj; 4171 return ps.pkgFlags; 4172 } 4173 } 4174 return 0; 4175 } 4176 4177 @Override 4178 public int getPrivateFlagsForUid(int uid) { 4179 synchronized (mPackages) { 4180 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4181 if (obj instanceof SharedUserSetting) { 4182 final SharedUserSetting sus = (SharedUserSetting) obj; 4183 return sus.pkgPrivateFlags; 4184 } else if (obj instanceof PackageSetting) { 4185 final PackageSetting ps = (PackageSetting) obj; 4186 return ps.pkgPrivateFlags; 4187 } 4188 } 4189 return 0; 4190 } 4191 4192 @Override 4193 public boolean isUidPrivileged(int uid) { 4194 uid = UserHandle.getAppId(uid); 4195 // reader 4196 synchronized (mPackages) { 4197 Object obj = mSettings.getUserIdLPr(uid); 4198 if (obj instanceof SharedUserSetting) { 4199 final SharedUserSetting sus = (SharedUserSetting) obj; 4200 final Iterator<PackageSetting> it = sus.packages.iterator(); 4201 while (it.hasNext()) { 4202 if (it.next().isPrivileged()) { 4203 return true; 4204 } 4205 } 4206 } else if (obj instanceof PackageSetting) { 4207 final PackageSetting ps = (PackageSetting) obj; 4208 return ps.isPrivileged(); 4209 } 4210 } 4211 return false; 4212 } 4213 4214 @Override 4215 public String[] getAppOpPermissionPackages(String permissionName) { 4216 synchronized (mPackages) { 4217 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4218 if (pkgs == null) { 4219 return null; 4220 } 4221 return pkgs.toArray(new String[pkgs.size()]); 4222 } 4223 } 4224 4225 @Override 4226 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4227 int flags, int userId) { 4228 if (!sUserManager.exists(userId)) return null; 4229 flags = augmentFlagsForUser(flags, userId); 4230 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4231 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4232 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4233 } 4234 4235 @Override 4236 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4237 IntentFilter filter, int match, ComponentName activity) { 4238 final int userId = UserHandle.getCallingUserId(); 4239 if (DEBUG_PREFERRED) { 4240 Log.v(TAG, "setLastChosenActivity intent=" + intent 4241 + " resolvedType=" + resolvedType 4242 + " flags=" + flags 4243 + " filter=" + filter 4244 + " match=" + match 4245 + " activity=" + activity); 4246 filter.dump(new PrintStreamPrinter(System.out), " "); 4247 } 4248 intent.setComponent(null); 4249 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4250 // Find any earlier preferred or last chosen entries and nuke them 4251 findPreferredActivity(intent, resolvedType, 4252 flags, query, 0, false, true, false, userId); 4253 // Add the new activity as the last chosen for this filter 4254 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4255 "Setting last chosen"); 4256 } 4257 4258 @Override 4259 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4260 final int userId = UserHandle.getCallingUserId(); 4261 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4262 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4263 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4264 false, false, false, userId); 4265 } 4266 4267 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4268 int flags, List<ResolveInfo> query, int userId) { 4269 if (query != null) { 4270 final int N = query.size(); 4271 if (N == 1) { 4272 return query.get(0); 4273 } else if (N > 1) { 4274 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4275 // If there is more than one activity with the same priority, 4276 // then let the user decide between them. 4277 ResolveInfo r0 = query.get(0); 4278 ResolveInfo r1 = query.get(1); 4279 if (DEBUG_INTENT_MATCHING || debug) { 4280 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4281 + r1.activityInfo.name + "=" + r1.priority); 4282 } 4283 // If the first activity has a higher priority, or a different 4284 // default, then it is always desireable to pick it. 4285 if (r0.priority != r1.priority 4286 || r0.preferredOrder != r1.preferredOrder 4287 || r0.isDefault != r1.isDefault) { 4288 return query.get(0); 4289 } 4290 // If we have saved a preference for a preferred activity for 4291 // this Intent, use that. 4292 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4293 flags, query, r0.priority, true, false, debug, userId); 4294 if (ri != null) { 4295 return ri; 4296 } 4297 ri = new ResolveInfo(mResolveInfo); 4298 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4299 ri.activityInfo.applicationInfo = new ApplicationInfo( 4300 ri.activityInfo.applicationInfo); 4301 if (userId != 0) { 4302 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4303 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4304 } 4305 // Make sure that the resolver is displayable in car mode 4306 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4307 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4308 return ri; 4309 } 4310 } 4311 return null; 4312 } 4313 4314 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4315 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4316 final int N = query.size(); 4317 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4318 .get(userId); 4319 // Get the list of persistent preferred activities that handle the intent 4320 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4321 List<PersistentPreferredActivity> pprefs = ppir != null 4322 ? ppir.queryIntent(intent, resolvedType, 4323 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4324 : null; 4325 if (pprefs != null && pprefs.size() > 0) { 4326 final int M = pprefs.size(); 4327 for (int i=0; i<M; i++) { 4328 final PersistentPreferredActivity ppa = pprefs.get(i); 4329 if (DEBUG_PREFERRED || debug) { 4330 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4331 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4332 + "\n component=" + ppa.mComponent); 4333 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4334 } 4335 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4336 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4337 if (DEBUG_PREFERRED || debug) { 4338 Slog.v(TAG, "Found persistent preferred activity:"); 4339 if (ai != null) { 4340 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4341 } else { 4342 Slog.v(TAG, " null"); 4343 } 4344 } 4345 if (ai == null) { 4346 // This previously registered persistent preferred activity 4347 // component is no longer known. Ignore it and do NOT remove it. 4348 continue; 4349 } 4350 for (int j=0; j<N; j++) { 4351 final ResolveInfo ri = query.get(j); 4352 if (!ri.activityInfo.applicationInfo.packageName 4353 .equals(ai.applicationInfo.packageName)) { 4354 continue; 4355 } 4356 if (!ri.activityInfo.name.equals(ai.name)) { 4357 continue; 4358 } 4359 // Found a persistent preference that can handle the intent. 4360 if (DEBUG_PREFERRED || debug) { 4361 Slog.v(TAG, "Returning persistent preferred activity: " + 4362 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4363 } 4364 return ri; 4365 } 4366 } 4367 } 4368 return null; 4369 } 4370 4371 // TODO: handle preferred activities missing while user has amnesia 4372 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4373 List<ResolveInfo> query, int priority, boolean always, 4374 boolean removeMatches, boolean debug, int userId) { 4375 if (!sUserManager.exists(userId)) return null; 4376 flags = augmentFlagsForUser(flags, userId); 4377 // writer 4378 synchronized (mPackages) { 4379 if (intent.getSelector() != null) { 4380 intent = intent.getSelector(); 4381 } 4382 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4383 4384 // Try to find a matching persistent preferred activity. 4385 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4386 debug, userId); 4387 4388 // If a persistent preferred activity matched, use it. 4389 if (pri != null) { 4390 return pri; 4391 } 4392 4393 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4394 // Get the list of preferred activities that handle the intent 4395 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4396 List<PreferredActivity> prefs = pir != null 4397 ? pir.queryIntent(intent, resolvedType, 4398 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4399 : null; 4400 if (prefs != null && prefs.size() > 0) { 4401 boolean changed = false; 4402 try { 4403 // First figure out how good the original match set is. 4404 // We will only allow preferred activities that came 4405 // from the same match quality. 4406 int match = 0; 4407 4408 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4409 4410 final int N = query.size(); 4411 for (int j=0; j<N; j++) { 4412 final ResolveInfo ri = query.get(j); 4413 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4414 + ": 0x" + Integer.toHexString(match)); 4415 if (ri.match > match) { 4416 match = ri.match; 4417 } 4418 } 4419 4420 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4421 + Integer.toHexString(match)); 4422 4423 match &= IntentFilter.MATCH_CATEGORY_MASK; 4424 final int M = prefs.size(); 4425 for (int i=0; i<M; i++) { 4426 final PreferredActivity pa = prefs.get(i); 4427 if (DEBUG_PREFERRED || debug) { 4428 Slog.v(TAG, "Checking PreferredActivity ds=" 4429 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4430 + "\n component=" + pa.mPref.mComponent); 4431 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4432 } 4433 if (pa.mPref.mMatch != match) { 4434 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4435 + Integer.toHexString(pa.mPref.mMatch)); 4436 continue; 4437 } 4438 // If it's not an "always" type preferred activity and that's what we're 4439 // looking for, skip it. 4440 if (always && !pa.mPref.mAlways) { 4441 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4442 continue; 4443 } 4444 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4445 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4446 if (DEBUG_PREFERRED || debug) { 4447 Slog.v(TAG, "Found preferred activity:"); 4448 if (ai != null) { 4449 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4450 } else { 4451 Slog.v(TAG, " null"); 4452 } 4453 } 4454 if (ai == null) { 4455 // This previously registered preferred activity 4456 // component is no longer known. Most likely an update 4457 // to the app was installed and in the new version this 4458 // component no longer exists. Clean it up by removing 4459 // it from the preferred activities list, and skip it. 4460 Slog.w(TAG, "Removing dangling preferred activity: " 4461 + pa.mPref.mComponent); 4462 pir.removeFilter(pa); 4463 changed = true; 4464 continue; 4465 } 4466 for (int j=0; j<N; j++) { 4467 final ResolveInfo ri = query.get(j); 4468 if (!ri.activityInfo.applicationInfo.packageName 4469 .equals(ai.applicationInfo.packageName)) { 4470 continue; 4471 } 4472 if (!ri.activityInfo.name.equals(ai.name)) { 4473 continue; 4474 } 4475 4476 if (removeMatches) { 4477 pir.removeFilter(pa); 4478 changed = true; 4479 if (DEBUG_PREFERRED) { 4480 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4481 } 4482 break; 4483 } 4484 4485 // Okay we found a previously set preferred or last chosen app. 4486 // If the result set is different from when this 4487 // was created, we need to clear it and re-ask the 4488 // user their preference, if we're looking for an "always" type entry. 4489 if (always && !pa.mPref.sameSet(query)) { 4490 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4491 + intent + " type " + resolvedType); 4492 if (DEBUG_PREFERRED) { 4493 Slog.v(TAG, "Removing preferred activity since set changed " 4494 + pa.mPref.mComponent); 4495 } 4496 pir.removeFilter(pa); 4497 // Re-add the filter as a "last chosen" entry (!always) 4498 PreferredActivity lastChosen = new PreferredActivity( 4499 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4500 pir.addFilter(lastChosen); 4501 changed = true; 4502 return null; 4503 } 4504 4505 // Yay! Either the set matched or we're looking for the last chosen 4506 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4507 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4508 return ri; 4509 } 4510 } 4511 } finally { 4512 if (changed) { 4513 if (DEBUG_PREFERRED) { 4514 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4515 } 4516 scheduleWritePackageRestrictionsLocked(userId); 4517 } 4518 } 4519 } 4520 } 4521 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4522 return null; 4523 } 4524 4525 /* 4526 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4527 */ 4528 @Override 4529 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4530 int targetUserId) { 4531 mContext.enforceCallingOrSelfPermission( 4532 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4533 List<CrossProfileIntentFilter> matches = 4534 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4535 if (matches != null) { 4536 int size = matches.size(); 4537 for (int i = 0; i < size; i++) { 4538 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4539 } 4540 } 4541 if (hasWebURI(intent)) { 4542 // cross-profile app linking works only towards the parent. 4543 final UserInfo parent = getProfileParent(sourceUserId); 4544 synchronized(mPackages) { 4545 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4546 intent, resolvedType, 0, sourceUserId, parent.id); 4547 return xpDomainInfo != null; 4548 } 4549 } 4550 return false; 4551 } 4552 4553 private UserInfo getProfileParent(int userId) { 4554 final long identity = Binder.clearCallingIdentity(); 4555 try { 4556 return sUserManager.getProfileParent(userId); 4557 } finally { 4558 Binder.restoreCallingIdentity(identity); 4559 } 4560 } 4561 4562 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4563 String resolvedType, int userId) { 4564 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4565 if (resolver != null) { 4566 return resolver.queryIntent(intent, resolvedType, false, userId); 4567 } 4568 return null; 4569 } 4570 4571 @Override 4572 public List<ResolveInfo> queryIntentActivities(Intent intent, 4573 String resolvedType, int flags, int userId) { 4574 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4575 flags = augmentFlagsForUser(flags, userId); 4576 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4577 ComponentName comp = intent.getComponent(); 4578 if (comp == null) { 4579 if (intent.getSelector() != null) { 4580 intent = intent.getSelector(); 4581 comp = intent.getComponent(); 4582 } 4583 } 4584 4585 if (comp != null) { 4586 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4587 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4588 if (ai != null) { 4589 final ResolveInfo ri = new ResolveInfo(); 4590 ri.activityInfo = ai; 4591 list.add(ri); 4592 } 4593 return list; 4594 } 4595 4596 // reader 4597 synchronized (mPackages) { 4598 final String pkgName = intent.getPackage(); 4599 if (pkgName == null) { 4600 List<CrossProfileIntentFilter> matchingFilters = 4601 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4602 // Check for results that need to skip the current profile. 4603 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4604 resolvedType, flags, userId); 4605 if (xpResolveInfo != null) { 4606 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4607 result.add(xpResolveInfo); 4608 return filterIfNotSystemUser(result, userId); 4609 } 4610 4611 // Check for results in the current profile. 4612 List<ResolveInfo> result = mActivities.queryIntent( 4613 intent, resolvedType, flags, userId); 4614 4615 // Check for cross profile results. 4616 xpResolveInfo = queryCrossProfileIntents( 4617 matchingFilters, intent, resolvedType, flags, userId); 4618 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4619 result.add(xpResolveInfo); 4620 Collections.sort(result, mResolvePrioritySorter); 4621 } 4622 result = filterIfNotSystemUser(result, userId); 4623 if (hasWebURI(intent)) { 4624 CrossProfileDomainInfo xpDomainInfo = null; 4625 final UserInfo parent = getProfileParent(userId); 4626 if (parent != null) { 4627 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4628 flags, userId, parent.id); 4629 } 4630 if (xpDomainInfo != null) { 4631 if (xpResolveInfo != null) { 4632 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4633 // in the result. 4634 result.remove(xpResolveInfo); 4635 } 4636 if (result.size() == 0) { 4637 result.add(xpDomainInfo.resolveInfo); 4638 return result; 4639 } 4640 } else if (result.size() <= 1) { 4641 return result; 4642 } 4643 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4644 xpDomainInfo, userId); 4645 Collections.sort(result, mResolvePrioritySorter); 4646 } 4647 return result; 4648 } 4649 final PackageParser.Package pkg = mPackages.get(pkgName); 4650 if (pkg != null) { 4651 return filterIfNotSystemUser( 4652 mActivities.queryIntentForPackage( 4653 intent, resolvedType, flags, pkg.activities, userId), 4654 userId); 4655 } 4656 return new ArrayList<ResolveInfo>(); 4657 } 4658 } 4659 4660 private static class CrossProfileDomainInfo { 4661 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4662 ResolveInfo resolveInfo; 4663 /* Best domain verification status of the activities found in the other profile */ 4664 int bestDomainVerificationStatus; 4665 } 4666 4667 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4668 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4669 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4670 sourceUserId)) { 4671 return null; 4672 } 4673 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4674 resolvedType, flags, parentUserId); 4675 4676 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4677 return null; 4678 } 4679 CrossProfileDomainInfo result = null; 4680 int size = resultTargetUser.size(); 4681 for (int i = 0; i < size; i++) { 4682 ResolveInfo riTargetUser = resultTargetUser.get(i); 4683 // Intent filter verification is only for filters that specify a host. So don't return 4684 // those that handle all web uris. 4685 if (riTargetUser.handleAllWebDataURI) { 4686 continue; 4687 } 4688 String packageName = riTargetUser.activityInfo.packageName; 4689 PackageSetting ps = mSettings.mPackages.get(packageName); 4690 if (ps == null) { 4691 continue; 4692 } 4693 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4694 int status = (int)(verificationState >> 32); 4695 if (result == null) { 4696 result = new CrossProfileDomainInfo(); 4697 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4698 sourceUserId, parentUserId); 4699 result.bestDomainVerificationStatus = status; 4700 } else { 4701 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4702 result.bestDomainVerificationStatus); 4703 } 4704 } 4705 // Don't consider matches with status NEVER across profiles. 4706 if (result != null && result.bestDomainVerificationStatus 4707 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4708 return null; 4709 } 4710 return result; 4711 } 4712 4713 /** 4714 * Verification statuses are ordered from the worse to the best, except for 4715 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4716 */ 4717 private int bestDomainVerificationStatus(int status1, int status2) { 4718 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4719 return status2; 4720 } 4721 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4722 return status1; 4723 } 4724 return (int) MathUtils.max(status1, status2); 4725 } 4726 4727 private boolean isUserEnabled(int userId) { 4728 long callingId = Binder.clearCallingIdentity(); 4729 try { 4730 UserInfo userInfo = sUserManager.getUserInfo(userId); 4731 return userInfo != null && userInfo.isEnabled(); 4732 } finally { 4733 Binder.restoreCallingIdentity(callingId); 4734 } 4735 } 4736 4737 /** 4738 * Filter out activities with systemUserOnly flag set, when current user is not System. 4739 * 4740 * @return filtered list 4741 */ 4742 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4743 if (userId == UserHandle.USER_SYSTEM) { 4744 return resolveInfos; 4745 } 4746 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4747 ResolveInfo info = resolveInfos.get(i); 4748 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4749 resolveInfos.remove(i); 4750 } 4751 } 4752 return resolveInfos; 4753 } 4754 4755 private static boolean hasWebURI(Intent intent) { 4756 if (intent.getData() == null) { 4757 return false; 4758 } 4759 final String scheme = intent.getScheme(); 4760 if (TextUtils.isEmpty(scheme)) { 4761 return false; 4762 } 4763 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4764 } 4765 4766 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4767 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4768 int userId) { 4769 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4770 4771 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4772 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4773 candidates.size()); 4774 } 4775 4776 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4777 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4778 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4779 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4780 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4781 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4782 4783 synchronized (mPackages) { 4784 final int count = candidates.size(); 4785 // First, try to use linked apps. Partition the candidates into four lists: 4786 // one for the final results, one for the "do not use ever", one for "undefined status" 4787 // and finally one for "browser app type". 4788 for (int n=0; n<count; n++) { 4789 ResolveInfo info = candidates.get(n); 4790 String packageName = info.activityInfo.packageName; 4791 PackageSetting ps = mSettings.mPackages.get(packageName); 4792 if (ps != null) { 4793 // Add to the special match all list (Browser use case) 4794 if (info.handleAllWebDataURI) { 4795 matchAllList.add(info); 4796 continue; 4797 } 4798 // Try to get the status from User settings first 4799 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4800 int status = (int)(packedStatus >> 32); 4801 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4802 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4803 if (DEBUG_DOMAIN_VERIFICATION) { 4804 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4805 + " : linkgen=" + linkGeneration); 4806 } 4807 // Use link-enabled generation as preferredOrder, i.e. 4808 // prefer newly-enabled over earlier-enabled. 4809 info.preferredOrder = linkGeneration; 4810 alwaysList.add(info); 4811 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4812 if (DEBUG_DOMAIN_VERIFICATION) { 4813 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4814 } 4815 neverList.add(info); 4816 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4817 if (DEBUG_DOMAIN_VERIFICATION) { 4818 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4819 } 4820 alwaysAskList.add(info); 4821 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4822 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4823 if (DEBUG_DOMAIN_VERIFICATION) { 4824 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4825 } 4826 undefinedList.add(info); 4827 } 4828 } 4829 } 4830 4831 // We'll want to include browser possibilities in a few cases 4832 boolean includeBrowser = false; 4833 4834 // First try to add the "always" resolution(s) for the current user, if any 4835 if (alwaysList.size() > 0) { 4836 result.addAll(alwaysList); 4837 } else { 4838 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4839 result.addAll(undefinedList); 4840 // Maybe add one for the other profile. 4841 if (xpDomainInfo != null && ( 4842 xpDomainInfo.bestDomainVerificationStatus 4843 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4844 result.add(xpDomainInfo.resolveInfo); 4845 } 4846 includeBrowser = true; 4847 } 4848 4849 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4850 // If there were 'always' entries their preferred order has been set, so we also 4851 // back that off to make the alternatives equivalent 4852 if (alwaysAskList.size() > 0) { 4853 for (ResolveInfo i : result) { 4854 i.preferredOrder = 0; 4855 } 4856 result.addAll(alwaysAskList); 4857 includeBrowser = true; 4858 } 4859 4860 if (includeBrowser) { 4861 // Also add browsers (all of them or only the default one) 4862 if (DEBUG_DOMAIN_VERIFICATION) { 4863 Slog.v(TAG, " ...including browsers in candidate set"); 4864 } 4865 if ((matchFlags & MATCH_ALL) != 0) { 4866 result.addAll(matchAllList); 4867 } else { 4868 // Browser/generic handling case. If there's a default browser, go straight 4869 // to that (but only if there is no other higher-priority match). 4870 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4871 int maxMatchPrio = 0; 4872 ResolveInfo defaultBrowserMatch = null; 4873 final int numCandidates = matchAllList.size(); 4874 for (int n = 0; n < numCandidates; n++) { 4875 ResolveInfo info = matchAllList.get(n); 4876 // track the highest overall match priority... 4877 if (info.priority > maxMatchPrio) { 4878 maxMatchPrio = info.priority; 4879 } 4880 // ...and the highest-priority default browser match 4881 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4882 if (defaultBrowserMatch == null 4883 || (defaultBrowserMatch.priority < info.priority)) { 4884 if (debug) { 4885 Slog.v(TAG, "Considering default browser match " + info); 4886 } 4887 defaultBrowserMatch = info; 4888 } 4889 } 4890 } 4891 if (defaultBrowserMatch != null 4892 && defaultBrowserMatch.priority >= maxMatchPrio 4893 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4894 { 4895 if (debug) { 4896 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4897 } 4898 result.add(defaultBrowserMatch); 4899 } else { 4900 result.addAll(matchAllList); 4901 } 4902 } 4903 4904 // If there is nothing selected, add all candidates and remove the ones that the user 4905 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4906 if (result.size() == 0) { 4907 result.addAll(candidates); 4908 result.removeAll(neverList); 4909 } 4910 } 4911 } 4912 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4913 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4914 result.size()); 4915 for (ResolveInfo info : result) { 4916 Slog.v(TAG, " + " + info.activityInfo); 4917 } 4918 } 4919 return result; 4920 } 4921 4922 // Returns a packed value as a long: 4923 // 4924 // high 'int'-sized word: link status: undefined/ask/never/always. 4925 // low 'int'-sized word: relative priority among 'always' results. 4926 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4927 long result = ps.getDomainVerificationStatusForUser(userId); 4928 // if none available, get the master status 4929 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4930 if (ps.getIntentFilterVerificationInfo() != null) { 4931 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4932 } 4933 } 4934 return result; 4935 } 4936 4937 private ResolveInfo querySkipCurrentProfileIntents( 4938 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4939 int flags, int sourceUserId) { 4940 if (matchingFilters != null) { 4941 int size = matchingFilters.size(); 4942 for (int i = 0; i < size; i ++) { 4943 CrossProfileIntentFilter filter = matchingFilters.get(i); 4944 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4945 // Checking if there are activities in the target user that can handle the 4946 // intent. 4947 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4948 resolvedType, flags, sourceUserId); 4949 if (resolveInfo != null) { 4950 return resolveInfo; 4951 } 4952 } 4953 } 4954 } 4955 return null; 4956 } 4957 4958 // Return matching ResolveInfo if any for skip current profile intent filters. 4959 private ResolveInfo queryCrossProfileIntents( 4960 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4961 int flags, int sourceUserId) { 4962 if (matchingFilters != null) { 4963 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4964 // match the same intent. For performance reasons, it is better not to 4965 // run queryIntent twice for the same userId 4966 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4967 int size = matchingFilters.size(); 4968 for (int i = 0; i < size; i++) { 4969 CrossProfileIntentFilter filter = matchingFilters.get(i); 4970 int targetUserId = filter.getTargetUserId(); 4971 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4972 && !alreadyTriedUserIds.get(targetUserId)) { 4973 // Checking if there are activities in the target user that can handle the 4974 // intent. 4975 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4976 resolvedType, flags, sourceUserId); 4977 if (resolveInfo != null) return resolveInfo; 4978 alreadyTriedUserIds.put(targetUserId, true); 4979 } 4980 } 4981 } 4982 return null; 4983 } 4984 4985 /** 4986 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4987 * will forward the intent to the filter's target user. 4988 * Otherwise, returns null. 4989 */ 4990 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4991 String resolvedType, int flags, int sourceUserId) { 4992 int targetUserId = filter.getTargetUserId(); 4993 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4994 resolvedType, flags, targetUserId); 4995 if (resultTargetUser != null && !resultTargetUser.isEmpty() 4996 && isUserEnabled(targetUserId)) { 4997 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 4998 } 4999 return null; 5000 } 5001 5002 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5003 int sourceUserId, int targetUserId) { 5004 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5005 long ident = Binder.clearCallingIdentity(); 5006 boolean targetIsProfile; 5007 try { 5008 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5009 } finally { 5010 Binder.restoreCallingIdentity(ident); 5011 } 5012 String className; 5013 if (targetIsProfile) { 5014 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5015 } else { 5016 className = FORWARD_INTENT_TO_PARENT; 5017 } 5018 ComponentName forwardingActivityComponentName = new ComponentName( 5019 mAndroidApplication.packageName, className); 5020 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5021 sourceUserId); 5022 if (!targetIsProfile) { 5023 forwardingActivityInfo.showUserIcon = targetUserId; 5024 forwardingResolveInfo.noResourceId = true; 5025 } 5026 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5027 forwardingResolveInfo.priority = 0; 5028 forwardingResolveInfo.preferredOrder = 0; 5029 forwardingResolveInfo.match = 0; 5030 forwardingResolveInfo.isDefault = true; 5031 forwardingResolveInfo.filter = filter; 5032 forwardingResolveInfo.targetUserId = targetUserId; 5033 return forwardingResolveInfo; 5034 } 5035 5036 @Override 5037 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5038 Intent[] specifics, String[] specificTypes, Intent intent, 5039 String resolvedType, int flags, int userId) { 5040 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5041 flags = augmentFlagsForUser(flags, userId); 5042 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5043 false, "query intent activity options"); 5044 final String resultsAction = intent.getAction(); 5045 5046 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5047 | PackageManager.GET_RESOLVED_FILTER, userId); 5048 5049 if (DEBUG_INTENT_MATCHING) { 5050 Log.v(TAG, "Query " + intent + ": " + results); 5051 } 5052 5053 int specificsPos = 0; 5054 int N; 5055 5056 // todo: note that the algorithm used here is O(N^2). This 5057 // isn't a problem in our current environment, but if we start running 5058 // into situations where we have more than 5 or 10 matches then this 5059 // should probably be changed to something smarter... 5060 5061 // First we go through and resolve each of the specific items 5062 // that were supplied, taking care of removing any corresponding 5063 // duplicate items in the generic resolve list. 5064 if (specifics != null) { 5065 for (int i=0; i<specifics.length; i++) { 5066 final Intent sintent = specifics[i]; 5067 if (sintent == null) { 5068 continue; 5069 } 5070 5071 if (DEBUG_INTENT_MATCHING) { 5072 Log.v(TAG, "Specific #" + i + ": " + sintent); 5073 } 5074 5075 String action = sintent.getAction(); 5076 if (resultsAction != null && resultsAction.equals(action)) { 5077 // If this action was explicitly requested, then don't 5078 // remove things that have it. 5079 action = null; 5080 } 5081 5082 ResolveInfo ri = null; 5083 ActivityInfo ai = null; 5084 5085 ComponentName comp = sintent.getComponent(); 5086 if (comp == null) { 5087 ri = resolveIntent( 5088 sintent, 5089 specificTypes != null ? specificTypes[i] : null, 5090 flags, userId); 5091 if (ri == null) { 5092 continue; 5093 } 5094 if (ri == mResolveInfo) { 5095 // ACK! Must do something better with this. 5096 } 5097 ai = ri.activityInfo; 5098 comp = new ComponentName(ai.applicationInfo.packageName, 5099 ai.name); 5100 } else { 5101 ai = getActivityInfo(comp, flags, userId); 5102 if (ai == null) { 5103 continue; 5104 } 5105 } 5106 5107 // Look for any generic query activities that are duplicates 5108 // of this specific one, and remove them from the results. 5109 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5110 N = results.size(); 5111 int j; 5112 for (j=specificsPos; j<N; j++) { 5113 ResolveInfo sri = results.get(j); 5114 if ((sri.activityInfo.name.equals(comp.getClassName()) 5115 && sri.activityInfo.applicationInfo.packageName.equals( 5116 comp.getPackageName())) 5117 || (action != null && sri.filter.matchAction(action))) { 5118 results.remove(j); 5119 if (DEBUG_INTENT_MATCHING) Log.v( 5120 TAG, "Removing duplicate item from " + j 5121 + " due to specific " + specificsPos); 5122 if (ri == null) { 5123 ri = sri; 5124 } 5125 j--; 5126 N--; 5127 } 5128 } 5129 5130 // Add this specific item to its proper place. 5131 if (ri == null) { 5132 ri = new ResolveInfo(); 5133 ri.activityInfo = ai; 5134 } 5135 results.add(specificsPos, ri); 5136 ri.specificIndex = i; 5137 specificsPos++; 5138 } 5139 } 5140 5141 // Now we go through the remaining generic results and remove any 5142 // duplicate actions that are found here. 5143 N = results.size(); 5144 for (int i=specificsPos; i<N-1; i++) { 5145 final ResolveInfo rii = results.get(i); 5146 if (rii.filter == null) { 5147 continue; 5148 } 5149 5150 // Iterate over all of the actions of this result's intent 5151 // filter... typically this should be just one. 5152 final Iterator<String> it = rii.filter.actionsIterator(); 5153 if (it == null) { 5154 continue; 5155 } 5156 while (it.hasNext()) { 5157 final String action = it.next(); 5158 if (resultsAction != null && resultsAction.equals(action)) { 5159 // If this action was explicitly requested, then don't 5160 // remove things that have it. 5161 continue; 5162 } 5163 for (int j=i+1; j<N; j++) { 5164 final ResolveInfo rij = results.get(j); 5165 if (rij.filter != null && rij.filter.hasAction(action)) { 5166 results.remove(j); 5167 if (DEBUG_INTENT_MATCHING) Log.v( 5168 TAG, "Removing duplicate item from " + j 5169 + " due to action " + action + " at " + i); 5170 j--; 5171 N--; 5172 } 5173 } 5174 } 5175 5176 // If the caller didn't request filter information, drop it now 5177 // so we don't have to marshall/unmarshall it. 5178 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5179 rii.filter = null; 5180 } 5181 } 5182 5183 // Filter out the caller activity if so requested. 5184 if (caller != null) { 5185 N = results.size(); 5186 for (int i=0; i<N; i++) { 5187 ActivityInfo ainfo = results.get(i).activityInfo; 5188 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5189 && caller.getClassName().equals(ainfo.name)) { 5190 results.remove(i); 5191 break; 5192 } 5193 } 5194 } 5195 5196 // If the caller didn't request filter information, 5197 // drop them now so we don't have to 5198 // marshall/unmarshall it. 5199 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5200 N = results.size(); 5201 for (int i=0; i<N; i++) { 5202 results.get(i).filter = null; 5203 } 5204 } 5205 5206 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5207 return results; 5208 } 5209 5210 @Override 5211 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5212 int userId) { 5213 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5214 flags = augmentFlagsForUser(flags, userId); 5215 ComponentName comp = intent.getComponent(); 5216 if (comp == null) { 5217 if (intent.getSelector() != null) { 5218 intent = intent.getSelector(); 5219 comp = intent.getComponent(); 5220 } 5221 } 5222 if (comp != null) { 5223 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5224 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5225 if (ai != null) { 5226 ResolveInfo ri = new ResolveInfo(); 5227 ri.activityInfo = ai; 5228 list.add(ri); 5229 } 5230 return list; 5231 } 5232 5233 // reader 5234 synchronized (mPackages) { 5235 String pkgName = intent.getPackage(); 5236 if (pkgName == null) { 5237 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5238 } 5239 final PackageParser.Package pkg = mPackages.get(pkgName); 5240 if (pkg != null) { 5241 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5242 userId); 5243 } 5244 return null; 5245 } 5246 } 5247 5248 @Override 5249 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5250 if (!sUserManager.exists(userId)) return null; 5251 flags = augmentFlagsForUser(flags, userId); 5252 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5253 if (query != null) { 5254 if (query.size() >= 1) { 5255 // If there is more than one service with the same priority, 5256 // just arbitrarily pick the first one. 5257 return query.get(0); 5258 } 5259 } 5260 return null; 5261 } 5262 5263 @Override 5264 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5265 int userId) { 5266 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5267 flags = augmentFlagsForUser(flags, userId); 5268 ComponentName comp = intent.getComponent(); 5269 if (comp == null) { 5270 if (intent.getSelector() != null) { 5271 intent = intent.getSelector(); 5272 comp = intent.getComponent(); 5273 } 5274 } 5275 if (comp != null) { 5276 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5277 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5278 if (si != null) { 5279 final ResolveInfo ri = new ResolveInfo(); 5280 ri.serviceInfo = si; 5281 list.add(ri); 5282 } 5283 return list; 5284 } 5285 5286 // reader 5287 synchronized (mPackages) { 5288 String pkgName = intent.getPackage(); 5289 if (pkgName == null) { 5290 return mServices.queryIntent(intent, resolvedType, flags, userId); 5291 } 5292 final PackageParser.Package pkg = mPackages.get(pkgName); 5293 if (pkg != null) { 5294 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5295 userId); 5296 } 5297 return null; 5298 } 5299 } 5300 5301 @Override 5302 public List<ResolveInfo> queryIntentContentProviders( 5303 Intent intent, String resolvedType, int flags, int userId) { 5304 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5305 flags = augmentFlagsForUser(flags, userId); 5306 ComponentName comp = intent.getComponent(); 5307 if (comp == null) { 5308 if (intent.getSelector() != null) { 5309 intent = intent.getSelector(); 5310 comp = intent.getComponent(); 5311 } 5312 } 5313 if (comp != null) { 5314 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5315 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5316 if (pi != null) { 5317 final ResolveInfo ri = new ResolveInfo(); 5318 ri.providerInfo = pi; 5319 list.add(ri); 5320 } 5321 return list; 5322 } 5323 5324 // reader 5325 synchronized (mPackages) { 5326 String pkgName = intent.getPackage(); 5327 if (pkgName == null) { 5328 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5329 } 5330 final PackageParser.Package pkg = mPackages.get(pkgName); 5331 if (pkg != null) { 5332 return mProviders.queryIntentForPackage( 5333 intent, resolvedType, flags, pkg.providers, userId); 5334 } 5335 return null; 5336 } 5337 } 5338 5339 @Override 5340 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5341 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5342 5343 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5344 5345 // writer 5346 synchronized (mPackages) { 5347 ArrayList<PackageInfo> list; 5348 if (listUninstalled) { 5349 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5350 for (PackageSetting ps : mSettings.mPackages.values()) { 5351 PackageInfo pi; 5352 if (ps.pkg != null) { 5353 pi = generatePackageInfo(ps.pkg, flags, userId); 5354 } else { 5355 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5356 } 5357 if (pi != null) { 5358 list.add(pi); 5359 } 5360 } 5361 } else { 5362 list = new ArrayList<PackageInfo>(mPackages.size()); 5363 for (PackageParser.Package p : mPackages.values()) { 5364 PackageInfo pi = generatePackageInfo(p, flags, userId); 5365 if (pi != null) { 5366 list.add(pi); 5367 } 5368 } 5369 } 5370 5371 return new ParceledListSlice<PackageInfo>(list); 5372 } 5373 } 5374 5375 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5376 String[] permissions, boolean[] tmp, int flags, int userId) { 5377 int numMatch = 0; 5378 final PermissionsState permissionsState = ps.getPermissionsState(); 5379 for (int i=0; i<permissions.length; i++) { 5380 final String permission = permissions[i]; 5381 if (permissionsState.hasPermission(permission, userId)) { 5382 tmp[i] = true; 5383 numMatch++; 5384 } else { 5385 tmp[i] = false; 5386 } 5387 } 5388 if (numMatch == 0) { 5389 return; 5390 } 5391 PackageInfo pi; 5392 if (ps.pkg != null) { 5393 pi = generatePackageInfo(ps.pkg, flags, userId); 5394 } else { 5395 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5396 } 5397 // The above might return null in cases of uninstalled apps or install-state 5398 // skew across users/profiles. 5399 if (pi != null) { 5400 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5401 if (numMatch == permissions.length) { 5402 pi.requestedPermissions = permissions; 5403 } else { 5404 pi.requestedPermissions = new String[numMatch]; 5405 numMatch = 0; 5406 for (int i=0; i<permissions.length; i++) { 5407 if (tmp[i]) { 5408 pi.requestedPermissions[numMatch] = permissions[i]; 5409 numMatch++; 5410 } 5411 } 5412 } 5413 } 5414 list.add(pi); 5415 } 5416 } 5417 5418 @Override 5419 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5420 String[] permissions, int flags, int userId) { 5421 if (!sUserManager.exists(userId)) return null; 5422 flags = augmentFlagsForUser(flags, userId); 5423 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5424 5425 // writer 5426 synchronized (mPackages) { 5427 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5428 boolean[] tmpBools = new boolean[permissions.length]; 5429 if (listUninstalled) { 5430 for (PackageSetting ps : mSettings.mPackages.values()) { 5431 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5432 } 5433 } else { 5434 for (PackageParser.Package pkg : mPackages.values()) { 5435 PackageSetting ps = (PackageSetting)pkg.mExtras; 5436 if (ps != null) { 5437 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5438 userId); 5439 } 5440 } 5441 } 5442 5443 return new ParceledListSlice<PackageInfo>(list); 5444 } 5445 } 5446 5447 @Override 5448 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5449 if (!sUserManager.exists(userId)) return null; 5450 flags = augmentFlagsForUser(flags, userId); 5451 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5452 5453 // writer 5454 synchronized (mPackages) { 5455 ArrayList<ApplicationInfo> list; 5456 if (listUninstalled) { 5457 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5458 for (PackageSetting ps : mSettings.mPackages.values()) { 5459 ApplicationInfo ai; 5460 if (ps.pkg != null) { 5461 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5462 ps.readUserState(userId), userId); 5463 } else { 5464 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5465 } 5466 if (ai != null) { 5467 list.add(ai); 5468 } 5469 } 5470 } else { 5471 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5472 for (PackageParser.Package p : mPackages.values()) { 5473 if (p.mExtras != null) { 5474 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5475 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5476 if (ai != null) { 5477 list.add(ai); 5478 } 5479 } 5480 } 5481 } 5482 5483 return new ParceledListSlice<ApplicationInfo>(list); 5484 } 5485 } 5486 5487 public List<ApplicationInfo> getPersistentApplications(int flags) { 5488 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5489 5490 // reader 5491 synchronized (mPackages) { 5492 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5493 final int userId = UserHandle.getCallingUserId(); 5494 while (i.hasNext()) { 5495 final PackageParser.Package p = i.next(); 5496 if (p.applicationInfo != null 5497 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5498 && (!mSafeMode || isSystemApp(p))) { 5499 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5500 if (ps != null) { 5501 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5502 ps.readUserState(userId), userId); 5503 if (ai != null) { 5504 finalList.add(ai); 5505 } 5506 } 5507 } 5508 } 5509 } 5510 5511 return finalList; 5512 } 5513 5514 @Override 5515 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5516 if (!sUserManager.exists(userId)) return null; 5517 flags = augmentFlagsForUser(flags, userId); 5518 // reader 5519 synchronized (mPackages) { 5520 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5521 PackageSetting ps = provider != null 5522 ? mSettings.mPackages.get(provider.owner.packageName) 5523 : null; 5524 return ps != null 5525 && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId) 5526 && (!mSafeMode || (provider.info.applicationInfo.flags 5527 &ApplicationInfo.FLAG_SYSTEM) != 0) 5528 ? PackageParser.generateProviderInfo(provider, flags, 5529 ps.readUserState(userId), userId) 5530 : null; 5531 } 5532 } 5533 5534 /** 5535 * @deprecated 5536 */ 5537 @Deprecated 5538 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5539 // reader 5540 synchronized (mPackages) { 5541 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5542 .entrySet().iterator(); 5543 final int userId = UserHandle.getCallingUserId(); 5544 while (i.hasNext()) { 5545 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5546 PackageParser.Provider p = entry.getValue(); 5547 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5548 5549 if (ps != null && p.syncable 5550 && (!mSafeMode || (p.info.applicationInfo.flags 5551 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5552 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5553 ps.readUserState(userId), userId); 5554 if (info != null) { 5555 outNames.add(entry.getKey()); 5556 outInfo.add(info); 5557 } 5558 } 5559 } 5560 } 5561 } 5562 5563 @Override 5564 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5565 int uid, int flags) { 5566 final int userId = processName != null ? UserHandle.getUserId(uid) 5567 : UserHandle.getCallingUserId(); 5568 if (!sUserManager.exists(userId)) return null; 5569 flags = augmentFlagsForUser(flags, userId); 5570 5571 ArrayList<ProviderInfo> finalList = null; 5572 // reader 5573 synchronized (mPackages) { 5574 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5575 while (i.hasNext()) { 5576 final PackageParser.Provider p = i.next(); 5577 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5578 if (ps != null && p.info.authority != null 5579 && (processName == null 5580 || (p.info.processName.equals(processName) 5581 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5582 && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId) 5583 && (!mSafeMode 5584 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5585 if (finalList == null) { 5586 finalList = new ArrayList<ProviderInfo>(3); 5587 } 5588 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5589 ps.readUserState(userId), userId); 5590 if (info != null) { 5591 finalList.add(info); 5592 } 5593 } 5594 } 5595 } 5596 5597 if (finalList != null) { 5598 Collections.sort(finalList, mProviderInitOrderSorter); 5599 return new ParceledListSlice<ProviderInfo>(finalList); 5600 } 5601 5602 return null; 5603 } 5604 5605 @Override 5606 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5607 int flags) { 5608 // reader 5609 synchronized (mPackages) { 5610 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5611 return PackageParser.generateInstrumentationInfo(i, flags); 5612 } 5613 } 5614 5615 @Override 5616 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5617 int flags) { 5618 ArrayList<InstrumentationInfo> finalList = 5619 new ArrayList<InstrumentationInfo>(); 5620 5621 // reader 5622 synchronized (mPackages) { 5623 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5624 while (i.hasNext()) { 5625 final PackageParser.Instrumentation p = i.next(); 5626 if (targetPackage == null 5627 || targetPackage.equals(p.info.targetPackage)) { 5628 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5629 flags); 5630 if (ii != null) { 5631 finalList.add(ii); 5632 } 5633 } 5634 } 5635 } 5636 5637 return finalList; 5638 } 5639 5640 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5641 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5642 if (overlays == null) { 5643 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5644 return; 5645 } 5646 for (PackageParser.Package opkg : overlays.values()) { 5647 // Not much to do if idmap fails: we already logged the error 5648 // and we certainly don't want to abort installation of pkg simply 5649 // because an overlay didn't fit properly. For these reasons, 5650 // ignore the return value of createIdmapForPackagePairLI. 5651 createIdmapForPackagePairLI(pkg, opkg); 5652 } 5653 } 5654 5655 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5656 PackageParser.Package opkg) { 5657 if (!opkg.mTrustedOverlay) { 5658 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5659 opkg.baseCodePath + ": overlay not trusted"); 5660 return false; 5661 } 5662 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5663 if (overlaySet == null) { 5664 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5665 opkg.baseCodePath + " but target package has no known overlays"); 5666 return false; 5667 } 5668 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5669 // TODO: generate idmap for split APKs 5670 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5671 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5672 + opkg.baseCodePath); 5673 return false; 5674 } 5675 PackageParser.Package[] overlayArray = 5676 overlaySet.values().toArray(new PackageParser.Package[0]); 5677 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5678 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5679 return p1.mOverlayPriority - p2.mOverlayPriority; 5680 } 5681 }; 5682 Arrays.sort(overlayArray, cmp); 5683 5684 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5685 int i = 0; 5686 for (PackageParser.Package p : overlayArray) { 5687 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5688 } 5689 return true; 5690 } 5691 5692 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5693 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5694 try { 5695 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5696 } finally { 5697 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5698 } 5699 } 5700 5701 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5702 final File[] files = dir.listFiles(); 5703 if (ArrayUtils.isEmpty(files)) { 5704 Log.d(TAG, "No files in app dir " + dir); 5705 return; 5706 } 5707 5708 if (DEBUG_PACKAGE_SCANNING) { 5709 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5710 + " flags=0x" + Integer.toHexString(parseFlags)); 5711 } 5712 5713 for (File file : files) { 5714 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5715 && !PackageInstallerService.isStageName(file.getName()); 5716 if (!isPackage) { 5717 // Ignore entries which are not packages 5718 continue; 5719 } 5720 try { 5721 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5722 scanFlags, currentTime, null); 5723 } catch (PackageManagerException e) { 5724 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5725 5726 // Delete invalid userdata apps 5727 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5728 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5729 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5730 if (file.isDirectory()) { 5731 mInstaller.rmPackageDir(file.getAbsolutePath()); 5732 } else { 5733 file.delete(); 5734 } 5735 } 5736 } 5737 } 5738 } 5739 5740 private static File getSettingsProblemFile() { 5741 File dataDir = Environment.getDataDirectory(); 5742 File systemDir = new File(dataDir, "system"); 5743 File fname = new File(systemDir, "uiderrors.txt"); 5744 return fname; 5745 } 5746 5747 static void reportSettingsProblem(int priority, String msg) { 5748 logCriticalInfo(priority, msg); 5749 } 5750 5751 static void logCriticalInfo(int priority, String msg) { 5752 Slog.println(priority, TAG, msg); 5753 EventLogTags.writePmCriticalInfo(msg); 5754 try { 5755 File fname = getSettingsProblemFile(); 5756 FileOutputStream out = new FileOutputStream(fname, true); 5757 PrintWriter pw = new FastPrintWriter(out); 5758 SimpleDateFormat formatter = new SimpleDateFormat(); 5759 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5760 pw.println(dateString + ": " + msg); 5761 pw.close(); 5762 FileUtils.setPermissions( 5763 fname.toString(), 5764 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5765 -1, -1); 5766 } catch (java.io.IOException e) { 5767 } 5768 } 5769 5770 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5771 PackageParser.Package pkg, File srcFile, int parseFlags) 5772 throws PackageManagerException { 5773 if (ps != null 5774 && ps.codePath.equals(srcFile) 5775 && ps.timeStamp == srcFile.lastModified() 5776 && !isCompatSignatureUpdateNeeded(pkg) 5777 && !isRecoverSignatureUpdateNeeded(pkg)) { 5778 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5779 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5780 ArraySet<PublicKey> signingKs; 5781 synchronized (mPackages) { 5782 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5783 } 5784 if (ps.signatures.mSignatures != null 5785 && ps.signatures.mSignatures.length != 0 5786 && signingKs != null) { 5787 // Optimization: reuse the existing cached certificates 5788 // if the package appears to be unchanged. 5789 pkg.mSignatures = ps.signatures.mSignatures; 5790 pkg.mSigningKeys = signingKs; 5791 return; 5792 } 5793 5794 Slog.w(TAG, "PackageSetting for " + ps.name 5795 + " is missing signatures. Collecting certs again to recover them."); 5796 } else { 5797 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5798 } 5799 5800 try { 5801 pp.collectCertificates(pkg, parseFlags); 5802 pp.collectManifestDigest(pkg); 5803 } catch (PackageParserException e) { 5804 throw PackageManagerException.from(e); 5805 } 5806 } 5807 5808 /** 5809 * Traces a package scan. 5810 * @see #scanPackageLI(File, int, int, long, UserHandle) 5811 */ 5812 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5813 long currentTime, UserHandle user) throws PackageManagerException { 5814 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5815 try { 5816 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5817 } finally { 5818 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5819 } 5820 } 5821 5822 /** 5823 * Scans a package and returns the newly parsed package. 5824 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5825 */ 5826 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5827 long currentTime, UserHandle user) throws PackageManagerException { 5828 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5829 parseFlags |= mDefParseFlags; 5830 PackageParser pp = new PackageParser(); 5831 pp.setSeparateProcesses(mSeparateProcesses); 5832 pp.setOnlyCoreApps(mOnlyCore); 5833 pp.setDisplayMetrics(mMetrics); 5834 5835 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5836 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5837 } 5838 5839 final PackageParser.Package pkg; 5840 try { 5841 pkg = pp.parsePackage(scanFile, parseFlags); 5842 } catch (PackageParserException e) { 5843 throw PackageManagerException.from(e); 5844 } 5845 5846 PackageSetting ps = null; 5847 PackageSetting updatedPkg; 5848 // reader 5849 synchronized (mPackages) { 5850 // Look to see if we already know about this package. 5851 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5852 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5853 // This package has been renamed to its original name. Let's 5854 // use that. 5855 ps = mSettings.peekPackageLPr(oldName); 5856 } 5857 // If there was no original package, see one for the real package name. 5858 if (ps == null) { 5859 ps = mSettings.peekPackageLPr(pkg.packageName); 5860 } 5861 // Check to see if this package could be hiding/updating a system 5862 // package. Must look for it either under the original or real 5863 // package name depending on our state. 5864 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5865 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5866 } 5867 boolean updatedPkgBetter = false; 5868 // First check if this is a system package that may involve an update 5869 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 5870 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5871 // it needs to drop FLAG_PRIVILEGED. 5872 if (locationIsPrivileged(scanFile)) { 5873 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5874 } else { 5875 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5876 } 5877 5878 if (ps != null && !ps.codePath.equals(scanFile)) { 5879 // The path has changed from what was last scanned... check the 5880 // version of the new path against what we have stored to determine 5881 // what to do. 5882 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5883 if (pkg.mVersionCode <= ps.versionCode) { 5884 // The system package has been updated and the code path does not match 5885 // Ignore entry. Skip it. 5886 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5887 + " ignored: updated version " + ps.versionCode 5888 + " better than this " + pkg.mVersionCode); 5889 if (!updatedPkg.codePath.equals(scanFile)) { 5890 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5891 + ps.name + " changing from " + updatedPkg.codePathString 5892 + " to " + scanFile); 5893 updatedPkg.codePath = scanFile; 5894 updatedPkg.codePathString = scanFile.toString(); 5895 updatedPkg.resourcePath = scanFile; 5896 updatedPkg.resourcePathString = scanFile.toString(); 5897 } 5898 updatedPkg.pkg = pkg; 5899 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5900 "Package " + ps.name + " at " + scanFile 5901 + " ignored: updated version " + ps.versionCode 5902 + " better than this " + pkg.mVersionCode); 5903 } else { 5904 // The current app on the system partition is better than 5905 // what we have updated to on the data partition; switch 5906 // back to the system partition version. 5907 // At this point, its safely assumed that package installation for 5908 // apps in system partition will go through. If not there won't be a working 5909 // version of the app 5910 // writer 5911 synchronized (mPackages) { 5912 // Just remove the loaded entries from package lists. 5913 mPackages.remove(ps.name); 5914 } 5915 5916 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5917 + " reverting from " + ps.codePathString 5918 + ": new version " + pkg.mVersionCode 5919 + " better than installed " + ps.versionCode); 5920 5921 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5922 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5923 synchronized (mInstallLock) { 5924 args.cleanUpResourcesLI(); 5925 } 5926 synchronized (mPackages) { 5927 mSettings.enableSystemPackageLPw(ps.name); 5928 } 5929 updatedPkgBetter = true; 5930 } 5931 } 5932 } 5933 5934 if (updatedPkg != null) { 5935 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5936 // initially 5937 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5938 5939 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5940 // flag set initially 5941 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5942 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5943 } 5944 } 5945 5946 // Verify certificates against what was last scanned 5947 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5948 5949 /* 5950 * A new system app appeared, but we already had a non-system one of the 5951 * same name installed earlier. 5952 */ 5953 boolean shouldHideSystemApp = false; 5954 if (updatedPkg == null && ps != null 5955 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5956 /* 5957 * Check to make sure the signatures match first. If they don't, 5958 * wipe the installed application and its data. 5959 */ 5960 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5961 != PackageManager.SIGNATURE_MATCH) { 5962 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5963 + " signatures don't match existing userdata copy; removing"); 5964 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5965 ps = null; 5966 } else { 5967 /* 5968 * If the newly-added system app is an older version than the 5969 * already installed version, hide it. It will be scanned later 5970 * and re-added like an update. 5971 */ 5972 if (pkg.mVersionCode <= ps.versionCode) { 5973 shouldHideSystemApp = true; 5974 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5975 + " but new version " + pkg.mVersionCode + " better than installed " 5976 + ps.versionCode + "; hiding system"); 5977 } else { 5978 /* 5979 * The newly found system app is a newer version that the 5980 * one previously installed. Simply remove the 5981 * already-installed application and replace it with our own 5982 * while keeping the application data. 5983 */ 5984 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5985 + " reverting from " + ps.codePathString + ": new version " 5986 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5987 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5988 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5989 synchronized (mInstallLock) { 5990 args.cleanUpResourcesLI(); 5991 } 5992 } 5993 } 5994 } 5995 5996 // The apk is forward locked (not public) if its code and resources 5997 // are kept in different files. (except for app in either system or 5998 // vendor path). 5999 // TODO grab this value from PackageSettings 6000 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6001 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6002 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6003 } 6004 } 6005 6006 // TODO: extend to support forward-locked splits 6007 String resourcePath = null; 6008 String baseResourcePath = null; 6009 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6010 if (ps != null && ps.resourcePathString != null) { 6011 resourcePath = ps.resourcePathString; 6012 baseResourcePath = ps.resourcePathString; 6013 } else { 6014 // Should not happen at all. Just log an error. 6015 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6016 } 6017 } else { 6018 resourcePath = pkg.codePath; 6019 baseResourcePath = pkg.baseCodePath; 6020 } 6021 6022 // Set application objects path explicitly. 6023 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6024 pkg.applicationInfo.setCodePath(pkg.codePath); 6025 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6026 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6027 pkg.applicationInfo.setResourcePath(resourcePath); 6028 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6029 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6030 6031 // Note that we invoke the following method only if we are about to unpack an application 6032 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6033 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6034 6035 /* 6036 * If the system app should be overridden by a previously installed 6037 * data, hide the system app now and let the /data/app scan pick it up 6038 * again. 6039 */ 6040 if (shouldHideSystemApp) { 6041 synchronized (mPackages) { 6042 mSettings.disableSystemPackageLPw(pkg.packageName); 6043 } 6044 } 6045 6046 return scannedPkg; 6047 } 6048 6049 private static String fixProcessName(String defProcessName, 6050 String processName, int uid) { 6051 if (processName == null) { 6052 return defProcessName; 6053 } 6054 return processName; 6055 } 6056 6057 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6058 throws PackageManagerException { 6059 if (pkgSetting.signatures.mSignatures != null) { 6060 // Already existing package. Make sure signatures match 6061 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6062 == PackageManager.SIGNATURE_MATCH; 6063 if (!match) { 6064 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6065 == PackageManager.SIGNATURE_MATCH; 6066 } 6067 if (!match) { 6068 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6069 == PackageManager.SIGNATURE_MATCH; 6070 } 6071 if (!match) { 6072 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6073 + pkg.packageName + " signatures do not match the " 6074 + "previously installed version; ignoring!"); 6075 } 6076 } 6077 6078 // Check for shared user signatures 6079 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6080 // Already existing package. Make sure signatures match 6081 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6082 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6083 if (!match) { 6084 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6085 == PackageManager.SIGNATURE_MATCH; 6086 } 6087 if (!match) { 6088 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6089 == PackageManager.SIGNATURE_MATCH; 6090 } 6091 if (!match) { 6092 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6093 "Package " + pkg.packageName 6094 + " has no signatures that match those in shared user " 6095 + pkgSetting.sharedUser.name + "; ignoring!"); 6096 } 6097 } 6098 } 6099 6100 /** 6101 * Enforces that only the system UID or root's UID can call a method exposed 6102 * via Binder. 6103 * 6104 * @param message used as message if SecurityException is thrown 6105 * @throws SecurityException if the caller is not system or root 6106 */ 6107 private static final void enforceSystemOrRoot(String message) { 6108 final int uid = Binder.getCallingUid(); 6109 if (uid != Process.SYSTEM_UID && uid != 0) { 6110 throw new SecurityException(message); 6111 } 6112 } 6113 6114 @Override 6115 public void performFstrimIfNeeded() { 6116 enforceSystemOrRoot("Only the system can request fstrim"); 6117 6118 // Before everything else, see whether we need to fstrim. 6119 try { 6120 IMountService ms = PackageHelper.getMountService(); 6121 if (ms != null) { 6122 final boolean isUpgrade = isUpgrade(); 6123 boolean doTrim = isUpgrade; 6124 if (doTrim) { 6125 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6126 } else { 6127 final long interval = android.provider.Settings.Global.getLong( 6128 mContext.getContentResolver(), 6129 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6130 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6131 if (interval > 0) { 6132 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6133 if (timeSinceLast > interval) { 6134 doTrim = true; 6135 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6136 + "; running immediately"); 6137 } 6138 } 6139 } 6140 if (doTrim) { 6141 if (!isFirstBoot()) { 6142 try { 6143 ActivityManagerNative.getDefault().showBootMessage( 6144 mContext.getResources().getString( 6145 R.string.android_upgrading_fstrim), true); 6146 } catch (RemoteException e) { 6147 } 6148 } 6149 ms.runMaintenance(); 6150 } 6151 } else { 6152 Slog.e(TAG, "Mount service unavailable!"); 6153 } 6154 } catch (RemoteException e) { 6155 // Can't happen; MountService is local 6156 } 6157 } 6158 6159 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6160 List<ResolveInfo> ris = null; 6161 try { 6162 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6163 intent, null, 0, userId); 6164 } catch (RemoteException e) { 6165 } 6166 ArraySet<String> pkgNames = new ArraySet<String>(); 6167 if (ris != null) { 6168 for (ResolveInfo ri : ris) { 6169 pkgNames.add(ri.activityInfo.packageName); 6170 } 6171 } 6172 return pkgNames; 6173 } 6174 6175 @Override 6176 public void notifyPackageUse(String packageName) { 6177 synchronized (mPackages) { 6178 PackageParser.Package p = mPackages.get(packageName); 6179 if (p == null) { 6180 return; 6181 } 6182 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6183 } 6184 } 6185 6186 @Override 6187 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6188 return performDexOptTraced(packageName, instructionSet); 6189 } 6190 6191 public boolean performDexOpt(String packageName, String instructionSet) { 6192 return performDexOptTraced(packageName, instructionSet); 6193 } 6194 6195 private boolean performDexOptTraced(String packageName, String instructionSet) { 6196 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6197 try { 6198 return performDexOptInternal(packageName, instructionSet); 6199 } finally { 6200 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6201 } 6202 } 6203 6204 private boolean performDexOptInternal(String packageName, String instructionSet) { 6205 PackageParser.Package p; 6206 final String targetInstructionSet; 6207 synchronized (mPackages) { 6208 p = mPackages.get(packageName); 6209 if (p == null) { 6210 return false; 6211 } 6212 mPackageUsage.write(false); 6213 6214 targetInstructionSet = instructionSet != null ? instructionSet : 6215 getPrimaryInstructionSet(p.applicationInfo); 6216 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6217 return false; 6218 } 6219 } 6220 long callingId = Binder.clearCallingIdentity(); 6221 try { 6222 synchronized (mInstallLock) { 6223 final String[] instructionSets = new String[] { targetInstructionSet }; 6224 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6225 true /* inclDependencies */); 6226 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6227 } 6228 } finally { 6229 Binder.restoreCallingIdentity(callingId); 6230 } 6231 } 6232 6233 public ArraySet<String> getPackagesThatNeedDexOpt() { 6234 ArraySet<String> pkgs = null; 6235 synchronized (mPackages) { 6236 for (PackageParser.Package p : mPackages.values()) { 6237 if (DEBUG_DEXOPT) { 6238 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6239 } 6240 if (!p.mDexOptPerformed.isEmpty()) { 6241 continue; 6242 } 6243 if (pkgs == null) { 6244 pkgs = new ArraySet<String>(); 6245 } 6246 pkgs.add(p.packageName); 6247 } 6248 } 6249 return pkgs; 6250 } 6251 6252 public void shutdown() { 6253 mPackageUsage.write(true); 6254 } 6255 6256 @Override 6257 public void forceDexOpt(String packageName) { 6258 enforceSystemOrRoot("forceDexOpt"); 6259 6260 PackageParser.Package pkg; 6261 synchronized (mPackages) { 6262 pkg = mPackages.get(packageName); 6263 if (pkg == null) { 6264 throw new IllegalArgumentException("Missing package: " + packageName); 6265 } 6266 } 6267 6268 synchronized (mInstallLock) { 6269 final String[] instructionSets = new String[] { 6270 getPrimaryInstructionSet(pkg.applicationInfo) }; 6271 6272 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6273 6274 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6275 true /* inclDependencies */); 6276 6277 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6278 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6279 throw new IllegalStateException("Failed to dexopt: " + res); 6280 } 6281 } 6282 } 6283 6284 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6285 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6286 Slog.w(TAG, "Unable to update from " + oldPkg.name 6287 + " to " + newPkg.packageName 6288 + ": old package not in system partition"); 6289 return false; 6290 } else if (mPackages.get(oldPkg.name) != null) { 6291 Slog.w(TAG, "Unable to update from " + oldPkg.name 6292 + " to " + newPkg.packageName 6293 + ": old package still exists"); 6294 return false; 6295 } 6296 return true; 6297 } 6298 6299 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6300 int[] users = sUserManager.getUserIds(); 6301 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6302 if (res < 0) { 6303 return res; 6304 } 6305 for (int user : users) { 6306 if (user != 0) { 6307 res = mInstaller.createUserData(volumeUuid, packageName, 6308 UserHandle.getUid(user, uid), user, seinfo); 6309 if (res < 0) { 6310 return res; 6311 } 6312 } 6313 } 6314 return res; 6315 } 6316 6317 private int removeDataDirsLI(String volumeUuid, String packageName) { 6318 int[] users = sUserManager.getUserIds(); 6319 int res = 0; 6320 for (int user : users) { 6321 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6322 if (resInner < 0) { 6323 res = resInner; 6324 } 6325 } 6326 6327 return res; 6328 } 6329 6330 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6331 int[] users = sUserManager.getUserIds(); 6332 int res = 0; 6333 for (int user : users) { 6334 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6335 if (resInner < 0) { 6336 res = resInner; 6337 } 6338 } 6339 return res; 6340 } 6341 6342 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6343 PackageParser.Package changingLib) { 6344 if (file.path != null) { 6345 usesLibraryFiles.add(file.path); 6346 return; 6347 } 6348 PackageParser.Package p = mPackages.get(file.apk); 6349 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6350 // If we are doing this while in the middle of updating a library apk, 6351 // then we need to make sure to use that new apk for determining the 6352 // dependencies here. (We haven't yet finished committing the new apk 6353 // to the package manager state.) 6354 if (p == null || p.packageName.equals(changingLib.packageName)) { 6355 p = changingLib; 6356 } 6357 } 6358 if (p != null) { 6359 usesLibraryFiles.addAll(p.getAllCodePaths()); 6360 } 6361 } 6362 6363 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6364 PackageParser.Package changingLib) throws PackageManagerException { 6365 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6366 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6367 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6368 for (int i=0; i<N; i++) { 6369 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6370 if (file == null) { 6371 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6372 "Package " + pkg.packageName + " requires unavailable shared library " 6373 + pkg.usesLibraries.get(i) + "; failing!"); 6374 } 6375 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6376 } 6377 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6378 for (int i=0; i<N; i++) { 6379 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6380 if (file == null) { 6381 Slog.w(TAG, "Package " + pkg.packageName 6382 + " desires unavailable shared library " 6383 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6384 } else { 6385 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6386 } 6387 } 6388 N = usesLibraryFiles.size(); 6389 if (N > 0) { 6390 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6391 } else { 6392 pkg.usesLibraryFiles = null; 6393 } 6394 } 6395 } 6396 6397 private static boolean hasString(List<String> list, List<String> which) { 6398 if (list == null) { 6399 return false; 6400 } 6401 for (int i=list.size()-1; i>=0; i--) { 6402 for (int j=which.size()-1; j>=0; j--) { 6403 if (which.get(j).equals(list.get(i))) { 6404 return true; 6405 } 6406 } 6407 } 6408 return false; 6409 } 6410 6411 private void updateAllSharedLibrariesLPw() { 6412 for (PackageParser.Package pkg : mPackages.values()) { 6413 try { 6414 updateSharedLibrariesLPw(pkg, null); 6415 } catch (PackageManagerException e) { 6416 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6417 } 6418 } 6419 } 6420 6421 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6422 PackageParser.Package changingPkg) { 6423 ArrayList<PackageParser.Package> res = null; 6424 for (PackageParser.Package pkg : mPackages.values()) { 6425 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6426 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6427 if (res == null) { 6428 res = new ArrayList<PackageParser.Package>(); 6429 } 6430 res.add(pkg); 6431 try { 6432 updateSharedLibrariesLPw(pkg, changingPkg); 6433 } catch (PackageManagerException e) { 6434 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6435 } 6436 } 6437 } 6438 return res; 6439 } 6440 6441 /** 6442 * Derive the value of the {@code cpuAbiOverride} based on the provided 6443 * value and an optional stored value from the package settings. 6444 */ 6445 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6446 String cpuAbiOverride = null; 6447 6448 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6449 cpuAbiOverride = null; 6450 } else if (abiOverride != null) { 6451 cpuAbiOverride = abiOverride; 6452 } else if (settings != null) { 6453 cpuAbiOverride = settings.cpuAbiOverrideString; 6454 } 6455 6456 return cpuAbiOverride; 6457 } 6458 6459 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6460 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6461 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6462 try { 6463 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6464 } finally { 6465 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6466 } 6467 } 6468 6469 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6470 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6471 boolean success = false; 6472 try { 6473 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6474 currentTime, user); 6475 success = true; 6476 return res; 6477 } finally { 6478 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6479 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6480 } 6481 } 6482 } 6483 6484 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6485 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6486 final File scanFile = new File(pkg.codePath); 6487 if (pkg.applicationInfo.getCodePath() == null || 6488 pkg.applicationInfo.getResourcePath() == null) { 6489 // Bail out. The resource and code paths haven't been set. 6490 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6491 "Code and resource paths haven't been set correctly"); 6492 } 6493 6494 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6495 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6496 } else { 6497 // Only allow system apps to be flagged as core apps. 6498 pkg.coreApp = false; 6499 } 6500 6501 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6502 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6503 } 6504 6505 if (mCustomResolverComponentName != null && 6506 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6507 setUpCustomResolverActivity(pkg); 6508 } 6509 6510 if (pkg.packageName.equals("android")) { 6511 synchronized (mPackages) { 6512 if (mAndroidApplication != null) { 6513 Slog.w(TAG, "*************************************************"); 6514 Slog.w(TAG, "Core android package being redefined. Skipping."); 6515 Slog.w(TAG, " file=" + scanFile); 6516 Slog.w(TAG, "*************************************************"); 6517 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6518 "Core android package being redefined. Skipping."); 6519 } 6520 6521 // Set up information for our fall-back user intent resolution activity. 6522 mPlatformPackage = pkg; 6523 pkg.mVersionCode = mSdkVersion; 6524 mAndroidApplication = pkg.applicationInfo; 6525 6526 if (!mResolverReplaced) { 6527 mResolveActivity.applicationInfo = mAndroidApplication; 6528 mResolveActivity.name = ResolverActivity.class.getName(); 6529 mResolveActivity.packageName = mAndroidApplication.packageName; 6530 mResolveActivity.processName = "system:ui"; 6531 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6532 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6533 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6534 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6535 mResolveActivity.exported = true; 6536 mResolveActivity.enabled = true; 6537 mResolveInfo.activityInfo = mResolveActivity; 6538 mResolveInfo.priority = 0; 6539 mResolveInfo.preferredOrder = 0; 6540 mResolveInfo.match = 0; 6541 mResolveComponentName = new ComponentName( 6542 mAndroidApplication.packageName, mResolveActivity.name); 6543 } 6544 } 6545 } 6546 6547 if (DEBUG_PACKAGE_SCANNING) { 6548 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6549 Log.d(TAG, "Scanning package " + pkg.packageName); 6550 } 6551 6552 if (mPackages.containsKey(pkg.packageName) 6553 || mSharedLibraries.containsKey(pkg.packageName)) { 6554 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6555 "Application package " + pkg.packageName 6556 + " already installed. Skipping duplicate."); 6557 } 6558 6559 // If we're only installing presumed-existing packages, require that the 6560 // scanned APK is both already known and at the path previously established 6561 // for it. Previously unknown packages we pick up normally, but if we have an 6562 // a priori expectation about this package's install presence, enforce it. 6563 // With a singular exception for new system packages. When an OTA contains 6564 // a new system package, we allow the codepath to change from a system location 6565 // to the user-installed location. If we don't allow this change, any newer, 6566 // user-installed version of the application will be ignored. 6567 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6568 if (mExpectingBetter.containsKey(pkg.packageName)) { 6569 logCriticalInfo(Log.WARN, 6570 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6571 } else { 6572 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6573 if (known != null) { 6574 if (DEBUG_PACKAGE_SCANNING) { 6575 Log.d(TAG, "Examining " + pkg.codePath 6576 + " and requiring known paths " + known.codePathString 6577 + " & " + known.resourcePathString); 6578 } 6579 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6580 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6581 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6582 "Application package " + pkg.packageName 6583 + " found at " + pkg.applicationInfo.getCodePath() 6584 + " but expected at " + known.codePathString + "; ignoring."); 6585 } 6586 } 6587 } 6588 } 6589 6590 // Initialize package source and resource directories 6591 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6592 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6593 6594 SharedUserSetting suid = null; 6595 PackageSetting pkgSetting = null; 6596 6597 if (!isSystemApp(pkg)) { 6598 // Only system apps can use these features. 6599 pkg.mOriginalPackages = null; 6600 pkg.mRealPackage = null; 6601 pkg.mAdoptPermissions = null; 6602 } 6603 6604 // writer 6605 synchronized (mPackages) { 6606 if (pkg.mSharedUserId != null) { 6607 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6608 if (suid == null) { 6609 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6610 "Creating application package " + pkg.packageName 6611 + " for shared user failed"); 6612 } 6613 if (DEBUG_PACKAGE_SCANNING) { 6614 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6615 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6616 + "): packages=" + suid.packages); 6617 } 6618 } 6619 6620 // Check if we are renaming from an original package name. 6621 PackageSetting origPackage = null; 6622 String realName = null; 6623 if (pkg.mOriginalPackages != null) { 6624 // This package may need to be renamed to a previously 6625 // installed name. Let's check on that... 6626 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6627 if (pkg.mOriginalPackages.contains(renamed)) { 6628 // This package had originally been installed as the 6629 // original name, and we have already taken care of 6630 // transitioning to the new one. Just update the new 6631 // one to continue using the old name. 6632 realName = pkg.mRealPackage; 6633 if (!pkg.packageName.equals(renamed)) { 6634 // Callers into this function may have already taken 6635 // care of renaming the package; only do it here if 6636 // it is not already done. 6637 pkg.setPackageName(renamed); 6638 } 6639 6640 } else { 6641 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6642 if ((origPackage = mSettings.peekPackageLPr( 6643 pkg.mOriginalPackages.get(i))) != null) { 6644 // We do have the package already installed under its 6645 // original name... should we use it? 6646 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6647 // New package is not compatible with original. 6648 origPackage = null; 6649 continue; 6650 } else if (origPackage.sharedUser != null) { 6651 // Make sure uid is compatible between packages. 6652 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6653 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6654 + " to " + pkg.packageName + ": old uid " 6655 + origPackage.sharedUser.name 6656 + " differs from " + pkg.mSharedUserId); 6657 origPackage = null; 6658 continue; 6659 } 6660 } else { 6661 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6662 + pkg.packageName + " to old name " + origPackage.name); 6663 } 6664 break; 6665 } 6666 } 6667 } 6668 } 6669 6670 if (mTransferedPackages.contains(pkg.packageName)) { 6671 Slog.w(TAG, "Package " + pkg.packageName 6672 + " was transferred to another, but its .apk remains"); 6673 } 6674 6675 // Just create the setting, don't add it yet. For already existing packages 6676 // the PkgSetting exists already and doesn't have to be created. 6677 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6678 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6679 pkg.applicationInfo.primaryCpuAbi, 6680 pkg.applicationInfo.secondaryCpuAbi, 6681 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6682 user, false); 6683 if (pkgSetting == null) { 6684 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6685 "Creating application package " + pkg.packageName + " failed"); 6686 } 6687 6688 if (pkgSetting.origPackage != null) { 6689 // If we are first transitioning from an original package, 6690 // fix up the new package's name now. We need to do this after 6691 // looking up the package under its new name, so getPackageLP 6692 // can take care of fiddling things correctly. 6693 pkg.setPackageName(origPackage.name); 6694 6695 // File a report about this. 6696 String msg = "New package " + pkgSetting.realName 6697 + " renamed to replace old package " + pkgSetting.name; 6698 reportSettingsProblem(Log.WARN, msg); 6699 6700 // Make a note of it. 6701 mTransferedPackages.add(origPackage.name); 6702 6703 // No longer need to retain this. 6704 pkgSetting.origPackage = null; 6705 } 6706 6707 if (realName != null) { 6708 // Make a note of it. 6709 mTransferedPackages.add(pkg.packageName); 6710 } 6711 6712 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6713 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6714 } 6715 6716 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6717 // Check all shared libraries and map to their actual file path. 6718 // We only do this here for apps not on a system dir, because those 6719 // are the only ones that can fail an install due to this. We 6720 // will take care of the system apps by updating all of their 6721 // library paths after the scan is done. 6722 updateSharedLibrariesLPw(pkg, null); 6723 } 6724 6725 if (mFoundPolicyFile) { 6726 SELinuxMMAC.assignSeinfoValue(pkg); 6727 } 6728 6729 pkg.applicationInfo.uid = pkgSetting.appId; 6730 pkg.mExtras = pkgSetting; 6731 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6732 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6733 // We just determined the app is signed correctly, so bring 6734 // over the latest parsed certs. 6735 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6736 } else { 6737 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6738 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6739 "Package " + pkg.packageName + " upgrade keys do not match the " 6740 + "previously installed version"); 6741 } else { 6742 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6743 String msg = "System package " + pkg.packageName 6744 + " signature changed; retaining data."; 6745 reportSettingsProblem(Log.WARN, msg); 6746 } 6747 } 6748 } else { 6749 try { 6750 verifySignaturesLP(pkgSetting, pkg); 6751 // We just determined the app is signed correctly, so bring 6752 // over the latest parsed certs. 6753 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6754 } catch (PackageManagerException e) { 6755 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6756 throw e; 6757 } 6758 // The signature has changed, but this package is in the system 6759 // image... let's recover! 6760 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6761 // However... if this package is part of a shared user, but it 6762 // doesn't match the signature of the shared user, let's fail. 6763 // What this means is that you can't change the signatures 6764 // associated with an overall shared user, which doesn't seem all 6765 // that unreasonable. 6766 if (pkgSetting.sharedUser != null) { 6767 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6768 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6769 throw new PackageManagerException( 6770 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6771 "Signature mismatch for shared user : " 6772 + pkgSetting.sharedUser); 6773 } 6774 } 6775 // File a report about this. 6776 String msg = "System package " + pkg.packageName 6777 + " signature changed; retaining data."; 6778 reportSettingsProblem(Log.WARN, msg); 6779 } 6780 } 6781 // Verify that this new package doesn't have any content providers 6782 // that conflict with existing packages. Only do this if the 6783 // package isn't already installed, since we don't want to break 6784 // things that are installed. 6785 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6786 final int N = pkg.providers.size(); 6787 int i; 6788 for (i=0; i<N; i++) { 6789 PackageParser.Provider p = pkg.providers.get(i); 6790 if (p.info.authority != null) { 6791 String names[] = p.info.authority.split(";"); 6792 for (int j = 0; j < names.length; j++) { 6793 if (mProvidersByAuthority.containsKey(names[j])) { 6794 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6795 final String otherPackageName = 6796 ((other != null && other.getComponentName() != null) ? 6797 other.getComponentName().getPackageName() : "?"); 6798 throw new PackageManagerException( 6799 INSTALL_FAILED_CONFLICTING_PROVIDER, 6800 "Can't install because provider name " + names[j] 6801 + " (in package " + pkg.applicationInfo.packageName 6802 + ") is already used by " + otherPackageName); 6803 } 6804 } 6805 } 6806 } 6807 } 6808 6809 if (pkg.mAdoptPermissions != null) { 6810 // This package wants to adopt ownership of permissions from 6811 // another package. 6812 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6813 final String origName = pkg.mAdoptPermissions.get(i); 6814 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6815 if (orig != null) { 6816 if (verifyPackageUpdateLPr(orig, pkg)) { 6817 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6818 + pkg.packageName); 6819 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6820 } 6821 } 6822 } 6823 } 6824 } 6825 6826 final String pkgName = pkg.packageName; 6827 6828 final long scanFileTime = scanFile.lastModified(); 6829 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6830 pkg.applicationInfo.processName = fixProcessName( 6831 pkg.applicationInfo.packageName, 6832 pkg.applicationInfo.processName, 6833 pkg.applicationInfo.uid); 6834 6835 if (pkg != mPlatformPackage) { 6836 // This is a normal package, need to make its data directory. 6837 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 6838 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 6839 6840 boolean uidError = false; 6841 if (dataPath.exists()) { 6842 int currentUid = 0; 6843 try { 6844 StructStat stat = Os.stat(dataPath.getPath()); 6845 currentUid = stat.st_uid; 6846 } catch (ErrnoException e) { 6847 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6848 } 6849 6850 // If we have mismatched owners for the data path, we have a problem. 6851 if (currentUid != pkg.applicationInfo.uid) { 6852 boolean recovered = false; 6853 if (currentUid == 0) { 6854 // The directory somehow became owned by root. Wow. 6855 // This is probably because the system was stopped while 6856 // installd was in the middle of messing with its libs 6857 // directory. Ask installd to fix that. 6858 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6859 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6860 if (ret >= 0) { 6861 recovered = true; 6862 String msg = "Package " + pkg.packageName 6863 + " unexpectedly changed to uid 0; recovered to " + 6864 + pkg.applicationInfo.uid; 6865 reportSettingsProblem(Log.WARN, msg); 6866 } 6867 } 6868 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6869 || (scanFlags&SCAN_BOOTING) != 0)) { 6870 // If this is a system app, we can at least delete its 6871 // current data so the application will still work. 6872 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6873 if (ret >= 0) { 6874 // TODO: Kill the processes first 6875 // Old data gone! 6876 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6877 ? "System package " : "Third party package "; 6878 String msg = prefix + pkg.packageName 6879 + " has changed from uid: " 6880 + currentUid + " to " 6881 + pkg.applicationInfo.uid + "; old data erased"; 6882 reportSettingsProblem(Log.WARN, msg); 6883 recovered = true; 6884 6885 // And now re-install the app. 6886 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6887 pkg.applicationInfo.seinfo); 6888 if (ret == -1) { 6889 // Ack should not happen! 6890 msg = prefix + pkg.packageName 6891 + " could not have data directory re-created after delete."; 6892 reportSettingsProblem(Log.WARN, msg); 6893 throw new PackageManagerException( 6894 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6895 } 6896 } 6897 if (!recovered) { 6898 mHasSystemUidErrors = true; 6899 } 6900 } else if (!recovered) { 6901 // If we allow this install to proceed, we will be broken. 6902 // Abort, abort! 6903 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6904 "scanPackageLI"); 6905 } 6906 if (!recovered) { 6907 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6908 + pkg.applicationInfo.uid + "/fs_" 6909 + currentUid; 6910 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6911 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6912 String msg = "Package " + pkg.packageName 6913 + " has mismatched uid: " 6914 + currentUid + " on disk, " 6915 + pkg.applicationInfo.uid + " in settings"; 6916 // writer 6917 synchronized (mPackages) { 6918 mSettings.mReadMessages.append(msg); 6919 mSettings.mReadMessages.append('\n'); 6920 uidError = true; 6921 if (!pkgSetting.uidError) { 6922 reportSettingsProblem(Log.ERROR, msg); 6923 } 6924 } 6925 } 6926 } 6927 6928 if (mShouldRestoreconData) { 6929 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6930 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6931 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6932 } 6933 } else { 6934 if (DEBUG_PACKAGE_SCANNING) { 6935 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6936 Log.v(TAG, "Want this data dir: " + dataPath); 6937 } 6938 //invoke installer to do the actual installation 6939 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6940 pkg.applicationInfo.seinfo); 6941 if (ret < 0) { 6942 // Error from installer 6943 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6944 "Unable to create data dirs [errorCode=" + ret + "]"); 6945 } 6946 } 6947 6948 // Get all of our default paths setup 6949 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 6950 6951 pkgSetting.uidError = uidError; 6952 } 6953 6954 final String path = scanFile.getPath(); 6955 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6956 6957 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6958 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6959 6960 // Some system apps still use directory structure for native libraries 6961 // in which case we might end up not detecting abi solely based on apk 6962 // structure. Try to detect abi based on directory structure. 6963 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6964 pkg.applicationInfo.primaryCpuAbi == null) { 6965 setBundledAppAbisAndRoots(pkg, pkgSetting); 6966 setNativeLibraryPaths(pkg); 6967 } 6968 6969 } else { 6970 if ((scanFlags & SCAN_MOVE) != 0) { 6971 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6972 // but we already have this packages package info in the PackageSetting. We just 6973 // use that and derive the native library path based on the new codepath. 6974 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6975 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6976 } 6977 6978 // Set native library paths again. For moves, the path will be updated based on the 6979 // ABIs we've determined above. For non-moves, the path will be updated based on the 6980 // ABIs we determined during compilation, but the path will depend on the final 6981 // package path (after the rename away from the stage path). 6982 setNativeLibraryPaths(pkg); 6983 } 6984 6985 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6986 final int[] userIds = sUserManager.getUserIds(); 6987 synchronized (mInstallLock) { 6988 // Make sure all user data directories are ready to roll; we're okay 6989 // if they already exist 6990 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6991 for (int userId : userIds) { 6992 if (userId != UserHandle.USER_SYSTEM) { 6993 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6994 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6995 pkg.applicationInfo.seinfo); 6996 } 6997 } 6998 } 6999 7000 // Create a native library symlink only if we have native libraries 7001 // and if the native libraries are 32 bit libraries. We do not provide 7002 // this symlink for 64 bit libraries. 7003 if (pkg.applicationInfo.primaryCpuAbi != null && 7004 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7005 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7006 try { 7007 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7008 for (int userId : userIds) { 7009 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7010 nativeLibPath, userId) < 0) { 7011 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7012 "Failed linking native library dir (user=" + userId + ")"); 7013 } 7014 } 7015 } finally { 7016 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7017 } 7018 } 7019 } 7020 7021 // This is a special case for the "system" package, where the ABI is 7022 // dictated by the zygote configuration (and init.rc). We should keep track 7023 // of this ABI so that we can deal with "normal" applications that run under 7024 // the same UID correctly. 7025 if (mPlatformPackage == pkg) { 7026 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7027 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7028 } 7029 7030 // If there's a mismatch between the abi-override in the package setting 7031 // and the abiOverride specified for the install. Warn about this because we 7032 // would've already compiled the app without taking the package setting into 7033 // account. 7034 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7035 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7036 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7037 " for package: " + pkg.packageName); 7038 } 7039 } 7040 7041 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7042 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7043 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7044 7045 // Copy the derived override back to the parsed package, so that we can 7046 // update the package settings accordingly. 7047 pkg.cpuAbiOverride = cpuAbiOverride; 7048 7049 if (DEBUG_ABI_SELECTION) { 7050 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7051 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7052 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7053 } 7054 7055 // Push the derived path down into PackageSettings so we know what to 7056 // clean up at uninstall time. 7057 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7058 7059 if (DEBUG_ABI_SELECTION) { 7060 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7061 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7062 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7063 } 7064 7065 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7066 // We don't do this here during boot because we can do it all 7067 // at once after scanning all existing packages. 7068 // 7069 // We also do this *before* we perform dexopt on this package, so that 7070 // we can avoid redundant dexopts, and also to make sure we've got the 7071 // code and package path correct. 7072 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7073 pkg, true /* boot complete */); 7074 } 7075 7076 if (mFactoryTest && pkg.requestedPermissions.contains( 7077 android.Manifest.permission.FACTORY_TEST)) { 7078 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7079 } 7080 7081 ArrayList<PackageParser.Package> clientLibPkgs = null; 7082 7083 // writer 7084 synchronized (mPackages) { 7085 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7086 // Only system apps can add new shared libraries. 7087 if (pkg.libraryNames != null) { 7088 for (int i=0; i<pkg.libraryNames.size(); i++) { 7089 String name = pkg.libraryNames.get(i); 7090 boolean allowed = false; 7091 if (pkg.isUpdatedSystemApp()) { 7092 // New library entries can only be added through the 7093 // system image. This is important to get rid of a lot 7094 // of nasty edge cases: for example if we allowed a non- 7095 // system update of the app to add a library, then uninstalling 7096 // the update would make the library go away, and assumptions 7097 // we made such as through app install filtering would now 7098 // have allowed apps on the device which aren't compatible 7099 // with it. Better to just have the restriction here, be 7100 // conservative, and create many fewer cases that can negatively 7101 // impact the user experience. 7102 final PackageSetting sysPs = mSettings 7103 .getDisabledSystemPkgLPr(pkg.packageName); 7104 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7105 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7106 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7107 allowed = true; 7108 break; 7109 } 7110 } 7111 } 7112 } else { 7113 allowed = true; 7114 } 7115 if (allowed) { 7116 if (!mSharedLibraries.containsKey(name)) { 7117 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7118 } else if (!name.equals(pkg.packageName)) { 7119 Slog.w(TAG, "Package " + pkg.packageName + " library " 7120 + name + " already exists; skipping"); 7121 } 7122 } else { 7123 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7124 + name + " that is not declared on system image; skipping"); 7125 } 7126 } 7127 if ((scanFlags & SCAN_BOOTING) == 0) { 7128 // If we are not booting, we need to update any applications 7129 // that are clients of our shared library. If we are booting, 7130 // this will all be done once the scan is complete. 7131 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7132 } 7133 } 7134 } 7135 } 7136 7137 // Request the ActivityManager to kill the process(only for existing packages) 7138 // so that we do not end up in a confused state while the user is still using the older 7139 // version of the application while the new one gets installed. 7140 if ((scanFlags & SCAN_REPLACING) != 0) { 7141 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7142 7143 killApplication(pkg.applicationInfo.packageName, 7144 pkg.applicationInfo.uid, "replace pkg"); 7145 7146 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7147 } 7148 7149 // Also need to kill any apps that are dependent on the library. 7150 if (clientLibPkgs != null) { 7151 for (int i=0; i<clientLibPkgs.size(); i++) { 7152 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7153 killApplication(clientPkg.applicationInfo.packageName, 7154 clientPkg.applicationInfo.uid, "update lib"); 7155 } 7156 } 7157 7158 // Make sure we're not adding any bogus keyset info 7159 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7160 ksms.assertScannedPackageValid(pkg); 7161 7162 // writer 7163 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7164 7165 boolean createIdmapFailed = false; 7166 synchronized (mPackages) { 7167 // We don't expect installation to fail beyond this point 7168 7169 // Add the new setting to mSettings 7170 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7171 // Add the new setting to mPackages 7172 mPackages.put(pkg.applicationInfo.packageName, pkg); 7173 // Make sure we don't accidentally delete its data. 7174 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7175 while (iter.hasNext()) { 7176 PackageCleanItem item = iter.next(); 7177 if (pkgName.equals(item.packageName)) { 7178 iter.remove(); 7179 } 7180 } 7181 7182 // Take care of first install / last update times. 7183 if (currentTime != 0) { 7184 if (pkgSetting.firstInstallTime == 0) { 7185 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7186 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7187 pkgSetting.lastUpdateTime = currentTime; 7188 } 7189 } else if (pkgSetting.firstInstallTime == 0) { 7190 // We need *something*. Take time time stamp of the file. 7191 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7192 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7193 if (scanFileTime != pkgSetting.timeStamp) { 7194 // A package on the system image has changed; consider this 7195 // to be an update. 7196 pkgSetting.lastUpdateTime = scanFileTime; 7197 } 7198 } 7199 7200 // Add the package's KeySets to the global KeySetManagerService 7201 ksms.addScannedPackageLPw(pkg); 7202 7203 int N = pkg.providers.size(); 7204 StringBuilder r = null; 7205 int i; 7206 for (i=0; i<N; i++) { 7207 PackageParser.Provider p = pkg.providers.get(i); 7208 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7209 p.info.processName, pkg.applicationInfo.uid); 7210 mProviders.addProvider(p); 7211 p.syncable = p.info.isSyncable; 7212 if (p.info.authority != null) { 7213 String names[] = p.info.authority.split(";"); 7214 p.info.authority = null; 7215 for (int j = 0; j < names.length; j++) { 7216 if (j == 1 && p.syncable) { 7217 // We only want the first authority for a provider to possibly be 7218 // syncable, so if we already added this provider using a different 7219 // authority clear the syncable flag. We copy the provider before 7220 // changing it because the mProviders object contains a reference 7221 // to a provider that we don't want to change. 7222 // Only do this for the second authority since the resulting provider 7223 // object can be the same for all future authorities for this provider. 7224 p = new PackageParser.Provider(p); 7225 p.syncable = false; 7226 } 7227 if (!mProvidersByAuthority.containsKey(names[j])) { 7228 mProvidersByAuthority.put(names[j], p); 7229 if (p.info.authority == null) { 7230 p.info.authority = names[j]; 7231 } else { 7232 p.info.authority = p.info.authority + ";" + names[j]; 7233 } 7234 if (DEBUG_PACKAGE_SCANNING) { 7235 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7236 Log.d(TAG, "Registered content provider: " + names[j] 7237 + ", className = " + p.info.name + ", isSyncable = " 7238 + p.info.isSyncable); 7239 } 7240 } else { 7241 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7242 Slog.w(TAG, "Skipping provider name " + names[j] + 7243 " (in package " + pkg.applicationInfo.packageName + 7244 "): name already used by " 7245 + ((other != null && other.getComponentName() != null) 7246 ? other.getComponentName().getPackageName() : "?")); 7247 } 7248 } 7249 } 7250 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7251 if (r == null) { 7252 r = new StringBuilder(256); 7253 } else { 7254 r.append(' '); 7255 } 7256 r.append(p.info.name); 7257 } 7258 } 7259 if (r != null) { 7260 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7261 } 7262 7263 N = pkg.services.size(); 7264 r = null; 7265 for (i=0; i<N; i++) { 7266 PackageParser.Service s = pkg.services.get(i); 7267 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7268 s.info.processName, pkg.applicationInfo.uid); 7269 mServices.addService(s); 7270 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7271 if (r == null) { 7272 r = new StringBuilder(256); 7273 } else { 7274 r.append(' '); 7275 } 7276 r.append(s.info.name); 7277 } 7278 } 7279 if (r != null) { 7280 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7281 } 7282 7283 N = pkg.receivers.size(); 7284 r = null; 7285 for (i=0; i<N; i++) { 7286 PackageParser.Activity a = pkg.receivers.get(i); 7287 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7288 a.info.processName, pkg.applicationInfo.uid); 7289 mReceivers.addActivity(a, "receiver"); 7290 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7291 if (r == null) { 7292 r = new StringBuilder(256); 7293 } else { 7294 r.append(' '); 7295 } 7296 r.append(a.info.name); 7297 } 7298 } 7299 if (r != null) { 7300 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7301 } 7302 7303 N = pkg.activities.size(); 7304 r = null; 7305 for (i=0; i<N; i++) { 7306 PackageParser.Activity a = pkg.activities.get(i); 7307 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7308 a.info.processName, pkg.applicationInfo.uid); 7309 mActivities.addActivity(a, "activity"); 7310 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7311 if (r == null) { 7312 r = new StringBuilder(256); 7313 } else { 7314 r.append(' '); 7315 } 7316 r.append(a.info.name); 7317 } 7318 } 7319 if (r != null) { 7320 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7321 } 7322 7323 N = pkg.permissionGroups.size(); 7324 r = null; 7325 for (i=0; i<N; i++) { 7326 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7327 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7328 if (cur == null) { 7329 mPermissionGroups.put(pg.info.name, pg); 7330 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7331 if (r == null) { 7332 r = new StringBuilder(256); 7333 } else { 7334 r.append(' '); 7335 } 7336 r.append(pg.info.name); 7337 } 7338 } else { 7339 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7340 + pg.info.packageName + " ignored: original from " 7341 + cur.info.packageName); 7342 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7343 if (r == null) { 7344 r = new StringBuilder(256); 7345 } else { 7346 r.append(' '); 7347 } 7348 r.append("DUP:"); 7349 r.append(pg.info.name); 7350 } 7351 } 7352 } 7353 if (r != null) { 7354 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7355 } 7356 7357 N = pkg.permissions.size(); 7358 r = null; 7359 for (i=0; i<N; i++) { 7360 PackageParser.Permission p = pkg.permissions.get(i); 7361 7362 // Assume by default that we did not install this permission into the system. 7363 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7364 7365 // Now that permission groups have a special meaning, we ignore permission 7366 // groups for legacy apps to prevent unexpected behavior. In particular, 7367 // permissions for one app being granted to someone just becuase they happen 7368 // to be in a group defined by another app (before this had no implications). 7369 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7370 p.group = mPermissionGroups.get(p.info.group); 7371 // Warn for a permission in an unknown group. 7372 if (p.info.group != null && p.group == null) { 7373 Slog.w(TAG, "Permission " + p.info.name + " from package " 7374 + p.info.packageName + " in an unknown group " + p.info.group); 7375 } 7376 } 7377 7378 ArrayMap<String, BasePermission> permissionMap = 7379 p.tree ? mSettings.mPermissionTrees 7380 : mSettings.mPermissions; 7381 BasePermission bp = permissionMap.get(p.info.name); 7382 7383 // Allow system apps to redefine non-system permissions 7384 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7385 final boolean currentOwnerIsSystem = (bp.perm != null 7386 && isSystemApp(bp.perm.owner)); 7387 if (isSystemApp(p.owner)) { 7388 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7389 // It's a built-in permission and no owner, take ownership now 7390 bp.packageSetting = pkgSetting; 7391 bp.perm = p; 7392 bp.uid = pkg.applicationInfo.uid; 7393 bp.sourcePackage = p.info.packageName; 7394 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7395 } else if (!currentOwnerIsSystem) { 7396 String msg = "New decl " + p.owner + " of permission " 7397 + p.info.name + " is system; overriding " + bp.sourcePackage; 7398 reportSettingsProblem(Log.WARN, msg); 7399 bp = null; 7400 } 7401 } 7402 } 7403 7404 if (bp == null) { 7405 bp = new BasePermission(p.info.name, p.info.packageName, 7406 BasePermission.TYPE_NORMAL); 7407 permissionMap.put(p.info.name, bp); 7408 } 7409 7410 if (bp.perm == null) { 7411 if (bp.sourcePackage == null 7412 || bp.sourcePackage.equals(p.info.packageName)) { 7413 BasePermission tree = findPermissionTreeLP(p.info.name); 7414 if (tree == null 7415 || tree.sourcePackage.equals(p.info.packageName)) { 7416 bp.packageSetting = pkgSetting; 7417 bp.perm = p; 7418 bp.uid = pkg.applicationInfo.uid; 7419 bp.sourcePackage = p.info.packageName; 7420 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7421 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7422 if (r == null) { 7423 r = new StringBuilder(256); 7424 } else { 7425 r.append(' '); 7426 } 7427 r.append(p.info.name); 7428 } 7429 } else { 7430 Slog.w(TAG, "Permission " + p.info.name + " from package " 7431 + p.info.packageName + " ignored: base tree " 7432 + tree.name + " is from package " 7433 + tree.sourcePackage); 7434 } 7435 } else { 7436 Slog.w(TAG, "Permission " + p.info.name + " from package " 7437 + p.info.packageName + " ignored: original from " 7438 + bp.sourcePackage); 7439 } 7440 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7441 if (r == null) { 7442 r = new StringBuilder(256); 7443 } else { 7444 r.append(' '); 7445 } 7446 r.append("DUP:"); 7447 r.append(p.info.name); 7448 } 7449 if (bp.perm == p) { 7450 bp.protectionLevel = p.info.protectionLevel; 7451 } 7452 } 7453 7454 if (r != null) { 7455 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7456 } 7457 7458 N = pkg.instrumentation.size(); 7459 r = null; 7460 for (i=0; i<N; i++) { 7461 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7462 a.info.packageName = pkg.applicationInfo.packageName; 7463 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7464 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7465 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7466 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7467 a.info.dataDir = pkg.applicationInfo.dataDir; 7468 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7469 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7470 7471 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7472 // need other information about the application, like the ABI and what not ? 7473 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7474 mInstrumentation.put(a.getComponentName(), a); 7475 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7476 if (r == null) { 7477 r = new StringBuilder(256); 7478 } else { 7479 r.append(' '); 7480 } 7481 r.append(a.info.name); 7482 } 7483 } 7484 if (r != null) { 7485 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7486 } 7487 7488 if (pkg.protectedBroadcasts != null) { 7489 N = pkg.protectedBroadcasts.size(); 7490 for (i=0; i<N; i++) { 7491 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7492 } 7493 } 7494 7495 pkgSetting.setTimeStamp(scanFileTime); 7496 7497 // Create idmap files for pairs of (packages, overlay packages). 7498 // Note: "android", ie framework-res.apk, is handled by native layers. 7499 if (pkg.mOverlayTarget != null) { 7500 // This is an overlay package. 7501 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7502 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7503 mOverlays.put(pkg.mOverlayTarget, 7504 new ArrayMap<String, PackageParser.Package>()); 7505 } 7506 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7507 map.put(pkg.packageName, pkg); 7508 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7509 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7510 createIdmapFailed = true; 7511 } 7512 } 7513 } else if (mOverlays.containsKey(pkg.packageName) && 7514 !pkg.packageName.equals("android")) { 7515 // This is a regular package, with one or more known overlay packages. 7516 createIdmapsForPackageLI(pkg); 7517 } 7518 } 7519 7520 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7521 7522 if (createIdmapFailed) { 7523 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7524 "scanPackageLI failed to createIdmap"); 7525 } 7526 return pkg; 7527 } 7528 7529 /** 7530 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7531 * is derived purely on the basis of the contents of {@code scanFile} and 7532 * {@code cpuAbiOverride}. 7533 * 7534 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7535 */ 7536 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7537 String cpuAbiOverride, boolean extractLibs) 7538 throws PackageManagerException { 7539 // TODO: We can probably be smarter about this stuff. For installed apps, 7540 // we can calculate this information at install time once and for all. For 7541 // system apps, we can probably assume that this information doesn't change 7542 // after the first boot scan. As things stand, we do lots of unnecessary work. 7543 7544 // Give ourselves some initial paths; we'll come back for another 7545 // pass once we've determined ABI below. 7546 setNativeLibraryPaths(pkg); 7547 7548 // We would never need to extract libs for forward-locked and external packages, 7549 // since the container service will do it for us. We shouldn't attempt to 7550 // extract libs from system app when it was not updated. 7551 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7552 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7553 extractLibs = false; 7554 } 7555 7556 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7557 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7558 7559 NativeLibraryHelper.Handle handle = null; 7560 try { 7561 handle = NativeLibraryHelper.Handle.create(pkg); 7562 // TODO(multiArch): This can be null for apps that didn't go through the 7563 // usual installation process. We can calculate it again, like we 7564 // do during install time. 7565 // 7566 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7567 // unnecessary. 7568 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7569 7570 // Null out the abis so that they can be recalculated. 7571 pkg.applicationInfo.primaryCpuAbi = null; 7572 pkg.applicationInfo.secondaryCpuAbi = null; 7573 if (isMultiArch(pkg.applicationInfo)) { 7574 // Warn if we've set an abiOverride for multi-lib packages.. 7575 // By definition, we need to copy both 32 and 64 bit libraries for 7576 // such packages. 7577 if (pkg.cpuAbiOverride != null 7578 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7579 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7580 } 7581 7582 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7583 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7584 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7585 if (extractLibs) { 7586 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7587 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7588 useIsaSpecificSubdirs); 7589 } else { 7590 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7591 } 7592 } 7593 7594 maybeThrowExceptionForMultiArchCopy( 7595 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7596 7597 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7598 if (extractLibs) { 7599 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7600 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7601 useIsaSpecificSubdirs); 7602 } else { 7603 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7604 } 7605 } 7606 7607 maybeThrowExceptionForMultiArchCopy( 7608 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7609 7610 if (abi64 >= 0) { 7611 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7612 } 7613 7614 if (abi32 >= 0) { 7615 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7616 if (abi64 >= 0) { 7617 pkg.applicationInfo.secondaryCpuAbi = abi; 7618 } else { 7619 pkg.applicationInfo.primaryCpuAbi = abi; 7620 } 7621 } 7622 } else { 7623 String[] abiList = (cpuAbiOverride != null) ? 7624 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7625 7626 // Enable gross and lame hacks for apps that are built with old 7627 // SDK tools. We must scan their APKs for renderscript bitcode and 7628 // not launch them if it's present. Don't bother checking on devices 7629 // that don't have 64 bit support. 7630 boolean needsRenderScriptOverride = false; 7631 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7632 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7633 abiList = Build.SUPPORTED_32_BIT_ABIS; 7634 needsRenderScriptOverride = true; 7635 } 7636 7637 final int copyRet; 7638 if (extractLibs) { 7639 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7640 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7641 } else { 7642 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7643 } 7644 7645 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7646 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7647 "Error unpackaging native libs for app, errorCode=" + copyRet); 7648 } 7649 7650 if (copyRet >= 0) { 7651 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7652 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7653 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7654 } else if (needsRenderScriptOverride) { 7655 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7656 } 7657 } 7658 } catch (IOException ioe) { 7659 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7660 } finally { 7661 IoUtils.closeQuietly(handle); 7662 } 7663 7664 // Now that we've calculated the ABIs and determined if it's an internal app, 7665 // we will go ahead and populate the nativeLibraryPath. 7666 setNativeLibraryPaths(pkg); 7667 } 7668 7669 /** 7670 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7671 * i.e, so that all packages can be run inside a single process if required. 7672 * 7673 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7674 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7675 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7676 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7677 * updating a package that belongs to a shared user. 7678 * 7679 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7680 * adds unnecessary complexity. 7681 */ 7682 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7683 PackageParser.Package scannedPackage, boolean bootComplete) { 7684 String requiredInstructionSet = null; 7685 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7686 requiredInstructionSet = VMRuntime.getInstructionSet( 7687 scannedPackage.applicationInfo.primaryCpuAbi); 7688 } 7689 7690 PackageSetting requirer = null; 7691 for (PackageSetting ps : packagesForUser) { 7692 // If packagesForUser contains scannedPackage, we skip it. This will happen 7693 // when scannedPackage is an update of an existing package. Without this check, 7694 // we will never be able to change the ABI of any package belonging to a shared 7695 // user, even if it's compatible with other packages. 7696 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7697 if (ps.primaryCpuAbiString == null) { 7698 continue; 7699 } 7700 7701 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7702 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7703 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7704 // this but there's not much we can do. 7705 String errorMessage = "Instruction set mismatch, " 7706 + ((requirer == null) ? "[caller]" : requirer) 7707 + " requires " + requiredInstructionSet + " whereas " + ps 7708 + " requires " + instructionSet; 7709 Slog.w(TAG, errorMessage); 7710 } 7711 7712 if (requiredInstructionSet == null) { 7713 requiredInstructionSet = instructionSet; 7714 requirer = ps; 7715 } 7716 } 7717 } 7718 7719 if (requiredInstructionSet != null) { 7720 String adjustedAbi; 7721 if (requirer != null) { 7722 // requirer != null implies that either scannedPackage was null or that scannedPackage 7723 // did not require an ABI, in which case we have to adjust scannedPackage to match 7724 // the ABI of the set (which is the same as requirer's ABI) 7725 adjustedAbi = requirer.primaryCpuAbiString; 7726 if (scannedPackage != null) { 7727 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7728 } 7729 } else { 7730 // requirer == null implies that we're updating all ABIs in the set to 7731 // match scannedPackage. 7732 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7733 } 7734 7735 for (PackageSetting ps : packagesForUser) { 7736 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7737 if (ps.primaryCpuAbiString != null) { 7738 continue; 7739 } 7740 7741 ps.primaryCpuAbiString = adjustedAbi; 7742 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7743 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7744 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7745 mInstaller.rmdex(ps.codePathString, 7746 getDexCodeInstructionSet(getPreferredInstructionSet())); 7747 } 7748 } 7749 } 7750 } 7751 } 7752 7753 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7754 synchronized (mPackages) { 7755 mResolverReplaced = true; 7756 // Set up information for custom user intent resolution activity. 7757 mResolveActivity.applicationInfo = pkg.applicationInfo; 7758 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7759 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7760 mResolveActivity.processName = pkg.applicationInfo.packageName; 7761 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7762 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7763 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7764 mResolveActivity.theme = 0; 7765 mResolveActivity.exported = true; 7766 mResolveActivity.enabled = true; 7767 mResolveInfo.activityInfo = mResolveActivity; 7768 mResolveInfo.priority = 0; 7769 mResolveInfo.preferredOrder = 0; 7770 mResolveInfo.match = 0; 7771 mResolveComponentName = mCustomResolverComponentName; 7772 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7773 mResolveComponentName); 7774 } 7775 } 7776 7777 private static String calculateBundledApkRoot(final String codePathString) { 7778 final File codePath = new File(codePathString); 7779 final File codeRoot; 7780 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7781 codeRoot = Environment.getRootDirectory(); 7782 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7783 codeRoot = Environment.getOemDirectory(); 7784 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7785 codeRoot = Environment.getVendorDirectory(); 7786 } else { 7787 // Unrecognized code path; take its top real segment as the apk root: 7788 // e.g. /something/app/blah.apk => /something 7789 try { 7790 File f = codePath.getCanonicalFile(); 7791 File parent = f.getParentFile(); // non-null because codePath is a file 7792 File tmp; 7793 while ((tmp = parent.getParentFile()) != null) { 7794 f = parent; 7795 parent = tmp; 7796 } 7797 codeRoot = f; 7798 Slog.w(TAG, "Unrecognized code path " 7799 + codePath + " - using " + codeRoot); 7800 } catch (IOException e) { 7801 // Can't canonicalize the code path -- shenanigans? 7802 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7803 return Environment.getRootDirectory().getPath(); 7804 } 7805 } 7806 return codeRoot.getPath(); 7807 } 7808 7809 /** 7810 * Derive and set the location of native libraries for the given package, 7811 * which varies depending on where and how the package was installed. 7812 */ 7813 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7814 final ApplicationInfo info = pkg.applicationInfo; 7815 final String codePath = pkg.codePath; 7816 final File codeFile = new File(codePath); 7817 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7818 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7819 7820 info.nativeLibraryRootDir = null; 7821 info.nativeLibraryRootRequiresIsa = false; 7822 info.nativeLibraryDir = null; 7823 info.secondaryNativeLibraryDir = null; 7824 7825 if (isApkFile(codeFile)) { 7826 // Monolithic install 7827 if (bundledApp) { 7828 // If "/system/lib64/apkname" exists, assume that is the per-package 7829 // native library directory to use; otherwise use "/system/lib/apkname". 7830 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7831 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7832 getPrimaryInstructionSet(info)); 7833 7834 // This is a bundled system app so choose the path based on the ABI. 7835 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7836 // is just the default path. 7837 final String apkName = deriveCodePathName(codePath); 7838 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7839 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7840 apkName).getAbsolutePath(); 7841 7842 if (info.secondaryCpuAbi != null) { 7843 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7844 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7845 secondaryLibDir, apkName).getAbsolutePath(); 7846 } 7847 } else if (asecApp) { 7848 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7849 .getAbsolutePath(); 7850 } else { 7851 final String apkName = deriveCodePathName(codePath); 7852 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7853 .getAbsolutePath(); 7854 } 7855 7856 info.nativeLibraryRootRequiresIsa = false; 7857 info.nativeLibraryDir = info.nativeLibraryRootDir; 7858 } else { 7859 // Cluster install 7860 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7861 info.nativeLibraryRootRequiresIsa = true; 7862 7863 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7864 getPrimaryInstructionSet(info)).getAbsolutePath(); 7865 7866 if (info.secondaryCpuAbi != null) { 7867 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7868 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7869 } 7870 } 7871 } 7872 7873 /** 7874 * Calculate the abis and roots for a bundled app. These can uniquely 7875 * be determined from the contents of the system partition, i.e whether 7876 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7877 * of this information, and instead assume that the system was built 7878 * sensibly. 7879 */ 7880 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7881 PackageSetting pkgSetting) { 7882 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7883 7884 // If "/system/lib64/apkname" exists, assume that is the per-package 7885 // native library directory to use; otherwise use "/system/lib/apkname". 7886 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7887 setBundledAppAbi(pkg, apkRoot, apkName); 7888 // pkgSetting might be null during rescan following uninstall of updates 7889 // to a bundled app, so accommodate that possibility. The settings in 7890 // that case will be established later from the parsed package. 7891 // 7892 // If the settings aren't null, sync them up with what we've just derived. 7893 // note that apkRoot isn't stored in the package settings. 7894 if (pkgSetting != null) { 7895 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7896 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7897 } 7898 } 7899 7900 /** 7901 * Deduces the ABI of a bundled app and sets the relevant fields on the 7902 * parsed pkg object. 7903 * 7904 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7905 * under which system libraries are installed. 7906 * @param apkName the name of the installed package. 7907 */ 7908 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7909 final File codeFile = new File(pkg.codePath); 7910 7911 final boolean has64BitLibs; 7912 final boolean has32BitLibs; 7913 if (isApkFile(codeFile)) { 7914 // Monolithic install 7915 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7916 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7917 } else { 7918 // Cluster install 7919 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7920 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7921 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7922 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7923 has64BitLibs = (new File(rootDir, isa)).exists(); 7924 } else { 7925 has64BitLibs = false; 7926 } 7927 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7928 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7929 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7930 has32BitLibs = (new File(rootDir, isa)).exists(); 7931 } else { 7932 has32BitLibs = false; 7933 } 7934 } 7935 7936 if (has64BitLibs && !has32BitLibs) { 7937 // The package has 64 bit libs, but not 32 bit libs. Its primary 7938 // ABI should be 64 bit. We can safely assume here that the bundled 7939 // native libraries correspond to the most preferred ABI in the list. 7940 7941 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7942 pkg.applicationInfo.secondaryCpuAbi = null; 7943 } else if (has32BitLibs && !has64BitLibs) { 7944 // The package has 32 bit libs but not 64 bit libs. Its primary 7945 // ABI should be 32 bit. 7946 7947 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7948 pkg.applicationInfo.secondaryCpuAbi = null; 7949 } else if (has32BitLibs && has64BitLibs) { 7950 // The application has both 64 and 32 bit bundled libraries. We check 7951 // here that the app declares multiArch support, and warn if it doesn't. 7952 // 7953 // We will be lenient here and record both ABIs. The primary will be the 7954 // ABI that's higher on the list, i.e, a device that's configured to prefer 7955 // 64 bit apps will see a 64 bit primary ABI, 7956 7957 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7958 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7959 } 7960 7961 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7962 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7963 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7964 } else { 7965 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7966 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7967 } 7968 } else { 7969 pkg.applicationInfo.primaryCpuAbi = null; 7970 pkg.applicationInfo.secondaryCpuAbi = null; 7971 } 7972 } 7973 7974 private void killApplication(String pkgName, int appId, String reason) { 7975 // Request the ActivityManager to kill the process(only for existing packages) 7976 // so that we do not end up in a confused state while the user is still using the older 7977 // version of the application while the new one gets installed. 7978 IActivityManager am = ActivityManagerNative.getDefault(); 7979 if (am != null) { 7980 try { 7981 am.killApplicationWithAppId(pkgName, appId, reason); 7982 } catch (RemoteException e) { 7983 } 7984 } 7985 } 7986 7987 void removePackageLI(PackageSetting ps, boolean chatty) { 7988 if (DEBUG_INSTALL) { 7989 if (chatty) 7990 Log.d(TAG, "Removing package " + ps.name); 7991 } 7992 7993 // writer 7994 synchronized (mPackages) { 7995 mPackages.remove(ps.name); 7996 final PackageParser.Package pkg = ps.pkg; 7997 if (pkg != null) { 7998 cleanPackageDataStructuresLILPw(pkg, chatty); 7999 } 8000 } 8001 } 8002 8003 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8004 if (DEBUG_INSTALL) { 8005 if (chatty) 8006 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8007 } 8008 8009 // writer 8010 synchronized (mPackages) { 8011 mPackages.remove(pkg.applicationInfo.packageName); 8012 cleanPackageDataStructuresLILPw(pkg, chatty); 8013 } 8014 } 8015 8016 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8017 int N = pkg.providers.size(); 8018 StringBuilder r = null; 8019 int i; 8020 for (i=0; i<N; i++) { 8021 PackageParser.Provider p = pkg.providers.get(i); 8022 mProviders.removeProvider(p); 8023 if (p.info.authority == null) { 8024 8025 /* There was another ContentProvider with this authority when 8026 * this app was installed so this authority is null, 8027 * Ignore it as we don't have to unregister the provider. 8028 */ 8029 continue; 8030 } 8031 String names[] = p.info.authority.split(";"); 8032 for (int j = 0; j < names.length; j++) { 8033 if (mProvidersByAuthority.get(names[j]) == p) { 8034 mProvidersByAuthority.remove(names[j]); 8035 if (DEBUG_REMOVE) { 8036 if (chatty) 8037 Log.d(TAG, "Unregistered content provider: " + names[j] 8038 + ", className = " + p.info.name + ", isSyncable = " 8039 + p.info.isSyncable); 8040 } 8041 } 8042 } 8043 if (DEBUG_REMOVE && chatty) { 8044 if (r == null) { 8045 r = new StringBuilder(256); 8046 } else { 8047 r.append(' '); 8048 } 8049 r.append(p.info.name); 8050 } 8051 } 8052 if (r != null) { 8053 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8054 } 8055 8056 N = pkg.services.size(); 8057 r = null; 8058 for (i=0; i<N; i++) { 8059 PackageParser.Service s = pkg.services.get(i); 8060 mServices.removeService(s); 8061 if (chatty) { 8062 if (r == null) { 8063 r = new StringBuilder(256); 8064 } else { 8065 r.append(' '); 8066 } 8067 r.append(s.info.name); 8068 } 8069 } 8070 if (r != null) { 8071 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8072 } 8073 8074 N = pkg.receivers.size(); 8075 r = null; 8076 for (i=0; i<N; i++) { 8077 PackageParser.Activity a = pkg.receivers.get(i); 8078 mReceivers.removeActivity(a, "receiver"); 8079 if (DEBUG_REMOVE && chatty) { 8080 if (r == null) { 8081 r = new StringBuilder(256); 8082 } else { 8083 r.append(' '); 8084 } 8085 r.append(a.info.name); 8086 } 8087 } 8088 if (r != null) { 8089 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8090 } 8091 8092 N = pkg.activities.size(); 8093 r = null; 8094 for (i=0; i<N; i++) { 8095 PackageParser.Activity a = pkg.activities.get(i); 8096 mActivities.removeActivity(a, "activity"); 8097 if (DEBUG_REMOVE && chatty) { 8098 if (r == null) { 8099 r = new StringBuilder(256); 8100 } else { 8101 r.append(' '); 8102 } 8103 r.append(a.info.name); 8104 } 8105 } 8106 if (r != null) { 8107 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8108 } 8109 8110 N = pkg.permissions.size(); 8111 r = null; 8112 for (i=0; i<N; i++) { 8113 PackageParser.Permission p = pkg.permissions.get(i); 8114 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8115 if (bp == null) { 8116 bp = mSettings.mPermissionTrees.get(p.info.name); 8117 } 8118 if (bp != null && bp.perm == p) { 8119 bp.perm = null; 8120 if (DEBUG_REMOVE && chatty) { 8121 if (r == null) { 8122 r = new StringBuilder(256); 8123 } else { 8124 r.append(' '); 8125 } 8126 r.append(p.info.name); 8127 } 8128 } 8129 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8130 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8131 if (appOpPerms != null) { 8132 appOpPerms.remove(pkg.packageName); 8133 } 8134 } 8135 } 8136 if (r != null) { 8137 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8138 } 8139 8140 N = pkg.requestedPermissions.size(); 8141 r = null; 8142 for (i=0; i<N; i++) { 8143 String perm = pkg.requestedPermissions.get(i); 8144 BasePermission bp = mSettings.mPermissions.get(perm); 8145 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8146 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8147 if (appOpPerms != null) { 8148 appOpPerms.remove(pkg.packageName); 8149 if (appOpPerms.isEmpty()) { 8150 mAppOpPermissionPackages.remove(perm); 8151 } 8152 } 8153 } 8154 } 8155 if (r != null) { 8156 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8157 } 8158 8159 N = pkg.instrumentation.size(); 8160 r = null; 8161 for (i=0; i<N; i++) { 8162 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8163 mInstrumentation.remove(a.getComponentName()); 8164 if (DEBUG_REMOVE && chatty) { 8165 if (r == null) { 8166 r = new StringBuilder(256); 8167 } else { 8168 r.append(' '); 8169 } 8170 r.append(a.info.name); 8171 } 8172 } 8173 if (r != null) { 8174 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8175 } 8176 8177 r = null; 8178 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8179 // Only system apps can hold shared libraries. 8180 if (pkg.libraryNames != null) { 8181 for (i=0; i<pkg.libraryNames.size(); i++) { 8182 String name = pkg.libraryNames.get(i); 8183 SharedLibraryEntry cur = mSharedLibraries.get(name); 8184 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8185 mSharedLibraries.remove(name); 8186 if (DEBUG_REMOVE && chatty) { 8187 if (r == null) { 8188 r = new StringBuilder(256); 8189 } else { 8190 r.append(' '); 8191 } 8192 r.append(name); 8193 } 8194 } 8195 } 8196 } 8197 } 8198 if (r != null) { 8199 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8200 } 8201 } 8202 8203 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8204 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8205 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8206 return true; 8207 } 8208 } 8209 return false; 8210 } 8211 8212 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8213 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8214 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8215 8216 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8217 int flags) { 8218 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8219 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8220 } 8221 8222 private void updatePermissionsLPw(String changingPkg, 8223 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8224 // Make sure there are no dangling permission trees. 8225 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8226 while (it.hasNext()) { 8227 final BasePermission bp = it.next(); 8228 if (bp.packageSetting == null) { 8229 // We may not yet have parsed the package, so just see if 8230 // we still know about its settings. 8231 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8232 } 8233 if (bp.packageSetting == null) { 8234 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8235 + " from package " + bp.sourcePackage); 8236 it.remove(); 8237 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8238 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8239 Slog.i(TAG, "Removing old permission tree: " + bp.name 8240 + " from package " + bp.sourcePackage); 8241 flags |= UPDATE_PERMISSIONS_ALL; 8242 it.remove(); 8243 } 8244 } 8245 } 8246 8247 // Make sure all dynamic permissions have been assigned to a package, 8248 // and make sure there are no dangling permissions. 8249 it = mSettings.mPermissions.values().iterator(); 8250 while (it.hasNext()) { 8251 final BasePermission bp = it.next(); 8252 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8253 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8254 + bp.name + " pkg=" + bp.sourcePackage 8255 + " info=" + bp.pendingInfo); 8256 if (bp.packageSetting == null && bp.pendingInfo != null) { 8257 final BasePermission tree = findPermissionTreeLP(bp.name); 8258 if (tree != null && tree.perm != null) { 8259 bp.packageSetting = tree.packageSetting; 8260 bp.perm = new PackageParser.Permission(tree.perm.owner, 8261 new PermissionInfo(bp.pendingInfo)); 8262 bp.perm.info.packageName = tree.perm.info.packageName; 8263 bp.perm.info.name = bp.name; 8264 bp.uid = tree.uid; 8265 } 8266 } 8267 } 8268 if (bp.packageSetting == null) { 8269 // We may not yet have parsed the package, so just see if 8270 // we still know about its settings. 8271 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8272 } 8273 if (bp.packageSetting == null) { 8274 Slog.w(TAG, "Removing dangling permission: " + bp.name 8275 + " from package " + bp.sourcePackage); 8276 it.remove(); 8277 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8278 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8279 Slog.i(TAG, "Removing old permission: " + bp.name 8280 + " from package " + bp.sourcePackage); 8281 flags |= UPDATE_PERMISSIONS_ALL; 8282 it.remove(); 8283 } 8284 } 8285 } 8286 8287 // Now update the permissions for all packages, in particular 8288 // replace the granted permissions of the system packages. 8289 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8290 for (PackageParser.Package pkg : mPackages.values()) { 8291 if (pkg != pkgInfo) { 8292 // Only replace for packages on requested volume 8293 final String volumeUuid = getVolumeUuidForPackage(pkg); 8294 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8295 && Objects.equals(replaceVolumeUuid, volumeUuid); 8296 grantPermissionsLPw(pkg, replace, changingPkg); 8297 } 8298 } 8299 } 8300 8301 if (pkgInfo != null) { 8302 // Only replace for packages on requested volume 8303 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8304 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8305 && Objects.equals(replaceVolumeUuid, volumeUuid); 8306 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8307 } 8308 } 8309 8310 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8311 String packageOfInterest) { 8312 // IMPORTANT: There are two types of permissions: install and runtime. 8313 // Install time permissions are granted when the app is installed to 8314 // all device users and users added in the future. Runtime permissions 8315 // are granted at runtime explicitly to specific users. Normal and signature 8316 // protected permissions are install time permissions. Dangerous permissions 8317 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8318 // otherwise they are runtime permissions. This function does not manage 8319 // runtime permissions except for the case an app targeting Lollipop MR1 8320 // being upgraded to target a newer SDK, in which case dangerous permissions 8321 // are transformed from install time to runtime ones. 8322 8323 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8324 if (ps == null) { 8325 return; 8326 } 8327 8328 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8329 8330 PermissionsState permissionsState = ps.getPermissionsState(); 8331 PermissionsState origPermissions = permissionsState; 8332 8333 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8334 8335 boolean runtimePermissionsRevoked = false; 8336 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8337 8338 boolean changedInstallPermission = false; 8339 8340 if (replace) { 8341 ps.installPermissionsFixed = false; 8342 if (!ps.isSharedUser()) { 8343 origPermissions = new PermissionsState(permissionsState); 8344 permissionsState.reset(); 8345 } else { 8346 // We need to know only about runtime permission changes since the 8347 // calling code always writes the install permissions state but 8348 // the runtime ones are written only if changed. The only cases of 8349 // changed runtime permissions here are promotion of an install to 8350 // runtime and revocation of a runtime from a shared user. 8351 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8352 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8353 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8354 runtimePermissionsRevoked = true; 8355 } 8356 } 8357 } 8358 8359 permissionsState.setGlobalGids(mGlobalGids); 8360 8361 final int N = pkg.requestedPermissions.size(); 8362 for (int i=0; i<N; i++) { 8363 final String name = pkg.requestedPermissions.get(i); 8364 final BasePermission bp = mSettings.mPermissions.get(name); 8365 8366 if (DEBUG_INSTALL) { 8367 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8368 } 8369 8370 if (bp == null || bp.packageSetting == null) { 8371 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8372 Slog.w(TAG, "Unknown permission " + name 8373 + " in package " + pkg.packageName); 8374 } 8375 continue; 8376 } 8377 8378 final String perm = bp.name; 8379 boolean allowedSig = false; 8380 int grant = GRANT_DENIED; 8381 8382 // Keep track of app op permissions. 8383 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8384 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8385 if (pkgs == null) { 8386 pkgs = new ArraySet<>(); 8387 mAppOpPermissionPackages.put(bp.name, pkgs); 8388 } 8389 pkgs.add(pkg.packageName); 8390 } 8391 8392 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8393 switch (level) { 8394 case PermissionInfo.PROTECTION_NORMAL: { 8395 // For all apps normal permissions are install time ones. 8396 grant = GRANT_INSTALL; 8397 } break; 8398 8399 case PermissionInfo.PROTECTION_DANGEROUS: { 8400 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8401 // For legacy apps dangerous permissions are install time ones. 8402 grant = GRANT_INSTALL_LEGACY; 8403 } else if (origPermissions.hasInstallPermission(bp.name)) { 8404 // For legacy apps that became modern, install becomes runtime. 8405 grant = GRANT_UPGRADE; 8406 } else if (mPromoteSystemApps 8407 && isSystemApp(ps) 8408 && mExistingSystemPackages.contains(ps.name)) { 8409 // For legacy system apps, install becomes runtime. 8410 // We cannot check hasInstallPermission() for system apps since those 8411 // permissions were granted implicitly and not persisted pre-M. 8412 grant = GRANT_UPGRADE; 8413 } else { 8414 // For modern apps keep runtime permissions unchanged. 8415 grant = GRANT_RUNTIME; 8416 } 8417 } break; 8418 8419 case PermissionInfo.PROTECTION_SIGNATURE: { 8420 // For all apps signature permissions are install time ones. 8421 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8422 if (allowedSig) { 8423 grant = GRANT_INSTALL; 8424 } 8425 } break; 8426 } 8427 8428 if (DEBUG_INSTALL) { 8429 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8430 } 8431 8432 if (grant != GRANT_DENIED) { 8433 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8434 // If this is an existing, non-system package, then 8435 // we can't add any new permissions to it. 8436 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8437 // Except... if this is a permission that was added 8438 // to the platform (note: need to only do this when 8439 // updating the platform). 8440 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8441 grant = GRANT_DENIED; 8442 } 8443 } 8444 } 8445 8446 switch (grant) { 8447 case GRANT_INSTALL: { 8448 // Revoke this as runtime permission to handle the case of 8449 // a runtime permission being downgraded to an install one. 8450 for (int userId : UserManagerService.getInstance().getUserIds()) { 8451 if (origPermissions.getRuntimePermissionState( 8452 bp.name, userId) != null) { 8453 // Revoke the runtime permission and clear the flags. 8454 origPermissions.revokeRuntimePermission(bp, userId); 8455 origPermissions.updatePermissionFlags(bp, userId, 8456 PackageManager.MASK_PERMISSION_FLAGS, 0); 8457 // If we revoked a permission permission, we have to write. 8458 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8459 changedRuntimePermissionUserIds, userId); 8460 } 8461 } 8462 // Grant an install permission. 8463 if (permissionsState.grantInstallPermission(bp) != 8464 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8465 changedInstallPermission = true; 8466 } 8467 } break; 8468 8469 case GRANT_INSTALL_LEGACY: { 8470 // Grant an install permission. 8471 if (permissionsState.grantInstallPermission(bp) != 8472 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8473 changedInstallPermission = true; 8474 } 8475 } break; 8476 8477 case GRANT_RUNTIME: { 8478 // Grant previously granted runtime permissions. 8479 for (int userId : UserManagerService.getInstance().getUserIds()) { 8480 PermissionState permissionState = origPermissions 8481 .getRuntimePermissionState(bp.name, userId); 8482 final int flags = permissionState != null 8483 ? permissionState.getFlags() : 0; 8484 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8485 if (permissionsState.grantRuntimePermission(bp, userId) == 8486 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8487 // If we cannot put the permission as it was, we have to write. 8488 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8489 changedRuntimePermissionUserIds, userId); 8490 } 8491 } 8492 // Propagate the permission flags. 8493 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8494 } 8495 } break; 8496 8497 case GRANT_UPGRADE: { 8498 // Grant runtime permissions for a previously held install permission. 8499 PermissionState permissionState = origPermissions 8500 .getInstallPermissionState(bp.name); 8501 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8502 8503 if (origPermissions.revokeInstallPermission(bp) 8504 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8505 // We will be transferring the permission flags, so clear them. 8506 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8507 PackageManager.MASK_PERMISSION_FLAGS, 0); 8508 changedInstallPermission = true; 8509 } 8510 8511 // If the permission is not to be promoted to runtime we ignore it and 8512 // also its other flags as they are not applicable to install permissions. 8513 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8514 for (int userId : currentUserIds) { 8515 if (permissionsState.grantRuntimePermission(bp, userId) != 8516 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8517 // Transfer the permission flags. 8518 permissionsState.updatePermissionFlags(bp, userId, 8519 flags, flags); 8520 // If we granted the permission, we have to write. 8521 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8522 changedRuntimePermissionUserIds, userId); 8523 } 8524 } 8525 } 8526 } break; 8527 8528 default: { 8529 if (packageOfInterest == null 8530 || packageOfInterest.equals(pkg.packageName)) { 8531 Slog.w(TAG, "Not granting permission " + perm 8532 + " to package " + pkg.packageName 8533 + " because it was previously installed without"); 8534 } 8535 } break; 8536 } 8537 } else { 8538 if (permissionsState.revokeInstallPermission(bp) != 8539 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8540 // Also drop the permission flags. 8541 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8542 PackageManager.MASK_PERMISSION_FLAGS, 0); 8543 changedInstallPermission = true; 8544 Slog.i(TAG, "Un-granting permission " + perm 8545 + " from package " + pkg.packageName 8546 + " (protectionLevel=" + bp.protectionLevel 8547 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8548 + ")"); 8549 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8550 // Don't print warning for app op permissions, since it is fine for them 8551 // not to be granted, there is a UI for the user to decide. 8552 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8553 Slog.w(TAG, "Not granting permission " + perm 8554 + " to package " + pkg.packageName 8555 + " (protectionLevel=" + bp.protectionLevel 8556 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8557 + ")"); 8558 } 8559 } 8560 } 8561 } 8562 8563 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8564 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8565 // This is the first that we have heard about this package, so the 8566 // permissions we have now selected are fixed until explicitly 8567 // changed. 8568 ps.installPermissionsFixed = true; 8569 } 8570 8571 // Persist the runtime permissions state for users with changes. If permissions 8572 // were revoked because no app in the shared user declares them we have to 8573 // write synchronously to avoid losing runtime permissions state. 8574 for (int userId : changedRuntimePermissionUserIds) { 8575 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8576 } 8577 8578 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8579 } 8580 8581 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8582 boolean allowed = false; 8583 final int NP = PackageParser.NEW_PERMISSIONS.length; 8584 for (int ip=0; ip<NP; ip++) { 8585 final PackageParser.NewPermissionInfo npi 8586 = PackageParser.NEW_PERMISSIONS[ip]; 8587 if (npi.name.equals(perm) 8588 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8589 allowed = true; 8590 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8591 + pkg.packageName); 8592 break; 8593 } 8594 } 8595 return allowed; 8596 } 8597 8598 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8599 BasePermission bp, PermissionsState origPermissions) { 8600 boolean allowed; 8601 allowed = (compareSignatures( 8602 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8603 == PackageManager.SIGNATURE_MATCH) 8604 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8605 == PackageManager.SIGNATURE_MATCH); 8606 if (!allowed && (bp.protectionLevel 8607 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8608 if (isSystemApp(pkg)) { 8609 // For updated system applications, a system permission 8610 // is granted only if it had been defined by the original application. 8611 if (pkg.isUpdatedSystemApp()) { 8612 final PackageSetting sysPs = mSettings 8613 .getDisabledSystemPkgLPr(pkg.packageName); 8614 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8615 // If the original was granted this permission, we take 8616 // that grant decision as read and propagate it to the 8617 // update. 8618 if (sysPs.isPrivileged()) { 8619 allowed = true; 8620 } 8621 } else { 8622 // The system apk may have been updated with an older 8623 // version of the one on the data partition, but which 8624 // granted a new system permission that it didn't have 8625 // before. In this case we do want to allow the app to 8626 // now get the new permission if the ancestral apk is 8627 // privileged to get it. 8628 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8629 for (int j=0; 8630 j<sysPs.pkg.requestedPermissions.size(); j++) { 8631 if (perm.equals( 8632 sysPs.pkg.requestedPermissions.get(j))) { 8633 allowed = true; 8634 break; 8635 } 8636 } 8637 } 8638 } 8639 } else { 8640 allowed = isPrivilegedApp(pkg); 8641 } 8642 } 8643 } 8644 if (!allowed) { 8645 if (!allowed && (bp.protectionLevel 8646 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8647 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8648 // If this was a previously normal/dangerous permission that got moved 8649 // to a system permission as part of the runtime permission redesign, then 8650 // we still want to blindly grant it to old apps. 8651 allowed = true; 8652 } 8653 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8654 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8655 // If this permission is to be granted to the system installer and 8656 // this app is an installer, then it gets the permission. 8657 allowed = true; 8658 } 8659 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8660 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8661 // If this permission is to be granted to the system verifier and 8662 // this app is a verifier, then it gets the permission. 8663 allowed = true; 8664 } 8665 if (!allowed && (bp.protectionLevel 8666 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8667 && isSystemApp(pkg)) { 8668 // Any pre-installed system app is allowed to get this permission. 8669 allowed = true; 8670 } 8671 if (!allowed && (bp.protectionLevel 8672 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8673 // For development permissions, a development permission 8674 // is granted only if it was already granted. 8675 allowed = origPermissions.hasInstallPermission(perm); 8676 } 8677 } 8678 return allowed; 8679 } 8680 8681 final class ActivityIntentResolver 8682 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8683 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8684 boolean defaultOnly, int userId) { 8685 if (!sUserManager.exists(userId)) return null; 8686 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8687 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8688 } 8689 8690 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8691 int userId) { 8692 if (!sUserManager.exists(userId)) return null; 8693 mFlags = flags; 8694 return super.queryIntent(intent, resolvedType, 8695 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8696 } 8697 8698 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8699 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8700 if (!sUserManager.exists(userId)) return null; 8701 if (packageActivities == null) { 8702 return null; 8703 } 8704 mFlags = flags; 8705 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8706 final int N = packageActivities.size(); 8707 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8708 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8709 8710 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8711 for (int i = 0; i < N; ++i) { 8712 intentFilters = packageActivities.get(i).intents; 8713 if (intentFilters != null && intentFilters.size() > 0) { 8714 PackageParser.ActivityIntentInfo[] array = 8715 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8716 intentFilters.toArray(array); 8717 listCut.add(array); 8718 } 8719 } 8720 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8721 } 8722 8723 public final void addActivity(PackageParser.Activity a, String type) { 8724 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8725 mActivities.put(a.getComponentName(), a); 8726 if (DEBUG_SHOW_INFO) 8727 Log.v( 8728 TAG, " " + type + " " + 8729 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8730 if (DEBUG_SHOW_INFO) 8731 Log.v(TAG, " Class=" + a.info.name); 8732 final int NI = a.intents.size(); 8733 for (int j=0; j<NI; j++) { 8734 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8735 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8736 intent.setPriority(0); 8737 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8738 + a.className + " with priority > 0, forcing to 0"); 8739 } 8740 if (DEBUG_SHOW_INFO) { 8741 Log.v(TAG, " IntentFilter:"); 8742 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8743 } 8744 if (!intent.debugCheck()) { 8745 Log.w(TAG, "==> For Activity " + a.info.name); 8746 } 8747 addFilter(intent); 8748 } 8749 } 8750 8751 public final void removeActivity(PackageParser.Activity a, String type) { 8752 mActivities.remove(a.getComponentName()); 8753 if (DEBUG_SHOW_INFO) { 8754 Log.v(TAG, " " + type + " " 8755 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8756 : a.info.name) + ":"); 8757 Log.v(TAG, " Class=" + a.info.name); 8758 } 8759 final int NI = a.intents.size(); 8760 for (int j=0; j<NI; j++) { 8761 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8762 if (DEBUG_SHOW_INFO) { 8763 Log.v(TAG, " IntentFilter:"); 8764 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8765 } 8766 removeFilter(intent); 8767 } 8768 } 8769 8770 @Override 8771 protected boolean allowFilterResult( 8772 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8773 ActivityInfo filterAi = filter.activity.info; 8774 for (int i=dest.size()-1; i>=0; i--) { 8775 ActivityInfo destAi = dest.get(i).activityInfo; 8776 if (destAi.name == filterAi.name 8777 && destAi.packageName == filterAi.packageName) { 8778 return false; 8779 } 8780 } 8781 return true; 8782 } 8783 8784 @Override 8785 protected ActivityIntentInfo[] newArray(int size) { 8786 return new ActivityIntentInfo[size]; 8787 } 8788 8789 @Override 8790 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8791 if (!sUserManager.exists(userId)) return true; 8792 PackageParser.Package p = filter.activity.owner; 8793 if (p != null) { 8794 PackageSetting ps = (PackageSetting)p.mExtras; 8795 if (ps != null) { 8796 // System apps are never considered stopped for purposes of 8797 // filtering, because there may be no way for the user to 8798 // actually re-launch them. 8799 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8800 && ps.getStopped(userId); 8801 } 8802 } 8803 return false; 8804 } 8805 8806 @Override 8807 protected boolean isPackageForFilter(String packageName, 8808 PackageParser.ActivityIntentInfo info) { 8809 return packageName.equals(info.activity.owner.packageName); 8810 } 8811 8812 @Override 8813 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8814 int match, int userId) { 8815 if (!sUserManager.exists(userId)) return null; 8816 if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) { 8817 return null; 8818 } 8819 final PackageParser.Activity activity = info.activity; 8820 if (mSafeMode && (activity.info.applicationInfo.flags 8821 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8822 return null; 8823 } 8824 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8825 if (ps == null) { 8826 return null; 8827 } 8828 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8829 ps.readUserState(userId), userId); 8830 if (ai == null) { 8831 return null; 8832 } 8833 final ResolveInfo res = new ResolveInfo(); 8834 res.activityInfo = ai; 8835 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8836 res.filter = info; 8837 } 8838 if (info != null) { 8839 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8840 } 8841 res.priority = info.getPriority(); 8842 res.preferredOrder = activity.owner.mPreferredOrder; 8843 //System.out.println("Result: " + res.activityInfo.className + 8844 // " = " + res.priority); 8845 res.match = match; 8846 res.isDefault = info.hasDefault; 8847 res.labelRes = info.labelRes; 8848 res.nonLocalizedLabel = info.nonLocalizedLabel; 8849 if (userNeedsBadging(userId)) { 8850 res.noResourceId = true; 8851 } else { 8852 res.icon = info.icon; 8853 } 8854 res.iconResourceId = info.icon; 8855 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8856 return res; 8857 } 8858 8859 @Override 8860 protected void sortResults(List<ResolveInfo> results) { 8861 Collections.sort(results, mResolvePrioritySorter); 8862 } 8863 8864 @Override 8865 protected void dumpFilter(PrintWriter out, String prefix, 8866 PackageParser.ActivityIntentInfo filter) { 8867 out.print(prefix); out.print( 8868 Integer.toHexString(System.identityHashCode(filter.activity))); 8869 out.print(' '); 8870 filter.activity.printComponentShortName(out); 8871 out.print(" filter "); 8872 out.println(Integer.toHexString(System.identityHashCode(filter))); 8873 } 8874 8875 @Override 8876 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8877 return filter.activity; 8878 } 8879 8880 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8881 PackageParser.Activity activity = (PackageParser.Activity)label; 8882 out.print(prefix); out.print( 8883 Integer.toHexString(System.identityHashCode(activity))); 8884 out.print(' '); 8885 activity.printComponentShortName(out); 8886 if (count > 1) { 8887 out.print(" ("); out.print(count); out.print(" filters)"); 8888 } 8889 out.println(); 8890 } 8891 8892// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8893// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8894// final List<ResolveInfo> retList = Lists.newArrayList(); 8895// while (i.hasNext()) { 8896// final ResolveInfo resolveInfo = i.next(); 8897// if (isEnabledLP(resolveInfo.activityInfo)) { 8898// retList.add(resolveInfo); 8899// } 8900// } 8901// return retList; 8902// } 8903 8904 // Keys are String (activity class name), values are Activity. 8905 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8906 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8907 private int mFlags; 8908 } 8909 8910 private final class ServiceIntentResolver 8911 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8912 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8913 boolean defaultOnly, int userId) { 8914 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8915 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8916 } 8917 8918 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8919 int userId) { 8920 if (!sUserManager.exists(userId)) return null; 8921 mFlags = flags; 8922 return super.queryIntent(intent, resolvedType, 8923 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8924 } 8925 8926 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8927 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8928 if (!sUserManager.exists(userId)) return null; 8929 if (packageServices == null) { 8930 return null; 8931 } 8932 mFlags = flags; 8933 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8934 final int N = packageServices.size(); 8935 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8936 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8937 8938 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8939 for (int i = 0; i < N; ++i) { 8940 intentFilters = packageServices.get(i).intents; 8941 if (intentFilters != null && intentFilters.size() > 0) { 8942 PackageParser.ServiceIntentInfo[] array = 8943 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8944 intentFilters.toArray(array); 8945 listCut.add(array); 8946 } 8947 } 8948 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8949 } 8950 8951 public final void addService(PackageParser.Service s) { 8952 mServices.put(s.getComponentName(), s); 8953 if (DEBUG_SHOW_INFO) { 8954 Log.v(TAG, " " 8955 + (s.info.nonLocalizedLabel != null 8956 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8957 Log.v(TAG, " Class=" + s.info.name); 8958 } 8959 final int NI = s.intents.size(); 8960 int j; 8961 for (j=0; j<NI; j++) { 8962 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8963 if (DEBUG_SHOW_INFO) { 8964 Log.v(TAG, " IntentFilter:"); 8965 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8966 } 8967 if (!intent.debugCheck()) { 8968 Log.w(TAG, "==> For Service " + s.info.name); 8969 } 8970 addFilter(intent); 8971 } 8972 } 8973 8974 public final void removeService(PackageParser.Service s) { 8975 mServices.remove(s.getComponentName()); 8976 if (DEBUG_SHOW_INFO) { 8977 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8978 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8979 Log.v(TAG, " Class=" + s.info.name); 8980 } 8981 final int NI = s.intents.size(); 8982 int j; 8983 for (j=0; j<NI; j++) { 8984 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8985 if (DEBUG_SHOW_INFO) { 8986 Log.v(TAG, " IntentFilter:"); 8987 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8988 } 8989 removeFilter(intent); 8990 } 8991 } 8992 8993 @Override 8994 protected boolean allowFilterResult( 8995 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8996 ServiceInfo filterSi = filter.service.info; 8997 for (int i=dest.size()-1; i>=0; i--) { 8998 ServiceInfo destAi = dest.get(i).serviceInfo; 8999 if (destAi.name == filterSi.name 9000 && destAi.packageName == filterSi.packageName) { 9001 return false; 9002 } 9003 } 9004 return true; 9005 } 9006 9007 @Override 9008 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9009 return new PackageParser.ServiceIntentInfo[size]; 9010 } 9011 9012 @Override 9013 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9014 if (!sUserManager.exists(userId)) return true; 9015 PackageParser.Package p = filter.service.owner; 9016 if (p != null) { 9017 PackageSetting ps = (PackageSetting)p.mExtras; 9018 if (ps != null) { 9019 // System apps are never considered stopped for purposes of 9020 // filtering, because there may be no way for the user to 9021 // actually re-launch them. 9022 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9023 && ps.getStopped(userId); 9024 } 9025 } 9026 return false; 9027 } 9028 9029 @Override 9030 protected boolean isPackageForFilter(String packageName, 9031 PackageParser.ServiceIntentInfo info) { 9032 return packageName.equals(info.service.owner.packageName); 9033 } 9034 9035 @Override 9036 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9037 int match, int userId) { 9038 if (!sUserManager.exists(userId)) return null; 9039 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9040 if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) { 9041 return null; 9042 } 9043 final PackageParser.Service service = info.service; 9044 if (mSafeMode && (service.info.applicationInfo.flags 9045 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9046 return null; 9047 } 9048 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9049 if (ps == null) { 9050 return null; 9051 } 9052 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9053 ps.readUserState(userId), userId); 9054 if (si == null) { 9055 return null; 9056 } 9057 final ResolveInfo res = new ResolveInfo(); 9058 res.serviceInfo = si; 9059 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9060 res.filter = filter; 9061 } 9062 res.priority = info.getPriority(); 9063 res.preferredOrder = service.owner.mPreferredOrder; 9064 res.match = match; 9065 res.isDefault = info.hasDefault; 9066 res.labelRes = info.labelRes; 9067 res.nonLocalizedLabel = info.nonLocalizedLabel; 9068 res.icon = info.icon; 9069 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9070 return res; 9071 } 9072 9073 @Override 9074 protected void sortResults(List<ResolveInfo> results) { 9075 Collections.sort(results, mResolvePrioritySorter); 9076 } 9077 9078 @Override 9079 protected void dumpFilter(PrintWriter out, String prefix, 9080 PackageParser.ServiceIntentInfo filter) { 9081 out.print(prefix); out.print( 9082 Integer.toHexString(System.identityHashCode(filter.service))); 9083 out.print(' '); 9084 filter.service.printComponentShortName(out); 9085 out.print(" filter "); 9086 out.println(Integer.toHexString(System.identityHashCode(filter))); 9087 } 9088 9089 @Override 9090 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9091 return filter.service; 9092 } 9093 9094 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9095 PackageParser.Service service = (PackageParser.Service)label; 9096 out.print(prefix); out.print( 9097 Integer.toHexString(System.identityHashCode(service))); 9098 out.print(' '); 9099 service.printComponentShortName(out); 9100 if (count > 1) { 9101 out.print(" ("); out.print(count); out.print(" filters)"); 9102 } 9103 out.println(); 9104 } 9105 9106// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9107// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9108// final List<ResolveInfo> retList = Lists.newArrayList(); 9109// while (i.hasNext()) { 9110// final ResolveInfo resolveInfo = (ResolveInfo) i; 9111// if (isEnabledLP(resolveInfo.serviceInfo)) { 9112// retList.add(resolveInfo); 9113// } 9114// } 9115// return retList; 9116// } 9117 9118 // Keys are String (activity class name), values are Activity. 9119 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9120 = new ArrayMap<ComponentName, PackageParser.Service>(); 9121 private int mFlags; 9122 }; 9123 9124 private final class ProviderIntentResolver 9125 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9126 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9127 boolean defaultOnly, int userId) { 9128 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9129 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9130 } 9131 9132 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9133 int userId) { 9134 if (!sUserManager.exists(userId)) 9135 return null; 9136 mFlags = flags; 9137 return super.queryIntent(intent, resolvedType, 9138 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9139 } 9140 9141 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9142 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9143 if (!sUserManager.exists(userId)) 9144 return null; 9145 if (packageProviders == null) { 9146 return null; 9147 } 9148 mFlags = flags; 9149 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9150 final int N = packageProviders.size(); 9151 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9152 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9153 9154 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9155 for (int i = 0; i < N; ++i) { 9156 intentFilters = packageProviders.get(i).intents; 9157 if (intentFilters != null && intentFilters.size() > 0) { 9158 PackageParser.ProviderIntentInfo[] array = 9159 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9160 intentFilters.toArray(array); 9161 listCut.add(array); 9162 } 9163 } 9164 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9165 } 9166 9167 public final void addProvider(PackageParser.Provider p) { 9168 if (mProviders.containsKey(p.getComponentName())) { 9169 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9170 return; 9171 } 9172 9173 mProviders.put(p.getComponentName(), p); 9174 if (DEBUG_SHOW_INFO) { 9175 Log.v(TAG, " " 9176 + (p.info.nonLocalizedLabel != null 9177 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9178 Log.v(TAG, " Class=" + p.info.name); 9179 } 9180 final int NI = p.intents.size(); 9181 int j; 9182 for (j = 0; j < NI; j++) { 9183 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9184 if (DEBUG_SHOW_INFO) { 9185 Log.v(TAG, " IntentFilter:"); 9186 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9187 } 9188 if (!intent.debugCheck()) { 9189 Log.w(TAG, "==> For Provider " + p.info.name); 9190 } 9191 addFilter(intent); 9192 } 9193 } 9194 9195 public final void removeProvider(PackageParser.Provider p) { 9196 mProviders.remove(p.getComponentName()); 9197 if (DEBUG_SHOW_INFO) { 9198 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9199 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9200 Log.v(TAG, " Class=" + p.info.name); 9201 } 9202 final int NI = p.intents.size(); 9203 int j; 9204 for (j = 0; j < NI; j++) { 9205 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9206 if (DEBUG_SHOW_INFO) { 9207 Log.v(TAG, " IntentFilter:"); 9208 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9209 } 9210 removeFilter(intent); 9211 } 9212 } 9213 9214 @Override 9215 protected boolean allowFilterResult( 9216 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9217 ProviderInfo filterPi = filter.provider.info; 9218 for (int i = dest.size() - 1; i >= 0; i--) { 9219 ProviderInfo destPi = dest.get(i).providerInfo; 9220 if (destPi.name == filterPi.name 9221 && destPi.packageName == filterPi.packageName) { 9222 return false; 9223 } 9224 } 9225 return true; 9226 } 9227 9228 @Override 9229 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9230 return new PackageParser.ProviderIntentInfo[size]; 9231 } 9232 9233 @Override 9234 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9235 if (!sUserManager.exists(userId)) 9236 return true; 9237 PackageParser.Package p = filter.provider.owner; 9238 if (p != null) { 9239 PackageSetting ps = (PackageSetting) p.mExtras; 9240 if (ps != null) { 9241 // System apps are never considered stopped for purposes of 9242 // filtering, because there may be no way for the user to 9243 // actually re-launch them. 9244 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9245 && ps.getStopped(userId); 9246 } 9247 } 9248 return false; 9249 } 9250 9251 @Override 9252 protected boolean isPackageForFilter(String packageName, 9253 PackageParser.ProviderIntentInfo info) { 9254 return packageName.equals(info.provider.owner.packageName); 9255 } 9256 9257 @Override 9258 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9259 int match, int userId) { 9260 if (!sUserManager.exists(userId)) 9261 return null; 9262 final PackageParser.ProviderIntentInfo info = filter; 9263 if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) { 9264 return null; 9265 } 9266 final PackageParser.Provider provider = info.provider; 9267 if (mSafeMode && (provider.info.applicationInfo.flags 9268 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9269 return null; 9270 } 9271 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9272 if (ps == null) { 9273 return null; 9274 } 9275 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9276 ps.readUserState(userId), userId); 9277 if (pi == null) { 9278 return null; 9279 } 9280 final ResolveInfo res = new ResolveInfo(); 9281 res.providerInfo = pi; 9282 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9283 res.filter = filter; 9284 } 9285 res.priority = info.getPriority(); 9286 res.preferredOrder = provider.owner.mPreferredOrder; 9287 res.match = match; 9288 res.isDefault = info.hasDefault; 9289 res.labelRes = info.labelRes; 9290 res.nonLocalizedLabel = info.nonLocalizedLabel; 9291 res.icon = info.icon; 9292 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9293 return res; 9294 } 9295 9296 @Override 9297 protected void sortResults(List<ResolveInfo> results) { 9298 Collections.sort(results, mResolvePrioritySorter); 9299 } 9300 9301 @Override 9302 protected void dumpFilter(PrintWriter out, String prefix, 9303 PackageParser.ProviderIntentInfo filter) { 9304 out.print(prefix); 9305 out.print( 9306 Integer.toHexString(System.identityHashCode(filter.provider))); 9307 out.print(' '); 9308 filter.provider.printComponentShortName(out); 9309 out.print(" filter "); 9310 out.println(Integer.toHexString(System.identityHashCode(filter))); 9311 } 9312 9313 @Override 9314 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9315 return filter.provider; 9316 } 9317 9318 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9319 PackageParser.Provider provider = (PackageParser.Provider)label; 9320 out.print(prefix); out.print( 9321 Integer.toHexString(System.identityHashCode(provider))); 9322 out.print(' '); 9323 provider.printComponentShortName(out); 9324 if (count > 1) { 9325 out.print(" ("); out.print(count); out.print(" filters)"); 9326 } 9327 out.println(); 9328 } 9329 9330 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9331 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9332 private int mFlags; 9333 }; 9334 9335 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9336 new Comparator<ResolveInfo>() { 9337 public int compare(ResolveInfo r1, ResolveInfo r2) { 9338 int v1 = r1.priority; 9339 int v2 = r2.priority; 9340 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9341 if (v1 != v2) { 9342 return (v1 > v2) ? -1 : 1; 9343 } 9344 v1 = r1.preferredOrder; 9345 v2 = r2.preferredOrder; 9346 if (v1 != v2) { 9347 return (v1 > v2) ? -1 : 1; 9348 } 9349 if (r1.isDefault != r2.isDefault) { 9350 return r1.isDefault ? -1 : 1; 9351 } 9352 v1 = r1.match; 9353 v2 = r2.match; 9354 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9355 if (v1 != v2) { 9356 return (v1 > v2) ? -1 : 1; 9357 } 9358 if (r1.system != r2.system) { 9359 return r1.system ? -1 : 1; 9360 } 9361 return 0; 9362 } 9363 }; 9364 9365 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9366 new Comparator<ProviderInfo>() { 9367 public int compare(ProviderInfo p1, ProviderInfo p2) { 9368 final int v1 = p1.initOrder; 9369 final int v2 = p2.initOrder; 9370 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9371 } 9372 }; 9373 9374 final void sendPackageBroadcast(final String action, final String pkg, 9375 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9376 final int[] userIds) { 9377 mHandler.post(new Runnable() { 9378 @Override 9379 public void run() { 9380 try { 9381 final IActivityManager am = ActivityManagerNative.getDefault(); 9382 if (am == null) return; 9383 final int[] resolvedUserIds; 9384 if (userIds == null) { 9385 resolvedUserIds = am.getRunningUserIds(); 9386 } else { 9387 resolvedUserIds = userIds; 9388 } 9389 for (int id : resolvedUserIds) { 9390 final Intent intent = new Intent(action, 9391 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9392 if (extras != null) { 9393 intent.putExtras(extras); 9394 } 9395 if (targetPkg != null) { 9396 intent.setPackage(targetPkg); 9397 } 9398 // Modify the UID when posting to other users 9399 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9400 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9401 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9402 intent.putExtra(Intent.EXTRA_UID, uid); 9403 } 9404 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9405 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9406 if (DEBUG_BROADCASTS) { 9407 RuntimeException here = new RuntimeException("here"); 9408 here.fillInStackTrace(); 9409 Slog.d(TAG, "Sending to user " + id + ": " 9410 + intent.toShortString(false, true, false, false) 9411 + " " + intent.getExtras(), here); 9412 } 9413 am.broadcastIntent(null, intent, null, finishedReceiver, 9414 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9415 null, finishedReceiver != null, false, id); 9416 } 9417 } catch (RemoteException ex) { 9418 } 9419 } 9420 }); 9421 } 9422 9423 /** 9424 * Check if the external storage media is available. This is true if there 9425 * is a mounted external storage medium or if the external storage is 9426 * emulated. 9427 */ 9428 private boolean isExternalMediaAvailable() { 9429 return mMediaMounted || Environment.isExternalStorageEmulated(); 9430 } 9431 9432 @Override 9433 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9434 // writer 9435 synchronized (mPackages) { 9436 if (!isExternalMediaAvailable()) { 9437 // If the external storage is no longer mounted at this point, 9438 // the caller may not have been able to delete all of this 9439 // packages files and can not delete any more. Bail. 9440 return null; 9441 } 9442 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9443 if (lastPackage != null) { 9444 pkgs.remove(lastPackage); 9445 } 9446 if (pkgs.size() > 0) { 9447 return pkgs.get(0); 9448 } 9449 } 9450 return null; 9451 } 9452 9453 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9454 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9455 userId, andCode ? 1 : 0, packageName); 9456 if (mSystemReady) { 9457 msg.sendToTarget(); 9458 } else { 9459 if (mPostSystemReadyMessages == null) { 9460 mPostSystemReadyMessages = new ArrayList<>(); 9461 } 9462 mPostSystemReadyMessages.add(msg); 9463 } 9464 } 9465 9466 void startCleaningPackages() { 9467 // reader 9468 synchronized (mPackages) { 9469 if (!isExternalMediaAvailable()) { 9470 return; 9471 } 9472 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9473 return; 9474 } 9475 } 9476 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9477 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9478 IActivityManager am = ActivityManagerNative.getDefault(); 9479 if (am != null) { 9480 try { 9481 am.startService(null, intent, null, mContext.getOpPackageName(), 9482 UserHandle.USER_SYSTEM); 9483 } catch (RemoteException e) { 9484 } 9485 } 9486 } 9487 9488 @Override 9489 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9490 int installFlags, String installerPackageName, VerificationParams verificationParams, 9491 String packageAbiOverride) { 9492 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9493 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9494 } 9495 9496 @Override 9497 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9498 int installFlags, String installerPackageName, VerificationParams verificationParams, 9499 String packageAbiOverride, int userId) { 9500 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9501 9502 final int callingUid = Binder.getCallingUid(); 9503 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9504 9505 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9506 try { 9507 if (observer != null) { 9508 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9509 } 9510 } catch (RemoteException re) { 9511 } 9512 return; 9513 } 9514 9515 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9516 installFlags |= PackageManager.INSTALL_FROM_ADB; 9517 9518 } else { 9519 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9520 // about installerPackageName. 9521 9522 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9523 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9524 } 9525 9526 UserHandle user; 9527 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9528 user = UserHandle.ALL; 9529 } else { 9530 user = new UserHandle(userId); 9531 } 9532 9533 // Only system components can circumvent runtime permissions when installing. 9534 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9535 && mContext.checkCallingOrSelfPermission(Manifest.permission 9536 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9537 throw new SecurityException("You need the " 9538 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9539 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9540 } 9541 9542 verificationParams.setInstallerUid(callingUid); 9543 9544 final File originFile = new File(originPath); 9545 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9546 9547 final Message msg = mHandler.obtainMessage(INIT_COPY); 9548 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9549 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9550 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9551 msg.obj = params; 9552 9553 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9554 System.identityHashCode(msg.obj)); 9555 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9556 System.identityHashCode(msg.obj)); 9557 9558 mHandler.sendMessage(msg); 9559 } 9560 9561 void installStage(String packageName, File stagedDir, String stagedCid, 9562 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9563 String installerPackageName, int installerUid, UserHandle user) { 9564 final VerificationParams verifParams = new VerificationParams( 9565 null, sessionParams.originatingUri, sessionParams.referrerUri, 9566 sessionParams.originatingUid, null); 9567 verifParams.setInstallerUid(installerUid); 9568 9569 final OriginInfo origin; 9570 if (stagedDir != null) { 9571 origin = OriginInfo.fromStagedFile(stagedDir); 9572 } else { 9573 origin = OriginInfo.fromStagedContainer(stagedCid); 9574 } 9575 9576 final Message msg = mHandler.obtainMessage(INIT_COPY); 9577 final InstallParams params = new InstallParams(origin, null, observer, 9578 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9579 verifParams, user, sessionParams.abiOverride, 9580 sessionParams.grantedRuntimePermissions); 9581 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9582 msg.obj = params; 9583 9584 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9585 System.identityHashCode(msg.obj)); 9586 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9587 System.identityHashCode(msg.obj)); 9588 9589 mHandler.sendMessage(msg); 9590 } 9591 9592 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9593 Bundle extras = new Bundle(1); 9594 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9595 9596 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9597 packageName, extras, null, null, new int[] {userId}); 9598 try { 9599 IActivityManager am = ActivityManagerNative.getDefault(); 9600 final boolean isSystem = 9601 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9602 if (isSystem && am.isUserRunning(userId, 0)) { 9603 // The just-installed/enabled app is bundled on the system, so presumed 9604 // to be able to run automatically without needing an explicit launch. 9605 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9606 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9607 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9608 .setPackage(packageName); 9609 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9610 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9611 } 9612 } catch (RemoteException e) { 9613 // shouldn't happen 9614 Slog.w(TAG, "Unable to bootstrap installed package", e); 9615 } 9616 } 9617 9618 @Override 9619 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9620 int userId) { 9621 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9622 PackageSetting pkgSetting; 9623 final int uid = Binder.getCallingUid(); 9624 enforceCrossUserPermission(uid, userId, true, true, 9625 "setApplicationHiddenSetting for user " + userId); 9626 9627 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9628 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9629 return false; 9630 } 9631 9632 long callingId = Binder.clearCallingIdentity(); 9633 try { 9634 boolean sendAdded = false; 9635 boolean sendRemoved = false; 9636 // writer 9637 synchronized (mPackages) { 9638 pkgSetting = mSettings.mPackages.get(packageName); 9639 if (pkgSetting == null) { 9640 return false; 9641 } 9642 if (pkgSetting.getHidden(userId) != hidden) { 9643 pkgSetting.setHidden(hidden, userId); 9644 mSettings.writePackageRestrictionsLPr(userId); 9645 if (hidden) { 9646 sendRemoved = true; 9647 } else { 9648 sendAdded = true; 9649 } 9650 } 9651 } 9652 if (sendAdded) { 9653 sendPackageAddedForUser(packageName, pkgSetting, userId); 9654 return true; 9655 } 9656 if (sendRemoved) { 9657 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9658 "hiding pkg"); 9659 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9660 return true; 9661 } 9662 } finally { 9663 Binder.restoreCallingIdentity(callingId); 9664 } 9665 return false; 9666 } 9667 9668 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9669 int userId) { 9670 final PackageRemovedInfo info = new PackageRemovedInfo(); 9671 info.removedPackage = packageName; 9672 info.removedUsers = new int[] {userId}; 9673 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9674 info.sendBroadcast(false, false, false); 9675 } 9676 9677 /** 9678 * Returns true if application is not found or there was an error. Otherwise it returns 9679 * the hidden state of the package for the given user. 9680 */ 9681 @Override 9682 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9683 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9684 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9685 false, "getApplicationHidden for user " + userId); 9686 PackageSetting pkgSetting; 9687 long callingId = Binder.clearCallingIdentity(); 9688 try { 9689 // writer 9690 synchronized (mPackages) { 9691 pkgSetting = mSettings.mPackages.get(packageName); 9692 if (pkgSetting == null) { 9693 return true; 9694 } 9695 return pkgSetting.getHidden(userId); 9696 } 9697 } finally { 9698 Binder.restoreCallingIdentity(callingId); 9699 } 9700 } 9701 9702 /** 9703 * @hide 9704 */ 9705 @Override 9706 public int installExistingPackageAsUser(String packageName, int userId) { 9707 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9708 null); 9709 PackageSetting pkgSetting; 9710 final int uid = Binder.getCallingUid(); 9711 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9712 + userId); 9713 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9714 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9715 } 9716 9717 long callingId = Binder.clearCallingIdentity(); 9718 try { 9719 boolean sendAdded = false; 9720 9721 // writer 9722 synchronized (mPackages) { 9723 pkgSetting = mSettings.mPackages.get(packageName); 9724 if (pkgSetting == null) { 9725 return PackageManager.INSTALL_FAILED_INVALID_URI; 9726 } 9727 if (!pkgSetting.getInstalled(userId)) { 9728 pkgSetting.setInstalled(true, userId); 9729 pkgSetting.setHidden(false, userId); 9730 mSettings.writePackageRestrictionsLPr(userId); 9731 sendAdded = true; 9732 } 9733 } 9734 9735 if (sendAdded) { 9736 sendPackageAddedForUser(packageName, pkgSetting, userId); 9737 } 9738 } finally { 9739 Binder.restoreCallingIdentity(callingId); 9740 } 9741 9742 return PackageManager.INSTALL_SUCCEEDED; 9743 } 9744 9745 boolean isUserRestricted(int userId, String restrictionKey) { 9746 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9747 if (restrictions.getBoolean(restrictionKey, false)) { 9748 Log.w(TAG, "User is restricted: " + restrictionKey); 9749 return true; 9750 } 9751 return false; 9752 } 9753 9754 @Override 9755 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9756 mContext.enforceCallingOrSelfPermission( 9757 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9758 "Only package verification agents can verify applications"); 9759 9760 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9761 final PackageVerificationResponse response = new PackageVerificationResponse( 9762 verificationCode, Binder.getCallingUid()); 9763 msg.arg1 = id; 9764 msg.obj = response; 9765 mHandler.sendMessage(msg); 9766 } 9767 9768 @Override 9769 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9770 long millisecondsToDelay) { 9771 mContext.enforceCallingOrSelfPermission( 9772 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9773 "Only package verification agents can extend verification timeouts"); 9774 9775 final PackageVerificationState state = mPendingVerification.get(id); 9776 final PackageVerificationResponse response = new PackageVerificationResponse( 9777 verificationCodeAtTimeout, Binder.getCallingUid()); 9778 9779 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9780 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9781 } 9782 if (millisecondsToDelay < 0) { 9783 millisecondsToDelay = 0; 9784 } 9785 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9786 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9787 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9788 } 9789 9790 if ((state != null) && !state.timeoutExtended()) { 9791 state.extendTimeout(); 9792 9793 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9794 msg.arg1 = id; 9795 msg.obj = response; 9796 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9797 } 9798 } 9799 9800 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9801 int verificationCode, UserHandle user) { 9802 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9803 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9804 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9805 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9806 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9807 9808 mContext.sendBroadcastAsUser(intent, user, 9809 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9810 } 9811 9812 private ComponentName matchComponentForVerifier(String packageName, 9813 List<ResolveInfo> receivers) { 9814 ActivityInfo targetReceiver = null; 9815 9816 final int NR = receivers.size(); 9817 for (int i = 0; i < NR; i++) { 9818 final ResolveInfo info = receivers.get(i); 9819 if (info.activityInfo == null) { 9820 continue; 9821 } 9822 9823 if (packageName.equals(info.activityInfo.packageName)) { 9824 targetReceiver = info.activityInfo; 9825 break; 9826 } 9827 } 9828 9829 if (targetReceiver == null) { 9830 return null; 9831 } 9832 9833 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9834 } 9835 9836 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9837 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9838 if (pkgInfo.verifiers.length == 0) { 9839 return null; 9840 } 9841 9842 final int N = pkgInfo.verifiers.length; 9843 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9844 for (int i = 0; i < N; i++) { 9845 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9846 9847 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9848 receivers); 9849 if (comp == null) { 9850 continue; 9851 } 9852 9853 final int verifierUid = getUidForVerifier(verifierInfo); 9854 if (verifierUid == -1) { 9855 continue; 9856 } 9857 9858 if (DEBUG_VERIFY) { 9859 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9860 + " with the correct signature"); 9861 } 9862 sufficientVerifiers.add(comp); 9863 verificationState.addSufficientVerifier(verifierUid); 9864 } 9865 9866 return sufficientVerifiers; 9867 } 9868 9869 private int getUidForVerifier(VerifierInfo verifierInfo) { 9870 synchronized (mPackages) { 9871 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9872 if (pkg == null) { 9873 return -1; 9874 } else if (pkg.mSignatures.length != 1) { 9875 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9876 + " has more than one signature; ignoring"); 9877 return -1; 9878 } 9879 9880 /* 9881 * If the public key of the package's signature does not match 9882 * our expected public key, then this is a different package and 9883 * we should skip. 9884 */ 9885 9886 final byte[] expectedPublicKey; 9887 try { 9888 final Signature verifierSig = pkg.mSignatures[0]; 9889 final PublicKey publicKey = verifierSig.getPublicKey(); 9890 expectedPublicKey = publicKey.getEncoded(); 9891 } catch (CertificateException e) { 9892 return -1; 9893 } 9894 9895 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9896 9897 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9898 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9899 + " does not have the expected public key; ignoring"); 9900 return -1; 9901 } 9902 9903 return pkg.applicationInfo.uid; 9904 } 9905 } 9906 9907 @Override 9908 public void finishPackageInstall(int token) { 9909 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9910 9911 if (DEBUG_INSTALL) { 9912 Slog.v(TAG, "BM finishing package install for " + token); 9913 } 9914 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 9915 9916 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9917 mHandler.sendMessage(msg); 9918 } 9919 9920 /** 9921 * Get the verification agent timeout. 9922 * 9923 * @return verification timeout in milliseconds 9924 */ 9925 private long getVerificationTimeout() { 9926 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9927 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9928 DEFAULT_VERIFICATION_TIMEOUT); 9929 } 9930 9931 /** 9932 * Get the default verification agent response code. 9933 * 9934 * @return default verification response code 9935 */ 9936 private int getDefaultVerificationResponse() { 9937 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9938 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9939 DEFAULT_VERIFICATION_RESPONSE); 9940 } 9941 9942 /** 9943 * Check whether or not package verification has been enabled. 9944 * 9945 * @return true if verification should be performed 9946 */ 9947 private boolean isVerificationEnabled(int userId, int installFlags) { 9948 if (!DEFAULT_VERIFY_ENABLE) { 9949 return false; 9950 } 9951 // TODO: fix b/25118622; don't bypass verification 9952 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 9953 return false; 9954 } 9955 9956 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9957 9958 // Check if installing from ADB 9959 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9960 // Do not run verification in a test harness environment 9961 if (ActivityManager.isRunningInTestHarness()) { 9962 return false; 9963 } 9964 if (ensureVerifyAppsEnabled) { 9965 return true; 9966 } 9967 // Check if the developer does not want package verification for ADB installs 9968 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9969 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9970 return false; 9971 } 9972 } 9973 9974 if (ensureVerifyAppsEnabled) { 9975 return true; 9976 } 9977 9978 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9979 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9980 } 9981 9982 @Override 9983 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9984 throws RemoteException { 9985 mContext.enforceCallingOrSelfPermission( 9986 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9987 "Only intentfilter verification agents can verify applications"); 9988 9989 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9990 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9991 Binder.getCallingUid(), verificationCode, failedDomains); 9992 msg.arg1 = id; 9993 msg.obj = response; 9994 mHandler.sendMessage(msg); 9995 } 9996 9997 @Override 9998 public int getIntentVerificationStatus(String packageName, int userId) { 9999 synchronized (mPackages) { 10000 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10001 } 10002 } 10003 10004 @Override 10005 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10006 mContext.enforceCallingOrSelfPermission( 10007 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10008 10009 boolean result = false; 10010 synchronized (mPackages) { 10011 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10012 } 10013 if (result) { 10014 scheduleWritePackageRestrictionsLocked(userId); 10015 } 10016 return result; 10017 } 10018 10019 @Override 10020 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10021 synchronized (mPackages) { 10022 return mSettings.getIntentFilterVerificationsLPr(packageName); 10023 } 10024 } 10025 10026 @Override 10027 public List<IntentFilter> getAllIntentFilters(String packageName) { 10028 if (TextUtils.isEmpty(packageName)) { 10029 return Collections.<IntentFilter>emptyList(); 10030 } 10031 synchronized (mPackages) { 10032 PackageParser.Package pkg = mPackages.get(packageName); 10033 if (pkg == null || pkg.activities == null) { 10034 return Collections.<IntentFilter>emptyList(); 10035 } 10036 final int count = pkg.activities.size(); 10037 ArrayList<IntentFilter> result = new ArrayList<>(); 10038 for (int n=0; n<count; n++) { 10039 PackageParser.Activity activity = pkg.activities.get(n); 10040 if (activity.intents != null || activity.intents.size() > 0) { 10041 result.addAll(activity.intents); 10042 } 10043 } 10044 return result; 10045 } 10046 } 10047 10048 @Override 10049 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10050 mContext.enforceCallingOrSelfPermission( 10051 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10052 10053 synchronized (mPackages) { 10054 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10055 if (packageName != null) { 10056 result |= updateIntentVerificationStatus(packageName, 10057 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10058 userId); 10059 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10060 packageName, userId); 10061 } 10062 return result; 10063 } 10064 } 10065 10066 @Override 10067 public String getDefaultBrowserPackageName(int userId) { 10068 synchronized (mPackages) { 10069 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10070 } 10071 } 10072 10073 /** 10074 * Get the "allow unknown sources" setting. 10075 * 10076 * @return the current "allow unknown sources" setting 10077 */ 10078 private int getUnknownSourcesSettings() { 10079 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10080 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10081 -1); 10082 } 10083 10084 @Override 10085 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10086 final int uid = Binder.getCallingUid(); 10087 // writer 10088 synchronized (mPackages) { 10089 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10090 if (targetPackageSetting == null) { 10091 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10092 } 10093 10094 PackageSetting installerPackageSetting; 10095 if (installerPackageName != null) { 10096 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10097 if (installerPackageSetting == null) { 10098 throw new IllegalArgumentException("Unknown installer package: " 10099 + installerPackageName); 10100 } 10101 } else { 10102 installerPackageSetting = null; 10103 } 10104 10105 Signature[] callerSignature; 10106 Object obj = mSettings.getUserIdLPr(uid); 10107 if (obj != null) { 10108 if (obj instanceof SharedUserSetting) { 10109 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10110 } else if (obj instanceof PackageSetting) { 10111 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10112 } else { 10113 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10114 } 10115 } else { 10116 throw new SecurityException("Unknown calling uid " + uid); 10117 } 10118 10119 // Verify: can't set installerPackageName to a package that is 10120 // not signed with the same cert as the caller. 10121 if (installerPackageSetting != null) { 10122 if (compareSignatures(callerSignature, 10123 installerPackageSetting.signatures.mSignatures) 10124 != PackageManager.SIGNATURE_MATCH) { 10125 throw new SecurityException( 10126 "Caller does not have same cert as new installer package " 10127 + installerPackageName); 10128 } 10129 } 10130 10131 // Verify: if target already has an installer package, it must 10132 // be signed with the same cert as the caller. 10133 if (targetPackageSetting.installerPackageName != null) { 10134 PackageSetting setting = mSettings.mPackages.get( 10135 targetPackageSetting.installerPackageName); 10136 // If the currently set package isn't valid, then it's always 10137 // okay to change it. 10138 if (setting != null) { 10139 if (compareSignatures(callerSignature, 10140 setting.signatures.mSignatures) 10141 != PackageManager.SIGNATURE_MATCH) { 10142 throw new SecurityException( 10143 "Caller does not have same cert as old installer package " 10144 + targetPackageSetting.installerPackageName); 10145 } 10146 } 10147 } 10148 10149 // Okay! 10150 targetPackageSetting.installerPackageName = installerPackageName; 10151 scheduleWriteSettingsLocked(); 10152 } 10153 } 10154 10155 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10156 // Queue up an async operation since the package installation may take a little while. 10157 mHandler.post(new Runnable() { 10158 public void run() { 10159 mHandler.removeCallbacks(this); 10160 // Result object to be returned 10161 PackageInstalledInfo res = new PackageInstalledInfo(); 10162 res.returnCode = currentStatus; 10163 res.uid = -1; 10164 res.pkg = null; 10165 res.removedInfo = new PackageRemovedInfo(); 10166 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10167 args.doPreInstall(res.returnCode); 10168 synchronized (mInstallLock) { 10169 installPackageTracedLI(args, res); 10170 } 10171 args.doPostInstall(res.returnCode, res.uid); 10172 } 10173 10174 // A restore should be performed at this point if (a) the install 10175 // succeeded, (b) the operation is not an update, and (c) the new 10176 // package has not opted out of backup participation. 10177 final boolean update = res.removedInfo.removedPackage != null; 10178 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10179 boolean doRestore = !update 10180 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10181 10182 // Set up the post-install work request bookkeeping. This will be used 10183 // and cleaned up by the post-install event handling regardless of whether 10184 // there's a restore pass performed. Token values are >= 1. 10185 int token; 10186 if (mNextInstallToken < 0) mNextInstallToken = 1; 10187 token = mNextInstallToken++; 10188 10189 PostInstallData data = new PostInstallData(args, res); 10190 mRunningInstalls.put(token, data); 10191 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10192 10193 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10194 // Pass responsibility to the Backup Manager. It will perform a 10195 // restore if appropriate, then pass responsibility back to the 10196 // Package Manager to run the post-install observer callbacks 10197 // and broadcasts. 10198 IBackupManager bm = IBackupManager.Stub.asInterface( 10199 ServiceManager.getService(Context.BACKUP_SERVICE)); 10200 if (bm != null) { 10201 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10202 + " to BM for possible restore"); 10203 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10204 try { 10205 // TODO: http://b/22388012 10206 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10207 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10208 } else { 10209 doRestore = false; 10210 } 10211 } catch (RemoteException e) { 10212 // can't happen; the backup manager is local 10213 } catch (Exception e) { 10214 Slog.e(TAG, "Exception trying to enqueue restore", e); 10215 doRestore = false; 10216 } 10217 } else { 10218 Slog.e(TAG, "Backup Manager not found!"); 10219 doRestore = false; 10220 } 10221 } 10222 10223 if (!doRestore) { 10224 // No restore possible, or the Backup Manager was mysteriously not 10225 // available -- just fire the post-install work request directly. 10226 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10227 10228 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10229 10230 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10231 mHandler.sendMessage(msg); 10232 } 10233 } 10234 }); 10235 } 10236 10237 private abstract class HandlerParams { 10238 private static final int MAX_RETRIES = 4; 10239 10240 /** 10241 * Number of times startCopy() has been attempted and had a non-fatal 10242 * error. 10243 */ 10244 private int mRetries = 0; 10245 10246 /** User handle for the user requesting the information or installation. */ 10247 private final UserHandle mUser; 10248 String traceMethod; 10249 int traceCookie; 10250 10251 HandlerParams(UserHandle user) { 10252 mUser = user; 10253 } 10254 10255 UserHandle getUser() { 10256 return mUser; 10257 } 10258 10259 HandlerParams setTraceMethod(String traceMethod) { 10260 this.traceMethod = traceMethod; 10261 return this; 10262 } 10263 10264 HandlerParams setTraceCookie(int traceCookie) { 10265 this.traceCookie = traceCookie; 10266 return this; 10267 } 10268 10269 final boolean startCopy() { 10270 boolean res; 10271 try { 10272 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10273 10274 if (++mRetries > MAX_RETRIES) { 10275 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10276 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10277 handleServiceError(); 10278 return false; 10279 } else { 10280 handleStartCopy(); 10281 res = true; 10282 } 10283 } catch (RemoteException e) { 10284 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10285 mHandler.sendEmptyMessage(MCS_RECONNECT); 10286 res = false; 10287 } 10288 handleReturnCode(); 10289 return res; 10290 } 10291 10292 final void serviceError() { 10293 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10294 handleServiceError(); 10295 handleReturnCode(); 10296 } 10297 10298 abstract void handleStartCopy() throws RemoteException; 10299 abstract void handleServiceError(); 10300 abstract void handleReturnCode(); 10301 } 10302 10303 class MeasureParams extends HandlerParams { 10304 private final PackageStats mStats; 10305 private boolean mSuccess; 10306 10307 private final IPackageStatsObserver mObserver; 10308 10309 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10310 super(new UserHandle(stats.userHandle)); 10311 mObserver = observer; 10312 mStats = stats; 10313 } 10314 10315 @Override 10316 public String toString() { 10317 return "MeasureParams{" 10318 + Integer.toHexString(System.identityHashCode(this)) 10319 + " " + mStats.packageName + "}"; 10320 } 10321 10322 @Override 10323 void handleStartCopy() throws RemoteException { 10324 synchronized (mInstallLock) { 10325 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10326 } 10327 10328 if (mSuccess) { 10329 final boolean mounted; 10330 if (Environment.isExternalStorageEmulated()) { 10331 mounted = true; 10332 } else { 10333 final String status = Environment.getExternalStorageState(); 10334 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10335 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10336 } 10337 10338 if (mounted) { 10339 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10340 10341 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10342 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10343 10344 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10345 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10346 10347 // Always subtract cache size, since it's a subdirectory 10348 mStats.externalDataSize -= mStats.externalCacheSize; 10349 10350 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10351 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10352 10353 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10354 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10355 } 10356 } 10357 } 10358 10359 @Override 10360 void handleReturnCode() { 10361 if (mObserver != null) { 10362 try { 10363 mObserver.onGetStatsCompleted(mStats, mSuccess); 10364 } catch (RemoteException e) { 10365 Slog.i(TAG, "Observer no longer exists."); 10366 } 10367 } 10368 } 10369 10370 @Override 10371 void handleServiceError() { 10372 Slog.e(TAG, "Could not measure application " + mStats.packageName 10373 + " external storage"); 10374 } 10375 } 10376 10377 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10378 throws RemoteException { 10379 long result = 0; 10380 for (File path : paths) { 10381 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10382 } 10383 return result; 10384 } 10385 10386 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10387 for (File path : paths) { 10388 try { 10389 mcs.clearDirectory(path.getAbsolutePath()); 10390 } catch (RemoteException e) { 10391 } 10392 } 10393 } 10394 10395 static class OriginInfo { 10396 /** 10397 * Location where install is coming from, before it has been 10398 * copied/renamed into place. This could be a single monolithic APK 10399 * file, or a cluster directory. This location may be untrusted. 10400 */ 10401 final File file; 10402 final String cid; 10403 10404 /** 10405 * Flag indicating that {@link #file} or {@link #cid} has already been 10406 * staged, meaning downstream users don't need to defensively copy the 10407 * contents. 10408 */ 10409 final boolean staged; 10410 10411 /** 10412 * Flag indicating that {@link #file} or {@link #cid} is an already 10413 * installed app that is being moved. 10414 */ 10415 final boolean existing; 10416 10417 final String resolvedPath; 10418 final File resolvedFile; 10419 10420 static OriginInfo fromNothing() { 10421 return new OriginInfo(null, null, false, false); 10422 } 10423 10424 static OriginInfo fromUntrustedFile(File file) { 10425 return new OriginInfo(file, null, false, false); 10426 } 10427 10428 static OriginInfo fromExistingFile(File file) { 10429 return new OriginInfo(file, null, false, true); 10430 } 10431 10432 static OriginInfo fromStagedFile(File file) { 10433 return new OriginInfo(file, null, true, false); 10434 } 10435 10436 static OriginInfo fromStagedContainer(String cid) { 10437 return new OriginInfo(null, cid, true, false); 10438 } 10439 10440 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10441 this.file = file; 10442 this.cid = cid; 10443 this.staged = staged; 10444 this.existing = existing; 10445 10446 if (cid != null) { 10447 resolvedPath = PackageHelper.getSdDir(cid); 10448 resolvedFile = new File(resolvedPath); 10449 } else if (file != null) { 10450 resolvedPath = file.getAbsolutePath(); 10451 resolvedFile = file; 10452 } else { 10453 resolvedPath = null; 10454 resolvedFile = null; 10455 } 10456 } 10457 } 10458 10459 class MoveInfo { 10460 final int moveId; 10461 final String fromUuid; 10462 final String toUuid; 10463 final String packageName; 10464 final String dataAppName; 10465 final int appId; 10466 final String seinfo; 10467 10468 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10469 String dataAppName, int appId, String seinfo) { 10470 this.moveId = moveId; 10471 this.fromUuid = fromUuid; 10472 this.toUuid = toUuid; 10473 this.packageName = packageName; 10474 this.dataAppName = dataAppName; 10475 this.appId = appId; 10476 this.seinfo = seinfo; 10477 } 10478 } 10479 10480 class InstallParams extends HandlerParams { 10481 final OriginInfo origin; 10482 final MoveInfo move; 10483 final IPackageInstallObserver2 observer; 10484 int installFlags; 10485 final String installerPackageName; 10486 final String volumeUuid; 10487 final VerificationParams verificationParams; 10488 private InstallArgs mArgs; 10489 private int mRet; 10490 final String packageAbiOverride; 10491 final String[] grantedRuntimePermissions; 10492 10493 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10494 int installFlags, String installerPackageName, String volumeUuid, 10495 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10496 String[] grantedPermissions) { 10497 super(user); 10498 this.origin = origin; 10499 this.move = move; 10500 this.observer = observer; 10501 this.installFlags = installFlags; 10502 this.installerPackageName = installerPackageName; 10503 this.volumeUuid = volumeUuid; 10504 this.verificationParams = verificationParams; 10505 this.packageAbiOverride = packageAbiOverride; 10506 this.grantedRuntimePermissions = grantedPermissions; 10507 } 10508 10509 @Override 10510 public String toString() { 10511 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10512 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10513 } 10514 10515 public ManifestDigest getManifestDigest() { 10516 if (verificationParams == null) { 10517 return null; 10518 } 10519 return verificationParams.getManifestDigest(); 10520 } 10521 10522 private int installLocationPolicy(PackageInfoLite pkgLite) { 10523 String packageName = pkgLite.packageName; 10524 int installLocation = pkgLite.installLocation; 10525 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10526 // reader 10527 synchronized (mPackages) { 10528 PackageParser.Package pkg = mPackages.get(packageName); 10529 if (pkg != null) { 10530 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10531 // Check for downgrading. 10532 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10533 try { 10534 checkDowngrade(pkg, pkgLite); 10535 } catch (PackageManagerException e) { 10536 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10537 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10538 } 10539 } 10540 // Check for updated system application. 10541 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10542 if (onSd) { 10543 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10544 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10545 } 10546 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10547 } else { 10548 if (onSd) { 10549 // Install flag overrides everything. 10550 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10551 } 10552 // If current upgrade specifies particular preference 10553 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10554 // Application explicitly specified internal. 10555 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10556 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10557 // App explictly prefers external. Let policy decide 10558 } else { 10559 // Prefer previous location 10560 if (isExternal(pkg)) { 10561 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10562 } 10563 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10564 } 10565 } 10566 } else { 10567 // Invalid install. Return error code 10568 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10569 } 10570 } 10571 } 10572 // All the special cases have been taken care of. 10573 // Return result based on recommended install location. 10574 if (onSd) { 10575 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10576 } 10577 return pkgLite.recommendedInstallLocation; 10578 } 10579 10580 /* 10581 * Invoke remote method to get package information and install 10582 * location values. Override install location based on default 10583 * policy if needed and then create install arguments based 10584 * on the install location. 10585 */ 10586 public void handleStartCopy() throws RemoteException { 10587 int ret = PackageManager.INSTALL_SUCCEEDED; 10588 10589 // If we're already staged, we've firmly committed to an install location 10590 if (origin.staged) { 10591 if (origin.file != null) { 10592 installFlags |= PackageManager.INSTALL_INTERNAL; 10593 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10594 } else if (origin.cid != null) { 10595 installFlags |= PackageManager.INSTALL_EXTERNAL; 10596 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10597 } else { 10598 throw new IllegalStateException("Invalid stage location"); 10599 } 10600 } 10601 10602 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10603 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10604 PackageInfoLite pkgLite = null; 10605 10606 if (onInt && onSd) { 10607 // Check if both bits are set. 10608 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10609 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10610 } else { 10611 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10612 packageAbiOverride); 10613 10614 /* 10615 * If we have too little free space, try to free cache 10616 * before giving up. 10617 */ 10618 if (!origin.staged && pkgLite.recommendedInstallLocation 10619 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10620 // TODO: focus freeing disk space on the target device 10621 final StorageManager storage = StorageManager.from(mContext); 10622 final long lowThreshold = storage.getStorageLowBytes( 10623 Environment.getDataDirectory()); 10624 10625 final long sizeBytes = mContainerService.calculateInstalledSize( 10626 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10627 10628 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10629 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10630 installFlags, packageAbiOverride); 10631 } 10632 10633 /* 10634 * The cache free must have deleted the file we 10635 * downloaded to install. 10636 * 10637 * TODO: fix the "freeCache" call to not delete 10638 * the file we care about. 10639 */ 10640 if (pkgLite.recommendedInstallLocation 10641 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10642 pkgLite.recommendedInstallLocation 10643 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10644 } 10645 } 10646 } 10647 10648 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10649 int loc = pkgLite.recommendedInstallLocation; 10650 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10651 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10652 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10653 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10654 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10655 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10656 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10657 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10658 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10659 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10660 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10661 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10662 } else { 10663 // Override with defaults if needed. 10664 loc = installLocationPolicy(pkgLite); 10665 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10666 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10667 } else if (!onSd && !onInt) { 10668 // Override install location with flags 10669 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10670 // Set the flag to install on external media. 10671 installFlags |= PackageManager.INSTALL_EXTERNAL; 10672 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10673 } else { 10674 // Make sure the flag for installing on external 10675 // media is unset 10676 installFlags |= PackageManager.INSTALL_INTERNAL; 10677 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10678 } 10679 } 10680 } 10681 } 10682 10683 final InstallArgs args = createInstallArgs(this); 10684 mArgs = args; 10685 10686 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10687 // TODO: http://b/22976637 10688 // Apps installed for "all" users use the device owner to verify the app 10689 UserHandle verifierUser = getUser(); 10690 if (verifierUser == UserHandle.ALL) { 10691 verifierUser = UserHandle.SYSTEM; 10692 } 10693 10694 /* 10695 * Determine if we have any installed package verifiers. If we 10696 * do, then we'll defer to them to verify the packages. 10697 */ 10698 final int requiredUid = mRequiredVerifierPackage == null ? -1 10699 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10700 if (!origin.existing && requiredUid != -1 10701 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10702 final Intent verification = new Intent( 10703 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10704 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10705 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10706 PACKAGE_MIME_TYPE); 10707 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10708 10709 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10710 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10711 verifierUser.getIdentifier()); 10712 10713 if (DEBUG_VERIFY) { 10714 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10715 + verification.toString() + " with " + pkgLite.verifiers.length 10716 + " optional verifiers"); 10717 } 10718 10719 final int verificationId = mPendingVerificationToken++; 10720 10721 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10722 10723 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10724 installerPackageName); 10725 10726 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10727 installFlags); 10728 10729 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10730 pkgLite.packageName); 10731 10732 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10733 pkgLite.versionCode); 10734 10735 if (verificationParams != null) { 10736 if (verificationParams.getVerificationURI() != null) { 10737 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10738 verificationParams.getVerificationURI()); 10739 } 10740 if (verificationParams.getOriginatingURI() != null) { 10741 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10742 verificationParams.getOriginatingURI()); 10743 } 10744 if (verificationParams.getReferrer() != null) { 10745 verification.putExtra(Intent.EXTRA_REFERRER, 10746 verificationParams.getReferrer()); 10747 } 10748 if (verificationParams.getOriginatingUid() >= 0) { 10749 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10750 verificationParams.getOriginatingUid()); 10751 } 10752 if (verificationParams.getInstallerUid() >= 0) { 10753 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10754 verificationParams.getInstallerUid()); 10755 } 10756 } 10757 10758 final PackageVerificationState verificationState = new PackageVerificationState( 10759 requiredUid, args); 10760 10761 mPendingVerification.append(verificationId, verificationState); 10762 10763 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10764 receivers, verificationState); 10765 10766 /* 10767 * If any sufficient verifiers were listed in the package 10768 * manifest, attempt to ask them. 10769 */ 10770 if (sufficientVerifiers != null) { 10771 final int N = sufficientVerifiers.size(); 10772 if (N == 0) { 10773 Slog.i(TAG, "Additional verifiers required, but none installed."); 10774 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10775 } else { 10776 for (int i = 0; i < N; i++) { 10777 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10778 10779 final Intent sufficientIntent = new Intent(verification); 10780 sufficientIntent.setComponent(verifierComponent); 10781 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10782 } 10783 } 10784 } 10785 10786 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10787 mRequiredVerifierPackage, receivers); 10788 if (ret == PackageManager.INSTALL_SUCCEEDED 10789 && mRequiredVerifierPackage != null) { 10790 Trace.asyncTraceBegin( 10791 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10792 /* 10793 * Send the intent to the required verification agent, 10794 * but only start the verification timeout after the 10795 * target BroadcastReceivers have run. 10796 */ 10797 verification.setComponent(requiredVerifierComponent); 10798 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10799 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10800 new BroadcastReceiver() { 10801 @Override 10802 public void onReceive(Context context, Intent intent) { 10803 final Message msg = mHandler 10804 .obtainMessage(CHECK_PENDING_VERIFICATION); 10805 msg.arg1 = verificationId; 10806 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10807 } 10808 }, null, 0, null, null); 10809 10810 /* 10811 * We don't want the copy to proceed until verification 10812 * succeeds, so null out this field. 10813 */ 10814 mArgs = null; 10815 } 10816 } else { 10817 /* 10818 * No package verification is enabled, so immediately start 10819 * the remote call to initiate copy using temporary file. 10820 */ 10821 ret = args.copyApk(mContainerService, true); 10822 } 10823 } 10824 10825 mRet = ret; 10826 } 10827 10828 @Override 10829 void handleReturnCode() { 10830 // If mArgs is null, then MCS couldn't be reached. When it 10831 // reconnects, it will try again to install. At that point, this 10832 // will succeed. 10833 if (mArgs != null) { 10834 processPendingInstall(mArgs, mRet); 10835 } 10836 } 10837 10838 @Override 10839 void handleServiceError() { 10840 mArgs = createInstallArgs(this); 10841 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10842 } 10843 10844 public boolean isForwardLocked() { 10845 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10846 } 10847 } 10848 10849 /** 10850 * Used during creation of InstallArgs 10851 * 10852 * @param installFlags package installation flags 10853 * @return true if should be installed on external storage 10854 */ 10855 private static boolean installOnExternalAsec(int installFlags) { 10856 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10857 return false; 10858 } 10859 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10860 return true; 10861 } 10862 return false; 10863 } 10864 10865 /** 10866 * Used during creation of InstallArgs 10867 * 10868 * @param installFlags package installation flags 10869 * @return true if should be installed as forward locked 10870 */ 10871 private static boolean installForwardLocked(int installFlags) { 10872 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10873 } 10874 10875 private InstallArgs createInstallArgs(InstallParams params) { 10876 if (params.move != null) { 10877 return new MoveInstallArgs(params); 10878 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10879 return new AsecInstallArgs(params); 10880 } else { 10881 return new FileInstallArgs(params); 10882 } 10883 } 10884 10885 /** 10886 * Create args that describe an existing installed package. Typically used 10887 * when cleaning up old installs, or used as a move source. 10888 */ 10889 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10890 String resourcePath, String[] instructionSets) { 10891 final boolean isInAsec; 10892 if (installOnExternalAsec(installFlags)) { 10893 /* Apps on SD card are always in ASEC containers. */ 10894 isInAsec = true; 10895 } else if (installForwardLocked(installFlags) 10896 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10897 /* 10898 * Forward-locked apps are only in ASEC containers if they're the 10899 * new style 10900 */ 10901 isInAsec = true; 10902 } else { 10903 isInAsec = false; 10904 } 10905 10906 if (isInAsec) { 10907 return new AsecInstallArgs(codePath, instructionSets, 10908 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10909 } else { 10910 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10911 } 10912 } 10913 10914 static abstract class InstallArgs { 10915 /** @see InstallParams#origin */ 10916 final OriginInfo origin; 10917 /** @see InstallParams#move */ 10918 final MoveInfo move; 10919 10920 final IPackageInstallObserver2 observer; 10921 // Always refers to PackageManager flags only 10922 final int installFlags; 10923 final String installerPackageName; 10924 final String volumeUuid; 10925 final ManifestDigest manifestDigest; 10926 final UserHandle user; 10927 final String abiOverride; 10928 final String[] installGrantPermissions; 10929 /** If non-null, drop an async trace when the install completes */ 10930 final String traceMethod; 10931 final int traceCookie; 10932 10933 // The list of instruction sets supported by this app. This is currently 10934 // only used during the rmdex() phase to clean up resources. We can get rid of this 10935 // if we move dex files under the common app path. 10936 /* nullable */ String[] instructionSets; 10937 10938 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10939 int installFlags, String installerPackageName, String volumeUuid, 10940 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10941 String abiOverride, String[] installGrantPermissions, 10942 String traceMethod, int traceCookie) { 10943 this.origin = origin; 10944 this.move = move; 10945 this.installFlags = installFlags; 10946 this.observer = observer; 10947 this.installerPackageName = installerPackageName; 10948 this.volumeUuid = volumeUuid; 10949 this.manifestDigest = manifestDigest; 10950 this.user = user; 10951 this.instructionSets = instructionSets; 10952 this.abiOverride = abiOverride; 10953 this.installGrantPermissions = installGrantPermissions; 10954 this.traceMethod = traceMethod; 10955 this.traceCookie = traceCookie; 10956 } 10957 10958 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10959 abstract int doPreInstall(int status); 10960 10961 /** 10962 * Rename package into final resting place. All paths on the given 10963 * scanned package should be updated to reflect the rename. 10964 */ 10965 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10966 abstract int doPostInstall(int status, int uid); 10967 10968 /** @see PackageSettingBase#codePathString */ 10969 abstract String getCodePath(); 10970 /** @see PackageSettingBase#resourcePathString */ 10971 abstract String getResourcePath(); 10972 10973 // Need installer lock especially for dex file removal. 10974 abstract void cleanUpResourcesLI(); 10975 abstract boolean doPostDeleteLI(boolean delete); 10976 10977 /** 10978 * Called before the source arguments are copied. This is used mostly 10979 * for MoveParams when it needs to read the source file to put it in the 10980 * destination. 10981 */ 10982 int doPreCopy() { 10983 return PackageManager.INSTALL_SUCCEEDED; 10984 } 10985 10986 /** 10987 * Called after the source arguments are copied. This is used mostly for 10988 * MoveParams when it needs to read the source file to put it in the 10989 * destination. 10990 * 10991 * @return 10992 */ 10993 int doPostCopy(int uid) { 10994 return PackageManager.INSTALL_SUCCEEDED; 10995 } 10996 10997 protected boolean isFwdLocked() { 10998 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10999 } 11000 11001 protected boolean isExternalAsec() { 11002 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11003 } 11004 11005 UserHandle getUser() { 11006 return user; 11007 } 11008 } 11009 11010 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11011 if (!allCodePaths.isEmpty()) { 11012 if (instructionSets == null) { 11013 throw new IllegalStateException("instructionSet == null"); 11014 } 11015 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11016 for (String codePath : allCodePaths) { 11017 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11018 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11019 if (retCode < 0) { 11020 Slog.w(TAG, "Couldn't remove dex file for package: " 11021 + " at location " + codePath + ", retcode=" + retCode); 11022 // we don't consider this to be a failure of the core package deletion 11023 } 11024 } 11025 } 11026 } 11027 } 11028 11029 /** 11030 * Logic to handle installation of non-ASEC applications, including copying 11031 * and renaming logic. 11032 */ 11033 class FileInstallArgs extends InstallArgs { 11034 private File codeFile; 11035 private File resourceFile; 11036 11037 // Example topology: 11038 // /data/app/com.example/base.apk 11039 // /data/app/com.example/split_foo.apk 11040 // /data/app/com.example/lib/arm/libfoo.so 11041 // /data/app/com.example/lib/arm64/libfoo.so 11042 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11043 11044 /** New install */ 11045 FileInstallArgs(InstallParams params) { 11046 super(params.origin, params.move, params.observer, params.installFlags, 11047 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11048 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11049 params.grantedRuntimePermissions, 11050 params.traceMethod, params.traceCookie); 11051 if (isFwdLocked()) { 11052 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11053 } 11054 } 11055 11056 /** Existing install */ 11057 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11058 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11059 null, null, null, 0); 11060 this.codeFile = (codePath != null) ? new File(codePath) : null; 11061 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11062 } 11063 11064 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11065 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11066 try { 11067 return doCopyApk(imcs, temp); 11068 } finally { 11069 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11070 } 11071 } 11072 11073 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11074 if (origin.staged) { 11075 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11076 codeFile = origin.file; 11077 resourceFile = origin.file; 11078 return PackageManager.INSTALL_SUCCEEDED; 11079 } 11080 11081 try { 11082 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11083 codeFile = tempDir; 11084 resourceFile = tempDir; 11085 } catch (IOException e) { 11086 Slog.w(TAG, "Failed to create copy file: " + e); 11087 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11088 } 11089 11090 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11091 @Override 11092 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11093 if (!FileUtils.isValidExtFilename(name)) { 11094 throw new IllegalArgumentException("Invalid filename: " + name); 11095 } 11096 try { 11097 final File file = new File(codeFile, name); 11098 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11099 O_RDWR | O_CREAT, 0644); 11100 Os.chmod(file.getAbsolutePath(), 0644); 11101 return new ParcelFileDescriptor(fd); 11102 } catch (ErrnoException e) { 11103 throw new RemoteException("Failed to open: " + e.getMessage()); 11104 } 11105 } 11106 }; 11107 11108 int ret = PackageManager.INSTALL_SUCCEEDED; 11109 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11110 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11111 Slog.e(TAG, "Failed to copy package"); 11112 return ret; 11113 } 11114 11115 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11116 NativeLibraryHelper.Handle handle = null; 11117 try { 11118 handle = NativeLibraryHelper.Handle.create(codeFile); 11119 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11120 abiOverride); 11121 } catch (IOException e) { 11122 Slog.e(TAG, "Copying native libraries failed", e); 11123 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11124 } finally { 11125 IoUtils.closeQuietly(handle); 11126 } 11127 11128 return ret; 11129 } 11130 11131 int doPreInstall(int status) { 11132 if (status != PackageManager.INSTALL_SUCCEEDED) { 11133 cleanUp(); 11134 } 11135 return status; 11136 } 11137 11138 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11139 if (status != PackageManager.INSTALL_SUCCEEDED) { 11140 cleanUp(); 11141 return false; 11142 } 11143 11144 final File targetDir = codeFile.getParentFile(); 11145 final File beforeCodeFile = codeFile; 11146 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11147 11148 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11149 try { 11150 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11151 } catch (ErrnoException e) { 11152 Slog.w(TAG, "Failed to rename", e); 11153 return false; 11154 } 11155 11156 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11157 Slog.w(TAG, "Failed to restorecon"); 11158 return false; 11159 } 11160 11161 // Reflect the rename internally 11162 codeFile = afterCodeFile; 11163 resourceFile = afterCodeFile; 11164 11165 // Reflect the rename in scanned details 11166 pkg.codePath = afterCodeFile.getAbsolutePath(); 11167 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11168 pkg.baseCodePath); 11169 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11170 pkg.splitCodePaths); 11171 11172 // Reflect the rename in app info 11173 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11174 pkg.applicationInfo.setCodePath(pkg.codePath); 11175 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11176 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11177 pkg.applicationInfo.setResourcePath(pkg.codePath); 11178 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11179 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11180 11181 return true; 11182 } 11183 11184 int doPostInstall(int status, int uid) { 11185 if (status != PackageManager.INSTALL_SUCCEEDED) { 11186 cleanUp(); 11187 } 11188 return status; 11189 } 11190 11191 @Override 11192 String getCodePath() { 11193 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11194 } 11195 11196 @Override 11197 String getResourcePath() { 11198 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11199 } 11200 11201 private boolean cleanUp() { 11202 if (codeFile == null || !codeFile.exists()) { 11203 return false; 11204 } 11205 11206 if (codeFile.isDirectory()) { 11207 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11208 } else { 11209 codeFile.delete(); 11210 } 11211 11212 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11213 resourceFile.delete(); 11214 } 11215 11216 return true; 11217 } 11218 11219 void cleanUpResourcesLI() { 11220 // Try enumerating all code paths before deleting 11221 List<String> allCodePaths = Collections.EMPTY_LIST; 11222 if (codeFile != null && codeFile.exists()) { 11223 try { 11224 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11225 allCodePaths = pkg.getAllCodePaths(); 11226 } catch (PackageParserException e) { 11227 // Ignored; we tried our best 11228 } 11229 } 11230 11231 cleanUp(); 11232 removeDexFiles(allCodePaths, instructionSets); 11233 } 11234 11235 boolean doPostDeleteLI(boolean delete) { 11236 // XXX err, shouldn't we respect the delete flag? 11237 cleanUpResourcesLI(); 11238 return true; 11239 } 11240 } 11241 11242 private boolean isAsecExternal(String cid) { 11243 final String asecPath = PackageHelper.getSdFilesystem(cid); 11244 return !asecPath.startsWith(mAsecInternalPath); 11245 } 11246 11247 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11248 PackageManagerException { 11249 if (copyRet < 0) { 11250 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11251 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11252 throw new PackageManagerException(copyRet, message); 11253 } 11254 } 11255 } 11256 11257 /** 11258 * Extract the MountService "container ID" from the full code path of an 11259 * .apk. 11260 */ 11261 static String cidFromCodePath(String fullCodePath) { 11262 int eidx = fullCodePath.lastIndexOf("/"); 11263 String subStr1 = fullCodePath.substring(0, eidx); 11264 int sidx = subStr1.lastIndexOf("/"); 11265 return subStr1.substring(sidx+1, eidx); 11266 } 11267 11268 /** 11269 * Logic to handle installation of ASEC applications, including copying and 11270 * renaming logic. 11271 */ 11272 class AsecInstallArgs extends InstallArgs { 11273 static final String RES_FILE_NAME = "pkg.apk"; 11274 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11275 11276 String cid; 11277 String packagePath; 11278 String resourcePath; 11279 11280 /** New install */ 11281 AsecInstallArgs(InstallParams params) { 11282 super(params.origin, params.move, params.observer, params.installFlags, 11283 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11284 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11285 params.grantedRuntimePermissions, 11286 params.traceMethod, params.traceCookie); 11287 } 11288 11289 /** Existing install */ 11290 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11291 boolean isExternal, boolean isForwardLocked) { 11292 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11293 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11294 instructionSets, null, null, null, 0); 11295 // Hackily pretend we're still looking at a full code path 11296 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11297 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11298 } 11299 11300 // Extract cid from fullCodePath 11301 int eidx = fullCodePath.lastIndexOf("/"); 11302 String subStr1 = fullCodePath.substring(0, eidx); 11303 int sidx = subStr1.lastIndexOf("/"); 11304 cid = subStr1.substring(sidx+1, eidx); 11305 setMountPath(subStr1); 11306 } 11307 11308 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11309 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11310 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11311 instructionSets, null, null, null, 0); 11312 this.cid = cid; 11313 setMountPath(PackageHelper.getSdDir(cid)); 11314 } 11315 11316 void createCopyFile() { 11317 cid = mInstallerService.allocateExternalStageCidLegacy(); 11318 } 11319 11320 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11321 if (origin.staged) { 11322 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11323 cid = origin.cid; 11324 setMountPath(PackageHelper.getSdDir(cid)); 11325 return PackageManager.INSTALL_SUCCEEDED; 11326 } 11327 11328 if (temp) { 11329 createCopyFile(); 11330 } else { 11331 /* 11332 * Pre-emptively destroy the container since it's destroyed if 11333 * copying fails due to it existing anyway. 11334 */ 11335 PackageHelper.destroySdDir(cid); 11336 } 11337 11338 final String newMountPath = imcs.copyPackageToContainer( 11339 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11340 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11341 11342 if (newMountPath != null) { 11343 setMountPath(newMountPath); 11344 return PackageManager.INSTALL_SUCCEEDED; 11345 } else { 11346 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11347 } 11348 } 11349 11350 @Override 11351 String getCodePath() { 11352 return packagePath; 11353 } 11354 11355 @Override 11356 String getResourcePath() { 11357 return resourcePath; 11358 } 11359 11360 int doPreInstall(int status) { 11361 if (status != PackageManager.INSTALL_SUCCEEDED) { 11362 // Destroy container 11363 PackageHelper.destroySdDir(cid); 11364 } else { 11365 boolean mounted = PackageHelper.isContainerMounted(cid); 11366 if (!mounted) { 11367 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11368 Process.SYSTEM_UID); 11369 if (newMountPath != null) { 11370 setMountPath(newMountPath); 11371 } else { 11372 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11373 } 11374 } 11375 } 11376 return status; 11377 } 11378 11379 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11380 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11381 String newMountPath = null; 11382 if (PackageHelper.isContainerMounted(cid)) { 11383 // Unmount the container 11384 if (!PackageHelper.unMountSdDir(cid)) { 11385 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11386 return false; 11387 } 11388 } 11389 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11390 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11391 " which might be stale. Will try to clean up."); 11392 // Clean up the stale container and proceed to recreate. 11393 if (!PackageHelper.destroySdDir(newCacheId)) { 11394 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11395 return false; 11396 } 11397 // Successfully cleaned up stale container. Try to rename again. 11398 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11399 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11400 + " inspite of cleaning it up."); 11401 return false; 11402 } 11403 } 11404 if (!PackageHelper.isContainerMounted(newCacheId)) { 11405 Slog.w(TAG, "Mounting container " + newCacheId); 11406 newMountPath = PackageHelper.mountSdDir(newCacheId, 11407 getEncryptKey(), Process.SYSTEM_UID); 11408 } else { 11409 newMountPath = PackageHelper.getSdDir(newCacheId); 11410 } 11411 if (newMountPath == null) { 11412 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11413 return false; 11414 } 11415 Log.i(TAG, "Succesfully renamed " + cid + 11416 " to " + newCacheId + 11417 " at new path: " + newMountPath); 11418 cid = newCacheId; 11419 11420 final File beforeCodeFile = new File(packagePath); 11421 setMountPath(newMountPath); 11422 final File afterCodeFile = new File(packagePath); 11423 11424 // Reflect the rename in scanned details 11425 pkg.codePath = afterCodeFile.getAbsolutePath(); 11426 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11427 pkg.baseCodePath); 11428 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11429 pkg.splitCodePaths); 11430 11431 // Reflect the rename in app info 11432 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11433 pkg.applicationInfo.setCodePath(pkg.codePath); 11434 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11435 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11436 pkg.applicationInfo.setResourcePath(pkg.codePath); 11437 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11438 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11439 11440 return true; 11441 } 11442 11443 private void setMountPath(String mountPath) { 11444 final File mountFile = new File(mountPath); 11445 11446 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11447 if (monolithicFile.exists()) { 11448 packagePath = monolithicFile.getAbsolutePath(); 11449 if (isFwdLocked()) { 11450 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11451 } else { 11452 resourcePath = packagePath; 11453 } 11454 } else { 11455 packagePath = mountFile.getAbsolutePath(); 11456 resourcePath = packagePath; 11457 } 11458 } 11459 11460 int doPostInstall(int status, int uid) { 11461 if (status != PackageManager.INSTALL_SUCCEEDED) { 11462 cleanUp(); 11463 } else { 11464 final int groupOwner; 11465 final String protectedFile; 11466 if (isFwdLocked()) { 11467 groupOwner = UserHandle.getSharedAppGid(uid); 11468 protectedFile = RES_FILE_NAME; 11469 } else { 11470 groupOwner = -1; 11471 protectedFile = null; 11472 } 11473 11474 if (uid < Process.FIRST_APPLICATION_UID 11475 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11476 Slog.e(TAG, "Failed to finalize " + cid); 11477 PackageHelper.destroySdDir(cid); 11478 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11479 } 11480 11481 boolean mounted = PackageHelper.isContainerMounted(cid); 11482 if (!mounted) { 11483 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11484 } 11485 } 11486 return status; 11487 } 11488 11489 private void cleanUp() { 11490 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11491 11492 // Destroy secure container 11493 PackageHelper.destroySdDir(cid); 11494 } 11495 11496 private List<String> getAllCodePaths() { 11497 final File codeFile = new File(getCodePath()); 11498 if (codeFile != null && codeFile.exists()) { 11499 try { 11500 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11501 return pkg.getAllCodePaths(); 11502 } catch (PackageParserException e) { 11503 // Ignored; we tried our best 11504 } 11505 } 11506 return Collections.EMPTY_LIST; 11507 } 11508 11509 void cleanUpResourcesLI() { 11510 // Enumerate all code paths before deleting 11511 cleanUpResourcesLI(getAllCodePaths()); 11512 } 11513 11514 private void cleanUpResourcesLI(List<String> allCodePaths) { 11515 cleanUp(); 11516 removeDexFiles(allCodePaths, instructionSets); 11517 } 11518 11519 String getPackageName() { 11520 return getAsecPackageName(cid); 11521 } 11522 11523 boolean doPostDeleteLI(boolean delete) { 11524 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11525 final List<String> allCodePaths = getAllCodePaths(); 11526 boolean mounted = PackageHelper.isContainerMounted(cid); 11527 if (mounted) { 11528 // Unmount first 11529 if (PackageHelper.unMountSdDir(cid)) { 11530 mounted = false; 11531 } 11532 } 11533 if (!mounted && delete) { 11534 cleanUpResourcesLI(allCodePaths); 11535 } 11536 return !mounted; 11537 } 11538 11539 @Override 11540 int doPreCopy() { 11541 if (isFwdLocked()) { 11542 if (!PackageHelper.fixSdPermissions(cid, 11543 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11544 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11545 } 11546 } 11547 11548 return PackageManager.INSTALL_SUCCEEDED; 11549 } 11550 11551 @Override 11552 int doPostCopy(int uid) { 11553 if (isFwdLocked()) { 11554 if (uid < Process.FIRST_APPLICATION_UID 11555 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11556 RES_FILE_NAME)) { 11557 Slog.e(TAG, "Failed to finalize " + cid); 11558 PackageHelper.destroySdDir(cid); 11559 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11560 } 11561 } 11562 11563 return PackageManager.INSTALL_SUCCEEDED; 11564 } 11565 } 11566 11567 /** 11568 * Logic to handle movement of existing installed applications. 11569 */ 11570 class MoveInstallArgs extends InstallArgs { 11571 private File codeFile; 11572 private File resourceFile; 11573 11574 /** New install */ 11575 MoveInstallArgs(InstallParams params) { 11576 super(params.origin, params.move, params.observer, params.installFlags, 11577 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11578 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11579 params.grantedRuntimePermissions, 11580 params.traceMethod, params.traceCookie); 11581 } 11582 11583 int copyApk(IMediaContainerService imcs, boolean temp) { 11584 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11585 + move.fromUuid + " to " + move.toUuid); 11586 synchronized (mInstaller) { 11587 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11588 move.dataAppName, move.appId, move.seinfo) != 0) { 11589 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11590 } 11591 } 11592 11593 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11594 resourceFile = codeFile; 11595 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11596 11597 return PackageManager.INSTALL_SUCCEEDED; 11598 } 11599 11600 int doPreInstall(int status) { 11601 if (status != PackageManager.INSTALL_SUCCEEDED) { 11602 cleanUp(move.toUuid); 11603 } 11604 return status; 11605 } 11606 11607 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11608 if (status != PackageManager.INSTALL_SUCCEEDED) { 11609 cleanUp(move.toUuid); 11610 return false; 11611 } 11612 11613 // Reflect the move in app info 11614 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11615 pkg.applicationInfo.setCodePath(pkg.codePath); 11616 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11617 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11618 pkg.applicationInfo.setResourcePath(pkg.codePath); 11619 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11620 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11621 11622 return true; 11623 } 11624 11625 int doPostInstall(int status, int uid) { 11626 if (status == PackageManager.INSTALL_SUCCEEDED) { 11627 cleanUp(move.fromUuid); 11628 } else { 11629 cleanUp(move.toUuid); 11630 } 11631 return status; 11632 } 11633 11634 @Override 11635 String getCodePath() { 11636 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11637 } 11638 11639 @Override 11640 String getResourcePath() { 11641 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11642 } 11643 11644 private boolean cleanUp(String volumeUuid) { 11645 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11646 move.dataAppName); 11647 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11648 synchronized (mInstallLock) { 11649 // Clean up both app data and code 11650 removeDataDirsLI(volumeUuid, move.packageName); 11651 if (codeFile.isDirectory()) { 11652 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11653 } else { 11654 codeFile.delete(); 11655 } 11656 } 11657 return true; 11658 } 11659 11660 void cleanUpResourcesLI() { 11661 throw new UnsupportedOperationException(); 11662 } 11663 11664 boolean doPostDeleteLI(boolean delete) { 11665 throw new UnsupportedOperationException(); 11666 } 11667 } 11668 11669 static String getAsecPackageName(String packageCid) { 11670 int idx = packageCid.lastIndexOf("-"); 11671 if (idx == -1) { 11672 return packageCid; 11673 } 11674 return packageCid.substring(0, idx); 11675 } 11676 11677 // Utility method used to create code paths based on package name and available index. 11678 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11679 String idxStr = ""; 11680 int idx = 1; 11681 // Fall back to default value of idx=1 if prefix is not 11682 // part of oldCodePath 11683 if (oldCodePath != null) { 11684 String subStr = oldCodePath; 11685 // Drop the suffix right away 11686 if (suffix != null && subStr.endsWith(suffix)) { 11687 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11688 } 11689 // If oldCodePath already contains prefix find out the 11690 // ending index to either increment or decrement. 11691 int sidx = subStr.lastIndexOf(prefix); 11692 if (sidx != -1) { 11693 subStr = subStr.substring(sidx + prefix.length()); 11694 if (subStr != null) { 11695 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11696 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11697 } 11698 try { 11699 idx = Integer.parseInt(subStr); 11700 if (idx <= 1) { 11701 idx++; 11702 } else { 11703 idx--; 11704 } 11705 } catch(NumberFormatException e) { 11706 } 11707 } 11708 } 11709 } 11710 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11711 return prefix + idxStr; 11712 } 11713 11714 private File getNextCodePath(File targetDir, String packageName) { 11715 int suffix = 1; 11716 File result; 11717 do { 11718 result = new File(targetDir, packageName + "-" + suffix); 11719 suffix++; 11720 } while (result.exists()); 11721 return result; 11722 } 11723 11724 // Utility method that returns the relative package path with respect 11725 // to the installation directory. Like say for /data/data/com.test-1.apk 11726 // string com.test-1 is returned. 11727 static String deriveCodePathName(String codePath) { 11728 if (codePath == null) { 11729 return null; 11730 } 11731 final File codeFile = new File(codePath); 11732 final String name = codeFile.getName(); 11733 if (codeFile.isDirectory()) { 11734 return name; 11735 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11736 final int lastDot = name.lastIndexOf('.'); 11737 return name.substring(0, lastDot); 11738 } else { 11739 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11740 return null; 11741 } 11742 } 11743 11744 class PackageInstalledInfo { 11745 String name; 11746 int uid; 11747 // The set of users that originally had this package installed. 11748 int[] origUsers; 11749 // The set of users that now have this package installed. 11750 int[] newUsers; 11751 PackageParser.Package pkg; 11752 int returnCode; 11753 String returnMsg; 11754 PackageRemovedInfo removedInfo; 11755 11756 public void setError(int code, String msg) { 11757 returnCode = code; 11758 returnMsg = msg; 11759 Slog.w(TAG, msg); 11760 } 11761 11762 public void setError(String msg, PackageParserException e) { 11763 returnCode = e.error; 11764 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11765 Slog.w(TAG, msg, e); 11766 } 11767 11768 public void setError(String msg, PackageManagerException e) { 11769 returnCode = e.error; 11770 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11771 Slog.w(TAG, msg, e); 11772 } 11773 11774 // In some error cases we want to convey more info back to the observer 11775 String origPackage; 11776 String origPermission; 11777 } 11778 11779 /* 11780 * Install a non-existing package. 11781 */ 11782 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11783 UserHandle user, String installerPackageName, String volumeUuid, 11784 PackageInstalledInfo res) { 11785 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11786 11787 // Remember this for later, in case we need to rollback this install 11788 String pkgName = pkg.packageName; 11789 11790 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11791 // TODO: b/23350563 11792 final boolean dataDirExists = Environment 11793 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11794 11795 synchronized(mPackages) { 11796 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11797 // A package with the same name is already installed, though 11798 // it has been renamed to an older name. The package we 11799 // are trying to install should be installed as an update to 11800 // the existing one, but that has not been requested, so bail. 11801 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11802 + " without first uninstalling package running as " 11803 + mSettings.mRenamedPackages.get(pkgName)); 11804 return; 11805 } 11806 if (mPackages.containsKey(pkgName)) { 11807 // Don't allow installation over an existing package with the same name. 11808 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11809 + " without first uninstalling."); 11810 return; 11811 } 11812 } 11813 11814 try { 11815 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11816 System.currentTimeMillis(), user); 11817 11818 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11819 // delete the partially installed application. the data directory will have to be 11820 // restored if it was already existing 11821 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11822 // remove package from internal structures. Note that we want deletePackageX to 11823 // delete the package data and cache directories that it created in 11824 // scanPackageLocked, unless those directories existed before we even tried to 11825 // install. 11826 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11827 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11828 res.removedInfo, true); 11829 } 11830 11831 } catch (PackageManagerException e) { 11832 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11833 } 11834 11835 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11836 } 11837 11838 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11839 // Can't rotate keys during boot or if sharedUser. 11840 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11841 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11842 return false; 11843 } 11844 // app is using upgradeKeySets; make sure all are valid 11845 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11846 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11847 for (int i = 0; i < upgradeKeySets.length; i++) { 11848 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11849 Slog.wtf(TAG, "Package " 11850 + (oldPs.name != null ? oldPs.name : "<null>") 11851 + " contains upgrade-key-set reference to unknown key-set: " 11852 + upgradeKeySets[i] 11853 + " reverting to signatures check."); 11854 return false; 11855 } 11856 } 11857 return true; 11858 } 11859 11860 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11861 // Upgrade keysets are being used. Determine if new package has a superset of the 11862 // required keys. 11863 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11864 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11865 for (int i = 0; i < upgradeKeySets.length; i++) { 11866 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11867 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11868 return true; 11869 } 11870 } 11871 return false; 11872 } 11873 11874 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11875 UserHandle user, String installerPackageName, String volumeUuid, 11876 PackageInstalledInfo res) { 11877 final PackageParser.Package oldPackage; 11878 final String pkgName = pkg.packageName; 11879 final int[] allUsers; 11880 final boolean[] perUserInstalled; 11881 11882 // First find the old package info and check signatures 11883 synchronized(mPackages) { 11884 oldPackage = mPackages.get(pkgName); 11885 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11886 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11887 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11888 if(!checkUpgradeKeySetLP(ps, pkg)) { 11889 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11890 "New package not signed by keys specified by upgrade-keysets: " 11891 + pkgName); 11892 return; 11893 } 11894 } else { 11895 // default to original signature matching 11896 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11897 != PackageManager.SIGNATURE_MATCH) { 11898 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11899 "New package has a different signature: " + pkgName); 11900 return; 11901 } 11902 } 11903 11904 // In case of rollback, remember per-user/profile install state 11905 allUsers = sUserManager.getUserIds(); 11906 perUserInstalled = new boolean[allUsers.length]; 11907 for (int i = 0; i < allUsers.length; i++) { 11908 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11909 } 11910 } 11911 11912 boolean sysPkg = (isSystemApp(oldPackage)); 11913 if (sysPkg) { 11914 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11915 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11916 } else { 11917 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11918 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11919 } 11920 } 11921 11922 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11923 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11924 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11925 String volumeUuid, PackageInstalledInfo res) { 11926 String pkgName = deletedPackage.packageName; 11927 boolean deletedPkg = true; 11928 boolean updatedSettings = false; 11929 11930 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11931 + deletedPackage); 11932 long origUpdateTime; 11933 if (pkg.mExtras != null) { 11934 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11935 } else { 11936 origUpdateTime = 0; 11937 } 11938 11939 // First delete the existing package while retaining the data directory 11940 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11941 res.removedInfo, true)) { 11942 // If the existing package wasn't successfully deleted 11943 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11944 deletedPkg = false; 11945 } else { 11946 // Successfully deleted the old package; proceed with replace. 11947 11948 // If deleted package lived in a container, give users a chance to 11949 // relinquish resources before killing. 11950 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11951 if (DEBUG_INSTALL) { 11952 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11953 } 11954 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11955 final ArrayList<String> pkgList = new ArrayList<String>(1); 11956 pkgList.add(deletedPackage.applicationInfo.packageName); 11957 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11958 } 11959 11960 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11961 try { 11962 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 11963 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11964 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11965 perUserInstalled, res, user); 11966 updatedSettings = true; 11967 } catch (PackageManagerException e) { 11968 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11969 } 11970 } 11971 11972 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11973 // remove package from internal structures. Note that we want deletePackageX to 11974 // delete the package data and cache directories that it created in 11975 // scanPackageLocked, unless those directories existed before we even tried to 11976 // install. 11977 if(updatedSettings) { 11978 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11979 deletePackageLI( 11980 pkgName, null, true, allUsers, perUserInstalled, 11981 PackageManager.DELETE_KEEP_DATA, 11982 res.removedInfo, true); 11983 } 11984 // Since we failed to install the new package we need to restore the old 11985 // package that we deleted. 11986 if (deletedPkg) { 11987 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11988 File restoreFile = new File(deletedPackage.codePath); 11989 // Parse old package 11990 boolean oldExternal = isExternal(deletedPackage); 11991 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11992 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11993 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11994 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11995 try { 11996 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 11997 null); 11998 } catch (PackageManagerException e) { 11999 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12000 + e.getMessage()); 12001 return; 12002 } 12003 // Restore of old package succeeded. Update permissions. 12004 // writer 12005 synchronized (mPackages) { 12006 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12007 UPDATE_PERMISSIONS_ALL); 12008 // can downgrade to reader 12009 mSettings.writeLPr(); 12010 } 12011 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12012 } 12013 } 12014 } 12015 12016 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12017 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12018 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12019 String volumeUuid, PackageInstalledInfo res) { 12020 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12021 + ", old=" + deletedPackage); 12022 boolean disabledSystem = false; 12023 boolean updatedSettings = false; 12024 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12025 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12026 != 0) { 12027 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12028 } 12029 String packageName = deletedPackage.packageName; 12030 if (packageName == null) { 12031 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12032 "Attempt to delete null packageName."); 12033 return; 12034 } 12035 PackageParser.Package oldPkg; 12036 PackageSetting oldPkgSetting; 12037 // reader 12038 synchronized (mPackages) { 12039 oldPkg = mPackages.get(packageName); 12040 oldPkgSetting = mSettings.mPackages.get(packageName); 12041 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12042 (oldPkgSetting == null)) { 12043 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12044 "Couldn't find package:" + packageName + " information"); 12045 return; 12046 } 12047 } 12048 12049 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12050 12051 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12052 res.removedInfo.removedPackage = packageName; 12053 // Remove existing system package 12054 removePackageLI(oldPkgSetting, true); 12055 // writer 12056 synchronized (mPackages) { 12057 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12058 if (!disabledSystem && deletedPackage != null) { 12059 // We didn't need to disable the .apk as a current system package, 12060 // which means we are replacing another update that is already 12061 // installed. We need to make sure to delete the older one's .apk. 12062 res.removedInfo.args = createInstallArgsForExisting(0, 12063 deletedPackage.applicationInfo.getCodePath(), 12064 deletedPackage.applicationInfo.getResourcePath(), 12065 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12066 } else { 12067 res.removedInfo.args = null; 12068 } 12069 } 12070 12071 // Successfully disabled the old package. Now proceed with re-installation 12072 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12073 12074 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12075 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12076 12077 PackageParser.Package newPackage = null; 12078 try { 12079 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12080 if (newPackage.mExtras != null) { 12081 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12082 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12083 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12084 12085 // is the update attempting to change shared user? that isn't going to work... 12086 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12087 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12088 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12089 + " to " + newPkgSetting.sharedUser); 12090 updatedSettings = true; 12091 } 12092 } 12093 12094 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12095 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12096 perUserInstalled, res, user); 12097 updatedSettings = true; 12098 } 12099 12100 } catch (PackageManagerException e) { 12101 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12102 } 12103 12104 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12105 // Re installation failed. Restore old information 12106 // Remove new pkg information 12107 if (newPackage != null) { 12108 removeInstalledPackageLI(newPackage, true); 12109 } 12110 // Add back the old system package 12111 try { 12112 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12113 } catch (PackageManagerException e) { 12114 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12115 } 12116 // Restore the old system information in Settings 12117 synchronized (mPackages) { 12118 if (disabledSystem) { 12119 mSettings.enableSystemPackageLPw(packageName); 12120 } 12121 if (updatedSettings) { 12122 mSettings.setInstallerPackageName(packageName, 12123 oldPkgSetting.installerPackageName); 12124 } 12125 mSettings.writeLPr(); 12126 } 12127 } 12128 } 12129 12130 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12131 // Collect all used permissions in the UID 12132 ArraySet<String> usedPermissions = new ArraySet<>(); 12133 final int packageCount = su.packages.size(); 12134 for (int i = 0; i < packageCount; i++) { 12135 PackageSetting ps = su.packages.valueAt(i); 12136 if (ps.pkg == null) { 12137 continue; 12138 } 12139 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12140 for (int j = 0; j < requestedPermCount; j++) { 12141 String permission = ps.pkg.requestedPermissions.get(j); 12142 BasePermission bp = mSettings.mPermissions.get(permission); 12143 if (bp != null) { 12144 usedPermissions.add(permission); 12145 } 12146 } 12147 } 12148 12149 PermissionsState permissionsState = su.getPermissionsState(); 12150 // Prune install permissions 12151 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12152 final int installPermCount = installPermStates.size(); 12153 for (int i = installPermCount - 1; i >= 0; i--) { 12154 PermissionState permissionState = installPermStates.get(i); 12155 if (!usedPermissions.contains(permissionState.getName())) { 12156 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12157 if (bp != null) { 12158 permissionsState.revokeInstallPermission(bp); 12159 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12160 PackageManager.MASK_PERMISSION_FLAGS, 0); 12161 } 12162 } 12163 } 12164 12165 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12166 12167 // Prune runtime permissions 12168 for (int userId : allUserIds) { 12169 List<PermissionState> runtimePermStates = permissionsState 12170 .getRuntimePermissionStates(userId); 12171 final int runtimePermCount = runtimePermStates.size(); 12172 for (int i = runtimePermCount - 1; i >= 0; i--) { 12173 PermissionState permissionState = runtimePermStates.get(i); 12174 if (!usedPermissions.contains(permissionState.getName())) { 12175 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12176 if (bp != null) { 12177 permissionsState.revokeRuntimePermission(bp, userId); 12178 permissionsState.updatePermissionFlags(bp, userId, 12179 PackageManager.MASK_PERMISSION_FLAGS, 0); 12180 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12181 runtimePermissionChangedUserIds, userId); 12182 } 12183 } 12184 } 12185 } 12186 12187 return runtimePermissionChangedUserIds; 12188 } 12189 12190 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12191 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12192 UserHandle user) { 12193 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12194 12195 String pkgName = newPackage.packageName; 12196 synchronized (mPackages) { 12197 //write settings. the installStatus will be incomplete at this stage. 12198 //note that the new package setting would have already been 12199 //added to mPackages. It hasn't been persisted yet. 12200 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12201 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12202 mSettings.writeLPr(); 12203 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12204 } 12205 12206 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12207 synchronized (mPackages) { 12208 updatePermissionsLPw(newPackage.packageName, newPackage, 12209 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12210 ? UPDATE_PERMISSIONS_ALL : 0)); 12211 // For system-bundled packages, we assume that installing an upgraded version 12212 // of the package implies that the user actually wants to run that new code, 12213 // so we enable the package. 12214 PackageSetting ps = mSettings.mPackages.get(pkgName); 12215 if (ps != null) { 12216 if (isSystemApp(newPackage)) { 12217 // NB: implicit assumption that system package upgrades apply to all users 12218 if (DEBUG_INSTALL) { 12219 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12220 } 12221 if (res.origUsers != null) { 12222 for (int userHandle : res.origUsers) { 12223 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12224 userHandle, installerPackageName); 12225 } 12226 } 12227 // Also convey the prior install/uninstall state 12228 if (allUsers != null && perUserInstalled != null) { 12229 for (int i = 0; i < allUsers.length; i++) { 12230 if (DEBUG_INSTALL) { 12231 Slog.d(TAG, " user " + allUsers[i] 12232 + " => " + perUserInstalled[i]); 12233 } 12234 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12235 } 12236 // these install state changes will be persisted in the 12237 // upcoming call to mSettings.writeLPr(). 12238 } 12239 } 12240 // It's implied that when a user requests installation, they want the app to be 12241 // installed and enabled. 12242 int userId = user.getIdentifier(); 12243 if (userId != UserHandle.USER_ALL) { 12244 ps.setInstalled(true, userId); 12245 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12246 } 12247 } 12248 res.name = pkgName; 12249 res.uid = newPackage.applicationInfo.uid; 12250 res.pkg = newPackage; 12251 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12252 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12253 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12254 //to update install status 12255 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12256 mSettings.writeLPr(); 12257 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12258 } 12259 12260 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12261 } 12262 12263 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12264 try { 12265 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12266 installPackageLI(args, res); 12267 } finally { 12268 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12269 } 12270 } 12271 12272 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12273 final int installFlags = args.installFlags; 12274 final String installerPackageName = args.installerPackageName; 12275 final String volumeUuid = args.volumeUuid; 12276 final File tmpPackageFile = new File(args.getCodePath()); 12277 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12278 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12279 || (args.volumeUuid != null)); 12280 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12281 boolean replace = false; 12282 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12283 if (args.move != null) { 12284 // moving a complete application; perfom an initial scan on the new install location 12285 scanFlags |= SCAN_INITIAL; 12286 } 12287 // Result object to be returned 12288 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12289 12290 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12291 12292 // Retrieve PackageSettings and parse package 12293 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12294 | PackageParser.PARSE_ENFORCE_CODE 12295 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12296 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12297 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12298 PackageParser pp = new PackageParser(); 12299 pp.setSeparateProcesses(mSeparateProcesses); 12300 pp.setDisplayMetrics(mMetrics); 12301 12302 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12303 final PackageParser.Package pkg; 12304 try { 12305 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12306 } catch (PackageParserException e) { 12307 res.setError("Failed parse during installPackageLI", e); 12308 return; 12309 } finally { 12310 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12311 } 12312 12313 // Mark that we have an install time CPU ABI override. 12314 pkg.cpuAbiOverride = args.abiOverride; 12315 12316 String pkgName = res.name = pkg.packageName; 12317 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12318 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12319 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12320 return; 12321 } 12322 } 12323 12324 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12325 try { 12326 pp.collectCertificates(pkg, parseFlags); 12327 } catch (PackageParserException e) { 12328 res.setError("Failed collect during installPackageLI", e); 12329 return; 12330 } finally { 12331 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12332 } 12333 12334 /* If the installer passed in a manifest digest, compare it now. */ 12335 if (args.manifestDigest != null) { 12336 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12337 try { 12338 pp.collectManifestDigest(pkg); 12339 } catch (PackageParserException e) { 12340 res.setError("Failed collect during installPackageLI", e); 12341 return; 12342 } finally { 12343 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12344 } 12345 12346 if (DEBUG_INSTALL) { 12347 final String parsedManifest = pkg.manifestDigest == null ? "null" 12348 : pkg.manifestDigest.toString(); 12349 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12350 + parsedManifest); 12351 } 12352 12353 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12354 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12355 return; 12356 } 12357 } else if (DEBUG_INSTALL) { 12358 final String parsedManifest = pkg.manifestDigest == null 12359 ? "null" : pkg.manifestDigest.toString(); 12360 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12361 } 12362 12363 // Get rid of all references to package scan path via parser. 12364 pp = null; 12365 String oldCodePath = null; 12366 boolean systemApp = false; 12367 synchronized (mPackages) { 12368 // Check if installing already existing package 12369 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12370 String oldName = mSettings.mRenamedPackages.get(pkgName); 12371 if (pkg.mOriginalPackages != null 12372 && pkg.mOriginalPackages.contains(oldName) 12373 && mPackages.containsKey(oldName)) { 12374 // This package is derived from an original package, 12375 // and this device has been updating from that original 12376 // name. We must continue using the original name, so 12377 // rename the new package here. 12378 pkg.setPackageName(oldName); 12379 pkgName = pkg.packageName; 12380 replace = true; 12381 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12382 + oldName + " pkgName=" + pkgName); 12383 } else if (mPackages.containsKey(pkgName)) { 12384 // This package, under its official name, already exists 12385 // on the device; we should replace it. 12386 replace = true; 12387 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12388 } 12389 12390 // Prevent apps opting out from runtime permissions 12391 if (replace) { 12392 PackageParser.Package oldPackage = mPackages.get(pkgName); 12393 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12394 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12395 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12396 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12397 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12398 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12399 + " doesn't support runtime permissions but the old" 12400 + " target SDK " + oldTargetSdk + " does."); 12401 return; 12402 } 12403 } 12404 } 12405 12406 PackageSetting ps = mSettings.mPackages.get(pkgName); 12407 if (ps != null) { 12408 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12409 12410 // Quick sanity check that we're signed correctly if updating; 12411 // we'll check this again later when scanning, but we want to 12412 // bail early here before tripping over redefined permissions. 12413 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12414 if (!checkUpgradeKeySetLP(ps, pkg)) { 12415 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12416 + pkg.packageName + " upgrade keys do not match the " 12417 + "previously installed version"); 12418 return; 12419 } 12420 } else { 12421 try { 12422 verifySignaturesLP(ps, pkg); 12423 } catch (PackageManagerException e) { 12424 res.setError(e.error, e.getMessage()); 12425 return; 12426 } 12427 } 12428 12429 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12430 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12431 systemApp = (ps.pkg.applicationInfo.flags & 12432 ApplicationInfo.FLAG_SYSTEM) != 0; 12433 } 12434 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12435 } 12436 12437 // Check whether the newly-scanned package wants to define an already-defined perm 12438 int N = pkg.permissions.size(); 12439 for (int i = N-1; i >= 0; i--) { 12440 PackageParser.Permission perm = pkg.permissions.get(i); 12441 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12442 if (bp != null) { 12443 // If the defining package is signed with our cert, it's okay. This 12444 // also includes the "updating the same package" case, of course. 12445 // "updating same package" could also involve key-rotation. 12446 final boolean sigsOk; 12447 if (bp.sourcePackage.equals(pkg.packageName) 12448 && (bp.packageSetting instanceof PackageSetting) 12449 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12450 scanFlags))) { 12451 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12452 } else { 12453 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12454 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12455 } 12456 if (!sigsOk) { 12457 // If the owning package is the system itself, we log but allow 12458 // install to proceed; we fail the install on all other permission 12459 // redefinitions. 12460 if (!bp.sourcePackage.equals("android")) { 12461 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12462 + pkg.packageName + " attempting to redeclare permission " 12463 + perm.info.name + " already owned by " + bp.sourcePackage); 12464 res.origPermission = perm.info.name; 12465 res.origPackage = bp.sourcePackage; 12466 return; 12467 } else { 12468 Slog.w(TAG, "Package " + pkg.packageName 12469 + " attempting to redeclare system permission " 12470 + perm.info.name + "; ignoring new declaration"); 12471 pkg.permissions.remove(i); 12472 } 12473 } 12474 } 12475 } 12476 12477 } 12478 12479 if (systemApp && onExternal) { 12480 // Disable updates to system apps on sdcard 12481 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12482 "Cannot install updates to system apps on sdcard"); 12483 return; 12484 } 12485 12486 if (args.move != null) { 12487 // We did an in-place move, so dex is ready to roll 12488 scanFlags |= SCAN_NO_DEX; 12489 scanFlags |= SCAN_MOVE; 12490 12491 synchronized (mPackages) { 12492 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12493 if (ps == null) { 12494 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12495 "Missing settings for moved package " + pkgName); 12496 } 12497 12498 // We moved the entire application as-is, so bring over the 12499 // previously derived ABI information. 12500 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12501 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12502 } 12503 12504 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12505 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12506 scanFlags |= SCAN_NO_DEX; 12507 12508 try { 12509 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12510 true /* extract libs */); 12511 } catch (PackageManagerException pme) { 12512 Slog.e(TAG, "Error deriving application ABI", pme); 12513 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12514 return; 12515 } 12516 } 12517 12518 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12519 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12520 return; 12521 } 12522 12523 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12524 12525 if (replace) { 12526 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12527 installerPackageName, volumeUuid, res); 12528 } else { 12529 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12530 args.user, installerPackageName, volumeUuid, res); 12531 } 12532 synchronized (mPackages) { 12533 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12534 if (ps != null) { 12535 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12536 } 12537 } 12538 } 12539 12540 private void startIntentFilterVerifications(int userId, boolean replacing, 12541 PackageParser.Package pkg) { 12542 if (mIntentFilterVerifierComponent == null) { 12543 Slog.w(TAG, "No IntentFilter verification will not be done as " 12544 + "there is no IntentFilterVerifier available!"); 12545 return; 12546 } 12547 12548 final int verifierUid = getPackageUid( 12549 mIntentFilterVerifierComponent.getPackageName(), 12550 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12551 12552 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12553 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12554 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12555 mHandler.sendMessage(msg); 12556 } 12557 12558 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12559 PackageParser.Package pkg) { 12560 int size = pkg.activities.size(); 12561 if (size == 0) { 12562 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12563 "No activity, so no need to verify any IntentFilter!"); 12564 return; 12565 } 12566 12567 final boolean hasDomainURLs = hasDomainURLs(pkg); 12568 if (!hasDomainURLs) { 12569 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12570 "No domain URLs, so no need to verify any IntentFilter!"); 12571 return; 12572 } 12573 12574 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12575 + " if any IntentFilter from the " + size 12576 + " Activities needs verification ..."); 12577 12578 int count = 0; 12579 final String packageName = pkg.packageName; 12580 12581 synchronized (mPackages) { 12582 // If this is a new install and we see that we've already run verification for this 12583 // package, we have nothing to do: it means the state was restored from backup. 12584 if (!replacing) { 12585 IntentFilterVerificationInfo ivi = 12586 mSettings.getIntentFilterVerificationLPr(packageName); 12587 if (ivi != null) { 12588 if (DEBUG_DOMAIN_VERIFICATION) { 12589 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12590 + ivi.getStatusString()); 12591 } 12592 return; 12593 } 12594 } 12595 12596 // If any filters need to be verified, then all need to be. 12597 boolean needToVerify = false; 12598 for (PackageParser.Activity a : pkg.activities) { 12599 for (ActivityIntentInfo filter : a.intents) { 12600 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12601 if (DEBUG_DOMAIN_VERIFICATION) { 12602 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12603 } 12604 needToVerify = true; 12605 break; 12606 } 12607 } 12608 } 12609 12610 if (needToVerify) { 12611 final int verificationId = mIntentFilterVerificationToken++; 12612 for (PackageParser.Activity a : pkg.activities) { 12613 for (ActivityIntentInfo filter : a.intents) { 12614 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12615 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12616 "Verification needed for IntentFilter:" + filter.toString()); 12617 mIntentFilterVerifier.addOneIntentFilterVerification( 12618 verifierUid, userId, verificationId, filter, packageName); 12619 count++; 12620 } 12621 } 12622 } 12623 } 12624 } 12625 12626 if (count > 0) { 12627 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12628 + " IntentFilter verification" + (count > 1 ? "s" : "") 12629 + " for userId:" + userId); 12630 mIntentFilterVerifier.startVerifications(userId); 12631 } else { 12632 if (DEBUG_DOMAIN_VERIFICATION) { 12633 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12634 } 12635 } 12636 } 12637 12638 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12639 final ComponentName cn = filter.activity.getComponentName(); 12640 final String packageName = cn.getPackageName(); 12641 12642 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12643 packageName); 12644 if (ivi == null) { 12645 return true; 12646 } 12647 int status = ivi.getStatus(); 12648 switch (status) { 12649 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12650 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12651 return true; 12652 12653 default: 12654 // Nothing to do 12655 return false; 12656 } 12657 } 12658 12659 private static boolean isMultiArch(PackageSetting ps) { 12660 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12661 } 12662 12663 private static boolean isMultiArch(ApplicationInfo info) { 12664 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12665 } 12666 12667 private static boolean isExternal(PackageParser.Package pkg) { 12668 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12669 } 12670 12671 private static boolean isExternal(PackageSetting ps) { 12672 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12673 } 12674 12675 private static boolean isExternal(ApplicationInfo info) { 12676 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12677 } 12678 12679 private static boolean isSystemApp(PackageParser.Package pkg) { 12680 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12681 } 12682 12683 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12684 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12685 } 12686 12687 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12688 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12689 } 12690 12691 private static boolean isSystemApp(PackageSetting ps) { 12692 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12693 } 12694 12695 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12696 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12697 } 12698 12699 private int packageFlagsToInstallFlags(PackageSetting ps) { 12700 int installFlags = 0; 12701 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12702 // This existing package was an external ASEC install when we have 12703 // the external flag without a UUID 12704 installFlags |= PackageManager.INSTALL_EXTERNAL; 12705 } 12706 if (ps.isForwardLocked()) { 12707 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12708 } 12709 return installFlags; 12710 } 12711 12712 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12713 if (isExternal(pkg)) { 12714 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12715 return StorageManager.UUID_PRIMARY_PHYSICAL; 12716 } else { 12717 return pkg.volumeUuid; 12718 } 12719 } else { 12720 return StorageManager.UUID_PRIVATE_INTERNAL; 12721 } 12722 } 12723 12724 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12725 if (isExternal(pkg)) { 12726 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12727 return mSettings.getExternalVersion(); 12728 } else { 12729 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12730 } 12731 } else { 12732 return mSettings.getInternalVersion(); 12733 } 12734 } 12735 12736 private void deleteTempPackageFiles() { 12737 final FilenameFilter filter = new FilenameFilter() { 12738 public boolean accept(File dir, String name) { 12739 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12740 } 12741 }; 12742 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12743 file.delete(); 12744 } 12745 } 12746 12747 @Override 12748 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12749 int flags) { 12750 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12751 flags); 12752 } 12753 12754 @Override 12755 public void deletePackage(final String packageName, 12756 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12757 mContext.enforceCallingOrSelfPermission( 12758 android.Manifest.permission.DELETE_PACKAGES, null); 12759 Preconditions.checkNotNull(packageName); 12760 Preconditions.checkNotNull(observer); 12761 final int uid = Binder.getCallingUid(); 12762 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 12763 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 12764 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 12765 mContext.enforceCallingPermission( 12766 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12767 "deletePackage for user " + userId); 12768 } 12769 12770 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12771 try { 12772 observer.onPackageDeleted(packageName, 12773 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12774 } catch (RemoteException re) { 12775 } 12776 return; 12777 } 12778 12779 for (int currentUserId : users) { 12780 if (getBlockUninstallForUser(packageName, currentUserId)) { 12781 try { 12782 observer.onPackageDeleted(packageName, 12783 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 12784 } catch (RemoteException re) { 12785 } 12786 return; 12787 } 12788 } 12789 12790 if (DEBUG_REMOVE) { 12791 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12792 } 12793 // Queue up an async operation since the package deletion may take a little while. 12794 mHandler.post(new Runnable() { 12795 public void run() { 12796 mHandler.removeCallbacks(this); 12797 final int returnCode = deletePackageX(packageName, userId, flags); 12798 try { 12799 observer.onPackageDeleted(packageName, returnCode, null); 12800 } catch (RemoteException e) { 12801 Log.i(TAG, "Observer no longer exists."); 12802 } //end catch 12803 } //end run 12804 }); 12805 } 12806 12807 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12808 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12809 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12810 try { 12811 if (dpm != null) { 12812 // Does the package contains the device owner? 12813 if (dpm.isDeviceOwnerPackage(packageName)) { 12814 return true; 12815 } 12816 // Does it contain a device admin for any user? 12817 int[] users; 12818 if (userId == UserHandle.USER_ALL) { 12819 users = sUserManager.getUserIds(); 12820 } else { 12821 users = new int[]{userId}; 12822 } 12823 for (int i = 0; i < users.length; ++i) { 12824 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12825 return true; 12826 } 12827 } 12828 } 12829 } catch (RemoteException e) { 12830 } 12831 return false; 12832 } 12833 12834 /** 12835 * This method is an internal method that could be get invoked either 12836 * to delete an installed package or to clean up a failed installation. 12837 * After deleting an installed package, a broadcast is sent to notify any 12838 * listeners that the package has been installed. For cleaning up a failed 12839 * installation, the broadcast is not necessary since the package's 12840 * installation wouldn't have sent the initial broadcast either 12841 * The key steps in deleting a package are 12842 * deleting the package information in internal structures like mPackages, 12843 * deleting the packages base directories through installd 12844 * updating mSettings to reflect current status 12845 * persisting settings for later use 12846 * sending a broadcast if necessary 12847 */ 12848 private int deletePackageX(String packageName, int userId, int flags) { 12849 final PackageRemovedInfo info = new PackageRemovedInfo(); 12850 final boolean res; 12851 12852 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12853 ? UserHandle.ALL : new UserHandle(userId); 12854 12855 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12856 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12857 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12858 } 12859 12860 boolean removedForAllUsers = false; 12861 boolean systemUpdate = false; 12862 12863 // for the uninstall-updates case and restricted profiles, remember the per- 12864 // userhandle installed state 12865 int[] allUsers; 12866 boolean[] perUserInstalled; 12867 synchronized (mPackages) { 12868 PackageSetting ps = mSettings.mPackages.get(packageName); 12869 allUsers = sUserManager.getUserIds(); 12870 perUserInstalled = new boolean[allUsers.length]; 12871 for (int i = 0; i < allUsers.length; i++) { 12872 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12873 } 12874 } 12875 12876 synchronized (mInstallLock) { 12877 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12878 res = deletePackageLI(packageName, removeForUser, 12879 true, allUsers, perUserInstalled, 12880 flags | REMOVE_CHATTY, info, true); 12881 systemUpdate = info.isRemovedPackageSystemUpdate; 12882 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12883 removedForAllUsers = true; 12884 } 12885 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12886 + " removedForAllUsers=" + removedForAllUsers); 12887 } 12888 12889 if (res) { 12890 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12891 12892 // If the removed package was a system update, the old system package 12893 // was re-enabled; we need to broadcast this information 12894 if (systemUpdate) { 12895 Bundle extras = new Bundle(1); 12896 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12897 ? info.removedAppId : info.uid); 12898 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12899 12900 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12901 extras, null, null, null); 12902 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12903 extras, null, null, null); 12904 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12905 null, packageName, null, null); 12906 } 12907 } 12908 // Force a gc here. 12909 Runtime.getRuntime().gc(); 12910 // Delete the resources here after sending the broadcast to let 12911 // other processes clean up before deleting resources. 12912 if (info.args != null) { 12913 synchronized (mInstallLock) { 12914 info.args.doPostDeleteLI(true); 12915 } 12916 } 12917 12918 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12919 } 12920 12921 class PackageRemovedInfo { 12922 String removedPackage; 12923 int uid = -1; 12924 int removedAppId = -1; 12925 int[] removedUsers = null; 12926 boolean isRemovedPackageSystemUpdate = false; 12927 // Clean up resources deleted packages. 12928 InstallArgs args = null; 12929 12930 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12931 Bundle extras = new Bundle(1); 12932 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12933 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12934 if (replacing) { 12935 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12936 } 12937 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12938 if (removedPackage != null) { 12939 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12940 extras, null, null, removedUsers); 12941 if (fullRemove && !replacing) { 12942 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12943 extras, null, null, removedUsers); 12944 } 12945 } 12946 if (removedAppId >= 0) { 12947 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12948 removedUsers); 12949 } 12950 } 12951 } 12952 12953 /* 12954 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12955 * flag is not set, the data directory is removed as well. 12956 * make sure this flag is set for partially installed apps. If not its meaningless to 12957 * delete a partially installed application. 12958 */ 12959 private void removePackageDataLI(PackageSetting ps, 12960 int[] allUserHandles, boolean[] perUserInstalled, 12961 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12962 String packageName = ps.name; 12963 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12964 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12965 // Retrieve object to delete permissions for shared user later on 12966 final PackageSetting deletedPs; 12967 // reader 12968 synchronized (mPackages) { 12969 deletedPs = mSettings.mPackages.get(packageName); 12970 if (outInfo != null) { 12971 outInfo.removedPackage = packageName; 12972 outInfo.removedUsers = deletedPs != null 12973 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12974 : null; 12975 } 12976 } 12977 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12978 removeDataDirsLI(ps.volumeUuid, packageName); 12979 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12980 } 12981 // writer 12982 synchronized (mPackages) { 12983 if (deletedPs != null) { 12984 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12985 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12986 clearDefaultBrowserIfNeeded(packageName); 12987 if (outInfo != null) { 12988 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12989 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12990 } 12991 updatePermissionsLPw(deletedPs.name, null, 0); 12992 if (deletedPs.sharedUser != null) { 12993 // Remove permissions associated with package. Since runtime 12994 // permissions are per user we have to kill the removed package 12995 // or packages running under the shared user of the removed 12996 // package if revoking the permissions requested only by the removed 12997 // package is successful and this causes a change in gids. 12998 for (int userId : UserManagerService.getInstance().getUserIds()) { 12999 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13000 userId); 13001 if (userIdToKill == UserHandle.USER_ALL 13002 || userIdToKill >= UserHandle.USER_SYSTEM) { 13003 // If gids changed for this user, kill all affected packages. 13004 mHandler.post(new Runnable() { 13005 @Override 13006 public void run() { 13007 // This has to happen with no lock held. 13008 killApplication(deletedPs.name, deletedPs.appId, 13009 KILL_APP_REASON_GIDS_CHANGED); 13010 } 13011 }); 13012 break; 13013 } 13014 } 13015 } 13016 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13017 } 13018 // make sure to preserve per-user disabled state if this removal was just 13019 // a downgrade of a system app to the factory package 13020 if (allUserHandles != null && perUserInstalled != null) { 13021 if (DEBUG_REMOVE) { 13022 Slog.d(TAG, "Propagating install state across downgrade"); 13023 } 13024 for (int i = 0; i < allUserHandles.length; i++) { 13025 if (DEBUG_REMOVE) { 13026 Slog.d(TAG, " user " + allUserHandles[i] 13027 + " => " + perUserInstalled[i]); 13028 } 13029 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13030 } 13031 } 13032 } 13033 // can downgrade to reader 13034 if (writeSettings) { 13035 // Save settings now 13036 mSettings.writeLPr(); 13037 } 13038 } 13039 if (outInfo != null) { 13040 // A user ID was deleted here. Go through all users and remove it 13041 // from KeyStore. 13042 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13043 } 13044 } 13045 13046 static boolean locationIsPrivileged(File path) { 13047 try { 13048 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13049 .getCanonicalPath(); 13050 return path.getCanonicalPath().startsWith(privilegedAppDir); 13051 } catch (IOException e) { 13052 Slog.e(TAG, "Unable to access code path " + path); 13053 } 13054 return false; 13055 } 13056 13057 /* 13058 * Tries to delete system package. 13059 */ 13060 private boolean deleteSystemPackageLI(PackageSetting newPs, 13061 int[] allUserHandles, boolean[] perUserInstalled, 13062 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13063 final boolean applyUserRestrictions 13064 = (allUserHandles != null) && (perUserInstalled != null); 13065 PackageSetting disabledPs = null; 13066 // Confirm if the system package has been updated 13067 // An updated system app can be deleted. This will also have to restore 13068 // the system pkg from system partition 13069 // reader 13070 synchronized (mPackages) { 13071 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13072 } 13073 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13074 + " disabledPs=" + disabledPs); 13075 if (disabledPs == null) { 13076 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13077 return false; 13078 } else if (DEBUG_REMOVE) { 13079 Slog.d(TAG, "Deleting system pkg from data partition"); 13080 } 13081 if (DEBUG_REMOVE) { 13082 if (applyUserRestrictions) { 13083 Slog.d(TAG, "Remembering install states:"); 13084 for (int i = 0; i < allUserHandles.length; i++) { 13085 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13086 } 13087 } 13088 } 13089 // Delete the updated package 13090 outInfo.isRemovedPackageSystemUpdate = true; 13091 if (disabledPs.versionCode < newPs.versionCode) { 13092 // Delete data for downgrades 13093 flags &= ~PackageManager.DELETE_KEEP_DATA; 13094 } else { 13095 // Preserve data by setting flag 13096 flags |= PackageManager.DELETE_KEEP_DATA; 13097 } 13098 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13099 allUserHandles, perUserInstalled, outInfo, writeSettings); 13100 if (!ret) { 13101 return false; 13102 } 13103 // writer 13104 synchronized (mPackages) { 13105 // Reinstate the old system package 13106 mSettings.enableSystemPackageLPw(newPs.name); 13107 // Remove any native libraries from the upgraded package. 13108 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13109 } 13110 // Install the system package 13111 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13112 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13113 if (locationIsPrivileged(disabledPs.codePath)) { 13114 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13115 } 13116 13117 final PackageParser.Package newPkg; 13118 try { 13119 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13120 } catch (PackageManagerException e) { 13121 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13122 return false; 13123 } 13124 13125 // writer 13126 synchronized (mPackages) { 13127 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13128 13129 // Propagate the permissions state as we do not want to drop on the floor 13130 // runtime permissions. The update permissions method below will take 13131 // care of removing obsolete permissions and grant install permissions. 13132 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13133 updatePermissionsLPw(newPkg.packageName, newPkg, 13134 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13135 13136 if (applyUserRestrictions) { 13137 if (DEBUG_REMOVE) { 13138 Slog.d(TAG, "Propagating install state across reinstall"); 13139 } 13140 for (int i = 0; i < allUserHandles.length; i++) { 13141 if (DEBUG_REMOVE) { 13142 Slog.d(TAG, " user " + allUserHandles[i] 13143 + " => " + perUserInstalled[i]); 13144 } 13145 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13146 13147 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13148 } 13149 // Regardless of writeSettings we need to ensure that this restriction 13150 // state propagation is persisted 13151 mSettings.writeAllUsersPackageRestrictionsLPr(); 13152 } 13153 // can downgrade to reader here 13154 if (writeSettings) { 13155 mSettings.writeLPr(); 13156 } 13157 } 13158 return true; 13159 } 13160 13161 private boolean deleteInstalledPackageLI(PackageSetting ps, 13162 boolean deleteCodeAndResources, int flags, 13163 int[] allUserHandles, boolean[] perUserInstalled, 13164 PackageRemovedInfo outInfo, boolean writeSettings) { 13165 if (outInfo != null) { 13166 outInfo.uid = ps.appId; 13167 } 13168 13169 // Delete package data from internal structures and also remove data if flag is set 13170 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13171 13172 // Delete application code and resources 13173 if (deleteCodeAndResources && (outInfo != null)) { 13174 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13175 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13176 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13177 } 13178 return true; 13179 } 13180 13181 @Override 13182 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13183 int userId) { 13184 mContext.enforceCallingOrSelfPermission( 13185 android.Manifest.permission.DELETE_PACKAGES, null); 13186 synchronized (mPackages) { 13187 PackageSetting ps = mSettings.mPackages.get(packageName); 13188 if (ps == null) { 13189 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13190 return false; 13191 } 13192 if (!ps.getInstalled(userId)) { 13193 // Can't block uninstall for an app that is not installed or enabled. 13194 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13195 return false; 13196 } 13197 ps.setBlockUninstall(blockUninstall, userId); 13198 mSettings.writePackageRestrictionsLPr(userId); 13199 } 13200 return true; 13201 } 13202 13203 @Override 13204 public boolean getBlockUninstallForUser(String packageName, int userId) { 13205 synchronized (mPackages) { 13206 PackageSetting ps = mSettings.mPackages.get(packageName); 13207 if (ps == null) { 13208 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13209 return false; 13210 } 13211 return ps.getBlockUninstall(userId); 13212 } 13213 } 13214 13215 /* 13216 * This method handles package deletion in general 13217 */ 13218 private boolean deletePackageLI(String packageName, UserHandle user, 13219 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13220 int flags, PackageRemovedInfo outInfo, 13221 boolean writeSettings) { 13222 if (packageName == null) { 13223 Slog.w(TAG, "Attempt to delete null packageName."); 13224 return false; 13225 } 13226 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13227 PackageSetting ps; 13228 boolean dataOnly = false; 13229 int removeUser = -1; 13230 int appId = -1; 13231 synchronized (mPackages) { 13232 ps = mSettings.mPackages.get(packageName); 13233 if (ps == null) { 13234 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13235 return false; 13236 } 13237 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13238 && user.getIdentifier() != UserHandle.USER_ALL) { 13239 // The caller is asking that the package only be deleted for a single 13240 // user. To do this, we just mark its uninstalled state and delete 13241 // its data. If this is a system app, we only allow this to happen if 13242 // they have set the special DELETE_SYSTEM_APP which requests different 13243 // semantics than normal for uninstalling system apps. 13244 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13245 final int userId = user.getIdentifier(); 13246 ps.setUserState(userId, 13247 COMPONENT_ENABLED_STATE_DEFAULT, 13248 false, //installed 13249 true, //stopped 13250 true, //notLaunched 13251 false, //hidden 13252 null, null, null, 13253 false, // blockUninstall 13254 ps.readUserState(userId).domainVerificationStatus, 0); 13255 if (!isSystemApp(ps)) { 13256 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13257 // Other user still have this package installed, so all 13258 // we need to do is clear this user's data and save that 13259 // it is uninstalled. 13260 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13261 removeUser = user.getIdentifier(); 13262 appId = ps.appId; 13263 scheduleWritePackageRestrictionsLocked(removeUser); 13264 } else { 13265 // We need to set it back to 'installed' so the uninstall 13266 // broadcasts will be sent correctly. 13267 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13268 ps.setInstalled(true, user.getIdentifier()); 13269 } 13270 } else { 13271 // This is a system app, so we assume that the 13272 // other users still have this package installed, so all 13273 // we need to do is clear this user's data and save that 13274 // it is uninstalled. 13275 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13276 removeUser = user.getIdentifier(); 13277 appId = ps.appId; 13278 scheduleWritePackageRestrictionsLocked(removeUser); 13279 } 13280 } 13281 } 13282 13283 if (removeUser >= 0) { 13284 // From above, we determined that we are deleting this only 13285 // for a single user. Continue the work here. 13286 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13287 if (outInfo != null) { 13288 outInfo.removedPackage = packageName; 13289 outInfo.removedAppId = appId; 13290 outInfo.removedUsers = new int[] {removeUser}; 13291 } 13292 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13293 removeKeystoreDataIfNeeded(removeUser, appId); 13294 schedulePackageCleaning(packageName, removeUser, false); 13295 synchronized (mPackages) { 13296 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13297 scheduleWritePackageRestrictionsLocked(removeUser); 13298 } 13299 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13300 } 13301 return true; 13302 } 13303 13304 if (dataOnly) { 13305 // Delete application data first 13306 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13307 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13308 return true; 13309 } 13310 13311 boolean ret = false; 13312 if (isSystemApp(ps)) { 13313 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13314 // When an updated system application is deleted we delete the existing resources as well and 13315 // fall back to existing code in system partition 13316 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13317 flags, outInfo, writeSettings); 13318 } else { 13319 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13320 // Kill application pre-emptively especially for apps on sd. 13321 killApplication(packageName, ps.appId, "uninstall pkg"); 13322 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13323 allUserHandles, perUserInstalled, 13324 outInfo, writeSettings); 13325 } 13326 13327 return ret; 13328 } 13329 13330 private final class ClearStorageConnection implements ServiceConnection { 13331 IMediaContainerService mContainerService; 13332 13333 @Override 13334 public void onServiceConnected(ComponentName name, IBinder service) { 13335 synchronized (this) { 13336 mContainerService = IMediaContainerService.Stub.asInterface(service); 13337 notifyAll(); 13338 } 13339 } 13340 13341 @Override 13342 public void onServiceDisconnected(ComponentName name) { 13343 } 13344 } 13345 13346 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13347 final boolean mounted; 13348 if (Environment.isExternalStorageEmulated()) { 13349 mounted = true; 13350 } else { 13351 final String status = Environment.getExternalStorageState(); 13352 13353 mounted = status.equals(Environment.MEDIA_MOUNTED) 13354 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13355 } 13356 13357 if (!mounted) { 13358 return; 13359 } 13360 13361 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13362 int[] users; 13363 if (userId == UserHandle.USER_ALL) { 13364 users = sUserManager.getUserIds(); 13365 } else { 13366 users = new int[] { userId }; 13367 } 13368 final ClearStorageConnection conn = new ClearStorageConnection(); 13369 if (mContext.bindServiceAsUser( 13370 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13371 try { 13372 for (int curUser : users) { 13373 long timeout = SystemClock.uptimeMillis() + 5000; 13374 synchronized (conn) { 13375 long now = SystemClock.uptimeMillis(); 13376 while (conn.mContainerService == null && now < timeout) { 13377 try { 13378 conn.wait(timeout - now); 13379 } catch (InterruptedException e) { 13380 } 13381 } 13382 } 13383 if (conn.mContainerService == null) { 13384 return; 13385 } 13386 13387 final UserEnvironment userEnv = new UserEnvironment(curUser); 13388 clearDirectory(conn.mContainerService, 13389 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13390 if (allData) { 13391 clearDirectory(conn.mContainerService, 13392 userEnv.buildExternalStorageAppDataDirs(packageName)); 13393 clearDirectory(conn.mContainerService, 13394 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13395 } 13396 } 13397 } finally { 13398 mContext.unbindService(conn); 13399 } 13400 } 13401 } 13402 13403 @Override 13404 public void clearApplicationUserData(final String packageName, 13405 final IPackageDataObserver observer, final int userId) { 13406 mContext.enforceCallingOrSelfPermission( 13407 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13408 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13409 // Queue up an async operation since the package deletion may take a little while. 13410 mHandler.post(new Runnable() { 13411 public void run() { 13412 mHandler.removeCallbacks(this); 13413 final boolean succeeded; 13414 synchronized (mInstallLock) { 13415 succeeded = clearApplicationUserDataLI(packageName, userId); 13416 } 13417 clearExternalStorageDataSync(packageName, userId, true); 13418 if (succeeded) { 13419 // invoke DeviceStorageMonitor's update method to clear any notifications 13420 DeviceStorageMonitorInternal 13421 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13422 if (dsm != null) { 13423 dsm.checkMemory(); 13424 } 13425 } 13426 if(observer != null) { 13427 try { 13428 observer.onRemoveCompleted(packageName, succeeded); 13429 } catch (RemoteException e) { 13430 Log.i(TAG, "Observer no longer exists."); 13431 } 13432 } //end if observer 13433 } //end run 13434 }); 13435 } 13436 13437 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13438 if (packageName == null) { 13439 Slog.w(TAG, "Attempt to delete null packageName."); 13440 return false; 13441 } 13442 13443 // Try finding details about the requested package 13444 PackageParser.Package pkg; 13445 synchronized (mPackages) { 13446 pkg = mPackages.get(packageName); 13447 if (pkg == null) { 13448 final PackageSetting ps = mSettings.mPackages.get(packageName); 13449 if (ps != null) { 13450 pkg = ps.pkg; 13451 } 13452 } 13453 13454 if (pkg == null) { 13455 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13456 return false; 13457 } 13458 13459 PackageSetting ps = (PackageSetting) pkg.mExtras; 13460 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13461 } 13462 13463 // Always delete data directories for package, even if we found no other 13464 // record of app. This helps users recover from UID mismatches without 13465 // resorting to a full data wipe. 13466 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13467 if (retCode < 0) { 13468 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13469 return false; 13470 } 13471 13472 final int appId = pkg.applicationInfo.uid; 13473 removeKeystoreDataIfNeeded(userId, appId); 13474 13475 // Create a native library symlink only if we have native libraries 13476 // and if the native libraries are 32 bit libraries. We do not provide 13477 // this symlink for 64 bit libraries. 13478 if (pkg.applicationInfo.primaryCpuAbi != null && 13479 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13480 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13481 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13482 nativeLibPath, userId) < 0) { 13483 Slog.w(TAG, "Failed linking native library dir"); 13484 return false; 13485 } 13486 } 13487 13488 return true; 13489 } 13490 13491 /** 13492 * Reverts user permission state changes (permissions and flags) in 13493 * all packages for a given user. 13494 * 13495 * @param userId The device user for which to do a reset. 13496 */ 13497 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13498 final int packageCount = mPackages.size(); 13499 for (int i = 0; i < packageCount; i++) { 13500 PackageParser.Package pkg = mPackages.valueAt(i); 13501 PackageSetting ps = (PackageSetting) pkg.mExtras; 13502 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13503 } 13504 } 13505 13506 /** 13507 * Reverts user permission state changes (permissions and flags). 13508 * 13509 * @param ps The package for which to reset. 13510 * @param userId The device user for which to do a reset. 13511 */ 13512 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13513 final PackageSetting ps, final int userId) { 13514 if (ps.pkg == null) { 13515 return; 13516 } 13517 13518 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13519 | FLAG_PERMISSION_USER_FIXED 13520 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13521 13522 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13523 | FLAG_PERMISSION_POLICY_FIXED; 13524 13525 boolean writeInstallPermissions = false; 13526 boolean writeRuntimePermissions = false; 13527 13528 final int permissionCount = ps.pkg.requestedPermissions.size(); 13529 for (int i = 0; i < permissionCount; i++) { 13530 String permission = ps.pkg.requestedPermissions.get(i); 13531 13532 BasePermission bp = mSettings.mPermissions.get(permission); 13533 if (bp == null) { 13534 continue; 13535 } 13536 13537 // If shared user we just reset the state to which only this app contributed. 13538 if (ps.sharedUser != null) { 13539 boolean used = false; 13540 final int packageCount = ps.sharedUser.packages.size(); 13541 for (int j = 0; j < packageCount; j++) { 13542 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13543 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13544 && pkg.pkg.requestedPermissions.contains(permission)) { 13545 used = true; 13546 break; 13547 } 13548 } 13549 if (used) { 13550 continue; 13551 } 13552 } 13553 13554 PermissionsState permissionsState = ps.getPermissionsState(); 13555 13556 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13557 13558 // Always clear the user settable flags. 13559 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13560 bp.name) != null; 13561 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13562 if (hasInstallState) { 13563 writeInstallPermissions = true; 13564 } else { 13565 writeRuntimePermissions = true; 13566 } 13567 } 13568 13569 // Below is only runtime permission handling. 13570 if (!bp.isRuntime()) { 13571 continue; 13572 } 13573 13574 // Never clobber system or policy. 13575 if ((oldFlags & policyOrSystemFlags) != 0) { 13576 continue; 13577 } 13578 13579 // If this permission was granted by default, make sure it is. 13580 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13581 if (permissionsState.grantRuntimePermission(bp, userId) 13582 != PERMISSION_OPERATION_FAILURE) { 13583 writeRuntimePermissions = true; 13584 } 13585 } else { 13586 // Otherwise, reset the permission. 13587 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13588 switch (revokeResult) { 13589 case PERMISSION_OPERATION_SUCCESS: { 13590 writeRuntimePermissions = true; 13591 } break; 13592 13593 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13594 writeRuntimePermissions = true; 13595 final int appId = ps.appId; 13596 mHandler.post(new Runnable() { 13597 @Override 13598 public void run() { 13599 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13600 } 13601 }); 13602 } break; 13603 } 13604 } 13605 } 13606 13607 // Synchronously write as we are taking permissions away. 13608 if (writeRuntimePermissions) { 13609 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13610 } 13611 13612 // Synchronously write as we are taking permissions away. 13613 if (writeInstallPermissions) { 13614 mSettings.writeLPr(); 13615 } 13616 } 13617 13618 /** 13619 * Remove entries from the keystore daemon. Will only remove it if the 13620 * {@code appId} is valid. 13621 */ 13622 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13623 if (appId < 0) { 13624 return; 13625 } 13626 13627 final KeyStore keyStore = KeyStore.getInstance(); 13628 if (keyStore != null) { 13629 if (userId == UserHandle.USER_ALL) { 13630 for (final int individual : sUserManager.getUserIds()) { 13631 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13632 } 13633 } else { 13634 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13635 } 13636 } else { 13637 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13638 } 13639 } 13640 13641 @Override 13642 public void deleteApplicationCacheFiles(final String packageName, 13643 final IPackageDataObserver observer) { 13644 mContext.enforceCallingOrSelfPermission( 13645 android.Manifest.permission.DELETE_CACHE_FILES, null); 13646 // Queue up an async operation since the package deletion may take a little while. 13647 final int userId = UserHandle.getCallingUserId(); 13648 mHandler.post(new Runnable() { 13649 public void run() { 13650 mHandler.removeCallbacks(this); 13651 final boolean succeded; 13652 synchronized (mInstallLock) { 13653 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13654 } 13655 clearExternalStorageDataSync(packageName, userId, false); 13656 if (observer != null) { 13657 try { 13658 observer.onRemoveCompleted(packageName, succeded); 13659 } catch (RemoteException e) { 13660 Log.i(TAG, "Observer no longer exists."); 13661 } 13662 } //end if observer 13663 } //end run 13664 }); 13665 } 13666 13667 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13668 if (packageName == null) { 13669 Slog.w(TAG, "Attempt to delete null packageName."); 13670 return false; 13671 } 13672 PackageParser.Package p; 13673 synchronized (mPackages) { 13674 p = mPackages.get(packageName); 13675 } 13676 if (p == null) { 13677 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13678 return false; 13679 } 13680 final ApplicationInfo applicationInfo = p.applicationInfo; 13681 if (applicationInfo == null) { 13682 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13683 return false; 13684 } 13685 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13686 if (retCode < 0) { 13687 Slog.w(TAG, "Couldn't remove cache files for package: " 13688 + packageName + " u" + userId); 13689 return false; 13690 } 13691 return true; 13692 } 13693 13694 @Override 13695 public void getPackageSizeInfo(final String packageName, int userHandle, 13696 final IPackageStatsObserver observer) { 13697 mContext.enforceCallingOrSelfPermission( 13698 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13699 if (packageName == null) { 13700 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13701 } 13702 13703 PackageStats stats = new PackageStats(packageName, userHandle); 13704 13705 /* 13706 * Queue up an async operation since the package measurement may take a 13707 * little while. 13708 */ 13709 Message msg = mHandler.obtainMessage(INIT_COPY); 13710 msg.obj = new MeasureParams(stats, observer); 13711 mHandler.sendMessage(msg); 13712 } 13713 13714 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13715 PackageStats pStats) { 13716 if (packageName == null) { 13717 Slog.w(TAG, "Attempt to get size of null packageName."); 13718 return false; 13719 } 13720 PackageParser.Package p; 13721 boolean dataOnly = false; 13722 String libDirRoot = null; 13723 String asecPath = null; 13724 PackageSetting ps = null; 13725 synchronized (mPackages) { 13726 p = mPackages.get(packageName); 13727 ps = mSettings.mPackages.get(packageName); 13728 if(p == null) { 13729 dataOnly = true; 13730 if((ps == null) || (ps.pkg == null)) { 13731 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13732 return false; 13733 } 13734 p = ps.pkg; 13735 } 13736 if (ps != null) { 13737 libDirRoot = ps.legacyNativeLibraryPathString; 13738 } 13739 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13740 final long token = Binder.clearCallingIdentity(); 13741 try { 13742 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13743 if (secureContainerId != null) { 13744 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13745 } 13746 } finally { 13747 Binder.restoreCallingIdentity(token); 13748 } 13749 } 13750 } 13751 String publicSrcDir = null; 13752 if(!dataOnly) { 13753 final ApplicationInfo applicationInfo = p.applicationInfo; 13754 if (applicationInfo == null) { 13755 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13756 return false; 13757 } 13758 if (p.isForwardLocked()) { 13759 publicSrcDir = applicationInfo.getBaseResourcePath(); 13760 } 13761 } 13762 // TODO: extend to measure size of split APKs 13763 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13764 // not just the first level. 13765 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13766 // just the primary. 13767 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13768 13769 String apkPath; 13770 File packageDir = new File(p.codePath); 13771 13772 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13773 apkPath = packageDir.getAbsolutePath(); 13774 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13775 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13776 libDirRoot = null; 13777 } 13778 } else { 13779 apkPath = p.baseCodePath; 13780 } 13781 13782 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13783 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13784 if (res < 0) { 13785 return false; 13786 } 13787 13788 // Fix-up for forward-locked applications in ASEC containers. 13789 if (!isExternal(p)) { 13790 pStats.codeSize += pStats.externalCodeSize; 13791 pStats.externalCodeSize = 0L; 13792 } 13793 13794 return true; 13795 } 13796 13797 13798 @Override 13799 public void addPackageToPreferred(String packageName) { 13800 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13801 } 13802 13803 @Override 13804 public void removePackageFromPreferred(String packageName) { 13805 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13806 } 13807 13808 @Override 13809 public List<PackageInfo> getPreferredPackages(int flags) { 13810 return new ArrayList<PackageInfo>(); 13811 } 13812 13813 private int getUidTargetSdkVersionLockedLPr(int uid) { 13814 Object obj = mSettings.getUserIdLPr(uid); 13815 if (obj instanceof SharedUserSetting) { 13816 final SharedUserSetting sus = (SharedUserSetting) obj; 13817 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13818 final Iterator<PackageSetting> it = sus.packages.iterator(); 13819 while (it.hasNext()) { 13820 final PackageSetting ps = it.next(); 13821 if (ps.pkg != null) { 13822 int v = ps.pkg.applicationInfo.targetSdkVersion; 13823 if (v < vers) vers = v; 13824 } 13825 } 13826 return vers; 13827 } else if (obj instanceof PackageSetting) { 13828 final PackageSetting ps = (PackageSetting) obj; 13829 if (ps.pkg != null) { 13830 return ps.pkg.applicationInfo.targetSdkVersion; 13831 } 13832 } 13833 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13834 } 13835 13836 @Override 13837 public void addPreferredActivity(IntentFilter filter, int match, 13838 ComponentName[] set, ComponentName activity, int userId) { 13839 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13840 "Adding preferred"); 13841 } 13842 13843 private void addPreferredActivityInternal(IntentFilter filter, int match, 13844 ComponentName[] set, ComponentName activity, boolean always, int userId, 13845 String opname) { 13846 // writer 13847 int callingUid = Binder.getCallingUid(); 13848 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13849 if (filter.countActions() == 0) { 13850 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13851 return; 13852 } 13853 synchronized (mPackages) { 13854 if (mContext.checkCallingOrSelfPermission( 13855 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13856 != PackageManager.PERMISSION_GRANTED) { 13857 if (getUidTargetSdkVersionLockedLPr(callingUid) 13858 < Build.VERSION_CODES.FROYO) { 13859 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13860 + callingUid); 13861 return; 13862 } 13863 mContext.enforceCallingOrSelfPermission( 13864 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13865 } 13866 13867 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13868 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13869 + userId + ":"); 13870 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13871 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13872 scheduleWritePackageRestrictionsLocked(userId); 13873 } 13874 } 13875 13876 @Override 13877 public void replacePreferredActivity(IntentFilter filter, int match, 13878 ComponentName[] set, ComponentName activity, int userId) { 13879 if (filter.countActions() != 1) { 13880 throw new IllegalArgumentException( 13881 "replacePreferredActivity expects filter to have only 1 action."); 13882 } 13883 if (filter.countDataAuthorities() != 0 13884 || filter.countDataPaths() != 0 13885 || filter.countDataSchemes() > 1 13886 || filter.countDataTypes() != 0) { 13887 throw new IllegalArgumentException( 13888 "replacePreferredActivity expects filter to have no data authorities, " + 13889 "paths, or types; and at most one scheme."); 13890 } 13891 13892 final int callingUid = Binder.getCallingUid(); 13893 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13894 synchronized (mPackages) { 13895 if (mContext.checkCallingOrSelfPermission( 13896 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13897 != PackageManager.PERMISSION_GRANTED) { 13898 if (getUidTargetSdkVersionLockedLPr(callingUid) 13899 < Build.VERSION_CODES.FROYO) { 13900 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13901 + Binder.getCallingUid()); 13902 return; 13903 } 13904 mContext.enforceCallingOrSelfPermission( 13905 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13906 } 13907 13908 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13909 if (pir != null) { 13910 // Get all of the existing entries that exactly match this filter. 13911 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13912 if (existing != null && existing.size() == 1) { 13913 PreferredActivity cur = existing.get(0); 13914 if (DEBUG_PREFERRED) { 13915 Slog.i(TAG, "Checking replace of preferred:"); 13916 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13917 if (!cur.mPref.mAlways) { 13918 Slog.i(TAG, " -- CUR; not mAlways!"); 13919 } else { 13920 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13921 Slog.i(TAG, " -- CUR: mSet=" 13922 + Arrays.toString(cur.mPref.mSetComponents)); 13923 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13924 Slog.i(TAG, " -- NEW: mMatch=" 13925 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13926 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13927 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13928 } 13929 } 13930 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13931 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13932 && cur.mPref.sameSet(set)) { 13933 // Setting the preferred activity to what it happens to be already 13934 if (DEBUG_PREFERRED) { 13935 Slog.i(TAG, "Replacing with same preferred activity " 13936 + cur.mPref.mShortComponent + " for user " 13937 + userId + ":"); 13938 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13939 } 13940 return; 13941 } 13942 } 13943 13944 if (existing != null) { 13945 if (DEBUG_PREFERRED) { 13946 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13947 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13948 } 13949 for (int i = 0; i < existing.size(); i++) { 13950 PreferredActivity pa = existing.get(i); 13951 if (DEBUG_PREFERRED) { 13952 Slog.i(TAG, "Removing existing preferred activity " 13953 + pa.mPref.mComponent + ":"); 13954 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13955 } 13956 pir.removeFilter(pa); 13957 } 13958 } 13959 } 13960 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13961 "Replacing preferred"); 13962 } 13963 } 13964 13965 @Override 13966 public void clearPackagePreferredActivities(String packageName) { 13967 final int uid = Binder.getCallingUid(); 13968 // writer 13969 synchronized (mPackages) { 13970 PackageParser.Package pkg = mPackages.get(packageName); 13971 if (pkg == null || pkg.applicationInfo.uid != uid) { 13972 if (mContext.checkCallingOrSelfPermission( 13973 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13974 != PackageManager.PERMISSION_GRANTED) { 13975 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13976 < Build.VERSION_CODES.FROYO) { 13977 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13978 + Binder.getCallingUid()); 13979 return; 13980 } 13981 mContext.enforceCallingOrSelfPermission( 13982 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13983 } 13984 } 13985 13986 int user = UserHandle.getCallingUserId(); 13987 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13988 scheduleWritePackageRestrictionsLocked(user); 13989 } 13990 } 13991 } 13992 13993 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13994 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13995 ArrayList<PreferredActivity> removed = null; 13996 boolean changed = false; 13997 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13998 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13999 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14000 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14001 continue; 14002 } 14003 Iterator<PreferredActivity> it = pir.filterIterator(); 14004 while (it.hasNext()) { 14005 PreferredActivity pa = it.next(); 14006 // Mark entry for removal only if it matches the package name 14007 // and the entry is of type "always". 14008 if (packageName == null || 14009 (pa.mPref.mComponent.getPackageName().equals(packageName) 14010 && pa.mPref.mAlways)) { 14011 if (removed == null) { 14012 removed = new ArrayList<PreferredActivity>(); 14013 } 14014 removed.add(pa); 14015 } 14016 } 14017 if (removed != null) { 14018 for (int j=0; j<removed.size(); j++) { 14019 PreferredActivity pa = removed.get(j); 14020 pir.removeFilter(pa); 14021 } 14022 changed = true; 14023 } 14024 } 14025 return changed; 14026 } 14027 14028 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14029 private void clearIntentFilterVerificationsLPw(int userId) { 14030 final int packageCount = mPackages.size(); 14031 for (int i = 0; i < packageCount; i++) { 14032 PackageParser.Package pkg = mPackages.valueAt(i); 14033 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14034 } 14035 } 14036 14037 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14038 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14039 if (userId == UserHandle.USER_ALL) { 14040 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14041 sUserManager.getUserIds())) { 14042 for (int oneUserId : sUserManager.getUserIds()) { 14043 scheduleWritePackageRestrictionsLocked(oneUserId); 14044 } 14045 } 14046 } else { 14047 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14048 scheduleWritePackageRestrictionsLocked(userId); 14049 } 14050 } 14051 } 14052 14053 void clearDefaultBrowserIfNeeded(String packageName) { 14054 for (int oneUserId : sUserManager.getUserIds()) { 14055 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14056 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14057 if (packageName.equals(defaultBrowserPackageName)) { 14058 setDefaultBrowserPackageName(null, oneUserId); 14059 } 14060 } 14061 } 14062 14063 @Override 14064 public void resetApplicationPreferences(int userId) { 14065 mContext.enforceCallingOrSelfPermission( 14066 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14067 // writer 14068 synchronized (mPackages) { 14069 final long identity = Binder.clearCallingIdentity(); 14070 try { 14071 clearPackagePreferredActivitiesLPw(null, userId); 14072 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14073 // TODO: We have to reset the default SMS and Phone. This requires 14074 // significant refactoring to keep all default apps in the package 14075 // manager (cleaner but more work) or have the services provide 14076 // callbacks to the package manager to request a default app reset. 14077 applyFactoryDefaultBrowserLPw(userId); 14078 clearIntentFilterVerificationsLPw(userId); 14079 primeDomainVerificationsLPw(userId); 14080 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14081 scheduleWritePackageRestrictionsLocked(userId); 14082 } finally { 14083 Binder.restoreCallingIdentity(identity); 14084 } 14085 } 14086 } 14087 14088 @Override 14089 public int getPreferredActivities(List<IntentFilter> outFilters, 14090 List<ComponentName> outActivities, String packageName) { 14091 14092 int num = 0; 14093 final int userId = UserHandle.getCallingUserId(); 14094 // reader 14095 synchronized (mPackages) { 14096 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14097 if (pir != null) { 14098 final Iterator<PreferredActivity> it = pir.filterIterator(); 14099 while (it.hasNext()) { 14100 final PreferredActivity pa = it.next(); 14101 if (packageName == null 14102 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14103 && pa.mPref.mAlways)) { 14104 if (outFilters != null) { 14105 outFilters.add(new IntentFilter(pa)); 14106 } 14107 if (outActivities != null) { 14108 outActivities.add(pa.mPref.mComponent); 14109 } 14110 } 14111 } 14112 } 14113 } 14114 14115 return num; 14116 } 14117 14118 @Override 14119 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14120 int userId) { 14121 int callingUid = Binder.getCallingUid(); 14122 if (callingUid != Process.SYSTEM_UID) { 14123 throw new SecurityException( 14124 "addPersistentPreferredActivity can only be run by the system"); 14125 } 14126 if (filter.countActions() == 0) { 14127 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14128 return; 14129 } 14130 synchronized (mPackages) { 14131 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14132 " :"); 14133 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14134 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14135 new PersistentPreferredActivity(filter, activity)); 14136 scheduleWritePackageRestrictionsLocked(userId); 14137 } 14138 } 14139 14140 @Override 14141 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14142 int callingUid = Binder.getCallingUid(); 14143 if (callingUid != Process.SYSTEM_UID) { 14144 throw new SecurityException( 14145 "clearPackagePersistentPreferredActivities can only be run by the system"); 14146 } 14147 ArrayList<PersistentPreferredActivity> removed = null; 14148 boolean changed = false; 14149 synchronized (mPackages) { 14150 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14151 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14152 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14153 .valueAt(i); 14154 if (userId != thisUserId) { 14155 continue; 14156 } 14157 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14158 while (it.hasNext()) { 14159 PersistentPreferredActivity ppa = it.next(); 14160 // Mark entry for removal only if it matches the package name. 14161 if (ppa.mComponent.getPackageName().equals(packageName)) { 14162 if (removed == null) { 14163 removed = new ArrayList<PersistentPreferredActivity>(); 14164 } 14165 removed.add(ppa); 14166 } 14167 } 14168 if (removed != null) { 14169 for (int j=0; j<removed.size(); j++) { 14170 PersistentPreferredActivity ppa = removed.get(j); 14171 ppir.removeFilter(ppa); 14172 } 14173 changed = true; 14174 } 14175 } 14176 14177 if (changed) { 14178 scheduleWritePackageRestrictionsLocked(userId); 14179 } 14180 } 14181 } 14182 14183 /** 14184 * Common machinery for picking apart a restored XML blob and passing 14185 * it to a caller-supplied functor to be applied to the running system. 14186 */ 14187 private void restoreFromXml(XmlPullParser parser, int userId, 14188 String expectedStartTag, BlobXmlRestorer functor) 14189 throws IOException, XmlPullParserException { 14190 int type; 14191 while ((type = parser.next()) != XmlPullParser.START_TAG 14192 && type != XmlPullParser.END_DOCUMENT) { 14193 } 14194 if (type != XmlPullParser.START_TAG) { 14195 // oops didn't find a start tag?! 14196 if (DEBUG_BACKUP) { 14197 Slog.e(TAG, "Didn't find start tag during restore"); 14198 } 14199 return; 14200 } 14201 14202 // this is supposed to be TAG_PREFERRED_BACKUP 14203 if (!expectedStartTag.equals(parser.getName())) { 14204 if (DEBUG_BACKUP) { 14205 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14206 } 14207 return; 14208 } 14209 14210 // skip interfering stuff, then we're aligned with the backing implementation 14211 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14212 functor.apply(parser, userId); 14213 } 14214 14215 private interface BlobXmlRestorer { 14216 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14217 } 14218 14219 /** 14220 * Non-Binder method, support for the backup/restore mechanism: write the 14221 * full set of preferred activities in its canonical XML format. Returns the 14222 * XML output as a byte array, or null if there is none. 14223 */ 14224 @Override 14225 public byte[] getPreferredActivityBackup(int userId) { 14226 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14227 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14228 } 14229 14230 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14231 try { 14232 final XmlSerializer serializer = new FastXmlSerializer(); 14233 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14234 serializer.startDocument(null, true); 14235 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14236 14237 synchronized (mPackages) { 14238 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14239 } 14240 14241 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14242 serializer.endDocument(); 14243 serializer.flush(); 14244 } catch (Exception e) { 14245 if (DEBUG_BACKUP) { 14246 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14247 } 14248 return null; 14249 } 14250 14251 return dataStream.toByteArray(); 14252 } 14253 14254 @Override 14255 public void restorePreferredActivities(byte[] backup, int userId) { 14256 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14257 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14258 } 14259 14260 try { 14261 final XmlPullParser parser = Xml.newPullParser(); 14262 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14263 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14264 new BlobXmlRestorer() { 14265 @Override 14266 public void apply(XmlPullParser parser, int userId) 14267 throws XmlPullParserException, IOException { 14268 synchronized (mPackages) { 14269 mSettings.readPreferredActivitiesLPw(parser, userId); 14270 } 14271 } 14272 } ); 14273 } catch (Exception e) { 14274 if (DEBUG_BACKUP) { 14275 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14276 } 14277 } 14278 } 14279 14280 /** 14281 * Non-Binder method, support for the backup/restore mechanism: write the 14282 * default browser (etc) settings in its canonical XML format. Returns the default 14283 * browser XML representation as a byte array, or null if there is none. 14284 */ 14285 @Override 14286 public byte[] getDefaultAppsBackup(int userId) { 14287 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14288 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14289 } 14290 14291 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14292 try { 14293 final XmlSerializer serializer = new FastXmlSerializer(); 14294 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14295 serializer.startDocument(null, true); 14296 serializer.startTag(null, TAG_DEFAULT_APPS); 14297 14298 synchronized (mPackages) { 14299 mSettings.writeDefaultAppsLPr(serializer, userId); 14300 } 14301 14302 serializer.endTag(null, TAG_DEFAULT_APPS); 14303 serializer.endDocument(); 14304 serializer.flush(); 14305 } catch (Exception e) { 14306 if (DEBUG_BACKUP) { 14307 Slog.e(TAG, "Unable to write default apps for backup", e); 14308 } 14309 return null; 14310 } 14311 14312 return dataStream.toByteArray(); 14313 } 14314 14315 @Override 14316 public void restoreDefaultApps(byte[] backup, int userId) { 14317 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14318 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14319 } 14320 14321 try { 14322 final XmlPullParser parser = Xml.newPullParser(); 14323 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14324 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14325 new BlobXmlRestorer() { 14326 @Override 14327 public void apply(XmlPullParser parser, int userId) 14328 throws XmlPullParserException, IOException { 14329 synchronized (mPackages) { 14330 mSettings.readDefaultAppsLPw(parser, userId); 14331 } 14332 } 14333 } ); 14334 } catch (Exception e) { 14335 if (DEBUG_BACKUP) { 14336 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14337 } 14338 } 14339 } 14340 14341 @Override 14342 public byte[] getIntentFilterVerificationBackup(int userId) { 14343 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14344 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14345 } 14346 14347 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14348 try { 14349 final XmlSerializer serializer = new FastXmlSerializer(); 14350 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14351 serializer.startDocument(null, true); 14352 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14353 14354 synchronized (mPackages) { 14355 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14356 } 14357 14358 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14359 serializer.endDocument(); 14360 serializer.flush(); 14361 } catch (Exception e) { 14362 if (DEBUG_BACKUP) { 14363 Slog.e(TAG, "Unable to write default apps for backup", e); 14364 } 14365 return null; 14366 } 14367 14368 return dataStream.toByteArray(); 14369 } 14370 14371 @Override 14372 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14373 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14374 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14375 } 14376 14377 try { 14378 final XmlPullParser parser = Xml.newPullParser(); 14379 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14380 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14381 new BlobXmlRestorer() { 14382 @Override 14383 public void apply(XmlPullParser parser, int userId) 14384 throws XmlPullParserException, IOException { 14385 synchronized (mPackages) { 14386 mSettings.readAllDomainVerificationsLPr(parser, userId); 14387 mSettings.writeLPr(); 14388 } 14389 } 14390 } ); 14391 } catch (Exception e) { 14392 if (DEBUG_BACKUP) { 14393 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14394 } 14395 } 14396 } 14397 14398 @Override 14399 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14400 int sourceUserId, int targetUserId, int flags) { 14401 mContext.enforceCallingOrSelfPermission( 14402 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14403 int callingUid = Binder.getCallingUid(); 14404 enforceOwnerRights(ownerPackage, callingUid); 14405 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14406 if (intentFilter.countActions() == 0) { 14407 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14408 return; 14409 } 14410 synchronized (mPackages) { 14411 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14412 ownerPackage, targetUserId, flags); 14413 CrossProfileIntentResolver resolver = 14414 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14415 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14416 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14417 if (existing != null) { 14418 int size = existing.size(); 14419 for (int i = 0; i < size; i++) { 14420 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14421 return; 14422 } 14423 } 14424 } 14425 resolver.addFilter(newFilter); 14426 scheduleWritePackageRestrictionsLocked(sourceUserId); 14427 } 14428 } 14429 14430 @Override 14431 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14432 mContext.enforceCallingOrSelfPermission( 14433 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14434 int callingUid = Binder.getCallingUid(); 14435 enforceOwnerRights(ownerPackage, callingUid); 14436 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14437 synchronized (mPackages) { 14438 CrossProfileIntentResolver resolver = 14439 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14440 ArraySet<CrossProfileIntentFilter> set = 14441 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14442 for (CrossProfileIntentFilter filter : set) { 14443 if (filter.getOwnerPackage().equals(ownerPackage)) { 14444 resolver.removeFilter(filter); 14445 } 14446 } 14447 scheduleWritePackageRestrictionsLocked(sourceUserId); 14448 } 14449 } 14450 14451 // Enforcing that callingUid is owning pkg on userId 14452 private void enforceOwnerRights(String pkg, int callingUid) { 14453 // The system owns everything. 14454 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14455 return; 14456 } 14457 int callingUserId = UserHandle.getUserId(callingUid); 14458 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14459 if (pi == null) { 14460 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14461 + callingUserId); 14462 } 14463 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14464 throw new SecurityException("Calling uid " + callingUid 14465 + " does not own package " + pkg); 14466 } 14467 } 14468 14469 @Override 14470 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14471 Intent intent = new Intent(Intent.ACTION_MAIN); 14472 intent.addCategory(Intent.CATEGORY_HOME); 14473 14474 final int callingUserId = UserHandle.getCallingUserId(); 14475 List<ResolveInfo> list = queryIntentActivities(intent, null, 14476 PackageManager.GET_META_DATA, callingUserId); 14477 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14478 true, false, false, callingUserId); 14479 14480 allHomeCandidates.clear(); 14481 if (list != null) { 14482 for (ResolveInfo ri : list) { 14483 allHomeCandidates.add(ri); 14484 } 14485 } 14486 return (preferred == null || preferred.activityInfo == null) 14487 ? null 14488 : new ComponentName(preferred.activityInfo.packageName, 14489 preferred.activityInfo.name); 14490 } 14491 14492 @Override 14493 public void setApplicationEnabledSetting(String appPackageName, 14494 int newState, int flags, int userId, String callingPackage) { 14495 if (!sUserManager.exists(userId)) return; 14496 if (callingPackage == null) { 14497 callingPackage = Integer.toString(Binder.getCallingUid()); 14498 } 14499 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14500 } 14501 14502 @Override 14503 public void setComponentEnabledSetting(ComponentName componentName, 14504 int newState, int flags, int userId) { 14505 if (!sUserManager.exists(userId)) return; 14506 setEnabledSetting(componentName.getPackageName(), 14507 componentName.getClassName(), newState, flags, userId, null); 14508 } 14509 14510 private void setEnabledSetting(final String packageName, String className, int newState, 14511 final int flags, int userId, String callingPackage) { 14512 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14513 || newState == COMPONENT_ENABLED_STATE_ENABLED 14514 || newState == COMPONENT_ENABLED_STATE_DISABLED 14515 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14516 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14517 throw new IllegalArgumentException("Invalid new component state: " 14518 + newState); 14519 } 14520 PackageSetting pkgSetting; 14521 final int uid = Binder.getCallingUid(); 14522 final int permission = mContext.checkCallingOrSelfPermission( 14523 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14524 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14525 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14526 boolean sendNow = false; 14527 boolean isApp = (className == null); 14528 String componentName = isApp ? packageName : className; 14529 int packageUid = -1; 14530 ArrayList<String> components; 14531 14532 // writer 14533 synchronized (mPackages) { 14534 pkgSetting = mSettings.mPackages.get(packageName); 14535 if (pkgSetting == null) { 14536 if (className == null) { 14537 throw new IllegalArgumentException( 14538 "Unknown package: " + packageName); 14539 } 14540 throw new IllegalArgumentException( 14541 "Unknown component: " + packageName 14542 + "/" + className); 14543 } 14544 // Allow root and verify that userId is not being specified by a different user 14545 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14546 throw new SecurityException( 14547 "Permission Denial: attempt to change component state from pid=" 14548 + Binder.getCallingPid() 14549 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14550 } 14551 if (className == null) { 14552 // We're dealing with an application/package level state change 14553 if (pkgSetting.getEnabled(userId) == newState) { 14554 // Nothing to do 14555 return; 14556 } 14557 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14558 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14559 // Don't care about who enables an app. 14560 callingPackage = null; 14561 } 14562 pkgSetting.setEnabled(newState, userId, callingPackage); 14563 // pkgSetting.pkg.mSetEnabled = newState; 14564 } else { 14565 // We're dealing with a component level state change 14566 // First, verify that this is a valid class name. 14567 PackageParser.Package pkg = pkgSetting.pkg; 14568 if (pkg == null || !pkg.hasComponentClassName(className)) { 14569 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14570 throw new IllegalArgumentException("Component class " + className 14571 + " does not exist in " + packageName); 14572 } else { 14573 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14574 + className + " does not exist in " + packageName); 14575 } 14576 } 14577 switch (newState) { 14578 case COMPONENT_ENABLED_STATE_ENABLED: 14579 if (!pkgSetting.enableComponentLPw(className, userId)) { 14580 return; 14581 } 14582 break; 14583 case COMPONENT_ENABLED_STATE_DISABLED: 14584 if (!pkgSetting.disableComponentLPw(className, userId)) { 14585 return; 14586 } 14587 break; 14588 case COMPONENT_ENABLED_STATE_DEFAULT: 14589 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14590 return; 14591 } 14592 break; 14593 default: 14594 Slog.e(TAG, "Invalid new component state: " + newState); 14595 return; 14596 } 14597 } 14598 scheduleWritePackageRestrictionsLocked(userId); 14599 components = mPendingBroadcasts.get(userId, packageName); 14600 final boolean newPackage = components == null; 14601 if (newPackage) { 14602 components = new ArrayList<String>(); 14603 } 14604 if (!components.contains(componentName)) { 14605 components.add(componentName); 14606 } 14607 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14608 sendNow = true; 14609 // Purge entry from pending broadcast list if another one exists already 14610 // since we are sending one right away. 14611 mPendingBroadcasts.remove(userId, packageName); 14612 } else { 14613 if (newPackage) { 14614 mPendingBroadcasts.put(userId, packageName, components); 14615 } 14616 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14617 // Schedule a message 14618 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14619 } 14620 } 14621 } 14622 14623 long callingId = Binder.clearCallingIdentity(); 14624 try { 14625 if (sendNow) { 14626 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14627 sendPackageChangedBroadcast(packageName, 14628 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14629 } 14630 } finally { 14631 Binder.restoreCallingIdentity(callingId); 14632 } 14633 } 14634 14635 private void sendPackageChangedBroadcast(String packageName, 14636 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14637 if (DEBUG_INSTALL) 14638 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14639 + componentNames); 14640 Bundle extras = new Bundle(4); 14641 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14642 String nameList[] = new String[componentNames.size()]; 14643 componentNames.toArray(nameList); 14644 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14645 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14646 extras.putInt(Intent.EXTRA_UID, packageUid); 14647 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14648 new int[] {UserHandle.getUserId(packageUid)}); 14649 } 14650 14651 @Override 14652 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14653 if (!sUserManager.exists(userId)) return; 14654 final int uid = Binder.getCallingUid(); 14655 final int permission = mContext.checkCallingOrSelfPermission( 14656 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14657 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14658 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14659 // writer 14660 synchronized (mPackages) { 14661 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14662 allowedByPermission, uid, userId)) { 14663 scheduleWritePackageRestrictionsLocked(userId); 14664 } 14665 } 14666 } 14667 14668 @Override 14669 public String getInstallerPackageName(String packageName) { 14670 // reader 14671 synchronized (mPackages) { 14672 return mSettings.getInstallerPackageNameLPr(packageName); 14673 } 14674 } 14675 14676 @Override 14677 public int getApplicationEnabledSetting(String packageName, int userId) { 14678 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14679 int uid = Binder.getCallingUid(); 14680 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14681 // reader 14682 synchronized (mPackages) { 14683 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14684 } 14685 } 14686 14687 @Override 14688 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14689 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14690 int uid = Binder.getCallingUid(); 14691 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14692 // reader 14693 synchronized (mPackages) { 14694 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14695 } 14696 } 14697 14698 @Override 14699 public void enterSafeMode() { 14700 enforceSystemOrRoot("Only the system can request entering safe mode"); 14701 14702 if (!mSystemReady) { 14703 mSafeMode = true; 14704 } 14705 } 14706 14707 @Override 14708 public void systemReady() { 14709 mSystemReady = true; 14710 14711 // Read the compatibilty setting when the system is ready. 14712 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14713 mContext.getContentResolver(), 14714 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14715 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14716 if (DEBUG_SETTINGS) { 14717 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14718 } 14719 14720 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14721 14722 synchronized (mPackages) { 14723 // Verify that all of the preferred activity components actually 14724 // exist. It is possible for applications to be updated and at 14725 // that point remove a previously declared activity component that 14726 // had been set as a preferred activity. We try to clean this up 14727 // the next time we encounter that preferred activity, but it is 14728 // possible for the user flow to never be able to return to that 14729 // situation so here we do a sanity check to make sure we haven't 14730 // left any junk around. 14731 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14732 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14733 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14734 removed.clear(); 14735 for (PreferredActivity pa : pir.filterSet()) { 14736 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14737 removed.add(pa); 14738 } 14739 } 14740 if (removed.size() > 0) { 14741 for (int r=0; r<removed.size(); r++) { 14742 PreferredActivity pa = removed.get(r); 14743 Slog.w(TAG, "Removing dangling preferred activity: " 14744 + pa.mPref.mComponent); 14745 pir.removeFilter(pa); 14746 } 14747 mSettings.writePackageRestrictionsLPr( 14748 mSettings.mPreferredActivities.keyAt(i)); 14749 } 14750 } 14751 14752 for (int userId : UserManagerService.getInstance().getUserIds()) { 14753 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14754 grantPermissionsUserIds = ArrayUtils.appendInt( 14755 grantPermissionsUserIds, userId); 14756 } 14757 } 14758 } 14759 sUserManager.systemReady(); 14760 14761 // If we upgraded grant all default permissions before kicking off. 14762 for (int userId : grantPermissionsUserIds) { 14763 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14764 } 14765 14766 // Kick off any messages waiting for system ready 14767 if (mPostSystemReadyMessages != null) { 14768 for (Message msg : mPostSystemReadyMessages) { 14769 msg.sendToTarget(); 14770 } 14771 mPostSystemReadyMessages = null; 14772 } 14773 14774 // Watch for external volumes that come and go over time 14775 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14776 storage.registerListener(mStorageListener); 14777 14778 mInstallerService.systemReady(); 14779 mPackageDexOptimizer.systemReady(); 14780 14781 MountServiceInternal mountServiceInternal = LocalServices.getService( 14782 MountServiceInternal.class); 14783 mountServiceInternal.addExternalStoragePolicy( 14784 new MountServiceInternal.ExternalStorageMountPolicy() { 14785 @Override 14786 public int getMountMode(int uid, String packageName) { 14787 if (Process.isIsolated(uid)) { 14788 return Zygote.MOUNT_EXTERNAL_NONE; 14789 } 14790 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14791 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14792 } 14793 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14794 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14795 } 14796 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14797 return Zygote.MOUNT_EXTERNAL_READ; 14798 } 14799 return Zygote.MOUNT_EXTERNAL_WRITE; 14800 } 14801 14802 @Override 14803 public boolean hasExternalStorage(int uid, String packageName) { 14804 return true; 14805 } 14806 }); 14807 } 14808 14809 @Override 14810 public boolean isSafeMode() { 14811 return mSafeMode; 14812 } 14813 14814 @Override 14815 public boolean hasSystemUidErrors() { 14816 return mHasSystemUidErrors; 14817 } 14818 14819 static String arrayToString(int[] array) { 14820 StringBuffer buf = new StringBuffer(128); 14821 buf.append('['); 14822 if (array != null) { 14823 for (int i=0; i<array.length; i++) { 14824 if (i > 0) buf.append(", "); 14825 buf.append(array[i]); 14826 } 14827 } 14828 buf.append(']'); 14829 return buf.toString(); 14830 } 14831 14832 static class DumpState { 14833 public static final int DUMP_LIBS = 1 << 0; 14834 public static final int DUMP_FEATURES = 1 << 1; 14835 public static final int DUMP_RESOLVERS = 1 << 2; 14836 public static final int DUMP_PERMISSIONS = 1 << 3; 14837 public static final int DUMP_PACKAGES = 1 << 4; 14838 public static final int DUMP_SHARED_USERS = 1 << 5; 14839 public static final int DUMP_MESSAGES = 1 << 6; 14840 public static final int DUMP_PROVIDERS = 1 << 7; 14841 public static final int DUMP_VERIFIERS = 1 << 8; 14842 public static final int DUMP_PREFERRED = 1 << 9; 14843 public static final int DUMP_PREFERRED_XML = 1 << 10; 14844 public static final int DUMP_KEYSETS = 1 << 11; 14845 public static final int DUMP_VERSION = 1 << 12; 14846 public static final int DUMP_INSTALLS = 1 << 13; 14847 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14848 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14849 14850 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14851 14852 private int mTypes; 14853 14854 private int mOptions; 14855 14856 private boolean mTitlePrinted; 14857 14858 private SharedUserSetting mSharedUser; 14859 14860 public boolean isDumping(int type) { 14861 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14862 return true; 14863 } 14864 14865 return (mTypes & type) != 0; 14866 } 14867 14868 public void setDump(int type) { 14869 mTypes |= type; 14870 } 14871 14872 public boolean isOptionEnabled(int option) { 14873 return (mOptions & option) != 0; 14874 } 14875 14876 public void setOptionEnabled(int option) { 14877 mOptions |= option; 14878 } 14879 14880 public boolean onTitlePrinted() { 14881 final boolean printed = mTitlePrinted; 14882 mTitlePrinted = true; 14883 return printed; 14884 } 14885 14886 public boolean getTitlePrinted() { 14887 return mTitlePrinted; 14888 } 14889 14890 public void setTitlePrinted(boolean enabled) { 14891 mTitlePrinted = enabled; 14892 } 14893 14894 public SharedUserSetting getSharedUser() { 14895 return mSharedUser; 14896 } 14897 14898 public void setSharedUser(SharedUserSetting user) { 14899 mSharedUser = user; 14900 } 14901 } 14902 14903 @Override 14904 public void onShellCommand(FileDescriptor in, FileDescriptor out, 14905 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 14906 (new PackageManagerShellCommand(this)).exec( 14907 this, in, out, err, args, resultReceiver); 14908 } 14909 14910 @Override 14911 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14912 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14913 != PackageManager.PERMISSION_GRANTED) { 14914 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14915 + Binder.getCallingPid() 14916 + ", uid=" + Binder.getCallingUid() 14917 + " without permission " 14918 + android.Manifest.permission.DUMP); 14919 return; 14920 } 14921 14922 DumpState dumpState = new DumpState(); 14923 boolean fullPreferred = false; 14924 boolean checkin = false; 14925 14926 String packageName = null; 14927 ArraySet<String> permissionNames = null; 14928 14929 int opti = 0; 14930 while (opti < args.length) { 14931 String opt = args[opti]; 14932 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14933 break; 14934 } 14935 opti++; 14936 14937 if ("-a".equals(opt)) { 14938 // Right now we only know how to print all. 14939 } else if ("-h".equals(opt)) { 14940 pw.println("Package manager dump options:"); 14941 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14942 pw.println(" --checkin: dump for a checkin"); 14943 pw.println(" -f: print details of intent filters"); 14944 pw.println(" -h: print this help"); 14945 pw.println(" cmd may be one of:"); 14946 pw.println(" l[ibraries]: list known shared libraries"); 14947 pw.println(" f[ibraries]: list device features"); 14948 pw.println(" k[eysets]: print known keysets"); 14949 pw.println(" r[esolvers]: dump intent resolvers"); 14950 pw.println(" perm[issions]: dump permissions"); 14951 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14952 pw.println(" pref[erred]: print preferred package settings"); 14953 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14954 pw.println(" prov[iders]: dump content providers"); 14955 pw.println(" p[ackages]: dump installed packages"); 14956 pw.println(" s[hared-users]: dump shared user IDs"); 14957 pw.println(" m[essages]: print collected runtime messages"); 14958 pw.println(" v[erifiers]: print package verifier info"); 14959 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14960 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14961 pw.println(" version: print database version info"); 14962 pw.println(" write: write current settings now"); 14963 pw.println(" installs: details about install sessions"); 14964 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14965 pw.println(" <package.name>: info about given package"); 14966 return; 14967 } else if ("--checkin".equals(opt)) { 14968 checkin = true; 14969 } else if ("-f".equals(opt)) { 14970 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14971 } else { 14972 pw.println("Unknown argument: " + opt + "; use -h for help"); 14973 } 14974 } 14975 14976 // Is the caller requesting to dump a particular piece of data? 14977 if (opti < args.length) { 14978 String cmd = args[opti]; 14979 opti++; 14980 // Is this a package name? 14981 if ("android".equals(cmd) || cmd.contains(".")) { 14982 packageName = cmd; 14983 // When dumping a single package, we always dump all of its 14984 // filter information since the amount of data will be reasonable. 14985 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14986 } else if ("check-permission".equals(cmd)) { 14987 if (opti >= args.length) { 14988 pw.println("Error: check-permission missing permission argument"); 14989 return; 14990 } 14991 String perm = args[opti]; 14992 opti++; 14993 if (opti >= args.length) { 14994 pw.println("Error: check-permission missing package argument"); 14995 return; 14996 } 14997 String pkg = args[opti]; 14998 opti++; 14999 int user = UserHandle.getUserId(Binder.getCallingUid()); 15000 if (opti < args.length) { 15001 try { 15002 user = Integer.parseInt(args[opti]); 15003 } catch (NumberFormatException e) { 15004 pw.println("Error: check-permission user argument is not a number: " 15005 + args[opti]); 15006 return; 15007 } 15008 } 15009 pw.println(checkPermission(perm, pkg, user)); 15010 return; 15011 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15012 dumpState.setDump(DumpState.DUMP_LIBS); 15013 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15014 dumpState.setDump(DumpState.DUMP_FEATURES); 15015 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15016 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15017 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15018 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15019 } else if ("permission".equals(cmd)) { 15020 if (opti >= args.length) { 15021 pw.println("Error: permission requires permission name"); 15022 return; 15023 } 15024 permissionNames = new ArraySet<>(); 15025 while (opti < args.length) { 15026 permissionNames.add(args[opti]); 15027 opti++; 15028 } 15029 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15030 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15031 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15032 dumpState.setDump(DumpState.DUMP_PREFERRED); 15033 } else if ("preferred-xml".equals(cmd)) { 15034 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15035 if (opti < args.length && "--full".equals(args[opti])) { 15036 fullPreferred = true; 15037 opti++; 15038 } 15039 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15040 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15041 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15042 dumpState.setDump(DumpState.DUMP_PACKAGES); 15043 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15044 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15045 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15046 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15047 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15048 dumpState.setDump(DumpState.DUMP_MESSAGES); 15049 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15050 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15051 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15052 || "intent-filter-verifiers".equals(cmd)) { 15053 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15054 } else if ("version".equals(cmd)) { 15055 dumpState.setDump(DumpState.DUMP_VERSION); 15056 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15057 dumpState.setDump(DumpState.DUMP_KEYSETS); 15058 } else if ("installs".equals(cmd)) { 15059 dumpState.setDump(DumpState.DUMP_INSTALLS); 15060 } else if ("write".equals(cmd)) { 15061 synchronized (mPackages) { 15062 mSettings.writeLPr(); 15063 pw.println("Settings written."); 15064 return; 15065 } 15066 } 15067 } 15068 15069 if (checkin) { 15070 pw.println("vers,1"); 15071 } 15072 15073 // reader 15074 synchronized (mPackages) { 15075 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15076 if (!checkin) { 15077 if (dumpState.onTitlePrinted()) 15078 pw.println(); 15079 pw.println("Database versions:"); 15080 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15081 } 15082 } 15083 15084 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15085 if (!checkin) { 15086 if (dumpState.onTitlePrinted()) 15087 pw.println(); 15088 pw.println("Verifiers:"); 15089 pw.print(" Required: "); 15090 pw.print(mRequiredVerifierPackage); 15091 pw.print(" (uid="); 15092 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15093 pw.println(")"); 15094 } else if (mRequiredVerifierPackage != null) { 15095 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15096 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15097 } 15098 } 15099 15100 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15101 packageName == null) { 15102 if (mIntentFilterVerifierComponent != null) { 15103 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15104 if (!checkin) { 15105 if (dumpState.onTitlePrinted()) 15106 pw.println(); 15107 pw.println("Intent Filter Verifier:"); 15108 pw.print(" Using: "); 15109 pw.print(verifierPackageName); 15110 pw.print(" (uid="); 15111 pw.print(getPackageUid(verifierPackageName, 0)); 15112 pw.println(")"); 15113 } else if (verifierPackageName != null) { 15114 pw.print("ifv,"); pw.print(verifierPackageName); 15115 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15116 } 15117 } else { 15118 pw.println(); 15119 pw.println("No Intent Filter Verifier available!"); 15120 } 15121 } 15122 15123 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15124 boolean printedHeader = false; 15125 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15126 while (it.hasNext()) { 15127 String name = it.next(); 15128 SharedLibraryEntry ent = mSharedLibraries.get(name); 15129 if (!checkin) { 15130 if (!printedHeader) { 15131 if (dumpState.onTitlePrinted()) 15132 pw.println(); 15133 pw.println("Libraries:"); 15134 printedHeader = true; 15135 } 15136 pw.print(" "); 15137 } else { 15138 pw.print("lib,"); 15139 } 15140 pw.print(name); 15141 if (!checkin) { 15142 pw.print(" -> "); 15143 } 15144 if (ent.path != null) { 15145 if (!checkin) { 15146 pw.print("(jar) "); 15147 pw.print(ent.path); 15148 } else { 15149 pw.print(",jar,"); 15150 pw.print(ent.path); 15151 } 15152 } else { 15153 if (!checkin) { 15154 pw.print("(apk) "); 15155 pw.print(ent.apk); 15156 } else { 15157 pw.print(",apk,"); 15158 pw.print(ent.apk); 15159 } 15160 } 15161 pw.println(); 15162 } 15163 } 15164 15165 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15166 if (dumpState.onTitlePrinted()) 15167 pw.println(); 15168 if (!checkin) { 15169 pw.println("Features:"); 15170 } 15171 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15172 while (it.hasNext()) { 15173 String name = it.next(); 15174 if (!checkin) { 15175 pw.print(" "); 15176 } else { 15177 pw.print("feat,"); 15178 } 15179 pw.println(name); 15180 } 15181 } 15182 15183 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15184 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15185 : "Activity Resolver Table:", " ", packageName, 15186 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15187 dumpState.setTitlePrinted(true); 15188 } 15189 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15190 : "Receiver Resolver Table:", " ", packageName, 15191 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15192 dumpState.setTitlePrinted(true); 15193 } 15194 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15195 : "Service Resolver Table:", " ", packageName, 15196 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15197 dumpState.setTitlePrinted(true); 15198 } 15199 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15200 : "Provider Resolver Table:", " ", packageName, 15201 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15202 dumpState.setTitlePrinted(true); 15203 } 15204 } 15205 15206 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15207 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15208 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15209 int user = mSettings.mPreferredActivities.keyAt(i); 15210 if (pir.dump(pw, 15211 dumpState.getTitlePrinted() 15212 ? "\nPreferred Activities User " + user + ":" 15213 : "Preferred Activities User " + user + ":", " ", 15214 packageName, true, false)) { 15215 dumpState.setTitlePrinted(true); 15216 } 15217 } 15218 } 15219 15220 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15221 pw.flush(); 15222 FileOutputStream fout = new FileOutputStream(fd); 15223 BufferedOutputStream str = new BufferedOutputStream(fout); 15224 XmlSerializer serializer = new FastXmlSerializer(); 15225 try { 15226 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15227 serializer.startDocument(null, true); 15228 serializer.setFeature( 15229 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15230 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15231 serializer.endDocument(); 15232 serializer.flush(); 15233 } catch (IllegalArgumentException e) { 15234 pw.println("Failed writing: " + e); 15235 } catch (IllegalStateException e) { 15236 pw.println("Failed writing: " + e); 15237 } catch (IOException e) { 15238 pw.println("Failed writing: " + e); 15239 } 15240 } 15241 15242 if (!checkin 15243 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15244 && packageName == null) { 15245 pw.println(); 15246 int count = mSettings.mPackages.size(); 15247 if (count == 0) { 15248 pw.println("No applications!"); 15249 pw.println(); 15250 } else { 15251 final String prefix = " "; 15252 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15253 if (allPackageSettings.size() == 0) { 15254 pw.println("No domain preferred apps!"); 15255 pw.println(); 15256 } else { 15257 pw.println("App verification status:"); 15258 pw.println(); 15259 count = 0; 15260 for (PackageSetting ps : allPackageSettings) { 15261 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15262 if (ivi == null || ivi.getPackageName() == null) continue; 15263 pw.println(prefix + "Package: " + ivi.getPackageName()); 15264 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15265 pw.println(prefix + "Status: " + ivi.getStatusString()); 15266 pw.println(); 15267 count++; 15268 } 15269 if (count == 0) { 15270 pw.println(prefix + "No app verification established."); 15271 pw.println(); 15272 } 15273 for (int userId : sUserManager.getUserIds()) { 15274 pw.println("App linkages for user " + userId + ":"); 15275 pw.println(); 15276 count = 0; 15277 for (PackageSetting ps : allPackageSettings) { 15278 final long status = ps.getDomainVerificationStatusForUser(userId); 15279 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15280 continue; 15281 } 15282 pw.println(prefix + "Package: " + ps.name); 15283 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15284 String statusStr = IntentFilterVerificationInfo. 15285 getStatusStringFromValue(status); 15286 pw.println(prefix + "Status: " + statusStr); 15287 pw.println(); 15288 count++; 15289 } 15290 if (count == 0) { 15291 pw.println(prefix + "No configured app linkages."); 15292 pw.println(); 15293 } 15294 } 15295 } 15296 } 15297 } 15298 15299 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15300 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15301 if (packageName == null && permissionNames == null) { 15302 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15303 if (iperm == 0) { 15304 if (dumpState.onTitlePrinted()) 15305 pw.println(); 15306 pw.println("AppOp Permissions:"); 15307 } 15308 pw.print(" AppOp Permission "); 15309 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15310 pw.println(":"); 15311 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15312 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15313 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15314 } 15315 } 15316 } 15317 } 15318 15319 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15320 boolean printedSomething = false; 15321 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15322 if (packageName != null && !packageName.equals(p.info.packageName)) { 15323 continue; 15324 } 15325 if (!printedSomething) { 15326 if (dumpState.onTitlePrinted()) 15327 pw.println(); 15328 pw.println("Registered ContentProviders:"); 15329 printedSomething = true; 15330 } 15331 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15332 pw.print(" "); pw.println(p.toString()); 15333 } 15334 printedSomething = false; 15335 for (Map.Entry<String, PackageParser.Provider> entry : 15336 mProvidersByAuthority.entrySet()) { 15337 PackageParser.Provider p = entry.getValue(); 15338 if (packageName != null && !packageName.equals(p.info.packageName)) { 15339 continue; 15340 } 15341 if (!printedSomething) { 15342 if (dumpState.onTitlePrinted()) 15343 pw.println(); 15344 pw.println("ContentProvider Authorities:"); 15345 printedSomething = true; 15346 } 15347 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15348 pw.print(" "); pw.println(p.toString()); 15349 if (p.info != null && p.info.applicationInfo != null) { 15350 final String appInfo = p.info.applicationInfo.toString(); 15351 pw.print(" applicationInfo="); pw.println(appInfo); 15352 } 15353 } 15354 } 15355 15356 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15357 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15358 } 15359 15360 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15361 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15362 } 15363 15364 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15365 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15366 } 15367 15368 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15369 // XXX should handle packageName != null by dumping only install data that 15370 // the given package is involved with. 15371 if (dumpState.onTitlePrinted()) pw.println(); 15372 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15373 } 15374 15375 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15376 if (dumpState.onTitlePrinted()) pw.println(); 15377 mSettings.dumpReadMessagesLPr(pw, dumpState); 15378 15379 pw.println(); 15380 pw.println("Package warning messages:"); 15381 BufferedReader in = null; 15382 String line = null; 15383 try { 15384 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15385 while ((line = in.readLine()) != null) { 15386 if (line.contains("ignored: updated version")) continue; 15387 pw.println(line); 15388 } 15389 } catch (IOException ignored) { 15390 } finally { 15391 IoUtils.closeQuietly(in); 15392 } 15393 } 15394 15395 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15396 BufferedReader in = null; 15397 String line = null; 15398 try { 15399 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15400 while ((line = in.readLine()) != null) { 15401 if (line.contains("ignored: updated version")) continue; 15402 pw.print("msg,"); 15403 pw.println(line); 15404 } 15405 } catch (IOException ignored) { 15406 } finally { 15407 IoUtils.closeQuietly(in); 15408 } 15409 } 15410 } 15411 } 15412 15413 private String dumpDomainString(String packageName) { 15414 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15415 List<IntentFilter> filters = getAllIntentFilters(packageName); 15416 15417 ArraySet<String> result = new ArraySet<>(); 15418 if (iviList.size() > 0) { 15419 for (IntentFilterVerificationInfo ivi : iviList) { 15420 for (String host : ivi.getDomains()) { 15421 result.add(host); 15422 } 15423 } 15424 } 15425 if (filters != null && filters.size() > 0) { 15426 for (IntentFilter filter : filters) { 15427 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15428 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15429 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15430 result.addAll(filter.getHostsList()); 15431 } 15432 } 15433 } 15434 15435 StringBuilder sb = new StringBuilder(result.size() * 16); 15436 for (String domain : result) { 15437 if (sb.length() > 0) sb.append(" "); 15438 sb.append(domain); 15439 } 15440 return sb.toString(); 15441 } 15442 15443 // ------- apps on sdcard specific code ------- 15444 static final boolean DEBUG_SD_INSTALL = false; 15445 15446 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15447 15448 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15449 15450 private boolean mMediaMounted = false; 15451 15452 static String getEncryptKey() { 15453 try { 15454 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15455 SD_ENCRYPTION_KEYSTORE_NAME); 15456 if (sdEncKey == null) { 15457 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15458 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15459 if (sdEncKey == null) { 15460 Slog.e(TAG, "Failed to create encryption keys"); 15461 return null; 15462 } 15463 } 15464 return sdEncKey; 15465 } catch (NoSuchAlgorithmException nsae) { 15466 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15467 return null; 15468 } catch (IOException ioe) { 15469 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15470 return null; 15471 } 15472 } 15473 15474 /* 15475 * Update media status on PackageManager. 15476 */ 15477 @Override 15478 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15479 int callingUid = Binder.getCallingUid(); 15480 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15481 throw new SecurityException("Media status can only be updated by the system"); 15482 } 15483 // reader; this apparently protects mMediaMounted, but should probably 15484 // be a different lock in that case. 15485 synchronized (mPackages) { 15486 Log.i(TAG, "Updating external media status from " 15487 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15488 + (mediaStatus ? "mounted" : "unmounted")); 15489 if (DEBUG_SD_INSTALL) 15490 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15491 + ", mMediaMounted=" + mMediaMounted); 15492 if (mediaStatus == mMediaMounted) { 15493 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15494 : 0, -1); 15495 mHandler.sendMessage(msg); 15496 return; 15497 } 15498 mMediaMounted = mediaStatus; 15499 } 15500 // Queue up an async operation since the package installation may take a 15501 // little while. 15502 mHandler.post(new Runnable() { 15503 public void run() { 15504 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15505 } 15506 }); 15507 } 15508 15509 /** 15510 * Called by MountService when the initial ASECs to scan are available. 15511 * Should block until all the ASEC containers are finished being scanned. 15512 */ 15513 public void scanAvailableAsecs() { 15514 updateExternalMediaStatusInner(true, false, false); 15515 if (mShouldRestoreconData) { 15516 SELinuxMMAC.setRestoreconDone(); 15517 mShouldRestoreconData = false; 15518 } 15519 } 15520 15521 /* 15522 * Collect information of applications on external media, map them against 15523 * existing containers and update information based on current mount status. 15524 * Please note that we always have to report status if reportStatus has been 15525 * set to true especially when unloading packages. 15526 */ 15527 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15528 boolean externalStorage) { 15529 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15530 int[] uidArr = EmptyArray.INT; 15531 15532 final String[] list = PackageHelper.getSecureContainerList(); 15533 if (ArrayUtils.isEmpty(list)) { 15534 Log.i(TAG, "No secure containers found"); 15535 } else { 15536 // Process list of secure containers and categorize them 15537 // as active or stale based on their package internal state. 15538 15539 // reader 15540 synchronized (mPackages) { 15541 for (String cid : list) { 15542 // Leave stages untouched for now; installer service owns them 15543 if (PackageInstallerService.isStageName(cid)) continue; 15544 15545 if (DEBUG_SD_INSTALL) 15546 Log.i(TAG, "Processing container " + cid); 15547 String pkgName = getAsecPackageName(cid); 15548 if (pkgName == null) { 15549 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15550 continue; 15551 } 15552 if (DEBUG_SD_INSTALL) 15553 Log.i(TAG, "Looking for pkg : " + pkgName); 15554 15555 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15556 if (ps == null) { 15557 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15558 continue; 15559 } 15560 15561 /* 15562 * Skip packages that are not external if we're unmounting 15563 * external storage. 15564 */ 15565 if (externalStorage && !isMounted && !isExternal(ps)) { 15566 continue; 15567 } 15568 15569 final AsecInstallArgs args = new AsecInstallArgs(cid, 15570 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15571 // The package status is changed only if the code path 15572 // matches between settings and the container id. 15573 if (ps.codePathString != null 15574 && ps.codePathString.startsWith(args.getCodePath())) { 15575 if (DEBUG_SD_INSTALL) { 15576 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15577 + " at code path: " + ps.codePathString); 15578 } 15579 15580 // We do have a valid package installed on sdcard 15581 processCids.put(args, ps.codePathString); 15582 final int uid = ps.appId; 15583 if (uid != -1) { 15584 uidArr = ArrayUtils.appendInt(uidArr, uid); 15585 } 15586 } else { 15587 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15588 + ps.codePathString); 15589 } 15590 } 15591 } 15592 15593 Arrays.sort(uidArr); 15594 } 15595 15596 // Process packages with valid entries. 15597 if (isMounted) { 15598 if (DEBUG_SD_INSTALL) 15599 Log.i(TAG, "Loading packages"); 15600 loadMediaPackages(processCids, uidArr, externalStorage); 15601 startCleaningPackages(); 15602 mInstallerService.onSecureContainersAvailable(); 15603 } else { 15604 if (DEBUG_SD_INSTALL) 15605 Log.i(TAG, "Unloading packages"); 15606 unloadMediaPackages(processCids, uidArr, reportStatus); 15607 } 15608 } 15609 15610 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15611 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15612 final int size = infos.size(); 15613 final String[] packageNames = new String[size]; 15614 final int[] packageUids = new int[size]; 15615 for (int i = 0; i < size; i++) { 15616 final ApplicationInfo info = infos.get(i); 15617 packageNames[i] = info.packageName; 15618 packageUids[i] = info.uid; 15619 } 15620 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15621 finishedReceiver); 15622 } 15623 15624 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15625 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15626 sendResourcesChangedBroadcast(mediaStatus, replacing, 15627 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15628 } 15629 15630 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15631 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15632 int size = pkgList.length; 15633 if (size > 0) { 15634 // Send broadcasts here 15635 Bundle extras = new Bundle(); 15636 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15637 if (uidArr != null) { 15638 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15639 } 15640 if (replacing) { 15641 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15642 } 15643 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15644 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15645 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15646 } 15647 } 15648 15649 /* 15650 * Look at potentially valid container ids from processCids If package 15651 * information doesn't match the one on record or package scanning fails, 15652 * the cid is added to list of removeCids. We currently don't delete stale 15653 * containers. 15654 */ 15655 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15656 boolean externalStorage) { 15657 ArrayList<String> pkgList = new ArrayList<String>(); 15658 Set<AsecInstallArgs> keys = processCids.keySet(); 15659 15660 for (AsecInstallArgs args : keys) { 15661 String codePath = processCids.get(args); 15662 if (DEBUG_SD_INSTALL) 15663 Log.i(TAG, "Loading container : " + args.cid); 15664 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15665 try { 15666 // Make sure there are no container errors first. 15667 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15668 Slog.e(TAG, "Failed to mount cid : " + args.cid 15669 + " when installing from sdcard"); 15670 continue; 15671 } 15672 // Check code path here. 15673 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15674 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15675 + " does not match one in settings " + codePath); 15676 continue; 15677 } 15678 // Parse package 15679 int parseFlags = mDefParseFlags; 15680 if (args.isExternalAsec()) { 15681 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15682 } 15683 if (args.isFwdLocked()) { 15684 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15685 } 15686 15687 synchronized (mInstallLock) { 15688 PackageParser.Package pkg = null; 15689 try { 15690 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15691 } catch (PackageManagerException e) { 15692 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15693 } 15694 // Scan the package 15695 if (pkg != null) { 15696 /* 15697 * TODO why is the lock being held? doPostInstall is 15698 * called in other places without the lock. This needs 15699 * to be straightened out. 15700 */ 15701 // writer 15702 synchronized (mPackages) { 15703 retCode = PackageManager.INSTALL_SUCCEEDED; 15704 pkgList.add(pkg.packageName); 15705 // Post process args 15706 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15707 pkg.applicationInfo.uid); 15708 } 15709 } else { 15710 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15711 } 15712 } 15713 15714 } finally { 15715 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15716 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15717 } 15718 } 15719 } 15720 // writer 15721 synchronized (mPackages) { 15722 // If the platform SDK has changed since the last time we booted, 15723 // we need to re-grant app permission to catch any new ones that 15724 // appear. This is really a hack, and means that apps can in some 15725 // cases get permissions that the user didn't initially explicitly 15726 // allow... it would be nice to have some better way to handle 15727 // this situation. 15728 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15729 : mSettings.getInternalVersion(); 15730 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15731 : StorageManager.UUID_PRIVATE_INTERNAL; 15732 15733 int updateFlags = UPDATE_PERMISSIONS_ALL; 15734 if (ver.sdkVersion != mSdkVersion) { 15735 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15736 + mSdkVersion + "; regranting permissions for external"); 15737 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15738 } 15739 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15740 15741 // Yay, everything is now upgraded 15742 ver.forceCurrent(); 15743 15744 // can downgrade to reader 15745 // Persist settings 15746 mSettings.writeLPr(); 15747 } 15748 // Send a broadcast to let everyone know we are done processing 15749 if (pkgList.size() > 0) { 15750 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15751 } 15752 } 15753 15754 /* 15755 * Utility method to unload a list of specified containers 15756 */ 15757 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15758 // Just unmount all valid containers. 15759 for (AsecInstallArgs arg : cidArgs) { 15760 synchronized (mInstallLock) { 15761 arg.doPostDeleteLI(false); 15762 } 15763 } 15764 } 15765 15766 /* 15767 * Unload packages mounted on external media. This involves deleting package 15768 * data from internal structures, sending broadcasts about diabled packages, 15769 * gc'ing to free up references, unmounting all secure containers 15770 * corresponding to packages on external media, and posting a 15771 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15772 * that we always have to post this message if status has been requested no 15773 * matter what. 15774 */ 15775 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15776 final boolean reportStatus) { 15777 if (DEBUG_SD_INSTALL) 15778 Log.i(TAG, "unloading media packages"); 15779 ArrayList<String> pkgList = new ArrayList<String>(); 15780 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15781 final Set<AsecInstallArgs> keys = processCids.keySet(); 15782 for (AsecInstallArgs args : keys) { 15783 String pkgName = args.getPackageName(); 15784 if (DEBUG_SD_INSTALL) 15785 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15786 // Delete package internally 15787 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15788 synchronized (mInstallLock) { 15789 boolean res = deletePackageLI(pkgName, null, false, null, null, 15790 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15791 if (res) { 15792 pkgList.add(pkgName); 15793 } else { 15794 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15795 failedList.add(args); 15796 } 15797 } 15798 } 15799 15800 // reader 15801 synchronized (mPackages) { 15802 // We didn't update the settings after removing each package; 15803 // write them now for all packages. 15804 mSettings.writeLPr(); 15805 } 15806 15807 // We have to absolutely send UPDATED_MEDIA_STATUS only 15808 // after confirming that all the receivers processed the ordered 15809 // broadcast when packages get disabled, force a gc to clean things up. 15810 // and unload all the containers. 15811 if (pkgList.size() > 0) { 15812 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15813 new IIntentReceiver.Stub() { 15814 public void performReceive(Intent intent, int resultCode, String data, 15815 Bundle extras, boolean ordered, boolean sticky, 15816 int sendingUser) throws RemoteException { 15817 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15818 reportStatus ? 1 : 0, 1, keys); 15819 mHandler.sendMessage(msg); 15820 } 15821 }); 15822 } else { 15823 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15824 keys); 15825 mHandler.sendMessage(msg); 15826 } 15827 } 15828 15829 private void loadPrivatePackages(final VolumeInfo vol) { 15830 mHandler.post(new Runnable() { 15831 @Override 15832 public void run() { 15833 loadPrivatePackagesInner(vol); 15834 } 15835 }); 15836 } 15837 15838 private void loadPrivatePackagesInner(VolumeInfo vol) { 15839 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15840 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15841 15842 final VersionInfo ver; 15843 final List<PackageSetting> packages; 15844 synchronized (mPackages) { 15845 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15846 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15847 } 15848 15849 for (PackageSetting ps : packages) { 15850 synchronized (mInstallLock) { 15851 final PackageParser.Package pkg; 15852 try { 15853 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 15854 loaded.add(pkg.applicationInfo); 15855 } catch (PackageManagerException e) { 15856 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15857 } 15858 15859 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15860 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15861 } 15862 } 15863 } 15864 15865 synchronized (mPackages) { 15866 int updateFlags = UPDATE_PERMISSIONS_ALL; 15867 if (ver.sdkVersion != mSdkVersion) { 15868 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15869 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15870 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15871 } 15872 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 15873 15874 // Yay, everything is now upgraded 15875 ver.forceCurrent(); 15876 15877 mSettings.writeLPr(); 15878 } 15879 15880 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15881 sendResourcesChangedBroadcast(true, false, loaded, null); 15882 } 15883 15884 private void unloadPrivatePackages(final VolumeInfo vol) { 15885 mHandler.post(new Runnable() { 15886 @Override 15887 public void run() { 15888 unloadPrivatePackagesInner(vol); 15889 } 15890 }); 15891 } 15892 15893 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15894 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15895 synchronized (mInstallLock) { 15896 synchronized (mPackages) { 15897 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15898 for (PackageSetting ps : packages) { 15899 if (ps.pkg == null) continue; 15900 15901 final ApplicationInfo info = ps.pkg.applicationInfo; 15902 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15903 if (deletePackageLI(ps.name, null, false, null, null, 15904 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15905 unloaded.add(info); 15906 } else { 15907 Slog.w(TAG, "Failed to unload " + ps.codePath); 15908 } 15909 } 15910 15911 mSettings.writeLPr(); 15912 } 15913 } 15914 15915 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15916 sendResourcesChangedBroadcast(false, false, unloaded, null); 15917 } 15918 15919 /** 15920 * Examine all users present on given mounted volume, and destroy data 15921 * belonging to users that are no longer valid, or whose user ID has been 15922 * recycled. 15923 */ 15924 private void reconcileUsers(String volumeUuid) { 15925 final File[] files = FileUtils 15926 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15927 for (File file : files) { 15928 if (!file.isDirectory()) continue; 15929 15930 final int userId; 15931 final UserInfo info; 15932 try { 15933 userId = Integer.parseInt(file.getName()); 15934 info = sUserManager.getUserInfo(userId); 15935 } catch (NumberFormatException e) { 15936 Slog.w(TAG, "Invalid user directory " + file); 15937 continue; 15938 } 15939 15940 boolean destroyUser = false; 15941 if (info == null) { 15942 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15943 + " because no matching user was found"); 15944 destroyUser = true; 15945 } else { 15946 try { 15947 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15948 } catch (IOException e) { 15949 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15950 + " because we failed to enforce serial number: " + e); 15951 destroyUser = true; 15952 } 15953 } 15954 15955 if (destroyUser) { 15956 synchronized (mInstallLock) { 15957 mInstaller.removeUserDataDirs(volumeUuid, userId); 15958 } 15959 } 15960 } 15961 15962 final StorageManager sm = mContext.getSystemService(StorageManager.class); 15963 final UserManager um = mContext.getSystemService(UserManager.class); 15964 for (UserInfo user : um.getUsers()) { 15965 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15966 if (userDir.exists()) continue; 15967 15968 try { 15969 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber); 15970 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15971 } catch (IOException e) { 15972 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15973 } 15974 } 15975 } 15976 15977 /** 15978 * Examine all apps present on given mounted volume, and destroy apps that 15979 * aren't expected, either due to uninstallation or reinstallation on 15980 * another volume. 15981 */ 15982 private void reconcileApps(String volumeUuid) { 15983 final File[] files = FileUtils 15984 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15985 for (File file : files) { 15986 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15987 && !PackageInstallerService.isStageName(file.getName()); 15988 if (!isPackage) { 15989 // Ignore entries which are not packages 15990 continue; 15991 } 15992 15993 boolean destroyApp = false; 15994 String packageName = null; 15995 try { 15996 final PackageLite pkg = PackageParser.parsePackageLite(file, 15997 PackageParser.PARSE_MUST_BE_APK); 15998 packageName = pkg.packageName; 15999 16000 synchronized (mPackages) { 16001 final PackageSetting ps = mSettings.mPackages.get(packageName); 16002 if (ps == null) { 16003 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16004 + volumeUuid + " because we found no install record"); 16005 destroyApp = true; 16006 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16007 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16008 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16009 destroyApp = true; 16010 } 16011 } 16012 16013 } catch (PackageParserException e) { 16014 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16015 destroyApp = true; 16016 } 16017 16018 if (destroyApp) { 16019 synchronized (mInstallLock) { 16020 if (packageName != null) { 16021 removeDataDirsLI(volumeUuid, packageName); 16022 } 16023 if (file.isDirectory()) { 16024 mInstaller.rmPackageDir(file.getAbsolutePath()); 16025 } else { 16026 file.delete(); 16027 } 16028 } 16029 } 16030 } 16031 } 16032 16033 private void unfreezePackage(String packageName) { 16034 synchronized (mPackages) { 16035 final PackageSetting ps = mSettings.mPackages.get(packageName); 16036 if (ps != null) { 16037 ps.frozen = false; 16038 } 16039 } 16040 } 16041 16042 @Override 16043 public int movePackage(final String packageName, final String volumeUuid) { 16044 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16045 16046 final int moveId = mNextMoveId.getAndIncrement(); 16047 mHandler.post(new Runnable() { 16048 @Override 16049 public void run() { 16050 try { 16051 movePackageInternal(packageName, volumeUuid, moveId); 16052 } catch (PackageManagerException e) { 16053 Slog.w(TAG, "Failed to move " + packageName, e); 16054 mMoveCallbacks.notifyStatusChanged(moveId, 16055 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16056 } 16057 } 16058 }); 16059 return moveId; 16060 } 16061 16062 private void movePackageInternal(final String packageName, final String volumeUuid, 16063 final int moveId) throws PackageManagerException { 16064 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16065 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16066 final PackageManager pm = mContext.getPackageManager(); 16067 16068 final boolean currentAsec; 16069 final String currentVolumeUuid; 16070 final File codeFile; 16071 final String installerPackageName; 16072 final String packageAbiOverride; 16073 final int appId; 16074 final String seinfo; 16075 final String label; 16076 16077 // reader 16078 synchronized (mPackages) { 16079 final PackageParser.Package pkg = mPackages.get(packageName); 16080 final PackageSetting ps = mSettings.mPackages.get(packageName); 16081 if (pkg == null || ps == null) { 16082 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16083 } 16084 16085 if (pkg.applicationInfo.isSystemApp()) { 16086 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16087 "Cannot move system application"); 16088 } 16089 16090 if (pkg.applicationInfo.isExternalAsec()) { 16091 currentAsec = true; 16092 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16093 } else if (pkg.applicationInfo.isForwardLocked()) { 16094 currentAsec = true; 16095 currentVolumeUuid = "forward_locked"; 16096 } else { 16097 currentAsec = false; 16098 currentVolumeUuid = ps.volumeUuid; 16099 16100 final File probe = new File(pkg.codePath); 16101 final File probeOat = new File(probe, "oat"); 16102 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16103 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16104 "Move only supported for modern cluster style installs"); 16105 } 16106 } 16107 16108 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16109 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16110 "Package already moved to " + volumeUuid); 16111 } 16112 16113 if (ps.frozen) { 16114 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16115 "Failed to move already frozen package"); 16116 } 16117 ps.frozen = true; 16118 16119 codeFile = new File(pkg.codePath); 16120 installerPackageName = ps.installerPackageName; 16121 packageAbiOverride = ps.cpuAbiOverrideString; 16122 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16123 seinfo = pkg.applicationInfo.seinfo; 16124 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16125 } 16126 16127 // Now that we're guarded by frozen state, kill app during move 16128 final long token = Binder.clearCallingIdentity(); 16129 try { 16130 killApplication(packageName, appId, "move pkg"); 16131 } finally { 16132 Binder.restoreCallingIdentity(token); 16133 } 16134 16135 final Bundle extras = new Bundle(); 16136 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16137 extras.putString(Intent.EXTRA_TITLE, label); 16138 mMoveCallbacks.notifyCreated(moveId, extras); 16139 16140 int installFlags; 16141 final boolean moveCompleteApp; 16142 final File measurePath; 16143 16144 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16145 installFlags = INSTALL_INTERNAL; 16146 moveCompleteApp = !currentAsec; 16147 measurePath = Environment.getDataAppDirectory(volumeUuid); 16148 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16149 installFlags = INSTALL_EXTERNAL; 16150 moveCompleteApp = false; 16151 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16152 } else { 16153 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16154 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16155 || !volume.isMountedWritable()) { 16156 unfreezePackage(packageName); 16157 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16158 "Move location not mounted private volume"); 16159 } 16160 16161 Preconditions.checkState(!currentAsec); 16162 16163 installFlags = INSTALL_INTERNAL; 16164 moveCompleteApp = true; 16165 measurePath = Environment.getDataAppDirectory(volumeUuid); 16166 } 16167 16168 final PackageStats stats = new PackageStats(null, -1); 16169 synchronized (mInstaller) { 16170 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16171 unfreezePackage(packageName); 16172 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16173 "Failed to measure package size"); 16174 } 16175 } 16176 16177 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16178 + stats.dataSize); 16179 16180 final long startFreeBytes = measurePath.getFreeSpace(); 16181 final long sizeBytes; 16182 if (moveCompleteApp) { 16183 sizeBytes = stats.codeSize + stats.dataSize; 16184 } else { 16185 sizeBytes = stats.codeSize; 16186 } 16187 16188 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16189 unfreezePackage(packageName); 16190 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16191 "Not enough free space to move"); 16192 } 16193 16194 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16195 16196 final CountDownLatch installedLatch = new CountDownLatch(1); 16197 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16198 @Override 16199 public void onUserActionRequired(Intent intent) throws RemoteException { 16200 throw new IllegalStateException(); 16201 } 16202 16203 @Override 16204 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16205 Bundle extras) throws RemoteException { 16206 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16207 + PackageManager.installStatusToString(returnCode, msg)); 16208 16209 installedLatch.countDown(); 16210 16211 // Regardless of success or failure of the move operation, 16212 // always unfreeze the package 16213 unfreezePackage(packageName); 16214 16215 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16216 switch (status) { 16217 case PackageInstaller.STATUS_SUCCESS: 16218 mMoveCallbacks.notifyStatusChanged(moveId, 16219 PackageManager.MOVE_SUCCEEDED); 16220 break; 16221 case PackageInstaller.STATUS_FAILURE_STORAGE: 16222 mMoveCallbacks.notifyStatusChanged(moveId, 16223 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16224 break; 16225 default: 16226 mMoveCallbacks.notifyStatusChanged(moveId, 16227 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16228 break; 16229 } 16230 } 16231 }; 16232 16233 final MoveInfo move; 16234 if (moveCompleteApp) { 16235 // Kick off a thread to report progress estimates 16236 new Thread() { 16237 @Override 16238 public void run() { 16239 while (true) { 16240 try { 16241 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16242 break; 16243 } 16244 } catch (InterruptedException ignored) { 16245 } 16246 16247 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16248 final int progress = 10 + (int) MathUtils.constrain( 16249 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16250 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16251 } 16252 } 16253 }.start(); 16254 16255 final String dataAppName = codeFile.getName(); 16256 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16257 dataAppName, appId, seinfo); 16258 } else { 16259 move = null; 16260 } 16261 16262 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16263 16264 final Message msg = mHandler.obtainMessage(INIT_COPY); 16265 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16266 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16267 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16268 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16269 msg.obj = params; 16270 16271 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16272 System.identityHashCode(msg.obj)); 16273 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16274 System.identityHashCode(msg.obj)); 16275 16276 mHandler.sendMessage(msg); 16277 } 16278 16279 @Override 16280 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16281 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16282 16283 final int realMoveId = mNextMoveId.getAndIncrement(); 16284 final Bundle extras = new Bundle(); 16285 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16286 mMoveCallbacks.notifyCreated(realMoveId, extras); 16287 16288 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16289 @Override 16290 public void onCreated(int moveId, Bundle extras) { 16291 // Ignored 16292 } 16293 16294 @Override 16295 public void onStatusChanged(int moveId, int status, long estMillis) { 16296 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16297 } 16298 }; 16299 16300 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16301 storage.setPrimaryStorageUuid(volumeUuid, callback); 16302 return realMoveId; 16303 } 16304 16305 @Override 16306 public int getMoveStatus(int moveId) { 16307 mContext.enforceCallingOrSelfPermission( 16308 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16309 return mMoveCallbacks.mLastStatus.get(moveId); 16310 } 16311 16312 @Override 16313 public void registerMoveCallback(IPackageMoveObserver callback) { 16314 mContext.enforceCallingOrSelfPermission( 16315 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16316 mMoveCallbacks.register(callback); 16317 } 16318 16319 @Override 16320 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16321 mContext.enforceCallingOrSelfPermission( 16322 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16323 mMoveCallbacks.unregister(callback); 16324 } 16325 16326 @Override 16327 public boolean setInstallLocation(int loc) { 16328 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16329 null); 16330 if (getInstallLocation() == loc) { 16331 return true; 16332 } 16333 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16334 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16335 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16336 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16337 return true; 16338 } 16339 return false; 16340 } 16341 16342 @Override 16343 public int getInstallLocation() { 16344 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16345 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16346 PackageHelper.APP_INSTALL_AUTO); 16347 } 16348 16349 /** Called by UserManagerService */ 16350 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16351 mDirtyUsers.remove(userHandle); 16352 mSettings.removeUserLPw(userHandle); 16353 mPendingBroadcasts.remove(userHandle); 16354 if (mInstaller != null) { 16355 // Technically, we shouldn't be doing this with the package lock 16356 // held. However, this is very rare, and there is already so much 16357 // other disk I/O going on, that we'll let it slide for now. 16358 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16359 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16360 final String volumeUuid = vol.getFsUuid(); 16361 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16362 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16363 } 16364 } 16365 mUserNeedsBadging.delete(userHandle); 16366 removeUnusedPackagesLILPw(userManager, userHandle); 16367 } 16368 16369 /** 16370 * We're removing userHandle and would like to remove any downloaded packages 16371 * that are no longer in use by any other user. 16372 * @param userHandle the user being removed 16373 */ 16374 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16375 final boolean DEBUG_CLEAN_APKS = false; 16376 int [] users = userManager.getUserIds(); 16377 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16378 while (psit.hasNext()) { 16379 PackageSetting ps = psit.next(); 16380 if (ps.pkg == null) { 16381 continue; 16382 } 16383 final String packageName = ps.pkg.packageName; 16384 // Skip over if system app 16385 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16386 continue; 16387 } 16388 if (DEBUG_CLEAN_APKS) { 16389 Slog.i(TAG, "Checking package " + packageName); 16390 } 16391 boolean keep = false; 16392 for (int i = 0; i < users.length; i++) { 16393 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16394 keep = true; 16395 if (DEBUG_CLEAN_APKS) { 16396 Slog.i(TAG, " Keeping package " + packageName + " for user " 16397 + users[i]); 16398 } 16399 break; 16400 } 16401 } 16402 if (!keep) { 16403 if (DEBUG_CLEAN_APKS) { 16404 Slog.i(TAG, " Removing package " + packageName); 16405 } 16406 mHandler.post(new Runnable() { 16407 public void run() { 16408 deletePackageX(packageName, userHandle, 0); 16409 } //end run 16410 }); 16411 } 16412 } 16413 } 16414 16415 /** Called by UserManagerService */ 16416 void createNewUserLILPw(int userHandle) { 16417 if (mInstaller != null) { 16418 mInstaller.createUserConfig(userHandle); 16419 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16420 applyFactoryDefaultBrowserLPw(userHandle); 16421 primeDomainVerificationsLPw(userHandle); 16422 } 16423 } 16424 16425 void newUserCreated(final int userHandle) { 16426 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16427 } 16428 16429 @Override 16430 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16431 mContext.enforceCallingOrSelfPermission( 16432 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16433 "Only package verification agents can read the verifier device identity"); 16434 16435 synchronized (mPackages) { 16436 return mSettings.getVerifierDeviceIdentityLPw(); 16437 } 16438 } 16439 16440 @Override 16441 public void setPermissionEnforced(String permission, boolean enforced) { 16442 // TODO: Now that we no longer change GID for storage, this should to away. 16443 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16444 "setPermissionEnforced"); 16445 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16446 synchronized (mPackages) { 16447 if (mSettings.mReadExternalStorageEnforced == null 16448 || mSettings.mReadExternalStorageEnforced != enforced) { 16449 mSettings.mReadExternalStorageEnforced = enforced; 16450 mSettings.writeLPr(); 16451 } 16452 } 16453 // kill any non-foreground processes so we restart them and 16454 // grant/revoke the GID. 16455 final IActivityManager am = ActivityManagerNative.getDefault(); 16456 if (am != null) { 16457 final long token = Binder.clearCallingIdentity(); 16458 try { 16459 am.killProcessesBelowForeground("setPermissionEnforcement"); 16460 } catch (RemoteException e) { 16461 } finally { 16462 Binder.restoreCallingIdentity(token); 16463 } 16464 } 16465 } else { 16466 throw new IllegalArgumentException("No selective enforcement for " + permission); 16467 } 16468 } 16469 16470 @Override 16471 @Deprecated 16472 public boolean isPermissionEnforced(String permission) { 16473 return true; 16474 } 16475 16476 @Override 16477 public boolean isStorageLow() { 16478 final long token = Binder.clearCallingIdentity(); 16479 try { 16480 final DeviceStorageMonitorInternal 16481 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16482 if (dsm != null) { 16483 return dsm.isMemoryLow(); 16484 } else { 16485 return false; 16486 } 16487 } finally { 16488 Binder.restoreCallingIdentity(token); 16489 } 16490 } 16491 16492 @Override 16493 public IPackageInstaller getPackageInstaller() { 16494 return mInstallerService; 16495 } 16496 16497 private boolean userNeedsBadging(int userId) { 16498 int index = mUserNeedsBadging.indexOfKey(userId); 16499 if (index < 0) { 16500 final UserInfo userInfo; 16501 final long token = Binder.clearCallingIdentity(); 16502 try { 16503 userInfo = sUserManager.getUserInfo(userId); 16504 } finally { 16505 Binder.restoreCallingIdentity(token); 16506 } 16507 final boolean b; 16508 if (userInfo != null && userInfo.isManagedProfile()) { 16509 b = true; 16510 } else { 16511 b = false; 16512 } 16513 mUserNeedsBadging.put(userId, b); 16514 return b; 16515 } 16516 return mUserNeedsBadging.valueAt(index); 16517 } 16518 16519 @Override 16520 public KeySet getKeySetByAlias(String packageName, String alias) { 16521 if (packageName == null || alias == null) { 16522 return null; 16523 } 16524 synchronized(mPackages) { 16525 final PackageParser.Package pkg = mPackages.get(packageName); 16526 if (pkg == null) { 16527 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16528 throw new IllegalArgumentException("Unknown package: " + packageName); 16529 } 16530 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16531 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16532 } 16533 } 16534 16535 @Override 16536 public KeySet getSigningKeySet(String packageName) { 16537 if (packageName == null) { 16538 return null; 16539 } 16540 synchronized(mPackages) { 16541 final PackageParser.Package pkg = mPackages.get(packageName); 16542 if (pkg == null) { 16543 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16544 throw new IllegalArgumentException("Unknown package: " + packageName); 16545 } 16546 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16547 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16548 throw new SecurityException("May not access signing KeySet of other apps."); 16549 } 16550 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16551 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16552 } 16553 } 16554 16555 @Override 16556 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16557 if (packageName == null || ks == null) { 16558 return false; 16559 } 16560 synchronized(mPackages) { 16561 final PackageParser.Package pkg = mPackages.get(packageName); 16562 if (pkg == null) { 16563 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16564 throw new IllegalArgumentException("Unknown package: " + packageName); 16565 } 16566 IBinder ksh = ks.getToken(); 16567 if (ksh instanceof KeySetHandle) { 16568 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16569 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16570 } 16571 return false; 16572 } 16573 } 16574 16575 @Override 16576 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16577 if (packageName == null || ks == null) { 16578 return false; 16579 } 16580 synchronized(mPackages) { 16581 final PackageParser.Package pkg = mPackages.get(packageName); 16582 if (pkg == null) { 16583 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16584 throw new IllegalArgumentException("Unknown package: " + packageName); 16585 } 16586 IBinder ksh = ks.getToken(); 16587 if (ksh instanceof KeySetHandle) { 16588 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16589 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16590 } 16591 return false; 16592 } 16593 } 16594 16595 /** 16596 * Check and throw if the given before/after packages would be considered a 16597 * downgrade. 16598 */ 16599 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16600 throws PackageManagerException { 16601 if (after.versionCode < before.mVersionCode) { 16602 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16603 "Update version code " + after.versionCode + " is older than current " 16604 + before.mVersionCode); 16605 } else if (after.versionCode == before.mVersionCode) { 16606 if (after.baseRevisionCode < before.baseRevisionCode) { 16607 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16608 "Update base revision code " + after.baseRevisionCode 16609 + " is older than current " + before.baseRevisionCode); 16610 } 16611 16612 if (!ArrayUtils.isEmpty(after.splitNames)) { 16613 for (int i = 0; i < after.splitNames.length; i++) { 16614 final String splitName = after.splitNames[i]; 16615 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16616 if (j != -1) { 16617 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16618 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16619 "Update split " + splitName + " revision code " 16620 + after.splitRevisionCodes[i] + " is older than current " 16621 + before.splitRevisionCodes[j]); 16622 } 16623 } 16624 } 16625 } 16626 } 16627 } 16628 16629 private static class MoveCallbacks extends Handler { 16630 private static final int MSG_CREATED = 1; 16631 private static final int MSG_STATUS_CHANGED = 2; 16632 16633 private final RemoteCallbackList<IPackageMoveObserver> 16634 mCallbacks = new RemoteCallbackList<>(); 16635 16636 private final SparseIntArray mLastStatus = new SparseIntArray(); 16637 16638 public MoveCallbacks(Looper looper) { 16639 super(looper); 16640 } 16641 16642 public void register(IPackageMoveObserver callback) { 16643 mCallbacks.register(callback); 16644 } 16645 16646 public void unregister(IPackageMoveObserver callback) { 16647 mCallbacks.unregister(callback); 16648 } 16649 16650 @Override 16651 public void handleMessage(Message msg) { 16652 final SomeArgs args = (SomeArgs) msg.obj; 16653 final int n = mCallbacks.beginBroadcast(); 16654 for (int i = 0; i < n; i++) { 16655 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16656 try { 16657 invokeCallback(callback, msg.what, args); 16658 } catch (RemoteException ignored) { 16659 } 16660 } 16661 mCallbacks.finishBroadcast(); 16662 args.recycle(); 16663 } 16664 16665 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16666 throws RemoteException { 16667 switch (what) { 16668 case MSG_CREATED: { 16669 callback.onCreated(args.argi1, (Bundle) args.arg2); 16670 break; 16671 } 16672 case MSG_STATUS_CHANGED: { 16673 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16674 break; 16675 } 16676 } 16677 } 16678 16679 private void notifyCreated(int moveId, Bundle extras) { 16680 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16681 16682 final SomeArgs args = SomeArgs.obtain(); 16683 args.argi1 = moveId; 16684 args.arg2 = extras; 16685 obtainMessage(MSG_CREATED, args).sendToTarget(); 16686 } 16687 16688 private void notifyStatusChanged(int moveId, int status) { 16689 notifyStatusChanged(moveId, status, -1); 16690 } 16691 16692 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16693 Slog.v(TAG, "Move " + moveId + " status " + status); 16694 16695 final SomeArgs args = SomeArgs.obtain(); 16696 args.argi1 = moveId; 16697 args.argi2 = status; 16698 args.arg3 = estMillis; 16699 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16700 16701 synchronized (mLastStatus) { 16702 mLastStatus.put(moveId, status); 16703 } 16704 } 16705 } 16706 16707 private final class OnPermissionChangeListeners extends Handler { 16708 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16709 16710 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16711 new RemoteCallbackList<>(); 16712 16713 public OnPermissionChangeListeners(Looper looper) { 16714 super(looper); 16715 } 16716 16717 @Override 16718 public void handleMessage(Message msg) { 16719 switch (msg.what) { 16720 case MSG_ON_PERMISSIONS_CHANGED: { 16721 final int uid = msg.arg1; 16722 handleOnPermissionsChanged(uid); 16723 } break; 16724 } 16725 } 16726 16727 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16728 mPermissionListeners.register(listener); 16729 16730 } 16731 16732 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16733 mPermissionListeners.unregister(listener); 16734 } 16735 16736 public void onPermissionsChanged(int uid) { 16737 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16738 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16739 } 16740 } 16741 16742 private void handleOnPermissionsChanged(int uid) { 16743 final int count = mPermissionListeners.beginBroadcast(); 16744 try { 16745 for (int i = 0; i < count; i++) { 16746 IOnPermissionsChangeListener callback = mPermissionListeners 16747 .getBroadcastItem(i); 16748 try { 16749 callback.onPermissionsChanged(uid); 16750 } catch (RemoteException e) { 16751 Log.e(TAG, "Permission listener is dead", e); 16752 } 16753 } 16754 } finally { 16755 mPermissionListeners.finishBroadcast(); 16756 } 16757 } 16758 } 16759 16760 private class PackageManagerInternalImpl extends PackageManagerInternal { 16761 @Override 16762 public void setLocationPackagesProvider(PackagesProvider provider) { 16763 synchronized (mPackages) { 16764 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16765 } 16766 } 16767 16768 @Override 16769 public void setImePackagesProvider(PackagesProvider provider) { 16770 synchronized (mPackages) { 16771 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16772 } 16773 } 16774 16775 @Override 16776 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16777 synchronized (mPackages) { 16778 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16779 } 16780 } 16781 16782 @Override 16783 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16784 synchronized (mPackages) { 16785 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16786 } 16787 } 16788 16789 @Override 16790 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16791 synchronized (mPackages) { 16792 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16793 } 16794 } 16795 16796 @Override 16797 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16798 synchronized (mPackages) { 16799 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16800 } 16801 } 16802 16803 @Override 16804 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16805 synchronized (mPackages) { 16806 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16807 } 16808 } 16809 16810 @Override 16811 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16812 synchronized (mPackages) { 16813 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16814 packageName, userId); 16815 } 16816 } 16817 16818 @Override 16819 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16820 synchronized (mPackages) { 16821 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16822 packageName, userId); 16823 } 16824 } 16825 @Override 16826 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16827 synchronized (mPackages) { 16828 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16829 packageName, userId); 16830 } 16831 } 16832 } 16833 16834 @Override 16835 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16836 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16837 synchronized (mPackages) { 16838 final long identity = Binder.clearCallingIdentity(); 16839 try { 16840 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16841 packageNames, userId); 16842 } finally { 16843 Binder.restoreCallingIdentity(identity); 16844 } 16845 } 16846 } 16847 16848 private static void enforceSystemOrPhoneCaller(String tag) { 16849 int callingUid = Binder.getCallingUid(); 16850 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16851 throw new SecurityException( 16852 "Cannot call " + tag + " from UID " + callingUid); 16853 } 16854 } 16855} 16856