PackageManagerService.java revision c982b407b9ff83465a12ec9225409edf45828ef0
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 71import static android.system.OsConstants.O_CREAT; 72import static android.system.OsConstants.O_RDWR; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 77import static com.android.internal.util.ArrayUtils.appendInt; 78import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 87 88import android.Manifest; 89import android.app.ActivityManager; 90import android.app.ActivityManagerNative; 91import android.app.AppGlobals; 92import android.app.IActivityManager; 93import android.app.admin.IDevicePolicyManager; 94import android.app.backup.IBackupManager; 95import android.app.usage.UsageStats; 96import android.app.usage.UsageStatsManager; 97import android.content.BroadcastReceiver; 98import android.content.ComponentName; 99import android.content.Context; 100import android.content.IIntentReceiver; 101import android.content.Intent; 102import android.content.IntentFilter; 103import android.content.IntentSender; 104import android.content.IntentSender.SendIntentException; 105import android.content.ServiceConnection; 106import android.content.pm.ActivityInfo; 107import android.content.pm.ApplicationInfo; 108import android.content.pm.FeatureInfo; 109import android.content.pm.IOnPermissionsChangeListener; 110import android.content.pm.IPackageDataObserver; 111import android.content.pm.IPackageDeleteObserver; 112import android.content.pm.IPackageDeleteObserver2; 113import android.content.pm.IPackageInstallObserver2; 114import android.content.pm.IPackageInstaller; 115import android.content.pm.IPackageManager; 116import android.content.pm.IPackageMoveObserver; 117import android.content.pm.IPackageStatsObserver; 118import android.content.pm.InstrumentationInfo; 119import android.content.pm.IntentFilterVerificationInfo; 120import android.content.pm.KeySet; 121import android.content.pm.ManifestDigest; 122import android.content.pm.PackageCleanItem; 123import android.content.pm.PackageInfo; 124import android.content.pm.PackageInfoLite; 125import android.content.pm.PackageInstaller; 126import android.content.pm.PackageManager; 127import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 128import android.content.pm.PackageManagerInternal; 129import android.content.pm.PackageParser; 130import android.content.pm.PackageParser.ActivityIntentInfo; 131import android.content.pm.PackageParser.PackageLite; 132import android.content.pm.PackageParser.PackageParserException; 133import android.content.pm.PackageStats; 134import android.content.pm.PackageUserState; 135import android.content.pm.ParceledListSlice; 136import android.content.pm.PermissionGroupInfo; 137import android.content.pm.PermissionInfo; 138import android.content.pm.ProviderInfo; 139import android.content.pm.ResolveInfo; 140import android.content.pm.ServiceInfo; 141import android.content.pm.Signature; 142import android.content.pm.UserInfo; 143import android.content.pm.VerificationParams; 144import android.content.pm.VerifierDeviceIdentity; 145import android.content.pm.VerifierInfo; 146import android.content.res.Resources; 147import android.hardware.display.DisplayManager; 148import android.net.Uri; 149import android.os.Debug; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Environment; 154import android.os.Environment.UserEnvironment; 155import android.os.FileUtils; 156import android.os.Handler; 157import android.os.IBinder; 158import android.os.Looper; 159import android.os.Message; 160import android.os.Parcel; 161import android.os.ParcelFileDescriptor; 162import android.os.Process; 163import android.os.RemoteCallbackList; 164import android.os.RemoteException; 165import android.os.SELinux; 166import android.os.ServiceManager; 167import android.os.SystemClock; 168import android.os.SystemProperties; 169import android.os.Trace; 170import android.os.UserHandle; 171import android.os.UserManager; 172import android.os.storage.IMountService; 173import android.os.storage.MountServiceInternal; 174import android.os.storage.StorageEventListener; 175import android.os.storage.StorageManager; 176import android.os.storage.VolumeInfo; 177import android.os.storage.VolumeRecord; 178import android.security.KeyStore; 179import android.security.SystemKeyStore; 180import android.system.ErrnoException; 181import android.system.Os; 182import android.system.StructStat; 183import android.text.TextUtils; 184import android.text.format.DateUtils; 185import android.util.ArrayMap; 186import android.util.ArraySet; 187import android.util.AtomicFile; 188import android.util.DisplayMetrics; 189import android.util.EventLog; 190import android.util.ExceptionUtils; 191import android.util.Log; 192import android.util.LogPrinter; 193import android.util.MathUtils; 194import android.util.PrintStreamPrinter; 195import android.util.Slog; 196import android.util.SparseArray; 197import android.util.SparseBooleanArray; 198import android.util.SparseIntArray; 199import android.util.Xml; 200import android.view.Display; 201 202import dalvik.system.DexFile; 203import dalvik.system.VMRuntime; 204 205import libcore.io.IoUtils; 206import libcore.util.EmptyArray; 207 208import com.android.internal.R; 209import com.android.internal.annotations.GuardedBy; 210import com.android.internal.app.IMediaContainerService; 211import com.android.internal.app.ResolverActivity; 212import com.android.internal.content.NativeLibraryHelper; 213import com.android.internal.content.PackageHelper; 214import com.android.internal.os.IParcelFileDescriptorFactory; 215import com.android.internal.os.SomeArgs; 216import com.android.internal.os.Zygote; 217import com.android.internal.util.ArrayUtils; 218import com.android.internal.util.FastPrintWriter; 219import com.android.internal.util.FastXmlSerializer; 220import com.android.internal.util.IndentingPrintWriter; 221import com.android.internal.util.Preconditions; 222import com.android.server.EventLogTags; 223import com.android.server.FgThread; 224import com.android.server.IntentResolver; 225import com.android.server.LocalServices; 226import com.android.server.ServiceThread; 227import com.android.server.SystemConfig; 228import com.android.server.Watchdog; 229import com.android.server.pm.PermissionsState.PermissionState; 230import com.android.server.pm.Settings.DatabaseVersion; 231import com.android.server.pm.Settings.VersionInfo; 232import com.android.server.storage.DeviceStorageMonitorInternal; 233 234import org.xmlpull.v1.XmlPullParser; 235import org.xmlpull.v1.XmlPullParserException; 236import org.xmlpull.v1.XmlSerializer; 237 238import java.io.BufferedInputStream; 239import java.io.BufferedOutputStream; 240import java.io.BufferedReader; 241import java.io.ByteArrayInputStream; 242import java.io.ByteArrayOutputStream; 243import java.io.File; 244import java.io.FileDescriptor; 245import java.io.FileNotFoundException; 246import java.io.FileOutputStream; 247import java.io.FileReader; 248import java.io.FilenameFilter; 249import java.io.IOException; 250import java.io.InputStream; 251import java.io.PrintWriter; 252import java.nio.charset.StandardCharsets; 253import java.security.NoSuchAlgorithmException; 254import java.security.PublicKey; 255import java.security.cert.CertificateEncodingException; 256import java.security.cert.CertificateException; 257import java.text.SimpleDateFormat; 258import java.util.ArrayList; 259import java.util.Arrays; 260import java.util.Collection; 261import java.util.Collections; 262import java.util.Comparator; 263import java.util.Date; 264import java.util.Iterator; 265import java.util.List; 266import java.util.Map; 267import java.util.Objects; 268import java.util.Set; 269import java.util.concurrent.CountDownLatch; 270import java.util.concurrent.TimeUnit; 271import java.util.concurrent.atomic.AtomicBoolean; 272import java.util.concurrent.atomic.AtomicInteger; 273import java.util.concurrent.atomic.AtomicLong; 274 275/** 276 * Keep track of all those .apks everywhere. 277 * 278 * This is very central to the platform's security; please run the unit 279 * tests whenever making modifications here: 280 * 281runtest -c android.content.pm.PackageManagerTests frameworks-core 282 * 283 * {@hide} 284 */ 285public class PackageManagerService extends IPackageManager.Stub { 286 static final String TAG = "PackageManager"; 287 static final boolean DEBUG_SETTINGS = false; 288 static final boolean DEBUG_PREFERRED = false; 289 static final boolean DEBUG_UPGRADE = false; 290 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 291 private static final boolean DEBUG_BACKUP = false; 292 private static final boolean DEBUG_INSTALL = false; 293 private static final boolean DEBUG_REMOVE = false; 294 private static final boolean DEBUG_BROADCASTS = false; 295 private static final boolean DEBUG_SHOW_INFO = false; 296 private static final boolean DEBUG_PACKAGE_INFO = false; 297 private static final boolean DEBUG_INTENT_MATCHING = false; 298 private static final boolean DEBUG_PACKAGE_SCANNING = false; 299 private static final boolean DEBUG_VERIFY = false; 300 private static final boolean DEBUG_DEXOPT = false; 301 private static final boolean DEBUG_ABI_SELECTION = false; 302 303 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 304 305 private static final int RADIO_UID = Process.PHONE_UID; 306 private static final int LOG_UID = Process.LOG_UID; 307 private static final int NFC_UID = Process.NFC_UID; 308 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 309 private static final int SHELL_UID = Process.SHELL_UID; 310 311 // Cap the size of permission trees that 3rd party apps can define 312 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 313 314 // Suffix used during package installation when copying/moving 315 // package apks to install directory. 316 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 317 318 static final int SCAN_NO_DEX = 1<<1; 319 static final int SCAN_FORCE_DEX = 1<<2; 320 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 321 static final int SCAN_NEW_INSTALL = 1<<4; 322 static final int SCAN_NO_PATHS = 1<<5; 323 static final int SCAN_UPDATE_TIME = 1<<6; 324 static final int SCAN_DEFER_DEX = 1<<7; 325 static final int SCAN_BOOTING = 1<<8; 326 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 327 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 328 static final int SCAN_REPLACING = 1<<11; 329 static final int SCAN_REQUIRE_KNOWN = 1<<12; 330 static final int SCAN_MOVE = 1<<13; 331 static final int SCAN_INITIAL = 1<<14; 332 333 static final int REMOVE_CHATTY = 1<<16; 334 335 private static final int[] EMPTY_INT_ARRAY = new int[0]; 336 337 /** 338 * Timeout (in milliseconds) after which the watchdog should declare that 339 * our handler thread is wedged. The usual default for such things is one 340 * minute but we sometimes do very lengthy I/O operations on this thread, 341 * such as installing multi-gigabyte applications, so ours needs to be longer. 342 */ 343 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 344 345 /** 346 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 347 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 348 * settings entry if available, otherwise we use the hardcoded default. If it's been 349 * more than this long since the last fstrim, we force one during the boot sequence. 350 * 351 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 352 * one gets run at the next available charging+idle time. This final mandatory 353 * no-fstrim check kicks in only of the other scheduling criteria is never met. 354 */ 355 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 356 357 /** 358 * Whether verification is enabled by default. 359 */ 360 private static final boolean DEFAULT_VERIFY_ENABLE = true; 361 362 /** 363 * The default maximum time to wait for the verification agent to return in 364 * milliseconds. 365 */ 366 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 367 368 /** 369 * The default response for package verification timeout. 370 * 371 * This can be either PackageManager.VERIFICATION_ALLOW or 372 * PackageManager.VERIFICATION_REJECT. 373 */ 374 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 375 376 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 377 378 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 379 DEFAULT_CONTAINER_PACKAGE, 380 "com.android.defcontainer.DefaultContainerService"); 381 382 private static final String KILL_APP_REASON_GIDS_CHANGED = 383 "permission grant or revoke changed gids"; 384 385 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 386 "permissions revoked"; 387 388 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 389 390 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 391 392 /** Permission grant: not grant the permission. */ 393 private static final int GRANT_DENIED = 1; 394 395 /** Permission grant: grant the permission as an install permission. */ 396 private static final int GRANT_INSTALL = 2; 397 398 /** Permission grant: grant the permission as an install permission for a legacy app. */ 399 private static final int GRANT_INSTALL_LEGACY = 3; 400 401 /** Permission grant: grant the permission as a runtime one. */ 402 private static final int GRANT_RUNTIME = 4; 403 404 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 405 private static final int GRANT_UPGRADE = 5; 406 407 /** Canonical intent used to identify what counts as a "web browser" app */ 408 private static final Intent sBrowserIntent; 409 static { 410 sBrowserIntent = new Intent(); 411 sBrowserIntent.setAction(Intent.ACTION_VIEW); 412 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 413 sBrowserIntent.setData(Uri.parse("http:")); 414 } 415 416 final ServiceThread mHandlerThread; 417 418 final PackageHandler mHandler; 419 420 /** 421 * Messages for {@link #mHandler} that need to wait for system ready before 422 * being dispatched. 423 */ 424 private ArrayList<Message> mPostSystemReadyMessages; 425 426 final int mSdkVersion = Build.VERSION.SDK_INT; 427 428 final Context mContext; 429 final boolean mFactoryTest; 430 final boolean mOnlyCore; 431 final boolean mLazyDexOpt; 432 final long mDexOptLRUThresholdInMills; 433 final DisplayMetrics mMetrics; 434 final int mDefParseFlags; 435 final String[] mSeparateProcesses; 436 final boolean mIsUpgrade; 437 438 // This is where all application persistent data goes. 439 final File mAppDataDir; 440 441 // This is where all application persistent data goes for secondary users. 442 final File mUserAppDataDir; 443 444 /** The location for ASEC container files on internal storage. */ 445 final String mAsecInternalPath; 446 447 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 448 // LOCK HELD. Can be called with mInstallLock held. 449 @GuardedBy("mInstallLock") 450 final Installer mInstaller; 451 452 /** Directory where installed third-party apps stored */ 453 final File mAppInstallDir; 454 455 /** 456 * Directory to which applications installed internally have their 457 * 32 bit native libraries copied. 458 */ 459 private File mAppLib32InstallDir; 460 461 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 462 // apps. 463 final File mDrmAppPrivateInstallDir; 464 465 // ---------------------------------------------------------------- 466 467 // Lock for state used when installing and doing other long running 468 // operations. Methods that must be called with this lock held have 469 // the suffix "LI". 470 final Object mInstallLock = new Object(); 471 472 // ---------------------------------------------------------------- 473 474 // Keys are String (package name), values are Package. This also serves 475 // as the lock for the global state. Methods that must be called with 476 // this lock held have the prefix "LP". 477 @GuardedBy("mPackages") 478 final ArrayMap<String, PackageParser.Package> mPackages = 479 new ArrayMap<String, PackageParser.Package>(); 480 481 // Tracks available target package names -> overlay package paths. 482 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 483 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 484 485 /** 486 * Tracks new system packages [received in an OTA] that we expect to 487 * find updated user-installed versions. Keys are package name, values 488 * are package location. 489 */ 490 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 491 492 /** 493 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 494 */ 495 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 496 /** 497 * Whether or not system app permissions should be promoted from install to runtime. 498 */ 499 boolean mPromoteSystemApps; 500 501 final Settings mSettings; 502 boolean mRestoredSettings; 503 504 // System configuration read by SystemConfig. 505 final int[] mGlobalGids; 506 final SparseArray<ArraySet<String>> mSystemPermissions; 507 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 508 509 // If mac_permissions.xml was found for seinfo labeling. 510 boolean mFoundPolicyFile; 511 512 // If a recursive restorecon of /data/data/<pkg> is needed. 513 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 514 515 public static final class SharedLibraryEntry { 516 public final String path; 517 public final String apk; 518 519 SharedLibraryEntry(String _path, String _apk) { 520 path = _path; 521 apk = _apk; 522 } 523 } 524 525 // Currently known shared libraries. 526 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 527 new ArrayMap<String, SharedLibraryEntry>(); 528 529 // All available activities, for your resolving pleasure. 530 final ActivityIntentResolver mActivities = 531 new ActivityIntentResolver(); 532 533 // All available receivers, for your resolving pleasure. 534 final ActivityIntentResolver mReceivers = 535 new ActivityIntentResolver(); 536 537 // All available services, for your resolving pleasure. 538 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 539 540 // All available providers, for your resolving pleasure. 541 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 542 543 // Mapping from provider base names (first directory in content URI codePath) 544 // to the provider information. 545 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 546 new ArrayMap<String, PackageParser.Provider>(); 547 548 // Mapping from instrumentation class names to info about them. 549 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 550 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 551 552 // Mapping from permission names to info about them. 553 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 554 new ArrayMap<String, PackageParser.PermissionGroup>(); 555 556 // Packages whose data we have transfered into another package, thus 557 // should no longer exist. 558 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 559 560 // Broadcast actions that are only available to the system. 561 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 562 563 /** List of packages waiting for verification. */ 564 final SparseArray<PackageVerificationState> mPendingVerification 565 = new SparseArray<PackageVerificationState>(); 566 567 /** Set of packages associated with each app op permission. */ 568 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 569 570 final PackageInstallerService mInstallerService; 571 572 private final PackageDexOptimizer mPackageDexOptimizer; 573 574 private AtomicInteger mNextMoveId = new AtomicInteger(); 575 private final MoveCallbacks mMoveCallbacks; 576 577 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 578 579 // Cache of users who need badging. 580 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 581 582 /** Token for keys in mPendingVerification. */ 583 private int mPendingVerificationToken = 0; 584 585 volatile boolean mSystemReady; 586 volatile boolean mSafeMode; 587 volatile boolean mHasSystemUidErrors; 588 589 ApplicationInfo mAndroidApplication; 590 final ActivityInfo mResolveActivity = new ActivityInfo(); 591 final ResolveInfo mResolveInfo = new ResolveInfo(); 592 ComponentName mResolveComponentName; 593 PackageParser.Package mPlatformPackage; 594 ComponentName mCustomResolverComponentName; 595 596 boolean mResolverReplaced = false; 597 598 private final ComponentName mIntentFilterVerifierComponent; 599 private int mIntentFilterVerificationToken = 0; 600 601 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 602 = new SparseArray<IntentFilterVerificationState>(); 603 604 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 605 new DefaultPermissionGrantPolicy(this); 606 607 private static class IFVerificationParams { 608 PackageParser.Package pkg; 609 boolean replacing; 610 int userId; 611 int verifierUid; 612 613 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 614 int _userId, int _verifierUid) { 615 pkg = _pkg; 616 replacing = _replacing; 617 userId = _userId; 618 replacing = _replacing; 619 verifierUid = _verifierUid; 620 } 621 } 622 623 private interface IntentFilterVerifier<T extends IntentFilter> { 624 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 625 T filter, String packageName); 626 void startVerifications(int userId); 627 void receiveVerificationResponse(int verificationId); 628 } 629 630 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 631 private Context mContext; 632 private ComponentName mIntentFilterVerifierComponent; 633 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 634 635 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 636 mContext = context; 637 mIntentFilterVerifierComponent = verifierComponent; 638 } 639 640 private String getDefaultScheme() { 641 return IntentFilter.SCHEME_HTTPS; 642 } 643 644 @Override 645 public void startVerifications(int userId) { 646 // Launch verifications requests 647 int count = mCurrentIntentFilterVerifications.size(); 648 for (int n=0; n<count; n++) { 649 int verificationId = mCurrentIntentFilterVerifications.get(n); 650 final IntentFilterVerificationState ivs = 651 mIntentFilterVerificationStates.get(verificationId); 652 653 String packageName = ivs.getPackageName(); 654 655 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 656 final int filterCount = filters.size(); 657 ArraySet<String> domainsSet = new ArraySet<>(); 658 for (int m=0; m<filterCount; m++) { 659 PackageParser.ActivityIntentInfo filter = filters.get(m); 660 domainsSet.addAll(filter.getHostsList()); 661 } 662 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 663 synchronized (mPackages) { 664 if (mSettings.createIntentFilterVerificationIfNeededLPw( 665 packageName, domainsList) != null) { 666 scheduleWriteSettingsLocked(); 667 } 668 } 669 sendVerificationRequest(userId, verificationId, ivs); 670 } 671 mCurrentIntentFilterVerifications.clear(); 672 } 673 674 private void sendVerificationRequest(int userId, int verificationId, 675 IntentFilterVerificationState ivs) { 676 677 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 678 verificationIntent.putExtra( 679 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 680 verificationId); 681 verificationIntent.putExtra( 682 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 683 getDefaultScheme()); 684 verificationIntent.putExtra( 685 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 686 ivs.getHostsString()); 687 verificationIntent.putExtra( 688 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 689 ivs.getPackageName()); 690 verificationIntent.setComponent(mIntentFilterVerifierComponent); 691 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 692 693 UserHandle user = new UserHandle(userId); 694 mContext.sendBroadcastAsUser(verificationIntent, user); 695 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 696 "Sending IntentFilter verification broadcast"); 697 } 698 699 public void receiveVerificationResponse(int verificationId) { 700 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 701 702 final boolean verified = ivs.isVerified(); 703 704 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 705 final int count = filters.size(); 706 if (DEBUG_DOMAIN_VERIFICATION) { 707 Slog.i(TAG, "Received verification response " + verificationId 708 + " for " + count + " filters, verified=" + verified); 709 } 710 for (int n=0; n<count; n++) { 711 PackageParser.ActivityIntentInfo filter = filters.get(n); 712 filter.setVerified(verified); 713 714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 715 + " verified with result:" + verified + " and hosts:" 716 + ivs.getHostsString()); 717 } 718 719 mIntentFilterVerificationStates.remove(verificationId); 720 721 final String packageName = ivs.getPackageName(); 722 IntentFilterVerificationInfo ivi = null; 723 724 synchronized (mPackages) { 725 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 726 } 727 if (ivi == null) { 728 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 729 + verificationId + " packageName:" + packageName); 730 return; 731 } 732 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 733 "Updating IntentFilterVerificationInfo for package " + packageName 734 +" verificationId:" + verificationId); 735 736 synchronized (mPackages) { 737 if (verified) { 738 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 739 } else { 740 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 741 } 742 scheduleWriteSettingsLocked(); 743 744 final int userId = ivs.getUserId(); 745 if (userId != UserHandle.USER_ALL) { 746 final int userStatus = 747 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 748 749 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 750 boolean needUpdate = false; 751 752 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 753 // already been set by the User thru the Disambiguation dialog 754 switch (userStatus) { 755 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 756 if (verified) { 757 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 758 } else { 759 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 760 } 761 needUpdate = true; 762 break; 763 764 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 765 if (verified) { 766 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 767 needUpdate = true; 768 } 769 break; 770 771 default: 772 // Nothing to do 773 } 774 775 if (needUpdate) { 776 mSettings.updateIntentFilterVerificationStatusLPw( 777 packageName, updatedStatus, userId); 778 scheduleWritePackageRestrictionsLocked(userId); 779 } 780 } 781 } 782 } 783 784 @Override 785 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 786 ActivityIntentInfo filter, String packageName) { 787 if (!hasValidDomains(filter)) { 788 return false; 789 } 790 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 791 if (ivs == null) { 792 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 793 packageName); 794 } 795 if (DEBUG_DOMAIN_VERIFICATION) { 796 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 797 } 798 ivs.addFilter(filter); 799 return true; 800 } 801 802 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 803 int userId, int verificationId, String packageName) { 804 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 805 verifierUid, userId, packageName); 806 ivs.setPendingState(); 807 synchronized (mPackages) { 808 mIntentFilterVerificationStates.append(verificationId, ivs); 809 mCurrentIntentFilterVerifications.add(verificationId); 810 } 811 return ivs; 812 } 813 } 814 815 private static boolean hasValidDomains(ActivityIntentInfo filter) { 816 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 817 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 818 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 819 } 820 821 private IntentFilterVerifier mIntentFilterVerifier; 822 823 // Set of pending broadcasts for aggregating enable/disable of components. 824 static class PendingPackageBroadcasts { 825 // for each user id, a map of <package name -> components within that package> 826 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 827 828 public PendingPackageBroadcasts() { 829 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 830 } 831 832 public ArrayList<String> get(int userId, String packageName) { 833 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 834 return packages.get(packageName); 835 } 836 837 public void put(int userId, String packageName, ArrayList<String> components) { 838 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 839 packages.put(packageName, components); 840 } 841 842 public void remove(int userId, String packageName) { 843 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 844 if (packages != null) { 845 packages.remove(packageName); 846 } 847 } 848 849 public void remove(int userId) { 850 mUidMap.remove(userId); 851 } 852 853 public int userIdCount() { 854 return mUidMap.size(); 855 } 856 857 public int userIdAt(int n) { 858 return mUidMap.keyAt(n); 859 } 860 861 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 862 return mUidMap.get(userId); 863 } 864 865 public int size() { 866 // total number of pending broadcast entries across all userIds 867 int num = 0; 868 for (int i = 0; i< mUidMap.size(); i++) { 869 num += mUidMap.valueAt(i).size(); 870 } 871 return num; 872 } 873 874 public void clear() { 875 mUidMap.clear(); 876 } 877 878 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 879 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 880 if (map == null) { 881 map = new ArrayMap<String, ArrayList<String>>(); 882 mUidMap.put(userId, map); 883 } 884 return map; 885 } 886 } 887 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 888 889 // Service Connection to remote media container service to copy 890 // package uri's from external media onto secure containers 891 // or internal storage. 892 private IMediaContainerService mContainerService = null; 893 894 static final int SEND_PENDING_BROADCAST = 1; 895 static final int MCS_BOUND = 3; 896 static final int END_COPY = 4; 897 static final int INIT_COPY = 5; 898 static final int MCS_UNBIND = 6; 899 static final int START_CLEANING_PACKAGE = 7; 900 static final int FIND_INSTALL_LOC = 8; 901 static final int POST_INSTALL = 9; 902 static final int MCS_RECONNECT = 10; 903 static final int MCS_GIVE_UP = 11; 904 static final int UPDATED_MEDIA_STATUS = 12; 905 static final int WRITE_SETTINGS = 13; 906 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 907 static final int PACKAGE_VERIFIED = 15; 908 static final int CHECK_PENDING_VERIFICATION = 16; 909 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 910 static final int INTENT_FILTER_VERIFIED = 18; 911 912 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 913 914 // Delay time in millisecs 915 static final int BROADCAST_DELAY = 10 * 1000; 916 917 static UserManagerService sUserManager; 918 919 // Stores a list of users whose package restrictions file needs to be updated 920 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 921 922 final private DefaultContainerConnection mDefContainerConn = 923 new DefaultContainerConnection(); 924 class DefaultContainerConnection implements ServiceConnection { 925 public void onServiceConnected(ComponentName name, IBinder service) { 926 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 927 IMediaContainerService imcs = 928 IMediaContainerService.Stub.asInterface(service); 929 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 930 } 931 932 public void onServiceDisconnected(ComponentName name) { 933 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 934 } 935 } 936 937 // Recordkeeping of restore-after-install operations that are currently in flight 938 // between the Package Manager and the Backup Manager 939 class PostInstallData { 940 public InstallArgs args; 941 public PackageInstalledInfo res; 942 943 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 944 args = _a; 945 res = _r; 946 } 947 } 948 949 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 950 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 951 952 // XML tags for backup/restore of various bits of state 953 private static final String TAG_PREFERRED_BACKUP = "pa"; 954 private static final String TAG_DEFAULT_APPS = "da"; 955 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 956 957 final String mRequiredVerifierPackage; 958 final String mRequiredInstallerPackage; 959 960 private final PackageUsage mPackageUsage = new PackageUsage(); 961 962 private class PackageUsage { 963 private static final int WRITE_INTERVAL 964 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 965 966 private final Object mFileLock = new Object(); 967 private final AtomicLong mLastWritten = new AtomicLong(0); 968 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 969 970 private boolean mIsHistoricalPackageUsageAvailable = true; 971 972 boolean isHistoricalPackageUsageAvailable() { 973 return mIsHistoricalPackageUsageAvailable; 974 } 975 976 void write(boolean force) { 977 if (force) { 978 writeInternal(); 979 return; 980 } 981 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 982 && !DEBUG_DEXOPT) { 983 return; 984 } 985 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 986 new Thread("PackageUsage_DiskWriter") { 987 @Override 988 public void run() { 989 try { 990 writeInternal(); 991 } finally { 992 mBackgroundWriteRunning.set(false); 993 } 994 } 995 }.start(); 996 } 997 } 998 999 private void writeInternal() { 1000 synchronized (mPackages) { 1001 synchronized (mFileLock) { 1002 AtomicFile file = getFile(); 1003 FileOutputStream f = null; 1004 try { 1005 f = file.startWrite(); 1006 BufferedOutputStream out = new BufferedOutputStream(f); 1007 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1008 StringBuilder sb = new StringBuilder(); 1009 for (PackageParser.Package pkg : mPackages.values()) { 1010 if (pkg.mLastPackageUsageTimeInMills == 0) { 1011 continue; 1012 } 1013 sb.setLength(0); 1014 sb.append(pkg.packageName); 1015 sb.append(' '); 1016 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1017 sb.append('\n'); 1018 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1019 } 1020 out.flush(); 1021 file.finishWrite(f); 1022 } catch (IOException e) { 1023 if (f != null) { 1024 file.failWrite(f); 1025 } 1026 Log.e(TAG, "Failed to write package usage times", e); 1027 } 1028 } 1029 } 1030 mLastWritten.set(SystemClock.elapsedRealtime()); 1031 } 1032 1033 void readLP() { 1034 synchronized (mFileLock) { 1035 AtomicFile file = getFile(); 1036 BufferedInputStream in = null; 1037 try { 1038 in = new BufferedInputStream(file.openRead()); 1039 StringBuffer sb = new StringBuffer(); 1040 while (true) { 1041 String packageName = readToken(in, sb, ' '); 1042 if (packageName == null) { 1043 break; 1044 } 1045 String timeInMillisString = readToken(in, sb, '\n'); 1046 if (timeInMillisString == null) { 1047 throw new IOException("Failed to find last usage time for package " 1048 + packageName); 1049 } 1050 PackageParser.Package pkg = mPackages.get(packageName); 1051 if (pkg == null) { 1052 continue; 1053 } 1054 long timeInMillis; 1055 try { 1056 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1057 } catch (NumberFormatException e) { 1058 throw new IOException("Failed to parse " + timeInMillisString 1059 + " as a long.", e); 1060 } 1061 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1062 } 1063 } catch (FileNotFoundException expected) { 1064 mIsHistoricalPackageUsageAvailable = false; 1065 } catch (IOException e) { 1066 Log.w(TAG, "Failed to read package usage times", e); 1067 } finally { 1068 IoUtils.closeQuietly(in); 1069 } 1070 } 1071 mLastWritten.set(SystemClock.elapsedRealtime()); 1072 } 1073 1074 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1075 throws IOException { 1076 sb.setLength(0); 1077 while (true) { 1078 int ch = in.read(); 1079 if (ch == -1) { 1080 if (sb.length() == 0) { 1081 return null; 1082 } 1083 throw new IOException("Unexpected EOF"); 1084 } 1085 if (ch == endOfToken) { 1086 return sb.toString(); 1087 } 1088 sb.append((char)ch); 1089 } 1090 } 1091 1092 private AtomicFile getFile() { 1093 File dataDir = Environment.getDataDirectory(); 1094 File systemDir = new File(dataDir, "system"); 1095 File fname = new File(systemDir, "package-usage.list"); 1096 return new AtomicFile(fname); 1097 } 1098 } 1099 1100 class PackageHandler extends Handler { 1101 private boolean mBound = false; 1102 final ArrayList<HandlerParams> mPendingInstalls = 1103 new ArrayList<HandlerParams>(); 1104 1105 private boolean connectToService() { 1106 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1107 " DefaultContainerService"); 1108 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1111 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 mBound = true; 1114 return true; 1115 } 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1117 return false; 1118 } 1119 1120 private void disconnectService() { 1121 mContainerService = null; 1122 mBound = false; 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1124 mContext.unbindService(mDefContainerConn); 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 1128 PackageHandler(Looper looper) { 1129 super(looper); 1130 } 1131 1132 public void handleMessage(Message msg) { 1133 try { 1134 doHandleMessage(msg); 1135 } finally { 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } 1138 } 1139 1140 void doHandleMessage(Message msg) { 1141 switch (msg.what) { 1142 case INIT_COPY: { 1143 HandlerParams params = (HandlerParams) msg.obj; 1144 int idx = mPendingInstalls.size(); 1145 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1146 // If a bind was already initiated we dont really 1147 // need to do anything. The pending install 1148 // will be processed later on. 1149 if (!mBound) { 1150 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1151 System.identityHashCode(mHandler)); 1152 // If this is the only one pending we might 1153 // have to bind to the service again. 1154 if (!connectToService()) { 1155 Slog.e(TAG, "Failed to bind to media container service"); 1156 params.serviceError(); 1157 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1158 System.identityHashCode(mHandler)); 1159 if (params.traceMethod != null) { 1160 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1161 params.traceCookie); 1162 } 1163 return; 1164 } else { 1165 // Once we bind to the service, the first 1166 // pending request will be processed. 1167 mPendingInstalls.add(idx, params); 1168 } 1169 } else { 1170 mPendingInstalls.add(idx, params); 1171 // Already bound to the service. Just make 1172 // sure we trigger off processing the first request. 1173 if (idx == 0) { 1174 mHandler.sendEmptyMessage(MCS_BOUND); 1175 } 1176 } 1177 break; 1178 } 1179 case MCS_BOUND: { 1180 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1181 if (msg.obj != null) { 1182 mContainerService = (IMediaContainerService) msg.obj; 1183 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1184 System.identityHashCode(mHandler)); 1185 } 1186 if (mContainerService == null) { 1187 if (!mBound) { 1188 // Something seriously wrong since we are not bound and we are not 1189 // waiting for connection. Bail out. 1190 Slog.e(TAG, "Cannot bind to media container service"); 1191 for (HandlerParams params : mPendingInstalls) { 1192 // Indicate service bind error 1193 params.serviceError(); 1194 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1195 System.identityHashCode(params)); 1196 if (params.traceMethod != null) { 1197 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1198 params.traceMethod, params.traceCookie); 1199 } 1200 return; 1201 } 1202 mPendingInstalls.clear(); 1203 } else { 1204 Slog.w(TAG, "Waiting to connect to media container service"); 1205 } 1206 } else if (mPendingInstalls.size() > 0) { 1207 HandlerParams params = mPendingInstalls.get(0); 1208 if (params != null) { 1209 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1210 System.identityHashCode(params)); 1211 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1212 if (params.startCopy()) { 1213 // We are done... look for more work or to 1214 // go idle. 1215 if (DEBUG_SD_INSTALL) Log.i(TAG, 1216 "Checking for more work or unbind..."); 1217 // Delete pending install 1218 if (mPendingInstalls.size() > 0) { 1219 mPendingInstalls.remove(0); 1220 } 1221 if (mPendingInstalls.size() == 0) { 1222 if (mBound) { 1223 if (DEBUG_SD_INSTALL) Log.i(TAG, 1224 "Posting delayed MCS_UNBIND"); 1225 removeMessages(MCS_UNBIND); 1226 Message ubmsg = obtainMessage(MCS_UNBIND); 1227 // Unbind after a little delay, to avoid 1228 // continual thrashing. 1229 sendMessageDelayed(ubmsg, 10000); 1230 } 1231 } else { 1232 // There are more pending requests in queue. 1233 // Just post MCS_BOUND message to trigger processing 1234 // of next pending install. 1235 if (DEBUG_SD_INSTALL) Log.i(TAG, 1236 "Posting MCS_BOUND for next work"); 1237 mHandler.sendEmptyMessage(MCS_BOUND); 1238 } 1239 } 1240 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1241 } 1242 } else { 1243 // Should never happen ideally. 1244 Slog.w(TAG, "Empty queue"); 1245 } 1246 break; 1247 } 1248 case MCS_RECONNECT: { 1249 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1250 if (mPendingInstalls.size() > 0) { 1251 if (mBound) { 1252 disconnectService(); 1253 } 1254 if (!connectToService()) { 1255 Slog.e(TAG, "Failed to bind to media container service"); 1256 for (HandlerParams params : mPendingInstalls) { 1257 // Indicate service bind error 1258 params.serviceError(); 1259 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1260 System.identityHashCode(params)); 1261 } 1262 mPendingInstalls.clear(); 1263 } 1264 } 1265 break; 1266 } 1267 case MCS_UNBIND: { 1268 // If there is no actual work left, then time to unbind. 1269 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1270 1271 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1272 if (mBound) { 1273 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1274 1275 disconnectService(); 1276 } 1277 } else if (mPendingInstalls.size() > 0) { 1278 // There are more pending requests in queue. 1279 // Just post MCS_BOUND message to trigger processing 1280 // of next pending install. 1281 mHandler.sendEmptyMessage(MCS_BOUND); 1282 } 1283 1284 break; 1285 } 1286 case MCS_GIVE_UP: { 1287 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1288 HandlerParams params = mPendingInstalls.remove(0); 1289 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1290 System.identityHashCode(params)); 1291 break; 1292 } 1293 case SEND_PENDING_BROADCAST: { 1294 String packages[]; 1295 ArrayList<String> components[]; 1296 int size = 0; 1297 int uids[]; 1298 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1299 synchronized (mPackages) { 1300 if (mPendingBroadcasts == null) { 1301 return; 1302 } 1303 size = mPendingBroadcasts.size(); 1304 if (size <= 0) { 1305 // Nothing to be done. Just return 1306 return; 1307 } 1308 packages = new String[size]; 1309 components = new ArrayList[size]; 1310 uids = new int[size]; 1311 int i = 0; // filling out the above arrays 1312 1313 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1314 int packageUserId = mPendingBroadcasts.userIdAt(n); 1315 Iterator<Map.Entry<String, ArrayList<String>>> it 1316 = mPendingBroadcasts.packagesForUserId(packageUserId) 1317 .entrySet().iterator(); 1318 while (it.hasNext() && i < size) { 1319 Map.Entry<String, ArrayList<String>> ent = it.next(); 1320 packages[i] = ent.getKey(); 1321 components[i] = ent.getValue(); 1322 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1323 uids[i] = (ps != null) 1324 ? UserHandle.getUid(packageUserId, ps.appId) 1325 : -1; 1326 i++; 1327 } 1328 } 1329 size = i; 1330 mPendingBroadcasts.clear(); 1331 } 1332 // Send broadcasts 1333 for (int i = 0; i < size; i++) { 1334 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 break; 1338 } 1339 case START_CLEANING_PACKAGE: { 1340 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1341 final String packageName = (String)msg.obj; 1342 final int userId = msg.arg1; 1343 final boolean andCode = msg.arg2 != 0; 1344 synchronized (mPackages) { 1345 if (userId == UserHandle.USER_ALL) { 1346 int[] users = sUserManager.getUserIds(); 1347 for (int user : users) { 1348 mSettings.addPackageToCleanLPw( 1349 new PackageCleanItem(user, packageName, andCode)); 1350 } 1351 } else { 1352 mSettings.addPackageToCleanLPw( 1353 new PackageCleanItem(userId, packageName, andCode)); 1354 } 1355 } 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 startCleaningPackages(); 1358 } break; 1359 case POST_INSTALL: { 1360 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1361 PostInstallData data = mRunningInstalls.get(msg.arg1); 1362 mRunningInstalls.delete(msg.arg1); 1363 boolean deleteOld = false; 1364 1365 if (data != null) { 1366 InstallArgs args = data.args; 1367 PackageInstalledInfo res = data.res; 1368 1369 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1370 final String packageName = res.pkg.applicationInfo.packageName; 1371 res.removedInfo.sendBroadcast(false, true, false); 1372 Bundle extras = new Bundle(1); 1373 extras.putInt(Intent.EXTRA_UID, res.uid); 1374 1375 // Now that we successfully installed the package, grant runtime 1376 // permissions if requested before broadcasting the install. 1377 if ((args.installFlags 1378 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1379 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1380 args.installGrantPermissions); 1381 } 1382 1383 // Determine the set of users who are adding this 1384 // package for the first time vs. those who are seeing 1385 // an update. 1386 int[] firstUsers; 1387 int[] updateUsers = new int[0]; 1388 if (res.origUsers == null || res.origUsers.length == 0) { 1389 firstUsers = res.newUsers; 1390 } else { 1391 firstUsers = new int[0]; 1392 for (int i=0; i<res.newUsers.length; i++) { 1393 int user = res.newUsers[i]; 1394 boolean isNew = true; 1395 for (int j=0; j<res.origUsers.length; j++) { 1396 if (res.origUsers[j] == user) { 1397 isNew = false; 1398 break; 1399 } 1400 } 1401 if (isNew) { 1402 int[] newFirst = new int[firstUsers.length+1]; 1403 System.arraycopy(firstUsers, 0, newFirst, 0, 1404 firstUsers.length); 1405 newFirst[firstUsers.length] = user; 1406 firstUsers = newFirst; 1407 } else { 1408 int[] newUpdate = new int[updateUsers.length+1]; 1409 System.arraycopy(updateUsers, 0, newUpdate, 0, 1410 updateUsers.length); 1411 newUpdate[updateUsers.length] = user; 1412 updateUsers = newUpdate; 1413 } 1414 } 1415 } 1416 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1417 packageName, extras, null, null, firstUsers); 1418 final boolean update = res.removedInfo.removedPackage != null; 1419 if (update) { 1420 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1421 } 1422 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1423 packageName, extras, null, null, updateUsers); 1424 if (update) { 1425 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1426 packageName, extras, null, null, updateUsers); 1427 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1428 null, null, packageName, null, updateUsers); 1429 1430 // treat asec-hosted packages like removable media on upgrade 1431 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1432 if (DEBUG_INSTALL) { 1433 Slog.i(TAG, "upgrading pkg " + res.pkg 1434 + " is ASEC-hosted -> AVAILABLE"); 1435 } 1436 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1437 ArrayList<String> pkgList = new ArrayList<String>(1); 1438 pkgList.add(packageName); 1439 sendResourcesChangedBroadcast(true, true, 1440 pkgList,uidArray, null); 1441 } 1442 } 1443 if (res.removedInfo.args != null) { 1444 // Remove the replaced package's older resources safely now 1445 deleteOld = true; 1446 } 1447 1448 // If this app is a browser and it's newly-installed for some 1449 // users, clear any default-browser state in those users 1450 if (firstUsers.length > 0) { 1451 // the app's nature doesn't depend on the user, so we can just 1452 // check its browser nature in any user and generalize. 1453 if (packageIsBrowser(packageName, firstUsers[0])) { 1454 synchronized (mPackages) { 1455 for (int userId : firstUsers) { 1456 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1457 } 1458 } 1459 } 1460 } 1461 // Log current value of "unknown sources" setting 1462 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1463 getUnknownSourcesSettings()); 1464 } 1465 // Force a gc to clear up things 1466 Runtime.getRuntime().gc(); 1467 // We delete after a gc for applications on sdcard. 1468 if (deleteOld) { 1469 synchronized (mInstallLock) { 1470 res.removedInfo.args.doPostDeleteLI(true); 1471 } 1472 } 1473 if (args.observer != null) { 1474 try { 1475 Bundle extras = extrasForInstallResult(res); 1476 args.observer.onPackageInstalled(res.name, res.returnCode, 1477 res.returnMsg, extras); 1478 } catch (RemoteException e) { 1479 Slog.i(TAG, "Observer no longer exists."); 1480 } 1481 } 1482 if (args.traceMethod != null) { 1483 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1484 args.traceCookie); 1485 } 1486 return; 1487 } else { 1488 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1489 } 1490 1491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1492 } break; 1493 case UPDATED_MEDIA_STATUS: { 1494 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1495 boolean reportStatus = msg.arg1 == 1; 1496 boolean doGc = msg.arg2 == 1; 1497 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1498 if (doGc) { 1499 // Force a gc to clear up stale containers. 1500 Runtime.getRuntime().gc(); 1501 } 1502 if (msg.obj != null) { 1503 @SuppressWarnings("unchecked") 1504 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1506 // Unload containers 1507 unloadAllContainers(args); 1508 } 1509 if (reportStatus) { 1510 try { 1511 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1512 PackageHelper.getMountService().finishMediaUpdate(); 1513 } catch (RemoteException e) { 1514 Log.e(TAG, "MountService not running?"); 1515 } 1516 } 1517 } break; 1518 case WRITE_SETTINGS: { 1519 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1520 synchronized (mPackages) { 1521 removeMessages(WRITE_SETTINGS); 1522 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1523 mSettings.writeLPr(); 1524 mDirtyUsers.clear(); 1525 } 1526 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1527 } break; 1528 case WRITE_PACKAGE_RESTRICTIONS: { 1529 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1530 synchronized (mPackages) { 1531 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1532 for (int userId : mDirtyUsers) { 1533 mSettings.writePackageRestrictionsLPr(userId); 1534 } 1535 mDirtyUsers.clear(); 1536 } 1537 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1538 } break; 1539 case CHECK_PENDING_VERIFICATION: { 1540 final int verificationId = msg.arg1; 1541 final PackageVerificationState state = mPendingVerification.get(verificationId); 1542 1543 if ((state != null) && !state.timeoutExtended()) { 1544 final InstallArgs args = state.getInstallArgs(); 1545 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1546 1547 Slog.i(TAG, "Verification timed out for " + originUri); 1548 mPendingVerification.remove(verificationId); 1549 1550 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1551 1552 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1553 Slog.i(TAG, "Continuing with installation of " + originUri); 1554 state.setVerifierResponse(Binder.getCallingUid(), 1555 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1556 broadcastPackageVerified(verificationId, originUri, 1557 PackageManager.VERIFICATION_ALLOW, 1558 state.getInstallArgs().getUser()); 1559 try { 1560 ret = args.copyApk(mContainerService, true); 1561 } catch (RemoteException e) { 1562 Slog.e(TAG, "Could not contact the ContainerService"); 1563 } 1564 } else { 1565 broadcastPackageVerified(verificationId, originUri, 1566 PackageManager.VERIFICATION_REJECT, 1567 state.getInstallArgs().getUser()); 1568 } 1569 1570 Trace.asyncTraceEnd( 1571 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1572 1573 processPendingInstall(args, ret); 1574 mHandler.sendEmptyMessage(MCS_UNBIND); 1575 } 1576 break; 1577 } 1578 case PACKAGE_VERIFIED: { 1579 final int verificationId = msg.arg1; 1580 1581 final PackageVerificationState state = mPendingVerification.get(verificationId); 1582 if (state == null) { 1583 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1584 break; 1585 } 1586 1587 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1588 1589 state.setVerifierResponse(response.callerUid, response.code); 1590 1591 if (state.isVerificationComplete()) { 1592 mPendingVerification.remove(verificationId); 1593 1594 final InstallArgs args = state.getInstallArgs(); 1595 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1596 1597 int ret; 1598 if (state.isInstallAllowed()) { 1599 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1600 broadcastPackageVerified(verificationId, originUri, 1601 response.code, state.getInstallArgs().getUser()); 1602 try { 1603 ret = args.copyApk(mContainerService, true); 1604 } catch (RemoteException e) { 1605 Slog.e(TAG, "Could not contact the ContainerService"); 1606 } 1607 } else { 1608 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1609 } 1610 1611 Trace.asyncTraceEnd( 1612 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1613 1614 processPendingInstall(args, ret); 1615 mHandler.sendEmptyMessage(MCS_UNBIND); 1616 } 1617 1618 break; 1619 } 1620 case START_INTENT_FILTER_VERIFICATIONS: { 1621 IFVerificationParams params = (IFVerificationParams) msg.obj; 1622 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1623 params.replacing, params.pkg); 1624 break; 1625 } 1626 case INTENT_FILTER_VERIFIED: { 1627 final int verificationId = msg.arg1; 1628 1629 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1630 verificationId); 1631 if (state == null) { 1632 Slog.w(TAG, "Invalid IntentFilter verification token " 1633 + verificationId + " received"); 1634 break; 1635 } 1636 1637 final int userId = state.getUserId(); 1638 1639 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1640 "Processing IntentFilter verification with token:" 1641 + verificationId + " and userId:" + userId); 1642 1643 final IntentFilterVerificationResponse response = 1644 (IntentFilterVerificationResponse) msg.obj; 1645 1646 state.setVerifierResponse(response.callerUid, response.code); 1647 1648 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1649 "IntentFilter verification with token:" + verificationId 1650 + " and userId:" + userId 1651 + " is settings verifier response with response code:" 1652 + response.code); 1653 1654 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1655 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1656 + response.getFailedDomainsString()); 1657 } 1658 1659 if (state.isVerificationComplete()) { 1660 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1661 } else { 1662 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1663 "IntentFilter verification with token:" + verificationId 1664 + " was not said to be complete"); 1665 } 1666 1667 break; 1668 } 1669 } 1670 } 1671 } 1672 1673 private StorageEventListener mStorageListener = new StorageEventListener() { 1674 @Override 1675 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1676 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1677 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1678 final String volumeUuid = vol.getFsUuid(); 1679 1680 // Clean up any users or apps that were removed or recreated 1681 // while this volume was missing 1682 reconcileUsers(volumeUuid); 1683 reconcileApps(volumeUuid); 1684 1685 // Clean up any install sessions that expired or were 1686 // cancelled while this volume was missing 1687 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1688 1689 loadPrivatePackages(vol); 1690 1691 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1692 unloadPrivatePackages(vol); 1693 } 1694 } 1695 1696 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1697 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1698 updateExternalMediaStatus(true, false); 1699 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1700 updateExternalMediaStatus(false, false); 1701 } 1702 } 1703 } 1704 1705 @Override 1706 public void onVolumeForgotten(String fsUuid) { 1707 if (TextUtils.isEmpty(fsUuid)) { 1708 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1709 return; 1710 } 1711 1712 // Remove any apps installed on the forgotten volume 1713 synchronized (mPackages) { 1714 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1715 for (PackageSetting ps : packages) { 1716 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1717 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1718 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1719 } 1720 1721 mSettings.onVolumeForgotten(fsUuid); 1722 mSettings.writeLPr(); 1723 } 1724 } 1725 }; 1726 1727 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1728 String[] grantedPermissions) { 1729 if (userId >= UserHandle.USER_SYSTEM) { 1730 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1731 } else if (userId == UserHandle.USER_ALL) { 1732 final int[] userIds; 1733 synchronized (mPackages) { 1734 userIds = UserManagerService.getInstance().getUserIds(); 1735 } 1736 for (int someUserId : userIds) { 1737 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1738 } 1739 } 1740 1741 // We could have touched GID membership, so flush out packages.list 1742 synchronized (mPackages) { 1743 mSettings.writePackageListLPr(); 1744 } 1745 } 1746 1747 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1748 String[] grantedPermissions) { 1749 SettingBase sb = (SettingBase) pkg.mExtras; 1750 if (sb == null) { 1751 return; 1752 } 1753 1754 PermissionsState permissionsState = sb.getPermissionsState(); 1755 1756 for (String permission : pkg.requestedPermissions) { 1757 BasePermission bp = mSettings.mPermissions.get(permission); 1758 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1759 || ArrayUtils.contains(grantedPermissions, permission))) { 1760 permissionsState.grantRuntimePermission(bp, userId); 1761 } 1762 } 1763 } 1764 1765 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1766 Bundle extras = null; 1767 switch (res.returnCode) { 1768 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1769 extras = new Bundle(); 1770 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1771 res.origPermission); 1772 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1773 res.origPackage); 1774 break; 1775 } 1776 case PackageManager.INSTALL_SUCCEEDED: { 1777 extras = new Bundle(); 1778 extras.putBoolean(Intent.EXTRA_REPLACING, 1779 res.removedInfo != null && res.removedInfo.removedPackage != null); 1780 break; 1781 } 1782 } 1783 return extras; 1784 } 1785 1786 void scheduleWriteSettingsLocked() { 1787 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1788 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1789 } 1790 } 1791 1792 void scheduleWritePackageRestrictionsLocked(int userId) { 1793 if (!sUserManager.exists(userId)) return; 1794 mDirtyUsers.add(userId); 1795 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1796 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1797 } 1798 } 1799 1800 public static PackageManagerService main(Context context, Installer installer, 1801 boolean factoryTest, boolean onlyCore) { 1802 PackageManagerService m = new PackageManagerService(context, installer, 1803 factoryTest, onlyCore); 1804 ServiceManager.addService("package", m); 1805 return m; 1806 } 1807 1808 static String[] splitString(String str, char sep) { 1809 int count = 1; 1810 int i = 0; 1811 while ((i=str.indexOf(sep, i)) >= 0) { 1812 count++; 1813 i++; 1814 } 1815 1816 String[] res = new String[count]; 1817 i=0; 1818 count = 0; 1819 int lastI=0; 1820 while ((i=str.indexOf(sep, i)) >= 0) { 1821 res[count] = str.substring(lastI, i); 1822 count++; 1823 i++; 1824 lastI = i; 1825 } 1826 res[count] = str.substring(lastI, str.length()); 1827 return res; 1828 } 1829 1830 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1831 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1832 Context.DISPLAY_SERVICE); 1833 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1834 } 1835 1836 public PackageManagerService(Context context, Installer installer, 1837 boolean factoryTest, boolean onlyCore) { 1838 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1839 SystemClock.uptimeMillis()); 1840 1841 if (mSdkVersion <= 0) { 1842 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1843 } 1844 1845 mContext = context; 1846 mFactoryTest = factoryTest; 1847 mOnlyCore = onlyCore; 1848 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1849 mMetrics = new DisplayMetrics(); 1850 mSettings = new Settings(mPackages); 1851 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1852 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1853 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1854 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1855 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1856 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1857 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1858 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1859 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1860 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1861 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1862 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1863 1864 // TODO: add a property to control this? 1865 long dexOptLRUThresholdInMinutes; 1866 if (mLazyDexOpt) { 1867 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1868 } else { 1869 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1870 } 1871 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1872 1873 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1874 if (separateProcesses != null && separateProcesses.length() > 0) { 1875 if ("*".equals(separateProcesses)) { 1876 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1877 mSeparateProcesses = null; 1878 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1879 } else { 1880 mDefParseFlags = 0; 1881 mSeparateProcesses = separateProcesses.split(","); 1882 Slog.w(TAG, "Running with debug.separate_processes: " 1883 + separateProcesses); 1884 } 1885 } else { 1886 mDefParseFlags = 0; 1887 mSeparateProcesses = null; 1888 } 1889 1890 mInstaller = installer; 1891 mPackageDexOptimizer = new PackageDexOptimizer(this); 1892 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1893 1894 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1895 FgThread.get().getLooper()); 1896 1897 getDefaultDisplayMetrics(context, mMetrics); 1898 1899 SystemConfig systemConfig = SystemConfig.getInstance(); 1900 mGlobalGids = systemConfig.getGlobalGids(); 1901 mSystemPermissions = systemConfig.getSystemPermissions(); 1902 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1903 1904 synchronized (mInstallLock) { 1905 // writer 1906 synchronized (mPackages) { 1907 mHandlerThread = new ServiceThread(TAG, 1908 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1909 mHandlerThread.start(); 1910 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1911 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1912 1913 File dataDir = Environment.getDataDirectory(); 1914 mAppDataDir = new File(dataDir, "data"); 1915 mAppInstallDir = new File(dataDir, "app"); 1916 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1917 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1918 mUserAppDataDir = new File(dataDir, "user"); 1919 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1920 1921 sUserManager = new UserManagerService(context, this, 1922 mInstallLock, mPackages); 1923 1924 // Propagate permission configuration in to package manager. 1925 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1926 = systemConfig.getPermissions(); 1927 for (int i=0; i<permConfig.size(); i++) { 1928 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1929 BasePermission bp = mSettings.mPermissions.get(perm.name); 1930 if (bp == null) { 1931 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1932 mSettings.mPermissions.put(perm.name, bp); 1933 } 1934 if (perm.gids != null) { 1935 bp.setGids(perm.gids, perm.perUser); 1936 } 1937 } 1938 1939 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1940 for (int i=0; i<libConfig.size(); i++) { 1941 mSharedLibraries.put(libConfig.keyAt(i), 1942 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1943 } 1944 1945 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1946 1947 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1948 1949 String customResolverActivity = Resources.getSystem().getString( 1950 R.string.config_customResolverActivity); 1951 if (TextUtils.isEmpty(customResolverActivity)) { 1952 customResolverActivity = null; 1953 } else { 1954 mCustomResolverComponentName = ComponentName.unflattenFromString( 1955 customResolverActivity); 1956 } 1957 1958 long startTime = SystemClock.uptimeMillis(); 1959 1960 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1961 startTime); 1962 1963 // Set flag to monitor and not change apk file paths when 1964 // scanning install directories. 1965 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1966 1967 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1968 1969 /** 1970 * Add everything in the in the boot class path to the 1971 * list of process files because dexopt will have been run 1972 * if necessary during zygote startup. 1973 */ 1974 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1975 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1976 1977 if (bootClassPath != null) { 1978 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1979 for (String element : bootClassPathElements) { 1980 alreadyDexOpted.add(element); 1981 } 1982 } else { 1983 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1984 } 1985 1986 if (systemServerClassPath != null) { 1987 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1988 for (String element : systemServerClassPathElements) { 1989 alreadyDexOpted.add(element); 1990 } 1991 } else { 1992 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1993 } 1994 1995 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1996 final String[] dexCodeInstructionSets = 1997 getDexCodeInstructionSets( 1998 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1999 2000 /** 2001 * Ensure all external libraries have had dexopt run on them. 2002 */ 2003 if (mSharedLibraries.size() > 0) { 2004 // NOTE: For now, we're compiling these system "shared libraries" 2005 // (and framework jars) into all available architectures. It's possible 2006 // to compile them only when we come across an app that uses them (there's 2007 // already logic for that in scanPackageLI) but that adds some complexity. 2008 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2009 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2010 final String lib = libEntry.path; 2011 if (lib == null) { 2012 continue; 2013 } 2014 2015 try { 2016 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2017 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2018 alreadyDexOpted.add(lib); 2019 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2020 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2021 } 2022 } catch (FileNotFoundException e) { 2023 Slog.w(TAG, "Library not found: " + lib); 2024 } catch (IOException e) { 2025 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2026 + e.getMessage()); 2027 } 2028 } 2029 } 2030 } 2031 2032 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2033 2034 // Gross hack for now: we know this file doesn't contain any 2035 // code, so don't dexopt it to avoid the resulting log spew. 2036 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2037 2038 // Gross hack for now: we know this file is only part of 2039 // the boot class path for art, so don't dexopt it to 2040 // avoid the resulting log spew. 2041 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2042 2043 /** 2044 * There are a number of commands implemented in Java, which 2045 * we currently need to do the dexopt on so that they can be 2046 * run from a non-root shell. 2047 */ 2048 String[] frameworkFiles = frameworkDir.list(); 2049 if (frameworkFiles != null) { 2050 // TODO: We could compile these only for the most preferred ABI. We should 2051 // first double check that the dex files for these commands are not referenced 2052 // by other system apps. 2053 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2054 for (int i=0; i<frameworkFiles.length; i++) { 2055 File libPath = new File(frameworkDir, frameworkFiles[i]); 2056 String path = libPath.getPath(); 2057 // Skip the file if we already did it. 2058 if (alreadyDexOpted.contains(path)) { 2059 continue; 2060 } 2061 // Skip the file if it is not a type we want to dexopt. 2062 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2063 continue; 2064 } 2065 try { 2066 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2067 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2068 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 2069 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2070 } 2071 } catch (FileNotFoundException e) { 2072 Slog.w(TAG, "Jar not found: " + path); 2073 } catch (IOException e) { 2074 Slog.w(TAG, "Exception reading jar: " + path, e); 2075 } 2076 } 2077 } 2078 } 2079 2080 final VersionInfo ver = mSettings.getInternalVersion(); 2081 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2082 // when upgrading from pre-M, promote system app permissions from install to runtime 2083 mPromoteSystemApps = 2084 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2085 2086 // save off the names of pre-existing system packages prior to scanning; we don't 2087 // want to automatically grant runtime permissions for new system apps 2088 if (mPromoteSystemApps) { 2089 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2090 while (pkgSettingIter.hasNext()) { 2091 PackageSetting ps = pkgSettingIter.next(); 2092 if (isSystemApp(ps)) { 2093 mExistingSystemPackages.add(ps.name); 2094 } 2095 } 2096 } 2097 2098 // Collect vendor overlay packages. 2099 // (Do this before scanning any apps.) 2100 // For security and version matching reason, only consider 2101 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2102 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2103 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2104 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2105 2106 // Find base frameworks (resource packages without code). 2107 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2108 | PackageParser.PARSE_IS_SYSTEM_DIR 2109 | PackageParser.PARSE_IS_PRIVILEGED, 2110 scanFlags | SCAN_NO_DEX, 0); 2111 2112 // Collected privileged system packages. 2113 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2114 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR 2116 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2117 2118 // Collect ordinary system packages. 2119 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2120 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2121 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2122 2123 // Collect all vendor packages. 2124 File vendorAppDir = new File("/vendor/app"); 2125 try { 2126 vendorAppDir = vendorAppDir.getCanonicalFile(); 2127 } catch (IOException e) { 2128 // failed to look up canonical path, continue with original one 2129 } 2130 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2131 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2132 2133 // Collect all OEM packages. 2134 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2135 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2136 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2137 2138 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2139 mInstaller.moveFiles(); 2140 2141 // Prune any system packages that no longer exist. 2142 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2143 if (!mOnlyCore) { 2144 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2145 while (psit.hasNext()) { 2146 PackageSetting ps = psit.next(); 2147 2148 /* 2149 * If this is not a system app, it can't be a 2150 * disable system app. 2151 */ 2152 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2153 continue; 2154 } 2155 2156 /* 2157 * If the package is scanned, it's not erased. 2158 */ 2159 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2160 if (scannedPkg != null) { 2161 /* 2162 * If the system app is both scanned and in the 2163 * disabled packages list, then it must have been 2164 * added via OTA. Remove it from the currently 2165 * scanned package so the previously user-installed 2166 * application can be scanned. 2167 */ 2168 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2169 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2170 + ps.name + "; removing system app. Last known codePath=" 2171 + ps.codePathString + ", installStatus=" + ps.installStatus 2172 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2173 + scannedPkg.mVersionCode); 2174 removePackageLI(ps, true); 2175 mExpectingBetter.put(ps.name, ps.codePath); 2176 } 2177 2178 continue; 2179 } 2180 2181 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2182 psit.remove(); 2183 logCriticalInfo(Log.WARN, "System package " + ps.name 2184 + " no longer exists; wiping its data"); 2185 removeDataDirsLI(null, ps.name); 2186 } else { 2187 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2188 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2189 possiblyDeletedUpdatedSystemApps.add(ps.name); 2190 } 2191 } 2192 } 2193 } 2194 2195 //look for any incomplete package installations 2196 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2197 //clean up list 2198 for(int i = 0; i < deletePkgsList.size(); i++) { 2199 //clean up here 2200 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2201 } 2202 //delete tmp files 2203 deleteTempPackageFiles(); 2204 2205 // Remove any shared userIDs that have no associated packages 2206 mSettings.pruneSharedUsersLPw(); 2207 2208 if (!mOnlyCore) { 2209 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2210 SystemClock.uptimeMillis()); 2211 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2212 2213 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2214 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2215 2216 /** 2217 * Remove disable package settings for any updated system 2218 * apps that were removed via an OTA. If they're not a 2219 * previously-updated app, remove them completely. 2220 * Otherwise, just revoke their system-level permissions. 2221 */ 2222 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2223 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2224 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2225 2226 String msg; 2227 if (deletedPkg == null) { 2228 msg = "Updated system package " + deletedAppName 2229 + " no longer exists; wiping its data"; 2230 removeDataDirsLI(null, deletedAppName); 2231 } else { 2232 msg = "Updated system app + " + deletedAppName 2233 + " no longer present; removing system privileges for " 2234 + deletedAppName; 2235 2236 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2237 2238 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2239 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2240 } 2241 logCriticalInfo(Log.WARN, msg); 2242 } 2243 2244 /** 2245 * Make sure all system apps that we expected to appear on 2246 * the userdata partition actually showed up. If they never 2247 * appeared, crawl back and revive the system version. 2248 */ 2249 for (int i = 0; i < mExpectingBetter.size(); i++) { 2250 final String packageName = mExpectingBetter.keyAt(i); 2251 if (!mPackages.containsKey(packageName)) { 2252 final File scanFile = mExpectingBetter.valueAt(i); 2253 2254 logCriticalInfo(Log.WARN, "Expected better " + packageName 2255 + " but never showed up; reverting to system"); 2256 2257 final int reparseFlags; 2258 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2259 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2260 | PackageParser.PARSE_IS_SYSTEM_DIR 2261 | PackageParser.PARSE_IS_PRIVILEGED; 2262 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2263 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2264 | PackageParser.PARSE_IS_SYSTEM_DIR; 2265 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2266 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2267 | PackageParser.PARSE_IS_SYSTEM_DIR; 2268 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2269 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2270 | PackageParser.PARSE_IS_SYSTEM_DIR; 2271 } else { 2272 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2273 continue; 2274 } 2275 2276 mSettings.enableSystemPackageLPw(packageName); 2277 2278 try { 2279 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, UserHandle.SYSTEM); 2280 } catch (PackageManagerException e) { 2281 Slog.e(TAG, "Failed to parse original system package: " 2282 + e.getMessage()); 2283 } 2284 } 2285 } 2286 } 2287 mExpectingBetter.clear(); 2288 2289 // Now that we know all of the shared libraries, update all clients to have 2290 // the correct library paths. 2291 updateAllSharedLibrariesLPw(); 2292 2293 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2294 // NOTE: We ignore potential failures here during a system scan (like 2295 // the rest of the commands above) because there's precious little we 2296 // can do about it. A settings error is reported, though. 2297 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2298 false /* force dexopt */, false /* defer dexopt */, 2299 false /* boot complete */); 2300 } 2301 2302 // Now that we know all the packages we are keeping, 2303 // read and update their last usage times. 2304 mPackageUsage.readLP(); 2305 2306 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2307 SystemClock.uptimeMillis()); 2308 Slog.i(TAG, "Time to scan packages: " 2309 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2310 + " seconds"); 2311 2312 // If the platform SDK has changed since the last time we booted, 2313 // we need to re-grant app permission to catch any new ones that 2314 // appear. This is really a hack, and means that apps can in some 2315 // cases get permissions that the user didn't initially explicitly 2316 // allow... it would be nice to have some better way to handle 2317 // this situation. 2318 int updateFlags = UPDATE_PERMISSIONS_ALL; 2319 if (ver.sdkVersion != mSdkVersion) { 2320 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2321 + mSdkVersion + "; regranting permissions for internal storage"); 2322 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2323 } 2324 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2325 ver.sdkVersion = mSdkVersion; 2326 2327 // If this is the first boot or an update from pre-M, and it is a normal 2328 // boot, then we need to initialize the default preferred apps across 2329 // all defined users. 2330 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2331 for (UserInfo user : sUserManager.getUsers(true)) { 2332 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2333 applyFactoryDefaultBrowserLPw(user.id); 2334 primeDomainVerificationsLPw(user.id); 2335 } 2336 } 2337 2338 // If this is first boot after an OTA, and a normal boot, then 2339 // we need to clear code cache directories. 2340 if (mIsUpgrade && !onlyCore) { 2341 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2342 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2343 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2344 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2345 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2346 } 2347 } 2348 ver.fingerprint = Build.FINGERPRINT; 2349 } 2350 2351 checkDefaultBrowser(); 2352 2353 // clear only after permissions and other defaults have been updated 2354 mExistingSystemPackages.clear(); 2355 mPromoteSystemApps = false; 2356 2357 // All the changes are done during package scanning. 2358 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2359 2360 // can downgrade to reader 2361 mSettings.writeLPr(); 2362 2363 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2364 SystemClock.uptimeMillis()); 2365 2366 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2367 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2368 2369 mInstallerService = new PackageInstallerService(context, this); 2370 2371 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2372 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2373 mIntentFilterVerifierComponent); 2374 2375 } // synchronized (mPackages) 2376 } // synchronized (mInstallLock) 2377 2378 // Now after opening every single application zip, make sure they 2379 // are all flushed. Not really needed, but keeps things nice and 2380 // tidy. 2381 Runtime.getRuntime().gc(); 2382 2383 // Expose private service for system components to use. 2384 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2385 } 2386 2387 @Override 2388 public boolean isFirstBoot() { 2389 return !mRestoredSettings; 2390 } 2391 2392 @Override 2393 public boolean isOnlyCoreApps() { 2394 return mOnlyCore; 2395 } 2396 2397 @Override 2398 public boolean isUpgrade() { 2399 return mIsUpgrade; 2400 } 2401 2402 private String getRequiredVerifierLPr() { 2403 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2404 // We only care about verifier that's installed under system user. 2405 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2406 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2407 2408 String requiredVerifier = null; 2409 2410 final int N = receivers.size(); 2411 for (int i = 0; i < N; i++) { 2412 final ResolveInfo info = receivers.get(i); 2413 2414 if (info.activityInfo == null) { 2415 continue; 2416 } 2417 2418 final String packageName = info.activityInfo.packageName; 2419 2420 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2421 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2422 continue; 2423 } 2424 2425 if (requiredVerifier != null) { 2426 throw new RuntimeException("There can be only one required verifier"); 2427 } 2428 2429 requiredVerifier = packageName; 2430 } 2431 2432 return requiredVerifier; 2433 } 2434 2435 private String getRequiredInstallerLPr() { 2436 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2437 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2438 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2439 2440 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2441 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2442 2443 String requiredInstaller = null; 2444 2445 final int N = installers.size(); 2446 for (int i = 0; i < N; i++) { 2447 final ResolveInfo info = installers.get(i); 2448 final String packageName = info.activityInfo.packageName; 2449 2450 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2451 continue; 2452 } 2453 2454 if (requiredInstaller != null) { 2455 throw new RuntimeException("There must be one required installer"); 2456 } 2457 2458 requiredInstaller = packageName; 2459 } 2460 2461 if (requiredInstaller == null) { 2462 throw new RuntimeException("There must be one required installer"); 2463 } 2464 2465 return requiredInstaller; 2466 } 2467 2468 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2469 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2470 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2471 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2472 2473 ComponentName verifierComponentName = null; 2474 2475 int priority = -1000; 2476 final int N = receivers.size(); 2477 for (int i = 0; i < N; i++) { 2478 final ResolveInfo info = receivers.get(i); 2479 2480 if (info.activityInfo == null) { 2481 continue; 2482 } 2483 2484 final String packageName = info.activityInfo.packageName; 2485 2486 final PackageSetting ps = mSettings.mPackages.get(packageName); 2487 if (ps == null) { 2488 continue; 2489 } 2490 2491 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2492 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2493 continue; 2494 } 2495 2496 // Select the IntentFilterVerifier with the highest priority 2497 if (priority < info.priority) { 2498 priority = info.priority; 2499 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2500 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2501 + verifierComponentName + " with priority: " + info.priority); 2502 } 2503 } 2504 2505 return verifierComponentName; 2506 } 2507 2508 private void primeDomainVerificationsLPw(int userId) { 2509 if (DEBUG_DOMAIN_VERIFICATION) { 2510 Slog.d(TAG, "Priming domain verifications in user " + userId); 2511 } 2512 2513 SystemConfig systemConfig = SystemConfig.getInstance(); 2514 ArraySet<String> packages = systemConfig.getLinkedApps(); 2515 ArraySet<String> domains = new ArraySet<String>(); 2516 2517 for (String packageName : packages) { 2518 PackageParser.Package pkg = mPackages.get(packageName); 2519 if (pkg != null) { 2520 if (!pkg.isSystemApp()) { 2521 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2522 continue; 2523 } 2524 2525 domains.clear(); 2526 for (PackageParser.Activity a : pkg.activities) { 2527 for (ActivityIntentInfo filter : a.intents) { 2528 if (hasValidDomains(filter)) { 2529 domains.addAll(filter.getHostsList()); 2530 } 2531 } 2532 } 2533 2534 if (domains.size() > 0) { 2535 if (DEBUG_DOMAIN_VERIFICATION) { 2536 Slog.v(TAG, " + " + packageName); 2537 } 2538 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2539 // state w.r.t. the formal app-linkage "no verification attempted" state; 2540 // and then 'always' in the per-user state actually used for intent resolution. 2541 final IntentFilterVerificationInfo ivi; 2542 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2543 new ArrayList<String>(domains)); 2544 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2545 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2546 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2547 } else { 2548 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2549 + "' does not handle web links"); 2550 } 2551 } else { 2552 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2553 } 2554 } 2555 2556 scheduleWritePackageRestrictionsLocked(userId); 2557 scheduleWriteSettingsLocked(); 2558 } 2559 2560 private void applyFactoryDefaultBrowserLPw(int userId) { 2561 // The default browser app's package name is stored in a string resource, 2562 // with a product-specific overlay used for vendor customization. 2563 String browserPkg = mContext.getResources().getString( 2564 com.android.internal.R.string.default_browser); 2565 if (!TextUtils.isEmpty(browserPkg)) { 2566 // non-empty string => required to be a known package 2567 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2568 if (ps == null) { 2569 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2570 browserPkg = null; 2571 } else { 2572 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2573 } 2574 } 2575 2576 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2577 // default. If there's more than one, just leave everything alone. 2578 if (browserPkg == null) { 2579 calculateDefaultBrowserLPw(userId); 2580 } 2581 } 2582 2583 private void calculateDefaultBrowserLPw(int userId) { 2584 List<String> allBrowsers = resolveAllBrowserApps(userId); 2585 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2586 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2587 } 2588 2589 private List<String> resolveAllBrowserApps(int userId) { 2590 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2591 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2592 PackageManager.MATCH_ALL, userId); 2593 2594 final int count = list.size(); 2595 List<String> result = new ArrayList<String>(count); 2596 for (int i=0; i<count; i++) { 2597 ResolveInfo info = list.get(i); 2598 if (info.activityInfo == null 2599 || !info.handleAllWebDataURI 2600 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2601 || result.contains(info.activityInfo.packageName)) { 2602 continue; 2603 } 2604 result.add(info.activityInfo.packageName); 2605 } 2606 2607 return result; 2608 } 2609 2610 private boolean packageIsBrowser(String packageName, int userId) { 2611 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2612 PackageManager.MATCH_ALL, userId); 2613 final int N = list.size(); 2614 for (int i = 0; i < N; i++) { 2615 ResolveInfo info = list.get(i); 2616 if (packageName.equals(info.activityInfo.packageName)) { 2617 return true; 2618 } 2619 } 2620 return false; 2621 } 2622 2623 private void checkDefaultBrowser() { 2624 final int myUserId = UserHandle.myUserId(); 2625 final String packageName = getDefaultBrowserPackageName(myUserId); 2626 if (packageName != null) { 2627 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2628 if (info == null) { 2629 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2630 synchronized (mPackages) { 2631 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2632 } 2633 } 2634 } 2635 } 2636 2637 @Override 2638 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2639 throws RemoteException { 2640 try { 2641 return super.onTransact(code, data, reply, flags); 2642 } catch (RuntimeException e) { 2643 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2644 Slog.wtf(TAG, "Package Manager Crash", e); 2645 } 2646 throw e; 2647 } 2648 } 2649 2650 void cleanupInstallFailedPackage(PackageSetting ps) { 2651 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2652 2653 removeDataDirsLI(ps.volumeUuid, ps.name); 2654 if (ps.codePath != null) { 2655 if (ps.codePath.isDirectory()) { 2656 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2657 } else { 2658 ps.codePath.delete(); 2659 } 2660 } 2661 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2662 if (ps.resourcePath.isDirectory()) { 2663 FileUtils.deleteContents(ps.resourcePath); 2664 } 2665 ps.resourcePath.delete(); 2666 } 2667 mSettings.removePackageLPw(ps.name); 2668 } 2669 2670 static int[] appendInts(int[] cur, int[] add) { 2671 if (add == null) return cur; 2672 if (cur == null) return add; 2673 final int N = add.length; 2674 for (int i=0; i<N; i++) { 2675 cur = appendInt(cur, add[i]); 2676 } 2677 return cur; 2678 } 2679 2680 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2681 if (!sUserManager.exists(userId)) return null; 2682 final PackageSetting ps = (PackageSetting) p.mExtras; 2683 if (ps == null) { 2684 return null; 2685 } 2686 2687 final PermissionsState permissionsState = ps.getPermissionsState(); 2688 2689 final int[] gids = permissionsState.computeGids(userId); 2690 final Set<String> permissions = permissionsState.getPermissions(userId); 2691 final PackageUserState state = ps.readUserState(userId); 2692 2693 return PackageParser.generatePackageInfo(p, gids, flags, 2694 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2695 } 2696 2697 @Override 2698 public boolean isPackageFrozen(String packageName) { 2699 synchronized (mPackages) { 2700 final PackageSetting ps = mSettings.mPackages.get(packageName); 2701 if (ps != null) { 2702 return ps.frozen; 2703 } 2704 } 2705 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2706 return true; 2707 } 2708 2709 @Override 2710 public boolean isPackageAvailable(String packageName, int userId) { 2711 if (!sUserManager.exists(userId)) return false; 2712 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2713 synchronized (mPackages) { 2714 PackageParser.Package p = mPackages.get(packageName); 2715 if (p != null) { 2716 final PackageSetting ps = (PackageSetting) p.mExtras; 2717 if (ps != null) { 2718 final PackageUserState state = ps.readUserState(userId); 2719 if (state != null) { 2720 return PackageParser.isAvailable(state); 2721 } 2722 } 2723 } 2724 } 2725 return false; 2726 } 2727 2728 @Override 2729 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2730 if (!sUserManager.exists(userId)) return null; 2731 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2732 // reader 2733 synchronized (mPackages) { 2734 PackageParser.Package p = mPackages.get(packageName); 2735 if (DEBUG_PACKAGE_INFO) 2736 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2737 if (p != null) { 2738 return generatePackageInfo(p, flags, userId); 2739 } 2740 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2741 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2742 } 2743 } 2744 return null; 2745 } 2746 2747 @Override 2748 public String[] currentToCanonicalPackageNames(String[] names) { 2749 String[] out = new String[names.length]; 2750 // reader 2751 synchronized (mPackages) { 2752 for (int i=names.length-1; i>=0; i--) { 2753 PackageSetting ps = mSettings.mPackages.get(names[i]); 2754 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2755 } 2756 } 2757 return out; 2758 } 2759 2760 @Override 2761 public String[] canonicalToCurrentPackageNames(String[] names) { 2762 String[] out = new String[names.length]; 2763 // reader 2764 synchronized (mPackages) { 2765 for (int i=names.length-1; i>=0; i--) { 2766 String cur = mSettings.mRenamedPackages.get(names[i]); 2767 out[i] = cur != null ? cur : names[i]; 2768 } 2769 } 2770 return out; 2771 } 2772 2773 @Override 2774 public int getPackageUid(String packageName, int userId) { 2775 if (!sUserManager.exists(userId)) return -1; 2776 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2777 2778 // reader 2779 synchronized (mPackages) { 2780 PackageParser.Package p = mPackages.get(packageName); 2781 if(p != null) { 2782 return UserHandle.getUid(userId, p.applicationInfo.uid); 2783 } 2784 PackageSetting ps = mSettings.mPackages.get(packageName); 2785 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2786 return -1; 2787 } 2788 return UserHandle.getUid(userId, ps.pkg.applicationInfo.uid); 2789 } 2790 } 2791 2792 @Override 2793 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2794 if (!sUserManager.exists(userId)) { 2795 return null; 2796 } 2797 2798 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2799 "getPackageGids"); 2800 2801 // reader 2802 synchronized (mPackages) { 2803 PackageParser.Package p = mPackages.get(packageName); 2804 if (DEBUG_PACKAGE_INFO) { 2805 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2806 } 2807 if (p != null) { 2808 PackageSetting ps = (PackageSetting) p.mExtras; 2809 return ps.getPermissionsState().computeGids(userId); 2810 } 2811 } 2812 2813 return null; 2814 } 2815 2816 static PermissionInfo generatePermissionInfo( 2817 BasePermission bp, int flags) { 2818 if (bp.perm != null) { 2819 return PackageParser.generatePermissionInfo(bp.perm, flags); 2820 } 2821 PermissionInfo pi = new PermissionInfo(); 2822 pi.name = bp.name; 2823 pi.packageName = bp.sourcePackage; 2824 pi.nonLocalizedLabel = bp.name; 2825 pi.protectionLevel = bp.protectionLevel; 2826 return pi; 2827 } 2828 2829 @Override 2830 public PermissionInfo getPermissionInfo(String name, int flags) { 2831 // reader 2832 synchronized (mPackages) { 2833 final BasePermission p = mSettings.mPermissions.get(name); 2834 if (p != null) { 2835 return generatePermissionInfo(p, flags); 2836 } 2837 return null; 2838 } 2839 } 2840 2841 @Override 2842 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2843 // reader 2844 synchronized (mPackages) { 2845 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2846 for (BasePermission p : mSettings.mPermissions.values()) { 2847 if (group == null) { 2848 if (p.perm == null || p.perm.info.group == null) { 2849 out.add(generatePermissionInfo(p, flags)); 2850 } 2851 } else { 2852 if (p.perm != null && group.equals(p.perm.info.group)) { 2853 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2854 } 2855 } 2856 } 2857 2858 if (out.size() > 0) { 2859 return out; 2860 } 2861 return mPermissionGroups.containsKey(group) ? out : null; 2862 } 2863 } 2864 2865 @Override 2866 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2867 // reader 2868 synchronized (mPackages) { 2869 return PackageParser.generatePermissionGroupInfo( 2870 mPermissionGroups.get(name), flags); 2871 } 2872 } 2873 2874 @Override 2875 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2876 // reader 2877 synchronized (mPackages) { 2878 final int N = mPermissionGroups.size(); 2879 ArrayList<PermissionGroupInfo> out 2880 = new ArrayList<PermissionGroupInfo>(N); 2881 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2882 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2883 } 2884 return out; 2885 } 2886 } 2887 2888 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2889 int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 PackageSetting ps = mSettings.mPackages.get(packageName); 2892 if (ps != null) { 2893 if (ps.pkg == null) { 2894 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2895 flags, userId); 2896 if (pInfo != null) { 2897 return pInfo.applicationInfo; 2898 } 2899 return null; 2900 } 2901 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2902 ps.readUserState(userId), userId); 2903 } 2904 return null; 2905 } 2906 2907 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2908 int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 PackageSetting ps = mSettings.mPackages.get(packageName); 2911 if (ps != null) { 2912 PackageParser.Package pkg = ps.pkg; 2913 if (pkg == null) { 2914 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2915 return null; 2916 } 2917 // Only data remains, so we aren't worried about code paths 2918 pkg = new PackageParser.Package(packageName); 2919 pkg.applicationInfo.packageName = packageName; 2920 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2921 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2922 pkg.applicationInfo.dataDir = Environment 2923 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2924 .getAbsolutePath(); 2925 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2926 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2927 } 2928 return generatePackageInfo(pkg, flags, userId); 2929 } 2930 return null; 2931 } 2932 2933 @Override 2934 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2935 if (!sUserManager.exists(userId)) return null; 2936 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2937 // writer 2938 synchronized (mPackages) { 2939 PackageParser.Package p = mPackages.get(packageName); 2940 if (DEBUG_PACKAGE_INFO) Log.v( 2941 TAG, "getApplicationInfo " + packageName 2942 + ": " + p); 2943 if (p != null) { 2944 PackageSetting ps = mSettings.mPackages.get(packageName); 2945 if (ps == null) return null; 2946 // Note: isEnabledLP() does not apply here - always return info 2947 return PackageParser.generateApplicationInfo( 2948 p, flags, ps.readUserState(userId), userId); 2949 } 2950 if ("android".equals(packageName)||"system".equals(packageName)) { 2951 return mAndroidApplication; 2952 } 2953 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2954 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2955 } 2956 } 2957 return null; 2958 } 2959 2960 @Override 2961 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2962 final IPackageDataObserver observer) { 2963 mContext.enforceCallingOrSelfPermission( 2964 android.Manifest.permission.CLEAR_APP_CACHE, null); 2965 // Queue up an async operation since clearing cache may take a little while. 2966 mHandler.post(new Runnable() { 2967 public void run() { 2968 mHandler.removeCallbacks(this); 2969 int retCode = -1; 2970 synchronized (mInstallLock) { 2971 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2972 if (retCode < 0) { 2973 Slog.w(TAG, "Couldn't clear application caches"); 2974 } 2975 } 2976 if (observer != null) { 2977 try { 2978 observer.onRemoveCompleted(null, (retCode >= 0)); 2979 } catch (RemoteException e) { 2980 Slog.w(TAG, "RemoveException when invoking call back"); 2981 } 2982 } 2983 } 2984 }); 2985 } 2986 2987 @Override 2988 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2989 final IntentSender pi) { 2990 mContext.enforceCallingOrSelfPermission( 2991 android.Manifest.permission.CLEAR_APP_CACHE, null); 2992 // Queue up an async operation since clearing cache may take a little while. 2993 mHandler.post(new Runnable() { 2994 public void run() { 2995 mHandler.removeCallbacks(this); 2996 int retCode = -1; 2997 synchronized (mInstallLock) { 2998 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2999 if (retCode < 0) { 3000 Slog.w(TAG, "Couldn't clear application caches"); 3001 } 3002 } 3003 if(pi != null) { 3004 try { 3005 // Callback via pending intent 3006 int code = (retCode >= 0) ? 1 : 0; 3007 pi.sendIntent(null, code, null, 3008 null, null); 3009 } catch (SendIntentException e1) { 3010 Slog.i(TAG, "Failed to send pending intent"); 3011 } 3012 } 3013 } 3014 }); 3015 } 3016 3017 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3018 synchronized (mInstallLock) { 3019 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3020 throw new IOException("Failed to free enough space"); 3021 } 3022 } 3023 } 3024 3025 @Override 3026 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3027 if (!sUserManager.exists(userId)) return null; 3028 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3029 synchronized (mPackages) { 3030 PackageParser.Activity a = mActivities.mActivities.get(component); 3031 3032 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3033 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3034 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3035 if (ps == null) return null; 3036 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3037 userId); 3038 } 3039 if (mResolveComponentName.equals(component)) { 3040 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3041 new PackageUserState(), userId); 3042 } 3043 } 3044 return null; 3045 } 3046 3047 @Override 3048 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3049 String resolvedType) { 3050 synchronized (mPackages) { 3051 if (component.equals(mResolveComponentName)) { 3052 // The resolver supports EVERYTHING! 3053 return true; 3054 } 3055 PackageParser.Activity a = mActivities.mActivities.get(component); 3056 if (a == null) { 3057 return false; 3058 } 3059 for (int i=0; i<a.intents.size(); i++) { 3060 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3061 intent.getData(), intent.getCategories(), TAG) >= 0) { 3062 return true; 3063 } 3064 } 3065 return false; 3066 } 3067 } 3068 3069 @Override 3070 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3071 if (!sUserManager.exists(userId)) return null; 3072 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3073 synchronized (mPackages) { 3074 PackageParser.Activity a = mReceivers.mActivities.get(component); 3075 if (DEBUG_PACKAGE_INFO) Log.v( 3076 TAG, "getReceiverInfo " + component + ": " + a); 3077 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3078 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3079 if (ps == null) return null; 3080 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3081 userId); 3082 } 3083 } 3084 return null; 3085 } 3086 3087 @Override 3088 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3089 if (!sUserManager.exists(userId)) return null; 3090 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3091 synchronized (mPackages) { 3092 PackageParser.Service s = mServices.mServices.get(component); 3093 if (DEBUG_PACKAGE_INFO) Log.v( 3094 TAG, "getServiceInfo " + component + ": " + s); 3095 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3096 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3097 if (ps == null) return null; 3098 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3099 userId); 3100 } 3101 } 3102 return null; 3103 } 3104 3105 @Override 3106 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3107 if (!sUserManager.exists(userId)) return null; 3108 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3109 synchronized (mPackages) { 3110 PackageParser.Provider p = mProviders.mProviders.get(component); 3111 if (DEBUG_PACKAGE_INFO) Log.v( 3112 TAG, "getProviderInfo " + component + ": " + p); 3113 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3114 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3115 if (ps == null) return null; 3116 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3117 userId); 3118 } 3119 } 3120 return null; 3121 } 3122 3123 @Override 3124 public String[] getSystemSharedLibraryNames() { 3125 Set<String> libSet; 3126 synchronized (mPackages) { 3127 libSet = mSharedLibraries.keySet(); 3128 int size = libSet.size(); 3129 if (size > 0) { 3130 String[] libs = new String[size]; 3131 libSet.toArray(libs); 3132 return libs; 3133 } 3134 } 3135 return null; 3136 } 3137 3138 /** 3139 * @hide 3140 */ 3141 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3142 synchronized (mPackages) { 3143 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3144 if (lib != null && lib.apk != null) { 3145 return mPackages.get(lib.apk); 3146 } 3147 } 3148 return null; 3149 } 3150 3151 @Override 3152 public FeatureInfo[] getSystemAvailableFeatures() { 3153 Collection<FeatureInfo> featSet; 3154 synchronized (mPackages) { 3155 featSet = mAvailableFeatures.values(); 3156 int size = featSet.size(); 3157 if (size > 0) { 3158 FeatureInfo[] features = new FeatureInfo[size+1]; 3159 featSet.toArray(features); 3160 FeatureInfo fi = new FeatureInfo(); 3161 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3162 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3163 features[size] = fi; 3164 return features; 3165 } 3166 } 3167 return null; 3168 } 3169 3170 @Override 3171 public boolean hasSystemFeature(String name) { 3172 synchronized (mPackages) { 3173 return mAvailableFeatures.containsKey(name); 3174 } 3175 } 3176 3177 private void checkValidCaller(int uid, int userId) { 3178 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3179 return; 3180 3181 throw new SecurityException("Caller uid=" + uid 3182 + " is not privileged to communicate with user=" + userId); 3183 } 3184 3185 @Override 3186 public int checkPermission(String permName, String pkgName, int userId) { 3187 if (!sUserManager.exists(userId)) { 3188 return PackageManager.PERMISSION_DENIED; 3189 } 3190 3191 synchronized (mPackages) { 3192 final PackageParser.Package p = mPackages.get(pkgName); 3193 if (p != null && p.mExtras != null) { 3194 final PackageSetting ps = (PackageSetting) p.mExtras; 3195 final PermissionsState permissionsState = ps.getPermissionsState(); 3196 if (permissionsState.hasPermission(permName, userId)) { 3197 return PackageManager.PERMISSION_GRANTED; 3198 } 3199 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3200 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3201 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3202 return PackageManager.PERMISSION_GRANTED; 3203 } 3204 } 3205 } 3206 3207 return PackageManager.PERMISSION_DENIED; 3208 } 3209 3210 @Override 3211 public int checkUidPermission(String permName, int uid) { 3212 final int userId = UserHandle.getUserId(uid); 3213 3214 if (!sUserManager.exists(userId)) { 3215 return PackageManager.PERMISSION_DENIED; 3216 } 3217 3218 synchronized (mPackages) { 3219 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3220 if (obj != null) { 3221 final SettingBase ps = (SettingBase) obj; 3222 final PermissionsState permissionsState = ps.getPermissionsState(); 3223 if (permissionsState.hasPermission(permName, userId)) { 3224 return PackageManager.PERMISSION_GRANTED; 3225 } 3226 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3227 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3228 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3229 return PackageManager.PERMISSION_GRANTED; 3230 } 3231 } else { 3232 ArraySet<String> perms = mSystemPermissions.get(uid); 3233 if (perms != null) { 3234 if (perms.contains(permName)) { 3235 return PackageManager.PERMISSION_GRANTED; 3236 } 3237 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3238 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3239 return PackageManager.PERMISSION_GRANTED; 3240 } 3241 } 3242 } 3243 } 3244 3245 return PackageManager.PERMISSION_DENIED; 3246 } 3247 3248 @Override 3249 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3250 if (UserHandle.getCallingUserId() != userId) { 3251 mContext.enforceCallingPermission( 3252 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3253 "isPermissionRevokedByPolicy for user " + userId); 3254 } 3255 3256 if (checkPermission(permission, packageName, userId) 3257 == PackageManager.PERMISSION_GRANTED) { 3258 return false; 3259 } 3260 3261 final long identity = Binder.clearCallingIdentity(); 3262 try { 3263 final int flags = getPermissionFlags(permission, packageName, userId); 3264 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3265 } finally { 3266 Binder.restoreCallingIdentity(identity); 3267 } 3268 } 3269 3270 @Override 3271 public String getPermissionControllerPackageName() { 3272 synchronized (mPackages) { 3273 return mRequiredInstallerPackage; 3274 } 3275 } 3276 3277 /** 3278 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3279 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3280 * @param checkShell TODO(yamasani): 3281 * @param message the message to log on security exception 3282 */ 3283 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3284 boolean checkShell, String message) { 3285 if (userId < 0) { 3286 throw new IllegalArgumentException("Invalid userId " + userId); 3287 } 3288 if (checkShell) { 3289 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3290 } 3291 if (userId == UserHandle.getUserId(callingUid)) return; 3292 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3293 if (requireFullPermission) { 3294 mContext.enforceCallingOrSelfPermission( 3295 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3296 } else { 3297 try { 3298 mContext.enforceCallingOrSelfPermission( 3299 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3300 } catch (SecurityException se) { 3301 mContext.enforceCallingOrSelfPermission( 3302 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3303 } 3304 } 3305 } 3306 } 3307 3308 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3309 if (callingUid == Process.SHELL_UID) { 3310 if (userHandle >= 0 3311 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3312 throw new SecurityException("Shell does not have permission to access user " 3313 + userHandle); 3314 } else if (userHandle < 0) { 3315 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3316 + Debug.getCallers(3)); 3317 } 3318 } 3319 } 3320 3321 private BasePermission findPermissionTreeLP(String permName) { 3322 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3323 if (permName.startsWith(bp.name) && 3324 permName.length() > bp.name.length() && 3325 permName.charAt(bp.name.length()) == '.') { 3326 return bp; 3327 } 3328 } 3329 return null; 3330 } 3331 3332 private BasePermission checkPermissionTreeLP(String permName) { 3333 if (permName != null) { 3334 BasePermission bp = findPermissionTreeLP(permName); 3335 if (bp != null) { 3336 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3337 return bp; 3338 } 3339 throw new SecurityException("Calling uid " 3340 + Binder.getCallingUid() 3341 + " is not allowed to add to permission tree " 3342 + bp.name + " owned by uid " + bp.uid); 3343 } 3344 } 3345 throw new SecurityException("No permission tree found for " + permName); 3346 } 3347 3348 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3349 if (s1 == null) { 3350 return s2 == null; 3351 } 3352 if (s2 == null) { 3353 return false; 3354 } 3355 if (s1.getClass() != s2.getClass()) { 3356 return false; 3357 } 3358 return s1.equals(s2); 3359 } 3360 3361 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3362 if (pi1.icon != pi2.icon) return false; 3363 if (pi1.logo != pi2.logo) return false; 3364 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3365 if (!compareStrings(pi1.name, pi2.name)) return false; 3366 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3367 // We'll take care of setting this one. 3368 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3369 // These are not currently stored in settings. 3370 //if (!compareStrings(pi1.group, pi2.group)) return false; 3371 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3372 //if (pi1.labelRes != pi2.labelRes) return false; 3373 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3374 return true; 3375 } 3376 3377 int permissionInfoFootprint(PermissionInfo info) { 3378 int size = info.name.length(); 3379 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3380 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3381 return size; 3382 } 3383 3384 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3385 int size = 0; 3386 for (BasePermission perm : mSettings.mPermissions.values()) { 3387 if (perm.uid == tree.uid) { 3388 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3389 } 3390 } 3391 return size; 3392 } 3393 3394 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3395 // We calculate the max size of permissions defined by this uid and throw 3396 // if that plus the size of 'info' would exceed our stated maximum. 3397 if (tree.uid != Process.SYSTEM_UID) { 3398 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3399 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3400 throw new SecurityException("Permission tree size cap exceeded"); 3401 } 3402 } 3403 } 3404 3405 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3406 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3407 throw new SecurityException("Label must be specified in permission"); 3408 } 3409 BasePermission tree = checkPermissionTreeLP(info.name); 3410 BasePermission bp = mSettings.mPermissions.get(info.name); 3411 boolean added = bp == null; 3412 boolean changed = true; 3413 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3414 if (added) { 3415 enforcePermissionCapLocked(info, tree); 3416 bp = new BasePermission(info.name, tree.sourcePackage, 3417 BasePermission.TYPE_DYNAMIC); 3418 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3419 throw new SecurityException( 3420 "Not allowed to modify non-dynamic permission " 3421 + info.name); 3422 } else { 3423 if (bp.protectionLevel == fixedLevel 3424 && bp.perm.owner.equals(tree.perm.owner) 3425 && bp.uid == tree.uid 3426 && comparePermissionInfos(bp.perm.info, info)) { 3427 changed = false; 3428 } 3429 } 3430 bp.protectionLevel = fixedLevel; 3431 info = new PermissionInfo(info); 3432 info.protectionLevel = fixedLevel; 3433 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3434 bp.perm.info.packageName = tree.perm.info.packageName; 3435 bp.uid = tree.uid; 3436 if (added) { 3437 mSettings.mPermissions.put(info.name, bp); 3438 } 3439 if (changed) { 3440 if (!async) { 3441 mSettings.writeLPr(); 3442 } else { 3443 scheduleWriteSettingsLocked(); 3444 } 3445 } 3446 return added; 3447 } 3448 3449 @Override 3450 public boolean addPermission(PermissionInfo info) { 3451 synchronized (mPackages) { 3452 return addPermissionLocked(info, false); 3453 } 3454 } 3455 3456 @Override 3457 public boolean addPermissionAsync(PermissionInfo info) { 3458 synchronized (mPackages) { 3459 return addPermissionLocked(info, true); 3460 } 3461 } 3462 3463 @Override 3464 public void removePermission(String name) { 3465 synchronized (mPackages) { 3466 checkPermissionTreeLP(name); 3467 BasePermission bp = mSettings.mPermissions.get(name); 3468 if (bp != null) { 3469 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3470 throw new SecurityException( 3471 "Not allowed to modify non-dynamic permission " 3472 + name); 3473 } 3474 mSettings.mPermissions.remove(name); 3475 mSettings.writeLPr(); 3476 } 3477 } 3478 } 3479 3480 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3481 BasePermission bp) { 3482 int index = pkg.requestedPermissions.indexOf(bp.name); 3483 if (index == -1) { 3484 throw new SecurityException("Package " + pkg.packageName 3485 + " has not requested permission " + bp.name); 3486 } 3487 if (!bp.isRuntime() && !bp.isDevelopment()) { 3488 throw new SecurityException("Permission " + bp.name 3489 + " is not a changeable permission type"); 3490 } 3491 } 3492 3493 @Override 3494 public void grantRuntimePermission(String packageName, String name, final int userId) { 3495 if (!sUserManager.exists(userId)) { 3496 Log.e(TAG, "No such user:" + userId); 3497 return; 3498 } 3499 3500 mContext.enforceCallingOrSelfPermission( 3501 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3502 "grantRuntimePermission"); 3503 3504 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3505 "grantRuntimePermission"); 3506 3507 final int uid; 3508 final SettingBase sb; 3509 3510 synchronized (mPackages) { 3511 final PackageParser.Package pkg = mPackages.get(packageName); 3512 if (pkg == null) { 3513 throw new IllegalArgumentException("Unknown package: " + packageName); 3514 } 3515 3516 final BasePermission bp = mSettings.mPermissions.get(name); 3517 if (bp == null) { 3518 throw new IllegalArgumentException("Unknown permission: " + name); 3519 } 3520 3521 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3522 3523 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3524 sb = (SettingBase) pkg.mExtras; 3525 if (sb == null) { 3526 throw new IllegalArgumentException("Unknown package: " + packageName); 3527 } 3528 3529 final PermissionsState permissionsState = sb.getPermissionsState(); 3530 3531 final int flags = permissionsState.getPermissionFlags(name, userId); 3532 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3533 throw new SecurityException("Cannot grant system fixed permission: " 3534 + name + " for package: " + packageName); 3535 } 3536 3537 if (bp.isDevelopment()) { 3538 // Development permissions must be handled specially, since they are not 3539 // normal runtime permissions. For now they apply to all users. 3540 if (permissionsState.grantInstallPermission(bp) != 3541 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3542 scheduleWriteSettingsLocked(); 3543 } 3544 return; 3545 } 3546 3547 final int result = permissionsState.grantRuntimePermission(bp, userId); 3548 switch (result) { 3549 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3550 return; 3551 } 3552 3553 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3554 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3555 mHandler.post(new Runnable() { 3556 @Override 3557 public void run() { 3558 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3559 } 3560 }); 3561 } break; 3562 } 3563 3564 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3565 3566 // Not critical if that is lost - app has to request again. 3567 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3568 } 3569 3570 // Only need to do this if user is initialized. Otherwise it's a new user 3571 // and there are no processes running as the user yet and there's no need 3572 // to make an expensive call to remount processes for the changed permissions. 3573 if (READ_EXTERNAL_STORAGE.equals(name) 3574 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3575 final long token = Binder.clearCallingIdentity(); 3576 try { 3577 if (sUserManager.isInitialized(userId)) { 3578 MountServiceInternal mountServiceInternal = LocalServices.getService( 3579 MountServiceInternal.class); 3580 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3581 } 3582 } finally { 3583 Binder.restoreCallingIdentity(token); 3584 } 3585 } 3586 } 3587 3588 @Override 3589 public void revokeRuntimePermission(String packageName, String name, int userId) { 3590 if (!sUserManager.exists(userId)) { 3591 Log.e(TAG, "No such user:" + userId); 3592 return; 3593 } 3594 3595 mContext.enforceCallingOrSelfPermission( 3596 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3597 "revokeRuntimePermission"); 3598 3599 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3600 "revokeRuntimePermission"); 3601 3602 final int appId; 3603 3604 synchronized (mPackages) { 3605 final PackageParser.Package pkg = mPackages.get(packageName); 3606 if (pkg == null) { 3607 throw new IllegalArgumentException("Unknown package: " + packageName); 3608 } 3609 3610 final BasePermission bp = mSettings.mPermissions.get(name); 3611 if (bp == null) { 3612 throw new IllegalArgumentException("Unknown permission: " + name); 3613 } 3614 3615 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3616 3617 SettingBase sb = (SettingBase) pkg.mExtras; 3618 if (sb == null) { 3619 throw new IllegalArgumentException("Unknown package: " + packageName); 3620 } 3621 3622 final PermissionsState permissionsState = sb.getPermissionsState(); 3623 3624 final int flags = permissionsState.getPermissionFlags(name, userId); 3625 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3626 throw new SecurityException("Cannot revoke system fixed permission: " 3627 + name + " for package: " + packageName); 3628 } 3629 3630 if (bp.isDevelopment()) { 3631 // Development permissions must be handled specially, since they are not 3632 // normal runtime permissions. For now they apply to all users. 3633 if (permissionsState.revokeInstallPermission(bp) != 3634 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3635 scheduleWriteSettingsLocked(); 3636 } 3637 return; 3638 } 3639 3640 if (permissionsState.revokeRuntimePermission(bp, userId) == 3641 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3642 return; 3643 } 3644 3645 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3646 3647 // Critical, after this call app should never have the permission. 3648 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3649 3650 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3651 } 3652 3653 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3654 } 3655 3656 @Override 3657 public void resetRuntimePermissions() { 3658 mContext.enforceCallingOrSelfPermission( 3659 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3660 "revokeRuntimePermission"); 3661 3662 int callingUid = Binder.getCallingUid(); 3663 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3664 mContext.enforceCallingOrSelfPermission( 3665 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3666 "resetRuntimePermissions"); 3667 } 3668 3669 synchronized (mPackages) { 3670 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3671 for (int userId : UserManagerService.getInstance().getUserIds()) { 3672 final int packageCount = mPackages.size(); 3673 for (int i = 0; i < packageCount; i++) { 3674 PackageParser.Package pkg = mPackages.valueAt(i); 3675 if (!(pkg.mExtras instanceof PackageSetting)) { 3676 continue; 3677 } 3678 PackageSetting ps = (PackageSetting) pkg.mExtras; 3679 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3680 } 3681 } 3682 } 3683 } 3684 3685 @Override 3686 public int getPermissionFlags(String name, String packageName, int userId) { 3687 if (!sUserManager.exists(userId)) { 3688 return 0; 3689 } 3690 3691 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3692 3693 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3694 "getPermissionFlags"); 3695 3696 synchronized (mPackages) { 3697 final PackageParser.Package pkg = mPackages.get(packageName); 3698 if (pkg == null) { 3699 throw new IllegalArgumentException("Unknown package: " + packageName); 3700 } 3701 3702 final BasePermission bp = mSettings.mPermissions.get(name); 3703 if (bp == null) { 3704 throw new IllegalArgumentException("Unknown permission: " + name); 3705 } 3706 3707 SettingBase sb = (SettingBase) pkg.mExtras; 3708 if (sb == null) { 3709 throw new IllegalArgumentException("Unknown package: " + packageName); 3710 } 3711 3712 PermissionsState permissionsState = sb.getPermissionsState(); 3713 return permissionsState.getPermissionFlags(name, userId); 3714 } 3715 } 3716 3717 @Override 3718 public void updatePermissionFlags(String name, String packageName, int flagMask, 3719 int flagValues, int userId) { 3720 if (!sUserManager.exists(userId)) { 3721 return; 3722 } 3723 3724 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3725 3726 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3727 "updatePermissionFlags"); 3728 3729 // Only the system can change these flags and nothing else. 3730 if (getCallingUid() != Process.SYSTEM_UID) { 3731 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3732 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3733 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3734 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3735 } 3736 3737 synchronized (mPackages) { 3738 final PackageParser.Package pkg = mPackages.get(packageName); 3739 if (pkg == null) { 3740 throw new IllegalArgumentException("Unknown package: " + packageName); 3741 } 3742 3743 final BasePermission bp = mSettings.mPermissions.get(name); 3744 if (bp == null) { 3745 throw new IllegalArgumentException("Unknown permission: " + name); 3746 } 3747 3748 SettingBase sb = (SettingBase) pkg.mExtras; 3749 if (sb == null) { 3750 throw new IllegalArgumentException("Unknown package: " + packageName); 3751 } 3752 3753 PermissionsState permissionsState = sb.getPermissionsState(); 3754 3755 // Only the package manager can change flags for system component permissions. 3756 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3757 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3758 return; 3759 } 3760 3761 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3762 3763 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3764 // Install and runtime permissions are stored in different places, 3765 // so figure out what permission changed and persist the change. 3766 if (permissionsState.getInstallPermissionState(name) != null) { 3767 scheduleWriteSettingsLocked(); 3768 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3769 || hadState) { 3770 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3771 } 3772 } 3773 } 3774 } 3775 3776 /** 3777 * Update the permission flags for all packages and runtime permissions of a user in order 3778 * to allow device or profile owner to remove POLICY_FIXED. 3779 */ 3780 @Override 3781 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3782 if (!sUserManager.exists(userId)) { 3783 return; 3784 } 3785 3786 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3787 3788 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3789 "updatePermissionFlagsForAllApps"); 3790 3791 // Only the system can change system fixed flags. 3792 if (getCallingUid() != Process.SYSTEM_UID) { 3793 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3794 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3795 } 3796 3797 synchronized (mPackages) { 3798 boolean changed = false; 3799 final int packageCount = mPackages.size(); 3800 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3801 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3802 SettingBase sb = (SettingBase) pkg.mExtras; 3803 if (sb == null) { 3804 continue; 3805 } 3806 PermissionsState permissionsState = sb.getPermissionsState(); 3807 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3808 userId, flagMask, flagValues); 3809 } 3810 if (changed) { 3811 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3812 } 3813 } 3814 } 3815 3816 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3817 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3818 != PackageManager.PERMISSION_GRANTED 3819 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3820 != PackageManager.PERMISSION_GRANTED) { 3821 throw new SecurityException(message + " requires " 3822 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3823 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3824 } 3825 } 3826 3827 @Override 3828 public boolean shouldShowRequestPermissionRationale(String permissionName, 3829 String packageName, int userId) { 3830 if (UserHandle.getCallingUserId() != userId) { 3831 mContext.enforceCallingPermission( 3832 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3833 "canShowRequestPermissionRationale for user " + userId); 3834 } 3835 3836 final int uid = getPackageUid(packageName, userId); 3837 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3838 return false; 3839 } 3840 3841 if (checkPermission(permissionName, packageName, userId) 3842 == PackageManager.PERMISSION_GRANTED) { 3843 return false; 3844 } 3845 3846 final int flags; 3847 3848 final long identity = Binder.clearCallingIdentity(); 3849 try { 3850 flags = getPermissionFlags(permissionName, 3851 packageName, userId); 3852 } finally { 3853 Binder.restoreCallingIdentity(identity); 3854 } 3855 3856 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3857 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3858 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3859 3860 if ((flags & fixedFlags) != 0) { 3861 return false; 3862 } 3863 3864 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3865 } 3866 3867 @Override 3868 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3869 mContext.enforceCallingOrSelfPermission( 3870 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3871 "addOnPermissionsChangeListener"); 3872 3873 synchronized (mPackages) { 3874 mOnPermissionChangeListeners.addListenerLocked(listener); 3875 } 3876 } 3877 3878 @Override 3879 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3880 synchronized (mPackages) { 3881 mOnPermissionChangeListeners.removeListenerLocked(listener); 3882 } 3883 } 3884 3885 @Override 3886 public boolean isProtectedBroadcast(String actionName) { 3887 synchronized (mPackages) { 3888 return mProtectedBroadcasts.contains(actionName); 3889 } 3890 } 3891 3892 @Override 3893 public int checkSignatures(String pkg1, String pkg2) { 3894 synchronized (mPackages) { 3895 final PackageParser.Package p1 = mPackages.get(pkg1); 3896 final PackageParser.Package p2 = mPackages.get(pkg2); 3897 if (p1 == null || p1.mExtras == null 3898 || p2 == null || p2.mExtras == null) { 3899 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3900 } 3901 return compareSignatures(p1.mSignatures, p2.mSignatures); 3902 } 3903 } 3904 3905 @Override 3906 public int checkUidSignatures(int uid1, int uid2) { 3907 // Map to base uids. 3908 uid1 = UserHandle.getAppId(uid1); 3909 uid2 = UserHandle.getAppId(uid2); 3910 // reader 3911 synchronized (mPackages) { 3912 Signature[] s1; 3913 Signature[] s2; 3914 Object obj = mSettings.getUserIdLPr(uid1); 3915 if (obj != null) { 3916 if (obj instanceof SharedUserSetting) { 3917 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3918 } else if (obj instanceof PackageSetting) { 3919 s1 = ((PackageSetting)obj).signatures.mSignatures; 3920 } else { 3921 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3922 } 3923 } else { 3924 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3925 } 3926 obj = mSettings.getUserIdLPr(uid2); 3927 if (obj != null) { 3928 if (obj instanceof SharedUserSetting) { 3929 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3930 } else if (obj instanceof PackageSetting) { 3931 s2 = ((PackageSetting)obj).signatures.mSignatures; 3932 } else { 3933 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3934 } 3935 } else { 3936 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3937 } 3938 return compareSignatures(s1, s2); 3939 } 3940 } 3941 3942 private void killUid(int appId, int userId, String reason) { 3943 final long identity = Binder.clearCallingIdentity(); 3944 try { 3945 IActivityManager am = ActivityManagerNative.getDefault(); 3946 if (am != null) { 3947 try { 3948 am.killUid(appId, userId, reason); 3949 } catch (RemoteException e) { 3950 /* ignore - same process */ 3951 } 3952 } 3953 } finally { 3954 Binder.restoreCallingIdentity(identity); 3955 } 3956 } 3957 3958 /** 3959 * Compares two sets of signatures. Returns: 3960 * <br /> 3961 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3962 * <br /> 3963 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3964 * <br /> 3965 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3966 * <br /> 3967 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3968 * <br /> 3969 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3970 */ 3971 static int compareSignatures(Signature[] s1, Signature[] s2) { 3972 if (s1 == null) { 3973 return s2 == null 3974 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3975 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3976 } 3977 3978 if (s2 == null) { 3979 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3980 } 3981 3982 if (s1.length != s2.length) { 3983 return PackageManager.SIGNATURE_NO_MATCH; 3984 } 3985 3986 // Since both signature sets are of size 1, we can compare without HashSets. 3987 if (s1.length == 1) { 3988 return s1[0].equals(s2[0]) ? 3989 PackageManager.SIGNATURE_MATCH : 3990 PackageManager.SIGNATURE_NO_MATCH; 3991 } 3992 3993 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3994 for (Signature sig : s1) { 3995 set1.add(sig); 3996 } 3997 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3998 for (Signature sig : s2) { 3999 set2.add(sig); 4000 } 4001 // Make sure s2 contains all signatures in s1. 4002 if (set1.equals(set2)) { 4003 return PackageManager.SIGNATURE_MATCH; 4004 } 4005 return PackageManager.SIGNATURE_NO_MATCH; 4006 } 4007 4008 /** 4009 * If the database version for this type of package (internal storage or 4010 * external storage) is less than the version where package signatures 4011 * were updated, return true. 4012 */ 4013 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4014 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4015 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4016 } 4017 4018 /** 4019 * Used for backward compatibility to make sure any packages with 4020 * certificate chains get upgraded to the new style. {@code existingSigs} 4021 * will be in the old format (since they were stored on disk from before the 4022 * system upgrade) and {@code scannedSigs} will be in the newer format. 4023 */ 4024 private int compareSignaturesCompat(PackageSignatures existingSigs, 4025 PackageParser.Package scannedPkg) { 4026 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4027 return PackageManager.SIGNATURE_NO_MATCH; 4028 } 4029 4030 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4031 for (Signature sig : existingSigs.mSignatures) { 4032 existingSet.add(sig); 4033 } 4034 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4035 for (Signature sig : scannedPkg.mSignatures) { 4036 try { 4037 Signature[] chainSignatures = sig.getChainSignatures(); 4038 for (Signature chainSig : chainSignatures) { 4039 scannedCompatSet.add(chainSig); 4040 } 4041 } catch (CertificateEncodingException e) { 4042 scannedCompatSet.add(sig); 4043 } 4044 } 4045 /* 4046 * Make sure the expanded scanned set contains all signatures in the 4047 * existing one. 4048 */ 4049 if (scannedCompatSet.equals(existingSet)) { 4050 // Migrate the old signatures to the new scheme. 4051 existingSigs.assignSignatures(scannedPkg.mSignatures); 4052 // The new KeySets will be re-added later in the scanning process. 4053 synchronized (mPackages) { 4054 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4055 } 4056 return PackageManager.SIGNATURE_MATCH; 4057 } 4058 return PackageManager.SIGNATURE_NO_MATCH; 4059 } 4060 4061 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4062 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4063 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4064 } 4065 4066 private int compareSignaturesRecover(PackageSignatures existingSigs, 4067 PackageParser.Package scannedPkg) { 4068 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4069 return PackageManager.SIGNATURE_NO_MATCH; 4070 } 4071 4072 String msg = null; 4073 try { 4074 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4075 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4076 + scannedPkg.packageName); 4077 return PackageManager.SIGNATURE_MATCH; 4078 } 4079 } catch (CertificateException e) { 4080 msg = e.getMessage(); 4081 } 4082 4083 logCriticalInfo(Log.INFO, 4084 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4085 return PackageManager.SIGNATURE_NO_MATCH; 4086 } 4087 4088 @Override 4089 public String[] getPackagesForUid(int uid) { 4090 uid = UserHandle.getAppId(uid); 4091 // reader 4092 synchronized (mPackages) { 4093 Object obj = mSettings.getUserIdLPr(uid); 4094 if (obj instanceof SharedUserSetting) { 4095 final SharedUserSetting sus = (SharedUserSetting) obj; 4096 final int N = sus.packages.size(); 4097 final String[] res = new String[N]; 4098 final Iterator<PackageSetting> it = sus.packages.iterator(); 4099 int i = 0; 4100 while (it.hasNext()) { 4101 res[i++] = it.next().name; 4102 } 4103 return res; 4104 } else if (obj instanceof PackageSetting) { 4105 final PackageSetting ps = (PackageSetting) obj; 4106 return new String[] { ps.name }; 4107 } 4108 } 4109 return null; 4110 } 4111 4112 @Override 4113 public String getNameForUid(int uid) { 4114 // reader 4115 synchronized (mPackages) { 4116 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4117 if (obj instanceof SharedUserSetting) { 4118 final SharedUserSetting sus = (SharedUserSetting) obj; 4119 return sus.name + ":" + sus.userId; 4120 } else if (obj instanceof PackageSetting) { 4121 final PackageSetting ps = (PackageSetting) obj; 4122 return ps.name; 4123 } 4124 } 4125 return null; 4126 } 4127 4128 @Override 4129 public int getUidForSharedUser(String sharedUserName) { 4130 if(sharedUserName == null) { 4131 return -1; 4132 } 4133 // reader 4134 synchronized (mPackages) { 4135 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4136 if (suid == null) { 4137 return -1; 4138 } 4139 return suid.userId; 4140 } 4141 } 4142 4143 @Override 4144 public int getFlagsForUid(int uid) { 4145 synchronized (mPackages) { 4146 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4147 if (obj instanceof SharedUserSetting) { 4148 final SharedUserSetting sus = (SharedUserSetting) obj; 4149 return sus.pkgFlags; 4150 } else if (obj instanceof PackageSetting) { 4151 final PackageSetting ps = (PackageSetting) obj; 4152 return ps.pkgFlags; 4153 } 4154 } 4155 return 0; 4156 } 4157 4158 @Override 4159 public int getPrivateFlagsForUid(int uid) { 4160 synchronized (mPackages) { 4161 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4162 if (obj instanceof SharedUserSetting) { 4163 final SharedUserSetting sus = (SharedUserSetting) obj; 4164 return sus.pkgPrivateFlags; 4165 } else if (obj instanceof PackageSetting) { 4166 final PackageSetting ps = (PackageSetting) obj; 4167 return ps.pkgPrivateFlags; 4168 } 4169 } 4170 return 0; 4171 } 4172 4173 @Override 4174 public boolean isUidPrivileged(int uid) { 4175 uid = UserHandle.getAppId(uid); 4176 // reader 4177 synchronized (mPackages) { 4178 Object obj = mSettings.getUserIdLPr(uid); 4179 if (obj instanceof SharedUserSetting) { 4180 final SharedUserSetting sus = (SharedUserSetting) obj; 4181 final Iterator<PackageSetting> it = sus.packages.iterator(); 4182 while (it.hasNext()) { 4183 if (it.next().isPrivileged()) { 4184 return true; 4185 } 4186 } 4187 } else if (obj instanceof PackageSetting) { 4188 final PackageSetting ps = (PackageSetting) obj; 4189 return ps.isPrivileged(); 4190 } 4191 } 4192 return false; 4193 } 4194 4195 @Override 4196 public String[] getAppOpPermissionPackages(String permissionName) { 4197 synchronized (mPackages) { 4198 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4199 if (pkgs == null) { 4200 return null; 4201 } 4202 return pkgs.toArray(new String[pkgs.size()]); 4203 } 4204 } 4205 4206 @Override 4207 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4208 int flags, int userId) { 4209 if (!sUserManager.exists(userId)) return null; 4210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4211 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4212 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4213 } 4214 4215 @Override 4216 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4217 IntentFilter filter, int match, ComponentName activity) { 4218 final int userId = UserHandle.getCallingUserId(); 4219 if (DEBUG_PREFERRED) { 4220 Log.v(TAG, "setLastChosenActivity intent=" + intent 4221 + " resolvedType=" + resolvedType 4222 + " flags=" + flags 4223 + " filter=" + filter 4224 + " match=" + match 4225 + " activity=" + activity); 4226 filter.dump(new PrintStreamPrinter(System.out), " "); 4227 } 4228 intent.setComponent(null); 4229 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4230 // Find any earlier preferred or last chosen entries and nuke them 4231 findPreferredActivity(intent, resolvedType, 4232 flags, query, 0, false, true, false, userId); 4233 // Add the new activity as the last chosen for this filter 4234 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4235 "Setting last chosen"); 4236 } 4237 4238 @Override 4239 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4240 final int userId = UserHandle.getCallingUserId(); 4241 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4242 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4243 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4244 false, false, false, userId); 4245 } 4246 4247 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4248 int flags, List<ResolveInfo> query, int userId) { 4249 if (query != null) { 4250 final int N = query.size(); 4251 if (N == 1) { 4252 return query.get(0); 4253 } else if (N > 1) { 4254 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4255 // If there is more than one activity with the same priority, 4256 // then let the user decide between them. 4257 ResolveInfo r0 = query.get(0); 4258 ResolveInfo r1 = query.get(1); 4259 if (DEBUG_INTENT_MATCHING || debug) { 4260 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4261 + r1.activityInfo.name + "=" + r1.priority); 4262 } 4263 // If the first activity has a higher priority, or a different 4264 // default, then it is always desireable to pick it. 4265 if (r0.priority != r1.priority 4266 || r0.preferredOrder != r1.preferredOrder 4267 || r0.isDefault != r1.isDefault) { 4268 return query.get(0); 4269 } 4270 // If we have saved a preference for a preferred activity for 4271 // this Intent, use that. 4272 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4273 flags, query, r0.priority, true, false, debug, userId); 4274 if (ri != null) { 4275 return ri; 4276 } 4277 ri = new ResolveInfo(mResolveInfo); 4278 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4279 ri.activityInfo.applicationInfo = new ApplicationInfo( 4280 ri.activityInfo.applicationInfo); 4281 if (userId != 0) { 4282 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4283 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4284 } 4285 // Make sure that the resolver is displayable in car mode 4286 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4287 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4288 return ri; 4289 } 4290 } 4291 return null; 4292 } 4293 4294 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4295 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4296 final int N = query.size(); 4297 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4298 .get(userId); 4299 // Get the list of persistent preferred activities that handle the intent 4300 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4301 List<PersistentPreferredActivity> pprefs = ppir != null 4302 ? ppir.queryIntent(intent, resolvedType, 4303 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4304 : null; 4305 if (pprefs != null && pprefs.size() > 0) { 4306 final int M = pprefs.size(); 4307 for (int i=0; i<M; i++) { 4308 final PersistentPreferredActivity ppa = pprefs.get(i); 4309 if (DEBUG_PREFERRED || debug) { 4310 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4311 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4312 + "\n component=" + ppa.mComponent); 4313 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4314 } 4315 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4316 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4317 if (DEBUG_PREFERRED || debug) { 4318 Slog.v(TAG, "Found persistent preferred activity:"); 4319 if (ai != null) { 4320 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4321 } else { 4322 Slog.v(TAG, " null"); 4323 } 4324 } 4325 if (ai == null) { 4326 // This previously registered persistent preferred activity 4327 // component is no longer known. Ignore it and do NOT remove it. 4328 continue; 4329 } 4330 for (int j=0; j<N; j++) { 4331 final ResolveInfo ri = query.get(j); 4332 if (!ri.activityInfo.applicationInfo.packageName 4333 .equals(ai.applicationInfo.packageName)) { 4334 continue; 4335 } 4336 if (!ri.activityInfo.name.equals(ai.name)) { 4337 continue; 4338 } 4339 // Found a persistent preference that can handle the intent. 4340 if (DEBUG_PREFERRED || debug) { 4341 Slog.v(TAG, "Returning persistent preferred activity: " + 4342 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4343 } 4344 return ri; 4345 } 4346 } 4347 } 4348 return null; 4349 } 4350 4351 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4352 List<ResolveInfo> query, int priority, boolean always, 4353 boolean removeMatches, boolean debug, int userId) { 4354 if (!sUserManager.exists(userId)) return null; 4355 // writer 4356 synchronized (mPackages) { 4357 if (intent.getSelector() != null) { 4358 intent = intent.getSelector(); 4359 } 4360 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4361 4362 // Try to find a matching persistent preferred activity. 4363 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4364 debug, userId); 4365 4366 // If a persistent preferred activity matched, use it. 4367 if (pri != null) { 4368 return pri; 4369 } 4370 4371 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4372 // Get the list of preferred activities that handle the intent 4373 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4374 List<PreferredActivity> prefs = pir != null 4375 ? pir.queryIntent(intent, resolvedType, 4376 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4377 : null; 4378 if (prefs != null && prefs.size() > 0) { 4379 boolean changed = false; 4380 try { 4381 // First figure out how good the original match set is. 4382 // We will only allow preferred activities that came 4383 // from the same match quality. 4384 int match = 0; 4385 4386 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4387 4388 final int N = query.size(); 4389 for (int j=0; j<N; j++) { 4390 final ResolveInfo ri = query.get(j); 4391 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4392 + ": 0x" + Integer.toHexString(match)); 4393 if (ri.match > match) { 4394 match = ri.match; 4395 } 4396 } 4397 4398 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4399 + Integer.toHexString(match)); 4400 4401 match &= IntentFilter.MATCH_CATEGORY_MASK; 4402 final int M = prefs.size(); 4403 for (int i=0; i<M; i++) { 4404 final PreferredActivity pa = prefs.get(i); 4405 if (DEBUG_PREFERRED || debug) { 4406 Slog.v(TAG, "Checking PreferredActivity ds=" 4407 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4408 + "\n component=" + pa.mPref.mComponent); 4409 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4410 } 4411 if (pa.mPref.mMatch != match) { 4412 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4413 + Integer.toHexString(pa.mPref.mMatch)); 4414 continue; 4415 } 4416 // If it's not an "always" type preferred activity and that's what we're 4417 // looking for, skip it. 4418 if (always && !pa.mPref.mAlways) { 4419 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4420 continue; 4421 } 4422 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4423 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4424 if (DEBUG_PREFERRED || debug) { 4425 Slog.v(TAG, "Found preferred activity:"); 4426 if (ai != null) { 4427 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4428 } else { 4429 Slog.v(TAG, " null"); 4430 } 4431 } 4432 if (ai == null) { 4433 // This previously registered preferred activity 4434 // component is no longer known. Most likely an update 4435 // to the app was installed and in the new version this 4436 // component no longer exists. Clean it up by removing 4437 // it from the preferred activities list, and skip it. 4438 Slog.w(TAG, "Removing dangling preferred activity: " 4439 + pa.mPref.mComponent); 4440 pir.removeFilter(pa); 4441 changed = true; 4442 continue; 4443 } 4444 for (int j=0; j<N; j++) { 4445 final ResolveInfo ri = query.get(j); 4446 if (!ri.activityInfo.applicationInfo.packageName 4447 .equals(ai.applicationInfo.packageName)) { 4448 continue; 4449 } 4450 if (!ri.activityInfo.name.equals(ai.name)) { 4451 continue; 4452 } 4453 4454 if (removeMatches) { 4455 pir.removeFilter(pa); 4456 changed = true; 4457 if (DEBUG_PREFERRED) { 4458 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4459 } 4460 break; 4461 } 4462 4463 // Okay we found a previously set preferred or last chosen app. 4464 // If the result set is different from when this 4465 // was created, we need to clear it and re-ask the 4466 // user their preference, if we're looking for an "always" type entry. 4467 if (always && !pa.mPref.sameSet(query)) { 4468 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4469 + intent + " type " + resolvedType); 4470 if (DEBUG_PREFERRED) { 4471 Slog.v(TAG, "Removing preferred activity since set changed " 4472 + pa.mPref.mComponent); 4473 } 4474 pir.removeFilter(pa); 4475 // Re-add the filter as a "last chosen" entry (!always) 4476 PreferredActivity lastChosen = new PreferredActivity( 4477 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4478 pir.addFilter(lastChosen); 4479 changed = true; 4480 return null; 4481 } 4482 4483 // Yay! Either the set matched or we're looking for the last chosen 4484 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4485 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4486 return ri; 4487 } 4488 } 4489 } finally { 4490 if (changed) { 4491 if (DEBUG_PREFERRED) { 4492 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4493 } 4494 scheduleWritePackageRestrictionsLocked(userId); 4495 } 4496 } 4497 } 4498 } 4499 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4500 return null; 4501 } 4502 4503 /* 4504 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4505 */ 4506 @Override 4507 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4508 int targetUserId) { 4509 mContext.enforceCallingOrSelfPermission( 4510 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4511 List<CrossProfileIntentFilter> matches = 4512 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4513 if (matches != null) { 4514 int size = matches.size(); 4515 for (int i = 0; i < size; i++) { 4516 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4517 } 4518 } 4519 if (hasWebURI(intent)) { 4520 // cross-profile app linking works only towards the parent. 4521 final UserInfo parent = getProfileParent(sourceUserId); 4522 synchronized(mPackages) { 4523 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4524 intent, resolvedType, 0, sourceUserId, parent.id); 4525 return xpDomainInfo != null; 4526 } 4527 } 4528 return false; 4529 } 4530 4531 private UserInfo getProfileParent(int userId) { 4532 final long identity = Binder.clearCallingIdentity(); 4533 try { 4534 return sUserManager.getProfileParent(userId); 4535 } finally { 4536 Binder.restoreCallingIdentity(identity); 4537 } 4538 } 4539 4540 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4541 String resolvedType, int userId) { 4542 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4543 if (resolver != null) { 4544 return resolver.queryIntent(intent, resolvedType, false, userId); 4545 } 4546 return null; 4547 } 4548 4549 @Override 4550 public List<ResolveInfo> queryIntentActivities(Intent intent, 4551 String resolvedType, int flags, int userId) { 4552 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4553 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4554 ComponentName comp = intent.getComponent(); 4555 if (comp == null) { 4556 if (intent.getSelector() != null) { 4557 intent = intent.getSelector(); 4558 comp = intent.getComponent(); 4559 } 4560 } 4561 4562 if (comp != null) { 4563 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4564 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4565 if (ai != null) { 4566 final ResolveInfo ri = new ResolveInfo(); 4567 ri.activityInfo = ai; 4568 list.add(ri); 4569 } 4570 return list; 4571 } 4572 4573 // reader 4574 synchronized (mPackages) { 4575 final String pkgName = intent.getPackage(); 4576 if (pkgName == null) { 4577 List<CrossProfileIntentFilter> matchingFilters = 4578 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4579 // Check for results that need to skip the current profile. 4580 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4581 resolvedType, flags, userId); 4582 if (xpResolveInfo != null) { 4583 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4584 result.add(xpResolveInfo); 4585 return filterIfNotSystemUser(result, userId); 4586 } 4587 4588 // Check for results in the current profile. 4589 List<ResolveInfo> result = mActivities.queryIntent( 4590 intent, resolvedType, flags, userId); 4591 4592 // Check for cross profile results. 4593 xpResolveInfo = queryCrossProfileIntents( 4594 matchingFilters, intent, resolvedType, flags, userId); 4595 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4596 result.add(xpResolveInfo); 4597 Collections.sort(result, mResolvePrioritySorter); 4598 } 4599 result = filterIfNotSystemUser(result, userId); 4600 if (hasWebURI(intent)) { 4601 CrossProfileDomainInfo xpDomainInfo = null; 4602 final UserInfo parent = getProfileParent(userId); 4603 if (parent != null) { 4604 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4605 flags, userId, parent.id); 4606 } 4607 if (xpDomainInfo != null) { 4608 if (xpResolveInfo != null) { 4609 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4610 // in the result. 4611 result.remove(xpResolveInfo); 4612 } 4613 if (result.size() == 0) { 4614 result.add(xpDomainInfo.resolveInfo); 4615 return result; 4616 } 4617 } else if (result.size() <= 1) { 4618 return result; 4619 } 4620 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4621 xpDomainInfo, userId); 4622 Collections.sort(result, mResolvePrioritySorter); 4623 } 4624 return result; 4625 } 4626 final PackageParser.Package pkg = mPackages.get(pkgName); 4627 if (pkg != null) { 4628 return filterIfNotSystemUser( 4629 mActivities.queryIntentForPackage( 4630 intent, resolvedType, flags, pkg.activities, userId), 4631 userId); 4632 } 4633 return new ArrayList<ResolveInfo>(); 4634 } 4635 } 4636 4637 private static class CrossProfileDomainInfo { 4638 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4639 ResolveInfo resolveInfo; 4640 /* Best domain verification status of the activities found in the other profile */ 4641 int bestDomainVerificationStatus; 4642 } 4643 4644 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4645 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4646 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4647 sourceUserId)) { 4648 return null; 4649 } 4650 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4651 resolvedType, flags, parentUserId); 4652 4653 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4654 return null; 4655 } 4656 CrossProfileDomainInfo result = null; 4657 int size = resultTargetUser.size(); 4658 for (int i = 0; i < size; i++) { 4659 ResolveInfo riTargetUser = resultTargetUser.get(i); 4660 // Intent filter verification is only for filters that specify a host. So don't return 4661 // those that handle all web uris. 4662 if (riTargetUser.handleAllWebDataURI) { 4663 continue; 4664 } 4665 String packageName = riTargetUser.activityInfo.packageName; 4666 PackageSetting ps = mSettings.mPackages.get(packageName); 4667 if (ps == null) { 4668 continue; 4669 } 4670 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4671 int status = (int)(verificationState >> 32); 4672 if (result == null) { 4673 result = new CrossProfileDomainInfo(); 4674 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4675 sourceUserId, parentUserId); 4676 result.bestDomainVerificationStatus = status; 4677 } else { 4678 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4679 result.bestDomainVerificationStatus); 4680 } 4681 } 4682 // Don't consider matches with status NEVER across profiles. 4683 if (result != null && result.bestDomainVerificationStatus 4684 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4685 return null; 4686 } 4687 return result; 4688 } 4689 4690 /** 4691 * Verification statuses are ordered from the worse to the best, except for 4692 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4693 */ 4694 private int bestDomainVerificationStatus(int status1, int status2) { 4695 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4696 return status2; 4697 } 4698 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4699 return status1; 4700 } 4701 return (int) MathUtils.max(status1, status2); 4702 } 4703 4704 private boolean isUserEnabled(int userId) { 4705 long callingId = Binder.clearCallingIdentity(); 4706 try { 4707 UserInfo userInfo = sUserManager.getUserInfo(userId); 4708 return userInfo != null && userInfo.isEnabled(); 4709 } finally { 4710 Binder.restoreCallingIdentity(callingId); 4711 } 4712 } 4713 4714 /** 4715 * Filter out activities with systemUserOnly flag set, when current user is not System. 4716 * 4717 * @return filtered list 4718 */ 4719 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4720 if (userId == UserHandle.USER_SYSTEM) { 4721 return resolveInfos; 4722 } 4723 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4724 ResolveInfo info = resolveInfos.get(i); 4725 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4726 resolveInfos.remove(i); 4727 } 4728 } 4729 return resolveInfos; 4730 } 4731 4732 private static boolean hasWebURI(Intent intent) { 4733 if (intent.getData() == null) { 4734 return false; 4735 } 4736 final String scheme = intent.getScheme(); 4737 if (TextUtils.isEmpty(scheme)) { 4738 return false; 4739 } 4740 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4741 } 4742 4743 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4744 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4745 int userId) { 4746 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4747 4748 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4749 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4750 candidates.size()); 4751 } 4752 4753 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4754 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4755 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4756 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4757 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4758 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4759 4760 synchronized (mPackages) { 4761 final int count = candidates.size(); 4762 // First, try to use linked apps. Partition the candidates into four lists: 4763 // one for the final results, one for the "do not use ever", one for "undefined status" 4764 // and finally one for "browser app type". 4765 for (int n=0; n<count; n++) { 4766 ResolveInfo info = candidates.get(n); 4767 String packageName = info.activityInfo.packageName; 4768 PackageSetting ps = mSettings.mPackages.get(packageName); 4769 if (ps != null) { 4770 // Add to the special match all list (Browser use case) 4771 if (info.handleAllWebDataURI) { 4772 matchAllList.add(info); 4773 continue; 4774 } 4775 // Try to get the status from User settings first 4776 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4777 int status = (int)(packedStatus >> 32); 4778 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4779 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4780 if (DEBUG_DOMAIN_VERIFICATION) { 4781 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4782 + " : linkgen=" + linkGeneration); 4783 } 4784 // Use link-enabled generation as preferredOrder, i.e. 4785 // prefer newly-enabled over earlier-enabled. 4786 info.preferredOrder = linkGeneration; 4787 alwaysList.add(info); 4788 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4789 if (DEBUG_DOMAIN_VERIFICATION) { 4790 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4791 } 4792 neverList.add(info); 4793 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4794 if (DEBUG_DOMAIN_VERIFICATION) { 4795 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4796 } 4797 alwaysAskList.add(info); 4798 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4799 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4800 if (DEBUG_DOMAIN_VERIFICATION) { 4801 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4802 } 4803 undefinedList.add(info); 4804 } 4805 } 4806 } 4807 4808 // We'll want to include browser possibilities in a few cases 4809 boolean includeBrowser = false; 4810 4811 // First try to add the "always" resolution(s) for the current user, if any 4812 if (alwaysList.size() > 0) { 4813 result.addAll(alwaysList); 4814 } else { 4815 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4816 result.addAll(undefinedList); 4817 // Maybe add one for the other profile. 4818 if (xpDomainInfo != null && ( 4819 xpDomainInfo.bestDomainVerificationStatus 4820 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4821 result.add(xpDomainInfo.resolveInfo); 4822 } 4823 includeBrowser = true; 4824 } 4825 4826 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4827 // If there were 'always' entries their preferred order has been set, so we also 4828 // back that off to make the alternatives equivalent 4829 if (alwaysAskList.size() > 0) { 4830 for (ResolveInfo i : result) { 4831 i.preferredOrder = 0; 4832 } 4833 result.addAll(alwaysAskList); 4834 includeBrowser = true; 4835 } 4836 4837 if (includeBrowser) { 4838 // Also add browsers (all of them or only the default one) 4839 if (DEBUG_DOMAIN_VERIFICATION) { 4840 Slog.v(TAG, " ...including browsers in candidate set"); 4841 } 4842 if ((matchFlags & MATCH_ALL) != 0) { 4843 result.addAll(matchAllList); 4844 } else { 4845 // Browser/generic handling case. If there's a default browser, go straight 4846 // to that (but only if there is no other higher-priority match). 4847 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4848 int maxMatchPrio = 0; 4849 ResolveInfo defaultBrowserMatch = null; 4850 final int numCandidates = matchAllList.size(); 4851 for (int n = 0; n < numCandidates; n++) { 4852 ResolveInfo info = matchAllList.get(n); 4853 // track the highest overall match priority... 4854 if (info.priority > maxMatchPrio) { 4855 maxMatchPrio = info.priority; 4856 } 4857 // ...and the highest-priority default browser match 4858 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4859 if (defaultBrowserMatch == null 4860 || (defaultBrowserMatch.priority < info.priority)) { 4861 if (debug) { 4862 Slog.v(TAG, "Considering default browser match " + info); 4863 } 4864 defaultBrowserMatch = info; 4865 } 4866 } 4867 } 4868 if (defaultBrowserMatch != null 4869 && defaultBrowserMatch.priority >= maxMatchPrio 4870 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4871 { 4872 if (debug) { 4873 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4874 } 4875 result.add(defaultBrowserMatch); 4876 } else { 4877 result.addAll(matchAllList); 4878 } 4879 } 4880 4881 // If there is nothing selected, add all candidates and remove the ones that the user 4882 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4883 if (result.size() == 0) { 4884 result.addAll(candidates); 4885 result.removeAll(neverList); 4886 } 4887 } 4888 } 4889 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4890 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4891 result.size()); 4892 for (ResolveInfo info : result) { 4893 Slog.v(TAG, " + " + info.activityInfo); 4894 } 4895 } 4896 return result; 4897 } 4898 4899 // Returns a packed value as a long: 4900 // 4901 // high 'int'-sized word: link status: undefined/ask/never/always. 4902 // low 'int'-sized word: relative priority among 'always' results. 4903 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4904 long result = ps.getDomainVerificationStatusForUser(userId); 4905 // if none available, get the master status 4906 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4907 if (ps.getIntentFilterVerificationInfo() != null) { 4908 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4909 } 4910 } 4911 return result; 4912 } 4913 4914 private ResolveInfo querySkipCurrentProfileIntents( 4915 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4916 int flags, int sourceUserId) { 4917 if (matchingFilters != null) { 4918 int size = matchingFilters.size(); 4919 for (int i = 0; i < size; i ++) { 4920 CrossProfileIntentFilter filter = matchingFilters.get(i); 4921 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4922 // Checking if there are activities in the target user that can handle the 4923 // intent. 4924 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4925 resolvedType, flags, sourceUserId); 4926 if (resolveInfo != null) { 4927 return resolveInfo; 4928 } 4929 } 4930 } 4931 } 4932 return null; 4933 } 4934 4935 // Return matching ResolveInfo if any for skip current profile intent filters. 4936 private ResolveInfo queryCrossProfileIntents( 4937 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4938 int flags, int sourceUserId) { 4939 if (matchingFilters != null) { 4940 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4941 // match the same intent. For performance reasons, it is better not to 4942 // run queryIntent twice for the same userId 4943 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4944 int size = matchingFilters.size(); 4945 for (int i = 0; i < size; i++) { 4946 CrossProfileIntentFilter filter = matchingFilters.get(i); 4947 int targetUserId = filter.getTargetUserId(); 4948 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4949 && !alreadyTriedUserIds.get(targetUserId)) { 4950 // Checking if there are activities in the target user that can handle the 4951 // intent. 4952 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4953 resolvedType, flags, sourceUserId); 4954 if (resolveInfo != null) return resolveInfo; 4955 alreadyTriedUserIds.put(targetUserId, true); 4956 } 4957 } 4958 } 4959 return null; 4960 } 4961 4962 /** 4963 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4964 * will forward the intent to the filter's target user. 4965 * Otherwise, returns null. 4966 */ 4967 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4968 String resolvedType, int flags, int sourceUserId) { 4969 int targetUserId = filter.getTargetUserId(); 4970 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4971 resolvedType, flags, targetUserId); 4972 if (resultTargetUser != null && !resultTargetUser.isEmpty() 4973 && isUserEnabled(targetUserId)) { 4974 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 4975 } 4976 return null; 4977 } 4978 4979 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 4980 int sourceUserId, int targetUserId) { 4981 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4982 long ident = Binder.clearCallingIdentity(); 4983 boolean targetIsProfile; 4984 try { 4985 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4986 } finally { 4987 Binder.restoreCallingIdentity(ident); 4988 } 4989 String className; 4990 if (targetIsProfile) { 4991 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4992 } else { 4993 className = FORWARD_INTENT_TO_PARENT; 4994 } 4995 ComponentName forwardingActivityComponentName = new ComponentName( 4996 mAndroidApplication.packageName, className); 4997 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4998 sourceUserId); 4999 if (!targetIsProfile) { 5000 forwardingActivityInfo.showUserIcon = targetUserId; 5001 forwardingResolveInfo.noResourceId = true; 5002 } 5003 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5004 forwardingResolveInfo.priority = 0; 5005 forwardingResolveInfo.preferredOrder = 0; 5006 forwardingResolveInfo.match = 0; 5007 forwardingResolveInfo.isDefault = true; 5008 forwardingResolveInfo.filter = filter; 5009 forwardingResolveInfo.targetUserId = targetUserId; 5010 return forwardingResolveInfo; 5011 } 5012 5013 @Override 5014 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5015 Intent[] specifics, String[] specificTypes, Intent intent, 5016 String resolvedType, int flags, int userId) { 5017 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5018 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5019 false, "query intent activity options"); 5020 final String resultsAction = intent.getAction(); 5021 5022 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5023 | PackageManager.GET_RESOLVED_FILTER, userId); 5024 5025 if (DEBUG_INTENT_MATCHING) { 5026 Log.v(TAG, "Query " + intent + ": " + results); 5027 } 5028 5029 int specificsPos = 0; 5030 int N; 5031 5032 // todo: note that the algorithm used here is O(N^2). This 5033 // isn't a problem in our current environment, but if we start running 5034 // into situations where we have more than 5 or 10 matches then this 5035 // should probably be changed to something smarter... 5036 5037 // First we go through and resolve each of the specific items 5038 // that were supplied, taking care of removing any corresponding 5039 // duplicate items in the generic resolve list. 5040 if (specifics != null) { 5041 for (int i=0; i<specifics.length; i++) { 5042 final Intent sintent = specifics[i]; 5043 if (sintent == null) { 5044 continue; 5045 } 5046 5047 if (DEBUG_INTENT_MATCHING) { 5048 Log.v(TAG, "Specific #" + i + ": " + sintent); 5049 } 5050 5051 String action = sintent.getAction(); 5052 if (resultsAction != null && resultsAction.equals(action)) { 5053 // If this action was explicitly requested, then don't 5054 // remove things that have it. 5055 action = null; 5056 } 5057 5058 ResolveInfo ri = null; 5059 ActivityInfo ai = null; 5060 5061 ComponentName comp = sintent.getComponent(); 5062 if (comp == null) { 5063 ri = resolveIntent( 5064 sintent, 5065 specificTypes != null ? specificTypes[i] : null, 5066 flags, userId); 5067 if (ri == null) { 5068 continue; 5069 } 5070 if (ri == mResolveInfo) { 5071 // ACK! Must do something better with this. 5072 } 5073 ai = ri.activityInfo; 5074 comp = new ComponentName(ai.applicationInfo.packageName, 5075 ai.name); 5076 } else { 5077 ai = getActivityInfo(comp, flags, userId); 5078 if (ai == null) { 5079 continue; 5080 } 5081 } 5082 5083 // Look for any generic query activities that are duplicates 5084 // of this specific one, and remove them from the results. 5085 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5086 N = results.size(); 5087 int j; 5088 for (j=specificsPos; j<N; j++) { 5089 ResolveInfo sri = results.get(j); 5090 if ((sri.activityInfo.name.equals(comp.getClassName()) 5091 && sri.activityInfo.applicationInfo.packageName.equals( 5092 comp.getPackageName())) 5093 || (action != null && sri.filter.matchAction(action))) { 5094 results.remove(j); 5095 if (DEBUG_INTENT_MATCHING) Log.v( 5096 TAG, "Removing duplicate item from " + j 5097 + " due to specific " + specificsPos); 5098 if (ri == null) { 5099 ri = sri; 5100 } 5101 j--; 5102 N--; 5103 } 5104 } 5105 5106 // Add this specific item to its proper place. 5107 if (ri == null) { 5108 ri = new ResolveInfo(); 5109 ri.activityInfo = ai; 5110 } 5111 results.add(specificsPos, ri); 5112 ri.specificIndex = i; 5113 specificsPos++; 5114 } 5115 } 5116 5117 // Now we go through the remaining generic results and remove any 5118 // duplicate actions that are found here. 5119 N = results.size(); 5120 for (int i=specificsPos; i<N-1; i++) { 5121 final ResolveInfo rii = results.get(i); 5122 if (rii.filter == null) { 5123 continue; 5124 } 5125 5126 // Iterate over all of the actions of this result's intent 5127 // filter... typically this should be just one. 5128 final Iterator<String> it = rii.filter.actionsIterator(); 5129 if (it == null) { 5130 continue; 5131 } 5132 while (it.hasNext()) { 5133 final String action = it.next(); 5134 if (resultsAction != null && resultsAction.equals(action)) { 5135 // If this action was explicitly requested, then don't 5136 // remove things that have it. 5137 continue; 5138 } 5139 for (int j=i+1; j<N; j++) { 5140 final ResolveInfo rij = results.get(j); 5141 if (rij.filter != null && rij.filter.hasAction(action)) { 5142 results.remove(j); 5143 if (DEBUG_INTENT_MATCHING) Log.v( 5144 TAG, "Removing duplicate item from " + j 5145 + " due to action " + action + " at " + i); 5146 j--; 5147 N--; 5148 } 5149 } 5150 } 5151 5152 // If the caller didn't request filter information, drop it now 5153 // so we don't have to marshall/unmarshall it. 5154 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5155 rii.filter = null; 5156 } 5157 } 5158 5159 // Filter out the caller activity if so requested. 5160 if (caller != null) { 5161 N = results.size(); 5162 for (int i=0; i<N; i++) { 5163 ActivityInfo ainfo = results.get(i).activityInfo; 5164 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5165 && caller.getClassName().equals(ainfo.name)) { 5166 results.remove(i); 5167 break; 5168 } 5169 } 5170 } 5171 5172 // If the caller didn't request filter information, 5173 // drop them now so we don't have to 5174 // marshall/unmarshall it. 5175 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5176 N = results.size(); 5177 for (int i=0; i<N; i++) { 5178 results.get(i).filter = null; 5179 } 5180 } 5181 5182 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5183 return results; 5184 } 5185 5186 @Override 5187 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5188 int userId) { 5189 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5190 ComponentName comp = intent.getComponent(); 5191 if (comp == null) { 5192 if (intent.getSelector() != null) { 5193 intent = intent.getSelector(); 5194 comp = intent.getComponent(); 5195 } 5196 } 5197 if (comp != null) { 5198 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5199 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5200 if (ai != null) { 5201 ResolveInfo ri = new ResolveInfo(); 5202 ri.activityInfo = ai; 5203 list.add(ri); 5204 } 5205 return list; 5206 } 5207 5208 // reader 5209 synchronized (mPackages) { 5210 String pkgName = intent.getPackage(); 5211 if (pkgName == null) { 5212 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5213 } 5214 final PackageParser.Package pkg = mPackages.get(pkgName); 5215 if (pkg != null) { 5216 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5217 userId); 5218 } 5219 return null; 5220 } 5221 } 5222 5223 @Override 5224 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5225 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5226 if (!sUserManager.exists(userId)) return null; 5227 if (query != null) { 5228 if (query.size() >= 1) { 5229 // If there is more than one service with the same priority, 5230 // just arbitrarily pick the first one. 5231 return query.get(0); 5232 } 5233 } 5234 return null; 5235 } 5236 5237 @Override 5238 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5239 int userId) { 5240 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5241 ComponentName comp = intent.getComponent(); 5242 if (comp == null) { 5243 if (intent.getSelector() != null) { 5244 intent = intent.getSelector(); 5245 comp = intent.getComponent(); 5246 } 5247 } 5248 if (comp != null) { 5249 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5250 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5251 if (si != null) { 5252 final ResolveInfo ri = new ResolveInfo(); 5253 ri.serviceInfo = si; 5254 list.add(ri); 5255 } 5256 return list; 5257 } 5258 5259 // reader 5260 synchronized (mPackages) { 5261 String pkgName = intent.getPackage(); 5262 if (pkgName == null) { 5263 return mServices.queryIntent(intent, resolvedType, flags, userId); 5264 } 5265 final PackageParser.Package pkg = mPackages.get(pkgName); 5266 if (pkg != null) { 5267 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5268 userId); 5269 } 5270 return null; 5271 } 5272 } 5273 5274 @Override 5275 public List<ResolveInfo> queryIntentContentProviders( 5276 Intent intent, String resolvedType, int flags, int userId) { 5277 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5278 ComponentName comp = intent.getComponent(); 5279 if (comp == null) { 5280 if (intent.getSelector() != null) { 5281 intent = intent.getSelector(); 5282 comp = intent.getComponent(); 5283 } 5284 } 5285 if (comp != null) { 5286 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5287 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5288 if (pi != null) { 5289 final ResolveInfo ri = new ResolveInfo(); 5290 ri.providerInfo = pi; 5291 list.add(ri); 5292 } 5293 return list; 5294 } 5295 5296 // reader 5297 synchronized (mPackages) { 5298 String pkgName = intent.getPackage(); 5299 if (pkgName == null) { 5300 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5301 } 5302 final PackageParser.Package pkg = mPackages.get(pkgName); 5303 if (pkg != null) { 5304 return mProviders.queryIntentForPackage( 5305 intent, resolvedType, flags, pkg.providers, userId); 5306 } 5307 return null; 5308 } 5309 } 5310 5311 @Override 5312 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5313 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5314 5315 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5316 5317 // writer 5318 synchronized (mPackages) { 5319 ArrayList<PackageInfo> list; 5320 if (listUninstalled) { 5321 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5322 for (PackageSetting ps : mSettings.mPackages.values()) { 5323 PackageInfo pi; 5324 if (ps.pkg != null) { 5325 pi = generatePackageInfo(ps.pkg, flags, userId); 5326 } else { 5327 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5328 } 5329 if (pi != null) { 5330 list.add(pi); 5331 } 5332 } 5333 } else { 5334 list = new ArrayList<PackageInfo>(mPackages.size()); 5335 for (PackageParser.Package p : mPackages.values()) { 5336 PackageInfo pi = generatePackageInfo(p, flags, userId); 5337 if (pi != null) { 5338 list.add(pi); 5339 } 5340 } 5341 } 5342 5343 return new ParceledListSlice<PackageInfo>(list); 5344 } 5345 } 5346 5347 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5348 String[] permissions, boolean[] tmp, int flags, int userId) { 5349 int numMatch = 0; 5350 final PermissionsState permissionsState = ps.getPermissionsState(); 5351 for (int i=0; i<permissions.length; i++) { 5352 final String permission = permissions[i]; 5353 if (permissionsState.hasPermission(permission, userId)) { 5354 tmp[i] = true; 5355 numMatch++; 5356 } else { 5357 tmp[i] = false; 5358 } 5359 } 5360 if (numMatch == 0) { 5361 return; 5362 } 5363 PackageInfo pi; 5364 if (ps.pkg != null) { 5365 pi = generatePackageInfo(ps.pkg, flags, userId); 5366 } else { 5367 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5368 } 5369 // The above might return null in cases of uninstalled apps or install-state 5370 // skew across users/profiles. 5371 if (pi != null) { 5372 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5373 if (numMatch == permissions.length) { 5374 pi.requestedPermissions = permissions; 5375 } else { 5376 pi.requestedPermissions = new String[numMatch]; 5377 numMatch = 0; 5378 for (int i=0; i<permissions.length; i++) { 5379 if (tmp[i]) { 5380 pi.requestedPermissions[numMatch] = permissions[i]; 5381 numMatch++; 5382 } 5383 } 5384 } 5385 } 5386 list.add(pi); 5387 } 5388 } 5389 5390 @Override 5391 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5392 String[] permissions, int flags, int userId) { 5393 if (!sUserManager.exists(userId)) return null; 5394 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5395 5396 // writer 5397 synchronized (mPackages) { 5398 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5399 boolean[] tmpBools = new boolean[permissions.length]; 5400 if (listUninstalled) { 5401 for (PackageSetting ps : mSettings.mPackages.values()) { 5402 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5403 } 5404 } else { 5405 for (PackageParser.Package pkg : mPackages.values()) { 5406 PackageSetting ps = (PackageSetting)pkg.mExtras; 5407 if (ps != null) { 5408 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5409 userId); 5410 } 5411 } 5412 } 5413 5414 return new ParceledListSlice<PackageInfo>(list); 5415 } 5416 } 5417 5418 @Override 5419 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5420 if (!sUserManager.exists(userId)) return null; 5421 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5422 5423 // writer 5424 synchronized (mPackages) { 5425 ArrayList<ApplicationInfo> list; 5426 if (listUninstalled) { 5427 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5428 for (PackageSetting ps : mSettings.mPackages.values()) { 5429 ApplicationInfo ai; 5430 if (ps.pkg != null) { 5431 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5432 ps.readUserState(userId), userId); 5433 } else { 5434 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5435 } 5436 if (ai != null) { 5437 list.add(ai); 5438 } 5439 } 5440 } else { 5441 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5442 for (PackageParser.Package p : mPackages.values()) { 5443 if (p.mExtras != null) { 5444 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5445 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5446 if (ai != null) { 5447 list.add(ai); 5448 } 5449 } 5450 } 5451 } 5452 5453 return new ParceledListSlice<ApplicationInfo>(list); 5454 } 5455 } 5456 5457 public List<ApplicationInfo> getPersistentApplications(int flags) { 5458 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5459 5460 // reader 5461 synchronized (mPackages) { 5462 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5463 final int userId = UserHandle.getCallingUserId(); 5464 while (i.hasNext()) { 5465 final PackageParser.Package p = i.next(); 5466 if (p.applicationInfo != null 5467 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5468 && (!mSafeMode || isSystemApp(p))) { 5469 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5470 if (ps != null) { 5471 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5472 ps.readUserState(userId), userId); 5473 if (ai != null) { 5474 finalList.add(ai); 5475 } 5476 } 5477 } 5478 } 5479 } 5480 5481 return finalList; 5482 } 5483 5484 @Override 5485 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5486 if (!sUserManager.exists(userId)) return null; 5487 // reader 5488 synchronized (mPackages) { 5489 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5490 PackageSetting ps = provider != null 5491 ? mSettings.mPackages.get(provider.owner.packageName) 5492 : null; 5493 return ps != null 5494 && mSettings.isEnabledLPr(provider.info, flags, userId) 5495 && (!mSafeMode || (provider.info.applicationInfo.flags 5496 &ApplicationInfo.FLAG_SYSTEM) != 0) 5497 ? PackageParser.generateProviderInfo(provider, flags, 5498 ps.readUserState(userId), userId) 5499 : null; 5500 } 5501 } 5502 5503 /** 5504 * @deprecated 5505 */ 5506 @Deprecated 5507 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5508 // reader 5509 synchronized (mPackages) { 5510 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5511 .entrySet().iterator(); 5512 final int userId = UserHandle.getCallingUserId(); 5513 while (i.hasNext()) { 5514 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5515 PackageParser.Provider p = entry.getValue(); 5516 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5517 5518 if (ps != null && p.syncable 5519 && (!mSafeMode || (p.info.applicationInfo.flags 5520 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5521 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5522 ps.readUserState(userId), userId); 5523 if (info != null) { 5524 outNames.add(entry.getKey()); 5525 outInfo.add(info); 5526 } 5527 } 5528 } 5529 } 5530 } 5531 5532 @Override 5533 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5534 int uid, int flags) { 5535 ArrayList<ProviderInfo> finalList = null; 5536 // reader 5537 synchronized (mPackages) { 5538 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5539 final int userId = processName != null ? 5540 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5541 while (i.hasNext()) { 5542 final PackageParser.Provider p = i.next(); 5543 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5544 if (ps != null && p.info.authority != null 5545 && (processName == null 5546 || (p.info.processName.equals(processName) 5547 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5548 && mSettings.isEnabledLPr(p.info, flags, userId) 5549 && (!mSafeMode 5550 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5551 if (finalList == null) { 5552 finalList = new ArrayList<ProviderInfo>(3); 5553 } 5554 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5555 ps.readUserState(userId), userId); 5556 if (info != null) { 5557 finalList.add(info); 5558 } 5559 } 5560 } 5561 } 5562 5563 if (finalList != null) { 5564 Collections.sort(finalList, mProviderInitOrderSorter); 5565 return new ParceledListSlice<ProviderInfo>(finalList); 5566 } 5567 5568 return null; 5569 } 5570 5571 @Override 5572 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5573 int flags) { 5574 // reader 5575 synchronized (mPackages) { 5576 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5577 return PackageParser.generateInstrumentationInfo(i, flags); 5578 } 5579 } 5580 5581 @Override 5582 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5583 int flags) { 5584 ArrayList<InstrumentationInfo> finalList = 5585 new ArrayList<InstrumentationInfo>(); 5586 5587 // reader 5588 synchronized (mPackages) { 5589 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5590 while (i.hasNext()) { 5591 final PackageParser.Instrumentation p = i.next(); 5592 if (targetPackage == null 5593 || targetPackage.equals(p.info.targetPackage)) { 5594 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5595 flags); 5596 if (ii != null) { 5597 finalList.add(ii); 5598 } 5599 } 5600 } 5601 } 5602 5603 return finalList; 5604 } 5605 5606 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5607 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5608 if (overlays == null) { 5609 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5610 return; 5611 } 5612 for (PackageParser.Package opkg : overlays.values()) { 5613 // Not much to do if idmap fails: we already logged the error 5614 // and we certainly don't want to abort installation of pkg simply 5615 // because an overlay didn't fit properly. For these reasons, 5616 // ignore the return value of createIdmapForPackagePairLI. 5617 createIdmapForPackagePairLI(pkg, opkg); 5618 } 5619 } 5620 5621 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5622 PackageParser.Package opkg) { 5623 if (!opkg.mTrustedOverlay) { 5624 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5625 opkg.baseCodePath + ": overlay not trusted"); 5626 return false; 5627 } 5628 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5629 if (overlaySet == null) { 5630 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5631 opkg.baseCodePath + " but target package has no known overlays"); 5632 return false; 5633 } 5634 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5635 // TODO: generate idmap for split APKs 5636 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5637 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5638 + opkg.baseCodePath); 5639 return false; 5640 } 5641 PackageParser.Package[] overlayArray = 5642 overlaySet.values().toArray(new PackageParser.Package[0]); 5643 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5644 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5645 return p1.mOverlayPriority - p2.mOverlayPriority; 5646 } 5647 }; 5648 Arrays.sort(overlayArray, cmp); 5649 5650 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5651 int i = 0; 5652 for (PackageParser.Package p : overlayArray) { 5653 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5654 } 5655 return true; 5656 } 5657 5658 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5659 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5660 try { 5661 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5662 } finally { 5663 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5664 } 5665 } 5666 5667 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5668 final File[] files = dir.listFiles(); 5669 if (ArrayUtils.isEmpty(files)) { 5670 Log.d(TAG, "No files in app dir " + dir); 5671 return; 5672 } 5673 5674 if (DEBUG_PACKAGE_SCANNING) { 5675 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5676 + " flags=0x" + Integer.toHexString(parseFlags)); 5677 } 5678 5679 for (File file : files) { 5680 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5681 && !PackageInstallerService.isStageName(file.getName()); 5682 if (!isPackage) { 5683 // Ignore entries which are not packages 5684 continue; 5685 } 5686 try { 5687 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5688 scanFlags, currentTime, UserHandle.SYSTEM); 5689 } catch (PackageManagerException e) { 5690 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5691 5692 // Delete invalid userdata apps 5693 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5694 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5695 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5696 if (file.isDirectory()) { 5697 mInstaller.rmPackageDir(file.getAbsolutePath()); 5698 } else { 5699 file.delete(); 5700 } 5701 } 5702 } 5703 } 5704 } 5705 5706 private static File getSettingsProblemFile() { 5707 File dataDir = Environment.getDataDirectory(); 5708 File systemDir = new File(dataDir, "system"); 5709 File fname = new File(systemDir, "uiderrors.txt"); 5710 return fname; 5711 } 5712 5713 static void reportSettingsProblem(int priority, String msg) { 5714 logCriticalInfo(priority, msg); 5715 } 5716 5717 static void logCriticalInfo(int priority, String msg) { 5718 Slog.println(priority, TAG, msg); 5719 EventLogTags.writePmCriticalInfo(msg); 5720 try { 5721 File fname = getSettingsProblemFile(); 5722 FileOutputStream out = new FileOutputStream(fname, true); 5723 PrintWriter pw = new FastPrintWriter(out); 5724 SimpleDateFormat formatter = new SimpleDateFormat(); 5725 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5726 pw.println(dateString + ": " + msg); 5727 pw.close(); 5728 FileUtils.setPermissions( 5729 fname.toString(), 5730 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5731 -1, -1); 5732 } catch (java.io.IOException e) { 5733 } 5734 } 5735 5736 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5737 PackageParser.Package pkg, File srcFile, int parseFlags) 5738 throws PackageManagerException { 5739 if (ps != null 5740 && ps.codePath.equals(srcFile) 5741 && ps.timeStamp == srcFile.lastModified() 5742 && !isCompatSignatureUpdateNeeded(pkg) 5743 && !isRecoverSignatureUpdateNeeded(pkg)) { 5744 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5745 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5746 ArraySet<PublicKey> signingKs; 5747 synchronized (mPackages) { 5748 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5749 } 5750 if (ps.signatures.mSignatures != null 5751 && ps.signatures.mSignatures.length != 0 5752 && signingKs != null) { 5753 // Optimization: reuse the existing cached certificates 5754 // if the package appears to be unchanged. 5755 pkg.mSignatures = ps.signatures.mSignatures; 5756 pkg.mSigningKeys = signingKs; 5757 return; 5758 } 5759 5760 Slog.w(TAG, "PackageSetting for " + ps.name 5761 + " is missing signatures. Collecting certs again to recover them."); 5762 } else { 5763 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5764 } 5765 5766 try { 5767 pp.collectCertificates(pkg, parseFlags); 5768 pp.collectManifestDigest(pkg); 5769 } catch (PackageParserException e) { 5770 throw PackageManagerException.from(e); 5771 } 5772 } 5773 5774 /** 5775 * Traces a package scan. 5776 * @see #scanPackageLI(File, int, int, long, UserHandle) 5777 */ 5778 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5779 long currentTime, UserHandle user) throws PackageManagerException { 5780 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5781 try { 5782 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5783 } finally { 5784 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5785 } 5786 } 5787 5788 /** 5789 * Scans a package and returns the newly parsed package. 5790 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5791 */ 5792 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5793 long currentTime, UserHandle user) throws PackageManagerException { 5794 Preconditions.checkNotNull(user); 5795 5796 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5797 parseFlags |= mDefParseFlags; 5798 PackageParser pp = new PackageParser(); 5799 pp.setSeparateProcesses(mSeparateProcesses); 5800 pp.setOnlyCoreApps(mOnlyCore); 5801 pp.setDisplayMetrics(mMetrics); 5802 5803 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5804 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5805 } 5806 5807 final PackageParser.Package pkg; 5808 try { 5809 pkg = pp.parsePackage(scanFile, parseFlags); 5810 } catch (PackageParserException e) { 5811 throw PackageManagerException.from(e); 5812 } 5813 5814 PackageSetting ps = null; 5815 PackageSetting updatedPkg; 5816 // reader 5817 synchronized (mPackages) { 5818 // Look to see if we already know about this package. 5819 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5820 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5821 // This package has been renamed to its original name. Let's 5822 // use that. 5823 ps = mSettings.peekPackageLPr(oldName); 5824 } 5825 // If there was no original package, see one for the real package name. 5826 if (ps == null) { 5827 ps = mSettings.peekPackageLPr(pkg.packageName); 5828 } 5829 // Check to see if this package could be hiding/updating a system 5830 // package. Must look for it either under the original or real 5831 // package name depending on our state. 5832 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5833 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5834 } 5835 boolean updatedPkgBetter = false; 5836 // First check if this is a system package that may involve an update 5837 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 5838 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5839 // it needs to drop FLAG_PRIVILEGED. 5840 if (locationIsPrivileged(scanFile)) { 5841 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5842 } else { 5843 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5844 } 5845 5846 if (ps != null && !ps.codePath.equals(scanFile)) { 5847 // The path has changed from what was last scanned... check the 5848 // version of the new path against what we have stored to determine 5849 // what to do. 5850 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5851 if (pkg.mVersionCode <= ps.versionCode) { 5852 // The system package has been updated and the code path does not match 5853 // Ignore entry. Skip it. 5854 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5855 + " ignored: updated version " + ps.versionCode 5856 + " better than this " + pkg.mVersionCode); 5857 if (!updatedPkg.codePath.equals(scanFile)) { 5858 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5859 + ps.name + " changing from " + updatedPkg.codePathString 5860 + " to " + scanFile); 5861 updatedPkg.codePath = scanFile; 5862 updatedPkg.codePathString = scanFile.toString(); 5863 updatedPkg.resourcePath = scanFile; 5864 updatedPkg.resourcePathString = scanFile.toString(); 5865 } 5866 updatedPkg.pkg = pkg; 5867 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5868 "Package " + ps.name + " at " + scanFile 5869 + " ignored: updated version " + ps.versionCode 5870 + " better than this " + pkg.mVersionCode); 5871 } else { 5872 // The current app on the system partition is better than 5873 // what we have updated to on the data partition; switch 5874 // back to the system partition version. 5875 // At this point, its safely assumed that package installation for 5876 // apps in system partition will go through. If not there won't be a working 5877 // version of the app 5878 // writer 5879 synchronized (mPackages) { 5880 // Just remove the loaded entries from package lists. 5881 mPackages.remove(ps.name); 5882 } 5883 5884 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5885 + " reverting from " + ps.codePathString 5886 + ": new version " + pkg.mVersionCode 5887 + " better than installed " + ps.versionCode); 5888 5889 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5890 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5891 synchronized (mInstallLock) { 5892 args.cleanUpResourcesLI(); 5893 } 5894 synchronized (mPackages) { 5895 mSettings.enableSystemPackageLPw(ps.name); 5896 } 5897 updatedPkgBetter = true; 5898 } 5899 } 5900 } 5901 5902 if (updatedPkg != null) { 5903 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5904 // initially 5905 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5906 5907 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5908 // flag set initially 5909 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5910 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5911 } 5912 } 5913 5914 // Verify certificates against what was last scanned 5915 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5916 5917 /* 5918 * A new system app appeared, but we already had a non-system one of the 5919 * same name installed earlier. 5920 */ 5921 boolean shouldHideSystemApp = false; 5922 if (updatedPkg == null && ps != null 5923 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5924 /* 5925 * Check to make sure the signatures match first. If they don't, 5926 * wipe the installed application and its data. 5927 */ 5928 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5929 != PackageManager.SIGNATURE_MATCH) { 5930 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5931 + " signatures don't match existing userdata copy; removing"); 5932 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5933 ps = null; 5934 } else { 5935 /* 5936 * If the newly-added system app is an older version than the 5937 * already installed version, hide it. It will be scanned later 5938 * and re-added like an update. 5939 */ 5940 if (pkg.mVersionCode <= ps.versionCode) { 5941 shouldHideSystemApp = true; 5942 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5943 + " but new version " + pkg.mVersionCode + " better than installed " 5944 + ps.versionCode + "; hiding system"); 5945 } else { 5946 /* 5947 * The newly found system app is a newer version that the 5948 * one previously installed. Simply remove the 5949 * already-installed application and replace it with our own 5950 * while keeping the application data. 5951 */ 5952 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5953 + " reverting from " + ps.codePathString + ": new version " 5954 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5955 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5956 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5957 synchronized (mInstallLock) { 5958 args.cleanUpResourcesLI(); 5959 } 5960 } 5961 } 5962 } 5963 5964 // The apk is forward locked (not public) if its code and resources 5965 // are kept in different files. (except for app in either system or 5966 // vendor path). 5967 // TODO grab this value from PackageSettings 5968 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5969 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5970 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5971 } 5972 } 5973 5974 // TODO: extend to support forward-locked splits 5975 String resourcePath = null; 5976 String baseResourcePath = null; 5977 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5978 if (ps != null && ps.resourcePathString != null) { 5979 resourcePath = ps.resourcePathString; 5980 baseResourcePath = ps.resourcePathString; 5981 } else { 5982 // Should not happen at all. Just log an error. 5983 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5984 } 5985 } else { 5986 resourcePath = pkg.codePath; 5987 baseResourcePath = pkg.baseCodePath; 5988 } 5989 5990 // Set application objects path explicitly. 5991 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5992 pkg.applicationInfo.setCodePath(pkg.codePath); 5993 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5994 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5995 pkg.applicationInfo.setResourcePath(resourcePath); 5996 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5997 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5998 5999 // Note that we invoke the following method only if we are about to unpack an application 6000 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6001 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6002 6003 /* 6004 * If the system app should be overridden by a previously installed 6005 * data, hide the system app now and let the /data/app scan pick it up 6006 * again. 6007 */ 6008 if (shouldHideSystemApp) { 6009 synchronized (mPackages) { 6010 mSettings.disableSystemPackageLPw(pkg.packageName); 6011 } 6012 } 6013 6014 return scannedPkg; 6015 } 6016 6017 private static String fixProcessName(String defProcessName, 6018 String processName, int uid) { 6019 if (processName == null) { 6020 return defProcessName; 6021 } 6022 return processName; 6023 } 6024 6025 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6026 throws PackageManagerException { 6027 if (pkgSetting.signatures.mSignatures != null) { 6028 // Already existing package. Make sure signatures match 6029 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6030 == PackageManager.SIGNATURE_MATCH; 6031 if (!match) { 6032 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6033 == PackageManager.SIGNATURE_MATCH; 6034 } 6035 if (!match) { 6036 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6037 == PackageManager.SIGNATURE_MATCH; 6038 } 6039 if (!match) { 6040 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6041 + pkg.packageName + " signatures do not match the " 6042 + "previously installed version; ignoring!"); 6043 } 6044 } 6045 6046 // Check for shared user signatures 6047 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6048 // Already existing package. Make sure signatures match 6049 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6050 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6051 if (!match) { 6052 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6053 == PackageManager.SIGNATURE_MATCH; 6054 } 6055 if (!match) { 6056 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6057 == PackageManager.SIGNATURE_MATCH; 6058 } 6059 if (!match) { 6060 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6061 "Package " + pkg.packageName 6062 + " has no signatures that match those in shared user " 6063 + pkgSetting.sharedUser.name + "; ignoring!"); 6064 } 6065 } 6066 } 6067 6068 /** 6069 * Enforces that only the system UID or root's UID can call a method exposed 6070 * via Binder. 6071 * 6072 * @param message used as message if SecurityException is thrown 6073 * @throws SecurityException if the caller is not system or root 6074 */ 6075 private static final void enforceSystemOrRoot(String message) { 6076 final int uid = Binder.getCallingUid(); 6077 if (uid != Process.SYSTEM_UID && uid != 0) { 6078 throw new SecurityException(message); 6079 } 6080 } 6081 6082 @Override 6083 public void performBootDexOpt() { 6084 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6085 6086 // Before everything else, see whether we need to fstrim. 6087 try { 6088 IMountService ms = PackageHelper.getMountService(); 6089 if (ms != null) { 6090 final boolean isUpgrade = isUpgrade(); 6091 boolean doTrim = isUpgrade; 6092 if (doTrim) { 6093 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6094 } else { 6095 final long interval = android.provider.Settings.Global.getLong( 6096 mContext.getContentResolver(), 6097 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6098 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6099 if (interval > 0) { 6100 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6101 if (timeSinceLast > interval) { 6102 doTrim = true; 6103 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6104 + "; running immediately"); 6105 } 6106 } 6107 } 6108 if (doTrim) { 6109 if (!isFirstBoot()) { 6110 try { 6111 ActivityManagerNative.getDefault().showBootMessage( 6112 mContext.getResources().getString( 6113 R.string.android_upgrading_fstrim), true); 6114 } catch (RemoteException e) { 6115 } 6116 } 6117 ms.runMaintenance(); 6118 } 6119 } else { 6120 Slog.e(TAG, "Mount service unavailable!"); 6121 } 6122 } catch (RemoteException e) { 6123 // Can't happen; MountService is local 6124 } 6125 6126 final ArraySet<PackageParser.Package> pkgs; 6127 synchronized (mPackages) { 6128 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6129 } 6130 6131 if (pkgs != null) { 6132 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6133 // in case the device runs out of space. 6134 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6135 // Give priority to core apps. 6136 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6137 PackageParser.Package pkg = it.next(); 6138 if (pkg.coreApp) { 6139 if (DEBUG_DEXOPT) { 6140 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6141 } 6142 sortedPkgs.add(pkg); 6143 it.remove(); 6144 } 6145 } 6146 // Give priority to system apps that listen for pre boot complete. 6147 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6148 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6149 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6150 PackageParser.Package pkg = it.next(); 6151 if (pkgNames.contains(pkg.packageName)) { 6152 if (DEBUG_DEXOPT) { 6153 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6154 } 6155 sortedPkgs.add(pkg); 6156 it.remove(); 6157 } 6158 } 6159 // Filter out packages that aren't recently used. 6160 filterRecentlyUsedApps(pkgs); 6161 // Add all remaining apps. 6162 for (PackageParser.Package pkg : pkgs) { 6163 if (DEBUG_DEXOPT) { 6164 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6165 } 6166 sortedPkgs.add(pkg); 6167 } 6168 6169 // If we want to be lazy, filter everything that wasn't recently used. 6170 if (mLazyDexOpt) { 6171 filterRecentlyUsedApps(sortedPkgs); 6172 } 6173 6174 int i = 0; 6175 int total = sortedPkgs.size(); 6176 File dataDir = Environment.getDataDirectory(); 6177 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6178 if (lowThreshold == 0) { 6179 throw new IllegalStateException("Invalid low memory threshold"); 6180 } 6181 for (PackageParser.Package pkg : sortedPkgs) { 6182 long usableSpace = dataDir.getUsableSpace(); 6183 if (usableSpace < lowThreshold) { 6184 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6185 break; 6186 } 6187 performBootDexOpt(pkg, ++i, total); 6188 } 6189 } 6190 } 6191 6192 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6193 // Filter out packages that aren't recently used. 6194 // 6195 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6196 // should do a full dexopt. 6197 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6198 int total = pkgs.size(); 6199 int skipped = 0; 6200 long now = System.currentTimeMillis(); 6201 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6202 PackageParser.Package pkg = i.next(); 6203 long then = pkg.mLastPackageUsageTimeInMills; 6204 if (then + mDexOptLRUThresholdInMills < now) { 6205 if (DEBUG_DEXOPT) { 6206 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6207 ((then == 0) ? "never" : new Date(then))); 6208 } 6209 i.remove(); 6210 skipped++; 6211 } 6212 } 6213 if (DEBUG_DEXOPT) { 6214 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6215 } 6216 } 6217 } 6218 6219 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6220 List<ResolveInfo> ris = null; 6221 try { 6222 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6223 intent, null, 0, userId); 6224 } catch (RemoteException e) { 6225 } 6226 ArraySet<String> pkgNames = new ArraySet<String>(); 6227 if (ris != null) { 6228 for (ResolveInfo ri : ris) { 6229 pkgNames.add(ri.activityInfo.packageName); 6230 } 6231 } 6232 return pkgNames; 6233 } 6234 6235 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6236 if (DEBUG_DEXOPT) { 6237 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6238 } 6239 if (!isFirstBoot()) { 6240 try { 6241 ActivityManagerNative.getDefault().showBootMessage( 6242 mContext.getResources().getString(R.string.android_upgrading_apk, 6243 curr, total), true); 6244 } catch (RemoteException e) { 6245 } 6246 } 6247 PackageParser.Package p = pkg; 6248 synchronized (mInstallLock) { 6249 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6250 false /* force dex */, false /* defer */, true /* include dependencies */, 6251 false /* boot complete */, false /*useJit*/); 6252 } 6253 } 6254 6255 @Override 6256 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6257 return performDexOptTraced(packageName, instructionSet, false); 6258 } 6259 6260 public boolean performDexOpt( 6261 String packageName, String instructionSet, boolean backgroundDexopt) { 6262 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6263 } 6264 6265 private boolean performDexOptTraced( 6266 String packageName, String instructionSet, boolean backgroundDexopt) { 6267 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6268 try { 6269 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6270 } finally { 6271 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6272 } 6273 } 6274 6275 private boolean performDexOptInternal( 6276 String packageName, String instructionSet, boolean backgroundDexopt) { 6277 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6278 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6279 if (!dexopt && !updateUsage) { 6280 // We aren't going to dexopt or update usage, so bail early. 6281 return false; 6282 } 6283 PackageParser.Package p; 6284 final String targetInstructionSet; 6285 synchronized (mPackages) { 6286 p = mPackages.get(packageName); 6287 if (p == null) { 6288 return false; 6289 } 6290 if (updateUsage) { 6291 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6292 } 6293 mPackageUsage.write(false); 6294 if (!dexopt) { 6295 // We aren't going to dexopt, so bail early. 6296 return false; 6297 } 6298 6299 targetInstructionSet = instructionSet != null ? instructionSet : 6300 getPrimaryInstructionSet(p.applicationInfo); 6301 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6302 return false; 6303 } 6304 } 6305 long callingId = Binder.clearCallingIdentity(); 6306 try { 6307 synchronized (mInstallLock) { 6308 final String[] instructionSets = new String[] { targetInstructionSet }; 6309 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6310 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6311 true /* boot complete */, false /*useJit*/); 6312 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6313 } 6314 } finally { 6315 Binder.restoreCallingIdentity(callingId); 6316 } 6317 } 6318 6319 public ArraySet<String> getPackagesThatNeedDexOpt() { 6320 ArraySet<String> pkgs = null; 6321 synchronized (mPackages) { 6322 for (PackageParser.Package p : mPackages.values()) { 6323 if (DEBUG_DEXOPT) { 6324 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6325 } 6326 if (!p.mDexOptPerformed.isEmpty()) { 6327 continue; 6328 } 6329 if (pkgs == null) { 6330 pkgs = new ArraySet<String>(); 6331 } 6332 pkgs.add(p.packageName); 6333 } 6334 } 6335 return pkgs; 6336 } 6337 6338 public void shutdown() { 6339 mPackageUsage.write(true); 6340 } 6341 6342 @Override 6343 public void forceDexOpt(String packageName) { 6344 enforceSystemOrRoot("forceDexOpt"); 6345 6346 PackageParser.Package pkg; 6347 synchronized (mPackages) { 6348 pkg = mPackages.get(packageName); 6349 if (pkg == null) { 6350 throw new IllegalArgumentException("Missing package: " + packageName); 6351 } 6352 } 6353 6354 synchronized (mInstallLock) { 6355 final String[] instructionSets = new String[] { 6356 getPrimaryInstructionSet(pkg.applicationInfo) }; 6357 6358 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6359 6360 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6361 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6362 true /* boot complete */, false /*useJit*/); 6363 6364 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6365 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6366 throw new IllegalStateException("Failed to dexopt: " + res); 6367 } 6368 } 6369 } 6370 6371 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6372 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6373 Slog.w(TAG, "Unable to update from " + oldPkg.name 6374 + " to " + newPkg.packageName 6375 + ": old package not in system partition"); 6376 return false; 6377 } else if (mPackages.get(oldPkg.name) != null) { 6378 Slog.w(TAG, "Unable to update from " + oldPkg.name 6379 + " to " + newPkg.packageName 6380 + ": old package still exists"); 6381 return false; 6382 } 6383 return true; 6384 } 6385 6386 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6387 int[] users = sUserManager.getUserIds(); 6388 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6389 if (res < 0) { 6390 return res; 6391 } 6392 for (int user : users) { 6393 if (user != 0) { 6394 res = mInstaller.createUserData(volumeUuid, packageName, 6395 UserHandle.getUid(user, uid), user, seinfo); 6396 if (res < 0) { 6397 return res; 6398 } 6399 } 6400 } 6401 return res; 6402 } 6403 6404 private int removeDataDirsLI(String volumeUuid, String packageName) { 6405 int[] users = sUserManager.getUserIds(); 6406 int res = 0; 6407 for (int user : users) { 6408 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6409 if (resInner < 0) { 6410 res = resInner; 6411 } 6412 } 6413 6414 return res; 6415 } 6416 6417 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6418 int[] users = sUserManager.getUserIds(); 6419 int res = 0; 6420 for (int user : users) { 6421 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6422 if (resInner < 0) { 6423 res = resInner; 6424 } 6425 } 6426 return res; 6427 } 6428 6429 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6430 PackageParser.Package changingLib) { 6431 if (file.path != null) { 6432 usesLibraryFiles.add(file.path); 6433 return; 6434 } 6435 PackageParser.Package p = mPackages.get(file.apk); 6436 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6437 // If we are doing this while in the middle of updating a library apk, 6438 // then we need to make sure to use that new apk for determining the 6439 // dependencies here. (We haven't yet finished committing the new apk 6440 // to the package manager state.) 6441 if (p == null || p.packageName.equals(changingLib.packageName)) { 6442 p = changingLib; 6443 } 6444 } 6445 if (p != null) { 6446 usesLibraryFiles.addAll(p.getAllCodePaths()); 6447 } 6448 } 6449 6450 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6451 PackageParser.Package changingLib) throws PackageManagerException { 6452 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6453 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6454 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6455 for (int i=0; i<N; i++) { 6456 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6457 if (file == null) { 6458 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6459 "Package " + pkg.packageName + " requires unavailable shared library " 6460 + pkg.usesLibraries.get(i) + "; failing!"); 6461 } 6462 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6463 } 6464 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6465 for (int i=0; i<N; i++) { 6466 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6467 if (file == null) { 6468 Slog.w(TAG, "Package " + pkg.packageName 6469 + " desires unavailable shared library " 6470 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6471 } else { 6472 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6473 } 6474 } 6475 N = usesLibraryFiles.size(); 6476 if (N > 0) { 6477 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6478 } else { 6479 pkg.usesLibraryFiles = null; 6480 } 6481 } 6482 } 6483 6484 private static boolean hasString(List<String> list, List<String> which) { 6485 if (list == null) { 6486 return false; 6487 } 6488 for (int i=list.size()-1; i>=0; i--) { 6489 for (int j=which.size()-1; j>=0; j--) { 6490 if (which.get(j).equals(list.get(i))) { 6491 return true; 6492 } 6493 } 6494 } 6495 return false; 6496 } 6497 6498 private void updateAllSharedLibrariesLPw() { 6499 for (PackageParser.Package pkg : mPackages.values()) { 6500 try { 6501 updateSharedLibrariesLPw(pkg, null); 6502 } catch (PackageManagerException e) { 6503 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6504 } 6505 } 6506 } 6507 6508 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6509 PackageParser.Package changingPkg) { 6510 ArrayList<PackageParser.Package> res = null; 6511 for (PackageParser.Package pkg : mPackages.values()) { 6512 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6513 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6514 if (res == null) { 6515 res = new ArrayList<PackageParser.Package>(); 6516 } 6517 res.add(pkg); 6518 try { 6519 updateSharedLibrariesLPw(pkg, changingPkg); 6520 } catch (PackageManagerException e) { 6521 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6522 } 6523 } 6524 } 6525 return res; 6526 } 6527 6528 /** 6529 * Derive the value of the {@code cpuAbiOverride} based on the provided 6530 * value and an optional stored value from the package settings. 6531 */ 6532 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6533 String cpuAbiOverride = null; 6534 6535 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6536 cpuAbiOverride = null; 6537 } else if (abiOverride != null) { 6538 cpuAbiOverride = abiOverride; 6539 } else if (settings != null) { 6540 cpuAbiOverride = settings.cpuAbiOverrideString; 6541 } 6542 6543 return cpuAbiOverride; 6544 } 6545 6546 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6547 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6548 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6549 try { 6550 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6551 } finally { 6552 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6553 } 6554 } 6555 6556 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6557 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6558 boolean success = false; 6559 try { 6560 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6561 currentTime, user); 6562 success = true; 6563 return res; 6564 } finally { 6565 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6566 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6567 } 6568 } 6569 } 6570 6571 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6572 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6573 final File scanFile = new File(pkg.codePath); 6574 if (pkg.applicationInfo.getCodePath() == null || 6575 pkg.applicationInfo.getResourcePath() == null) { 6576 // Bail out. The resource and code paths haven't been set. 6577 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6578 "Code and resource paths haven't been set correctly"); 6579 } 6580 6581 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6582 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6583 } else { 6584 // Only allow system apps to be flagged as core apps. 6585 pkg.coreApp = false; 6586 } 6587 6588 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6589 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6590 } 6591 6592 if (mCustomResolverComponentName != null && 6593 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6594 setUpCustomResolverActivity(pkg); 6595 } 6596 6597 if (pkg.packageName.equals("android")) { 6598 synchronized (mPackages) { 6599 if (mAndroidApplication != null) { 6600 Slog.w(TAG, "*************************************************"); 6601 Slog.w(TAG, "Core android package being redefined. Skipping."); 6602 Slog.w(TAG, " file=" + scanFile); 6603 Slog.w(TAG, "*************************************************"); 6604 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6605 "Core android package being redefined. Skipping."); 6606 } 6607 6608 // Set up information for our fall-back user intent resolution activity. 6609 mPlatformPackage = pkg; 6610 pkg.mVersionCode = mSdkVersion; 6611 mAndroidApplication = pkg.applicationInfo; 6612 6613 if (!mResolverReplaced) { 6614 mResolveActivity.applicationInfo = mAndroidApplication; 6615 mResolveActivity.name = ResolverActivity.class.getName(); 6616 mResolveActivity.packageName = mAndroidApplication.packageName; 6617 mResolveActivity.processName = "system:ui"; 6618 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6619 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6620 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6621 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6622 mResolveActivity.exported = true; 6623 mResolveActivity.enabled = true; 6624 mResolveInfo.activityInfo = mResolveActivity; 6625 mResolveInfo.priority = 0; 6626 mResolveInfo.preferredOrder = 0; 6627 mResolveInfo.match = 0; 6628 mResolveComponentName = new ComponentName( 6629 mAndroidApplication.packageName, mResolveActivity.name); 6630 } 6631 } 6632 } 6633 6634 if (DEBUG_PACKAGE_SCANNING) { 6635 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6636 Log.d(TAG, "Scanning package " + pkg.packageName); 6637 } 6638 6639 if (mPackages.containsKey(pkg.packageName) 6640 || mSharedLibraries.containsKey(pkg.packageName)) { 6641 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6642 "Application package " + pkg.packageName 6643 + " already installed. Skipping duplicate."); 6644 } 6645 6646 // If we're only installing presumed-existing packages, require that the 6647 // scanned APK is both already known and at the path previously established 6648 // for it. Previously unknown packages we pick up normally, but if we have an 6649 // a priori expectation about this package's install presence, enforce it. 6650 // With a singular exception for new system packages. When an OTA contains 6651 // a new system package, we allow the codepath to change from a system location 6652 // to the user-installed location. If we don't allow this change, any newer, 6653 // user-installed version of the application will be ignored. 6654 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6655 if (mExpectingBetter.containsKey(pkg.packageName)) { 6656 logCriticalInfo(Log.WARN, 6657 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6658 } else { 6659 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6660 if (known != null) { 6661 if (DEBUG_PACKAGE_SCANNING) { 6662 Log.d(TAG, "Examining " + pkg.codePath 6663 + " and requiring known paths " + known.codePathString 6664 + " & " + known.resourcePathString); 6665 } 6666 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6667 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6668 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6669 "Application package " + pkg.packageName 6670 + " found at " + pkg.applicationInfo.getCodePath() 6671 + " but expected at " + known.codePathString + "; ignoring."); 6672 } 6673 } 6674 } 6675 } 6676 6677 // Initialize package source and resource directories 6678 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6679 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6680 6681 SharedUserSetting suid = null; 6682 PackageSetting pkgSetting = null; 6683 6684 if (!isSystemApp(pkg)) { 6685 // Only system apps can use these features. 6686 pkg.mOriginalPackages = null; 6687 pkg.mRealPackage = null; 6688 pkg.mAdoptPermissions = null; 6689 } 6690 6691 // writer 6692 synchronized (mPackages) { 6693 if (pkg.mSharedUserId != null) { 6694 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6695 if (suid == null) { 6696 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6697 "Creating application package " + pkg.packageName 6698 + " for shared user failed"); 6699 } 6700 if (DEBUG_PACKAGE_SCANNING) { 6701 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6702 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6703 + "): packages=" + suid.packages); 6704 } 6705 } 6706 6707 // Check if we are renaming from an original package name. 6708 PackageSetting origPackage = null; 6709 String realName = null; 6710 if (pkg.mOriginalPackages != null) { 6711 // This package may need to be renamed to a previously 6712 // installed name. Let's check on that... 6713 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6714 if (pkg.mOriginalPackages.contains(renamed)) { 6715 // This package had originally been installed as the 6716 // original name, and we have already taken care of 6717 // transitioning to the new one. Just update the new 6718 // one to continue using the old name. 6719 realName = pkg.mRealPackage; 6720 if (!pkg.packageName.equals(renamed)) { 6721 // Callers into this function may have already taken 6722 // care of renaming the package; only do it here if 6723 // it is not already done. 6724 pkg.setPackageName(renamed); 6725 } 6726 6727 } else { 6728 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6729 if ((origPackage = mSettings.peekPackageLPr( 6730 pkg.mOriginalPackages.get(i))) != null) { 6731 // We do have the package already installed under its 6732 // original name... should we use it? 6733 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6734 // New package is not compatible with original. 6735 origPackage = null; 6736 continue; 6737 } else if (origPackage.sharedUser != null) { 6738 // Make sure uid is compatible between packages. 6739 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6740 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6741 + " to " + pkg.packageName + ": old uid " 6742 + origPackage.sharedUser.name 6743 + " differs from " + pkg.mSharedUserId); 6744 origPackage = null; 6745 continue; 6746 } 6747 } else { 6748 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6749 + pkg.packageName + " to old name " + origPackage.name); 6750 } 6751 break; 6752 } 6753 } 6754 } 6755 } 6756 6757 if (mTransferedPackages.contains(pkg.packageName)) { 6758 Slog.w(TAG, "Package " + pkg.packageName 6759 + " was transferred to another, but its .apk remains"); 6760 } 6761 6762 // Just create the setting, don't add it yet. For already existing packages 6763 // the PkgSetting exists already and doesn't have to be created. 6764 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6765 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6766 pkg.applicationInfo.primaryCpuAbi, 6767 pkg.applicationInfo.secondaryCpuAbi, 6768 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6769 user, false); 6770 if (pkgSetting == null) { 6771 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6772 "Creating application package " + pkg.packageName + " failed"); 6773 } 6774 6775 if (pkgSetting.origPackage != null) { 6776 // If we are first transitioning from an original package, 6777 // fix up the new package's name now. We need to do this after 6778 // looking up the package under its new name, so getPackageLP 6779 // can take care of fiddling things correctly. 6780 pkg.setPackageName(origPackage.name); 6781 6782 // File a report about this. 6783 String msg = "New package " + pkgSetting.realName 6784 + " renamed to replace old package " + pkgSetting.name; 6785 reportSettingsProblem(Log.WARN, msg); 6786 6787 // Make a note of it. 6788 mTransferedPackages.add(origPackage.name); 6789 6790 // No longer need to retain this. 6791 pkgSetting.origPackage = null; 6792 } 6793 6794 if (realName != null) { 6795 // Make a note of it. 6796 mTransferedPackages.add(pkg.packageName); 6797 } 6798 6799 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6800 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6801 } 6802 6803 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6804 // Check all shared libraries and map to their actual file path. 6805 // We only do this here for apps not on a system dir, because those 6806 // are the only ones that can fail an install due to this. We 6807 // will take care of the system apps by updating all of their 6808 // library paths after the scan is done. 6809 updateSharedLibrariesLPw(pkg, null); 6810 } 6811 6812 if (mFoundPolicyFile) { 6813 SELinuxMMAC.assignSeinfoValue(pkg); 6814 } 6815 6816 pkg.applicationInfo.uid = pkgSetting.appId; 6817 pkg.mExtras = pkgSetting; 6818 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6819 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6820 // We just determined the app is signed correctly, so bring 6821 // over the latest parsed certs. 6822 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6823 } else { 6824 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6825 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6826 "Package " + pkg.packageName + " upgrade keys do not match the " 6827 + "previously installed version"); 6828 } else { 6829 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6830 String msg = "System package " + pkg.packageName 6831 + " signature changed; retaining data."; 6832 reportSettingsProblem(Log.WARN, msg); 6833 } 6834 } 6835 } else { 6836 try { 6837 verifySignaturesLP(pkgSetting, pkg); 6838 // We just determined the app is signed correctly, so bring 6839 // over the latest parsed certs. 6840 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6841 } catch (PackageManagerException e) { 6842 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6843 throw e; 6844 } 6845 // The signature has changed, but this package is in the system 6846 // image... let's recover! 6847 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6848 // However... if this package is part of a shared user, but it 6849 // doesn't match the signature of the shared user, let's fail. 6850 // What this means is that you can't change the signatures 6851 // associated with an overall shared user, which doesn't seem all 6852 // that unreasonable. 6853 if (pkgSetting.sharedUser != null) { 6854 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6855 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6856 throw new PackageManagerException( 6857 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6858 "Signature mismatch for shared user : " 6859 + pkgSetting.sharedUser); 6860 } 6861 } 6862 // File a report about this. 6863 String msg = "System package " + pkg.packageName 6864 + " signature changed; retaining data."; 6865 reportSettingsProblem(Log.WARN, msg); 6866 } 6867 } 6868 // Verify that this new package doesn't have any content providers 6869 // that conflict with existing packages. Only do this if the 6870 // package isn't already installed, since we don't want to break 6871 // things that are installed. 6872 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6873 final int N = pkg.providers.size(); 6874 int i; 6875 for (i=0; i<N; i++) { 6876 PackageParser.Provider p = pkg.providers.get(i); 6877 if (p.info.authority != null) { 6878 String names[] = p.info.authority.split(";"); 6879 for (int j = 0; j < names.length; j++) { 6880 if (mProvidersByAuthority.containsKey(names[j])) { 6881 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6882 final String otherPackageName = 6883 ((other != null && other.getComponentName() != null) ? 6884 other.getComponentName().getPackageName() : "?"); 6885 throw new PackageManagerException( 6886 INSTALL_FAILED_CONFLICTING_PROVIDER, 6887 "Can't install because provider name " + names[j] 6888 + " (in package " + pkg.applicationInfo.packageName 6889 + ") is already used by " + otherPackageName); 6890 } 6891 } 6892 } 6893 } 6894 } 6895 6896 if (pkg.mAdoptPermissions != null) { 6897 // This package wants to adopt ownership of permissions from 6898 // another package. 6899 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6900 final String origName = pkg.mAdoptPermissions.get(i); 6901 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6902 if (orig != null) { 6903 if (verifyPackageUpdateLPr(orig, pkg)) { 6904 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6905 + pkg.packageName); 6906 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6907 } 6908 } 6909 } 6910 } 6911 } 6912 6913 final String pkgName = pkg.packageName; 6914 6915 final long scanFileTime = scanFile.lastModified(); 6916 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6917 pkg.applicationInfo.processName = fixProcessName( 6918 pkg.applicationInfo.packageName, 6919 pkg.applicationInfo.processName, 6920 pkg.applicationInfo.uid); 6921 6922 File dataPath; 6923 if (mPlatformPackage == pkg) { 6924 // The system package is special. 6925 dataPath = new File(Environment.getDataDirectory(), "system"); 6926 6927 pkg.applicationInfo.dataDir = dataPath.getPath(); 6928 6929 } else { 6930 // This is a normal package, need to make its data directory. 6931 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6932 UserHandle.USER_SYSTEM, pkg.packageName); 6933 6934 boolean uidError = false; 6935 if (dataPath.exists()) { 6936 int currentUid = 0; 6937 try { 6938 StructStat stat = Os.stat(dataPath.getPath()); 6939 currentUid = stat.st_uid; 6940 } catch (ErrnoException e) { 6941 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6942 } 6943 6944 // If we have mismatched owners for the data path, we have a problem. 6945 if (currentUid != pkg.applicationInfo.uid) { 6946 boolean recovered = false; 6947 if (currentUid == 0) { 6948 // The directory somehow became owned by root. Wow. 6949 // This is probably because the system was stopped while 6950 // installd was in the middle of messing with its libs 6951 // directory. Ask installd to fix that. 6952 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6953 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6954 if (ret >= 0) { 6955 recovered = true; 6956 String msg = "Package " + pkg.packageName 6957 + " unexpectedly changed to uid 0; recovered to " + 6958 + pkg.applicationInfo.uid; 6959 reportSettingsProblem(Log.WARN, msg); 6960 } 6961 } 6962 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6963 || (scanFlags&SCAN_BOOTING) != 0)) { 6964 // If this is a system app, we can at least delete its 6965 // current data so the application will still work. 6966 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6967 if (ret >= 0) { 6968 // TODO: Kill the processes first 6969 // Old data gone! 6970 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6971 ? "System package " : "Third party package "; 6972 String msg = prefix + pkg.packageName 6973 + " has changed from uid: " 6974 + currentUid + " to " 6975 + pkg.applicationInfo.uid + "; old data erased"; 6976 reportSettingsProblem(Log.WARN, msg); 6977 recovered = true; 6978 6979 // And now re-install the app. 6980 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6981 pkg.applicationInfo.seinfo); 6982 if (ret == -1) { 6983 // Ack should not happen! 6984 msg = prefix + pkg.packageName 6985 + " could not have data directory re-created after delete."; 6986 reportSettingsProblem(Log.WARN, msg); 6987 throw new PackageManagerException( 6988 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6989 } 6990 } 6991 if (!recovered) { 6992 mHasSystemUidErrors = true; 6993 } 6994 } else if (!recovered) { 6995 // If we allow this install to proceed, we will be broken. 6996 // Abort, abort! 6997 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6998 "scanPackageLI"); 6999 } 7000 if (!recovered) { 7001 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7002 + pkg.applicationInfo.uid + "/fs_" 7003 + currentUid; 7004 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7005 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7006 String msg = "Package " + pkg.packageName 7007 + " has mismatched uid: " 7008 + currentUid + " on disk, " 7009 + pkg.applicationInfo.uid + " in settings"; 7010 // writer 7011 synchronized (mPackages) { 7012 mSettings.mReadMessages.append(msg); 7013 mSettings.mReadMessages.append('\n'); 7014 uidError = true; 7015 if (!pkgSetting.uidError) { 7016 reportSettingsProblem(Log.ERROR, msg); 7017 } 7018 } 7019 } 7020 } 7021 pkg.applicationInfo.dataDir = dataPath.getPath(); 7022 if (mShouldRestoreconData) { 7023 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7024 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7025 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7026 } 7027 } else { 7028 if (DEBUG_PACKAGE_SCANNING) { 7029 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7030 Log.v(TAG, "Want this data dir: " + dataPath); 7031 } 7032 //invoke installer to do the actual installation 7033 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7034 pkg.applicationInfo.seinfo); 7035 if (ret < 0) { 7036 // Error from installer 7037 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7038 "Unable to create data dirs [errorCode=" + ret + "]"); 7039 } 7040 7041 if (dataPath.exists()) { 7042 pkg.applicationInfo.dataDir = dataPath.getPath(); 7043 } else { 7044 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7045 pkg.applicationInfo.dataDir = null; 7046 } 7047 } 7048 7049 pkgSetting.uidError = uidError; 7050 } 7051 7052 final String path = scanFile.getPath(); 7053 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7054 7055 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7056 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7057 7058 // Some system apps still use directory structure for native libraries 7059 // in which case we might end up not detecting abi solely based on apk 7060 // structure. Try to detect abi based on directory structure. 7061 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7062 pkg.applicationInfo.primaryCpuAbi == null) { 7063 setBundledAppAbisAndRoots(pkg, pkgSetting); 7064 setNativeLibraryPaths(pkg); 7065 } 7066 7067 } else { 7068 if ((scanFlags & SCAN_MOVE) != 0) { 7069 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7070 // but we already have this packages package info in the PackageSetting. We just 7071 // use that and derive the native library path based on the new codepath. 7072 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7073 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7074 } 7075 7076 // Set native library paths again. For moves, the path will be updated based on the 7077 // ABIs we've determined above. For non-moves, the path will be updated based on the 7078 // ABIs we determined during compilation, but the path will depend on the final 7079 // package path (after the rename away from the stage path). 7080 setNativeLibraryPaths(pkg); 7081 } 7082 7083 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7084 final int[] userIds = sUserManager.getUserIds(); 7085 synchronized (mInstallLock) { 7086 // Make sure all user data directories are ready to roll; we're okay 7087 // if they already exist 7088 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7089 for (int userId : userIds) { 7090 if (userId != UserHandle.USER_SYSTEM) { 7091 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7092 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7093 pkg.applicationInfo.seinfo); 7094 } 7095 } 7096 } 7097 7098 // Create a native library symlink only if we have native libraries 7099 // and if the native libraries are 32 bit libraries. We do not provide 7100 // this symlink for 64 bit libraries. 7101 if (pkg.applicationInfo.primaryCpuAbi != null && 7102 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7103 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7104 try { 7105 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7106 for (int userId : userIds) { 7107 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7108 nativeLibPath, userId) < 0) { 7109 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7110 "Failed linking native library dir (user=" + userId + ")"); 7111 } 7112 } 7113 } finally { 7114 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7115 } 7116 } 7117 } 7118 7119 // This is a special case for the "system" package, where the ABI is 7120 // dictated by the zygote configuration (and init.rc). We should keep track 7121 // of this ABI so that we can deal with "normal" applications that run under 7122 // the same UID correctly. 7123 if (mPlatformPackage == pkg) { 7124 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7125 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7126 } 7127 7128 // If there's a mismatch between the abi-override in the package setting 7129 // and the abiOverride specified for the install. Warn about this because we 7130 // would've already compiled the app without taking the package setting into 7131 // account. 7132 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7133 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7134 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7135 " for package: " + pkg.packageName); 7136 } 7137 } 7138 7139 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7140 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7141 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7142 7143 // Copy the derived override back to the parsed package, so that we can 7144 // update the package settings accordingly. 7145 pkg.cpuAbiOverride = cpuAbiOverride; 7146 7147 if (DEBUG_ABI_SELECTION) { 7148 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7149 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7150 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7151 } 7152 7153 // Push the derived path down into PackageSettings so we know what to 7154 // clean up at uninstall time. 7155 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7156 7157 if (DEBUG_ABI_SELECTION) { 7158 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7159 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7160 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7161 } 7162 7163 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7164 // We don't do this here during boot because we can do it all 7165 // at once after scanning all existing packages. 7166 // 7167 // We also do this *before* we perform dexopt on this package, so that 7168 // we can avoid redundant dexopts, and also to make sure we've got the 7169 // code and package path correct. 7170 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7171 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7172 } 7173 7174 if ((scanFlags & SCAN_NO_DEX) == 0) { 7175 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7176 7177 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7178 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7179 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7180 7181 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7182 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7183 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7184 } 7185 } 7186 if (mFactoryTest && pkg.requestedPermissions.contains( 7187 android.Manifest.permission.FACTORY_TEST)) { 7188 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7189 } 7190 7191 ArrayList<PackageParser.Package> clientLibPkgs = null; 7192 7193 // writer 7194 synchronized (mPackages) { 7195 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7196 // Only system apps can add new shared libraries. 7197 if (pkg.libraryNames != null) { 7198 for (int i=0; i<pkg.libraryNames.size(); i++) { 7199 String name = pkg.libraryNames.get(i); 7200 boolean allowed = false; 7201 if (pkg.isUpdatedSystemApp()) { 7202 // New library entries can only be added through the 7203 // system image. This is important to get rid of a lot 7204 // of nasty edge cases: for example if we allowed a non- 7205 // system update of the app to add a library, then uninstalling 7206 // the update would make the library go away, and assumptions 7207 // we made such as through app install filtering would now 7208 // have allowed apps on the device which aren't compatible 7209 // with it. Better to just have the restriction here, be 7210 // conservative, and create many fewer cases that can negatively 7211 // impact the user experience. 7212 final PackageSetting sysPs = mSettings 7213 .getDisabledSystemPkgLPr(pkg.packageName); 7214 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7215 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7216 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7217 allowed = true; 7218 break; 7219 } 7220 } 7221 } 7222 } else { 7223 allowed = true; 7224 } 7225 if (allowed) { 7226 if (!mSharedLibraries.containsKey(name)) { 7227 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7228 } else if (!name.equals(pkg.packageName)) { 7229 Slog.w(TAG, "Package " + pkg.packageName + " library " 7230 + name + " already exists; skipping"); 7231 } 7232 } else { 7233 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7234 + name + " that is not declared on system image; skipping"); 7235 } 7236 } 7237 if ((scanFlags&SCAN_BOOTING) == 0) { 7238 // If we are not booting, we need to update any applications 7239 // that are clients of our shared library. If we are booting, 7240 // this will all be done once the scan is complete. 7241 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7242 } 7243 } 7244 } 7245 } 7246 7247 // We also need to dexopt any apps that are dependent on this library. Note that 7248 // if these fail, we should abort the install since installing the library will 7249 // result in some apps being broken. 7250 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7251 try { 7252 if (clientLibPkgs != null) { 7253 if ((scanFlags & SCAN_NO_DEX) == 0) { 7254 for (int i = 0; i < clientLibPkgs.size(); i++) { 7255 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7256 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7257 null /* instruction sets */, forceDex, 7258 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7259 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7260 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7261 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7262 "scanPackageLI failed to dexopt clientLibPkgs"); 7263 } 7264 } 7265 } 7266 } 7267 } finally { 7268 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7269 } 7270 7271 // Request the ActivityManager to kill the process(only for existing packages) 7272 // so that we do not end up in a confused state while the user is still using the older 7273 // version of the application while the new one gets installed. 7274 if ((scanFlags & SCAN_REPLACING) != 0) { 7275 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7276 7277 killApplication(pkg.applicationInfo.packageName, 7278 pkg.applicationInfo.uid, "replace pkg"); 7279 7280 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7281 } 7282 7283 // Also need to kill any apps that are dependent on the library. 7284 if (clientLibPkgs != null) { 7285 for (int i=0; i<clientLibPkgs.size(); i++) { 7286 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7287 killApplication(clientPkg.applicationInfo.packageName, 7288 clientPkg.applicationInfo.uid, "update lib"); 7289 } 7290 } 7291 7292 // Make sure we're not adding any bogus keyset info 7293 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7294 ksms.assertScannedPackageValid(pkg); 7295 7296 // writer 7297 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7298 7299 boolean createIdmapFailed = false; 7300 synchronized (mPackages) { 7301 // We don't expect installation to fail beyond this point 7302 7303 // Add the new setting to mSettings 7304 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7305 // Add the new setting to mPackages 7306 mPackages.put(pkg.applicationInfo.packageName, pkg); 7307 // Make sure we don't accidentally delete its data. 7308 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7309 while (iter.hasNext()) { 7310 PackageCleanItem item = iter.next(); 7311 if (pkgName.equals(item.packageName)) { 7312 iter.remove(); 7313 } 7314 } 7315 7316 // Take care of first install / last update times. 7317 if (currentTime != 0) { 7318 if (pkgSetting.firstInstallTime == 0) { 7319 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7320 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7321 pkgSetting.lastUpdateTime = currentTime; 7322 } 7323 } else if (pkgSetting.firstInstallTime == 0) { 7324 // We need *something*. Take time time stamp of the file. 7325 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7326 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7327 if (scanFileTime != pkgSetting.timeStamp) { 7328 // A package on the system image has changed; consider this 7329 // to be an update. 7330 pkgSetting.lastUpdateTime = scanFileTime; 7331 } 7332 } 7333 7334 // Add the package's KeySets to the global KeySetManagerService 7335 ksms.addScannedPackageLPw(pkg); 7336 7337 int N = pkg.providers.size(); 7338 StringBuilder r = null; 7339 int i; 7340 for (i=0; i<N; i++) { 7341 PackageParser.Provider p = pkg.providers.get(i); 7342 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7343 p.info.processName, pkg.applicationInfo.uid); 7344 mProviders.addProvider(p); 7345 p.syncable = p.info.isSyncable; 7346 if (p.info.authority != null) { 7347 String names[] = p.info.authority.split(";"); 7348 p.info.authority = null; 7349 for (int j = 0; j < names.length; j++) { 7350 if (j == 1 && p.syncable) { 7351 // We only want the first authority for a provider to possibly be 7352 // syncable, so if we already added this provider using a different 7353 // authority clear the syncable flag. We copy the provider before 7354 // changing it because the mProviders object contains a reference 7355 // to a provider that we don't want to change. 7356 // Only do this for the second authority since the resulting provider 7357 // object can be the same for all future authorities for this provider. 7358 p = new PackageParser.Provider(p); 7359 p.syncable = false; 7360 } 7361 if (!mProvidersByAuthority.containsKey(names[j])) { 7362 mProvidersByAuthority.put(names[j], p); 7363 if (p.info.authority == null) { 7364 p.info.authority = names[j]; 7365 } else { 7366 p.info.authority = p.info.authority + ";" + names[j]; 7367 } 7368 if (DEBUG_PACKAGE_SCANNING) { 7369 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7370 Log.d(TAG, "Registered content provider: " + names[j] 7371 + ", className = " + p.info.name + ", isSyncable = " 7372 + p.info.isSyncable); 7373 } 7374 } else { 7375 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7376 Slog.w(TAG, "Skipping provider name " + names[j] + 7377 " (in package " + pkg.applicationInfo.packageName + 7378 "): name already used by " 7379 + ((other != null && other.getComponentName() != null) 7380 ? other.getComponentName().getPackageName() : "?")); 7381 } 7382 } 7383 } 7384 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7385 if (r == null) { 7386 r = new StringBuilder(256); 7387 } else { 7388 r.append(' '); 7389 } 7390 r.append(p.info.name); 7391 } 7392 } 7393 if (r != null) { 7394 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7395 } 7396 7397 N = pkg.services.size(); 7398 r = null; 7399 for (i=0; i<N; i++) { 7400 PackageParser.Service s = pkg.services.get(i); 7401 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7402 s.info.processName, pkg.applicationInfo.uid); 7403 mServices.addService(s); 7404 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7405 if (r == null) { 7406 r = new StringBuilder(256); 7407 } else { 7408 r.append(' '); 7409 } 7410 r.append(s.info.name); 7411 } 7412 } 7413 if (r != null) { 7414 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7415 } 7416 7417 N = pkg.receivers.size(); 7418 r = null; 7419 for (i=0; i<N; i++) { 7420 PackageParser.Activity a = pkg.receivers.get(i); 7421 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7422 a.info.processName, pkg.applicationInfo.uid); 7423 mReceivers.addActivity(a, "receiver"); 7424 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7425 if (r == null) { 7426 r = new StringBuilder(256); 7427 } else { 7428 r.append(' '); 7429 } 7430 r.append(a.info.name); 7431 } 7432 } 7433 if (r != null) { 7434 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7435 } 7436 7437 N = pkg.activities.size(); 7438 r = null; 7439 for (i=0; i<N; i++) { 7440 PackageParser.Activity a = pkg.activities.get(i); 7441 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7442 a.info.processName, pkg.applicationInfo.uid); 7443 mActivities.addActivity(a, "activity"); 7444 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7445 if (r == null) { 7446 r = new StringBuilder(256); 7447 } else { 7448 r.append(' '); 7449 } 7450 r.append(a.info.name); 7451 } 7452 } 7453 if (r != null) { 7454 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7455 } 7456 7457 N = pkg.permissionGroups.size(); 7458 r = null; 7459 for (i=0; i<N; i++) { 7460 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7461 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7462 if (cur == null) { 7463 mPermissionGroups.put(pg.info.name, pg); 7464 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7465 if (r == null) { 7466 r = new StringBuilder(256); 7467 } else { 7468 r.append(' '); 7469 } 7470 r.append(pg.info.name); 7471 } 7472 } else { 7473 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7474 + pg.info.packageName + " ignored: original from " 7475 + cur.info.packageName); 7476 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7477 if (r == null) { 7478 r = new StringBuilder(256); 7479 } else { 7480 r.append(' '); 7481 } 7482 r.append("DUP:"); 7483 r.append(pg.info.name); 7484 } 7485 } 7486 } 7487 if (r != null) { 7488 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7489 } 7490 7491 N = pkg.permissions.size(); 7492 r = null; 7493 for (i=0; i<N; i++) { 7494 PackageParser.Permission p = pkg.permissions.get(i); 7495 7496 // Assume by default that we did not install this permission into the system. 7497 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7498 7499 // Now that permission groups have a special meaning, we ignore permission 7500 // groups for legacy apps to prevent unexpected behavior. In particular, 7501 // permissions for one app being granted to someone just becuase they happen 7502 // to be in a group defined by another app (before this had no implications). 7503 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7504 p.group = mPermissionGroups.get(p.info.group); 7505 // Warn for a permission in an unknown group. 7506 if (p.info.group != null && p.group == null) { 7507 Slog.w(TAG, "Permission " + p.info.name + " from package " 7508 + p.info.packageName + " in an unknown group " + p.info.group); 7509 } 7510 } 7511 7512 ArrayMap<String, BasePermission> permissionMap = 7513 p.tree ? mSettings.mPermissionTrees 7514 : mSettings.mPermissions; 7515 BasePermission bp = permissionMap.get(p.info.name); 7516 7517 // Allow system apps to redefine non-system permissions 7518 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7519 final boolean currentOwnerIsSystem = (bp.perm != null 7520 && isSystemApp(bp.perm.owner)); 7521 if (isSystemApp(p.owner)) { 7522 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7523 // It's a built-in permission and no owner, take ownership now 7524 bp.packageSetting = pkgSetting; 7525 bp.perm = p; 7526 bp.uid = pkg.applicationInfo.uid; 7527 bp.sourcePackage = p.info.packageName; 7528 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7529 } else if (!currentOwnerIsSystem) { 7530 String msg = "New decl " + p.owner + " of permission " 7531 + p.info.name + " is system; overriding " + bp.sourcePackage; 7532 reportSettingsProblem(Log.WARN, msg); 7533 bp = null; 7534 } 7535 } 7536 } 7537 7538 if (bp == null) { 7539 bp = new BasePermission(p.info.name, p.info.packageName, 7540 BasePermission.TYPE_NORMAL); 7541 permissionMap.put(p.info.name, bp); 7542 } 7543 7544 if (bp.perm == null) { 7545 if (bp.sourcePackage == null 7546 || bp.sourcePackage.equals(p.info.packageName)) { 7547 BasePermission tree = findPermissionTreeLP(p.info.name); 7548 if (tree == null 7549 || tree.sourcePackage.equals(p.info.packageName)) { 7550 bp.packageSetting = pkgSetting; 7551 bp.perm = p; 7552 bp.uid = pkg.applicationInfo.uid; 7553 bp.sourcePackage = p.info.packageName; 7554 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7555 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7556 if (r == null) { 7557 r = new StringBuilder(256); 7558 } else { 7559 r.append(' '); 7560 } 7561 r.append(p.info.name); 7562 } 7563 } else { 7564 Slog.w(TAG, "Permission " + p.info.name + " from package " 7565 + p.info.packageName + " ignored: base tree " 7566 + tree.name + " is from package " 7567 + tree.sourcePackage); 7568 } 7569 } else { 7570 Slog.w(TAG, "Permission " + p.info.name + " from package " 7571 + p.info.packageName + " ignored: original from " 7572 + bp.sourcePackage); 7573 } 7574 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7575 if (r == null) { 7576 r = new StringBuilder(256); 7577 } else { 7578 r.append(' '); 7579 } 7580 r.append("DUP:"); 7581 r.append(p.info.name); 7582 } 7583 if (bp.perm == p) { 7584 bp.protectionLevel = p.info.protectionLevel; 7585 } 7586 } 7587 7588 if (r != null) { 7589 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7590 } 7591 7592 N = pkg.instrumentation.size(); 7593 r = null; 7594 for (i=0; i<N; i++) { 7595 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7596 a.info.packageName = pkg.applicationInfo.packageName; 7597 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7598 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7599 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7600 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7601 a.info.dataDir = pkg.applicationInfo.dataDir; 7602 7603 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7604 // need other information about the application, like the ABI and what not ? 7605 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7606 mInstrumentation.put(a.getComponentName(), a); 7607 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7608 if (r == null) { 7609 r = new StringBuilder(256); 7610 } else { 7611 r.append(' '); 7612 } 7613 r.append(a.info.name); 7614 } 7615 } 7616 if (r != null) { 7617 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7618 } 7619 7620 if (pkg.protectedBroadcasts != null) { 7621 N = pkg.protectedBroadcasts.size(); 7622 for (i=0; i<N; i++) { 7623 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7624 } 7625 } 7626 7627 pkgSetting.setTimeStamp(scanFileTime); 7628 7629 // Create idmap files for pairs of (packages, overlay packages). 7630 // Note: "android", ie framework-res.apk, is handled by native layers. 7631 if (pkg.mOverlayTarget != null) { 7632 // This is an overlay package. 7633 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7634 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7635 mOverlays.put(pkg.mOverlayTarget, 7636 new ArrayMap<String, PackageParser.Package>()); 7637 } 7638 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7639 map.put(pkg.packageName, pkg); 7640 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7641 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7642 createIdmapFailed = true; 7643 } 7644 } 7645 } else if (mOverlays.containsKey(pkg.packageName) && 7646 !pkg.packageName.equals("android")) { 7647 // This is a regular package, with one or more known overlay packages. 7648 createIdmapsForPackageLI(pkg); 7649 } 7650 } 7651 7652 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7653 7654 if (createIdmapFailed) { 7655 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7656 "scanPackageLI failed to createIdmap"); 7657 } 7658 return pkg; 7659 } 7660 7661 /** 7662 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7663 * is derived purely on the basis of the contents of {@code scanFile} and 7664 * {@code cpuAbiOverride}. 7665 * 7666 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7667 */ 7668 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7669 String cpuAbiOverride, boolean extractLibs) 7670 throws PackageManagerException { 7671 // TODO: We can probably be smarter about this stuff. For installed apps, 7672 // we can calculate this information at install time once and for all. For 7673 // system apps, we can probably assume that this information doesn't change 7674 // after the first boot scan. As things stand, we do lots of unnecessary work. 7675 7676 // Give ourselves some initial paths; we'll come back for another 7677 // pass once we've determined ABI below. 7678 setNativeLibraryPaths(pkg); 7679 7680 // We would never need to extract libs for forward-locked and external packages, 7681 // since the container service will do it for us. We shouldn't attempt to 7682 // extract libs from system app when it was not updated. 7683 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7684 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7685 extractLibs = false; 7686 } 7687 7688 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7689 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7690 7691 NativeLibraryHelper.Handle handle = null; 7692 try { 7693 handle = NativeLibraryHelper.Handle.create(pkg); 7694 // TODO(multiArch): This can be null for apps that didn't go through the 7695 // usual installation process. We can calculate it again, like we 7696 // do during install time. 7697 // 7698 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7699 // unnecessary. 7700 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7701 7702 // Null out the abis so that they can be recalculated. 7703 pkg.applicationInfo.primaryCpuAbi = null; 7704 pkg.applicationInfo.secondaryCpuAbi = null; 7705 if (isMultiArch(pkg.applicationInfo)) { 7706 // Warn if we've set an abiOverride for multi-lib packages.. 7707 // By definition, we need to copy both 32 and 64 bit libraries for 7708 // such packages. 7709 if (pkg.cpuAbiOverride != null 7710 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7711 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7712 } 7713 7714 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7715 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7716 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7717 if (extractLibs) { 7718 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7719 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7720 useIsaSpecificSubdirs); 7721 } else { 7722 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7723 } 7724 } 7725 7726 maybeThrowExceptionForMultiArchCopy( 7727 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7728 7729 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7730 if (extractLibs) { 7731 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7732 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7733 useIsaSpecificSubdirs); 7734 } else { 7735 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7736 } 7737 } 7738 7739 maybeThrowExceptionForMultiArchCopy( 7740 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7741 7742 if (abi64 >= 0) { 7743 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7744 } 7745 7746 if (abi32 >= 0) { 7747 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7748 if (abi64 >= 0) { 7749 pkg.applicationInfo.secondaryCpuAbi = abi; 7750 } else { 7751 pkg.applicationInfo.primaryCpuAbi = abi; 7752 } 7753 } 7754 } else { 7755 String[] abiList = (cpuAbiOverride != null) ? 7756 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7757 7758 // Enable gross and lame hacks for apps that are built with old 7759 // SDK tools. We must scan their APKs for renderscript bitcode and 7760 // not launch them if it's present. Don't bother checking on devices 7761 // that don't have 64 bit support. 7762 boolean needsRenderScriptOverride = false; 7763 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7764 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7765 abiList = Build.SUPPORTED_32_BIT_ABIS; 7766 needsRenderScriptOverride = true; 7767 } 7768 7769 final int copyRet; 7770 if (extractLibs) { 7771 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7772 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7773 } else { 7774 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7775 } 7776 7777 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7778 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7779 "Error unpackaging native libs for app, errorCode=" + copyRet); 7780 } 7781 7782 if (copyRet >= 0) { 7783 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7784 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7785 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7786 } else if (needsRenderScriptOverride) { 7787 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7788 } 7789 } 7790 } catch (IOException ioe) { 7791 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7792 } finally { 7793 IoUtils.closeQuietly(handle); 7794 } 7795 7796 // Now that we've calculated the ABIs and determined if it's an internal app, 7797 // we will go ahead and populate the nativeLibraryPath. 7798 setNativeLibraryPaths(pkg); 7799 } 7800 7801 /** 7802 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7803 * i.e, so that all packages can be run inside a single process if required. 7804 * 7805 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7806 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7807 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7808 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7809 * updating a package that belongs to a shared user. 7810 * 7811 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7812 * adds unnecessary complexity. 7813 */ 7814 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7815 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7816 boolean bootComplete) { 7817 String requiredInstructionSet = null; 7818 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7819 requiredInstructionSet = VMRuntime.getInstructionSet( 7820 scannedPackage.applicationInfo.primaryCpuAbi); 7821 } 7822 7823 PackageSetting requirer = null; 7824 for (PackageSetting ps : packagesForUser) { 7825 // If packagesForUser contains scannedPackage, we skip it. This will happen 7826 // when scannedPackage is an update of an existing package. Without this check, 7827 // we will never be able to change the ABI of any package belonging to a shared 7828 // user, even if it's compatible with other packages. 7829 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7830 if (ps.primaryCpuAbiString == null) { 7831 continue; 7832 } 7833 7834 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7835 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7836 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7837 // this but there's not much we can do. 7838 String errorMessage = "Instruction set mismatch, " 7839 + ((requirer == null) ? "[caller]" : requirer) 7840 + " requires " + requiredInstructionSet + " whereas " + ps 7841 + " requires " + instructionSet; 7842 Slog.w(TAG, errorMessage); 7843 } 7844 7845 if (requiredInstructionSet == null) { 7846 requiredInstructionSet = instructionSet; 7847 requirer = ps; 7848 } 7849 } 7850 } 7851 7852 if (requiredInstructionSet != null) { 7853 String adjustedAbi; 7854 if (requirer != null) { 7855 // requirer != null implies that either scannedPackage was null or that scannedPackage 7856 // did not require an ABI, in which case we have to adjust scannedPackage to match 7857 // the ABI of the set (which is the same as requirer's ABI) 7858 adjustedAbi = requirer.primaryCpuAbiString; 7859 if (scannedPackage != null) { 7860 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7861 } 7862 } else { 7863 // requirer == null implies that we're updating all ABIs in the set to 7864 // match scannedPackage. 7865 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7866 } 7867 7868 for (PackageSetting ps : packagesForUser) { 7869 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7870 if (ps.primaryCpuAbiString != null) { 7871 continue; 7872 } 7873 7874 ps.primaryCpuAbiString = adjustedAbi; 7875 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7876 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7877 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7878 7879 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7880 7881 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7882 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7883 bootComplete, false /*useJit*/); 7884 7885 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7886 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7887 ps.primaryCpuAbiString = null; 7888 ps.pkg.applicationInfo.primaryCpuAbi = null; 7889 return; 7890 } else { 7891 mInstaller.rmdex(ps.codePathString, 7892 getDexCodeInstructionSet(getPreferredInstructionSet())); 7893 } 7894 } 7895 } 7896 } 7897 } 7898 } 7899 7900 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7901 synchronized (mPackages) { 7902 mResolverReplaced = true; 7903 // Set up information for custom user intent resolution activity. 7904 mResolveActivity.applicationInfo = pkg.applicationInfo; 7905 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7906 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7907 mResolveActivity.processName = pkg.applicationInfo.packageName; 7908 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7909 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7910 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7911 mResolveActivity.theme = 0; 7912 mResolveActivity.exported = true; 7913 mResolveActivity.enabled = true; 7914 mResolveInfo.activityInfo = mResolveActivity; 7915 mResolveInfo.priority = 0; 7916 mResolveInfo.preferredOrder = 0; 7917 mResolveInfo.match = 0; 7918 mResolveComponentName = mCustomResolverComponentName; 7919 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7920 mResolveComponentName); 7921 } 7922 } 7923 7924 private static String calculateBundledApkRoot(final String codePathString) { 7925 final File codePath = new File(codePathString); 7926 final File codeRoot; 7927 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7928 codeRoot = Environment.getRootDirectory(); 7929 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7930 codeRoot = Environment.getOemDirectory(); 7931 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7932 codeRoot = Environment.getVendorDirectory(); 7933 } else { 7934 // Unrecognized code path; take its top real segment as the apk root: 7935 // e.g. /something/app/blah.apk => /something 7936 try { 7937 File f = codePath.getCanonicalFile(); 7938 File parent = f.getParentFile(); // non-null because codePath is a file 7939 File tmp; 7940 while ((tmp = parent.getParentFile()) != null) { 7941 f = parent; 7942 parent = tmp; 7943 } 7944 codeRoot = f; 7945 Slog.w(TAG, "Unrecognized code path " 7946 + codePath + " - using " + codeRoot); 7947 } catch (IOException e) { 7948 // Can't canonicalize the code path -- shenanigans? 7949 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7950 return Environment.getRootDirectory().getPath(); 7951 } 7952 } 7953 return codeRoot.getPath(); 7954 } 7955 7956 /** 7957 * Derive and set the location of native libraries for the given package, 7958 * which varies depending on where and how the package was installed. 7959 */ 7960 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7961 final ApplicationInfo info = pkg.applicationInfo; 7962 final String codePath = pkg.codePath; 7963 final File codeFile = new File(codePath); 7964 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7965 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7966 7967 info.nativeLibraryRootDir = null; 7968 info.nativeLibraryRootRequiresIsa = false; 7969 info.nativeLibraryDir = null; 7970 info.secondaryNativeLibraryDir = null; 7971 7972 if (isApkFile(codeFile)) { 7973 // Monolithic install 7974 if (bundledApp) { 7975 // If "/system/lib64/apkname" exists, assume that is the per-package 7976 // native library directory to use; otherwise use "/system/lib/apkname". 7977 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7978 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7979 getPrimaryInstructionSet(info)); 7980 7981 // This is a bundled system app so choose the path based on the ABI. 7982 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7983 // is just the default path. 7984 final String apkName = deriveCodePathName(codePath); 7985 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7986 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7987 apkName).getAbsolutePath(); 7988 7989 if (info.secondaryCpuAbi != null) { 7990 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7991 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7992 secondaryLibDir, apkName).getAbsolutePath(); 7993 } 7994 } else if (asecApp) { 7995 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7996 .getAbsolutePath(); 7997 } else { 7998 final String apkName = deriveCodePathName(codePath); 7999 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8000 .getAbsolutePath(); 8001 } 8002 8003 info.nativeLibraryRootRequiresIsa = false; 8004 info.nativeLibraryDir = info.nativeLibraryRootDir; 8005 } else { 8006 // Cluster install 8007 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8008 info.nativeLibraryRootRequiresIsa = true; 8009 8010 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8011 getPrimaryInstructionSet(info)).getAbsolutePath(); 8012 8013 if (info.secondaryCpuAbi != null) { 8014 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8015 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8016 } 8017 } 8018 } 8019 8020 /** 8021 * Calculate the abis and roots for a bundled app. These can uniquely 8022 * be determined from the contents of the system partition, i.e whether 8023 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8024 * of this information, and instead assume that the system was built 8025 * sensibly. 8026 */ 8027 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8028 PackageSetting pkgSetting) { 8029 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8030 8031 // If "/system/lib64/apkname" exists, assume that is the per-package 8032 // native library directory to use; otherwise use "/system/lib/apkname". 8033 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8034 setBundledAppAbi(pkg, apkRoot, apkName); 8035 // pkgSetting might be null during rescan following uninstall of updates 8036 // to a bundled app, so accommodate that possibility. The settings in 8037 // that case will be established later from the parsed package. 8038 // 8039 // If the settings aren't null, sync them up with what we've just derived. 8040 // note that apkRoot isn't stored in the package settings. 8041 if (pkgSetting != null) { 8042 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8043 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8044 } 8045 } 8046 8047 /** 8048 * Deduces the ABI of a bundled app and sets the relevant fields on the 8049 * parsed pkg object. 8050 * 8051 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8052 * under which system libraries are installed. 8053 * @param apkName the name of the installed package. 8054 */ 8055 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8056 final File codeFile = new File(pkg.codePath); 8057 8058 final boolean has64BitLibs; 8059 final boolean has32BitLibs; 8060 if (isApkFile(codeFile)) { 8061 // Monolithic install 8062 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8063 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8064 } else { 8065 // Cluster install 8066 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8067 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8068 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8069 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8070 has64BitLibs = (new File(rootDir, isa)).exists(); 8071 } else { 8072 has64BitLibs = false; 8073 } 8074 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8075 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8076 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8077 has32BitLibs = (new File(rootDir, isa)).exists(); 8078 } else { 8079 has32BitLibs = false; 8080 } 8081 } 8082 8083 if (has64BitLibs && !has32BitLibs) { 8084 // The package has 64 bit libs, but not 32 bit libs. Its primary 8085 // ABI should be 64 bit. We can safely assume here that the bundled 8086 // native libraries correspond to the most preferred ABI in the list. 8087 8088 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8089 pkg.applicationInfo.secondaryCpuAbi = null; 8090 } else if (has32BitLibs && !has64BitLibs) { 8091 // The package has 32 bit libs but not 64 bit libs. Its primary 8092 // ABI should be 32 bit. 8093 8094 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8095 pkg.applicationInfo.secondaryCpuAbi = null; 8096 } else if (has32BitLibs && has64BitLibs) { 8097 // The application has both 64 and 32 bit bundled libraries. We check 8098 // here that the app declares multiArch support, and warn if it doesn't. 8099 // 8100 // We will be lenient here and record both ABIs. The primary will be the 8101 // ABI that's higher on the list, i.e, a device that's configured to prefer 8102 // 64 bit apps will see a 64 bit primary ABI, 8103 8104 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8105 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8106 } 8107 8108 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8109 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8110 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8111 } else { 8112 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8113 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8114 } 8115 } else { 8116 pkg.applicationInfo.primaryCpuAbi = null; 8117 pkg.applicationInfo.secondaryCpuAbi = null; 8118 } 8119 } 8120 8121 private void killApplication(String pkgName, int appId, String reason) { 8122 // Request the ActivityManager to kill the process(only for existing packages) 8123 // so that we do not end up in a confused state while the user is still using the older 8124 // version of the application while the new one gets installed. 8125 IActivityManager am = ActivityManagerNative.getDefault(); 8126 if (am != null) { 8127 try { 8128 am.killApplicationWithAppId(pkgName, appId, reason); 8129 } catch (RemoteException e) { 8130 } 8131 } 8132 } 8133 8134 void removePackageLI(PackageSetting ps, boolean chatty) { 8135 if (DEBUG_INSTALL) { 8136 if (chatty) 8137 Log.d(TAG, "Removing package " + ps.name); 8138 } 8139 8140 // writer 8141 synchronized (mPackages) { 8142 mPackages.remove(ps.name); 8143 final PackageParser.Package pkg = ps.pkg; 8144 if (pkg != null) { 8145 cleanPackageDataStructuresLILPw(pkg, chatty); 8146 } 8147 } 8148 } 8149 8150 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8151 if (DEBUG_INSTALL) { 8152 if (chatty) 8153 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8154 } 8155 8156 // writer 8157 synchronized (mPackages) { 8158 mPackages.remove(pkg.applicationInfo.packageName); 8159 cleanPackageDataStructuresLILPw(pkg, chatty); 8160 } 8161 } 8162 8163 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8164 int N = pkg.providers.size(); 8165 StringBuilder r = null; 8166 int i; 8167 for (i=0; i<N; i++) { 8168 PackageParser.Provider p = pkg.providers.get(i); 8169 mProviders.removeProvider(p); 8170 if (p.info.authority == null) { 8171 8172 /* There was another ContentProvider with this authority when 8173 * this app was installed so this authority is null, 8174 * Ignore it as we don't have to unregister the provider. 8175 */ 8176 continue; 8177 } 8178 String names[] = p.info.authority.split(";"); 8179 for (int j = 0; j < names.length; j++) { 8180 if (mProvidersByAuthority.get(names[j]) == p) { 8181 mProvidersByAuthority.remove(names[j]); 8182 if (DEBUG_REMOVE) { 8183 if (chatty) 8184 Log.d(TAG, "Unregistered content provider: " + names[j] 8185 + ", className = " + p.info.name + ", isSyncable = " 8186 + p.info.isSyncable); 8187 } 8188 } 8189 } 8190 if (DEBUG_REMOVE && chatty) { 8191 if (r == null) { 8192 r = new StringBuilder(256); 8193 } else { 8194 r.append(' '); 8195 } 8196 r.append(p.info.name); 8197 } 8198 } 8199 if (r != null) { 8200 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8201 } 8202 8203 N = pkg.services.size(); 8204 r = null; 8205 for (i=0; i<N; i++) { 8206 PackageParser.Service s = pkg.services.get(i); 8207 mServices.removeService(s); 8208 if (chatty) { 8209 if (r == null) { 8210 r = new StringBuilder(256); 8211 } else { 8212 r.append(' '); 8213 } 8214 r.append(s.info.name); 8215 } 8216 } 8217 if (r != null) { 8218 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8219 } 8220 8221 N = pkg.receivers.size(); 8222 r = null; 8223 for (i=0; i<N; i++) { 8224 PackageParser.Activity a = pkg.receivers.get(i); 8225 mReceivers.removeActivity(a, "receiver"); 8226 if (DEBUG_REMOVE && chatty) { 8227 if (r == null) { 8228 r = new StringBuilder(256); 8229 } else { 8230 r.append(' '); 8231 } 8232 r.append(a.info.name); 8233 } 8234 } 8235 if (r != null) { 8236 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8237 } 8238 8239 N = pkg.activities.size(); 8240 r = null; 8241 for (i=0; i<N; i++) { 8242 PackageParser.Activity a = pkg.activities.get(i); 8243 mActivities.removeActivity(a, "activity"); 8244 if (DEBUG_REMOVE && chatty) { 8245 if (r == null) { 8246 r = new StringBuilder(256); 8247 } else { 8248 r.append(' '); 8249 } 8250 r.append(a.info.name); 8251 } 8252 } 8253 if (r != null) { 8254 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8255 } 8256 8257 N = pkg.permissions.size(); 8258 r = null; 8259 for (i=0; i<N; i++) { 8260 PackageParser.Permission p = pkg.permissions.get(i); 8261 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8262 if (bp == null) { 8263 bp = mSettings.mPermissionTrees.get(p.info.name); 8264 } 8265 if (bp != null && bp.perm == p) { 8266 bp.perm = null; 8267 if (DEBUG_REMOVE && chatty) { 8268 if (r == null) { 8269 r = new StringBuilder(256); 8270 } else { 8271 r.append(' '); 8272 } 8273 r.append(p.info.name); 8274 } 8275 } 8276 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8277 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8278 if (appOpPerms != null) { 8279 appOpPerms.remove(pkg.packageName); 8280 } 8281 } 8282 } 8283 if (r != null) { 8284 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8285 } 8286 8287 N = pkg.requestedPermissions.size(); 8288 r = null; 8289 for (i=0; i<N; i++) { 8290 String perm = pkg.requestedPermissions.get(i); 8291 BasePermission bp = mSettings.mPermissions.get(perm); 8292 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8293 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8294 if (appOpPerms != null) { 8295 appOpPerms.remove(pkg.packageName); 8296 if (appOpPerms.isEmpty()) { 8297 mAppOpPermissionPackages.remove(perm); 8298 } 8299 } 8300 } 8301 } 8302 if (r != null) { 8303 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8304 } 8305 8306 N = pkg.instrumentation.size(); 8307 r = null; 8308 for (i=0; i<N; i++) { 8309 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8310 mInstrumentation.remove(a.getComponentName()); 8311 if (DEBUG_REMOVE && chatty) { 8312 if (r == null) { 8313 r = new StringBuilder(256); 8314 } else { 8315 r.append(' '); 8316 } 8317 r.append(a.info.name); 8318 } 8319 } 8320 if (r != null) { 8321 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8322 } 8323 8324 r = null; 8325 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8326 // Only system apps can hold shared libraries. 8327 if (pkg.libraryNames != null) { 8328 for (i=0; i<pkg.libraryNames.size(); i++) { 8329 String name = pkg.libraryNames.get(i); 8330 SharedLibraryEntry cur = mSharedLibraries.get(name); 8331 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8332 mSharedLibraries.remove(name); 8333 if (DEBUG_REMOVE && chatty) { 8334 if (r == null) { 8335 r = new StringBuilder(256); 8336 } else { 8337 r.append(' '); 8338 } 8339 r.append(name); 8340 } 8341 } 8342 } 8343 } 8344 } 8345 if (r != null) { 8346 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8347 } 8348 } 8349 8350 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8351 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8352 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8353 return true; 8354 } 8355 } 8356 return false; 8357 } 8358 8359 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8360 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8361 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8362 8363 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8364 int flags) { 8365 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8366 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8367 } 8368 8369 private void updatePermissionsLPw(String changingPkg, 8370 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8371 // Make sure there are no dangling permission trees. 8372 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8373 while (it.hasNext()) { 8374 final BasePermission bp = it.next(); 8375 if (bp.packageSetting == null) { 8376 // We may not yet have parsed the package, so just see if 8377 // we still know about its settings. 8378 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8379 } 8380 if (bp.packageSetting == null) { 8381 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8382 + " from package " + bp.sourcePackage); 8383 it.remove(); 8384 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8385 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8386 Slog.i(TAG, "Removing old permission tree: " + bp.name 8387 + " from package " + bp.sourcePackage); 8388 flags |= UPDATE_PERMISSIONS_ALL; 8389 it.remove(); 8390 } 8391 } 8392 } 8393 8394 // Make sure all dynamic permissions have been assigned to a package, 8395 // and make sure there are no dangling permissions. 8396 it = mSettings.mPermissions.values().iterator(); 8397 while (it.hasNext()) { 8398 final BasePermission bp = it.next(); 8399 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8400 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8401 + bp.name + " pkg=" + bp.sourcePackage 8402 + " info=" + bp.pendingInfo); 8403 if (bp.packageSetting == null && bp.pendingInfo != null) { 8404 final BasePermission tree = findPermissionTreeLP(bp.name); 8405 if (tree != null && tree.perm != null) { 8406 bp.packageSetting = tree.packageSetting; 8407 bp.perm = new PackageParser.Permission(tree.perm.owner, 8408 new PermissionInfo(bp.pendingInfo)); 8409 bp.perm.info.packageName = tree.perm.info.packageName; 8410 bp.perm.info.name = bp.name; 8411 bp.uid = tree.uid; 8412 } 8413 } 8414 } 8415 if (bp.packageSetting == null) { 8416 // We may not yet have parsed the package, so just see if 8417 // we still know about its settings. 8418 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8419 } 8420 if (bp.packageSetting == null) { 8421 Slog.w(TAG, "Removing dangling permission: " + bp.name 8422 + " from package " + bp.sourcePackage); 8423 it.remove(); 8424 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8425 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8426 Slog.i(TAG, "Removing old permission: " + bp.name 8427 + " from package " + bp.sourcePackage); 8428 flags |= UPDATE_PERMISSIONS_ALL; 8429 it.remove(); 8430 } 8431 } 8432 } 8433 8434 // Now update the permissions for all packages, in particular 8435 // replace the granted permissions of the system packages. 8436 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8437 for (PackageParser.Package pkg : mPackages.values()) { 8438 if (pkg != pkgInfo) { 8439 // Only replace for packages on requested volume 8440 final String volumeUuid = getVolumeUuidForPackage(pkg); 8441 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8442 && Objects.equals(replaceVolumeUuid, volumeUuid); 8443 grantPermissionsLPw(pkg, replace, changingPkg); 8444 } 8445 } 8446 } 8447 8448 if (pkgInfo != null) { 8449 // Only replace for packages on requested volume 8450 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8451 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8452 && Objects.equals(replaceVolumeUuid, volumeUuid); 8453 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8454 } 8455 } 8456 8457 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8458 String packageOfInterest) { 8459 // IMPORTANT: There are two types of permissions: install and runtime. 8460 // Install time permissions are granted when the app is installed to 8461 // all device users and users added in the future. Runtime permissions 8462 // are granted at runtime explicitly to specific users. Normal and signature 8463 // protected permissions are install time permissions. Dangerous permissions 8464 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8465 // otherwise they are runtime permissions. This function does not manage 8466 // runtime permissions except for the case an app targeting Lollipop MR1 8467 // being upgraded to target a newer SDK, in which case dangerous permissions 8468 // are transformed from install time to runtime ones. 8469 8470 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8471 if (ps == null) { 8472 return; 8473 } 8474 8475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8476 8477 PermissionsState permissionsState = ps.getPermissionsState(); 8478 PermissionsState origPermissions = permissionsState; 8479 8480 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8481 8482 boolean runtimePermissionsRevoked = false; 8483 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8484 8485 boolean changedInstallPermission = false; 8486 8487 if (replace) { 8488 ps.installPermissionsFixed = false; 8489 if (!ps.isSharedUser()) { 8490 origPermissions = new PermissionsState(permissionsState); 8491 permissionsState.reset(); 8492 } else { 8493 // We need to know only about runtime permission changes since the 8494 // calling code always writes the install permissions state but 8495 // the runtime ones are written only if changed. The only cases of 8496 // changed runtime permissions here are promotion of an install to 8497 // runtime and revocation of a runtime from a shared user. 8498 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8499 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8500 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8501 runtimePermissionsRevoked = true; 8502 } 8503 } 8504 } 8505 8506 permissionsState.setGlobalGids(mGlobalGids); 8507 8508 final int N = pkg.requestedPermissions.size(); 8509 for (int i=0; i<N; i++) { 8510 final String name = pkg.requestedPermissions.get(i); 8511 final BasePermission bp = mSettings.mPermissions.get(name); 8512 8513 if (DEBUG_INSTALL) { 8514 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8515 } 8516 8517 if (bp == null || bp.packageSetting == null) { 8518 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8519 Slog.w(TAG, "Unknown permission " + name 8520 + " in package " + pkg.packageName); 8521 } 8522 continue; 8523 } 8524 8525 final String perm = bp.name; 8526 boolean allowedSig = false; 8527 int grant = GRANT_DENIED; 8528 8529 // Keep track of app op permissions. 8530 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8531 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8532 if (pkgs == null) { 8533 pkgs = new ArraySet<>(); 8534 mAppOpPermissionPackages.put(bp.name, pkgs); 8535 } 8536 pkgs.add(pkg.packageName); 8537 } 8538 8539 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8540 switch (level) { 8541 case PermissionInfo.PROTECTION_NORMAL: { 8542 // For all apps normal permissions are install time ones. 8543 grant = GRANT_INSTALL; 8544 } break; 8545 8546 case PermissionInfo.PROTECTION_DANGEROUS: { 8547 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8548 // For legacy apps dangerous permissions are install time ones. 8549 grant = GRANT_INSTALL_LEGACY; 8550 } else if (origPermissions.hasInstallPermission(bp.name)) { 8551 // For legacy apps that became modern, install becomes runtime. 8552 grant = GRANT_UPGRADE; 8553 } else if (mPromoteSystemApps 8554 && isSystemApp(ps) 8555 && mExistingSystemPackages.contains(ps.name)) { 8556 // For legacy system apps, install becomes runtime. 8557 // We cannot check hasInstallPermission() for system apps since those 8558 // permissions were granted implicitly and not persisted pre-M. 8559 grant = GRANT_UPGRADE; 8560 } else { 8561 // For modern apps keep runtime permissions unchanged. 8562 grant = GRANT_RUNTIME; 8563 } 8564 } break; 8565 8566 case PermissionInfo.PROTECTION_SIGNATURE: { 8567 // For all apps signature permissions are install time ones. 8568 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8569 if (allowedSig) { 8570 grant = GRANT_INSTALL; 8571 } 8572 } break; 8573 } 8574 8575 if (DEBUG_INSTALL) { 8576 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8577 } 8578 8579 if (grant != GRANT_DENIED) { 8580 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8581 // If this is an existing, non-system package, then 8582 // we can't add any new permissions to it. 8583 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8584 // Except... if this is a permission that was added 8585 // to the platform (note: need to only do this when 8586 // updating the platform). 8587 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8588 grant = GRANT_DENIED; 8589 } 8590 } 8591 } 8592 8593 switch (grant) { 8594 case GRANT_INSTALL: { 8595 // Revoke this as runtime permission to handle the case of 8596 // a runtime permission being downgraded to an install one. 8597 for (int userId : UserManagerService.getInstance().getUserIds()) { 8598 if (origPermissions.getRuntimePermissionState( 8599 bp.name, userId) != null) { 8600 // Revoke the runtime permission and clear the flags. 8601 origPermissions.revokeRuntimePermission(bp, userId); 8602 origPermissions.updatePermissionFlags(bp, userId, 8603 PackageManager.MASK_PERMISSION_FLAGS, 0); 8604 // If we revoked a permission permission, we have to write. 8605 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8606 changedRuntimePermissionUserIds, userId); 8607 } 8608 } 8609 // Grant an install permission. 8610 if (permissionsState.grantInstallPermission(bp) != 8611 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8612 changedInstallPermission = true; 8613 } 8614 } break; 8615 8616 case GRANT_INSTALL_LEGACY: { 8617 // Grant an install permission. 8618 if (permissionsState.grantInstallPermission(bp) != 8619 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8620 changedInstallPermission = true; 8621 } 8622 } break; 8623 8624 case GRANT_RUNTIME: { 8625 // Grant previously granted runtime permissions. 8626 for (int userId : UserManagerService.getInstance().getUserIds()) { 8627 PermissionState permissionState = origPermissions 8628 .getRuntimePermissionState(bp.name, userId); 8629 final int flags = permissionState != null 8630 ? permissionState.getFlags() : 0; 8631 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8632 if (permissionsState.grantRuntimePermission(bp, userId) == 8633 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8634 // If we cannot put the permission as it was, we have to write. 8635 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8636 changedRuntimePermissionUserIds, userId); 8637 } 8638 } 8639 // Propagate the permission flags. 8640 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8641 } 8642 } break; 8643 8644 case GRANT_UPGRADE: { 8645 // Grant runtime permissions for a previously held install permission. 8646 PermissionState permissionState = origPermissions 8647 .getInstallPermissionState(bp.name); 8648 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8649 8650 if (origPermissions.revokeInstallPermission(bp) 8651 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8652 // We will be transferring the permission flags, so clear them. 8653 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8654 PackageManager.MASK_PERMISSION_FLAGS, 0); 8655 changedInstallPermission = true; 8656 } 8657 8658 // If the permission is not to be promoted to runtime we ignore it and 8659 // also its other flags as they are not applicable to install permissions. 8660 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8661 for (int userId : currentUserIds) { 8662 if (permissionsState.grantRuntimePermission(bp, userId) != 8663 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8664 // Transfer the permission flags. 8665 permissionsState.updatePermissionFlags(bp, userId, 8666 flags, flags); 8667 // If we granted the permission, we have to write. 8668 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8669 changedRuntimePermissionUserIds, userId); 8670 } 8671 } 8672 } 8673 } break; 8674 8675 default: { 8676 if (packageOfInterest == null 8677 || packageOfInterest.equals(pkg.packageName)) { 8678 Slog.w(TAG, "Not granting permission " + perm 8679 + " to package " + pkg.packageName 8680 + " because it was previously installed without"); 8681 } 8682 } break; 8683 } 8684 } else { 8685 if (permissionsState.revokeInstallPermission(bp) != 8686 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8687 // Also drop the permission flags. 8688 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8689 PackageManager.MASK_PERMISSION_FLAGS, 0); 8690 changedInstallPermission = true; 8691 Slog.i(TAG, "Un-granting permission " + perm 8692 + " from package " + pkg.packageName 8693 + " (protectionLevel=" + bp.protectionLevel 8694 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8695 + ")"); 8696 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8697 // Don't print warning for app op permissions, since it is fine for them 8698 // not to be granted, there is a UI for the user to decide. 8699 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8700 Slog.w(TAG, "Not granting permission " + perm 8701 + " to package " + pkg.packageName 8702 + " (protectionLevel=" + bp.protectionLevel 8703 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8704 + ")"); 8705 } 8706 } 8707 } 8708 } 8709 8710 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8711 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8712 // This is the first that we have heard about this package, so the 8713 // permissions we have now selected are fixed until explicitly 8714 // changed. 8715 ps.installPermissionsFixed = true; 8716 } 8717 8718 // Persist the runtime permissions state for users with changes. If permissions 8719 // were revoked because no app in the shared user declares them we have to 8720 // write synchronously to avoid losing runtime permissions state. 8721 for (int userId : changedRuntimePermissionUserIds) { 8722 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8723 } 8724 8725 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8726 } 8727 8728 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8729 boolean allowed = false; 8730 final int NP = PackageParser.NEW_PERMISSIONS.length; 8731 for (int ip=0; ip<NP; ip++) { 8732 final PackageParser.NewPermissionInfo npi 8733 = PackageParser.NEW_PERMISSIONS[ip]; 8734 if (npi.name.equals(perm) 8735 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8736 allowed = true; 8737 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8738 + pkg.packageName); 8739 break; 8740 } 8741 } 8742 return allowed; 8743 } 8744 8745 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8746 BasePermission bp, PermissionsState origPermissions) { 8747 boolean allowed; 8748 allowed = (compareSignatures( 8749 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8750 == PackageManager.SIGNATURE_MATCH) 8751 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8752 == PackageManager.SIGNATURE_MATCH); 8753 if (!allowed && (bp.protectionLevel 8754 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8755 if (isSystemApp(pkg)) { 8756 // For updated system applications, a system permission 8757 // is granted only if it had been defined by the original application. 8758 if (pkg.isUpdatedSystemApp()) { 8759 final PackageSetting sysPs = mSettings 8760 .getDisabledSystemPkgLPr(pkg.packageName); 8761 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8762 // If the original was granted this permission, we take 8763 // that grant decision as read and propagate it to the 8764 // update. 8765 if (sysPs.isPrivileged()) { 8766 allowed = true; 8767 } 8768 } else { 8769 // The system apk may have been updated with an older 8770 // version of the one on the data partition, but which 8771 // granted a new system permission that it didn't have 8772 // before. In this case we do want to allow the app to 8773 // now get the new permission if the ancestral apk is 8774 // privileged to get it. 8775 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8776 for (int j=0; 8777 j<sysPs.pkg.requestedPermissions.size(); j++) { 8778 if (perm.equals( 8779 sysPs.pkg.requestedPermissions.get(j))) { 8780 allowed = true; 8781 break; 8782 } 8783 } 8784 } 8785 } 8786 } else { 8787 allowed = isPrivilegedApp(pkg); 8788 } 8789 } 8790 } 8791 if (!allowed) { 8792 if (!allowed && (bp.protectionLevel 8793 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8794 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8795 // If this was a previously normal/dangerous permission that got moved 8796 // to a system permission as part of the runtime permission redesign, then 8797 // we still want to blindly grant it to old apps. 8798 allowed = true; 8799 } 8800 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8801 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8802 // If this permission is to be granted to the system installer and 8803 // this app is an installer, then it gets the permission. 8804 allowed = true; 8805 } 8806 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8807 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8808 // If this permission is to be granted to the system verifier and 8809 // this app is a verifier, then it gets the permission. 8810 allowed = true; 8811 } 8812 if (!allowed && (bp.protectionLevel 8813 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8814 && isSystemApp(pkg)) { 8815 // Any pre-installed system app is allowed to get this permission. 8816 allowed = true; 8817 } 8818 if (!allowed && (bp.protectionLevel 8819 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8820 // For development permissions, a development permission 8821 // is granted only if it was already granted. 8822 allowed = origPermissions.hasInstallPermission(perm); 8823 } 8824 } 8825 return allowed; 8826 } 8827 8828 final class ActivityIntentResolver 8829 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8830 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8831 boolean defaultOnly, int userId) { 8832 if (!sUserManager.exists(userId)) return null; 8833 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8834 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8835 } 8836 8837 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8838 int userId) { 8839 if (!sUserManager.exists(userId)) return null; 8840 mFlags = flags; 8841 return super.queryIntent(intent, resolvedType, 8842 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8843 } 8844 8845 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8846 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8847 if (!sUserManager.exists(userId)) return null; 8848 if (packageActivities == null) { 8849 return null; 8850 } 8851 mFlags = flags; 8852 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8853 final int N = packageActivities.size(); 8854 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8855 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8856 8857 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8858 for (int i = 0; i < N; ++i) { 8859 intentFilters = packageActivities.get(i).intents; 8860 if (intentFilters != null && intentFilters.size() > 0) { 8861 PackageParser.ActivityIntentInfo[] array = 8862 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8863 intentFilters.toArray(array); 8864 listCut.add(array); 8865 } 8866 } 8867 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8868 } 8869 8870 public final void addActivity(PackageParser.Activity a, String type) { 8871 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8872 mActivities.put(a.getComponentName(), a); 8873 if (DEBUG_SHOW_INFO) 8874 Log.v( 8875 TAG, " " + type + " " + 8876 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8877 if (DEBUG_SHOW_INFO) 8878 Log.v(TAG, " Class=" + a.info.name); 8879 final int NI = a.intents.size(); 8880 for (int j=0; j<NI; j++) { 8881 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8882 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8883 intent.setPriority(0); 8884 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8885 + a.className + " with priority > 0, forcing to 0"); 8886 } 8887 if (DEBUG_SHOW_INFO) { 8888 Log.v(TAG, " IntentFilter:"); 8889 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8890 } 8891 if (!intent.debugCheck()) { 8892 Log.w(TAG, "==> For Activity " + a.info.name); 8893 } 8894 addFilter(intent); 8895 } 8896 } 8897 8898 public final void removeActivity(PackageParser.Activity a, String type) { 8899 mActivities.remove(a.getComponentName()); 8900 if (DEBUG_SHOW_INFO) { 8901 Log.v(TAG, " " + type + " " 8902 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8903 : a.info.name) + ":"); 8904 Log.v(TAG, " Class=" + a.info.name); 8905 } 8906 final int NI = a.intents.size(); 8907 for (int j=0; j<NI; j++) { 8908 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8909 if (DEBUG_SHOW_INFO) { 8910 Log.v(TAG, " IntentFilter:"); 8911 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8912 } 8913 removeFilter(intent); 8914 } 8915 } 8916 8917 @Override 8918 protected boolean allowFilterResult( 8919 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8920 ActivityInfo filterAi = filter.activity.info; 8921 for (int i=dest.size()-1; i>=0; i--) { 8922 ActivityInfo destAi = dest.get(i).activityInfo; 8923 if (destAi.name == filterAi.name 8924 && destAi.packageName == filterAi.packageName) { 8925 return false; 8926 } 8927 } 8928 return true; 8929 } 8930 8931 @Override 8932 protected ActivityIntentInfo[] newArray(int size) { 8933 return new ActivityIntentInfo[size]; 8934 } 8935 8936 @Override 8937 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8938 if (!sUserManager.exists(userId)) return true; 8939 PackageParser.Package p = filter.activity.owner; 8940 if (p != null) { 8941 PackageSetting ps = (PackageSetting)p.mExtras; 8942 if (ps != null) { 8943 // System apps are never considered stopped for purposes of 8944 // filtering, because there may be no way for the user to 8945 // actually re-launch them. 8946 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8947 && ps.getStopped(userId); 8948 } 8949 } 8950 return false; 8951 } 8952 8953 @Override 8954 protected boolean isPackageForFilter(String packageName, 8955 PackageParser.ActivityIntentInfo info) { 8956 return packageName.equals(info.activity.owner.packageName); 8957 } 8958 8959 @Override 8960 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8961 int match, int userId) { 8962 if (!sUserManager.exists(userId)) return null; 8963 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8964 return null; 8965 } 8966 final PackageParser.Activity activity = info.activity; 8967 if (mSafeMode && (activity.info.applicationInfo.flags 8968 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8969 return null; 8970 } 8971 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8972 if (ps == null) { 8973 return null; 8974 } 8975 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8976 ps.readUserState(userId), userId); 8977 if (ai == null) { 8978 return null; 8979 } 8980 final ResolveInfo res = new ResolveInfo(); 8981 res.activityInfo = ai; 8982 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8983 res.filter = info; 8984 } 8985 if (info != null) { 8986 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8987 } 8988 res.priority = info.getPriority(); 8989 res.preferredOrder = activity.owner.mPreferredOrder; 8990 //System.out.println("Result: " + res.activityInfo.className + 8991 // " = " + res.priority); 8992 res.match = match; 8993 res.isDefault = info.hasDefault; 8994 res.labelRes = info.labelRes; 8995 res.nonLocalizedLabel = info.nonLocalizedLabel; 8996 if (userNeedsBadging(userId)) { 8997 res.noResourceId = true; 8998 } else { 8999 res.icon = info.icon; 9000 } 9001 res.iconResourceId = info.icon; 9002 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9003 return res; 9004 } 9005 9006 @Override 9007 protected void sortResults(List<ResolveInfo> results) { 9008 Collections.sort(results, mResolvePrioritySorter); 9009 } 9010 9011 @Override 9012 protected void dumpFilter(PrintWriter out, String prefix, 9013 PackageParser.ActivityIntentInfo filter) { 9014 out.print(prefix); out.print( 9015 Integer.toHexString(System.identityHashCode(filter.activity))); 9016 out.print(' '); 9017 filter.activity.printComponentShortName(out); 9018 out.print(" filter "); 9019 out.println(Integer.toHexString(System.identityHashCode(filter))); 9020 } 9021 9022 @Override 9023 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9024 return filter.activity; 9025 } 9026 9027 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9028 PackageParser.Activity activity = (PackageParser.Activity)label; 9029 out.print(prefix); out.print( 9030 Integer.toHexString(System.identityHashCode(activity))); 9031 out.print(' '); 9032 activity.printComponentShortName(out); 9033 if (count > 1) { 9034 out.print(" ("); out.print(count); out.print(" filters)"); 9035 } 9036 out.println(); 9037 } 9038 9039// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9040// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9041// final List<ResolveInfo> retList = Lists.newArrayList(); 9042// while (i.hasNext()) { 9043// final ResolveInfo resolveInfo = i.next(); 9044// if (isEnabledLP(resolveInfo.activityInfo)) { 9045// retList.add(resolveInfo); 9046// } 9047// } 9048// return retList; 9049// } 9050 9051 // Keys are String (activity class name), values are Activity. 9052 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9053 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9054 private int mFlags; 9055 } 9056 9057 private final class ServiceIntentResolver 9058 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9059 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9060 boolean defaultOnly, int userId) { 9061 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9062 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9063 } 9064 9065 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9066 int userId) { 9067 if (!sUserManager.exists(userId)) return null; 9068 mFlags = flags; 9069 return super.queryIntent(intent, resolvedType, 9070 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9071 } 9072 9073 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9074 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9075 if (!sUserManager.exists(userId)) return null; 9076 if (packageServices == null) { 9077 return null; 9078 } 9079 mFlags = flags; 9080 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9081 final int N = packageServices.size(); 9082 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9083 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9084 9085 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9086 for (int i = 0; i < N; ++i) { 9087 intentFilters = packageServices.get(i).intents; 9088 if (intentFilters != null && intentFilters.size() > 0) { 9089 PackageParser.ServiceIntentInfo[] array = 9090 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9091 intentFilters.toArray(array); 9092 listCut.add(array); 9093 } 9094 } 9095 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9096 } 9097 9098 public final void addService(PackageParser.Service s) { 9099 mServices.put(s.getComponentName(), s); 9100 if (DEBUG_SHOW_INFO) { 9101 Log.v(TAG, " " 9102 + (s.info.nonLocalizedLabel != null 9103 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9104 Log.v(TAG, " Class=" + s.info.name); 9105 } 9106 final int NI = s.intents.size(); 9107 int j; 9108 for (j=0; j<NI; j++) { 9109 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9110 if (DEBUG_SHOW_INFO) { 9111 Log.v(TAG, " IntentFilter:"); 9112 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9113 } 9114 if (!intent.debugCheck()) { 9115 Log.w(TAG, "==> For Service " + s.info.name); 9116 } 9117 addFilter(intent); 9118 } 9119 } 9120 9121 public final void removeService(PackageParser.Service s) { 9122 mServices.remove(s.getComponentName()); 9123 if (DEBUG_SHOW_INFO) { 9124 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9125 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9126 Log.v(TAG, " Class=" + s.info.name); 9127 } 9128 final int NI = s.intents.size(); 9129 int j; 9130 for (j=0; j<NI; j++) { 9131 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9132 if (DEBUG_SHOW_INFO) { 9133 Log.v(TAG, " IntentFilter:"); 9134 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9135 } 9136 removeFilter(intent); 9137 } 9138 } 9139 9140 @Override 9141 protected boolean allowFilterResult( 9142 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9143 ServiceInfo filterSi = filter.service.info; 9144 for (int i=dest.size()-1; i>=0; i--) { 9145 ServiceInfo destAi = dest.get(i).serviceInfo; 9146 if (destAi.name == filterSi.name 9147 && destAi.packageName == filterSi.packageName) { 9148 return false; 9149 } 9150 } 9151 return true; 9152 } 9153 9154 @Override 9155 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9156 return new PackageParser.ServiceIntentInfo[size]; 9157 } 9158 9159 @Override 9160 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9161 if (!sUserManager.exists(userId)) return true; 9162 PackageParser.Package p = filter.service.owner; 9163 if (p != null) { 9164 PackageSetting ps = (PackageSetting)p.mExtras; 9165 if (ps != null) { 9166 // System apps are never considered stopped for purposes of 9167 // filtering, because there may be no way for the user to 9168 // actually re-launch them. 9169 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9170 && ps.getStopped(userId); 9171 } 9172 } 9173 return false; 9174 } 9175 9176 @Override 9177 protected boolean isPackageForFilter(String packageName, 9178 PackageParser.ServiceIntentInfo info) { 9179 return packageName.equals(info.service.owner.packageName); 9180 } 9181 9182 @Override 9183 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9184 int match, int userId) { 9185 if (!sUserManager.exists(userId)) return null; 9186 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9187 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9188 return null; 9189 } 9190 final PackageParser.Service service = info.service; 9191 if (mSafeMode && (service.info.applicationInfo.flags 9192 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9193 return null; 9194 } 9195 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9196 if (ps == null) { 9197 return null; 9198 } 9199 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9200 ps.readUserState(userId), userId); 9201 if (si == null) { 9202 return null; 9203 } 9204 final ResolveInfo res = new ResolveInfo(); 9205 res.serviceInfo = si; 9206 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9207 res.filter = filter; 9208 } 9209 res.priority = info.getPriority(); 9210 res.preferredOrder = service.owner.mPreferredOrder; 9211 res.match = match; 9212 res.isDefault = info.hasDefault; 9213 res.labelRes = info.labelRes; 9214 res.nonLocalizedLabel = info.nonLocalizedLabel; 9215 res.icon = info.icon; 9216 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9217 return res; 9218 } 9219 9220 @Override 9221 protected void sortResults(List<ResolveInfo> results) { 9222 Collections.sort(results, mResolvePrioritySorter); 9223 } 9224 9225 @Override 9226 protected void dumpFilter(PrintWriter out, String prefix, 9227 PackageParser.ServiceIntentInfo filter) { 9228 out.print(prefix); out.print( 9229 Integer.toHexString(System.identityHashCode(filter.service))); 9230 out.print(' '); 9231 filter.service.printComponentShortName(out); 9232 out.print(" filter "); 9233 out.println(Integer.toHexString(System.identityHashCode(filter))); 9234 } 9235 9236 @Override 9237 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9238 return filter.service; 9239 } 9240 9241 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9242 PackageParser.Service service = (PackageParser.Service)label; 9243 out.print(prefix); out.print( 9244 Integer.toHexString(System.identityHashCode(service))); 9245 out.print(' '); 9246 service.printComponentShortName(out); 9247 if (count > 1) { 9248 out.print(" ("); out.print(count); out.print(" filters)"); 9249 } 9250 out.println(); 9251 } 9252 9253// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9254// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9255// final List<ResolveInfo> retList = Lists.newArrayList(); 9256// while (i.hasNext()) { 9257// final ResolveInfo resolveInfo = (ResolveInfo) i; 9258// if (isEnabledLP(resolveInfo.serviceInfo)) { 9259// retList.add(resolveInfo); 9260// } 9261// } 9262// return retList; 9263// } 9264 9265 // Keys are String (activity class name), values are Activity. 9266 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9267 = new ArrayMap<ComponentName, PackageParser.Service>(); 9268 private int mFlags; 9269 }; 9270 9271 private final class ProviderIntentResolver 9272 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9273 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9274 boolean defaultOnly, int userId) { 9275 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9276 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9277 } 9278 9279 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9280 int userId) { 9281 if (!sUserManager.exists(userId)) 9282 return null; 9283 mFlags = flags; 9284 return super.queryIntent(intent, resolvedType, 9285 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9286 } 9287 9288 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9289 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9290 if (!sUserManager.exists(userId)) 9291 return null; 9292 if (packageProviders == null) { 9293 return null; 9294 } 9295 mFlags = flags; 9296 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9297 final int N = packageProviders.size(); 9298 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9299 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9300 9301 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9302 for (int i = 0; i < N; ++i) { 9303 intentFilters = packageProviders.get(i).intents; 9304 if (intentFilters != null && intentFilters.size() > 0) { 9305 PackageParser.ProviderIntentInfo[] array = 9306 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9307 intentFilters.toArray(array); 9308 listCut.add(array); 9309 } 9310 } 9311 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9312 } 9313 9314 public final void addProvider(PackageParser.Provider p) { 9315 if (mProviders.containsKey(p.getComponentName())) { 9316 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9317 return; 9318 } 9319 9320 mProviders.put(p.getComponentName(), p); 9321 if (DEBUG_SHOW_INFO) { 9322 Log.v(TAG, " " 9323 + (p.info.nonLocalizedLabel != null 9324 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9325 Log.v(TAG, " Class=" + p.info.name); 9326 } 9327 final int NI = p.intents.size(); 9328 int j; 9329 for (j = 0; j < NI; j++) { 9330 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9331 if (DEBUG_SHOW_INFO) { 9332 Log.v(TAG, " IntentFilter:"); 9333 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9334 } 9335 if (!intent.debugCheck()) { 9336 Log.w(TAG, "==> For Provider " + p.info.name); 9337 } 9338 addFilter(intent); 9339 } 9340 } 9341 9342 public final void removeProvider(PackageParser.Provider p) { 9343 mProviders.remove(p.getComponentName()); 9344 if (DEBUG_SHOW_INFO) { 9345 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9346 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9347 Log.v(TAG, " Class=" + p.info.name); 9348 } 9349 final int NI = p.intents.size(); 9350 int j; 9351 for (j = 0; j < NI; j++) { 9352 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9353 if (DEBUG_SHOW_INFO) { 9354 Log.v(TAG, " IntentFilter:"); 9355 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9356 } 9357 removeFilter(intent); 9358 } 9359 } 9360 9361 @Override 9362 protected boolean allowFilterResult( 9363 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9364 ProviderInfo filterPi = filter.provider.info; 9365 for (int i = dest.size() - 1; i >= 0; i--) { 9366 ProviderInfo destPi = dest.get(i).providerInfo; 9367 if (destPi.name == filterPi.name 9368 && destPi.packageName == filterPi.packageName) { 9369 return false; 9370 } 9371 } 9372 return true; 9373 } 9374 9375 @Override 9376 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9377 return new PackageParser.ProviderIntentInfo[size]; 9378 } 9379 9380 @Override 9381 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9382 if (!sUserManager.exists(userId)) 9383 return true; 9384 PackageParser.Package p = filter.provider.owner; 9385 if (p != null) { 9386 PackageSetting ps = (PackageSetting) p.mExtras; 9387 if (ps != null) { 9388 // System apps are never considered stopped for purposes of 9389 // filtering, because there may be no way for the user to 9390 // actually re-launch them. 9391 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9392 && ps.getStopped(userId); 9393 } 9394 } 9395 return false; 9396 } 9397 9398 @Override 9399 protected boolean isPackageForFilter(String packageName, 9400 PackageParser.ProviderIntentInfo info) { 9401 return packageName.equals(info.provider.owner.packageName); 9402 } 9403 9404 @Override 9405 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9406 int match, int userId) { 9407 if (!sUserManager.exists(userId)) 9408 return null; 9409 final PackageParser.ProviderIntentInfo info = filter; 9410 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9411 return null; 9412 } 9413 final PackageParser.Provider provider = info.provider; 9414 if (mSafeMode && (provider.info.applicationInfo.flags 9415 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9416 return null; 9417 } 9418 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9419 if (ps == null) { 9420 return null; 9421 } 9422 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9423 ps.readUserState(userId), userId); 9424 if (pi == null) { 9425 return null; 9426 } 9427 final ResolveInfo res = new ResolveInfo(); 9428 res.providerInfo = pi; 9429 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9430 res.filter = filter; 9431 } 9432 res.priority = info.getPriority(); 9433 res.preferredOrder = provider.owner.mPreferredOrder; 9434 res.match = match; 9435 res.isDefault = info.hasDefault; 9436 res.labelRes = info.labelRes; 9437 res.nonLocalizedLabel = info.nonLocalizedLabel; 9438 res.icon = info.icon; 9439 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9440 return res; 9441 } 9442 9443 @Override 9444 protected void sortResults(List<ResolveInfo> results) { 9445 Collections.sort(results, mResolvePrioritySorter); 9446 } 9447 9448 @Override 9449 protected void dumpFilter(PrintWriter out, String prefix, 9450 PackageParser.ProviderIntentInfo filter) { 9451 out.print(prefix); 9452 out.print( 9453 Integer.toHexString(System.identityHashCode(filter.provider))); 9454 out.print(' '); 9455 filter.provider.printComponentShortName(out); 9456 out.print(" filter "); 9457 out.println(Integer.toHexString(System.identityHashCode(filter))); 9458 } 9459 9460 @Override 9461 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9462 return filter.provider; 9463 } 9464 9465 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9466 PackageParser.Provider provider = (PackageParser.Provider)label; 9467 out.print(prefix); out.print( 9468 Integer.toHexString(System.identityHashCode(provider))); 9469 out.print(' '); 9470 provider.printComponentShortName(out); 9471 if (count > 1) { 9472 out.print(" ("); out.print(count); out.print(" filters)"); 9473 } 9474 out.println(); 9475 } 9476 9477 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9478 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9479 private int mFlags; 9480 }; 9481 9482 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9483 new Comparator<ResolveInfo>() { 9484 public int compare(ResolveInfo r1, ResolveInfo r2) { 9485 int v1 = r1.priority; 9486 int v2 = r2.priority; 9487 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9488 if (v1 != v2) { 9489 return (v1 > v2) ? -1 : 1; 9490 } 9491 v1 = r1.preferredOrder; 9492 v2 = r2.preferredOrder; 9493 if (v1 != v2) { 9494 return (v1 > v2) ? -1 : 1; 9495 } 9496 if (r1.isDefault != r2.isDefault) { 9497 return r1.isDefault ? -1 : 1; 9498 } 9499 v1 = r1.match; 9500 v2 = r2.match; 9501 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9502 if (v1 != v2) { 9503 return (v1 > v2) ? -1 : 1; 9504 } 9505 if (r1.system != r2.system) { 9506 return r1.system ? -1 : 1; 9507 } 9508 return 0; 9509 } 9510 }; 9511 9512 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9513 new Comparator<ProviderInfo>() { 9514 public int compare(ProviderInfo p1, ProviderInfo p2) { 9515 final int v1 = p1.initOrder; 9516 final int v2 = p2.initOrder; 9517 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9518 } 9519 }; 9520 9521 final void sendPackageBroadcast(final String action, final String pkg, 9522 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9523 final int[] userIds) { 9524 mHandler.post(new Runnable() { 9525 @Override 9526 public void run() { 9527 try { 9528 final IActivityManager am = ActivityManagerNative.getDefault(); 9529 if (am == null) return; 9530 final int[] resolvedUserIds; 9531 if (userIds == null) { 9532 resolvedUserIds = am.getRunningUserIds(); 9533 } else { 9534 resolvedUserIds = userIds; 9535 } 9536 for (int id : resolvedUserIds) { 9537 final Intent intent = new Intent(action, 9538 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9539 if (extras != null) { 9540 intent.putExtras(extras); 9541 } 9542 if (targetPkg != null) { 9543 intent.setPackage(targetPkg); 9544 } 9545 // Modify the UID when posting to other users 9546 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9547 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9548 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9549 intent.putExtra(Intent.EXTRA_UID, uid); 9550 } 9551 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9552 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9553 if (DEBUG_BROADCASTS) { 9554 RuntimeException here = new RuntimeException("here"); 9555 here.fillInStackTrace(); 9556 Slog.d(TAG, "Sending to user " + id + ": " 9557 + intent.toShortString(false, true, false, false) 9558 + " " + intent.getExtras(), here); 9559 } 9560 am.broadcastIntent(null, intent, null, finishedReceiver, 9561 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9562 null, finishedReceiver != null, false, id); 9563 } 9564 } catch (RemoteException ex) { 9565 } 9566 } 9567 }); 9568 } 9569 9570 /** 9571 * Check if the external storage media is available. This is true if there 9572 * is a mounted external storage medium or if the external storage is 9573 * emulated. 9574 */ 9575 private boolean isExternalMediaAvailable() { 9576 return mMediaMounted || Environment.isExternalStorageEmulated(); 9577 } 9578 9579 @Override 9580 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9581 // writer 9582 synchronized (mPackages) { 9583 if (!isExternalMediaAvailable()) { 9584 // If the external storage is no longer mounted at this point, 9585 // the caller may not have been able to delete all of this 9586 // packages files and can not delete any more. Bail. 9587 return null; 9588 } 9589 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9590 if (lastPackage != null) { 9591 pkgs.remove(lastPackage); 9592 } 9593 if (pkgs.size() > 0) { 9594 return pkgs.get(0); 9595 } 9596 } 9597 return null; 9598 } 9599 9600 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9601 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9602 userId, andCode ? 1 : 0, packageName); 9603 if (mSystemReady) { 9604 msg.sendToTarget(); 9605 } else { 9606 if (mPostSystemReadyMessages == null) { 9607 mPostSystemReadyMessages = new ArrayList<>(); 9608 } 9609 mPostSystemReadyMessages.add(msg); 9610 } 9611 } 9612 9613 void startCleaningPackages() { 9614 // reader 9615 synchronized (mPackages) { 9616 if (!isExternalMediaAvailable()) { 9617 return; 9618 } 9619 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9620 return; 9621 } 9622 } 9623 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9624 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9625 IActivityManager am = ActivityManagerNative.getDefault(); 9626 if (am != null) { 9627 try { 9628 am.startService(null, intent, null, mContext.getOpPackageName(), 9629 UserHandle.USER_SYSTEM); 9630 } catch (RemoteException e) { 9631 } 9632 } 9633 } 9634 9635 @Override 9636 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9637 int installFlags, String installerPackageName, VerificationParams verificationParams, 9638 String packageAbiOverride) { 9639 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9640 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9641 } 9642 9643 @Override 9644 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9645 int installFlags, String installerPackageName, VerificationParams verificationParams, 9646 String packageAbiOverride, int userId) { 9647 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9648 9649 final int callingUid = Binder.getCallingUid(); 9650 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9651 9652 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9653 try { 9654 if (observer != null) { 9655 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9656 } 9657 } catch (RemoteException re) { 9658 } 9659 return; 9660 } 9661 9662 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9663 installFlags |= PackageManager.INSTALL_FROM_ADB; 9664 9665 } else { 9666 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9667 // about installerPackageName. 9668 9669 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9670 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9671 } 9672 9673 UserHandle user; 9674 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9675 user = UserHandle.ALL; 9676 } else { 9677 user = new UserHandle(userId); 9678 } 9679 9680 // Only system components can circumvent runtime permissions when installing. 9681 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9682 && mContext.checkCallingOrSelfPermission(Manifest.permission 9683 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9684 throw new SecurityException("You need the " 9685 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9686 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9687 } 9688 9689 verificationParams.setInstallerUid(callingUid); 9690 9691 final File originFile = new File(originPath); 9692 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9693 9694 final Message msg = mHandler.obtainMessage(INIT_COPY); 9695 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9696 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9697 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9698 msg.obj = params; 9699 9700 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9701 System.identityHashCode(msg.obj)); 9702 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9703 System.identityHashCode(msg.obj)); 9704 9705 mHandler.sendMessage(msg); 9706 } 9707 9708 void installStage(String packageName, File stagedDir, String stagedCid, 9709 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9710 String installerPackageName, int installerUid, UserHandle user) { 9711 final VerificationParams verifParams = new VerificationParams( 9712 null, sessionParams.originatingUri, sessionParams.referrerUri, 9713 sessionParams.originatingUid, null); 9714 verifParams.setInstallerUid(installerUid); 9715 9716 final OriginInfo origin; 9717 if (stagedDir != null) { 9718 origin = OriginInfo.fromStagedFile(stagedDir); 9719 } else { 9720 origin = OriginInfo.fromStagedContainer(stagedCid); 9721 } 9722 9723 final Message msg = mHandler.obtainMessage(INIT_COPY); 9724 final InstallParams params = new InstallParams(origin, null, observer, 9725 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9726 verifParams, user, sessionParams.abiOverride, 9727 sessionParams.grantedRuntimePermissions); 9728 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9729 msg.obj = params; 9730 9731 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9732 System.identityHashCode(msg.obj)); 9733 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9734 System.identityHashCode(msg.obj)); 9735 9736 mHandler.sendMessage(msg); 9737 } 9738 9739 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9740 Bundle extras = new Bundle(1); 9741 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9742 9743 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9744 packageName, extras, null, null, new int[] {userId}); 9745 try { 9746 IActivityManager am = ActivityManagerNative.getDefault(); 9747 final boolean isSystem = 9748 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9749 if (isSystem && am.isUserRunning(userId, false)) { 9750 // The just-installed/enabled app is bundled on the system, so presumed 9751 // to be able to run automatically without needing an explicit launch. 9752 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9753 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9754 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9755 .setPackage(packageName); 9756 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9757 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9758 } 9759 } catch (RemoteException e) { 9760 // shouldn't happen 9761 Slog.w(TAG, "Unable to bootstrap installed package", e); 9762 } 9763 } 9764 9765 @Override 9766 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9767 int userId) { 9768 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9769 PackageSetting pkgSetting; 9770 final int uid = Binder.getCallingUid(); 9771 enforceCrossUserPermission(uid, userId, true, true, 9772 "setApplicationHiddenSetting for user " + userId); 9773 9774 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9775 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9776 return false; 9777 } 9778 9779 long callingId = Binder.clearCallingIdentity(); 9780 try { 9781 boolean sendAdded = false; 9782 boolean sendRemoved = false; 9783 // writer 9784 synchronized (mPackages) { 9785 pkgSetting = mSettings.mPackages.get(packageName); 9786 if (pkgSetting == null) { 9787 return false; 9788 } 9789 if (pkgSetting.getHidden(userId) != hidden) { 9790 pkgSetting.setHidden(hidden, userId); 9791 mSettings.writePackageRestrictionsLPr(userId); 9792 if (hidden) { 9793 sendRemoved = true; 9794 } else { 9795 sendAdded = true; 9796 } 9797 } 9798 } 9799 if (sendAdded) { 9800 sendPackageAddedForUser(packageName, pkgSetting, userId); 9801 return true; 9802 } 9803 if (sendRemoved) { 9804 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9805 "hiding pkg"); 9806 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9807 return true; 9808 } 9809 } finally { 9810 Binder.restoreCallingIdentity(callingId); 9811 } 9812 return false; 9813 } 9814 9815 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9816 int userId) { 9817 final PackageRemovedInfo info = new PackageRemovedInfo(); 9818 info.removedPackage = packageName; 9819 info.removedUsers = new int[] {userId}; 9820 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9821 info.sendBroadcast(false, false, false); 9822 } 9823 9824 /** 9825 * Returns true if application is not found or there was an error. Otherwise it returns 9826 * the hidden state of the package for the given user. 9827 */ 9828 @Override 9829 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9830 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9831 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9832 false, "getApplicationHidden for user " + userId); 9833 PackageSetting pkgSetting; 9834 long callingId = Binder.clearCallingIdentity(); 9835 try { 9836 // writer 9837 synchronized (mPackages) { 9838 pkgSetting = mSettings.mPackages.get(packageName); 9839 if (pkgSetting == null) { 9840 return true; 9841 } 9842 return pkgSetting.getHidden(userId); 9843 } 9844 } finally { 9845 Binder.restoreCallingIdentity(callingId); 9846 } 9847 } 9848 9849 /** 9850 * @hide 9851 */ 9852 @Override 9853 public int installExistingPackageAsUser(String packageName, int userId) { 9854 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9855 null); 9856 PackageSetting pkgSetting; 9857 final int uid = Binder.getCallingUid(); 9858 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9859 + userId); 9860 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9861 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9862 } 9863 9864 long callingId = Binder.clearCallingIdentity(); 9865 try { 9866 boolean sendAdded = false; 9867 9868 // writer 9869 synchronized (mPackages) { 9870 pkgSetting = mSettings.mPackages.get(packageName); 9871 if (pkgSetting == null) { 9872 return PackageManager.INSTALL_FAILED_INVALID_URI; 9873 } 9874 if (!pkgSetting.getInstalled(userId)) { 9875 pkgSetting.setInstalled(true, userId); 9876 pkgSetting.setHidden(false, userId); 9877 mSettings.writePackageRestrictionsLPr(userId); 9878 sendAdded = true; 9879 } 9880 } 9881 9882 if (sendAdded) { 9883 sendPackageAddedForUser(packageName, pkgSetting, userId); 9884 } 9885 } finally { 9886 Binder.restoreCallingIdentity(callingId); 9887 } 9888 9889 return PackageManager.INSTALL_SUCCEEDED; 9890 } 9891 9892 boolean isUserRestricted(int userId, String restrictionKey) { 9893 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9894 if (restrictions.getBoolean(restrictionKey, false)) { 9895 Log.w(TAG, "User is restricted: " + restrictionKey); 9896 return true; 9897 } 9898 return false; 9899 } 9900 9901 @Override 9902 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9903 mContext.enforceCallingOrSelfPermission( 9904 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9905 "Only package verification agents can verify applications"); 9906 9907 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9908 final PackageVerificationResponse response = new PackageVerificationResponse( 9909 verificationCode, Binder.getCallingUid()); 9910 msg.arg1 = id; 9911 msg.obj = response; 9912 mHandler.sendMessage(msg); 9913 } 9914 9915 @Override 9916 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9917 long millisecondsToDelay) { 9918 mContext.enforceCallingOrSelfPermission( 9919 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9920 "Only package verification agents can extend verification timeouts"); 9921 9922 final PackageVerificationState state = mPendingVerification.get(id); 9923 final PackageVerificationResponse response = new PackageVerificationResponse( 9924 verificationCodeAtTimeout, Binder.getCallingUid()); 9925 9926 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9927 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9928 } 9929 if (millisecondsToDelay < 0) { 9930 millisecondsToDelay = 0; 9931 } 9932 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9933 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9934 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9935 } 9936 9937 if ((state != null) && !state.timeoutExtended()) { 9938 state.extendTimeout(); 9939 9940 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9941 msg.arg1 = id; 9942 msg.obj = response; 9943 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9944 } 9945 } 9946 9947 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9948 int verificationCode, UserHandle user) { 9949 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9950 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9951 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9952 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9953 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9954 9955 mContext.sendBroadcastAsUser(intent, user, 9956 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9957 } 9958 9959 private ComponentName matchComponentForVerifier(String packageName, 9960 List<ResolveInfo> receivers) { 9961 ActivityInfo targetReceiver = null; 9962 9963 final int NR = receivers.size(); 9964 for (int i = 0; i < NR; i++) { 9965 final ResolveInfo info = receivers.get(i); 9966 if (info.activityInfo == null) { 9967 continue; 9968 } 9969 9970 if (packageName.equals(info.activityInfo.packageName)) { 9971 targetReceiver = info.activityInfo; 9972 break; 9973 } 9974 } 9975 9976 if (targetReceiver == null) { 9977 return null; 9978 } 9979 9980 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9981 } 9982 9983 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9984 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9985 if (pkgInfo.verifiers.length == 0) { 9986 return null; 9987 } 9988 9989 final int N = pkgInfo.verifiers.length; 9990 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9991 for (int i = 0; i < N; i++) { 9992 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9993 9994 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9995 receivers); 9996 if (comp == null) { 9997 continue; 9998 } 9999 10000 final int verifierUid = getUidForVerifier(verifierInfo); 10001 if (verifierUid == -1) { 10002 continue; 10003 } 10004 10005 if (DEBUG_VERIFY) { 10006 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10007 + " with the correct signature"); 10008 } 10009 sufficientVerifiers.add(comp); 10010 verificationState.addSufficientVerifier(verifierUid); 10011 } 10012 10013 return sufficientVerifiers; 10014 } 10015 10016 private int getUidForVerifier(VerifierInfo verifierInfo) { 10017 synchronized (mPackages) { 10018 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10019 if (pkg == null) { 10020 return -1; 10021 } else if (pkg.mSignatures.length != 1) { 10022 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10023 + " has more than one signature; ignoring"); 10024 return -1; 10025 } 10026 10027 /* 10028 * If the public key of the package's signature does not match 10029 * our expected public key, then this is a different package and 10030 * we should skip. 10031 */ 10032 10033 final byte[] expectedPublicKey; 10034 try { 10035 final Signature verifierSig = pkg.mSignatures[0]; 10036 final PublicKey publicKey = verifierSig.getPublicKey(); 10037 expectedPublicKey = publicKey.getEncoded(); 10038 } catch (CertificateException e) { 10039 return -1; 10040 } 10041 10042 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10043 10044 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10045 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10046 + " does not have the expected public key; ignoring"); 10047 return -1; 10048 } 10049 10050 return pkg.applicationInfo.uid; 10051 } 10052 } 10053 10054 @Override 10055 public void finishPackageInstall(int token) { 10056 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10057 10058 if (DEBUG_INSTALL) { 10059 Slog.v(TAG, "BM finishing package install for " + token); 10060 } 10061 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10062 10063 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10064 mHandler.sendMessage(msg); 10065 } 10066 10067 /** 10068 * Get the verification agent timeout. 10069 * 10070 * @return verification timeout in milliseconds 10071 */ 10072 private long getVerificationTimeout() { 10073 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10074 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10075 DEFAULT_VERIFICATION_TIMEOUT); 10076 } 10077 10078 /** 10079 * Get the default verification agent response code. 10080 * 10081 * @return default verification response code 10082 */ 10083 private int getDefaultVerificationResponse() { 10084 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10085 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10086 DEFAULT_VERIFICATION_RESPONSE); 10087 } 10088 10089 /** 10090 * Check whether or not package verification has been enabled. 10091 * 10092 * @return true if verification should be performed 10093 */ 10094 private boolean isVerificationEnabled(int userId, int installFlags) { 10095 if (!DEFAULT_VERIFY_ENABLE) { 10096 return false; 10097 } 10098 // TODO: fix b/25118622; don't bypass verification 10099 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10100 return false; 10101 } 10102 10103 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10104 10105 // Check if installing from ADB 10106 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10107 // Do not run verification in a test harness environment 10108 if (ActivityManager.isRunningInTestHarness()) { 10109 return false; 10110 } 10111 if (ensureVerifyAppsEnabled) { 10112 return true; 10113 } 10114 // Check if the developer does not want package verification for ADB installs 10115 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10116 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10117 return false; 10118 } 10119 } 10120 10121 if (ensureVerifyAppsEnabled) { 10122 return true; 10123 } 10124 10125 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10126 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10127 } 10128 10129 @Override 10130 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10131 throws RemoteException { 10132 mContext.enforceCallingOrSelfPermission( 10133 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10134 "Only intentfilter verification agents can verify applications"); 10135 10136 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10137 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10138 Binder.getCallingUid(), verificationCode, failedDomains); 10139 msg.arg1 = id; 10140 msg.obj = response; 10141 mHandler.sendMessage(msg); 10142 } 10143 10144 @Override 10145 public int getIntentVerificationStatus(String packageName, int userId) { 10146 synchronized (mPackages) { 10147 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10148 } 10149 } 10150 10151 @Override 10152 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10153 mContext.enforceCallingOrSelfPermission( 10154 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10155 10156 boolean result = false; 10157 synchronized (mPackages) { 10158 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10159 } 10160 if (result) { 10161 scheduleWritePackageRestrictionsLocked(userId); 10162 } 10163 return result; 10164 } 10165 10166 @Override 10167 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10168 synchronized (mPackages) { 10169 return mSettings.getIntentFilterVerificationsLPr(packageName); 10170 } 10171 } 10172 10173 @Override 10174 public List<IntentFilter> getAllIntentFilters(String packageName) { 10175 if (TextUtils.isEmpty(packageName)) { 10176 return Collections.<IntentFilter>emptyList(); 10177 } 10178 synchronized (mPackages) { 10179 PackageParser.Package pkg = mPackages.get(packageName); 10180 if (pkg == null || pkg.activities == null) { 10181 return Collections.<IntentFilter>emptyList(); 10182 } 10183 final int count = pkg.activities.size(); 10184 ArrayList<IntentFilter> result = new ArrayList<>(); 10185 for (int n=0; n<count; n++) { 10186 PackageParser.Activity activity = pkg.activities.get(n); 10187 if (activity.intents != null || activity.intents.size() > 0) { 10188 result.addAll(activity.intents); 10189 } 10190 } 10191 return result; 10192 } 10193 } 10194 10195 @Override 10196 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10197 mContext.enforceCallingOrSelfPermission( 10198 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10199 10200 synchronized (mPackages) { 10201 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10202 if (packageName != null) { 10203 result |= updateIntentVerificationStatus(packageName, 10204 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10205 userId); 10206 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10207 packageName, userId); 10208 } 10209 return result; 10210 } 10211 } 10212 10213 @Override 10214 public String getDefaultBrowserPackageName(int userId) { 10215 synchronized (mPackages) { 10216 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10217 } 10218 } 10219 10220 /** 10221 * Get the "allow unknown sources" setting. 10222 * 10223 * @return the current "allow unknown sources" setting 10224 */ 10225 private int getUnknownSourcesSettings() { 10226 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10227 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10228 -1); 10229 } 10230 10231 @Override 10232 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10233 final int uid = Binder.getCallingUid(); 10234 // writer 10235 synchronized (mPackages) { 10236 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10237 if (targetPackageSetting == null) { 10238 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10239 } 10240 10241 PackageSetting installerPackageSetting; 10242 if (installerPackageName != null) { 10243 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10244 if (installerPackageSetting == null) { 10245 throw new IllegalArgumentException("Unknown installer package: " 10246 + installerPackageName); 10247 } 10248 } else { 10249 installerPackageSetting = null; 10250 } 10251 10252 Signature[] callerSignature; 10253 Object obj = mSettings.getUserIdLPr(uid); 10254 if (obj != null) { 10255 if (obj instanceof SharedUserSetting) { 10256 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10257 } else if (obj instanceof PackageSetting) { 10258 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10259 } else { 10260 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10261 } 10262 } else { 10263 throw new SecurityException("Unknown calling uid " + uid); 10264 } 10265 10266 // Verify: can't set installerPackageName to a package that is 10267 // not signed with the same cert as the caller. 10268 if (installerPackageSetting != null) { 10269 if (compareSignatures(callerSignature, 10270 installerPackageSetting.signatures.mSignatures) 10271 != PackageManager.SIGNATURE_MATCH) { 10272 throw new SecurityException( 10273 "Caller does not have same cert as new installer package " 10274 + installerPackageName); 10275 } 10276 } 10277 10278 // Verify: if target already has an installer package, it must 10279 // be signed with the same cert as the caller. 10280 if (targetPackageSetting.installerPackageName != null) { 10281 PackageSetting setting = mSettings.mPackages.get( 10282 targetPackageSetting.installerPackageName); 10283 // If the currently set package isn't valid, then it's always 10284 // okay to change it. 10285 if (setting != null) { 10286 if (compareSignatures(callerSignature, 10287 setting.signatures.mSignatures) 10288 != PackageManager.SIGNATURE_MATCH) { 10289 throw new SecurityException( 10290 "Caller does not have same cert as old installer package " 10291 + targetPackageSetting.installerPackageName); 10292 } 10293 } 10294 } 10295 10296 // Okay! 10297 targetPackageSetting.installerPackageName = installerPackageName; 10298 scheduleWriteSettingsLocked(); 10299 } 10300 } 10301 10302 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10303 // Queue up an async operation since the package installation may take a little while. 10304 mHandler.post(new Runnable() { 10305 public void run() { 10306 mHandler.removeCallbacks(this); 10307 // Result object to be returned 10308 PackageInstalledInfo res = new PackageInstalledInfo(); 10309 res.returnCode = currentStatus; 10310 res.uid = -1; 10311 res.pkg = null; 10312 res.removedInfo = new PackageRemovedInfo(); 10313 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10314 args.doPreInstall(res.returnCode); 10315 synchronized (mInstallLock) { 10316 installPackageTracedLI(args, res); 10317 } 10318 args.doPostInstall(res.returnCode, res.uid); 10319 } 10320 10321 // A restore should be performed at this point if (a) the install 10322 // succeeded, (b) the operation is not an update, and (c) the new 10323 // package has not opted out of backup participation. 10324 final boolean update = res.removedInfo.removedPackage != null; 10325 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10326 boolean doRestore = !update 10327 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10328 10329 // Set up the post-install work request bookkeeping. This will be used 10330 // and cleaned up by the post-install event handling regardless of whether 10331 // there's a restore pass performed. Token values are >= 1. 10332 int token; 10333 if (mNextInstallToken < 0) mNextInstallToken = 1; 10334 token = mNextInstallToken++; 10335 10336 PostInstallData data = new PostInstallData(args, res); 10337 mRunningInstalls.put(token, data); 10338 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10339 10340 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10341 // Pass responsibility to the Backup Manager. It will perform a 10342 // restore if appropriate, then pass responsibility back to the 10343 // Package Manager to run the post-install observer callbacks 10344 // and broadcasts. 10345 IBackupManager bm = IBackupManager.Stub.asInterface( 10346 ServiceManager.getService(Context.BACKUP_SERVICE)); 10347 if (bm != null) { 10348 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10349 + " to BM for possible restore"); 10350 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10351 try { 10352 // TODO: http://b/22388012 10353 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10354 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10355 } else { 10356 doRestore = false; 10357 } 10358 } catch (RemoteException e) { 10359 // can't happen; the backup manager is local 10360 } catch (Exception e) { 10361 Slog.e(TAG, "Exception trying to enqueue restore", e); 10362 doRestore = false; 10363 } 10364 } else { 10365 Slog.e(TAG, "Backup Manager not found!"); 10366 doRestore = false; 10367 } 10368 } 10369 10370 if (!doRestore) { 10371 // No restore possible, or the Backup Manager was mysteriously not 10372 // available -- just fire the post-install work request directly. 10373 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10374 10375 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10376 10377 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10378 mHandler.sendMessage(msg); 10379 } 10380 } 10381 }); 10382 } 10383 10384 private abstract class HandlerParams { 10385 private static final int MAX_RETRIES = 4; 10386 10387 /** 10388 * Number of times startCopy() has been attempted and had a non-fatal 10389 * error. 10390 */ 10391 private int mRetries = 0; 10392 10393 /** User handle for the user requesting the information or installation. */ 10394 private final UserHandle mUser; 10395 String traceMethod; 10396 int traceCookie; 10397 10398 HandlerParams(UserHandle user) { 10399 mUser = user; 10400 } 10401 10402 UserHandle getUser() { 10403 return mUser; 10404 } 10405 10406 HandlerParams setTraceMethod(String traceMethod) { 10407 this.traceMethod = traceMethod; 10408 return this; 10409 } 10410 10411 HandlerParams setTraceCookie(int traceCookie) { 10412 this.traceCookie = traceCookie; 10413 return this; 10414 } 10415 10416 final boolean startCopy() { 10417 boolean res; 10418 try { 10419 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10420 10421 if (++mRetries > MAX_RETRIES) { 10422 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10423 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10424 handleServiceError(); 10425 return false; 10426 } else { 10427 handleStartCopy(); 10428 res = true; 10429 } 10430 } catch (RemoteException e) { 10431 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10432 mHandler.sendEmptyMessage(MCS_RECONNECT); 10433 res = false; 10434 } 10435 handleReturnCode(); 10436 return res; 10437 } 10438 10439 final void serviceError() { 10440 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10441 handleServiceError(); 10442 handleReturnCode(); 10443 } 10444 10445 abstract void handleStartCopy() throws RemoteException; 10446 abstract void handleServiceError(); 10447 abstract void handleReturnCode(); 10448 } 10449 10450 class MeasureParams extends HandlerParams { 10451 private final PackageStats mStats; 10452 private boolean mSuccess; 10453 10454 private final IPackageStatsObserver mObserver; 10455 10456 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10457 super(new UserHandle(stats.userHandle)); 10458 mObserver = observer; 10459 mStats = stats; 10460 } 10461 10462 @Override 10463 public String toString() { 10464 return "MeasureParams{" 10465 + Integer.toHexString(System.identityHashCode(this)) 10466 + " " + mStats.packageName + "}"; 10467 } 10468 10469 @Override 10470 void handleStartCopy() throws RemoteException { 10471 synchronized (mInstallLock) { 10472 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10473 } 10474 10475 if (mSuccess) { 10476 final boolean mounted; 10477 if (Environment.isExternalStorageEmulated()) { 10478 mounted = true; 10479 } else { 10480 final String status = Environment.getExternalStorageState(); 10481 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10482 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10483 } 10484 10485 if (mounted) { 10486 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10487 10488 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10489 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10490 10491 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10492 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10493 10494 // Always subtract cache size, since it's a subdirectory 10495 mStats.externalDataSize -= mStats.externalCacheSize; 10496 10497 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10498 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10499 10500 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10501 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10502 } 10503 } 10504 } 10505 10506 @Override 10507 void handleReturnCode() { 10508 if (mObserver != null) { 10509 try { 10510 mObserver.onGetStatsCompleted(mStats, mSuccess); 10511 } catch (RemoteException e) { 10512 Slog.i(TAG, "Observer no longer exists."); 10513 } 10514 } 10515 } 10516 10517 @Override 10518 void handleServiceError() { 10519 Slog.e(TAG, "Could not measure application " + mStats.packageName 10520 + " external storage"); 10521 } 10522 } 10523 10524 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10525 throws RemoteException { 10526 long result = 0; 10527 for (File path : paths) { 10528 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10529 } 10530 return result; 10531 } 10532 10533 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10534 for (File path : paths) { 10535 try { 10536 mcs.clearDirectory(path.getAbsolutePath()); 10537 } catch (RemoteException e) { 10538 } 10539 } 10540 } 10541 10542 static class OriginInfo { 10543 /** 10544 * Location where install is coming from, before it has been 10545 * copied/renamed into place. This could be a single monolithic APK 10546 * file, or a cluster directory. This location may be untrusted. 10547 */ 10548 final File file; 10549 final String cid; 10550 10551 /** 10552 * Flag indicating that {@link #file} or {@link #cid} has already been 10553 * staged, meaning downstream users don't need to defensively copy the 10554 * contents. 10555 */ 10556 final boolean staged; 10557 10558 /** 10559 * Flag indicating that {@link #file} or {@link #cid} is an already 10560 * installed app that is being moved. 10561 */ 10562 final boolean existing; 10563 10564 final String resolvedPath; 10565 final File resolvedFile; 10566 10567 static OriginInfo fromNothing() { 10568 return new OriginInfo(null, null, false, false); 10569 } 10570 10571 static OriginInfo fromUntrustedFile(File file) { 10572 return new OriginInfo(file, null, false, false); 10573 } 10574 10575 static OriginInfo fromExistingFile(File file) { 10576 return new OriginInfo(file, null, false, true); 10577 } 10578 10579 static OriginInfo fromStagedFile(File file) { 10580 return new OriginInfo(file, null, true, false); 10581 } 10582 10583 static OriginInfo fromStagedContainer(String cid) { 10584 return new OriginInfo(null, cid, true, false); 10585 } 10586 10587 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10588 this.file = file; 10589 this.cid = cid; 10590 this.staged = staged; 10591 this.existing = existing; 10592 10593 if (cid != null) { 10594 resolvedPath = PackageHelper.getSdDir(cid); 10595 resolvedFile = new File(resolvedPath); 10596 } else if (file != null) { 10597 resolvedPath = file.getAbsolutePath(); 10598 resolvedFile = file; 10599 } else { 10600 resolvedPath = null; 10601 resolvedFile = null; 10602 } 10603 } 10604 } 10605 10606 class MoveInfo { 10607 final int moveId; 10608 final String fromUuid; 10609 final String toUuid; 10610 final String packageName; 10611 final String dataAppName; 10612 final int appId; 10613 final String seinfo; 10614 10615 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10616 String dataAppName, int appId, String seinfo) { 10617 this.moveId = moveId; 10618 this.fromUuid = fromUuid; 10619 this.toUuid = toUuid; 10620 this.packageName = packageName; 10621 this.dataAppName = dataAppName; 10622 this.appId = appId; 10623 this.seinfo = seinfo; 10624 } 10625 } 10626 10627 class InstallParams extends HandlerParams { 10628 final OriginInfo origin; 10629 final MoveInfo move; 10630 final IPackageInstallObserver2 observer; 10631 int installFlags; 10632 final String installerPackageName; 10633 final String volumeUuid; 10634 final VerificationParams verificationParams; 10635 private InstallArgs mArgs; 10636 private int mRet; 10637 final String packageAbiOverride; 10638 final String[] grantedRuntimePermissions; 10639 10640 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10641 int installFlags, String installerPackageName, String volumeUuid, 10642 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10643 String[] grantedPermissions) { 10644 super(user); 10645 this.origin = origin; 10646 this.move = move; 10647 this.observer = observer; 10648 this.installFlags = installFlags; 10649 this.installerPackageName = installerPackageName; 10650 this.volumeUuid = volumeUuid; 10651 this.verificationParams = verificationParams; 10652 this.packageAbiOverride = packageAbiOverride; 10653 this.grantedRuntimePermissions = grantedPermissions; 10654 } 10655 10656 @Override 10657 public String toString() { 10658 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10659 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10660 } 10661 10662 public ManifestDigest getManifestDigest() { 10663 if (verificationParams == null) { 10664 return null; 10665 } 10666 return verificationParams.getManifestDigest(); 10667 } 10668 10669 private int installLocationPolicy(PackageInfoLite pkgLite) { 10670 String packageName = pkgLite.packageName; 10671 int installLocation = pkgLite.installLocation; 10672 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10673 // reader 10674 synchronized (mPackages) { 10675 PackageParser.Package pkg = mPackages.get(packageName); 10676 if (pkg != null) { 10677 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10678 // Check for downgrading. 10679 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10680 try { 10681 checkDowngrade(pkg, pkgLite); 10682 } catch (PackageManagerException e) { 10683 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10684 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10685 } 10686 } 10687 // Check for updated system application. 10688 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10689 if (onSd) { 10690 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10691 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10692 } 10693 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10694 } else { 10695 if (onSd) { 10696 // Install flag overrides everything. 10697 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10698 } 10699 // If current upgrade specifies particular preference 10700 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10701 // Application explicitly specified internal. 10702 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10703 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10704 // App explictly prefers external. Let policy decide 10705 } else { 10706 // Prefer previous location 10707 if (isExternal(pkg)) { 10708 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10709 } 10710 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10711 } 10712 } 10713 } else { 10714 // Invalid install. Return error code 10715 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10716 } 10717 } 10718 } 10719 // All the special cases have been taken care of. 10720 // Return result based on recommended install location. 10721 if (onSd) { 10722 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10723 } 10724 return pkgLite.recommendedInstallLocation; 10725 } 10726 10727 /* 10728 * Invoke remote method to get package information and install 10729 * location values. Override install location based on default 10730 * policy if needed and then create install arguments based 10731 * on the install location. 10732 */ 10733 public void handleStartCopy() throws RemoteException { 10734 int ret = PackageManager.INSTALL_SUCCEEDED; 10735 10736 // If we're already staged, we've firmly committed to an install location 10737 if (origin.staged) { 10738 if (origin.file != null) { 10739 installFlags |= PackageManager.INSTALL_INTERNAL; 10740 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10741 } else if (origin.cid != null) { 10742 installFlags |= PackageManager.INSTALL_EXTERNAL; 10743 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10744 } else { 10745 throw new IllegalStateException("Invalid stage location"); 10746 } 10747 } 10748 10749 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10750 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10751 PackageInfoLite pkgLite = null; 10752 10753 if (onInt && onSd) { 10754 // Check if both bits are set. 10755 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10756 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10757 } else { 10758 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10759 packageAbiOverride); 10760 10761 /* 10762 * If we have too little free space, try to free cache 10763 * before giving up. 10764 */ 10765 if (!origin.staged && pkgLite.recommendedInstallLocation 10766 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10767 // TODO: focus freeing disk space on the target device 10768 final StorageManager storage = StorageManager.from(mContext); 10769 final long lowThreshold = storage.getStorageLowBytes( 10770 Environment.getDataDirectory()); 10771 10772 final long sizeBytes = mContainerService.calculateInstalledSize( 10773 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10774 10775 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10776 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10777 installFlags, packageAbiOverride); 10778 } 10779 10780 /* 10781 * The cache free must have deleted the file we 10782 * downloaded to install. 10783 * 10784 * TODO: fix the "freeCache" call to not delete 10785 * the file we care about. 10786 */ 10787 if (pkgLite.recommendedInstallLocation 10788 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10789 pkgLite.recommendedInstallLocation 10790 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10791 } 10792 } 10793 } 10794 10795 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10796 int loc = pkgLite.recommendedInstallLocation; 10797 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10798 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10799 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10800 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10801 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10802 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10803 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10804 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10805 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10806 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10807 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10808 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10809 } else { 10810 // Override with defaults if needed. 10811 loc = installLocationPolicy(pkgLite); 10812 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10813 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10814 } else if (!onSd && !onInt) { 10815 // Override install location with flags 10816 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10817 // Set the flag to install on external media. 10818 installFlags |= PackageManager.INSTALL_EXTERNAL; 10819 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10820 } else { 10821 // Make sure the flag for installing on external 10822 // media is unset 10823 installFlags |= PackageManager.INSTALL_INTERNAL; 10824 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10825 } 10826 } 10827 } 10828 } 10829 10830 final InstallArgs args = createInstallArgs(this); 10831 mArgs = args; 10832 10833 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10834 // TODO: http://b/22976637 10835 // Apps installed for "all" users use the device owner to verify the app 10836 UserHandle verifierUser = getUser(); 10837 if (verifierUser == UserHandle.ALL) { 10838 verifierUser = UserHandle.SYSTEM; 10839 } 10840 10841 /* 10842 * Determine if we have any installed package verifiers. If we 10843 * do, then we'll defer to them to verify the packages. 10844 */ 10845 final int requiredUid = mRequiredVerifierPackage == null ? -1 10846 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10847 if (!origin.existing && requiredUid != -1 10848 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10849 final Intent verification = new Intent( 10850 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10851 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10852 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10853 PACKAGE_MIME_TYPE); 10854 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10855 10856 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10857 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10858 verifierUser.getIdentifier()); 10859 10860 if (DEBUG_VERIFY) { 10861 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10862 + verification.toString() + " with " + pkgLite.verifiers.length 10863 + " optional verifiers"); 10864 } 10865 10866 final int verificationId = mPendingVerificationToken++; 10867 10868 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10869 10870 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10871 installerPackageName); 10872 10873 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10874 installFlags); 10875 10876 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10877 pkgLite.packageName); 10878 10879 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10880 pkgLite.versionCode); 10881 10882 if (verificationParams != null) { 10883 if (verificationParams.getVerificationURI() != null) { 10884 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10885 verificationParams.getVerificationURI()); 10886 } 10887 if (verificationParams.getOriginatingURI() != null) { 10888 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10889 verificationParams.getOriginatingURI()); 10890 } 10891 if (verificationParams.getReferrer() != null) { 10892 verification.putExtra(Intent.EXTRA_REFERRER, 10893 verificationParams.getReferrer()); 10894 } 10895 if (verificationParams.getOriginatingUid() >= 0) { 10896 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10897 verificationParams.getOriginatingUid()); 10898 } 10899 if (verificationParams.getInstallerUid() >= 0) { 10900 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10901 verificationParams.getInstallerUid()); 10902 } 10903 } 10904 10905 final PackageVerificationState verificationState = new PackageVerificationState( 10906 requiredUid, args); 10907 10908 mPendingVerification.append(verificationId, verificationState); 10909 10910 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10911 receivers, verificationState); 10912 10913 /* 10914 * If any sufficient verifiers were listed in the package 10915 * manifest, attempt to ask them. 10916 */ 10917 if (sufficientVerifiers != null) { 10918 final int N = sufficientVerifiers.size(); 10919 if (N == 0) { 10920 Slog.i(TAG, "Additional verifiers required, but none installed."); 10921 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10922 } else { 10923 for (int i = 0; i < N; i++) { 10924 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10925 10926 final Intent sufficientIntent = new Intent(verification); 10927 sufficientIntent.setComponent(verifierComponent); 10928 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10929 } 10930 } 10931 } 10932 10933 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10934 mRequiredVerifierPackage, receivers); 10935 if (ret == PackageManager.INSTALL_SUCCEEDED 10936 && mRequiredVerifierPackage != null) { 10937 Trace.asyncTraceBegin( 10938 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10939 /* 10940 * Send the intent to the required verification agent, 10941 * but only start the verification timeout after the 10942 * target BroadcastReceivers have run. 10943 */ 10944 verification.setComponent(requiredVerifierComponent); 10945 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10946 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10947 new BroadcastReceiver() { 10948 @Override 10949 public void onReceive(Context context, Intent intent) { 10950 final Message msg = mHandler 10951 .obtainMessage(CHECK_PENDING_VERIFICATION); 10952 msg.arg1 = verificationId; 10953 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10954 } 10955 }, null, 0, null, null); 10956 10957 /* 10958 * We don't want the copy to proceed until verification 10959 * succeeds, so null out this field. 10960 */ 10961 mArgs = null; 10962 } 10963 } else { 10964 /* 10965 * No package verification is enabled, so immediately start 10966 * the remote call to initiate copy using temporary file. 10967 */ 10968 ret = args.copyApk(mContainerService, true); 10969 } 10970 } 10971 10972 mRet = ret; 10973 } 10974 10975 @Override 10976 void handleReturnCode() { 10977 // If mArgs is null, then MCS couldn't be reached. When it 10978 // reconnects, it will try again to install. At that point, this 10979 // will succeed. 10980 if (mArgs != null) { 10981 processPendingInstall(mArgs, mRet); 10982 } 10983 } 10984 10985 @Override 10986 void handleServiceError() { 10987 mArgs = createInstallArgs(this); 10988 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10989 } 10990 10991 public boolean isForwardLocked() { 10992 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10993 } 10994 } 10995 10996 /** 10997 * Used during creation of InstallArgs 10998 * 10999 * @param installFlags package installation flags 11000 * @return true if should be installed on external storage 11001 */ 11002 private static boolean installOnExternalAsec(int installFlags) { 11003 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11004 return false; 11005 } 11006 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11007 return true; 11008 } 11009 return false; 11010 } 11011 11012 /** 11013 * Used during creation of InstallArgs 11014 * 11015 * @param installFlags package installation flags 11016 * @return true if should be installed as forward locked 11017 */ 11018 private static boolean installForwardLocked(int installFlags) { 11019 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11020 } 11021 11022 private InstallArgs createInstallArgs(InstallParams params) { 11023 if (params.move != null) { 11024 return new MoveInstallArgs(params); 11025 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11026 return new AsecInstallArgs(params); 11027 } else { 11028 return new FileInstallArgs(params); 11029 } 11030 } 11031 11032 /** 11033 * Create args that describe an existing installed package. Typically used 11034 * when cleaning up old installs, or used as a move source. 11035 */ 11036 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11037 String resourcePath, String[] instructionSets) { 11038 final boolean isInAsec; 11039 if (installOnExternalAsec(installFlags)) { 11040 /* Apps on SD card are always in ASEC containers. */ 11041 isInAsec = true; 11042 } else if (installForwardLocked(installFlags) 11043 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11044 /* 11045 * Forward-locked apps are only in ASEC containers if they're the 11046 * new style 11047 */ 11048 isInAsec = true; 11049 } else { 11050 isInAsec = false; 11051 } 11052 11053 if (isInAsec) { 11054 return new AsecInstallArgs(codePath, instructionSets, 11055 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11056 } else { 11057 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11058 } 11059 } 11060 11061 static abstract class InstallArgs { 11062 /** @see InstallParams#origin */ 11063 final OriginInfo origin; 11064 /** @see InstallParams#move */ 11065 final MoveInfo move; 11066 11067 final IPackageInstallObserver2 observer; 11068 // Always refers to PackageManager flags only 11069 final int installFlags; 11070 final String installerPackageName; 11071 final String volumeUuid; 11072 final ManifestDigest manifestDigest; 11073 final UserHandle user; 11074 final String abiOverride; 11075 final String[] installGrantPermissions; 11076 /** If non-null, drop an async trace when the install completes */ 11077 final String traceMethod; 11078 final int traceCookie; 11079 11080 // The list of instruction sets supported by this app. This is currently 11081 // only used during the rmdex() phase to clean up resources. We can get rid of this 11082 // if we move dex files under the common app path. 11083 /* nullable */ String[] instructionSets; 11084 11085 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11086 int installFlags, String installerPackageName, String volumeUuid, 11087 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11088 String abiOverride, String[] installGrantPermissions, 11089 String traceMethod, int traceCookie) { 11090 this.origin = origin; 11091 this.move = move; 11092 this.installFlags = installFlags; 11093 this.observer = observer; 11094 this.installerPackageName = installerPackageName; 11095 this.volumeUuid = volumeUuid; 11096 this.manifestDigest = manifestDigest; 11097 this.user = user; 11098 this.instructionSets = instructionSets; 11099 this.abiOverride = abiOverride; 11100 this.installGrantPermissions = installGrantPermissions; 11101 this.traceMethod = traceMethod; 11102 this.traceCookie = traceCookie; 11103 } 11104 11105 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11106 abstract int doPreInstall(int status); 11107 11108 /** 11109 * Rename package into final resting place. All paths on the given 11110 * scanned package should be updated to reflect the rename. 11111 */ 11112 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11113 abstract int doPostInstall(int status, int uid); 11114 11115 /** @see PackageSettingBase#codePathString */ 11116 abstract String getCodePath(); 11117 /** @see PackageSettingBase#resourcePathString */ 11118 abstract String getResourcePath(); 11119 11120 // Need installer lock especially for dex file removal. 11121 abstract void cleanUpResourcesLI(); 11122 abstract boolean doPostDeleteLI(boolean delete); 11123 11124 /** 11125 * Called before the source arguments are copied. This is used mostly 11126 * for MoveParams when it needs to read the source file to put it in the 11127 * destination. 11128 */ 11129 int doPreCopy() { 11130 return PackageManager.INSTALL_SUCCEEDED; 11131 } 11132 11133 /** 11134 * Called after the source arguments are copied. This is used mostly for 11135 * MoveParams when it needs to read the source file to put it in the 11136 * destination. 11137 * 11138 * @return 11139 */ 11140 int doPostCopy(int uid) { 11141 return PackageManager.INSTALL_SUCCEEDED; 11142 } 11143 11144 protected boolean isFwdLocked() { 11145 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11146 } 11147 11148 protected boolean isExternalAsec() { 11149 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11150 } 11151 11152 UserHandle getUser() { 11153 return user; 11154 } 11155 } 11156 11157 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11158 if (!allCodePaths.isEmpty()) { 11159 if (instructionSets == null) { 11160 throw new IllegalStateException("instructionSet == null"); 11161 } 11162 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11163 for (String codePath : allCodePaths) { 11164 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11165 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11166 if (retCode < 0) { 11167 Slog.w(TAG, "Couldn't remove dex file for package: " 11168 + " at location " + codePath + ", retcode=" + retCode); 11169 // we don't consider this to be a failure of the core package deletion 11170 } 11171 } 11172 } 11173 } 11174 } 11175 11176 /** 11177 * Logic to handle installation of non-ASEC applications, including copying 11178 * and renaming logic. 11179 */ 11180 class FileInstallArgs extends InstallArgs { 11181 private File codeFile; 11182 private File resourceFile; 11183 11184 // Example topology: 11185 // /data/app/com.example/base.apk 11186 // /data/app/com.example/split_foo.apk 11187 // /data/app/com.example/lib/arm/libfoo.so 11188 // /data/app/com.example/lib/arm64/libfoo.so 11189 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11190 11191 /** New install */ 11192 FileInstallArgs(InstallParams params) { 11193 super(params.origin, params.move, params.observer, params.installFlags, 11194 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11195 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11196 params.grantedRuntimePermissions, 11197 params.traceMethod, params.traceCookie); 11198 if (isFwdLocked()) { 11199 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11200 } 11201 } 11202 11203 /** Existing install */ 11204 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11205 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11206 null, null, null, 0); 11207 this.codeFile = (codePath != null) ? new File(codePath) : null; 11208 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11209 } 11210 11211 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11212 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11213 try { 11214 return doCopyApk(imcs, temp); 11215 } finally { 11216 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11217 } 11218 } 11219 11220 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11221 if (origin.staged) { 11222 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11223 codeFile = origin.file; 11224 resourceFile = origin.file; 11225 return PackageManager.INSTALL_SUCCEEDED; 11226 } 11227 11228 try { 11229 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11230 codeFile = tempDir; 11231 resourceFile = tempDir; 11232 } catch (IOException e) { 11233 Slog.w(TAG, "Failed to create copy file: " + e); 11234 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11235 } 11236 11237 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11238 @Override 11239 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11240 if (!FileUtils.isValidExtFilename(name)) { 11241 throw new IllegalArgumentException("Invalid filename: " + name); 11242 } 11243 try { 11244 final File file = new File(codeFile, name); 11245 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11246 O_RDWR | O_CREAT, 0644); 11247 Os.chmod(file.getAbsolutePath(), 0644); 11248 return new ParcelFileDescriptor(fd); 11249 } catch (ErrnoException e) { 11250 throw new RemoteException("Failed to open: " + e.getMessage()); 11251 } 11252 } 11253 }; 11254 11255 int ret = PackageManager.INSTALL_SUCCEEDED; 11256 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11257 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11258 Slog.e(TAG, "Failed to copy package"); 11259 return ret; 11260 } 11261 11262 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11263 NativeLibraryHelper.Handle handle = null; 11264 try { 11265 handle = NativeLibraryHelper.Handle.create(codeFile); 11266 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11267 abiOverride); 11268 } catch (IOException e) { 11269 Slog.e(TAG, "Copying native libraries failed", e); 11270 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11271 } finally { 11272 IoUtils.closeQuietly(handle); 11273 } 11274 11275 return ret; 11276 } 11277 11278 int doPreInstall(int status) { 11279 if (status != PackageManager.INSTALL_SUCCEEDED) { 11280 cleanUp(); 11281 } 11282 return status; 11283 } 11284 11285 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11286 if (status != PackageManager.INSTALL_SUCCEEDED) { 11287 cleanUp(); 11288 return false; 11289 } 11290 11291 final File targetDir = codeFile.getParentFile(); 11292 final File beforeCodeFile = codeFile; 11293 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11294 11295 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11296 try { 11297 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11298 } catch (ErrnoException e) { 11299 Slog.w(TAG, "Failed to rename", e); 11300 return false; 11301 } 11302 11303 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11304 Slog.w(TAG, "Failed to restorecon"); 11305 return false; 11306 } 11307 11308 // Reflect the rename internally 11309 codeFile = afterCodeFile; 11310 resourceFile = afterCodeFile; 11311 11312 // Reflect the rename in scanned details 11313 pkg.codePath = afterCodeFile.getAbsolutePath(); 11314 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11315 pkg.baseCodePath); 11316 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11317 pkg.splitCodePaths); 11318 11319 // Reflect the rename in app info 11320 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11321 pkg.applicationInfo.setCodePath(pkg.codePath); 11322 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11323 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11324 pkg.applicationInfo.setResourcePath(pkg.codePath); 11325 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11326 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11327 11328 return true; 11329 } 11330 11331 int doPostInstall(int status, int uid) { 11332 if (status != PackageManager.INSTALL_SUCCEEDED) { 11333 cleanUp(); 11334 } 11335 return status; 11336 } 11337 11338 @Override 11339 String getCodePath() { 11340 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11341 } 11342 11343 @Override 11344 String getResourcePath() { 11345 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11346 } 11347 11348 private boolean cleanUp() { 11349 if (codeFile == null || !codeFile.exists()) { 11350 return false; 11351 } 11352 11353 if (codeFile.isDirectory()) { 11354 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11355 } else { 11356 codeFile.delete(); 11357 } 11358 11359 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11360 resourceFile.delete(); 11361 } 11362 11363 return true; 11364 } 11365 11366 void cleanUpResourcesLI() { 11367 // Try enumerating all code paths before deleting 11368 List<String> allCodePaths = Collections.EMPTY_LIST; 11369 if (codeFile != null && codeFile.exists()) { 11370 try { 11371 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11372 allCodePaths = pkg.getAllCodePaths(); 11373 } catch (PackageParserException e) { 11374 // Ignored; we tried our best 11375 } 11376 } 11377 11378 cleanUp(); 11379 removeDexFiles(allCodePaths, instructionSets); 11380 } 11381 11382 boolean doPostDeleteLI(boolean delete) { 11383 // XXX err, shouldn't we respect the delete flag? 11384 cleanUpResourcesLI(); 11385 return true; 11386 } 11387 } 11388 11389 private boolean isAsecExternal(String cid) { 11390 final String asecPath = PackageHelper.getSdFilesystem(cid); 11391 return !asecPath.startsWith(mAsecInternalPath); 11392 } 11393 11394 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11395 PackageManagerException { 11396 if (copyRet < 0) { 11397 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11398 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11399 throw new PackageManagerException(copyRet, message); 11400 } 11401 } 11402 } 11403 11404 /** 11405 * Extract the MountService "container ID" from the full code path of an 11406 * .apk. 11407 */ 11408 static String cidFromCodePath(String fullCodePath) { 11409 int eidx = fullCodePath.lastIndexOf("/"); 11410 String subStr1 = fullCodePath.substring(0, eidx); 11411 int sidx = subStr1.lastIndexOf("/"); 11412 return subStr1.substring(sidx+1, eidx); 11413 } 11414 11415 /** 11416 * Logic to handle installation of ASEC applications, including copying and 11417 * renaming logic. 11418 */ 11419 class AsecInstallArgs extends InstallArgs { 11420 static final String RES_FILE_NAME = "pkg.apk"; 11421 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11422 11423 String cid; 11424 String packagePath; 11425 String resourcePath; 11426 11427 /** New install */ 11428 AsecInstallArgs(InstallParams params) { 11429 super(params.origin, params.move, params.observer, params.installFlags, 11430 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11431 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11432 params.grantedRuntimePermissions, 11433 params.traceMethod, params.traceCookie); 11434 } 11435 11436 /** Existing install */ 11437 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11438 boolean isExternal, boolean isForwardLocked) { 11439 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11440 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11441 instructionSets, null, null, null, 0); 11442 // Hackily pretend we're still looking at a full code path 11443 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11444 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11445 } 11446 11447 // Extract cid from fullCodePath 11448 int eidx = fullCodePath.lastIndexOf("/"); 11449 String subStr1 = fullCodePath.substring(0, eidx); 11450 int sidx = subStr1.lastIndexOf("/"); 11451 cid = subStr1.substring(sidx+1, eidx); 11452 setMountPath(subStr1); 11453 } 11454 11455 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11456 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11457 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11458 instructionSets, null, null, null, 0); 11459 this.cid = cid; 11460 setMountPath(PackageHelper.getSdDir(cid)); 11461 } 11462 11463 void createCopyFile() { 11464 cid = mInstallerService.allocateExternalStageCidLegacy(); 11465 } 11466 11467 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11468 if (origin.staged) { 11469 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11470 cid = origin.cid; 11471 setMountPath(PackageHelper.getSdDir(cid)); 11472 return PackageManager.INSTALL_SUCCEEDED; 11473 } 11474 11475 if (temp) { 11476 createCopyFile(); 11477 } else { 11478 /* 11479 * Pre-emptively destroy the container since it's destroyed if 11480 * copying fails due to it existing anyway. 11481 */ 11482 PackageHelper.destroySdDir(cid); 11483 } 11484 11485 final String newMountPath = imcs.copyPackageToContainer( 11486 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11487 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11488 11489 if (newMountPath != null) { 11490 setMountPath(newMountPath); 11491 return PackageManager.INSTALL_SUCCEEDED; 11492 } else { 11493 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11494 } 11495 } 11496 11497 @Override 11498 String getCodePath() { 11499 return packagePath; 11500 } 11501 11502 @Override 11503 String getResourcePath() { 11504 return resourcePath; 11505 } 11506 11507 int doPreInstall(int status) { 11508 if (status != PackageManager.INSTALL_SUCCEEDED) { 11509 // Destroy container 11510 PackageHelper.destroySdDir(cid); 11511 } else { 11512 boolean mounted = PackageHelper.isContainerMounted(cid); 11513 if (!mounted) { 11514 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11515 Process.SYSTEM_UID); 11516 if (newMountPath != null) { 11517 setMountPath(newMountPath); 11518 } else { 11519 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11520 } 11521 } 11522 } 11523 return status; 11524 } 11525 11526 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11527 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11528 String newMountPath = null; 11529 if (PackageHelper.isContainerMounted(cid)) { 11530 // Unmount the container 11531 if (!PackageHelper.unMountSdDir(cid)) { 11532 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11533 return false; 11534 } 11535 } 11536 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11537 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11538 " which might be stale. Will try to clean up."); 11539 // Clean up the stale container and proceed to recreate. 11540 if (!PackageHelper.destroySdDir(newCacheId)) { 11541 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11542 return false; 11543 } 11544 // Successfully cleaned up stale container. Try to rename again. 11545 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11546 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11547 + " inspite of cleaning it up."); 11548 return false; 11549 } 11550 } 11551 if (!PackageHelper.isContainerMounted(newCacheId)) { 11552 Slog.w(TAG, "Mounting container " + newCacheId); 11553 newMountPath = PackageHelper.mountSdDir(newCacheId, 11554 getEncryptKey(), Process.SYSTEM_UID); 11555 } else { 11556 newMountPath = PackageHelper.getSdDir(newCacheId); 11557 } 11558 if (newMountPath == null) { 11559 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11560 return false; 11561 } 11562 Log.i(TAG, "Succesfully renamed " + cid + 11563 " to " + newCacheId + 11564 " at new path: " + newMountPath); 11565 cid = newCacheId; 11566 11567 final File beforeCodeFile = new File(packagePath); 11568 setMountPath(newMountPath); 11569 final File afterCodeFile = new File(packagePath); 11570 11571 // Reflect the rename in scanned details 11572 pkg.codePath = afterCodeFile.getAbsolutePath(); 11573 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11574 pkg.baseCodePath); 11575 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11576 pkg.splitCodePaths); 11577 11578 // Reflect the rename in app info 11579 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11580 pkg.applicationInfo.setCodePath(pkg.codePath); 11581 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11582 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11583 pkg.applicationInfo.setResourcePath(pkg.codePath); 11584 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11585 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11586 11587 return true; 11588 } 11589 11590 private void setMountPath(String mountPath) { 11591 final File mountFile = new File(mountPath); 11592 11593 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11594 if (monolithicFile.exists()) { 11595 packagePath = monolithicFile.getAbsolutePath(); 11596 if (isFwdLocked()) { 11597 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11598 } else { 11599 resourcePath = packagePath; 11600 } 11601 } else { 11602 packagePath = mountFile.getAbsolutePath(); 11603 resourcePath = packagePath; 11604 } 11605 } 11606 11607 int doPostInstall(int status, int uid) { 11608 if (status != PackageManager.INSTALL_SUCCEEDED) { 11609 cleanUp(); 11610 } else { 11611 final int groupOwner; 11612 final String protectedFile; 11613 if (isFwdLocked()) { 11614 groupOwner = UserHandle.getSharedAppGid(uid); 11615 protectedFile = RES_FILE_NAME; 11616 } else { 11617 groupOwner = -1; 11618 protectedFile = null; 11619 } 11620 11621 if (uid < Process.FIRST_APPLICATION_UID 11622 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11623 Slog.e(TAG, "Failed to finalize " + cid); 11624 PackageHelper.destroySdDir(cid); 11625 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11626 } 11627 11628 boolean mounted = PackageHelper.isContainerMounted(cid); 11629 if (!mounted) { 11630 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11631 } 11632 } 11633 return status; 11634 } 11635 11636 private void cleanUp() { 11637 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11638 11639 // Destroy secure container 11640 PackageHelper.destroySdDir(cid); 11641 } 11642 11643 private List<String> getAllCodePaths() { 11644 final File codeFile = new File(getCodePath()); 11645 if (codeFile != null && codeFile.exists()) { 11646 try { 11647 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11648 return pkg.getAllCodePaths(); 11649 } catch (PackageParserException e) { 11650 // Ignored; we tried our best 11651 } 11652 } 11653 return Collections.EMPTY_LIST; 11654 } 11655 11656 void cleanUpResourcesLI() { 11657 // Enumerate all code paths before deleting 11658 cleanUpResourcesLI(getAllCodePaths()); 11659 } 11660 11661 private void cleanUpResourcesLI(List<String> allCodePaths) { 11662 cleanUp(); 11663 removeDexFiles(allCodePaths, instructionSets); 11664 } 11665 11666 String getPackageName() { 11667 return getAsecPackageName(cid); 11668 } 11669 11670 boolean doPostDeleteLI(boolean delete) { 11671 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11672 final List<String> allCodePaths = getAllCodePaths(); 11673 boolean mounted = PackageHelper.isContainerMounted(cid); 11674 if (mounted) { 11675 // Unmount first 11676 if (PackageHelper.unMountSdDir(cid)) { 11677 mounted = false; 11678 } 11679 } 11680 if (!mounted && delete) { 11681 cleanUpResourcesLI(allCodePaths); 11682 } 11683 return !mounted; 11684 } 11685 11686 @Override 11687 int doPreCopy() { 11688 if (isFwdLocked()) { 11689 if (!PackageHelper.fixSdPermissions(cid, 11690 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11691 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11692 } 11693 } 11694 11695 return PackageManager.INSTALL_SUCCEEDED; 11696 } 11697 11698 @Override 11699 int doPostCopy(int uid) { 11700 if (isFwdLocked()) { 11701 if (uid < Process.FIRST_APPLICATION_UID 11702 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11703 RES_FILE_NAME)) { 11704 Slog.e(TAG, "Failed to finalize " + cid); 11705 PackageHelper.destroySdDir(cid); 11706 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11707 } 11708 } 11709 11710 return PackageManager.INSTALL_SUCCEEDED; 11711 } 11712 } 11713 11714 /** 11715 * Logic to handle movement of existing installed applications. 11716 */ 11717 class MoveInstallArgs extends InstallArgs { 11718 private File codeFile; 11719 private File resourceFile; 11720 11721 /** New install */ 11722 MoveInstallArgs(InstallParams params) { 11723 super(params.origin, params.move, params.observer, params.installFlags, 11724 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11725 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11726 params.grantedRuntimePermissions, 11727 params.traceMethod, params.traceCookie); 11728 } 11729 11730 int copyApk(IMediaContainerService imcs, boolean temp) { 11731 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11732 + move.fromUuid + " to " + move.toUuid); 11733 synchronized (mInstaller) { 11734 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11735 move.dataAppName, move.appId, move.seinfo) != 0) { 11736 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11737 } 11738 } 11739 11740 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11741 resourceFile = codeFile; 11742 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11743 11744 return PackageManager.INSTALL_SUCCEEDED; 11745 } 11746 11747 int doPreInstall(int status) { 11748 if (status != PackageManager.INSTALL_SUCCEEDED) { 11749 cleanUp(move.toUuid); 11750 } 11751 return status; 11752 } 11753 11754 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11755 if (status != PackageManager.INSTALL_SUCCEEDED) { 11756 cleanUp(move.toUuid); 11757 return false; 11758 } 11759 11760 // Reflect the move in app info 11761 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11762 pkg.applicationInfo.setCodePath(pkg.codePath); 11763 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11764 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11765 pkg.applicationInfo.setResourcePath(pkg.codePath); 11766 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11767 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11768 11769 return true; 11770 } 11771 11772 int doPostInstall(int status, int uid) { 11773 if (status == PackageManager.INSTALL_SUCCEEDED) { 11774 cleanUp(move.fromUuid); 11775 } else { 11776 cleanUp(move.toUuid); 11777 } 11778 return status; 11779 } 11780 11781 @Override 11782 String getCodePath() { 11783 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11784 } 11785 11786 @Override 11787 String getResourcePath() { 11788 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11789 } 11790 11791 private boolean cleanUp(String volumeUuid) { 11792 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11793 move.dataAppName); 11794 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11795 synchronized (mInstallLock) { 11796 // Clean up both app data and code 11797 removeDataDirsLI(volumeUuid, move.packageName); 11798 if (codeFile.isDirectory()) { 11799 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11800 } else { 11801 codeFile.delete(); 11802 } 11803 } 11804 return true; 11805 } 11806 11807 void cleanUpResourcesLI() { 11808 throw new UnsupportedOperationException(); 11809 } 11810 11811 boolean doPostDeleteLI(boolean delete) { 11812 throw new UnsupportedOperationException(); 11813 } 11814 } 11815 11816 static String getAsecPackageName(String packageCid) { 11817 int idx = packageCid.lastIndexOf("-"); 11818 if (idx == -1) { 11819 return packageCid; 11820 } 11821 return packageCid.substring(0, idx); 11822 } 11823 11824 // Utility method used to create code paths based on package name and available index. 11825 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11826 String idxStr = ""; 11827 int idx = 1; 11828 // Fall back to default value of idx=1 if prefix is not 11829 // part of oldCodePath 11830 if (oldCodePath != null) { 11831 String subStr = oldCodePath; 11832 // Drop the suffix right away 11833 if (suffix != null && subStr.endsWith(suffix)) { 11834 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11835 } 11836 // If oldCodePath already contains prefix find out the 11837 // ending index to either increment or decrement. 11838 int sidx = subStr.lastIndexOf(prefix); 11839 if (sidx != -1) { 11840 subStr = subStr.substring(sidx + prefix.length()); 11841 if (subStr != null) { 11842 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11843 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11844 } 11845 try { 11846 idx = Integer.parseInt(subStr); 11847 if (idx <= 1) { 11848 idx++; 11849 } else { 11850 idx--; 11851 } 11852 } catch(NumberFormatException e) { 11853 } 11854 } 11855 } 11856 } 11857 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11858 return prefix + idxStr; 11859 } 11860 11861 private File getNextCodePath(File targetDir, String packageName) { 11862 int suffix = 1; 11863 File result; 11864 do { 11865 result = new File(targetDir, packageName + "-" + suffix); 11866 suffix++; 11867 } while (result.exists()); 11868 return result; 11869 } 11870 11871 // Utility method that returns the relative package path with respect 11872 // to the installation directory. Like say for /data/data/com.test-1.apk 11873 // string com.test-1 is returned. 11874 static String deriveCodePathName(String codePath) { 11875 if (codePath == null) { 11876 return null; 11877 } 11878 final File codeFile = new File(codePath); 11879 final String name = codeFile.getName(); 11880 if (codeFile.isDirectory()) { 11881 return name; 11882 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11883 final int lastDot = name.lastIndexOf('.'); 11884 return name.substring(0, lastDot); 11885 } else { 11886 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11887 return null; 11888 } 11889 } 11890 11891 class PackageInstalledInfo { 11892 String name; 11893 int uid; 11894 // The set of users that originally had this package installed. 11895 int[] origUsers; 11896 // The set of users that now have this package installed. 11897 int[] newUsers; 11898 PackageParser.Package pkg; 11899 int returnCode; 11900 String returnMsg; 11901 PackageRemovedInfo removedInfo; 11902 11903 public void setError(int code, String msg) { 11904 returnCode = code; 11905 returnMsg = msg; 11906 Slog.w(TAG, msg); 11907 } 11908 11909 public void setError(String msg, PackageParserException e) { 11910 returnCode = e.error; 11911 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11912 Slog.w(TAG, msg, e); 11913 } 11914 11915 public void setError(String msg, PackageManagerException e) { 11916 returnCode = e.error; 11917 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11918 Slog.w(TAG, msg, e); 11919 } 11920 11921 // In some error cases we want to convey more info back to the observer 11922 String origPackage; 11923 String origPermission; 11924 } 11925 11926 /* 11927 * Install a non-existing package. 11928 */ 11929 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11930 UserHandle user, String installerPackageName, String volumeUuid, 11931 PackageInstalledInfo res) { 11932 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11933 11934 // Remember this for later, in case we need to rollback this install 11935 String pkgName = pkg.packageName; 11936 11937 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11938 // TODO: b/23350563 11939 final boolean dataDirExists = Environment 11940 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11941 11942 synchronized(mPackages) { 11943 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11944 // A package with the same name is already installed, though 11945 // it has been renamed to an older name. The package we 11946 // are trying to install should be installed as an update to 11947 // the existing one, but that has not been requested, so bail. 11948 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11949 + " without first uninstalling package running as " 11950 + mSettings.mRenamedPackages.get(pkgName)); 11951 return; 11952 } 11953 if (mPackages.containsKey(pkgName)) { 11954 // Don't allow installation over an existing package with the same name. 11955 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11956 + " without first uninstalling."); 11957 return; 11958 } 11959 } 11960 11961 try { 11962 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11963 System.currentTimeMillis(), user); 11964 11965 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11966 // delete the partially installed application. the data directory will have to be 11967 // restored if it was already existing 11968 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11969 // remove package from internal structures. Note that we want deletePackageX to 11970 // delete the package data and cache directories that it created in 11971 // scanPackageLocked, unless those directories existed before we even tried to 11972 // install. 11973 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11974 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11975 res.removedInfo, true); 11976 } 11977 11978 } catch (PackageManagerException e) { 11979 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11980 } 11981 11982 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11983 } 11984 11985 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11986 // Can't rotate keys during boot or if sharedUser. 11987 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11988 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11989 return false; 11990 } 11991 // app is using upgradeKeySets; make sure all are valid 11992 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11993 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11994 for (int i = 0; i < upgradeKeySets.length; i++) { 11995 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11996 Slog.wtf(TAG, "Package " 11997 + (oldPs.name != null ? oldPs.name : "<null>") 11998 + " contains upgrade-key-set reference to unknown key-set: " 11999 + upgradeKeySets[i] 12000 + " reverting to signatures check."); 12001 return false; 12002 } 12003 } 12004 return true; 12005 } 12006 12007 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12008 // Upgrade keysets are being used. Determine if new package has a superset of the 12009 // required keys. 12010 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12011 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12012 for (int i = 0; i < upgradeKeySets.length; i++) { 12013 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12014 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12015 return true; 12016 } 12017 } 12018 return false; 12019 } 12020 12021 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12022 UserHandle user, String installerPackageName, String volumeUuid, 12023 PackageInstalledInfo res) { 12024 final PackageParser.Package oldPackage; 12025 final String pkgName = pkg.packageName; 12026 final int[] allUsers; 12027 final boolean[] perUserInstalled; 12028 12029 // First find the old package info and check signatures 12030 synchronized(mPackages) { 12031 oldPackage = mPackages.get(pkgName); 12032 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12033 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12034 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12035 if(!checkUpgradeKeySetLP(ps, pkg)) { 12036 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12037 "New package not signed by keys specified by upgrade-keysets: " 12038 + pkgName); 12039 return; 12040 } 12041 } else { 12042 // default to original signature matching 12043 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12044 != PackageManager.SIGNATURE_MATCH) { 12045 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12046 "New package has a different signature: " + pkgName); 12047 return; 12048 } 12049 } 12050 12051 // In case of rollback, remember per-user/profile install state 12052 allUsers = sUserManager.getUserIds(); 12053 perUserInstalled = new boolean[allUsers.length]; 12054 for (int i = 0; i < allUsers.length; i++) { 12055 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12056 } 12057 } 12058 12059 boolean sysPkg = (isSystemApp(oldPackage)); 12060 if (sysPkg) { 12061 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12062 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12063 } else { 12064 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12065 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12066 } 12067 } 12068 12069 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12070 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12071 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12072 String volumeUuid, PackageInstalledInfo res) { 12073 String pkgName = deletedPackage.packageName; 12074 boolean deletedPkg = true; 12075 boolean updatedSettings = false; 12076 12077 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12078 + deletedPackage); 12079 long origUpdateTime; 12080 if (pkg.mExtras != null) { 12081 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12082 } else { 12083 origUpdateTime = 0; 12084 } 12085 12086 // First delete the existing package while retaining the data directory 12087 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12088 res.removedInfo, true)) { 12089 // If the existing package wasn't successfully deleted 12090 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12091 deletedPkg = false; 12092 } else { 12093 // Successfully deleted the old package; proceed with replace. 12094 12095 // If deleted package lived in a container, give users a chance to 12096 // relinquish resources before killing. 12097 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12098 if (DEBUG_INSTALL) { 12099 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12100 } 12101 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12102 final ArrayList<String> pkgList = new ArrayList<String>(1); 12103 pkgList.add(deletedPackage.applicationInfo.packageName); 12104 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12105 } 12106 12107 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12108 try { 12109 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12110 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12111 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12112 perUserInstalled, res, user); 12113 updatedSettings = true; 12114 } catch (PackageManagerException e) { 12115 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12116 } 12117 } 12118 12119 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12120 // remove package from internal structures. Note that we want deletePackageX to 12121 // delete the package data and cache directories that it created in 12122 // scanPackageLocked, unless those directories existed before we even tried to 12123 // install. 12124 if(updatedSettings) { 12125 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12126 deletePackageLI( 12127 pkgName, null, true, allUsers, perUserInstalled, 12128 PackageManager.DELETE_KEEP_DATA, 12129 res.removedInfo, true); 12130 } 12131 // Since we failed to install the new package we need to restore the old 12132 // package that we deleted. 12133 if (deletedPkg) { 12134 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12135 File restoreFile = new File(deletedPackage.codePath); 12136 // Parse old package 12137 boolean oldExternal = isExternal(deletedPackage); 12138 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12139 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12140 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12141 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12142 try { 12143 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12144 UserHandle.SYSTEM); 12145 } catch (PackageManagerException e) { 12146 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12147 + e.getMessage()); 12148 return; 12149 } 12150 // Restore of old package succeeded. Update permissions. 12151 // writer 12152 synchronized (mPackages) { 12153 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12154 UPDATE_PERMISSIONS_ALL); 12155 // can downgrade to reader 12156 mSettings.writeLPr(); 12157 } 12158 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12159 } 12160 } 12161 } 12162 12163 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12164 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12165 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12166 String volumeUuid, PackageInstalledInfo res) { 12167 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12168 + ", old=" + deletedPackage); 12169 boolean disabledSystem = false; 12170 boolean updatedSettings = false; 12171 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12172 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12173 != 0) { 12174 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12175 } 12176 String packageName = deletedPackage.packageName; 12177 if (packageName == null) { 12178 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12179 "Attempt to delete null packageName."); 12180 return; 12181 } 12182 PackageParser.Package oldPkg; 12183 PackageSetting oldPkgSetting; 12184 // reader 12185 synchronized (mPackages) { 12186 oldPkg = mPackages.get(packageName); 12187 oldPkgSetting = mSettings.mPackages.get(packageName); 12188 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12189 (oldPkgSetting == null)) { 12190 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12191 "Couldn't find package:" + packageName + " information"); 12192 return; 12193 } 12194 } 12195 12196 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12197 12198 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12199 res.removedInfo.removedPackage = packageName; 12200 // Remove existing system package 12201 removePackageLI(oldPkgSetting, true); 12202 // writer 12203 synchronized (mPackages) { 12204 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12205 if (!disabledSystem && deletedPackage != null) { 12206 // We didn't need to disable the .apk as a current system package, 12207 // which means we are replacing another update that is already 12208 // installed. We need to make sure to delete the older one's .apk. 12209 res.removedInfo.args = createInstallArgsForExisting(0, 12210 deletedPackage.applicationInfo.getCodePath(), 12211 deletedPackage.applicationInfo.getResourcePath(), 12212 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12213 } else { 12214 res.removedInfo.args = null; 12215 } 12216 } 12217 12218 // Successfully disabled the old package. Now proceed with re-installation 12219 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12220 12221 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12222 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12223 12224 PackageParser.Package newPackage = null; 12225 try { 12226 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12227 if (newPackage.mExtras != null) { 12228 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12229 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12230 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12231 12232 // is the update attempting to change shared user? that isn't going to work... 12233 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12234 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12235 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12236 + " to " + newPkgSetting.sharedUser); 12237 updatedSettings = true; 12238 } 12239 } 12240 12241 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12242 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12243 perUserInstalled, res, user); 12244 updatedSettings = true; 12245 } 12246 12247 } catch (PackageManagerException e) { 12248 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12249 } 12250 12251 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12252 // Re installation failed. Restore old information 12253 // Remove new pkg information 12254 if (newPackage != null) { 12255 removeInstalledPackageLI(newPackage, true); 12256 } 12257 // Add back the old system package 12258 try { 12259 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12260 } catch (PackageManagerException e) { 12261 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12262 } 12263 // Restore the old system information in Settings 12264 synchronized (mPackages) { 12265 if (disabledSystem) { 12266 mSettings.enableSystemPackageLPw(packageName); 12267 } 12268 if (updatedSettings) { 12269 mSettings.setInstallerPackageName(packageName, 12270 oldPkgSetting.installerPackageName); 12271 } 12272 mSettings.writeLPr(); 12273 } 12274 } 12275 } 12276 12277 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12278 // Collect all used permissions in the UID 12279 ArraySet<String> usedPermissions = new ArraySet<>(); 12280 final int packageCount = su.packages.size(); 12281 for (int i = 0; i < packageCount; i++) { 12282 PackageSetting ps = su.packages.valueAt(i); 12283 if (ps.pkg == null) { 12284 continue; 12285 } 12286 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12287 for (int j = 0; j < requestedPermCount; j++) { 12288 String permission = ps.pkg.requestedPermissions.get(j); 12289 BasePermission bp = mSettings.mPermissions.get(permission); 12290 if (bp != null) { 12291 usedPermissions.add(permission); 12292 } 12293 } 12294 } 12295 12296 PermissionsState permissionsState = su.getPermissionsState(); 12297 // Prune install permissions 12298 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12299 final int installPermCount = installPermStates.size(); 12300 for (int i = installPermCount - 1; i >= 0; i--) { 12301 PermissionState permissionState = installPermStates.get(i); 12302 if (!usedPermissions.contains(permissionState.getName())) { 12303 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12304 if (bp != null) { 12305 permissionsState.revokeInstallPermission(bp); 12306 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12307 PackageManager.MASK_PERMISSION_FLAGS, 0); 12308 } 12309 } 12310 } 12311 12312 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12313 12314 // Prune runtime permissions 12315 for (int userId : allUserIds) { 12316 List<PermissionState> runtimePermStates = permissionsState 12317 .getRuntimePermissionStates(userId); 12318 final int runtimePermCount = runtimePermStates.size(); 12319 for (int i = runtimePermCount - 1; i >= 0; i--) { 12320 PermissionState permissionState = runtimePermStates.get(i); 12321 if (!usedPermissions.contains(permissionState.getName())) { 12322 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12323 if (bp != null) { 12324 permissionsState.revokeRuntimePermission(bp, userId); 12325 permissionsState.updatePermissionFlags(bp, userId, 12326 PackageManager.MASK_PERMISSION_FLAGS, 0); 12327 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12328 runtimePermissionChangedUserIds, userId); 12329 } 12330 } 12331 } 12332 } 12333 12334 return runtimePermissionChangedUserIds; 12335 } 12336 12337 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12338 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12339 UserHandle user) { 12340 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12341 12342 String pkgName = newPackage.packageName; 12343 synchronized (mPackages) { 12344 //write settings. the installStatus will be incomplete at this stage. 12345 //note that the new package setting would have already been 12346 //added to mPackages. It hasn't been persisted yet. 12347 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12348 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12349 mSettings.writeLPr(); 12350 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12351 } 12352 12353 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12354 synchronized (mPackages) { 12355 updatePermissionsLPw(newPackage.packageName, newPackage, 12356 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12357 ? UPDATE_PERMISSIONS_ALL : 0)); 12358 // For system-bundled packages, we assume that installing an upgraded version 12359 // of the package implies that the user actually wants to run that new code, 12360 // so we enable the package. 12361 PackageSetting ps = mSettings.mPackages.get(pkgName); 12362 if (ps != null) { 12363 if (isSystemApp(newPackage)) { 12364 // NB: implicit assumption that system package upgrades apply to all users 12365 if (DEBUG_INSTALL) { 12366 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12367 } 12368 if (res.origUsers != null) { 12369 for (int userHandle : res.origUsers) { 12370 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12371 userHandle, installerPackageName); 12372 } 12373 } 12374 // Also convey the prior install/uninstall state 12375 if (allUsers != null && perUserInstalled != null) { 12376 for (int i = 0; i < allUsers.length; i++) { 12377 if (DEBUG_INSTALL) { 12378 Slog.d(TAG, " user " + allUsers[i] 12379 + " => " + perUserInstalled[i]); 12380 } 12381 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12382 } 12383 // these install state changes will be persisted in the 12384 // upcoming call to mSettings.writeLPr(). 12385 } 12386 } 12387 // It's implied that when a user requests installation, they want the app to be 12388 // installed and enabled. 12389 int userId = user.getIdentifier(); 12390 if (userId != UserHandle.USER_ALL) { 12391 ps.setInstalled(true, userId); 12392 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12393 } 12394 } 12395 res.name = pkgName; 12396 res.uid = newPackage.applicationInfo.uid; 12397 res.pkg = newPackage; 12398 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12399 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12400 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12401 //to update install status 12402 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12403 mSettings.writeLPr(); 12404 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12405 } 12406 12407 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12408 } 12409 12410 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12411 try { 12412 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12413 installPackageLI(args, res); 12414 } finally { 12415 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12416 } 12417 } 12418 12419 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12420 final int installFlags = args.installFlags; 12421 final String installerPackageName = args.installerPackageName; 12422 final String volumeUuid = args.volumeUuid; 12423 final File tmpPackageFile = new File(args.getCodePath()); 12424 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12425 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12426 || (args.volumeUuid != null)); 12427 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12428 boolean replace = false; 12429 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12430 if (args.move != null) { 12431 // moving a complete application; perfom an initial scan on the new install location 12432 scanFlags |= SCAN_INITIAL; 12433 } 12434 // Result object to be returned 12435 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12436 12437 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12438 12439 // Retrieve PackageSettings and parse package 12440 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12441 | PackageParser.PARSE_ENFORCE_CODE 12442 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12443 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12444 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12445 PackageParser pp = new PackageParser(); 12446 pp.setSeparateProcesses(mSeparateProcesses); 12447 pp.setDisplayMetrics(mMetrics); 12448 12449 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12450 final PackageParser.Package pkg; 12451 try { 12452 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12453 } catch (PackageParserException e) { 12454 res.setError("Failed parse during installPackageLI", e); 12455 return; 12456 } finally { 12457 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12458 } 12459 12460 // Mark that we have an install time CPU ABI override. 12461 pkg.cpuAbiOverride = args.abiOverride; 12462 12463 String pkgName = res.name = pkg.packageName; 12464 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12465 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12466 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12467 return; 12468 } 12469 } 12470 12471 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12472 try { 12473 pp.collectCertificates(pkg, parseFlags); 12474 } catch (PackageParserException e) { 12475 res.setError("Failed collect during installPackageLI", e); 12476 return; 12477 } finally { 12478 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12479 } 12480 12481 /* If the installer passed in a manifest digest, compare it now. */ 12482 if (args.manifestDigest != null) { 12483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12484 try { 12485 pp.collectManifestDigest(pkg); 12486 } catch (PackageParserException e) { 12487 res.setError("Failed collect during installPackageLI", e); 12488 return; 12489 } finally { 12490 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12491 } 12492 12493 if (DEBUG_INSTALL) { 12494 final String parsedManifest = pkg.manifestDigest == null ? "null" 12495 : pkg.manifestDigest.toString(); 12496 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12497 + parsedManifest); 12498 } 12499 12500 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12501 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12502 return; 12503 } 12504 } else if (DEBUG_INSTALL) { 12505 final String parsedManifest = pkg.manifestDigest == null 12506 ? "null" : pkg.manifestDigest.toString(); 12507 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12508 } 12509 12510 // Get rid of all references to package scan path via parser. 12511 pp = null; 12512 String oldCodePath = null; 12513 boolean systemApp = false; 12514 synchronized (mPackages) { 12515 // Check if installing already existing package 12516 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12517 String oldName = mSettings.mRenamedPackages.get(pkgName); 12518 if (pkg.mOriginalPackages != null 12519 && pkg.mOriginalPackages.contains(oldName) 12520 && mPackages.containsKey(oldName)) { 12521 // This package is derived from an original package, 12522 // and this device has been updating from that original 12523 // name. We must continue using the original name, so 12524 // rename the new package here. 12525 pkg.setPackageName(oldName); 12526 pkgName = pkg.packageName; 12527 replace = true; 12528 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12529 + oldName + " pkgName=" + pkgName); 12530 } else if (mPackages.containsKey(pkgName)) { 12531 // This package, under its official name, already exists 12532 // on the device; we should replace it. 12533 replace = true; 12534 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12535 } 12536 12537 // Prevent apps opting out from runtime permissions 12538 if (replace) { 12539 PackageParser.Package oldPackage = mPackages.get(pkgName); 12540 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12541 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12542 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12543 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12544 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12545 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12546 + " doesn't support runtime permissions but the old" 12547 + " target SDK " + oldTargetSdk + " does."); 12548 return; 12549 } 12550 } 12551 } 12552 12553 PackageSetting ps = mSettings.mPackages.get(pkgName); 12554 if (ps != null) { 12555 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12556 12557 // Quick sanity check that we're signed correctly if updating; 12558 // we'll check this again later when scanning, but we want to 12559 // bail early here before tripping over redefined permissions. 12560 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12561 if (!checkUpgradeKeySetLP(ps, pkg)) { 12562 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12563 + pkg.packageName + " upgrade keys do not match the " 12564 + "previously installed version"); 12565 return; 12566 } 12567 } else { 12568 try { 12569 verifySignaturesLP(ps, pkg); 12570 } catch (PackageManagerException e) { 12571 res.setError(e.error, e.getMessage()); 12572 return; 12573 } 12574 } 12575 12576 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12577 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12578 systemApp = (ps.pkg.applicationInfo.flags & 12579 ApplicationInfo.FLAG_SYSTEM) != 0; 12580 } 12581 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12582 } 12583 12584 // Check whether the newly-scanned package wants to define an already-defined perm 12585 int N = pkg.permissions.size(); 12586 for (int i = N-1; i >= 0; i--) { 12587 PackageParser.Permission perm = pkg.permissions.get(i); 12588 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12589 if (bp != null) { 12590 // If the defining package is signed with our cert, it's okay. This 12591 // also includes the "updating the same package" case, of course. 12592 // "updating same package" could also involve key-rotation. 12593 final boolean sigsOk; 12594 if (bp.sourcePackage.equals(pkg.packageName) 12595 && (bp.packageSetting instanceof PackageSetting) 12596 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12597 scanFlags))) { 12598 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12599 } else { 12600 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12601 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12602 } 12603 if (!sigsOk) { 12604 // If the owning package is the system itself, we log but allow 12605 // install to proceed; we fail the install on all other permission 12606 // redefinitions. 12607 if (!bp.sourcePackage.equals("android")) { 12608 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12609 + pkg.packageName + " attempting to redeclare permission " 12610 + perm.info.name + " already owned by " + bp.sourcePackage); 12611 res.origPermission = perm.info.name; 12612 res.origPackage = bp.sourcePackage; 12613 return; 12614 } else { 12615 Slog.w(TAG, "Package " + pkg.packageName 12616 + " attempting to redeclare system permission " 12617 + perm.info.name + "; ignoring new declaration"); 12618 pkg.permissions.remove(i); 12619 } 12620 } 12621 } 12622 } 12623 12624 } 12625 12626 if (systemApp && onExternal) { 12627 // Disable updates to system apps on sdcard 12628 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12629 "Cannot install updates to system apps on sdcard"); 12630 return; 12631 } 12632 12633 if (args.move != null) { 12634 // We did an in-place move, so dex is ready to roll 12635 scanFlags |= SCAN_NO_DEX; 12636 scanFlags |= SCAN_MOVE; 12637 12638 synchronized (mPackages) { 12639 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12640 if (ps == null) { 12641 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12642 "Missing settings for moved package " + pkgName); 12643 } 12644 12645 // We moved the entire application as-is, so bring over the 12646 // previously derived ABI information. 12647 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12648 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12649 } 12650 12651 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12652 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12653 scanFlags |= SCAN_NO_DEX; 12654 12655 try { 12656 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12657 true /* extract libs */); 12658 } catch (PackageManagerException pme) { 12659 Slog.e(TAG, "Error deriving application ABI", pme); 12660 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12661 return; 12662 } 12663 12664 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12665 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12666 12667 int result = mPackageDexOptimizer 12668 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12669 false /* defer */, false /* inclDependencies */, 12670 true /*bootComplete*/, quickInstall /*useJit*/); 12671 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12672 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12673 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12674 return; 12675 } 12676 } 12677 12678 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12679 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12680 return; 12681 } 12682 12683 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12684 12685 if (replace) { 12686 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12687 installerPackageName, volumeUuid, res); 12688 } else { 12689 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12690 args.user, installerPackageName, volumeUuid, res); 12691 } 12692 synchronized (mPackages) { 12693 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12694 if (ps != null) { 12695 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12696 } 12697 } 12698 } 12699 12700 private void startIntentFilterVerifications(int userId, boolean replacing, 12701 PackageParser.Package pkg) { 12702 if (mIntentFilterVerifierComponent == null) { 12703 Slog.w(TAG, "No IntentFilter verification will not be done as " 12704 + "there is no IntentFilterVerifier available!"); 12705 return; 12706 } 12707 12708 final int verifierUid = getPackageUid( 12709 mIntentFilterVerifierComponent.getPackageName(), 12710 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12711 12712 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12713 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12714 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12715 mHandler.sendMessage(msg); 12716 } 12717 12718 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12719 PackageParser.Package pkg) { 12720 int size = pkg.activities.size(); 12721 if (size == 0) { 12722 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12723 "No activity, so no need to verify any IntentFilter!"); 12724 return; 12725 } 12726 12727 final boolean hasDomainURLs = hasDomainURLs(pkg); 12728 if (!hasDomainURLs) { 12729 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12730 "No domain URLs, so no need to verify any IntentFilter!"); 12731 return; 12732 } 12733 12734 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12735 + " if any IntentFilter from the " + size 12736 + " Activities needs verification ..."); 12737 12738 int count = 0; 12739 final String packageName = pkg.packageName; 12740 12741 synchronized (mPackages) { 12742 // If this is a new install and we see that we've already run verification for this 12743 // package, we have nothing to do: it means the state was restored from backup. 12744 if (!replacing) { 12745 IntentFilterVerificationInfo ivi = 12746 mSettings.getIntentFilterVerificationLPr(packageName); 12747 if (ivi != null) { 12748 if (DEBUG_DOMAIN_VERIFICATION) { 12749 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12750 + ivi.getStatusString()); 12751 } 12752 return; 12753 } 12754 } 12755 12756 // If any filters need to be verified, then all need to be. 12757 boolean needToVerify = false; 12758 for (PackageParser.Activity a : pkg.activities) { 12759 for (ActivityIntentInfo filter : a.intents) { 12760 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12761 if (DEBUG_DOMAIN_VERIFICATION) { 12762 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12763 } 12764 needToVerify = true; 12765 break; 12766 } 12767 } 12768 } 12769 12770 if (needToVerify) { 12771 final int verificationId = mIntentFilterVerificationToken++; 12772 for (PackageParser.Activity a : pkg.activities) { 12773 for (ActivityIntentInfo filter : a.intents) { 12774 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12775 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12776 "Verification needed for IntentFilter:" + filter.toString()); 12777 mIntentFilterVerifier.addOneIntentFilterVerification( 12778 verifierUid, userId, verificationId, filter, packageName); 12779 count++; 12780 } 12781 } 12782 } 12783 } 12784 } 12785 12786 if (count > 0) { 12787 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12788 + " IntentFilter verification" + (count > 1 ? "s" : "") 12789 + " for userId:" + userId); 12790 mIntentFilterVerifier.startVerifications(userId); 12791 } else { 12792 if (DEBUG_DOMAIN_VERIFICATION) { 12793 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12794 } 12795 } 12796 } 12797 12798 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12799 final ComponentName cn = filter.activity.getComponentName(); 12800 final String packageName = cn.getPackageName(); 12801 12802 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12803 packageName); 12804 if (ivi == null) { 12805 return true; 12806 } 12807 int status = ivi.getStatus(); 12808 switch (status) { 12809 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12810 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12811 return true; 12812 12813 default: 12814 // Nothing to do 12815 return false; 12816 } 12817 } 12818 12819 private static boolean isMultiArch(PackageSetting ps) { 12820 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12821 } 12822 12823 private static boolean isMultiArch(ApplicationInfo info) { 12824 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12825 } 12826 12827 private static boolean isExternal(PackageParser.Package pkg) { 12828 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12829 } 12830 12831 private static boolean isExternal(PackageSetting ps) { 12832 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12833 } 12834 12835 private static boolean isExternal(ApplicationInfo info) { 12836 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12837 } 12838 12839 private static boolean isSystemApp(PackageParser.Package pkg) { 12840 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12841 } 12842 12843 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12844 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12845 } 12846 12847 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12848 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12849 } 12850 12851 private static boolean isSystemApp(PackageSetting ps) { 12852 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12853 } 12854 12855 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12856 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12857 } 12858 12859 private int packageFlagsToInstallFlags(PackageSetting ps) { 12860 int installFlags = 0; 12861 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12862 // This existing package was an external ASEC install when we have 12863 // the external flag without a UUID 12864 installFlags |= PackageManager.INSTALL_EXTERNAL; 12865 } 12866 if (ps.isForwardLocked()) { 12867 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12868 } 12869 return installFlags; 12870 } 12871 12872 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12873 if (isExternal(pkg)) { 12874 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12875 return StorageManager.UUID_PRIMARY_PHYSICAL; 12876 } else { 12877 return pkg.volumeUuid; 12878 } 12879 } else { 12880 return StorageManager.UUID_PRIVATE_INTERNAL; 12881 } 12882 } 12883 12884 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12885 if (isExternal(pkg)) { 12886 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12887 return mSettings.getExternalVersion(); 12888 } else { 12889 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12890 } 12891 } else { 12892 return mSettings.getInternalVersion(); 12893 } 12894 } 12895 12896 private void deleteTempPackageFiles() { 12897 final FilenameFilter filter = new FilenameFilter() { 12898 public boolean accept(File dir, String name) { 12899 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12900 } 12901 }; 12902 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12903 file.delete(); 12904 } 12905 } 12906 12907 @Override 12908 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12909 int flags) { 12910 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12911 flags); 12912 } 12913 12914 @Override 12915 public void deletePackage(final String packageName, 12916 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12917 mContext.enforceCallingOrSelfPermission( 12918 android.Manifest.permission.DELETE_PACKAGES, null); 12919 Preconditions.checkNotNull(packageName); 12920 Preconditions.checkNotNull(observer); 12921 final int uid = Binder.getCallingUid(); 12922 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 12923 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 12924 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 12925 mContext.enforceCallingPermission( 12926 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12927 "deletePackage for user " + userId); 12928 } 12929 12930 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12931 try { 12932 observer.onPackageDeleted(packageName, 12933 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12934 } catch (RemoteException re) { 12935 } 12936 return; 12937 } 12938 12939 for (int currentUserId : users) { 12940 if (getBlockUninstallForUser(packageName, currentUserId)) { 12941 try { 12942 observer.onPackageDeleted(packageName, 12943 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 12944 } catch (RemoteException re) { 12945 } 12946 return; 12947 } 12948 } 12949 12950 if (DEBUG_REMOVE) { 12951 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12952 } 12953 // Queue up an async operation since the package deletion may take a little while. 12954 mHandler.post(new Runnable() { 12955 public void run() { 12956 mHandler.removeCallbacks(this); 12957 final int returnCode = deletePackageX(packageName, userId, flags); 12958 try { 12959 observer.onPackageDeleted(packageName, returnCode, null); 12960 } catch (RemoteException e) { 12961 Log.i(TAG, "Observer no longer exists."); 12962 } //end catch 12963 } //end run 12964 }); 12965 } 12966 12967 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12968 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12969 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12970 try { 12971 if (dpm != null) { 12972 // Does the package contains the device owner? 12973 if (dpm.isDeviceOwnerPackage(packageName)) { 12974 return true; 12975 } 12976 // Does it contain a device admin for any user? 12977 int[] users; 12978 if (userId == UserHandle.USER_ALL) { 12979 users = sUserManager.getUserIds(); 12980 } else { 12981 users = new int[]{userId}; 12982 } 12983 for (int i = 0; i < users.length; ++i) { 12984 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12985 return true; 12986 } 12987 } 12988 } 12989 } catch (RemoteException e) { 12990 } 12991 return false; 12992 } 12993 12994 /** 12995 * This method is an internal method that could be get invoked either 12996 * to delete an installed package or to clean up a failed installation. 12997 * After deleting an installed package, a broadcast is sent to notify any 12998 * listeners that the package has been installed. For cleaning up a failed 12999 * installation, the broadcast is not necessary since the package's 13000 * installation wouldn't have sent the initial broadcast either 13001 * The key steps in deleting a package are 13002 * deleting the package information in internal structures like mPackages, 13003 * deleting the packages base directories through installd 13004 * updating mSettings to reflect current status 13005 * persisting settings for later use 13006 * sending a broadcast if necessary 13007 */ 13008 private int deletePackageX(String packageName, int userId, int flags) { 13009 final PackageRemovedInfo info = new PackageRemovedInfo(); 13010 final boolean res; 13011 13012 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13013 ? UserHandle.ALL : new UserHandle(userId); 13014 13015 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13016 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13017 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13018 } 13019 13020 boolean removedForAllUsers = false; 13021 boolean systemUpdate = false; 13022 13023 // for the uninstall-updates case and restricted profiles, remember the per- 13024 // userhandle installed state 13025 int[] allUsers; 13026 boolean[] perUserInstalled; 13027 synchronized (mPackages) { 13028 PackageSetting ps = mSettings.mPackages.get(packageName); 13029 allUsers = sUserManager.getUserIds(); 13030 perUserInstalled = new boolean[allUsers.length]; 13031 for (int i = 0; i < allUsers.length; i++) { 13032 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13033 } 13034 } 13035 13036 synchronized (mInstallLock) { 13037 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13038 res = deletePackageLI(packageName, removeForUser, 13039 true, allUsers, perUserInstalled, 13040 flags | REMOVE_CHATTY, info, true); 13041 systemUpdate = info.isRemovedPackageSystemUpdate; 13042 if (res && !systemUpdate && mPackages.get(packageName) == null) { 13043 removedForAllUsers = true; 13044 } 13045 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13046 + " removedForAllUsers=" + removedForAllUsers); 13047 } 13048 13049 if (res) { 13050 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13051 13052 // If the removed package was a system update, the old system package 13053 // was re-enabled; we need to broadcast this information 13054 if (systemUpdate) { 13055 Bundle extras = new Bundle(1); 13056 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13057 ? info.removedAppId : info.uid); 13058 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13059 13060 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13061 extras, null, null, null); 13062 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13063 extras, null, null, null); 13064 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13065 null, packageName, null, null); 13066 } 13067 } 13068 // Force a gc here. 13069 Runtime.getRuntime().gc(); 13070 // Delete the resources here after sending the broadcast to let 13071 // other processes clean up before deleting resources. 13072 if (info.args != null) { 13073 synchronized (mInstallLock) { 13074 info.args.doPostDeleteLI(true); 13075 } 13076 } 13077 13078 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13079 } 13080 13081 class PackageRemovedInfo { 13082 String removedPackage; 13083 int uid = -1; 13084 int removedAppId = -1; 13085 int[] removedUsers = null; 13086 boolean isRemovedPackageSystemUpdate = false; 13087 // Clean up resources deleted packages. 13088 InstallArgs args = null; 13089 13090 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13091 Bundle extras = new Bundle(1); 13092 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13093 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13094 if (replacing) { 13095 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13096 } 13097 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13098 if (removedPackage != null) { 13099 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13100 extras, null, null, removedUsers); 13101 if (fullRemove && !replacing) { 13102 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13103 extras, null, null, removedUsers); 13104 } 13105 } 13106 if (removedAppId >= 0) { 13107 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 13108 removedUsers); 13109 } 13110 } 13111 } 13112 13113 /* 13114 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13115 * flag is not set, the data directory is removed as well. 13116 * make sure this flag is set for partially installed apps. If not its meaningless to 13117 * delete a partially installed application. 13118 */ 13119 private void removePackageDataLI(PackageSetting ps, 13120 int[] allUserHandles, boolean[] perUserInstalled, 13121 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13122 String packageName = ps.name; 13123 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13124 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13125 // Retrieve object to delete permissions for shared user later on 13126 final PackageSetting deletedPs; 13127 // reader 13128 synchronized (mPackages) { 13129 deletedPs = mSettings.mPackages.get(packageName); 13130 if (outInfo != null) { 13131 outInfo.removedPackage = packageName; 13132 outInfo.removedUsers = deletedPs != null 13133 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13134 : null; 13135 } 13136 } 13137 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13138 removeDataDirsLI(ps.volumeUuid, packageName); 13139 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13140 } 13141 // writer 13142 synchronized (mPackages) { 13143 if (deletedPs != null) { 13144 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13145 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13146 clearDefaultBrowserIfNeeded(packageName); 13147 if (outInfo != null) { 13148 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13149 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13150 } 13151 updatePermissionsLPw(deletedPs.name, null, 0); 13152 if (deletedPs.sharedUser != null) { 13153 // Remove permissions associated with package. Since runtime 13154 // permissions are per user we have to kill the removed package 13155 // or packages running under the shared user of the removed 13156 // package if revoking the permissions requested only by the removed 13157 // package is successful and this causes a change in gids. 13158 for (int userId : UserManagerService.getInstance().getUserIds()) { 13159 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13160 userId); 13161 if (userIdToKill == UserHandle.USER_ALL 13162 || userIdToKill >= UserHandle.USER_SYSTEM) { 13163 // If gids changed for this user, kill all affected packages. 13164 mHandler.post(new Runnable() { 13165 @Override 13166 public void run() { 13167 // This has to happen with no lock held. 13168 killApplication(deletedPs.name, deletedPs.appId, 13169 KILL_APP_REASON_GIDS_CHANGED); 13170 } 13171 }); 13172 break; 13173 } 13174 } 13175 } 13176 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13177 } 13178 // make sure to preserve per-user disabled state if this removal was just 13179 // a downgrade of a system app to the factory package 13180 if (allUserHandles != null && perUserInstalled != null) { 13181 if (DEBUG_REMOVE) { 13182 Slog.d(TAG, "Propagating install state across downgrade"); 13183 } 13184 for (int i = 0; i < allUserHandles.length; i++) { 13185 if (DEBUG_REMOVE) { 13186 Slog.d(TAG, " user " + allUserHandles[i] 13187 + " => " + perUserInstalled[i]); 13188 } 13189 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13190 } 13191 } 13192 } 13193 // can downgrade to reader 13194 if (writeSettings) { 13195 // Save settings now 13196 mSettings.writeLPr(); 13197 } 13198 } 13199 if (outInfo != null) { 13200 // A user ID was deleted here. Go through all users and remove it 13201 // from KeyStore. 13202 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13203 } 13204 } 13205 13206 static boolean locationIsPrivileged(File path) { 13207 try { 13208 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13209 .getCanonicalPath(); 13210 return path.getCanonicalPath().startsWith(privilegedAppDir); 13211 } catch (IOException e) { 13212 Slog.e(TAG, "Unable to access code path " + path); 13213 } 13214 return false; 13215 } 13216 13217 /* 13218 * Tries to delete system package. 13219 */ 13220 private boolean deleteSystemPackageLI(PackageSetting newPs, 13221 int[] allUserHandles, boolean[] perUserInstalled, 13222 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13223 final boolean applyUserRestrictions 13224 = (allUserHandles != null) && (perUserInstalled != null); 13225 PackageSetting disabledPs = null; 13226 // Confirm if the system package has been updated 13227 // An updated system app can be deleted. This will also have to restore 13228 // the system pkg from system partition 13229 // reader 13230 synchronized (mPackages) { 13231 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13232 } 13233 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13234 + " disabledPs=" + disabledPs); 13235 if (disabledPs == null) { 13236 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13237 return false; 13238 } else if (DEBUG_REMOVE) { 13239 Slog.d(TAG, "Deleting system pkg from data partition"); 13240 } 13241 if (DEBUG_REMOVE) { 13242 if (applyUserRestrictions) { 13243 Slog.d(TAG, "Remembering install states:"); 13244 for (int i = 0; i < allUserHandles.length; i++) { 13245 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13246 } 13247 } 13248 } 13249 // Delete the updated package 13250 outInfo.isRemovedPackageSystemUpdate = true; 13251 if (disabledPs.versionCode < newPs.versionCode) { 13252 // Delete data for downgrades 13253 flags &= ~PackageManager.DELETE_KEEP_DATA; 13254 } else { 13255 // Preserve data by setting flag 13256 flags |= PackageManager.DELETE_KEEP_DATA; 13257 } 13258 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13259 allUserHandles, perUserInstalled, outInfo, writeSettings); 13260 if (!ret) { 13261 return false; 13262 } 13263 // writer 13264 synchronized (mPackages) { 13265 // Reinstate the old system package 13266 mSettings.enableSystemPackageLPw(newPs.name); 13267 // Remove any native libraries from the upgraded package. 13268 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13269 } 13270 // Install the system package 13271 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13272 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13273 if (locationIsPrivileged(disabledPs.codePath)) { 13274 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13275 } 13276 13277 final PackageParser.Package newPkg; 13278 try { 13279 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, 13280 UserHandle.SYSTEM); 13281 } catch (PackageManagerException e) { 13282 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13283 return false; 13284 } 13285 13286 // writer 13287 synchronized (mPackages) { 13288 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13289 13290 // Propagate the permissions state as we do not want to drop on the floor 13291 // runtime permissions. The update permissions method below will take 13292 // care of removing obsolete permissions and grant install permissions. 13293 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13294 updatePermissionsLPw(newPkg.packageName, newPkg, 13295 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13296 13297 if (applyUserRestrictions) { 13298 if (DEBUG_REMOVE) { 13299 Slog.d(TAG, "Propagating install state across reinstall"); 13300 } 13301 for (int i = 0; i < allUserHandles.length; i++) { 13302 if (DEBUG_REMOVE) { 13303 Slog.d(TAG, " user " + allUserHandles[i] 13304 + " => " + perUserInstalled[i]); 13305 } 13306 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13307 13308 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13309 } 13310 // Regardless of writeSettings we need to ensure that this restriction 13311 // state propagation is persisted 13312 mSettings.writeAllUsersPackageRestrictionsLPr(); 13313 } 13314 // can downgrade to reader here 13315 if (writeSettings) { 13316 mSettings.writeLPr(); 13317 } 13318 } 13319 return true; 13320 } 13321 13322 private boolean deleteInstalledPackageLI(PackageSetting ps, 13323 boolean deleteCodeAndResources, int flags, 13324 int[] allUserHandles, boolean[] perUserInstalled, 13325 PackageRemovedInfo outInfo, boolean writeSettings) { 13326 if (outInfo != null) { 13327 outInfo.uid = ps.appId; 13328 } 13329 13330 // Delete package data from internal structures and also remove data if flag is set 13331 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13332 13333 // Delete application code and resources 13334 if (deleteCodeAndResources && (outInfo != null)) { 13335 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13336 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13337 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13338 } 13339 return true; 13340 } 13341 13342 @Override 13343 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13344 int userId) { 13345 mContext.enforceCallingOrSelfPermission( 13346 android.Manifest.permission.DELETE_PACKAGES, null); 13347 synchronized (mPackages) { 13348 PackageSetting ps = mSettings.mPackages.get(packageName); 13349 if (ps == null) { 13350 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13351 return false; 13352 } 13353 if (!ps.getInstalled(userId)) { 13354 // Can't block uninstall for an app that is not installed or enabled. 13355 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13356 return false; 13357 } 13358 ps.setBlockUninstall(blockUninstall, userId); 13359 mSettings.writePackageRestrictionsLPr(userId); 13360 } 13361 return true; 13362 } 13363 13364 @Override 13365 public boolean getBlockUninstallForUser(String packageName, int userId) { 13366 synchronized (mPackages) { 13367 PackageSetting ps = mSettings.mPackages.get(packageName); 13368 if (ps == null) { 13369 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13370 return false; 13371 } 13372 return ps.getBlockUninstall(userId); 13373 } 13374 } 13375 13376 /* 13377 * This method handles package deletion in general 13378 */ 13379 private boolean deletePackageLI(String packageName, UserHandle user, 13380 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13381 int flags, PackageRemovedInfo outInfo, 13382 boolean writeSettings) { 13383 if (packageName == null) { 13384 Slog.w(TAG, "Attempt to delete null packageName."); 13385 return false; 13386 } 13387 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13388 PackageSetting ps; 13389 boolean dataOnly = false; 13390 int removeUser = -1; 13391 int appId = -1; 13392 synchronized (mPackages) { 13393 ps = mSettings.mPackages.get(packageName); 13394 if (ps == null) { 13395 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13396 return false; 13397 } 13398 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13399 && user.getIdentifier() != UserHandle.USER_ALL) { 13400 // The caller is asking that the package only be deleted for a single 13401 // user. To do this, we just mark its uninstalled state and delete 13402 // its data. If this is a system app, we only allow this to happen if 13403 // they have set the special DELETE_SYSTEM_APP which requests different 13404 // semantics than normal for uninstalling system apps. 13405 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13406 final int userId = user.getIdentifier(); 13407 ps.setUserState(userId, 13408 COMPONENT_ENABLED_STATE_DEFAULT, 13409 false, //installed 13410 true, //stopped 13411 true, //notLaunched 13412 false, //hidden 13413 null, null, null, 13414 false, // blockUninstall 13415 ps.readUserState(userId).domainVerificationStatus, 0); 13416 if (!isSystemApp(ps)) { 13417 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13418 // Other user still have this package installed, so all 13419 // we need to do is clear this user's data and save that 13420 // it is uninstalled. 13421 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13422 removeUser = user.getIdentifier(); 13423 appId = ps.appId; 13424 scheduleWritePackageRestrictionsLocked(removeUser); 13425 } else { 13426 // We need to set it back to 'installed' so the uninstall 13427 // broadcasts will be sent correctly. 13428 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13429 ps.setInstalled(true, user.getIdentifier()); 13430 } 13431 } else { 13432 // This is a system app, so we assume that the 13433 // other users still have this package installed, so all 13434 // we need to do is clear this user's data and save that 13435 // it is uninstalled. 13436 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13437 removeUser = user.getIdentifier(); 13438 appId = ps.appId; 13439 scheduleWritePackageRestrictionsLocked(removeUser); 13440 } 13441 } 13442 } 13443 13444 if (removeUser >= 0) { 13445 // From above, we determined that we are deleting this only 13446 // for a single user. Continue the work here. 13447 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13448 if (outInfo != null) { 13449 outInfo.removedPackage = packageName; 13450 outInfo.removedAppId = appId; 13451 outInfo.removedUsers = new int[] {removeUser}; 13452 } 13453 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13454 removeKeystoreDataIfNeeded(removeUser, appId); 13455 schedulePackageCleaning(packageName, removeUser, false); 13456 synchronized (mPackages) { 13457 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13458 scheduleWritePackageRestrictionsLocked(removeUser); 13459 } 13460 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13461 } 13462 return true; 13463 } 13464 13465 if (dataOnly) { 13466 // Delete application data first 13467 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13468 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13469 return true; 13470 } 13471 13472 boolean ret = false; 13473 if (isSystemApp(ps)) { 13474 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13475 // When an updated system application is deleted we delete the existing resources as well and 13476 // fall back to existing code in system partition 13477 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13478 flags, outInfo, writeSettings); 13479 } else { 13480 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13481 // Kill application pre-emptively especially for apps on sd. 13482 killApplication(packageName, ps.appId, "uninstall pkg"); 13483 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13484 allUserHandles, perUserInstalled, 13485 outInfo, writeSettings); 13486 } 13487 13488 return ret; 13489 } 13490 13491 private final class ClearStorageConnection implements ServiceConnection { 13492 IMediaContainerService mContainerService; 13493 13494 @Override 13495 public void onServiceConnected(ComponentName name, IBinder service) { 13496 synchronized (this) { 13497 mContainerService = IMediaContainerService.Stub.asInterface(service); 13498 notifyAll(); 13499 } 13500 } 13501 13502 @Override 13503 public void onServiceDisconnected(ComponentName name) { 13504 } 13505 } 13506 13507 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13508 final boolean mounted; 13509 if (Environment.isExternalStorageEmulated()) { 13510 mounted = true; 13511 } else { 13512 final String status = Environment.getExternalStorageState(); 13513 13514 mounted = status.equals(Environment.MEDIA_MOUNTED) 13515 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13516 } 13517 13518 if (!mounted) { 13519 return; 13520 } 13521 13522 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13523 int[] users; 13524 if (userId == UserHandle.USER_ALL) { 13525 users = sUserManager.getUserIds(); 13526 } else { 13527 users = new int[] { userId }; 13528 } 13529 final ClearStorageConnection conn = new ClearStorageConnection(); 13530 if (mContext.bindServiceAsUser( 13531 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13532 try { 13533 for (int curUser : users) { 13534 long timeout = SystemClock.uptimeMillis() + 5000; 13535 synchronized (conn) { 13536 long now = SystemClock.uptimeMillis(); 13537 while (conn.mContainerService == null && now < timeout) { 13538 try { 13539 conn.wait(timeout - now); 13540 } catch (InterruptedException e) { 13541 } 13542 } 13543 } 13544 if (conn.mContainerService == null) { 13545 return; 13546 } 13547 13548 final UserEnvironment userEnv = new UserEnvironment(curUser); 13549 clearDirectory(conn.mContainerService, 13550 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13551 if (allData) { 13552 clearDirectory(conn.mContainerService, 13553 userEnv.buildExternalStorageAppDataDirs(packageName)); 13554 clearDirectory(conn.mContainerService, 13555 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13556 } 13557 } 13558 } finally { 13559 mContext.unbindService(conn); 13560 } 13561 } 13562 } 13563 13564 @Override 13565 public void clearApplicationUserData(final String packageName, 13566 final IPackageDataObserver observer, final int userId) { 13567 mContext.enforceCallingOrSelfPermission( 13568 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13569 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13570 // Queue up an async operation since the package deletion may take a little while. 13571 mHandler.post(new Runnable() { 13572 public void run() { 13573 mHandler.removeCallbacks(this); 13574 final boolean succeeded; 13575 synchronized (mInstallLock) { 13576 succeeded = clearApplicationUserDataLI(packageName, userId); 13577 } 13578 clearExternalStorageDataSync(packageName, userId, true); 13579 if (succeeded) { 13580 // invoke DeviceStorageMonitor's update method to clear any notifications 13581 DeviceStorageMonitorInternal 13582 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13583 if (dsm != null) { 13584 dsm.checkMemory(); 13585 } 13586 } 13587 if(observer != null) { 13588 try { 13589 observer.onRemoveCompleted(packageName, succeeded); 13590 } catch (RemoteException e) { 13591 Log.i(TAG, "Observer no longer exists."); 13592 } 13593 } //end if observer 13594 } //end run 13595 }); 13596 } 13597 13598 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13599 if (packageName == null) { 13600 Slog.w(TAG, "Attempt to delete null packageName."); 13601 return false; 13602 } 13603 13604 // Try finding details about the requested package 13605 PackageParser.Package pkg; 13606 synchronized (mPackages) { 13607 pkg = mPackages.get(packageName); 13608 if (pkg == null) { 13609 final PackageSetting ps = mSettings.mPackages.get(packageName); 13610 if (ps != null) { 13611 pkg = ps.pkg; 13612 } 13613 } 13614 13615 if (pkg == null) { 13616 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13617 return false; 13618 } 13619 13620 PackageSetting ps = (PackageSetting) pkg.mExtras; 13621 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13622 } 13623 13624 // Always delete data directories for package, even if we found no other 13625 // record of app. This helps users recover from UID mismatches without 13626 // resorting to a full data wipe. 13627 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13628 if (retCode < 0) { 13629 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13630 return false; 13631 } 13632 13633 final int appId = pkg.applicationInfo.uid; 13634 removeKeystoreDataIfNeeded(userId, appId); 13635 13636 // Create a native library symlink only if we have native libraries 13637 // and if the native libraries are 32 bit libraries. We do not provide 13638 // this symlink for 64 bit libraries. 13639 if (pkg.applicationInfo.primaryCpuAbi != null && 13640 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13641 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13642 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13643 nativeLibPath, userId) < 0) { 13644 Slog.w(TAG, "Failed linking native library dir"); 13645 return false; 13646 } 13647 } 13648 13649 return true; 13650 } 13651 13652 /** 13653 * Reverts user permission state changes (permissions and flags) in 13654 * all packages for a given user. 13655 * 13656 * @param userId The device user for which to do a reset. 13657 */ 13658 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13659 final int packageCount = mPackages.size(); 13660 for (int i = 0; i < packageCount; i++) { 13661 PackageParser.Package pkg = mPackages.valueAt(i); 13662 PackageSetting ps = (PackageSetting) pkg.mExtras; 13663 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13664 } 13665 } 13666 13667 /** 13668 * Reverts user permission state changes (permissions and flags). 13669 * 13670 * @param ps The package for which to reset. 13671 * @param userId The device user for which to do a reset. 13672 */ 13673 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13674 final PackageSetting ps, final int userId) { 13675 if (ps.pkg == null) { 13676 return; 13677 } 13678 13679 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13680 | FLAG_PERMISSION_USER_FIXED 13681 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13682 13683 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13684 | FLAG_PERMISSION_POLICY_FIXED; 13685 13686 boolean writeInstallPermissions = false; 13687 boolean writeRuntimePermissions = false; 13688 13689 final int permissionCount = ps.pkg.requestedPermissions.size(); 13690 for (int i = 0; i < permissionCount; i++) { 13691 String permission = ps.pkg.requestedPermissions.get(i); 13692 13693 BasePermission bp = mSettings.mPermissions.get(permission); 13694 if (bp == null) { 13695 continue; 13696 } 13697 13698 // If shared user we just reset the state to which only this app contributed. 13699 if (ps.sharedUser != null) { 13700 boolean used = false; 13701 final int packageCount = ps.sharedUser.packages.size(); 13702 for (int j = 0; j < packageCount; j++) { 13703 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13704 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13705 && pkg.pkg.requestedPermissions.contains(permission)) { 13706 used = true; 13707 break; 13708 } 13709 } 13710 if (used) { 13711 continue; 13712 } 13713 } 13714 13715 PermissionsState permissionsState = ps.getPermissionsState(); 13716 13717 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13718 13719 // Always clear the user settable flags. 13720 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13721 bp.name) != null; 13722 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13723 if (hasInstallState) { 13724 writeInstallPermissions = true; 13725 } else { 13726 writeRuntimePermissions = true; 13727 } 13728 } 13729 13730 // Below is only runtime permission handling. 13731 if (!bp.isRuntime()) { 13732 continue; 13733 } 13734 13735 // Never clobber system or policy. 13736 if ((oldFlags & policyOrSystemFlags) != 0) { 13737 continue; 13738 } 13739 13740 // If this permission was granted by default, make sure it is. 13741 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13742 if (permissionsState.grantRuntimePermission(bp, userId) 13743 != PERMISSION_OPERATION_FAILURE) { 13744 writeRuntimePermissions = true; 13745 } 13746 } else { 13747 // Otherwise, reset the permission. 13748 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13749 switch (revokeResult) { 13750 case PERMISSION_OPERATION_SUCCESS: { 13751 writeRuntimePermissions = true; 13752 } break; 13753 13754 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13755 writeRuntimePermissions = true; 13756 final int appId = ps.appId; 13757 mHandler.post(new Runnable() { 13758 @Override 13759 public void run() { 13760 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13761 } 13762 }); 13763 } break; 13764 } 13765 } 13766 } 13767 13768 // Synchronously write as we are taking permissions away. 13769 if (writeRuntimePermissions) { 13770 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13771 } 13772 13773 // Synchronously write as we are taking permissions away. 13774 if (writeInstallPermissions) { 13775 mSettings.writeLPr(); 13776 } 13777 } 13778 13779 /** 13780 * Remove entries from the keystore daemon. Will only remove it if the 13781 * {@code appId} is valid. 13782 */ 13783 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13784 if (appId < 0) { 13785 return; 13786 } 13787 13788 final KeyStore keyStore = KeyStore.getInstance(); 13789 if (keyStore != null) { 13790 if (userId == UserHandle.USER_ALL) { 13791 for (final int individual : sUserManager.getUserIds()) { 13792 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13793 } 13794 } else { 13795 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13796 } 13797 } else { 13798 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13799 } 13800 } 13801 13802 @Override 13803 public void deleteApplicationCacheFiles(final String packageName, 13804 final IPackageDataObserver observer) { 13805 mContext.enforceCallingOrSelfPermission( 13806 android.Manifest.permission.DELETE_CACHE_FILES, null); 13807 // Queue up an async operation since the package deletion may take a little while. 13808 final int userId = UserHandle.getCallingUserId(); 13809 mHandler.post(new Runnable() { 13810 public void run() { 13811 mHandler.removeCallbacks(this); 13812 final boolean succeded; 13813 synchronized (mInstallLock) { 13814 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13815 } 13816 clearExternalStorageDataSync(packageName, userId, false); 13817 if (observer != null) { 13818 try { 13819 observer.onRemoveCompleted(packageName, succeded); 13820 } catch (RemoteException e) { 13821 Log.i(TAG, "Observer no longer exists."); 13822 } 13823 } //end if observer 13824 } //end run 13825 }); 13826 } 13827 13828 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13829 if (packageName == null) { 13830 Slog.w(TAG, "Attempt to delete null packageName."); 13831 return false; 13832 } 13833 PackageParser.Package p; 13834 synchronized (mPackages) { 13835 p = mPackages.get(packageName); 13836 } 13837 if (p == null) { 13838 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13839 return false; 13840 } 13841 final ApplicationInfo applicationInfo = p.applicationInfo; 13842 if (applicationInfo == null) { 13843 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13844 return false; 13845 } 13846 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13847 if (retCode < 0) { 13848 Slog.w(TAG, "Couldn't remove cache files for package: " 13849 + packageName + " u" + userId); 13850 return false; 13851 } 13852 return true; 13853 } 13854 13855 @Override 13856 public void getPackageSizeInfo(final String packageName, int userHandle, 13857 final IPackageStatsObserver observer) { 13858 mContext.enforceCallingOrSelfPermission( 13859 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13860 if (packageName == null) { 13861 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13862 } 13863 13864 PackageStats stats = new PackageStats(packageName, userHandle); 13865 13866 /* 13867 * Queue up an async operation since the package measurement may take a 13868 * little while. 13869 */ 13870 Message msg = mHandler.obtainMessage(INIT_COPY); 13871 msg.obj = new MeasureParams(stats, observer); 13872 mHandler.sendMessage(msg); 13873 } 13874 13875 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13876 PackageStats pStats) { 13877 if (packageName == null) { 13878 Slog.w(TAG, "Attempt to get size of null packageName."); 13879 return false; 13880 } 13881 PackageParser.Package p; 13882 boolean dataOnly = false; 13883 String libDirRoot = null; 13884 String asecPath = null; 13885 PackageSetting ps = null; 13886 synchronized (mPackages) { 13887 p = mPackages.get(packageName); 13888 ps = mSettings.mPackages.get(packageName); 13889 if(p == null) { 13890 dataOnly = true; 13891 if((ps == null) || (ps.pkg == null)) { 13892 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13893 return false; 13894 } 13895 p = ps.pkg; 13896 } 13897 if (ps != null) { 13898 libDirRoot = ps.legacyNativeLibraryPathString; 13899 } 13900 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13901 final long token = Binder.clearCallingIdentity(); 13902 try { 13903 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13904 if (secureContainerId != null) { 13905 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13906 } 13907 } finally { 13908 Binder.restoreCallingIdentity(token); 13909 } 13910 } 13911 } 13912 String publicSrcDir = null; 13913 if(!dataOnly) { 13914 final ApplicationInfo applicationInfo = p.applicationInfo; 13915 if (applicationInfo == null) { 13916 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13917 return false; 13918 } 13919 if (p.isForwardLocked()) { 13920 publicSrcDir = applicationInfo.getBaseResourcePath(); 13921 } 13922 } 13923 // TODO: extend to measure size of split APKs 13924 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13925 // not just the first level. 13926 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13927 // just the primary. 13928 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13929 13930 String apkPath; 13931 File packageDir = new File(p.codePath); 13932 13933 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13934 apkPath = packageDir.getAbsolutePath(); 13935 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13936 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13937 libDirRoot = null; 13938 } 13939 } else { 13940 apkPath = p.baseCodePath; 13941 } 13942 13943 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13944 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13945 if (res < 0) { 13946 return false; 13947 } 13948 13949 // Fix-up for forward-locked applications in ASEC containers. 13950 if (!isExternal(p)) { 13951 pStats.codeSize += pStats.externalCodeSize; 13952 pStats.externalCodeSize = 0L; 13953 } 13954 13955 return true; 13956 } 13957 13958 13959 @Override 13960 public void addPackageToPreferred(String packageName) { 13961 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13962 } 13963 13964 @Override 13965 public void removePackageFromPreferred(String packageName) { 13966 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13967 } 13968 13969 @Override 13970 public List<PackageInfo> getPreferredPackages(int flags) { 13971 return new ArrayList<PackageInfo>(); 13972 } 13973 13974 private int getUidTargetSdkVersionLockedLPr(int uid) { 13975 Object obj = mSettings.getUserIdLPr(uid); 13976 if (obj instanceof SharedUserSetting) { 13977 final SharedUserSetting sus = (SharedUserSetting) obj; 13978 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13979 final Iterator<PackageSetting> it = sus.packages.iterator(); 13980 while (it.hasNext()) { 13981 final PackageSetting ps = it.next(); 13982 if (ps.pkg != null) { 13983 int v = ps.pkg.applicationInfo.targetSdkVersion; 13984 if (v < vers) vers = v; 13985 } 13986 } 13987 return vers; 13988 } else if (obj instanceof PackageSetting) { 13989 final PackageSetting ps = (PackageSetting) obj; 13990 if (ps.pkg != null) { 13991 return ps.pkg.applicationInfo.targetSdkVersion; 13992 } 13993 } 13994 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13995 } 13996 13997 @Override 13998 public void addPreferredActivity(IntentFilter filter, int match, 13999 ComponentName[] set, ComponentName activity, int userId) { 14000 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14001 "Adding preferred"); 14002 } 14003 14004 private void addPreferredActivityInternal(IntentFilter filter, int match, 14005 ComponentName[] set, ComponentName activity, boolean always, int userId, 14006 String opname) { 14007 // writer 14008 int callingUid = Binder.getCallingUid(); 14009 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14010 if (filter.countActions() == 0) { 14011 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14012 return; 14013 } 14014 synchronized (mPackages) { 14015 if (mContext.checkCallingOrSelfPermission( 14016 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14017 != PackageManager.PERMISSION_GRANTED) { 14018 if (getUidTargetSdkVersionLockedLPr(callingUid) 14019 < Build.VERSION_CODES.FROYO) { 14020 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14021 + callingUid); 14022 return; 14023 } 14024 mContext.enforceCallingOrSelfPermission( 14025 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14026 } 14027 14028 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14029 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14030 + userId + ":"); 14031 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14032 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14033 scheduleWritePackageRestrictionsLocked(userId); 14034 } 14035 } 14036 14037 @Override 14038 public void replacePreferredActivity(IntentFilter filter, int match, 14039 ComponentName[] set, ComponentName activity, int userId) { 14040 if (filter.countActions() != 1) { 14041 throw new IllegalArgumentException( 14042 "replacePreferredActivity expects filter to have only 1 action."); 14043 } 14044 if (filter.countDataAuthorities() != 0 14045 || filter.countDataPaths() != 0 14046 || filter.countDataSchemes() > 1 14047 || filter.countDataTypes() != 0) { 14048 throw new IllegalArgumentException( 14049 "replacePreferredActivity expects filter to have no data authorities, " + 14050 "paths, or types; and at most one scheme."); 14051 } 14052 14053 final int callingUid = Binder.getCallingUid(); 14054 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14055 synchronized (mPackages) { 14056 if (mContext.checkCallingOrSelfPermission( 14057 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14058 != PackageManager.PERMISSION_GRANTED) { 14059 if (getUidTargetSdkVersionLockedLPr(callingUid) 14060 < Build.VERSION_CODES.FROYO) { 14061 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14062 + Binder.getCallingUid()); 14063 return; 14064 } 14065 mContext.enforceCallingOrSelfPermission( 14066 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14067 } 14068 14069 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14070 if (pir != null) { 14071 // Get all of the existing entries that exactly match this filter. 14072 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14073 if (existing != null && existing.size() == 1) { 14074 PreferredActivity cur = existing.get(0); 14075 if (DEBUG_PREFERRED) { 14076 Slog.i(TAG, "Checking replace of preferred:"); 14077 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14078 if (!cur.mPref.mAlways) { 14079 Slog.i(TAG, " -- CUR; not mAlways!"); 14080 } else { 14081 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14082 Slog.i(TAG, " -- CUR: mSet=" 14083 + Arrays.toString(cur.mPref.mSetComponents)); 14084 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14085 Slog.i(TAG, " -- NEW: mMatch=" 14086 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14087 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14088 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14089 } 14090 } 14091 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14092 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14093 && cur.mPref.sameSet(set)) { 14094 // Setting the preferred activity to what it happens to be already 14095 if (DEBUG_PREFERRED) { 14096 Slog.i(TAG, "Replacing with same preferred activity " 14097 + cur.mPref.mShortComponent + " for user " 14098 + userId + ":"); 14099 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14100 } 14101 return; 14102 } 14103 } 14104 14105 if (existing != null) { 14106 if (DEBUG_PREFERRED) { 14107 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14108 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14109 } 14110 for (int i = 0; i < existing.size(); i++) { 14111 PreferredActivity pa = existing.get(i); 14112 if (DEBUG_PREFERRED) { 14113 Slog.i(TAG, "Removing existing preferred activity " 14114 + pa.mPref.mComponent + ":"); 14115 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14116 } 14117 pir.removeFilter(pa); 14118 } 14119 } 14120 } 14121 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14122 "Replacing preferred"); 14123 } 14124 } 14125 14126 @Override 14127 public void clearPackagePreferredActivities(String packageName) { 14128 final int uid = Binder.getCallingUid(); 14129 // writer 14130 synchronized (mPackages) { 14131 PackageParser.Package pkg = mPackages.get(packageName); 14132 if (pkg == null || pkg.applicationInfo.uid != uid) { 14133 if (mContext.checkCallingOrSelfPermission( 14134 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14135 != PackageManager.PERMISSION_GRANTED) { 14136 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14137 < Build.VERSION_CODES.FROYO) { 14138 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14139 + Binder.getCallingUid()); 14140 return; 14141 } 14142 mContext.enforceCallingOrSelfPermission( 14143 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14144 } 14145 } 14146 14147 int user = UserHandle.getCallingUserId(); 14148 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14149 scheduleWritePackageRestrictionsLocked(user); 14150 } 14151 } 14152 } 14153 14154 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14155 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14156 ArrayList<PreferredActivity> removed = null; 14157 boolean changed = false; 14158 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14159 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14160 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14161 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14162 continue; 14163 } 14164 Iterator<PreferredActivity> it = pir.filterIterator(); 14165 while (it.hasNext()) { 14166 PreferredActivity pa = it.next(); 14167 // Mark entry for removal only if it matches the package name 14168 // and the entry is of type "always". 14169 if (packageName == null || 14170 (pa.mPref.mComponent.getPackageName().equals(packageName) 14171 && pa.mPref.mAlways)) { 14172 if (removed == null) { 14173 removed = new ArrayList<PreferredActivity>(); 14174 } 14175 removed.add(pa); 14176 } 14177 } 14178 if (removed != null) { 14179 for (int j=0; j<removed.size(); j++) { 14180 PreferredActivity pa = removed.get(j); 14181 pir.removeFilter(pa); 14182 } 14183 changed = true; 14184 } 14185 } 14186 return changed; 14187 } 14188 14189 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14190 private void clearIntentFilterVerificationsLPw(int userId) { 14191 final int packageCount = mPackages.size(); 14192 for (int i = 0; i < packageCount; i++) { 14193 PackageParser.Package pkg = mPackages.valueAt(i); 14194 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14195 } 14196 } 14197 14198 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14199 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14200 if (userId == UserHandle.USER_ALL) { 14201 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14202 sUserManager.getUserIds())) { 14203 for (int oneUserId : sUserManager.getUserIds()) { 14204 scheduleWritePackageRestrictionsLocked(oneUserId); 14205 } 14206 } 14207 } else { 14208 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14209 scheduleWritePackageRestrictionsLocked(userId); 14210 } 14211 } 14212 } 14213 14214 void clearDefaultBrowserIfNeeded(String packageName) { 14215 for (int oneUserId : sUserManager.getUserIds()) { 14216 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14217 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14218 if (packageName.equals(defaultBrowserPackageName)) { 14219 setDefaultBrowserPackageName(null, oneUserId); 14220 } 14221 } 14222 } 14223 14224 @Override 14225 public void resetApplicationPreferences(int userId) { 14226 mContext.enforceCallingOrSelfPermission( 14227 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14228 // writer 14229 synchronized (mPackages) { 14230 final long identity = Binder.clearCallingIdentity(); 14231 try { 14232 clearPackagePreferredActivitiesLPw(null, userId); 14233 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14234 // TODO: We have to reset the default SMS and Phone. This requires 14235 // significant refactoring to keep all default apps in the package 14236 // manager (cleaner but more work) or have the services provide 14237 // callbacks to the package manager to request a default app reset. 14238 applyFactoryDefaultBrowserLPw(userId); 14239 clearIntentFilterVerificationsLPw(userId); 14240 primeDomainVerificationsLPw(userId); 14241 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14242 scheduleWritePackageRestrictionsLocked(userId); 14243 } finally { 14244 Binder.restoreCallingIdentity(identity); 14245 } 14246 } 14247 } 14248 14249 @Override 14250 public int getPreferredActivities(List<IntentFilter> outFilters, 14251 List<ComponentName> outActivities, String packageName) { 14252 14253 int num = 0; 14254 final int userId = UserHandle.getCallingUserId(); 14255 // reader 14256 synchronized (mPackages) { 14257 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14258 if (pir != null) { 14259 final Iterator<PreferredActivity> it = pir.filterIterator(); 14260 while (it.hasNext()) { 14261 final PreferredActivity pa = it.next(); 14262 if (packageName == null 14263 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14264 && pa.mPref.mAlways)) { 14265 if (outFilters != null) { 14266 outFilters.add(new IntentFilter(pa)); 14267 } 14268 if (outActivities != null) { 14269 outActivities.add(pa.mPref.mComponent); 14270 } 14271 } 14272 } 14273 } 14274 } 14275 14276 return num; 14277 } 14278 14279 @Override 14280 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14281 int userId) { 14282 int callingUid = Binder.getCallingUid(); 14283 if (callingUid != Process.SYSTEM_UID) { 14284 throw new SecurityException( 14285 "addPersistentPreferredActivity can only be run by the system"); 14286 } 14287 if (filter.countActions() == 0) { 14288 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14289 return; 14290 } 14291 synchronized (mPackages) { 14292 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14293 " :"); 14294 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14295 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14296 new PersistentPreferredActivity(filter, activity)); 14297 scheduleWritePackageRestrictionsLocked(userId); 14298 } 14299 } 14300 14301 @Override 14302 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14303 int callingUid = Binder.getCallingUid(); 14304 if (callingUid != Process.SYSTEM_UID) { 14305 throw new SecurityException( 14306 "clearPackagePersistentPreferredActivities can only be run by the system"); 14307 } 14308 ArrayList<PersistentPreferredActivity> removed = null; 14309 boolean changed = false; 14310 synchronized (mPackages) { 14311 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14312 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14313 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14314 .valueAt(i); 14315 if (userId != thisUserId) { 14316 continue; 14317 } 14318 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14319 while (it.hasNext()) { 14320 PersistentPreferredActivity ppa = it.next(); 14321 // Mark entry for removal only if it matches the package name. 14322 if (ppa.mComponent.getPackageName().equals(packageName)) { 14323 if (removed == null) { 14324 removed = new ArrayList<PersistentPreferredActivity>(); 14325 } 14326 removed.add(ppa); 14327 } 14328 } 14329 if (removed != null) { 14330 for (int j=0; j<removed.size(); j++) { 14331 PersistentPreferredActivity ppa = removed.get(j); 14332 ppir.removeFilter(ppa); 14333 } 14334 changed = true; 14335 } 14336 } 14337 14338 if (changed) { 14339 scheduleWritePackageRestrictionsLocked(userId); 14340 } 14341 } 14342 } 14343 14344 /** 14345 * Common machinery for picking apart a restored XML blob and passing 14346 * it to a caller-supplied functor to be applied to the running system. 14347 */ 14348 private void restoreFromXml(XmlPullParser parser, int userId, 14349 String expectedStartTag, BlobXmlRestorer functor) 14350 throws IOException, XmlPullParserException { 14351 int type; 14352 while ((type = parser.next()) != XmlPullParser.START_TAG 14353 && type != XmlPullParser.END_DOCUMENT) { 14354 } 14355 if (type != XmlPullParser.START_TAG) { 14356 // oops didn't find a start tag?! 14357 if (DEBUG_BACKUP) { 14358 Slog.e(TAG, "Didn't find start tag during restore"); 14359 } 14360 return; 14361 } 14362 14363 // this is supposed to be TAG_PREFERRED_BACKUP 14364 if (!expectedStartTag.equals(parser.getName())) { 14365 if (DEBUG_BACKUP) { 14366 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14367 } 14368 return; 14369 } 14370 14371 // skip interfering stuff, then we're aligned with the backing implementation 14372 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14373 functor.apply(parser, userId); 14374 } 14375 14376 private interface BlobXmlRestorer { 14377 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14378 } 14379 14380 /** 14381 * Non-Binder method, support for the backup/restore mechanism: write the 14382 * full set of preferred activities in its canonical XML format. Returns the 14383 * XML output as a byte array, or null if there is none. 14384 */ 14385 @Override 14386 public byte[] getPreferredActivityBackup(int userId) { 14387 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14388 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14389 } 14390 14391 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14392 try { 14393 final XmlSerializer serializer = new FastXmlSerializer(); 14394 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14395 serializer.startDocument(null, true); 14396 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14397 14398 synchronized (mPackages) { 14399 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14400 } 14401 14402 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14403 serializer.endDocument(); 14404 serializer.flush(); 14405 } catch (Exception e) { 14406 if (DEBUG_BACKUP) { 14407 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14408 } 14409 return null; 14410 } 14411 14412 return dataStream.toByteArray(); 14413 } 14414 14415 @Override 14416 public void restorePreferredActivities(byte[] backup, int userId) { 14417 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14418 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14419 } 14420 14421 try { 14422 final XmlPullParser parser = Xml.newPullParser(); 14423 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14424 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14425 new BlobXmlRestorer() { 14426 @Override 14427 public void apply(XmlPullParser parser, int userId) 14428 throws XmlPullParserException, IOException { 14429 synchronized (mPackages) { 14430 mSettings.readPreferredActivitiesLPw(parser, userId); 14431 } 14432 } 14433 } ); 14434 } catch (Exception e) { 14435 if (DEBUG_BACKUP) { 14436 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14437 } 14438 } 14439 } 14440 14441 /** 14442 * Non-Binder method, support for the backup/restore mechanism: write the 14443 * default browser (etc) settings in its canonical XML format. Returns the default 14444 * browser XML representation as a byte array, or null if there is none. 14445 */ 14446 @Override 14447 public byte[] getDefaultAppsBackup(int userId) { 14448 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14449 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14450 } 14451 14452 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14453 try { 14454 final XmlSerializer serializer = new FastXmlSerializer(); 14455 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14456 serializer.startDocument(null, true); 14457 serializer.startTag(null, TAG_DEFAULT_APPS); 14458 14459 synchronized (mPackages) { 14460 mSettings.writeDefaultAppsLPr(serializer, userId); 14461 } 14462 14463 serializer.endTag(null, TAG_DEFAULT_APPS); 14464 serializer.endDocument(); 14465 serializer.flush(); 14466 } catch (Exception e) { 14467 if (DEBUG_BACKUP) { 14468 Slog.e(TAG, "Unable to write default apps for backup", e); 14469 } 14470 return null; 14471 } 14472 14473 return dataStream.toByteArray(); 14474 } 14475 14476 @Override 14477 public void restoreDefaultApps(byte[] backup, int userId) { 14478 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14479 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14480 } 14481 14482 try { 14483 final XmlPullParser parser = Xml.newPullParser(); 14484 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14485 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14486 new BlobXmlRestorer() { 14487 @Override 14488 public void apply(XmlPullParser parser, int userId) 14489 throws XmlPullParserException, IOException { 14490 synchronized (mPackages) { 14491 mSettings.readDefaultAppsLPw(parser, userId); 14492 } 14493 } 14494 } ); 14495 } catch (Exception e) { 14496 if (DEBUG_BACKUP) { 14497 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14498 } 14499 } 14500 } 14501 14502 @Override 14503 public byte[] getIntentFilterVerificationBackup(int userId) { 14504 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14505 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14506 } 14507 14508 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14509 try { 14510 final XmlSerializer serializer = new FastXmlSerializer(); 14511 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14512 serializer.startDocument(null, true); 14513 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14514 14515 synchronized (mPackages) { 14516 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14517 } 14518 14519 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14520 serializer.endDocument(); 14521 serializer.flush(); 14522 } catch (Exception e) { 14523 if (DEBUG_BACKUP) { 14524 Slog.e(TAG, "Unable to write default apps for backup", e); 14525 } 14526 return null; 14527 } 14528 14529 return dataStream.toByteArray(); 14530 } 14531 14532 @Override 14533 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14534 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14535 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14536 } 14537 14538 try { 14539 final XmlPullParser parser = Xml.newPullParser(); 14540 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14541 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14542 new BlobXmlRestorer() { 14543 @Override 14544 public void apply(XmlPullParser parser, int userId) 14545 throws XmlPullParserException, IOException { 14546 synchronized (mPackages) { 14547 mSettings.readAllDomainVerificationsLPr(parser, userId); 14548 mSettings.writeLPr(); 14549 } 14550 } 14551 } ); 14552 } catch (Exception e) { 14553 if (DEBUG_BACKUP) { 14554 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14555 } 14556 } 14557 } 14558 14559 @Override 14560 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14561 int sourceUserId, int targetUserId, int flags) { 14562 mContext.enforceCallingOrSelfPermission( 14563 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14564 int callingUid = Binder.getCallingUid(); 14565 enforceOwnerRights(ownerPackage, callingUid); 14566 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14567 if (intentFilter.countActions() == 0) { 14568 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14569 return; 14570 } 14571 synchronized (mPackages) { 14572 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14573 ownerPackage, targetUserId, flags); 14574 CrossProfileIntentResolver resolver = 14575 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14576 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14577 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14578 if (existing != null) { 14579 int size = existing.size(); 14580 for (int i = 0; i < size; i++) { 14581 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14582 return; 14583 } 14584 } 14585 } 14586 resolver.addFilter(newFilter); 14587 scheduleWritePackageRestrictionsLocked(sourceUserId); 14588 } 14589 } 14590 14591 @Override 14592 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14593 mContext.enforceCallingOrSelfPermission( 14594 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14595 int callingUid = Binder.getCallingUid(); 14596 enforceOwnerRights(ownerPackage, callingUid); 14597 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14598 synchronized (mPackages) { 14599 CrossProfileIntentResolver resolver = 14600 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14601 ArraySet<CrossProfileIntentFilter> set = 14602 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14603 for (CrossProfileIntentFilter filter : set) { 14604 if (filter.getOwnerPackage().equals(ownerPackage)) { 14605 resolver.removeFilter(filter); 14606 } 14607 } 14608 scheduleWritePackageRestrictionsLocked(sourceUserId); 14609 } 14610 } 14611 14612 // Enforcing that callingUid is owning pkg on userId 14613 private void enforceOwnerRights(String pkg, int callingUid) { 14614 // The system owns everything. 14615 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14616 return; 14617 } 14618 int callingUserId = UserHandle.getUserId(callingUid); 14619 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14620 if (pi == null) { 14621 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14622 + callingUserId); 14623 } 14624 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14625 throw new SecurityException("Calling uid " + callingUid 14626 + " does not own package " + pkg); 14627 } 14628 } 14629 14630 @Override 14631 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14632 Intent intent = new Intent(Intent.ACTION_MAIN); 14633 intent.addCategory(Intent.CATEGORY_HOME); 14634 14635 final int callingUserId = UserHandle.getCallingUserId(); 14636 List<ResolveInfo> list = queryIntentActivities(intent, null, 14637 PackageManager.GET_META_DATA, callingUserId); 14638 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14639 true, false, false, callingUserId); 14640 14641 allHomeCandidates.clear(); 14642 if (list != null) { 14643 for (ResolveInfo ri : list) { 14644 allHomeCandidates.add(ri); 14645 } 14646 } 14647 return (preferred == null || preferred.activityInfo == null) 14648 ? null 14649 : new ComponentName(preferred.activityInfo.packageName, 14650 preferred.activityInfo.name); 14651 } 14652 14653 @Override 14654 public void setApplicationEnabledSetting(String appPackageName, 14655 int newState, int flags, int userId, String callingPackage) { 14656 if (!sUserManager.exists(userId)) return; 14657 if (callingPackage == null) { 14658 callingPackage = Integer.toString(Binder.getCallingUid()); 14659 } 14660 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14661 } 14662 14663 @Override 14664 public void setComponentEnabledSetting(ComponentName componentName, 14665 int newState, int flags, int userId) { 14666 if (!sUserManager.exists(userId)) return; 14667 setEnabledSetting(componentName.getPackageName(), 14668 componentName.getClassName(), newState, flags, userId, null); 14669 } 14670 14671 private void setEnabledSetting(final String packageName, String className, int newState, 14672 final int flags, int userId, String callingPackage) { 14673 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14674 || newState == COMPONENT_ENABLED_STATE_ENABLED 14675 || newState == COMPONENT_ENABLED_STATE_DISABLED 14676 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14677 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14678 throw new IllegalArgumentException("Invalid new component state: " 14679 + newState); 14680 } 14681 PackageSetting pkgSetting; 14682 final int uid = Binder.getCallingUid(); 14683 final int permission = mContext.checkCallingOrSelfPermission( 14684 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14685 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14686 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14687 boolean sendNow = false; 14688 boolean isApp = (className == null); 14689 String componentName = isApp ? packageName : className; 14690 int packageUid = -1; 14691 ArrayList<String> components; 14692 14693 // writer 14694 synchronized (mPackages) { 14695 pkgSetting = mSettings.mPackages.get(packageName); 14696 if (pkgSetting == null) { 14697 if (className == null) { 14698 throw new IllegalArgumentException( 14699 "Unknown package: " + packageName); 14700 } 14701 throw new IllegalArgumentException( 14702 "Unknown component: " + packageName 14703 + "/" + className); 14704 } 14705 // Allow root and verify that userId is not being specified by a different user 14706 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14707 throw new SecurityException( 14708 "Permission Denial: attempt to change component state from pid=" 14709 + Binder.getCallingPid() 14710 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14711 } 14712 if (className == null) { 14713 // We're dealing with an application/package level state change 14714 if (pkgSetting.getEnabled(userId) == newState) { 14715 // Nothing to do 14716 return; 14717 } 14718 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14719 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14720 // Don't care about who enables an app. 14721 callingPackage = null; 14722 } 14723 pkgSetting.setEnabled(newState, userId, callingPackage); 14724 // pkgSetting.pkg.mSetEnabled = newState; 14725 } else { 14726 // We're dealing with a component level state change 14727 // First, verify that this is a valid class name. 14728 PackageParser.Package pkg = pkgSetting.pkg; 14729 if (pkg == null || !pkg.hasComponentClassName(className)) { 14730 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14731 throw new IllegalArgumentException("Component class " + className 14732 + " does not exist in " + packageName); 14733 } else { 14734 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14735 + className + " does not exist in " + packageName); 14736 } 14737 } 14738 switch (newState) { 14739 case COMPONENT_ENABLED_STATE_ENABLED: 14740 if (!pkgSetting.enableComponentLPw(className, userId)) { 14741 return; 14742 } 14743 break; 14744 case COMPONENT_ENABLED_STATE_DISABLED: 14745 if (!pkgSetting.disableComponentLPw(className, userId)) { 14746 return; 14747 } 14748 break; 14749 case COMPONENT_ENABLED_STATE_DEFAULT: 14750 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14751 return; 14752 } 14753 break; 14754 default: 14755 Slog.e(TAG, "Invalid new component state: " + newState); 14756 return; 14757 } 14758 } 14759 scheduleWritePackageRestrictionsLocked(userId); 14760 components = mPendingBroadcasts.get(userId, packageName); 14761 final boolean newPackage = components == null; 14762 if (newPackage) { 14763 components = new ArrayList<String>(); 14764 } 14765 if (!components.contains(componentName)) { 14766 components.add(componentName); 14767 } 14768 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14769 sendNow = true; 14770 // Purge entry from pending broadcast list if another one exists already 14771 // since we are sending one right away. 14772 mPendingBroadcasts.remove(userId, packageName); 14773 } else { 14774 if (newPackage) { 14775 mPendingBroadcasts.put(userId, packageName, components); 14776 } 14777 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14778 // Schedule a message 14779 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14780 } 14781 } 14782 } 14783 14784 long callingId = Binder.clearCallingIdentity(); 14785 try { 14786 if (sendNow) { 14787 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14788 sendPackageChangedBroadcast(packageName, 14789 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14790 } 14791 } finally { 14792 Binder.restoreCallingIdentity(callingId); 14793 } 14794 } 14795 14796 private void sendPackageChangedBroadcast(String packageName, 14797 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14798 if (DEBUG_INSTALL) 14799 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14800 + componentNames); 14801 Bundle extras = new Bundle(4); 14802 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14803 String nameList[] = new String[componentNames.size()]; 14804 componentNames.toArray(nameList); 14805 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14806 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14807 extras.putInt(Intent.EXTRA_UID, packageUid); 14808 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14809 new int[] {UserHandle.getUserId(packageUid)}); 14810 } 14811 14812 @Override 14813 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14814 if (!sUserManager.exists(userId)) return; 14815 final int uid = Binder.getCallingUid(); 14816 final int permission = mContext.checkCallingOrSelfPermission( 14817 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14818 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14819 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14820 // writer 14821 synchronized (mPackages) { 14822 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14823 allowedByPermission, uid, userId)) { 14824 scheduleWritePackageRestrictionsLocked(userId); 14825 } 14826 } 14827 } 14828 14829 @Override 14830 public String getInstallerPackageName(String packageName) { 14831 // reader 14832 synchronized (mPackages) { 14833 return mSettings.getInstallerPackageNameLPr(packageName); 14834 } 14835 } 14836 14837 @Override 14838 public int getApplicationEnabledSetting(String packageName, int userId) { 14839 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14840 int uid = Binder.getCallingUid(); 14841 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14842 // reader 14843 synchronized (mPackages) { 14844 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14845 } 14846 } 14847 14848 @Override 14849 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14850 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14851 int uid = Binder.getCallingUid(); 14852 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14853 // reader 14854 synchronized (mPackages) { 14855 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14856 } 14857 } 14858 14859 @Override 14860 public void enterSafeMode() { 14861 enforceSystemOrRoot("Only the system can request entering safe mode"); 14862 14863 if (!mSystemReady) { 14864 mSafeMode = true; 14865 } 14866 } 14867 14868 @Override 14869 public void systemReady() { 14870 mSystemReady = true; 14871 14872 // Read the compatibilty setting when the system is ready. 14873 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14874 mContext.getContentResolver(), 14875 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14876 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14877 if (DEBUG_SETTINGS) { 14878 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14879 } 14880 14881 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14882 14883 synchronized (mPackages) { 14884 // Verify that all of the preferred activity components actually 14885 // exist. It is possible for applications to be updated and at 14886 // that point remove a previously declared activity component that 14887 // had been set as a preferred activity. We try to clean this up 14888 // the next time we encounter that preferred activity, but it is 14889 // possible for the user flow to never be able to return to that 14890 // situation so here we do a sanity check to make sure we haven't 14891 // left any junk around. 14892 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14893 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14894 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14895 removed.clear(); 14896 for (PreferredActivity pa : pir.filterSet()) { 14897 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14898 removed.add(pa); 14899 } 14900 } 14901 if (removed.size() > 0) { 14902 for (int r=0; r<removed.size(); r++) { 14903 PreferredActivity pa = removed.get(r); 14904 Slog.w(TAG, "Removing dangling preferred activity: " 14905 + pa.mPref.mComponent); 14906 pir.removeFilter(pa); 14907 } 14908 mSettings.writePackageRestrictionsLPr( 14909 mSettings.mPreferredActivities.keyAt(i)); 14910 } 14911 } 14912 14913 for (int userId : UserManagerService.getInstance().getUserIds()) { 14914 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14915 grantPermissionsUserIds = ArrayUtils.appendInt( 14916 grantPermissionsUserIds, userId); 14917 } 14918 } 14919 } 14920 sUserManager.systemReady(); 14921 14922 // If we upgraded grant all default permissions before kicking off. 14923 for (int userId : grantPermissionsUserIds) { 14924 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14925 } 14926 14927 // Kick off any messages waiting for system ready 14928 if (mPostSystemReadyMessages != null) { 14929 for (Message msg : mPostSystemReadyMessages) { 14930 msg.sendToTarget(); 14931 } 14932 mPostSystemReadyMessages = null; 14933 } 14934 14935 // Watch for external volumes that come and go over time 14936 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14937 storage.registerListener(mStorageListener); 14938 14939 mInstallerService.systemReady(); 14940 mPackageDexOptimizer.systemReady(); 14941 14942 MountServiceInternal mountServiceInternal = LocalServices.getService( 14943 MountServiceInternal.class); 14944 mountServiceInternal.addExternalStoragePolicy( 14945 new MountServiceInternal.ExternalStorageMountPolicy() { 14946 @Override 14947 public int getMountMode(int uid, String packageName) { 14948 if (Process.isIsolated(uid)) { 14949 return Zygote.MOUNT_EXTERNAL_NONE; 14950 } 14951 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14952 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14953 } 14954 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14955 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14956 } 14957 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14958 return Zygote.MOUNT_EXTERNAL_READ; 14959 } 14960 return Zygote.MOUNT_EXTERNAL_WRITE; 14961 } 14962 14963 @Override 14964 public boolean hasExternalStorage(int uid, String packageName) { 14965 return true; 14966 } 14967 }); 14968 } 14969 14970 @Override 14971 public boolean isSafeMode() { 14972 return mSafeMode; 14973 } 14974 14975 @Override 14976 public boolean hasSystemUidErrors() { 14977 return mHasSystemUidErrors; 14978 } 14979 14980 static String arrayToString(int[] array) { 14981 StringBuffer buf = new StringBuffer(128); 14982 buf.append('['); 14983 if (array != null) { 14984 for (int i=0; i<array.length; i++) { 14985 if (i > 0) buf.append(", "); 14986 buf.append(array[i]); 14987 } 14988 } 14989 buf.append(']'); 14990 return buf.toString(); 14991 } 14992 14993 static class DumpState { 14994 public static final int DUMP_LIBS = 1 << 0; 14995 public static final int DUMP_FEATURES = 1 << 1; 14996 public static final int DUMP_RESOLVERS = 1 << 2; 14997 public static final int DUMP_PERMISSIONS = 1 << 3; 14998 public static final int DUMP_PACKAGES = 1 << 4; 14999 public static final int DUMP_SHARED_USERS = 1 << 5; 15000 public static final int DUMP_MESSAGES = 1 << 6; 15001 public static final int DUMP_PROVIDERS = 1 << 7; 15002 public static final int DUMP_VERIFIERS = 1 << 8; 15003 public static final int DUMP_PREFERRED = 1 << 9; 15004 public static final int DUMP_PREFERRED_XML = 1 << 10; 15005 public static final int DUMP_KEYSETS = 1 << 11; 15006 public static final int DUMP_VERSION = 1 << 12; 15007 public static final int DUMP_INSTALLS = 1 << 13; 15008 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 15009 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 15010 15011 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15012 15013 private int mTypes; 15014 15015 private int mOptions; 15016 15017 private boolean mTitlePrinted; 15018 15019 private SharedUserSetting mSharedUser; 15020 15021 public boolean isDumping(int type) { 15022 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15023 return true; 15024 } 15025 15026 return (mTypes & type) != 0; 15027 } 15028 15029 public void setDump(int type) { 15030 mTypes |= type; 15031 } 15032 15033 public boolean isOptionEnabled(int option) { 15034 return (mOptions & option) != 0; 15035 } 15036 15037 public void setOptionEnabled(int option) { 15038 mOptions |= option; 15039 } 15040 15041 public boolean onTitlePrinted() { 15042 final boolean printed = mTitlePrinted; 15043 mTitlePrinted = true; 15044 return printed; 15045 } 15046 15047 public boolean getTitlePrinted() { 15048 return mTitlePrinted; 15049 } 15050 15051 public void setTitlePrinted(boolean enabled) { 15052 mTitlePrinted = enabled; 15053 } 15054 15055 public SharedUserSetting getSharedUser() { 15056 return mSharedUser; 15057 } 15058 15059 public void setSharedUser(SharedUserSetting user) { 15060 mSharedUser = user; 15061 } 15062 } 15063 15064 @Override 15065 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15066 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15067 != PackageManager.PERMISSION_GRANTED) { 15068 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15069 + Binder.getCallingPid() 15070 + ", uid=" + Binder.getCallingUid() 15071 + " without permission " 15072 + android.Manifest.permission.DUMP); 15073 return; 15074 } 15075 15076 DumpState dumpState = new DumpState(); 15077 boolean fullPreferred = false; 15078 boolean checkin = false; 15079 15080 String packageName = null; 15081 ArraySet<String> permissionNames = null; 15082 15083 int opti = 0; 15084 while (opti < args.length) { 15085 String opt = args[opti]; 15086 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15087 break; 15088 } 15089 opti++; 15090 15091 if ("-a".equals(opt)) { 15092 // Right now we only know how to print all. 15093 } else if ("-h".equals(opt)) { 15094 pw.println("Package manager dump options:"); 15095 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15096 pw.println(" --checkin: dump for a checkin"); 15097 pw.println(" -f: print details of intent filters"); 15098 pw.println(" -h: print this help"); 15099 pw.println(" cmd may be one of:"); 15100 pw.println(" l[ibraries]: list known shared libraries"); 15101 pw.println(" f[ibraries]: list device features"); 15102 pw.println(" k[eysets]: print known keysets"); 15103 pw.println(" r[esolvers]: dump intent resolvers"); 15104 pw.println(" perm[issions]: dump permissions"); 15105 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15106 pw.println(" pref[erred]: print preferred package settings"); 15107 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15108 pw.println(" prov[iders]: dump content providers"); 15109 pw.println(" p[ackages]: dump installed packages"); 15110 pw.println(" s[hared-users]: dump shared user IDs"); 15111 pw.println(" m[essages]: print collected runtime messages"); 15112 pw.println(" v[erifiers]: print package verifier info"); 15113 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15114 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15115 pw.println(" version: print database version info"); 15116 pw.println(" write: write current settings now"); 15117 pw.println(" installs: details about install sessions"); 15118 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15119 pw.println(" <package.name>: info about given package"); 15120 return; 15121 } else if ("--checkin".equals(opt)) { 15122 checkin = true; 15123 } else if ("-f".equals(opt)) { 15124 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15125 } else { 15126 pw.println("Unknown argument: " + opt + "; use -h for help"); 15127 } 15128 } 15129 15130 // Is the caller requesting to dump a particular piece of data? 15131 if (opti < args.length) { 15132 String cmd = args[opti]; 15133 opti++; 15134 // Is this a package name? 15135 if ("android".equals(cmd) || cmd.contains(".")) { 15136 packageName = cmd; 15137 // When dumping a single package, we always dump all of its 15138 // filter information since the amount of data will be reasonable. 15139 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15140 } else if ("check-permission".equals(cmd)) { 15141 if (opti >= args.length) { 15142 pw.println("Error: check-permission missing permission argument"); 15143 return; 15144 } 15145 String perm = args[opti]; 15146 opti++; 15147 if (opti >= args.length) { 15148 pw.println("Error: check-permission missing package argument"); 15149 return; 15150 } 15151 String pkg = args[opti]; 15152 opti++; 15153 int user = UserHandle.getUserId(Binder.getCallingUid()); 15154 if (opti < args.length) { 15155 try { 15156 user = Integer.parseInt(args[opti]); 15157 } catch (NumberFormatException e) { 15158 pw.println("Error: check-permission user argument is not a number: " 15159 + args[opti]); 15160 return; 15161 } 15162 } 15163 pw.println(checkPermission(perm, pkg, user)); 15164 return; 15165 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15166 dumpState.setDump(DumpState.DUMP_LIBS); 15167 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15168 dumpState.setDump(DumpState.DUMP_FEATURES); 15169 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15170 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15171 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15172 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15173 } else if ("permission".equals(cmd)) { 15174 if (opti >= args.length) { 15175 pw.println("Error: permission requires permission name"); 15176 return; 15177 } 15178 permissionNames = new ArraySet<>(); 15179 while (opti < args.length) { 15180 permissionNames.add(args[opti]); 15181 opti++; 15182 } 15183 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15184 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15185 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15186 dumpState.setDump(DumpState.DUMP_PREFERRED); 15187 } else if ("preferred-xml".equals(cmd)) { 15188 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15189 if (opti < args.length && "--full".equals(args[opti])) { 15190 fullPreferred = true; 15191 opti++; 15192 } 15193 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15194 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15195 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15196 dumpState.setDump(DumpState.DUMP_PACKAGES); 15197 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15198 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15199 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15200 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15201 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15202 dumpState.setDump(DumpState.DUMP_MESSAGES); 15203 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15204 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15205 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15206 || "intent-filter-verifiers".equals(cmd)) { 15207 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15208 } else if ("version".equals(cmd)) { 15209 dumpState.setDump(DumpState.DUMP_VERSION); 15210 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15211 dumpState.setDump(DumpState.DUMP_KEYSETS); 15212 } else if ("installs".equals(cmd)) { 15213 dumpState.setDump(DumpState.DUMP_INSTALLS); 15214 } else if ("write".equals(cmd)) { 15215 synchronized (mPackages) { 15216 mSettings.writeLPr(); 15217 pw.println("Settings written."); 15218 return; 15219 } 15220 } 15221 } 15222 15223 if (checkin) { 15224 pw.println("vers,1"); 15225 } 15226 15227 // reader 15228 synchronized (mPackages) { 15229 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15230 if (!checkin) { 15231 if (dumpState.onTitlePrinted()) 15232 pw.println(); 15233 pw.println("Database versions:"); 15234 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15235 } 15236 } 15237 15238 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15239 if (!checkin) { 15240 if (dumpState.onTitlePrinted()) 15241 pw.println(); 15242 pw.println("Verifiers:"); 15243 pw.print(" Required: "); 15244 pw.print(mRequiredVerifierPackage); 15245 pw.print(" (uid="); 15246 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15247 pw.println(")"); 15248 } else if (mRequiredVerifierPackage != null) { 15249 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15250 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15251 } 15252 } 15253 15254 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15255 packageName == null) { 15256 if (mIntentFilterVerifierComponent != null) { 15257 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15258 if (!checkin) { 15259 if (dumpState.onTitlePrinted()) 15260 pw.println(); 15261 pw.println("Intent Filter Verifier:"); 15262 pw.print(" Using: "); 15263 pw.print(verifierPackageName); 15264 pw.print(" (uid="); 15265 pw.print(getPackageUid(verifierPackageName, 0)); 15266 pw.println(")"); 15267 } else if (verifierPackageName != null) { 15268 pw.print("ifv,"); pw.print(verifierPackageName); 15269 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15270 } 15271 } else { 15272 pw.println(); 15273 pw.println("No Intent Filter Verifier available!"); 15274 } 15275 } 15276 15277 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15278 boolean printedHeader = false; 15279 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15280 while (it.hasNext()) { 15281 String name = it.next(); 15282 SharedLibraryEntry ent = mSharedLibraries.get(name); 15283 if (!checkin) { 15284 if (!printedHeader) { 15285 if (dumpState.onTitlePrinted()) 15286 pw.println(); 15287 pw.println("Libraries:"); 15288 printedHeader = true; 15289 } 15290 pw.print(" "); 15291 } else { 15292 pw.print("lib,"); 15293 } 15294 pw.print(name); 15295 if (!checkin) { 15296 pw.print(" -> "); 15297 } 15298 if (ent.path != null) { 15299 if (!checkin) { 15300 pw.print("(jar) "); 15301 pw.print(ent.path); 15302 } else { 15303 pw.print(",jar,"); 15304 pw.print(ent.path); 15305 } 15306 } else { 15307 if (!checkin) { 15308 pw.print("(apk) "); 15309 pw.print(ent.apk); 15310 } else { 15311 pw.print(",apk,"); 15312 pw.print(ent.apk); 15313 } 15314 } 15315 pw.println(); 15316 } 15317 } 15318 15319 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15320 if (dumpState.onTitlePrinted()) 15321 pw.println(); 15322 if (!checkin) { 15323 pw.println("Features:"); 15324 } 15325 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15326 while (it.hasNext()) { 15327 String name = it.next(); 15328 if (!checkin) { 15329 pw.print(" "); 15330 } else { 15331 pw.print("feat,"); 15332 } 15333 pw.println(name); 15334 } 15335 } 15336 15337 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15338 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15339 : "Activity Resolver Table:", " ", packageName, 15340 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15341 dumpState.setTitlePrinted(true); 15342 } 15343 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15344 : "Receiver Resolver Table:", " ", packageName, 15345 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15346 dumpState.setTitlePrinted(true); 15347 } 15348 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15349 : "Service Resolver Table:", " ", packageName, 15350 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15351 dumpState.setTitlePrinted(true); 15352 } 15353 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15354 : "Provider Resolver Table:", " ", packageName, 15355 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15356 dumpState.setTitlePrinted(true); 15357 } 15358 } 15359 15360 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15361 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15362 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15363 int user = mSettings.mPreferredActivities.keyAt(i); 15364 if (pir.dump(pw, 15365 dumpState.getTitlePrinted() 15366 ? "\nPreferred Activities User " + user + ":" 15367 : "Preferred Activities User " + user + ":", " ", 15368 packageName, true, false)) { 15369 dumpState.setTitlePrinted(true); 15370 } 15371 } 15372 } 15373 15374 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15375 pw.flush(); 15376 FileOutputStream fout = new FileOutputStream(fd); 15377 BufferedOutputStream str = new BufferedOutputStream(fout); 15378 XmlSerializer serializer = new FastXmlSerializer(); 15379 try { 15380 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15381 serializer.startDocument(null, true); 15382 serializer.setFeature( 15383 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15384 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15385 serializer.endDocument(); 15386 serializer.flush(); 15387 } catch (IllegalArgumentException e) { 15388 pw.println("Failed writing: " + e); 15389 } catch (IllegalStateException e) { 15390 pw.println("Failed writing: " + e); 15391 } catch (IOException e) { 15392 pw.println("Failed writing: " + e); 15393 } 15394 } 15395 15396 if (!checkin 15397 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15398 && packageName == null) { 15399 pw.println(); 15400 int count = mSettings.mPackages.size(); 15401 if (count == 0) { 15402 pw.println("No applications!"); 15403 pw.println(); 15404 } else { 15405 final String prefix = " "; 15406 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15407 if (allPackageSettings.size() == 0) { 15408 pw.println("No domain preferred apps!"); 15409 pw.println(); 15410 } else { 15411 pw.println("App verification status:"); 15412 pw.println(); 15413 count = 0; 15414 for (PackageSetting ps : allPackageSettings) { 15415 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15416 if (ivi == null || ivi.getPackageName() == null) continue; 15417 pw.println(prefix + "Package: " + ivi.getPackageName()); 15418 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15419 pw.println(prefix + "Status: " + ivi.getStatusString()); 15420 pw.println(); 15421 count++; 15422 } 15423 if (count == 0) { 15424 pw.println(prefix + "No app verification established."); 15425 pw.println(); 15426 } 15427 for (int userId : sUserManager.getUserIds()) { 15428 pw.println("App linkages for user " + userId + ":"); 15429 pw.println(); 15430 count = 0; 15431 for (PackageSetting ps : allPackageSettings) { 15432 final long status = ps.getDomainVerificationStatusForUser(userId); 15433 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15434 continue; 15435 } 15436 pw.println(prefix + "Package: " + ps.name); 15437 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15438 String statusStr = IntentFilterVerificationInfo. 15439 getStatusStringFromValue(status); 15440 pw.println(prefix + "Status: " + statusStr); 15441 pw.println(); 15442 count++; 15443 } 15444 if (count == 0) { 15445 pw.println(prefix + "No configured app linkages."); 15446 pw.println(); 15447 } 15448 } 15449 } 15450 } 15451 } 15452 15453 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15454 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15455 if (packageName == null && permissionNames == null) { 15456 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15457 if (iperm == 0) { 15458 if (dumpState.onTitlePrinted()) 15459 pw.println(); 15460 pw.println("AppOp Permissions:"); 15461 } 15462 pw.print(" AppOp Permission "); 15463 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15464 pw.println(":"); 15465 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15466 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15467 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15468 } 15469 } 15470 } 15471 } 15472 15473 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15474 boolean printedSomething = false; 15475 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15476 if (packageName != null && !packageName.equals(p.info.packageName)) { 15477 continue; 15478 } 15479 if (!printedSomething) { 15480 if (dumpState.onTitlePrinted()) 15481 pw.println(); 15482 pw.println("Registered ContentProviders:"); 15483 printedSomething = true; 15484 } 15485 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15486 pw.print(" "); pw.println(p.toString()); 15487 } 15488 printedSomething = false; 15489 for (Map.Entry<String, PackageParser.Provider> entry : 15490 mProvidersByAuthority.entrySet()) { 15491 PackageParser.Provider p = entry.getValue(); 15492 if (packageName != null && !packageName.equals(p.info.packageName)) { 15493 continue; 15494 } 15495 if (!printedSomething) { 15496 if (dumpState.onTitlePrinted()) 15497 pw.println(); 15498 pw.println("ContentProvider Authorities:"); 15499 printedSomething = true; 15500 } 15501 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15502 pw.print(" "); pw.println(p.toString()); 15503 if (p.info != null && p.info.applicationInfo != null) { 15504 final String appInfo = p.info.applicationInfo.toString(); 15505 pw.print(" applicationInfo="); pw.println(appInfo); 15506 } 15507 } 15508 } 15509 15510 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15511 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15512 } 15513 15514 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15515 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15516 } 15517 15518 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15519 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15520 } 15521 15522 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15523 // XXX should handle packageName != null by dumping only install data that 15524 // the given package is involved with. 15525 if (dumpState.onTitlePrinted()) pw.println(); 15526 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15527 } 15528 15529 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15530 if (dumpState.onTitlePrinted()) pw.println(); 15531 mSettings.dumpReadMessagesLPr(pw, dumpState); 15532 15533 pw.println(); 15534 pw.println("Package warning messages:"); 15535 BufferedReader in = null; 15536 String line = null; 15537 try { 15538 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15539 while ((line = in.readLine()) != null) { 15540 if (line.contains("ignored: updated version")) continue; 15541 pw.println(line); 15542 } 15543 } catch (IOException ignored) { 15544 } finally { 15545 IoUtils.closeQuietly(in); 15546 } 15547 } 15548 15549 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15550 BufferedReader in = null; 15551 String line = null; 15552 try { 15553 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15554 while ((line = in.readLine()) != null) { 15555 if (line.contains("ignored: updated version")) continue; 15556 pw.print("msg,"); 15557 pw.println(line); 15558 } 15559 } catch (IOException ignored) { 15560 } finally { 15561 IoUtils.closeQuietly(in); 15562 } 15563 } 15564 } 15565 } 15566 15567 private String dumpDomainString(String packageName) { 15568 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15569 List<IntentFilter> filters = getAllIntentFilters(packageName); 15570 15571 ArraySet<String> result = new ArraySet<>(); 15572 if (iviList.size() > 0) { 15573 for (IntentFilterVerificationInfo ivi : iviList) { 15574 for (String host : ivi.getDomains()) { 15575 result.add(host); 15576 } 15577 } 15578 } 15579 if (filters != null && filters.size() > 0) { 15580 for (IntentFilter filter : filters) { 15581 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15582 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15583 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15584 result.addAll(filter.getHostsList()); 15585 } 15586 } 15587 } 15588 15589 StringBuilder sb = new StringBuilder(result.size() * 16); 15590 for (String domain : result) { 15591 if (sb.length() > 0) sb.append(" "); 15592 sb.append(domain); 15593 } 15594 return sb.toString(); 15595 } 15596 15597 // ------- apps on sdcard specific code ------- 15598 static final boolean DEBUG_SD_INSTALL = false; 15599 15600 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15601 15602 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15603 15604 private boolean mMediaMounted = false; 15605 15606 static String getEncryptKey() { 15607 try { 15608 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15609 SD_ENCRYPTION_KEYSTORE_NAME); 15610 if (sdEncKey == null) { 15611 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15612 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15613 if (sdEncKey == null) { 15614 Slog.e(TAG, "Failed to create encryption keys"); 15615 return null; 15616 } 15617 } 15618 return sdEncKey; 15619 } catch (NoSuchAlgorithmException nsae) { 15620 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15621 return null; 15622 } catch (IOException ioe) { 15623 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15624 return null; 15625 } 15626 } 15627 15628 /* 15629 * Update media status on PackageManager. 15630 */ 15631 @Override 15632 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15633 int callingUid = Binder.getCallingUid(); 15634 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15635 throw new SecurityException("Media status can only be updated by the system"); 15636 } 15637 // reader; this apparently protects mMediaMounted, but should probably 15638 // be a different lock in that case. 15639 synchronized (mPackages) { 15640 Log.i(TAG, "Updating external media status from " 15641 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15642 + (mediaStatus ? "mounted" : "unmounted")); 15643 if (DEBUG_SD_INSTALL) 15644 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15645 + ", mMediaMounted=" + mMediaMounted); 15646 if (mediaStatus == mMediaMounted) { 15647 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15648 : 0, -1); 15649 mHandler.sendMessage(msg); 15650 return; 15651 } 15652 mMediaMounted = mediaStatus; 15653 } 15654 // Queue up an async operation since the package installation may take a 15655 // little while. 15656 mHandler.post(new Runnable() { 15657 public void run() { 15658 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15659 } 15660 }); 15661 } 15662 15663 /** 15664 * Called by MountService when the initial ASECs to scan are available. 15665 * Should block until all the ASEC containers are finished being scanned. 15666 */ 15667 public void scanAvailableAsecs() { 15668 updateExternalMediaStatusInner(true, false, false); 15669 if (mShouldRestoreconData) { 15670 SELinuxMMAC.setRestoreconDone(); 15671 mShouldRestoreconData = false; 15672 } 15673 } 15674 15675 /* 15676 * Collect information of applications on external media, map them against 15677 * existing containers and update information based on current mount status. 15678 * Please note that we always have to report status if reportStatus has been 15679 * set to true especially when unloading packages. 15680 */ 15681 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15682 boolean externalStorage) { 15683 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15684 int[] uidArr = EmptyArray.INT; 15685 15686 final String[] list = PackageHelper.getSecureContainerList(); 15687 if (ArrayUtils.isEmpty(list)) { 15688 Log.i(TAG, "No secure containers found"); 15689 } else { 15690 // Process list of secure containers and categorize them 15691 // as active or stale based on their package internal state. 15692 15693 // reader 15694 synchronized (mPackages) { 15695 for (String cid : list) { 15696 // Leave stages untouched for now; installer service owns them 15697 if (PackageInstallerService.isStageName(cid)) continue; 15698 15699 if (DEBUG_SD_INSTALL) 15700 Log.i(TAG, "Processing container " + cid); 15701 String pkgName = getAsecPackageName(cid); 15702 if (pkgName == null) { 15703 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15704 continue; 15705 } 15706 if (DEBUG_SD_INSTALL) 15707 Log.i(TAG, "Looking for pkg : " + pkgName); 15708 15709 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15710 if (ps == null) { 15711 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15712 continue; 15713 } 15714 15715 /* 15716 * Skip packages that are not external if we're unmounting 15717 * external storage. 15718 */ 15719 if (externalStorage && !isMounted && !isExternal(ps)) { 15720 continue; 15721 } 15722 15723 final AsecInstallArgs args = new AsecInstallArgs(cid, 15724 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15725 // The package status is changed only if the code path 15726 // matches between settings and the container id. 15727 if (ps.codePathString != null 15728 && ps.codePathString.startsWith(args.getCodePath())) { 15729 if (DEBUG_SD_INSTALL) { 15730 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15731 + " at code path: " + ps.codePathString); 15732 } 15733 15734 // We do have a valid package installed on sdcard 15735 processCids.put(args, ps.codePathString); 15736 final int uid = ps.appId; 15737 if (uid != -1) { 15738 uidArr = ArrayUtils.appendInt(uidArr, uid); 15739 } 15740 } else { 15741 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15742 + ps.codePathString); 15743 } 15744 } 15745 } 15746 15747 Arrays.sort(uidArr); 15748 } 15749 15750 // Process packages with valid entries. 15751 if (isMounted) { 15752 if (DEBUG_SD_INSTALL) 15753 Log.i(TAG, "Loading packages"); 15754 loadMediaPackages(processCids, uidArr, externalStorage); 15755 startCleaningPackages(); 15756 mInstallerService.onSecureContainersAvailable(); 15757 } else { 15758 if (DEBUG_SD_INSTALL) 15759 Log.i(TAG, "Unloading packages"); 15760 unloadMediaPackages(processCids, uidArr, reportStatus); 15761 } 15762 } 15763 15764 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15765 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15766 final int size = infos.size(); 15767 final String[] packageNames = new String[size]; 15768 final int[] packageUids = new int[size]; 15769 for (int i = 0; i < size; i++) { 15770 final ApplicationInfo info = infos.get(i); 15771 packageNames[i] = info.packageName; 15772 packageUids[i] = info.uid; 15773 } 15774 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15775 finishedReceiver); 15776 } 15777 15778 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15779 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15780 sendResourcesChangedBroadcast(mediaStatus, replacing, 15781 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15782 } 15783 15784 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15785 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15786 int size = pkgList.length; 15787 if (size > 0) { 15788 // Send broadcasts here 15789 Bundle extras = new Bundle(); 15790 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15791 if (uidArr != null) { 15792 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15793 } 15794 if (replacing) { 15795 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15796 } 15797 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15798 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15799 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15800 } 15801 } 15802 15803 /* 15804 * Look at potentially valid container ids from processCids If package 15805 * information doesn't match the one on record or package scanning fails, 15806 * the cid is added to list of removeCids. We currently don't delete stale 15807 * containers. 15808 */ 15809 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15810 boolean externalStorage) { 15811 ArrayList<String> pkgList = new ArrayList<String>(); 15812 Set<AsecInstallArgs> keys = processCids.keySet(); 15813 15814 for (AsecInstallArgs args : keys) { 15815 String codePath = processCids.get(args); 15816 if (DEBUG_SD_INSTALL) 15817 Log.i(TAG, "Loading container : " + args.cid); 15818 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15819 try { 15820 // Make sure there are no container errors first. 15821 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15822 Slog.e(TAG, "Failed to mount cid : " + args.cid 15823 + " when installing from sdcard"); 15824 continue; 15825 } 15826 // Check code path here. 15827 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15828 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15829 + " does not match one in settings " + codePath); 15830 continue; 15831 } 15832 // Parse package 15833 int parseFlags = mDefParseFlags; 15834 if (args.isExternalAsec()) { 15835 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15836 } 15837 if (args.isFwdLocked()) { 15838 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15839 } 15840 15841 synchronized (mInstallLock) { 15842 PackageParser.Package pkg = null; 15843 try { 15844 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, 15845 UserHandle.SYSTEM); 15846 } catch (PackageManagerException e) { 15847 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15848 } 15849 // Scan the package 15850 if (pkg != null) { 15851 /* 15852 * TODO why is the lock being held? doPostInstall is 15853 * called in other places without the lock. This needs 15854 * to be straightened out. 15855 */ 15856 // writer 15857 synchronized (mPackages) { 15858 retCode = PackageManager.INSTALL_SUCCEEDED; 15859 pkgList.add(pkg.packageName); 15860 // Post process args 15861 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15862 pkg.applicationInfo.uid); 15863 } 15864 } else { 15865 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15866 } 15867 } 15868 15869 } finally { 15870 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15871 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15872 } 15873 } 15874 } 15875 // writer 15876 synchronized (mPackages) { 15877 // If the platform SDK has changed since the last time we booted, 15878 // we need to re-grant app permission to catch any new ones that 15879 // appear. This is really a hack, and means that apps can in some 15880 // cases get permissions that the user didn't initially explicitly 15881 // allow... it would be nice to have some better way to handle 15882 // this situation. 15883 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15884 : mSettings.getInternalVersion(); 15885 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15886 : StorageManager.UUID_PRIVATE_INTERNAL; 15887 15888 int updateFlags = UPDATE_PERMISSIONS_ALL; 15889 if (ver.sdkVersion != mSdkVersion) { 15890 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15891 + mSdkVersion + "; regranting permissions for external"); 15892 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15893 } 15894 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15895 15896 // Yay, everything is now upgraded 15897 ver.forceCurrent(); 15898 15899 // can downgrade to reader 15900 // Persist settings 15901 mSettings.writeLPr(); 15902 } 15903 // Send a broadcast to let everyone know we are done processing 15904 if (pkgList.size() > 0) { 15905 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15906 } 15907 } 15908 15909 /* 15910 * Utility method to unload a list of specified containers 15911 */ 15912 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15913 // Just unmount all valid containers. 15914 for (AsecInstallArgs arg : cidArgs) { 15915 synchronized (mInstallLock) { 15916 arg.doPostDeleteLI(false); 15917 } 15918 } 15919 } 15920 15921 /* 15922 * Unload packages mounted on external media. This involves deleting package 15923 * data from internal structures, sending broadcasts about diabled packages, 15924 * gc'ing to free up references, unmounting all secure containers 15925 * corresponding to packages on external media, and posting a 15926 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15927 * that we always have to post this message if status has been requested no 15928 * matter what. 15929 */ 15930 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15931 final boolean reportStatus) { 15932 if (DEBUG_SD_INSTALL) 15933 Log.i(TAG, "unloading media packages"); 15934 ArrayList<String> pkgList = new ArrayList<String>(); 15935 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15936 final Set<AsecInstallArgs> keys = processCids.keySet(); 15937 for (AsecInstallArgs args : keys) { 15938 String pkgName = args.getPackageName(); 15939 if (DEBUG_SD_INSTALL) 15940 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15941 // Delete package internally 15942 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15943 synchronized (mInstallLock) { 15944 boolean res = deletePackageLI(pkgName, null, false, null, null, 15945 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15946 if (res) { 15947 pkgList.add(pkgName); 15948 } else { 15949 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15950 failedList.add(args); 15951 } 15952 } 15953 } 15954 15955 // reader 15956 synchronized (mPackages) { 15957 // We didn't update the settings after removing each package; 15958 // write them now for all packages. 15959 mSettings.writeLPr(); 15960 } 15961 15962 // We have to absolutely send UPDATED_MEDIA_STATUS only 15963 // after confirming that all the receivers processed the ordered 15964 // broadcast when packages get disabled, force a gc to clean things up. 15965 // and unload all the containers. 15966 if (pkgList.size() > 0) { 15967 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15968 new IIntentReceiver.Stub() { 15969 public void performReceive(Intent intent, int resultCode, String data, 15970 Bundle extras, boolean ordered, boolean sticky, 15971 int sendingUser) throws RemoteException { 15972 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15973 reportStatus ? 1 : 0, 1, keys); 15974 mHandler.sendMessage(msg); 15975 } 15976 }); 15977 } else { 15978 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15979 keys); 15980 mHandler.sendMessage(msg); 15981 } 15982 } 15983 15984 private void loadPrivatePackages(final VolumeInfo vol) { 15985 mHandler.post(new Runnable() { 15986 @Override 15987 public void run() { 15988 loadPrivatePackagesInner(vol); 15989 } 15990 }); 15991 } 15992 15993 private void loadPrivatePackagesInner(VolumeInfo vol) { 15994 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15995 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15996 15997 final VersionInfo ver; 15998 final List<PackageSetting> packages; 15999 synchronized (mPackages) { 16000 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16001 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16002 } 16003 16004 for (PackageSetting ps : packages) { 16005 synchronized (mInstallLock) { 16006 final PackageParser.Package pkg; 16007 try { 16008 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, 16009 UserHandle.SYSTEM); 16010 loaded.add(pkg.applicationInfo); 16011 } catch (PackageManagerException e) { 16012 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16013 } 16014 16015 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16016 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16017 } 16018 } 16019 } 16020 16021 synchronized (mPackages) { 16022 int updateFlags = UPDATE_PERMISSIONS_ALL; 16023 if (ver.sdkVersion != mSdkVersion) { 16024 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16025 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16026 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16027 } 16028 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16029 16030 // Yay, everything is now upgraded 16031 ver.forceCurrent(); 16032 16033 mSettings.writeLPr(); 16034 } 16035 16036 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16037 sendResourcesChangedBroadcast(true, false, loaded, null); 16038 } 16039 16040 private void unloadPrivatePackages(final VolumeInfo vol) { 16041 mHandler.post(new Runnable() { 16042 @Override 16043 public void run() { 16044 unloadPrivatePackagesInner(vol); 16045 } 16046 }); 16047 } 16048 16049 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16050 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16051 synchronized (mInstallLock) { 16052 synchronized (mPackages) { 16053 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16054 for (PackageSetting ps : packages) { 16055 if (ps.pkg == null) continue; 16056 16057 final ApplicationInfo info = ps.pkg.applicationInfo; 16058 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16059 if (deletePackageLI(ps.name, null, false, null, null, 16060 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16061 unloaded.add(info); 16062 } else { 16063 Slog.w(TAG, "Failed to unload " + ps.codePath); 16064 } 16065 } 16066 16067 mSettings.writeLPr(); 16068 } 16069 } 16070 16071 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16072 sendResourcesChangedBroadcast(false, false, unloaded, null); 16073 } 16074 16075 /** 16076 * Examine all users present on given mounted volume, and destroy data 16077 * belonging to users that are no longer valid, or whose user ID has been 16078 * recycled. 16079 */ 16080 private void reconcileUsers(String volumeUuid) { 16081 final File[] files = FileUtils 16082 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16083 for (File file : files) { 16084 if (!file.isDirectory()) continue; 16085 16086 final int userId; 16087 final UserInfo info; 16088 try { 16089 userId = Integer.parseInt(file.getName()); 16090 info = sUserManager.getUserInfo(userId); 16091 } catch (NumberFormatException e) { 16092 Slog.w(TAG, "Invalid user directory " + file); 16093 continue; 16094 } 16095 16096 boolean destroyUser = false; 16097 if (info == null) { 16098 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16099 + " because no matching user was found"); 16100 destroyUser = true; 16101 } else { 16102 try { 16103 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16104 } catch (IOException e) { 16105 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16106 + " because we failed to enforce serial number: " + e); 16107 destroyUser = true; 16108 } 16109 } 16110 16111 if (destroyUser) { 16112 synchronized (mInstallLock) { 16113 mInstaller.removeUserDataDirs(volumeUuid, userId); 16114 } 16115 } 16116 } 16117 16118 final UserManager um = mContext.getSystemService(UserManager.class); 16119 for (UserInfo user : um.getUsers()) { 16120 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16121 if (userDir.exists()) continue; 16122 16123 try { 16124 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 16125 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16126 } catch (IOException e) { 16127 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16128 } 16129 } 16130 } 16131 16132 /** 16133 * Examine all apps present on given mounted volume, and destroy apps that 16134 * aren't expected, either due to uninstallation or reinstallation on 16135 * another volume. 16136 */ 16137 private void reconcileApps(String volumeUuid) { 16138 final File[] files = FileUtils 16139 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16140 for (File file : files) { 16141 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16142 && !PackageInstallerService.isStageName(file.getName()); 16143 if (!isPackage) { 16144 // Ignore entries which are not packages 16145 continue; 16146 } 16147 16148 boolean destroyApp = false; 16149 String packageName = null; 16150 try { 16151 final PackageLite pkg = PackageParser.parsePackageLite(file, 16152 PackageParser.PARSE_MUST_BE_APK); 16153 packageName = pkg.packageName; 16154 16155 synchronized (mPackages) { 16156 final PackageSetting ps = mSettings.mPackages.get(packageName); 16157 if (ps == null) { 16158 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16159 + volumeUuid + " because we found no install record"); 16160 destroyApp = true; 16161 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16162 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16163 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16164 destroyApp = true; 16165 } 16166 } 16167 16168 } catch (PackageParserException e) { 16169 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16170 destroyApp = true; 16171 } 16172 16173 if (destroyApp) { 16174 synchronized (mInstallLock) { 16175 if (packageName != null) { 16176 removeDataDirsLI(volumeUuid, packageName); 16177 } 16178 if (file.isDirectory()) { 16179 mInstaller.rmPackageDir(file.getAbsolutePath()); 16180 } else { 16181 file.delete(); 16182 } 16183 } 16184 } 16185 } 16186 } 16187 16188 private void unfreezePackage(String packageName) { 16189 synchronized (mPackages) { 16190 final PackageSetting ps = mSettings.mPackages.get(packageName); 16191 if (ps != null) { 16192 ps.frozen = false; 16193 } 16194 } 16195 } 16196 16197 @Override 16198 public int movePackage(final String packageName, final String volumeUuid) { 16199 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16200 16201 final int moveId = mNextMoveId.getAndIncrement(); 16202 try { 16203 movePackageInternal(packageName, volumeUuid, moveId); 16204 } catch (PackageManagerException e) { 16205 Slog.w(TAG, "Failed to move " + packageName, e); 16206 mMoveCallbacks.notifyStatusChanged(moveId, 16207 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16208 } 16209 return moveId; 16210 } 16211 16212 private void movePackageInternal(final String packageName, final String volumeUuid, 16213 final int moveId) throws PackageManagerException { 16214 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16215 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16216 final PackageManager pm = mContext.getPackageManager(); 16217 16218 final boolean currentAsec; 16219 final String currentVolumeUuid; 16220 final File codeFile; 16221 final String installerPackageName; 16222 final String packageAbiOverride; 16223 final int appId; 16224 final String seinfo; 16225 final String label; 16226 16227 // reader 16228 synchronized (mPackages) { 16229 final PackageParser.Package pkg = mPackages.get(packageName); 16230 final PackageSetting ps = mSettings.mPackages.get(packageName); 16231 if (pkg == null || ps == null) { 16232 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16233 } 16234 16235 if (pkg.applicationInfo.isSystemApp()) { 16236 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16237 "Cannot move system application"); 16238 } 16239 16240 if (pkg.applicationInfo.isExternalAsec()) { 16241 currentAsec = true; 16242 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16243 } else if (pkg.applicationInfo.isForwardLocked()) { 16244 currentAsec = true; 16245 currentVolumeUuid = "forward_locked"; 16246 } else { 16247 currentAsec = false; 16248 currentVolumeUuid = ps.volumeUuid; 16249 16250 final File probe = new File(pkg.codePath); 16251 final File probeOat = new File(probe, "oat"); 16252 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16253 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16254 "Move only supported for modern cluster style installs"); 16255 } 16256 } 16257 16258 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16259 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16260 "Package already moved to " + volumeUuid); 16261 } 16262 16263 if (ps.frozen) { 16264 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16265 "Failed to move already frozen package"); 16266 } 16267 ps.frozen = true; 16268 16269 codeFile = new File(pkg.codePath); 16270 installerPackageName = ps.installerPackageName; 16271 packageAbiOverride = ps.cpuAbiOverrideString; 16272 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16273 seinfo = pkg.applicationInfo.seinfo; 16274 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16275 } 16276 16277 // Now that we're guarded by frozen state, kill app during move 16278 final long token = Binder.clearCallingIdentity(); 16279 try { 16280 killApplication(packageName, appId, "move pkg"); 16281 } finally { 16282 Binder.restoreCallingIdentity(token); 16283 } 16284 16285 final Bundle extras = new Bundle(); 16286 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16287 extras.putString(Intent.EXTRA_TITLE, label); 16288 mMoveCallbacks.notifyCreated(moveId, extras); 16289 16290 int installFlags; 16291 final boolean moveCompleteApp; 16292 final File measurePath; 16293 16294 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16295 installFlags = INSTALL_INTERNAL; 16296 moveCompleteApp = !currentAsec; 16297 measurePath = Environment.getDataAppDirectory(volumeUuid); 16298 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16299 installFlags = INSTALL_EXTERNAL; 16300 moveCompleteApp = false; 16301 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16302 } else { 16303 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16304 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16305 || !volume.isMountedWritable()) { 16306 unfreezePackage(packageName); 16307 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16308 "Move location not mounted private volume"); 16309 } 16310 16311 Preconditions.checkState(!currentAsec); 16312 16313 installFlags = INSTALL_INTERNAL; 16314 moveCompleteApp = true; 16315 measurePath = Environment.getDataAppDirectory(volumeUuid); 16316 } 16317 16318 final PackageStats stats = new PackageStats(null, -1); 16319 synchronized (mInstaller) { 16320 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16321 unfreezePackage(packageName); 16322 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16323 "Failed to measure package size"); 16324 } 16325 } 16326 16327 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16328 + stats.dataSize); 16329 16330 final long startFreeBytes = measurePath.getFreeSpace(); 16331 final long sizeBytes; 16332 if (moveCompleteApp) { 16333 sizeBytes = stats.codeSize + stats.dataSize; 16334 } else { 16335 sizeBytes = stats.codeSize; 16336 } 16337 16338 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16339 unfreezePackage(packageName); 16340 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16341 "Not enough free space to move"); 16342 } 16343 16344 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16345 16346 final CountDownLatch installedLatch = new CountDownLatch(1); 16347 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16348 @Override 16349 public void onUserActionRequired(Intent intent) throws RemoteException { 16350 throw new IllegalStateException(); 16351 } 16352 16353 @Override 16354 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16355 Bundle extras) throws RemoteException { 16356 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16357 + PackageManager.installStatusToString(returnCode, msg)); 16358 16359 installedLatch.countDown(); 16360 16361 // Regardless of success or failure of the move operation, 16362 // always unfreeze the package 16363 unfreezePackage(packageName); 16364 16365 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16366 switch (status) { 16367 case PackageInstaller.STATUS_SUCCESS: 16368 mMoveCallbacks.notifyStatusChanged(moveId, 16369 PackageManager.MOVE_SUCCEEDED); 16370 break; 16371 case PackageInstaller.STATUS_FAILURE_STORAGE: 16372 mMoveCallbacks.notifyStatusChanged(moveId, 16373 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16374 break; 16375 default: 16376 mMoveCallbacks.notifyStatusChanged(moveId, 16377 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16378 break; 16379 } 16380 } 16381 }; 16382 16383 final MoveInfo move; 16384 if (moveCompleteApp) { 16385 // Kick off a thread to report progress estimates 16386 new Thread() { 16387 @Override 16388 public void run() { 16389 while (true) { 16390 try { 16391 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16392 break; 16393 } 16394 } catch (InterruptedException ignored) { 16395 } 16396 16397 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16398 final int progress = 10 + (int) MathUtils.constrain( 16399 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16400 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16401 } 16402 } 16403 }.start(); 16404 16405 final String dataAppName = codeFile.getName(); 16406 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16407 dataAppName, appId, seinfo); 16408 } else { 16409 move = null; 16410 } 16411 16412 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16413 16414 final Message msg = mHandler.obtainMessage(INIT_COPY); 16415 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16416 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16417 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16418 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16419 msg.obj = params; 16420 16421 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16422 System.identityHashCode(msg.obj)); 16423 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16424 System.identityHashCode(msg.obj)); 16425 16426 mHandler.sendMessage(msg); 16427 } 16428 16429 @Override 16430 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16431 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16432 16433 final int realMoveId = mNextMoveId.getAndIncrement(); 16434 final Bundle extras = new Bundle(); 16435 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16436 mMoveCallbacks.notifyCreated(realMoveId, extras); 16437 16438 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16439 @Override 16440 public void onCreated(int moveId, Bundle extras) { 16441 // Ignored 16442 } 16443 16444 @Override 16445 public void onStatusChanged(int moveId, int status, long estMillis) { 16446 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16447 } 16448 }; 16449 16450 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16451 storage.setPrimaryStorageUuid(volumeUuid, callback); 16452 return realMoveId; 16453 } 16454 16455 @Override 16456 public int getMoveStatus(int moveId) { 16457 mContext.enforceCallingOrSelfPermission( 16458 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16459 return mMoveCallbacks.mLastStatus.get(moveId); 16460 } 16461 16462 @Override 16463 public void registerMoveCallback(IPackageMoveObserver callback) { 16464 mContext.enforceCallingOrSelfPermission( 16465 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16466 mMoveCallbacks.register(callback); 16467 } 16468 16469 @Override 16470 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16471 mContext.enforceCallingOrSelfPermission( 16472 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16473 mMoveCallbacks.unregister(callback); 16474 } 16475 16476 @Override 16477 public boolean setInstallLocation(int loc) { 16478 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16479 null); 16480 if (getInstallLocation() == loc) { 16481 return true; 16482 } 16483 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16484 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16485 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16486 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16487 return true; 16488 } 16489 return false; 16490 } 16491 16492 @Override 16493 public int getInstallLocation() { 16494 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16495 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16496 PackageHelper.APP_INSTALL_AUTO); 16497 } 16498 16499 /** Called by UserManagerService */ 16500 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16501 mDirtyUsers.remove(userHandle); 16502 mSettings.removeUserLPw(userHandle); 16503 mPendingBroadcasts.remove(userHandle); 16504 if (mInstaller != null) { 16505 // Technically, we shouldn't be doing this with the package lock 16506 // held. However, this is very rare, and there is already so much 16507 // other disk I/O going on, that we'll let it slide for now. 16508 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16509 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16510 final String volumeUuid = vol.getFsUuid(); 16511 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16512 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16513 } 16514 } 16515 mUserNeedsBadging.delete(userHandle); 16516 removeUnusedPackagesLILPw(userManager, userHandle); 16517 } 16518 16519 /** 16520 * We're removing userHandle and would like to remove any downloaded packages 16521 * that are no longer in use by any other user. 16522 * @param userHandle the user being removed 16523 */ 16524 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16525 final boolean DEBUG_CLEAN_APKS = false; 16526 int [] users = userManager.getUserIdsLPr(); 16527 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16528 while (psit.hasNext()) { 16529 PackageSetting ps = psit.next(); 16530 if (ps.pkg == null) { 16531 continue; 16532 } 16533 final String packageName = ps.pkg.packageName; 16534 // Skip over if system app 16535 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16536 continue; 16537 } 16538 if (DEBUG_CLEAN_APKS) { 16539 Slog.i(TAG, "Checking package " + packageName); 16540 } 16541 boolean keep = false; 16542 for (int i = 0; i < users.length; i++) { 16543 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16544 keep = true; 16545 if (DEBUG_CLEAN_APKS) { 16546 Slog.i(TAG, " Keeping package " + packageName + " for user " 16547 + users[i]); 16548 } 16549 break; 16550 } 16551 } 16552 if (!keep) { 16553 if (DEBUG_CLEAN_APKS) { 16554 Slog.i(TAG, " Removing package " + packageName); 16555 } 16556 mHandler.post(new Runnable() { 16557 public void run() { 16558 deletePackageX(packageName, userHandle, 0); 16559 } //end run 16560 }); 16561 } 16562 } 16563 } 16564 16565 /** Called by UserManagerService */ 16566 void createNewUserLILPw(int userHandle) { 16567 if (mInstaller != null) { 16568 mInstaller.createUserConfig(userHandle); 16569 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16570 applyFactoryDefaultBrowserLPw(userHandle); 16571 primeDomainVerificationsLPw(userHandle); 16572 } 16573 } 16574 16575 void newUserCreated(final int userHandle) { 16576 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16577 } 16578 16579 @Override 16580 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16581 mContext.enforceCallingOrSelfPermission( 16582 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16583 "Only package verification agents can read the verifier device identity"); 16584 16585 synchronized (mPackages) { 16586 return mSettings.getVerifierDeviceIdentityLPw(); 16587 } 16588 } 16589 16590 @Override 16591 public void setPermissionEnforced(String permission, boolean enforced) { 16592 // TODO: Now that we no longer change GID for storage, this should to away. 16593 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16594 "setPermissionEnforced"); 16595 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16596 synchronized (mPackages) { 16597 if (mSettings.mReadExternalStorageEnforced == null 16598 || mSettings.mReadExternalStorageEnforced != enforced) { 16599 mSettings.mReadExternalStorageEnforced = enforced; 16600 mSettings.writeLPr(); 16601 } 16602 } 16603 // kill any non-foreground processes so we restart them and 16604 // grant/revoke the GID. 16605 final IActivityManager am = ActivityManagerNative.getDefault(); 16606 if (am != null) { 16607 final long token = Binder.clearCallingIdentity(); 16608 try { 16609 am.killProcessesBelowForeground("setPermissionEnforcement"); 16610 } catch (RemoteException e) { 16611 } finally { 16612 Binder.restoreCallingIdentity(token); 16613 } 16614 } 16615 } else { 16616 throw new IllegalArgumentException("No selective enforcement for " + permission); 16617 } 16618 } 16619 16620 @Override 16621 @Deprecated 16622 public boolean isPermissionEnforced(String permission) { 16623 return true; 16624 } 16625 16626 @Override 16627 public boolean isStorageLow() { 16628 final long token = Binder.clearCallingIdentity(); 16629 try { 16630 final DeviceStorageMonitorInternal 16631 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16632 if (dsm != null) { 16633 return dsm.isMemoryLow(); 16634 } else { 16635 return false; 16636 } 16637 } finally { 16638 Binder.restoreCallingIdentity(token); 16639 } 16640 } 16641 16642 @Override 16643 public IPackageInstaller getPackageInstaller() { 16644 return mInstallerService; 16645 } 16646 16647 private boolean userNeedsBadging(int userId) { 16648 int index = mUserNeedsBadging.indexOfKey(userId); 16649 if (index < 0) { 16650 final UserInfo userInfo; 16651 final long token = Binder.clearCallingIdentity(); 16652 try { 16653 userInfo = sUserManager.getUserInfo(userId); 16654 } finally { 16655 Binder.restoreCallingIdentity(token); 16656 } 16657 final boolean b; 16658 if (userInfo != null && userInfo.isManagedProfile()) { 16659 b = true; 16660 } else { 16661 b = false; 16662 } 16663 mUserNeedsBadging.put(userId, b); 16664 return b; 16665 } 16666 return mUserNeedsBadging.valueAt(index); 16667 } 16668 16669 @Override 16670 public KeySet getKeySetByAlias(String packageName, String alias) { 16671 if (packageName == null || alias == null) { 16672 return null; 16673 } 16674 synchronized(mPackages) { 16675 final PackageParser.Package pkg = mPackages.get(packageName); 16676 if (pkg == null) { 16677 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16678 throw new IllegalArgumentException("Unknown package: " + packageName); 16679 } 16680 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16681 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16682 } 16683 } 16684 16685 @Override 16686 public KeySet getSigningKeySet(String packageName) { 16687 if (packageName == null) { 16688 return null; 16689 } 16690 synchronized(mPackages) { 16691 final PackageParser.Package pkg = mPackages.get(packageName); 16692 if (pkg == null) { 16693 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16694 throw new IllegalArgumentException("Unknown package: " + packageName); 16695 } 16696 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16697 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16698 throw new SecurityException("May not access signing KeySet of other apps."); 16699 } 16700 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16701 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16702 } 16703 } 16704 16705 @Override 16706 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16707 if (packageName == null || ks == null) { 16708 return false; 16709 } 16710 synchronized(mPackages) { 16711 final PackageParser.Package pkg = mPackages.get(packageName); 16712 if (pkg == null) { 16713 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16714 throw new IllegalArgumentException("Unknown package: " + packageName); 16715 } 16716 IBinder ksh = ks.getToken(); 16717 if (ksh instanceof KeySetHandle) { 16718 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16719 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16720 } 16721 return false; 16722 } 16723 } 16724 16725 @Override 16726 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16727 if (packageName == null || ks == null) { 16728 return false; 16729 } 16730 synchronized(mPackages) { 16731 final PackageParser.Package pkg = mPackages.get(packageName); 16732 if (pkg == null) { 16733 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16734 throw new IllegalArgumentException("Unknown package: " + packageName); 16735 } 16736 IBinder ksh = ks.getToken(); 16737 if (ksh instanceof KeySetHandle) { 16738 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16739 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16740 } 16741 return false; 16742 } 16743 } 16744 16745 public void getUsageStatsIfNoPackageUsageInfo() { 16746 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16747 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16748 if (usm == null) { 16749 throw new IllegalStateException("UsageStatsManager must be initialized"); 16750 } 16751 long now = System.currentTimeMillis(); 16752 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16753 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16754 String packageName = entry.getKey(); 16755 PackageParser.Package pkg = mPackages.get(packageName); 16756 if (pkg == null) { 16757 continue; 16758 } 16759 UsageStats usage = entry.getValue(); 16760 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16761 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16762 } 16763 } 16764 } 16765 16766 /** 16767 * Check and throw if the given before/after packages would be considered a 16768 * downgrade. 16769 */ 16770 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16771 throws PackageManagerException { 16772 if (after.versionCode < before.mVersionCode) { 16773 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16774 "Update version code " + after.versionCode + " is older than current " 16775 + before.mVersionCode); 16776 } else if (after.versionCode == before.mVersionCode) { 16777 if (after.baseRevisionCode < before.baseRevisionCode) { 16778 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16779 "Update base revision code " + after.baseRevisionCode 16780 + " is older than current " + before.baseRevisionCode); 16781 } 16782 16783 if (!ArrayUtils.isEmpty(after.splitNames)) { 16784 for (int i = 0; i < after.splitNames.length; i++) { 16785 final String splitName = after.splitNames[i]; 16786 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16787 if (j != -1) { 16788 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16789 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16790 "Update split " + splitName + " revision code " 16791 + after.splitRevisionCodes[i] + " is older than current " 16792 + before.splitRevisionCodes[j]); 16793 } 16794 } 16795 } 16796 } 16797 } 16798 } 16799 16800 private static class MoveCallbacks extends Handler { 16801 private static final int MSG_CREATED = 1; 16802 private static final int MSG_STATUS_CHANGED = 2; 16803 16804 private final RemoteCallbackList<IPackageMoveObserver> 16805 mCallbacks = new RemoteCallbackList<>(); 16806 16807 private final SparseIntArray mLastStatus = new SparseIntArray(); 16808 16809 public MoveCallbacks(Looper looper) { 16810 super(looper); 16811 } 16812 16813 public void register(IPackageMoveObserver callback) { 16814 mCallbacks.register(callback); 16815 } 16816 16817 public void unregister(IPackageMoveObserver callback) { 16818 mCallbacks.unregister(callback); 16819 } 16820 16821 @Override 16822 public void handleMessage(Message msg) { 16823 final SomeArgs args = (SomeArgs) msg.obj; 16824 final int n = mCallbacks.beginBroadcast(); 16825 for (int i = 0; i < n; i++) { 16826 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16827 try { 16828 invokeCallback(callback, msg.what, args); 16829 } catch (RemoteException ignored) { 16830 } 16831 } 16832 mCallbacks.finishBroadcast(); 16833 args.recycle(); 16834 } 16835 16836 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16837 throws RemoteException { 16838 switch (what) { 16839 case MSG_CREATED: { 16840 callback.onCreated(args.argi1, (Bundle) args.arg2); 16841 break; 16842 } 16843 case MSG_STATUS_CHANGED: { 16844 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16845 break; 16846 } 16847 } 16848 } 16849 16850 private void notifyCreated(int moveId, Bundle extras) { 16851 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16852 16853 final SomeArgs args = SomeArgs.obtain(); 16854 args.argi1 = moveId; 16855 args.arg2 = extras; 16856 obtainMessage(MSG_CREATED, args).sendToTarget(); 16857 } 16858 16859 private void notifyStatusChanged(int moveId, int status) { 16860 notifyStatusChanged(moveId, status, -1); 16861 } 16862 16863 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16864 Slog.v(TAG, "Move " + moveId + " status " + status); 16865 16866 final SomeArgs args = SomeArgs.obtain(); 16867 args.argi1 = moveId; 16868 args.argi2 = status; 16869 args.arg3 = estMillis; 16870 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16871 16872 synchronized (mLastStatus) { 16873 mLastStatus.put(moveId, status); 16874 } 16875 } 16876 } 16877 16878 private final class OnPermissionChangeListeners extends Handler { 16879 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16880 16881 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16882 new RemoteCallbackList<>(); 16883 16884 public OnPermissionChangeListeners(Looper looper) { 16885 super(looper); 16886 } 16887 16888 @Override 16889 public void handleMessage(Message msg) { 16890 switch (msg.what) { 16891 case MSG_ON_PERMISSIONS_CHANGED: { 16892 final int uid = msg.arg1; 16893 handleOnPermissionsChanged(uid); 16894 } break; 16895 } 16896 } 16897 16898 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16899 mPermissionListeners.register(listener); 16900 16901 } 16902 16903 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16904 mPermissionListeners.unregister(listener); 16905 } 16906 16907 public void onPermissionsChanged(int uid) { 16908 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16909 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16910 } 16911 } 16912 16913 private void handleOnPermissionsChanged(int uid) { 16914 final int count = mPermissionListeners.beginBroadcast(); 16915 try { 16916 for (int i = 0; i < count; i++) { 16917 IOnPermissionsChangeListener callback = mPermissionListeners 16918 .getBroadcastItem(i); 16919 try { 16920 callback.onPermissionsChanged(uid); 16921 } catch (RemoteException e) { 16922 Log.e(TAG, "Permission listener is dead", e); 16923 } 16924 } 16925 } finally { 16926 mPermissionListeners.finishBroadcast(); 16927 } 16928 } 16929 } 16930 16931 private class PackageManagerInternalImpl extends PackageManagerInternal { 16932 @Override 16933 public void setLocationPackagesProvider(PackagesProvider provider) { 16934 synchronized (mPackages) { 16935 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16936 } 16937 } 16938 16939 @Override 16940 public void setImePackagesProvider(PackagesProvider provider) { 16941 synchronized (mPackages) { 16942 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16943 } 16944 } 16945 16946 @Override 16947 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16948 synchronized (mPackages) { 16949 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16950 } 16951 } 16952 16953 @Override 16954 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16955 synchronized (mPackages) { 16956 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16957 } 16958 } 16959 16960 @Override 16961 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16962 synchronized (mPackages) { 16963 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16964 } 16965 } 16966 16967 @Override 16968 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16969 synchronized (mPackages) { 16970 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16971 } 16972 } 16973 16974 @Override 16975 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16976 synchronized (mPackages) { 16977 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16978 } 16979 } 16980 16981 @Override 16982 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16983 synchronized (mPackages) { 16984 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16985 packageName, userId); 16986 } 16987 } 16988 16989 @Override 16990 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16991 synchronized (mPackages) { 16992 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16993 packageName, userId); 16994 } 16995 } 16996 @Override 16997 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16998 synchronized (mPackages) { 16999 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17000 packageName, userId); 17001 } 17002 } 17003 } 17004 17005 @Override 17006 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17007 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17008 synchronized (mPackages) { 17009 final long identity = Binder.clearCallingIdentity(); 17010 try { 17011 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17012 packageNames, userId); 17013 } finally { 17014 Binder.restoreCallingIdentity(identity); 17015 } 17016 } 17017 } 17018 17019 private static void enforceSystemOrPhoneCaller(String tag) { 17020 int callingUid = Binder.getCallingUid(); 17021 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17022 throw new SecurityException( 17023 "Cannot call " + tag + " from UID " + callingUid); 17024 } 17025 } 17026} 17027